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 |
|---|---|---|---|---|---|
# GNU Enterprise Common Library - Schema support for PostgreSQL
#
# Copyright 2000-2007 Free Software Foundation
#
# This file is part of GNU Enterprise.
#
# GNU Enterprise is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2, or (at your option) any later version.
#
# GNU Enterprise 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 program; see the file COPYING. If not,
# write to the Free Software Foundation, Inc., 59 Temple Place
# - Suite 330, Boston, MA 02111-1307, USA.
#
# $Id: Behavior.py 9222 2007-01-08 13:02:49Z johannes $
"""
Schema support plugin for PostgreSQL backends.
"""
__all__ = ['Behavior']
import os
from gnue.common.apps import errors
from gnue.common.datasources import GSchema
from gnue.common.datasources.drivers import DBSIG2
# =============================================================================
# Behavior class
# =============================================================================
class Behavior (DBSIG2.Behavior):
"""
Behavior class for PostgreSQL backends.
"""
# ---------------------------------------------------------------------------
# Constructor
# ---------------------------------------------------------------------------
def __init__ (self, *args, **kwargs):
DBSIG2.Behavior.__init__ (self, *args, **kwargs)
self.__RELKIND = {'v': {'type': 'view', 'name': u_("Views")},
'r': {'type': 'table', 'name': u_("Tables")}}
# Build typemap: {nativetype: (group, fieldtype)}
self.__TYPEMAP = {'date' : ('date', 'date'),
'bool' : ('boolean', 'boolean'),
'string': ('string', 'string')}
for item in ['numeric', 'float4', 'float8', 'money', 'int8',
'int2', 'int4', 'serial']:
self.__TYPEMAP [item] = ('number', 'number')
for item in ['time', 'reltime']:
self.__TYPEMAP [item] = ('date', 'time')
for item in ['timestamp', 'abstime']:
self.__TYPEMAP [item] = ('date', 'datetime')
self._maxIdLength_ = 31
self._alterMultiple_ = False
self._numbers_ = [[(4, 'smallint'), (9, 'integer'), (18, 'bigint')],
"numeric (%s,0)", "numeric (%(length)s,%(scale)s)"]
self._type2native_.update ({'boolean' : 'boolean',
'datetime': 'timestamp without time zone'})
# ---------------------------------------------------------------------------
# Create a new database
# ---------------------------------------------------------------------------
def _createDatabase_ (self):
"""
Create the requested user and database using the tools 'createuser',
'createdb' and 'dropuser'. Of course this function should better make use
of the template1 database using a connection object.
"""
dbname = self.__connection.parameters.get ('dbname')
username = self.__connection.parameters.get ('username', 'gnue')
password = self.__connection.parameters.get ('password')
host = self.__connection.parameters.get ('host')
port = self.__connection.parameters.get ('port')
owner = self.__connection.parameters.get ('owner', username)
ownerpwd = self.__connection.parameters.get ('ownerpwd')
site = ""
if host is not None:
site += " --host=%s" % host
if port is not None:
site += " --port=%s" % port
# First, let's connect to template1 using the given username and password
self.__connection.parameters ['dbname'] = 'template1'
self.__connection.manager.loginToConnection (self.__connection)
# Then have a look wether the requested owner is already available
result = self.__connection.sql ('SELECT usesysid FROM pg_user ' \
'WHERE usename = %(owner)s', {'owner': owner})
if not result:
cmd = 'CREATE USER %s' % owner
if ownerpwd:
cmd += " WITH PASSWORD '%s'" % ownerpwd
self.__connection.sql0 (cmd)
self.__connection.commit ()
# Now go and create that new database
cmd = "ABORT; CREATE DATABASE %s WITH OWNER %s ENCODING = 'UNICODE'; BEGIN"
self.__connection.sql0 (cmd % (dbname, owner))
self.__connection.commit ()
self.__connection.close ()
# Since the newly created database should be available now, connect to it
# using the given owner
self.__connection.parameters ['dbname'] = dbname
self.__connection.parameters ['username'] = owner
if ownerpwd:
self.__connection.parameters ['password'] = ownerpwd
else:
if 'password' in self.__connection.parameters:
del self.__connection.parameters ['password']
self.__connection.manager.loginToConnection (self.__connection)
# ---------------------------------------------------------------------------
# Read the current connection's schema
# ---------------------------------------------------------------------------
def _readSchema_ (self, parent):
"""
Read the connection's schema and build a GSchema object tree connected to
the given parent object (which is of type GSSchema).
"""
tables = self.__readTables (parent)
fields = self.__readFields (tables)
self.__readDefaults (fields)
self.__readKeys (tables)
self.__readConstraints (tables, fields)
# ---------------------------------------------------------------------------
# Read all table-like elements
# ---------------------------------------------------------------------------
def __readTables (self, parent):
mapping = {} # Maps OIDs to GSTable instances
tables = None
views = None
cmd = u"SELECT c.oid, c.relname, c.relkind " \
"FROM pg_class c, pg_namespace n " \
"WHERE n.nspname = 'public' AND n.oid = c.relnamespace AND " \
" c.relkind in (%s) " \
"ORDER BY c.relname" \
% ','.join (["%r" % kind for kind in self.__RELKIND.keys ()])
cursor = self.__connection.makecursor (cmd)
try:
for (oid, relname, relkind) in cursor.fetchall ():
kind = self.__RELKIND [relkind] ['type']
properties = {'id': oid, 'name': relname, 'kind': kind}
if relkind == 'v':
if views is None:
views = GSchema.GSTables (parent, **self.__RELKIND [relkind])
master = views
else:
if tables is None:
tables = GSchema.GSTables (parent, **self.__RELKIND [relkind])
master = tables
table = GSchema.GSTable (master, **properties)
# Maintain a temporary mapping from OID's to GSTable instances so
# adding fields afterwards runs faster
mapping [oid] = table
finally:
cursor.close ()
return mapping
# ---------------------------------------------------------------------------
# Find all fields
# ---------------------------------------------------------------------------
def __readFields (self, tables):
cmd = u"SELECT attrelid, attname, t.typname, attnotnull, " \
" atthasdef, atttypmod, attnum, attlen " \
"FROM pg_attribute a " \
"LEFT OUTER JOIN pg_type t ON t.oid = a.atttypid " \
"WHERE attnum >= 0 AND attisdropped = False " \
"ORDER BY attrelid, attnum"
cursor = self.__connection.makecursor (cmd)
fields = None
result = {}
try:
for rs in cursor.fetchall ():
(relid, name, typename, notnull, hasdef, typemod, attnum, attlen) = rs
# only process attributes from tables we've listed before
if not relid in tables:
continue
attrs = {'id' : "%s.%s" % (relid, attnum),
'name' : name,
'nativetype': typename,
'nullable' : hasdef or not notnull}
if typename.lower () in self.__TYPEMAP:
(group, attrs ['type']) = self.__TYPEMAP [typename.lower ()]
else:
(group, attrs ['type']) = self.__TYPEMAP ['string']
if group == 'number':
if typemod != -1:
value = typemod - 4
attrs ['length'] = value >> 16
attrs ['precision'] = value & 0xFFFF
elif attlen > 0:
attrs ['length'] = len ("%s" % 2L ** (attlen * 8))
elif typemod != -1:
attrs ['length'] = typemod - 4
# Remove obsolete attributes
if group in ['date', 'boolean']:
for item in ['length', 'precision']:
if item in attrs:
del attrs [item]
elif group in ['string']:
if 'precision' in attrs:
del attrs ['precision']
table = tables [relid]
fields = table.findChildOfType ('GSFields')
if fields is None:
fields = GSchema.GSFields (table)
result [attrs ['id']] = GSchema.GSField (fields, **attrs)
finally:
cursor.close ()
return result
# ---------------------------------------------------------------------------
# Read defaults and apply them to the given fields
# ---------------------------------------------------------------------------
def __readDefaults (self, fields):
cmd = u"SELECT adrelid, adnum, adsrc FROM pg_attrdef ORDER BY adrelid"
cursor = self.__connection.makecursor (cmd)
try:
for (relid, fieldnum, source) in cursor.fetchall ():
field = fields.get ("%s.%s" % (relid, fieldnum))
# Skip all defaults of not listed fields
if field is None:
continue
if source [:8] == 'nextval(':
field.defaultwith = 'serial'
elif source == 'now()':
field.defaultwith = 'timestamp'
else:
field.defaultwith = 'constant'
field.default = source.split ('::') [0].strip ("'")
finally:
cursor.close ()
# ---------------------------------------------------------------------------
# Read all indices and associate them with their table/view
# ---------------------------------------------------------------------------
def __readKeys (self, tables):
cmd = u"SELECT indrelid, indkey, indisunique, indisprimary, c.relname " \
"FROM pg_index i LEFT OUTER JOIN pg_class c ON c.oid = indexrelid"
cursor = self.__connection.makecursor (cmd)
try:
for (relid, fieldvec, isUnique, isPrimary, name) in cursor.fetchall ():
# Skip functional indices. A functional index is an index that is built
# upon a fuction manipulating a field upper(userid) vs userid
fields = [int (i) - 1 for i in fieldvec.split ()]
if not fields:
continue
# only process keys of listed tables
table = tables.get (relid)
if table is None:
continue
if isPrimary:
index = GSchema.GSPrimaryKey (table, name = name)
fClass = GSchema.GSPKField
else:
indices = table.findChildOfType ('GSIndexes')
if indices is None:
indices = GSchema.GSIndexes (table)
index = GSchema.GSIndex (indices, unique = isUnique, name = name)
fClass = GSchema.GSIndexField
fieldList = table.findChildrenOfType ('GSField', False, True)
for find in fields:
fClass (index, name = fieldList [find].name)
finally:
cursor.close ()
# ---------------------------------------------------------------------------
# Read all constraints
# ---------------------------------------------------------------------------
def __readConstraints (self, tables, fields):
cmd = u"SELECT conname, conrelid, confrelid, conkey, confkey, contype " \
"FROM pg_constraint WHERE contype in ('f', 'u')"
cursor = self.__connection.makecursor (cmd)
try:
for (name, relid, fkrel, key, fkey, ctype) in cursor.fetchall ():
table = tables.get (relid)
if ctype == 'f':
fktable = tables.get (fkrel)
# We need both ends of a relation to be a valid constraint
if table is None or fktable is None:
continue
parent = table.findChildOfType ('GSConstraints')
if parent is None:
parent = GSchema.GSConstraints (table)
constr = GSchema.GSForeignKey (parent, name = name,
references = fktable.name)
kp = isinstance (key, basestring) and key [1:-1].split (',') or key
fkp = isinstance (fkey, basestring) and fkey [1:-1].split(',') or fkey
k = [fields ["%s.%s" % (relid, i)].name for i in kp]
f = [fields ["%s.%s" % (fkrel, i)].name for i in fkp]
for (name, refname) in zip (k, f):
GSchema.GSFKField (constr, name = name, references = refname)
# Unique-Constraint
elif ctype == 'u':
parent = table.findChildOfType ('GSConstraints') or \
GSchema.GSConstraints (table)
constr = GSchema.GSUnique (parent, name = name)
kp = isinstance (key, basestring) and key [1:-1].split (',') or key
for name in [fields ["%s.%s" % (relid, i)].name for i in kp]:
GSchema.GSUQField (constr, name = name)
# Ok, since we know PostgreSQL automatically creates a unique index
# of the same name, we drop that index since it would only confuse a
# later diff
for ix in table.findChildrenOfType ('GSIndex', False, True):
if ix.name == constr.name:
parent = ix.getParent ()
parent._children.remove (ix)
ix.setParent (None)
finally:
cursor.close ()
# ---------------------------------------------------------------------------
# Handle special defaults
# ---------------------------------------------------------------------------
def _defaultwith_ (self, code, field):
"""
Create a sequence for 'serials' and set the default for 'timestamps'.
@param code: code-triple to get the result
@param field: GSField instance of the field having the default
"""
if field.defaultwith == 'serial':
seq = self._getSequenceName (field)
code [0].append (u"CREATE SEQUENCE %s" % seq)
field.default = "DEFAULT nextval ('%s')" % seq
elif field.defaultwith == 'timestamp':
field.default = "DEFAULT now()"
| HarmonyEnterpriseSolutions/harmony-platform | src/gnue/common/datasources/drivers/sql/postgresql/Behavior.py | Python | gpl-2.0 | 13,533 |
<?php
/**
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Bundle\EzPublishCoreBundle\Imagine\Filter\Loader;
use eZ\Bundle\EzPublishCoreBundle\Imagine\Filter\FilterInterface;
use Imagine\Image\ImageInterface;
use Liip\ImagineBundle\Imagine\Filter\Loader\LoaderInterface;
class SwirlFilterLoader implements LoaderInterface
{
/** @var FilterInterface */
private $filter;
public function __construct(FilterInterface $filter)
{
$this->filter = $filter;
}
public function load(ImageInterface $image, array $options = [])
{
if (!empty($options)) {
$this->filter->setOption('degrees', $options[0]);
}
return $this->filter->apply($image);
}
}
| ezsystems/ezpublish-kernel | eZ/Bundle/EzPublishCoreBundle/Imagine/Filter/Loader/SwirlFilterLoader.php | PHP | gpl-2.0 | 857 |
/*
* This file is part of the LIRE project: http://www.semanticmetadata.net/lire
* LIRE 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.
*
* LIRE 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 LIRE; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* We kindly ask you to refer the any or one of the following publications in
* any publication mentioning or employing Lire:
*
* Lux Mathias, Savvas A. Chatzichristofis. Lire: Lucene Image Retrieval –
* An Extensible Java CBIR Library. In proceedings of the 16th ACM International
* Conference on Multimedia, pp. 1085-1088, Vancouver, Canada, 2008
* URL: http://doi.acm.org/10.1145/1459359.1459577
*
* Lux Mathias. Content Based Image Retrieval with LIRE. In proceedings of the
* 19th ACM International Conference on Multimedia, pp. 735-738, Scottsdale,
* Arizona, USA, 2011
* URL: http://dl.acm.org/citation.cfm?id=2072432
*
* Mathias Lux, Oge Marques. Visual Information Retrieval using Java and LIRE
* Morgan & Claypool, 2013
* URL: http://www.morganclaypool.com/doi/abs/10.2200/S00468ED1V01Y201301ICR025
*
* Copyright statement:
* ====================
* (c) 2002-2013 by Mathias Lux (mathias@juggle.at)
* http://www.semanticmetadata.net/lire, http://www.lire-project.net
*
* Updated: 01.07.13 16:15
*/
package net.semanticmetadata.lire.indexing.tools;
import net.semanticmetadata.lire.DocumentBuilder;
import net.semanticmetadata.lire.imageanalysis.LireFeature;
import net.semanticmetadata.lire.indexing.parallel.WorkItem;
import net.semanticmetadata.lire.utils.ImageUtils;
import net.semanticmetadata.lire.utils.SerializationUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
/**
* The Extractor is a configurable class that extracts multiple features from multiple images
* and puts them into a data file. Main purpose is run multiple extractors at multiple machines
* and put the data files into one single index. Images are references relatively to the data file,
* so it should work fine for network file systems.
* <p/>
* File format is specified as: (12(345)+)+ with 1-5 being ...
* <p/>
* 1. Length of the file hashFunctionsFileName [4 bytes], an int n giving the number of bytes for the file hashFunctionsFileName
* 2. File hashFunctionsFileName, relative to the outfile [n bytes, see above]
* 3. Feature index [1 byte], see static members
* 4. Feature value length [4 bytes], an int k giving the number of bytes encoding the value
* 5. Feature value [k bytes, see above]
* <p/>
* The file is sent through an GZIPOutputStream, so it's compressed in addition.
* <p/>
* Note that the outfile has to be in a folder parent to all images!
*
* @author Mathias Lux, mathias@juggle.at, 08.03.13
*/
public class ParallelExtractor implements Runnable {
public static final String[] features = new String[]{
"net.semanticmetadata.lire.imageanalysis.CEDD", // 0
"net.semanticmetadata.lire.imageanalysis.FCTH", // 1
"net.semanticmetadata.lire.imageanalysis.OpponentHistogram", // 2
"net.semanticmetadata.lire.imageanalysis.joint.JointHistogram", // 3
"net.semanticmetadata.lire.imageanalysis.AutoColorCorrelogram", // 4
"net.semanticmetadata.lire.imageanalysis.ColorLayout", // 5
"net.semanticmetadata.lire.imageanalysis.EdgeHistogram", // 6
"net.semanticmetadata.lire.imageanalysis.Gabor", // 7
"net.semanticmetadata.lire.imageanalysis.JCD", // 8
"net.semanticmetadata.lire.imageanalysis.JpegCoefficientHistogram",
"net.semanticmetadata.lire.imageanalysis.ScalableColor", // 10
"net.semanticmetadata.lire.imageanalysis.SimpleColorHistogram", // 11
"net.semanticmetadata.lire.imageanalysis.Tamura", // 12
"net.semanticmetadata.lire.imageanalysis.LuminanceLayout", // 13
"net.semanticmetadata.lire.imageanalysis.PHOG", // 14
};
public static final String[] featureFieldNames = new String[]{
DocumentBuilder.FIELD_NAME_CEDD, // 0
DocumentBuilder.FIELD_NAME_FCTH, // 1
DocumentBuilder.FIELD_NAME_OPPONENT_HISTOGRAM, // 2
DocumentBuilder.FIELD_NAME_JOINT_HISTOGRAM, // 3
DocumentBuilder.FIELD_NAME_AUTOCOLORCORRELOGRAM, // 4
DocumentBuilder.FIELD_NAME_COLORLAYOUT, // 5
DocumentBuilder.FIELD_NAME_EDGEHISTOGRAM, // 6
DocumentBuilder.FIELD_NAME_GABOR, // 7
DocumentBuilder.FIELD_NAME_JCD, // 8
DocumentBuilder.FIELD_NAME_JPEGCOEFFS,
DocumentBuilder.FIELD_NAME_SCALABLECOLOR,
DocumentBuilder.FIELD_NAME_COLORHISTOGRAM,
DocumentBuilder.FIELD_NAME_TAMURA, // 12
DocumentBuilder.FIELD_NAME_LUMINANCE_LAYOUT, // 13
DocumentBuilder.FIELD_NAME_PHOG, // 14
};
static HashMap<String, Integer> feature2index;
static {
feature2index = new HashMap<String, Integer>(features.length);
for (int i = 0; i < features.length; i++) {
feature2index.put(features[i], i);
}
}
private static boolean force = false;
private static int numberOfThreads = 4;
Stack<WorkItem> images = new Stack<WorkItem>();
boolean ended = false;
int overallCount = 0;
OutputStream dos = null;
LinkedList<LireFeature> listOfFeatures;
File fileList = null;
File outFile = null;
private int monitoringInterval = 10;
private int maxSideLength = -1;
public ParallelExtractor() {
// default constructor.
listOfFeatures = new LinkedList<LireFeature>();
}
/**
* Sets the number of consumer threads that are employed for extraction
*
* @param numberOfThreads
*/
public static void setNumberOfThreads(int numberOfThreads) {
ParallelExtractor.numberOfThreads = numberOfThreads;
}
public static void main(String[] args) throws IOException {
ParallelExtractor e = new ParallelExtractor();
// parse programs args ...
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("-i")) {
// infile ...
if ((i + 1) < args.length)
e.setFileList(new File(args[i + 1]));
else printHelp();
} else if (arg.startsWith("-o")) {
// out file
if ((i + 1) < args.length)
e.setOutFile(new File(args[i + 1]));
else printHelp();
} else if (arg.startsWith("-m")) {
// out file
if ((i + 1) < args.length) {
try {
int s = Integer.parseInt(args[i + 1]);
if (s > 10)
e.setMaxSideLength(s);
} catch (NumberFormatException e1) {
e1.printStackTrace();
printHelp();
}
} else printHelp();
} else if (arg.startsWith("-f")) {
force = true;
} else if (arg.startsWith("-h")) {
// help
printHelp();
} else if (arg.startsWith("-n")) {
if ((i + 1) < args.length)
try {
ParallelExtractor.numberOfThreads = Integer.parseInt(args[i + 1]);
} catch (Exception e1) {
System.err.println("Could not set number of threads to \"" + args[i + 1] + "\".");
e1.printStackTrace();
}
else printHelp();
} else if (arg.startsWith("-c")) {
// config file ...
Properties p = new Properties();
p.load(new FileInputStream(new File(args[i + 1])));
Enumeration<?> enumeration = p.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
if (key.toLowerCase().startsWith("feature.")) {
try {
e.addFeature((LireFeature) Class.forName(p.getProperty(key)).newInstance());
} catch (Exception e1) {
System.err.println("Could not add feature named " + p.getProperty(key));
e1.printStackTrace();
}
}
}
}
}
// check if there is an infile, an outfile and some features to extract.
if (!e.isConfigured()) {
printHelp();
} else {
e.run();
}
}
private static void printHelp() {
System.out.println("Help for the ParallelExtractor class.\n" +
"=============================\n" +
"This help text is shown if you start the ParallelExtractor with the '-h' option.\n" +
"\n" +
"1. Usage\n" +
"========\n" +
"$> ParallelExtractor -i <infile> [-o <outfile>] -c <configfile> [-n <threads>] [-m <max_side_length>]\n" +
"\n" +
"Note: if you don't specify an outfile just \".data\" is appended to the infile for output.\n" +
"\n" +
"2. Config File\n" +
"==============\n" +
"The config file is a simple java Properties file. It basically gives the \n" +
"employed features as a list of properties, just like:\n" +
"\n" +
"feature.1=net.semanticmetadata.lire.imageanalysis.CEDD\n" +
"feature.2=net.semanticmetadata.lire.imageanalysis.FCTH\n" +
"\n" +
"... and so on. ");
}
/**
* Adds a feature to the extractor chain. All those features are extracted from images.
*
* @param feature
*/
public void addFeature(LireFeature feature) {
listOfFeatures.add(feature);
}
/**
* Sets the file list for processing. One image file per line is fine.
*
* @param fileList
*/
public void setFileList(File fileList) {
this.fileList = fileList;
}
/**
* Sets the outfile. The outfile has to be in a folder parent to all input images.
*
* @param outFile
*/
public void setOutFile(File outFile) {
this.outFile = outFile;
}
public int getMaxSideLength() {
return maxSideLength;
}
public void setMaxSideLength(int maxSideLength) {
this.maxSideLength = maxSideLength;
}
private boolean isConfigured() {
boolean configured = true;
if (fileList == null || !fileList.exists()) configured = false;
else if (outFile == null) {
// create an outfile ...
try {
outFile = new File(fileList.getCanonicalPath() + ".data");
System.out.println("Setting out file to " + outFile.getCanonicalFile());
} catch (IOException e) {
configured = false;
}
} else if (outFile.exists() && !force) {
System.err.println(outFile.getName() + " already exists. Please delete or choose another outfile.");
configured = false;
}
if (listOfFeatures.size() < 1) configured = false;
return configured;
}
@Override
public void run() {
// check:
if (fileList == null || !fileList.exists()) {
System.err.println("No text file with a list of images given.");
return;
}
if (listOfFeatures.size() == 0) {
System.err.println("No features to extract given.");
return;
}
try {
dos = new BufferedOutputStream(new FileOutputStream(outFile));
Thread p = new Thread(new Producer());
p.start();
LinkedList<Thread> threads = new LinkedList<Thread>();
long l = System.currentTimeMillis();
for (int i = 0; i < numberOfThreads; i++) {
Thread c = new Thread(new Consumer());
c.start();
threads.add(c);
}
Thread m = new Thread(new Monitoring());
m.start();
for (Iterator<Thread> iterator = threads.iterator(); iterator.hasNext(); ) {
iterator.next().join();
}
long l1 = System.currentTimeMillis() - l;
System.out.println("Analyzed " + overallCount + " images in " + l1 / 1000 + " seconds, ~" + (overallCount > 0 ? (l1 / overallCount) : "inf.") + " ms each.");
dos.close();
// writer.commit();
// writer.close();
// threadFinished = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private void addFeatures(List features) {
for (Iterator<LireFeature> iterator = listOfFeatures.iterator(); iterator.hasNext(); ) {
LireFeature next = iterator.next();
try {
features.add(next.getClass().newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Monitoring implements Runnable {
public void run() {
long ms = System.currentTimeMillis();
try {
Thread.sleep(1000 * monitoringInterval); // wait xx seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
while (!ended) {
try {
// print the current status:
long time = System.currentTimeMillis() - ms;
System.out.println("Analyzed " + overallCount + " images in " + time / 1000 + " seconds, " + ((overallCount > 0) ? (time / overallCount) : "n.a.") + " ms each (" + images.size() + " images currently in queue).");
Thread.sleep(1000 * monitoringInterval); // wait xx seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer implements Runnable {
public void run() {
int tmpSize = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(fileList));
String file = null;
File next = null;
while ((file = br.readLine()) != null) {
next = new File(file);
BufferedImage img = null;
try {
int fileSize = (int) next.length();
byte[] buffer = new byte[fileSize];
FileInputStream fis = new FileInputStream(next);
fis.read(buffer);
String path = next.getCanonicalPath();
synchronized (images) {
images.add(new WorkItem(path, buffer));
tmpSize = images.size();
// if the cache is too crowded, then wait.
if (tmpSize > 500) images.wait(500);
// if the cache is too small, dont' notify.
images.notify();
}
} catch (Exception e) {
System.err.println("Could not read image " + file + ": " + e.getMessage());
}
try {
if (tmpSize > 500) Thread.sleep(1000);
// else Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
synchronized (images) {
ended = true;
images.notifyAll();
}
}
}
class Consumer implements Runnable {
WorkItem tmp = null;
LinkedList<LireFeature> features = new LinkedList<LireFeature>();
int count = 0;
boolean locallyEnded = false;
Consumer() {
addFeatures(features);
}
public void run() {
byte[] myBuffer = new byte[1024 * 1024 * 10];
int bufferCount = 0;
while (!locallyEnded) {
synchronized (images) {
// we wait for the stack to be either filled or empty & not being filled any more.
while (images.empty() && !ended) {
try {
images.wait(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// make sure the thread locally knows that the end has come (outer loop)
if (images.empty() && ended)
locallyEnded = true;
// well the last thing we want is an exception in the very last round.
if (!images.empty() && !locallyEnded) {
tmp = images.pop();
count++;
overallCount++;
}
}
try {
bufferCount = 0;
if (!locallyEnded) {
ByteArrayInputStream b = new ByteArrayInputStream(tmp.getBuffer());
BufferedImage img = ImageIO.read(b);
if (maxSideLength > 50) img = ImageUtils.scaleImage(img, maxSideLength);
byte[] tmpBytes = tmp.getFileName().getBytes();
// everything is written to a buffer and only if no exception is thrown, the image goes to index.
System.arraycopy(SerializationUtils.toBytes(tmpBytes.length), 0, myBuffer, 0, 4);
bufferCount += 4;
// dos.write(SerializationUtils.toBytes(tmpBytes.length));
System.arraycopy(tmpBytes, 0, myBuffer, bufferCount, tmpBytes.length);
bufferCount += tmpBytes.length;
// dos.write(tmpBytes);
for (LireFeature feature : features) {
feature.extract(img);
myBuffer[bufferCount] = (byte) feature2index.get(feature.getClass().getName()).intValue();
bufferCount++;
// dos.write(feature2index.get(feature.getClass().getName()));
tmpBytes = feature.getByteArrayRepresentation();
System.arraycopy(SerializationUtils.toBytes(tmpBytes.length), 0, myBuffer, bufferCount, 4);
bufferCount += 4;
// dos.write(SerializationUtils.toBytes(tmpBytes.length));
System.arraycopy(tmpBytes, 0, myBuffer, bufferCount, tmpBytes.length);
bufferCount += tmpBytes.length;
// dos.write(tmpBytes);
}
// finally write everything to the stream - in case no exception was thrown..
synchronized (dos) {
dos.write(myBuffer, 0, bufferCount);
dos.write(-1);
dos.flush();
}
}
} catch (Exception e) {
System.err.println("Error processing file " + tmp.getFileName());
e.printStackTrace();
}
}
}
}
}
| GregBowyer/lire | src/main/java/net/semanticmetadata/lire/indexing/tools/ParallelExtractor.java | Java | gpl-2.0 | 21,231 |
/**
* 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("/BenchmarkTest01545")
public class BenchmarkTest01545 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 {
String param = request.getHeader("foo");
String bar;
// Simple ? condition that assigns param to bar on false condition
int i = 106;
bar = (7*42) - i > 200 ? "This should never happen" : param;
String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
try {
java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
statement.execute( sql, new String[] { "username", "password" } );
} catch (java.sql.SQLException e) {
throw new ServletException(e);
}
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01545.java | Java | gpl-2.0 | 2,076 |
from miasm.core.utils import size2mask
from miasm.expression.expression import ExprInt, ExprCond, ExprCompose, \
TOK_EQUAL
def simp_ext(_, expr):
if expr.op.startswith('zeroExt_'):
arg = expr.args[0]
if expr.size == arg.size:
return arg
return ExprCompose(arg, ExprInt(0, expr.size - arg.size))
if expr.op.startswith("signExt_"):
arg = expr.args[0]
add_size = expr.size - arg.size
new_expr = ExprCompose(
arg,
ExprCond(
arg.msb(),
ExprInt(size2mask(add_size), add_size),
ExprInt(0, add_size)
)
)
return new_expr
return expr
def simp_flags(_, expr):
args = expr.args
if expr.is_op("FLAG_EQ"):
return ExprCond(args[0], ExprInt(0, 1), ExprInt(1, 1))
elif expr.is_op("FLAG_EQ_AND"):
op1, op2 = args
return ExprCond(op1 & op2, ExprInt(0, 1), ExprInt(1, 1))
elif expr.is_op("FLAG_SIGN_SUB"):
return (args[0] - args[1]).msb()
elif expr.is_op("FLAG_EQ_CMP"):
return ExprCond(
args[0] - args[1],
ExprInt(0, 1),
ExprInt(1, 1),
)
elif expr.is_op("FLAG_ADD_CF"):
op1, op2 = args
res = op1 + op2
return (((op1 ^ op2) ^ res) ^ ((op1 ^ res) & (~(op1 ^ op2)))).msb()
elif expr.is_op("FLAG_SUB_CF"):
op1, op2 = args
res = op1 - op2
return (((op1 ^ op2) ^ res) ^ ((op1 ^ res) & (op1 ^ op2))).msb()
elif expr.is_op("FLAG_ADD_OF"):
op1, op2 = args
res = op1 + op2
return (((op1 ^ res) & (~(op1 ^ op2)))).msb()
elif expr.is_op("FLAG_SUB_OF"):
op1, op2 = args
res = op1 - op2
return (((op1 ^ res) & (op1 ^ op2))).msb()
elif expr.is_op("FLAG_EQ_ADDWC"):
op1, op2, op3 = args
return ExprCond(
op1 + op2 + op3.zeroExtend(op1.size),
ExprInt(0, 1),
ExprInt(1, 1),
)
elif expr.is_op("FLAG_ADDWC_OF"):
op1, op2, op3 = args
res = op1 + op2 + op3.zeroExtend(op1.size)
return (((op1 ^ res) & (~(op1 ^ op2)))).msb()
elif expr.is_op("FLAG_SUBWC_OF"):
op1, op2, op3 = args
res = op1 - (op2 + op3.zeroExtend(op1.size))
return (((op1 ^ res) & (op1 ^ op2))).msb()
elif expr.is_op("FLAG_ADDWC_CF"):
op1, op2, op3 = args
res = op1 + op2 + op3.zeroExtend(op1.size)
return (((op1 ^ op2) ^ res) ^ ((op1 ^ res) & (~(op1 ^ op2)))).msb()
elif expr.is_op("FLAG_SUBWC_CF"):
op1, op2, op3 = args
res = op1 - (op2 + op3.zeroExtend(op1.size))
return (((op1 ^ op2) ^ res) ^ ((op1 ^ res) & (op1 ^ op2))).msb()
elif expr.is_op("FLAG_SIGN_ADDWC"):
op1, op2, op3 = args
return (op1 + op2 + op3.zeroExtend(op1.size)).msb()
elif expr.is_op("FLAG_SIGN_SUBWC"):
op1, op2, op3 = args
return (op1 - (op2 + op3.zeroExtend(op1.size))).msb()
elif expr.is_op("FLAG_EQ_SUBWC"):
op1, op2, op3 = args
res = op1 - (op2 + op3.zeroExtend(op1.size))
return ExprCond(res, ExprInt(0, 1), ExprInt(1, 1))
elif expr.is_op("CC_U<="):
op_cf, op_zf = args
return op_cf | op_zf
elif expr.is_op("CC_U>="):
op_cf, = args
return ~op_cf
elif expr.is_op("CC_S<"):
op_nf, op_of = args
return op_nf ^ op_of
elif expr.is_op("CC_S>"):
op_nf, op_of, op_zf = args
return ~(op_zf | (op_nf ^ op_of))
elif expr.is_op("CC_S<="):
op_nf, op_of, op_zf = args
return op_zf | (op_nf ^ op_of)
elif expr.is_op("CC_S>="):
op_nf, op_of = args
return ~(op_nf ^ op_of)
elif expr.is_op("CC_U>"):
op_cf, op_zf = args
return ~(op_cf | op_zf)
elif expr.is_op("CC_U<"):
op_cf, = args
return op_cf
elif expr.is_op("CC_NEG"):
op_nf, = args
return op_nf
elif expr.is_op("CC_EQ"):
op_zf, = args
return op_zf
elif expr.is_op("CC_NE"):
op_zf, = args
return ~op_zf
elif expr.is_op("CC_POS"):
op_nf, = args
return ~op_nf
return expr
| serpilliere/miasm | miasm/expression/simplifications_explicit.py | Python | gpl-2.0 | 4,228 |
<?php
/**
* WooCommerce Jetpack Product Images
*
* The WooCommerce Jetpack Product Images class.
*
* @version 2.2.0
* @since 2.2.0
* @author Algoritmika Ltd.
*/
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! class_exists( 'WCJ_Product_Images' ) ) :
class WCJ_Product_Images extends WCJ_Module {
/**
* Constructor.
*/
public function __construct() {
$this->id = 'product_images';
$this->short_desc = __( 'Product Images', 'woocommerce-jetpack' );
$this->desc = __( 'Customize WooCommerce products images, thumbnails and sale flashes.', 'woocommerce-jetpack' );
parent::__construct();
if ( $this->is_enabled() ) {
// Product Image & Thumbnails
if ( 'yes' === get_option( 'wcj_product_images_and_thumbnails_enabled', 'no' ) ) {
if ( 'yes' === get_option( 'wcj_product_images_and_thumbnails_hide_on_single', 'no' ) ) {
add_action( 'init', array( $this, 'product_images_and_thumbnails_hide_on_single' ), PHP_INT_MAX );
} else {
add_filter( 'woocommerce_single_product_image_html', array( $this, 'customize_single_product_image_html' ) );
add_filter( 'woocommerce_single_product_image_thumbnail_html', array( $this, 'customize_single_product_image_thumbnail_html' ) );
}
if ( 'yes' === get_option( 'wcj_product_images_hide_on_archive', 'no' ) ) {
add_action( 'init', array( $this, 'product_images_hide_on_archive' ), PHP_INT_MAX );
}
// Single Product Thumbnails Columns Number
add_filter( 'woocommerce_product_thumbnails_columns', array( $this, 'change_product_thumbnails_columns_number' ) );
}
// Sale flash
if ( 'yes' === get_option( 'wcj_product_images_sale_flash_enabled', 'no' ) ) {
add_filter( 'woocommerce_sale_flash', array( $this, 'customize_sale_flash' ), PHP_INT_MAX, 3 );
}
}
}
/**
* product_images_and_thumbnails_hide_on_single.
*/
public function product_images_and_thumbnails_hide_on_single() {
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
}
/**
* product_images_hide_on_archive.
*/
public function product_images_hide_on_archive() {
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
}
/**
* customize_sale_flash.
*/
public function customize_sale_flash( $sale_flash_html, $post, $product ) {
// Hiding
if ( 'yes' === get_option( 'wcj_product_images_sale_flash_hide_on_archives', 'no' ) && is_archive() ) return '';
if ( 'yes' === get_option( 'wcj_product_images_sale_flash_hide_on_single', 'no' ) && is_single() && get_the_ID() === $product->id ) return '';
// Content
return do_shortcode(
get_option( 'wcj_product_images_sale_flash_html' ,
'<span class="onsale">' . __( 'Sale!', 'woocommerce' ) . '</span>' )
);
}
/**
* customize_single_product_image_html.
*/
public function customize_single_product_image_html( $image_link ) {
return ( 'yes' === get_option( 'wcj_product_images_hide_on_single', 'no' ) ) ? '' : $image_link;
}
/**
* customize_single_product_image_thumbnail_html.
*/
public function customize_single_product_image_thumbnail_html( $image_link ) {
return ( 'yes' === get_option( 'wcj_product_images_thumbnails_hide_on_single', 'no' ) ) ? '' : $image_link;
}
/**
* change_product_thumbnails_columns.
*/
public function change_product_thumbnails_columns_number( $columns_number ) {
return get_option( 'wcj_product_images_thumbnails_columns', 3 );
}
/**
* get_settings.
*/
function get_settings() {
$settings = array(
array( 'title' => __( 'Product Image and Thumbnails', 'woocommerce-jetpack' ), 'type' => 'title', 'desc' => '', 'id' => 'wcj_product_images_and_thumbnails_options' ),
array(
'title' => __( 'Enable Section', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_and_thumbnails_enabled',
'default' => 'no',
'type' => 'checkbox',
),
array(
'title' => __( 'Image and Thumbnails on Single', 'woocommerce-jetpack' ),
'desc' => __( 'Hide', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_and_thumbnails_hide_on_single',
'default' => 'no',
'type' => 'checkbox',
),
array(
'title' => __( 'Image on Single', 'woocommerce-jetpack' ),
'desc' => __( 'Hide', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_hide_on_single',
'default' => 'no',
'type' => 'checkbox',
),
array(
'title' => __( 'Thumbnails on Single', 'woocommerce-jetpack' ),
'desc' => __( 'Hide', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_thumbnails_hide_on_single',
'default' => 'no',
'type' => 'checkbox',
),
array(
'title' => __( 'Image on Archives', 'woocommerce-jetpack' ),
'desc' => __( 'Hide', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_hide_on_archive',
'default' => 'no',
'type' => 'checkbox',
),
array(
'title' => __( 'Single Product Thumbnails Columns', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_thumbnails_columns',
'default' => 3,
'type' => 'number',
),
array( 'type' => 'sectionend', 'id' => 'wcj_product_images_and_thumbnails_options' ),
array( 'title' => __( 'Product Images Sale Flash', 'woocommerce-jetpack' ), 'type' => 'title', 'desc' => '', 'id' => 'wcj_product_images_sale_flash_options' ),
array(
'title' => __( 'Enable Section', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_sale_flash_enabled',
'default' => 'no',
'type' => 'checkbox',
),
array(
'title' => __( 'HTML', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_sale_flash_html',
'default' => '<span class="onsale">' . __( 'Sale!', 'woocommerce' ) . '</span>',
'type' => 'textarea',
'css' => 'width:300px;height:100px;',
),
array(
'title' => __( 'Hide on Archives (Categories)', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_sale_flash_hide_on_archives',
'default' => 'no',
'type' => 'checkbox',
),
array(
'title' => __( 'Hide on Single', 'woocommerce-jetpack' ),
'id' => 'wcj_product_images_sale_flash_hide_on_single',
'default' => 'no',
'type' => 'checkbox',
),
array( 'type' => 'sectionend', 'id' => 'wcj_product_images_sale_flash_options' ),
);
return $this->add_enable_module_setting( $settings );
}
}
endif;
return new WCJ_Product_Images();
| SasaKlepikov/Syberg.eu | wp-content/plugins/woocommerce-jetpack/includes/class-wcj-product-images.php | PHP | gpl-2.0 | 6,506 |
<?php
/*
* @version $Id$
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2015-2016 Teclib'.
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");
}
/**
* NotificationTemplate Class
**/
class NotificationTemplate extends CommonDBTM {
// From CommonDBTM
public $dohistory = true;
//Signature to add to the template
public $signature = '';
//Store templates for each language
public $templates_by_languages = array();
static $rightname = 'config';
static function getTypeName($nb=0) {
return _n('Notification template', 'Notification templates', $nb);
}
static function canCreate() {
return static::canUpdate();
}
/**
* @since version 0.85
**/
static function canPurge() {
return static::canUpdate();
}
function defineTabs($options=array()) {
$ong = array();
$this->addDefaultFormTab($ong);
$this->addStandardTab('NotificationTemplateTranslation', $ong, $options);
$this->addStandardTab('Log', $ong, $options);
return $ong;
}
/**
* Reset already computed templates
**/
function resetComputedTemplates() {
$this->templates_by_languages = array();
}
function showForm($ID, $options=array()) {
global $CFG_GLPI;
if (!Config::canUpdate()) {
return false;
}
$spotted = false;
if (empty($ID)) {
if ($this->getEmpty()) {
$spotted = true;
}
} else {
if ($this->getFromDB($ID)) {
$spotted = true;
}
}
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'><td>" . __('Name') . "</td>";
echo "<td colspan='3'>";
Html::autocompletionTextField($this, "name");
echo "</td></tr>";
echo "<tr class='tab_bg_1'><td>" . __('Type') . "</td><td colspan='3'>";
Dropdown::showItemTypes('itemtype', $CFG_GLPI["notificationtemplates_types"],
array('value' => ($this->fields['itemtype']
?$this->fields['itemtype'] :'Ticket')));
echo "</td></tr>";
echo "<tr class='tab_bg_1'><td>".__('Comments')."</td>";
echo "<td colspan='3'>";
echo "<textarea cols='60' rows='5' name='comment' >".$this->fields["comment"]."</textarea>";
echo "</td></tr>";
echo "<tr class='tab_bg_1'><td>".__('CSS')."</td>";
echo "<td colspan='3'>";
echo "<textarea cols='60' rows='5' name='css' >".$this->fields["css"]."</textarea></td></tr>";
$this->showFormButtons($options);
return true;
}
function getSearchOptions() {
$tab = array();
$tab['common'] = __('Characteristics');
$tab[1]['table'] = $this->getTable();
$tab[1]['field'] = 'name';
$tab[1]['name'] = __('Name');
$tab[1]['datatype'] = 'itemlink';
$tab[1]['massiveaction'] = false;
$tab[4]['table'] = $this->getTable();
$tab[4]['field'] = 'itemtype';
$tab[4]['name'] = __('Type');
$tab[4]['datatype'] = 'itemtypename';
$tab[4]['itemtype_list'] = 'notificationtemplates_types';
$tab[4]['massiveaction'] = false;
$tab[16]['table'] = $this->getTable();
$tab[16]['field'] = 'comment';
$tab[16]['name'] = __('Comments');
$tab[16]['datatype'] = 'text';
return $tab;
}
/**
* Display templates available for an itemtype
*
* @param $name the dropdown name
* @param $itemtype display templates for this itemtype only
* @param $value the dropdown's default value (0 by default)
**/
static function dropdownTemplates($name, $itemtype, $value=0) {
global $DB;
self::dropdown(array('name' => $name,
'value' => $value,
'comment' => 1,
'condition' => "`itemtype`='$itemtype'"));
}
/**
* @param $options
**/
function getAdditionnalProcessOption($options) {
//Additionnal option can be given for template processing
//For the moment, only option to see private tasks & followups is available
if (!empty($options)
&& isset($options['sendprivate'])) {
return 1;
}
return 0;
}
/**
* @param $target NotificationTarget object
* @param $user_infos array
* @param $event
* @param $options array
*
* @return id of the template in templates_by_languages / false if computation failed
**/
function getTemplateByLanguage(NotificationTarget $target, $user_infos=array(), $event,
$options=array()) {
$lang = array();
$language = $user_infos['language'];
if (isset($user_infos['additionnaloption'])) {
$additionnaloption = $user_infos['additionnaloption'];
} else {
$additionnaloption = array();
}
$tid = $language;
$tid .= serialize($additionnaloption);
$tid = sha1($tid);
if (!isset($this->templates_by_languages[$tid])) {
//Switch to the desired language
$bak_dropdowntranslations = $_SESSION['glpi_dropdowntranslations'] ;
$_SESSION['glpi_dropdowntranslations'] = DropdownTranslation::getAvailableTranslations($language);
Session::loadLanguage($language);
$bak_language = $_SESSION["glpilanguage"] ;
$_SESSION["glpilanguage"] = $language ;
//If event is raised by a plugin, load it in order to get the language file available
if ($plug = isPluginItemType(get_class($target->obj))) {
Plugin::loadLang(strtolower($plug['plugin']),$language);
}
//Get template's language data for in this language
$options['additionnaloption'] = $additionnaloption;
$data = &$target->getForTemplate($event,$options);
$footer_string = Html::entity_decode_deep(sprintf(__('Automatically generated by GLPI %s'), GLPI_VERSION));
$add_header = Html::entity_decode_deep($target->getContentHeader());
$add_footer = Html::entity_decode_deep($target->getContentFooter());
//Restore default language
$_SESSION["glpilanguage"] = $bak_language ;
Session::loadLanguage();
$_SESSION['glpi_dropdowntranslations'] = $bak_dropdowntranslations ;
if ($plug = isPluginItemType(get_class($target->obj))) {
Plugin::loadLang(strtolower($plug['plugin']));
}
if ($template_datas = $this->getByLanguage($language)) {
//Template processing
// Decode html chars to have clean text
$template_datas['content_text']
= Html::entity_decode_deep($template_datas['content_text']);
$save_data = $data;
$data = Html::entity_decode_deep($data);
$template_datas['subject'] = Html::entity_decode_deep($template_datas['subject']);
$this->signature = Html::entity_decode_deep($this->signature);
$lang['subject'] = $target->getSubjectPrefix($event) .
self::process($template_datas['subject'], $data);
$lang['content_html'] = '';
//If no html content, then send only in text
if (!empty($template_datas['content_html'])) {
// Encode in HTML all chars
$data_html = Html::entities_deep($data);
$data_html = Html::nl2br_deep($data_html);
// Restore HTML tags
if (count($target->html_tags)) {
foreach ($target->html_tags as $tag) {
if (isset($save_data[$tag])) {
$data_html[$tag] = $save_data[$tag];
}
}
}
$signature_html = Html::entities_deep($this->signature);
$signature_html = Html::nl2br_deep($signature_html);
$template_datas['content_html'] = self::process($template_datas['content_html'],
$data_html);
$lang['content_html'] =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>".
"<html>
<head>
<META http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title>".Html::entities_deep($lang['subject'])."</title>
<style type='text/css'>
".$this->fields['css']."
</style>
</head>
<body>\n".(!empty($add_header)?$add_header."\n<br><br>":'').
$template_datas['content_html'].
"<br><br>-- \n<br>".$signature_html.
//TRANS %s is the GLPI version
"<br>$footer_string".
"<br><br>\n".(!empty($add_footer)?$add_footer."\n<br><br>":'').
"\n</body></html>";
}
$lang['content_text']
= (!empty($add_header)?$add_header."\n\n":''). Html::clean(self::process($template_datas['content_text'],
$data)."\n\n-- \n".$this->signature.
"\n".Html::entity_decode_deep(sprintf(__('Automatically generated by GLPI %s'), GLPI_VERSION)))."\n\n".$add_footer;
$this->templates_by_languages[$tid] = $lang;
}
}
if (isset($this->templates_by_languages[$tid])) {
return $tid;
}
return false;
}
/**
* @param $string
* @param $data
**/
static function process($string, $data) {
$offset = $new_offset = 0;
//Template processed
$output = "";
$cleandata = array();
// clean data for strtr
foreach ($data as $field => $value) {
if (!is_array($value)) {
$cleandata[$field] = $value;
}
}
//Remove all
$string = Toolbox::unclean_cross_side_scripting_deep($string);
//First of all process the FOREACH tag
if (preg_match_all("/##FOREACH[ ]?(FIRST|LAST)?[ ]?([0-9]*)?[ ]?([a-zA-Z-0-9\.]*)##/i",
$string, $out)) {
foreach ($out[3] as $id => $tag_infos) {
$regex = "/".$out[0][$id]."(.*)##ENDFOREACH".$tag_infos."##/Uis";
if (preg_match($regex,$string,$tag_out)
&& isset($data[$tag_infos])
&& is_array($data[$tag_infos])) {
$data_lang_foreach = $cleandata;
unset($data_lang_foreach[$tag_infos]);
//Manage FIRST & LAST statement
$foreachvalues = $data[$tag_infos];
if (!empty($foreachvalues)) {
if (isset($out[1][$id]) && ($out[1][$id] != '')) {
if ($out[1][$id] == 'FIRST') {
$foreachvalues = array_reverse($foreachvalues);
}
if (isset($out[2][$id]) && $out[2][$id]) {
$foreachvalues = array_slice($foreachvalues,0,$out[2][$id]);
} else {
$foreachvalues = array_slice($foreachvalues,0,1);
}
}
}
$output_foreach_string = "";
foreach ($foreachvalues as $line) {
foreach ($line as $field => $value) {
if (!is_array($value)) {
$data_lang_foreach[$field] = $value;
}
}
$tmp = self::processIf($tag_out[1], $data_lang_foreach);
$output_foreach_string .= strtr($tmp, $data_lang_foreach);
}
$string = str_replace($tag_out[0],$output_foreach_string, $string);
} else {
$string = str_replace($tag_out, '', $string);
}
}
}
//Now process IF statements
$string = self::processIf($string, $cleandata);
$string = strtr($string, $cleandata);
return $string;
}
/**
* @param $string
* @param $data
**/
static function processIf($string, $data) {
if (preg_match_all("/##IF([a-z\.]*)[=]?(.*?)##/i",$string,$out)) {
foreach ($out[1] as $key => $tag_infos) {
$if_field = $tag_infos;
//Get the field tag value (if one)
$regex_if = "/##IF".$if_field."[=]?.*##(.*)##ENDIF".$if_field."##/Uis";
//Get the else tag value (if one)
$regex_else = "/##ELSE".$if_field."[=]?.*##(.*)##ENDELSE".$if_field."##/Uis";
if (empty($out[2][$key]) && !strlen($out[2][$key]) ) { // No = : check if ot empty or not null
if (isset($data['##'.$if_field.'##'])
&& $data['##'.$if_field.'##'] != '0'
&& $data['##'.$if_field.'##'] != ''
&& $data['##'.$if_field.'##'] != ' '
&& !is_null($data['##'.$if_field.'##'])) {
$condition_ok = true;
} else {
$condition_ok = false;
}
} else { // check exact match
if (isset($data['##'.$if_field.'##'])
&& (Html::entity_decode_deep($data['##'.$if_field.'##'])
== Html::entity_decode_deep($out[2][$key]))) {
$condition_ok = true;
} else {
$condition_ok = false;
}
}
// Force only one replacement to permit multiple use of the same condition
if ($condition_ok) { // Do IF
$string = preg_replace($regex_if, "\\1", $string,1);
$string = preg_replace($regex_else, "", $string,1);
} else { // Do ELSE
$string = preg_replace($regex_if, "", $string,1);
$string = preg_replace($regex_else, "\\1", $string,1);
}
}
}
return $string;
}
/**
* @param $signature
**/
function setSignature($signature) {
$this->signature = $signature;
}
/**
* @param $language
**/
function getByLanguage($language) {
global $DB;
$query = "SELECT *
FROM `glpi_notificationtemplatetranslations`
WHERE `notificationtemplates_id` = '".$this->getField('id')."'
AND `language` IN ('$language','')
ORDER BY `language` DESC
LIMIT 1";
$iterator = $DB->request($query);
if ($iterator->numrows()) {
return $iterator->next();
}
//No template found at all!
return false;
}
/**
* @param $target NotificationTarget object
* @param $tid string template computed id
* @param $user_infos array
* @param $options array
**/
function getDataToSend(NotificationTarget $target, $tid, array $user_infos, array $options) {
$language = $user_infos['language'];
$user_email = $user_infos['email'];
$user_name = $user_infos['username'];
$sender = $target->getSender($options);
$replyto = $target->getReplyTo($options);
$mailing_options['to'] = $user_email;
$mailing_options['toname'] = $user_name;
$mailing_options['from'] = $sender['email'];
$mailing_options['fromname'] = $sender['name'];
$mailing_options['replyto'] = $replyto['email'];
$mailing_options['replytoname'] = $replyto['name'];
$mailing_options['messageid'] = $target->getMessageID();
$template_data = $this->templates_by_languages[$tid];
$mailing_options['subject'] = $template_data['subject'];
$mailing_options['content_html'] = $template_data['content_html'];
$mailing_options['content_text'] = $template_data['content_text'];
$mailing_options['items_id'] = $target->obj->getField('id');
if (isset($target->obj->documents)) {
$mailing_options['documents'] = $target->obj->documents;
}
return $mailing_options;
}
}
?>
| songjio/j_asset_glpi_kr | inc/notificationtemplate.class.php | PHP | gpl-2.0 | 17,678 |
package org.anddev.andengine.entity.layer.tiled.tmx;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.collision.RectangularShapeCollisionChecker;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader.ITMXTilePropertiesListener;
import org.anddev.andengine.entity.layer.tiled.tmx.util.constants.TMXConstants;
import org.anddev.andengine.entity.shape.RectangularShape;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.util.Base64;
import org.anddev.andengine.util.Base64InputStream;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.SAXUtils;
import org.anddev.andengine.util.StreamUtils;
import org.xml.sax.Attributes;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:27:31 - 20.07.2010
*/
public class TMXLayer extends RectangularShape implements TMXConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final TMXTiledMap mTMXTiledMap;
private final String mName;
private final int mTileColumns;
private final int mTileRows;
private final TMXTile[][] mTMXTiles;
private int mTilesAdded;
private final int mGlobalTileIDsExpected;
private final float[] mCullingVertices = new float[2 * 4];
private final TMXProperties<TMXLayerProperty> mTMXLayerProperties = new TMXProperties<TMXLayerProperty>();
// ===========================================================
// Constructors
// ===========================================================
public TMXLayer(final TMXTiledMap pTMXTiledMap, final Attributes pAttributes) {
super(0, 0, 0, 0, null);
this.mTMXTiledMap = pTMXTiledMap;
this.mName = pAttributes.getValue("", TAG_LAYER_ATTRIBUTE_NAME);
this.mTileColumns = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_LAYER_ATTRIBUTE_WIDTH);
this.mTileRows = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_LAYER_ATTRIBUTE_HEIGHT);
this.mTMXTiles = new TMXTile[this.mTileRows][this.mTileColumns];
super.mWidth = pTMXTiledMap.getTileWidth() * this.mTileColumns;
final float width = super.mWidth;
super.mBaseWidth = width;
super.mHeight = pTMXTiledMap.getTileHeight() * this.mTileRows;
final float height = super.mHeight;
super.mBaseHeight = height;
this.mRotationCenterX = width * 0.5f;
this.mRotationCenterY = height * 0.5f;
this.mScaleCenterX = this.mRotationCenterX;
this.mScaleCenterY = this.mRotationCenterY;
this.mGlobalTileIDsExpected = this.mTileColumns * this.mTileRows;
this.setVisible(SAXUtils.getIntAttribute(pAttributes, TAG_LAYER_ATTRIBUTE_VISIBLE, TAG_LAYER_ATTRIBUTE_VISIBLE_VALUE_DEFAULT) == 1);
this.setAlpha(SAXUtils.getFloatAttribute(pAttributes, TAG_LAYER_ATTRIBUTE_OPACITY, TAG_LAYER_ATTRIBUTE_OPACITY_VALUE_DEFAULT));
}
// ===========================================================
// Getter & Setter
// ===========================================================
public String getName() {
return this.mName;
}
public int getTileColumns() {
return this.mTileColumns;
}
public int getTileRows() {
return this.mTileRows;
}
public TMXTile[][] getTMXTiles() {
return this.mTMXTiles;
}
public TMXTile getTMXTile(final int pTileColumn, final int pTileRow) throws ArrayIndexOutOfBoundsException {
return this.mTMXTiles[pTileRow][pTileColumn];
}
/**
* @param pX in SceneCoordinates.
* @param pY in SceneCoordinates.
* @return the {@link TMXTile} located at <code>pX/pY</code>.
*/
public TMXTile getTMXTileAt(final float pX, final float pY) {
final float[] localCoords = this.convertSceneToLocalCoordinates(pX, pY);
final TMXTiledMap tmxTiledMap = this.mTMXTiledMap;
final int tileColumn = (int)(localCoords[VERTEX_INDEX_X] / tmxTiledMap.getTileWidth());
if(tileColumn < 0 || tileColumn > this.mTileColumns - 1) {
return null;
}
final int tileRow = (int)(localCoords[VERTEX_INDEX_Y] / tmxTiledMap.getTileWidth());
if(tileRow < 0 || tileRow > this.mTileRows - 1) {
return null;
}
return this.mTMXTiles[tileRow][tileColumn];
}
public void addTMXLayerProperty(final TMXLayerProperty pTMXLayerProperty) {
this.mTMXLayerProperties.add(pTMXLayerProperty);
}
public TMXProperties<TMXLayerProperty> getTMXLayerProperties() {
return this.mTMXLayerProperties;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
@Deprecated
public void setRotation(final float pRotation) {
}
@Override
protected void onUpdateVertexBuffer() {
/* Nothing. */
}
@Override
protected void onInitDraw(final GL10 pGL) {
super.onInitDraw(pGL);
GLHelper.enableTextures(pGL);
GLHelper.enableTexCoordArray(pGL);
}
@Override
protected void onApplyVertices(final GL10 pGL) {
if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) {
final GL11 gl11 = (GL11)pGL;
this.mTMXTiledMap.getSharedVertexBuffer().selectOnHardware(gl11);
GLHelper.vertexZeroPointer(gl11);
} else {
GLHelper.vertexPointer(pGL, this.mTMXTiledMap.getSharedVertexBuffer().getFloatBuffer());
}
}
@Override
protected void drawVertices(final GL10 pGL, final Camera pCamera) {
final TMXTile[][] tmxTiles = this.mTMXTiles;
final int tileColumns = this.mTileColumns;
final int tileRows = this.mTileRows;
final int tileWidth = this.mTMXTiledMap.getTileWidth();
final int tileHeight = this.mTMXTiledMap.getTileHeight();
final float scaledTileWidth = tileWidth * this.mScaleX;
final float scaledTileHeight = tileHeight * this.mScaleY;
final float[] cullingVertices = this.mCullingVertices;
RectangularShapeCollisionChecker.fillVertices(this, cullingVertices);
final float layerMinX = cullingVertices[VERTEX_INDEX_X];
final float layerMinY = cullingVertices[VERTEX_INDEX_Y];
final float cameraMinX = pCamera.getMinX();
final float cameraMinY = pCamera.getMinY();
final float cameraWidth = pCamera.getWidth();
final float cameraHeight = pCamera.getHeight();
/* Determine the area that is visible in the camera. */
final float firstColumnRaw = (cameraMinX - layerMinX) / scaledTileWidth;
final int firstColumn = MathUtils.bringToBounds(0, tileColumns - 1, (int)Math.floor(firstColumnRaw));
final int lastColumn = MathUtils.bringToBounds(0, tileColumns - 1, (int)Math.ceil(firstColumnRaw + cameraWidth / scaledTileWidth));
final float firstRowRaw = (cameraMinY - layerMinY) / scaledTileHeight;
final int firstRow = MathUtils.bringToBounds(0, tileRows - 1, (int)Math.floor(firstRowRaw));
final int lastRow = MathUtils.bringToBounds(0, tileRows - 1, (int)Math.floor(firstRowRaw + cameraHeight / scaledTileHeight));
final int visibleTilesTotalWidth = (lastColumn - firstColumn + 1) * tileWidth;
pGL.glTranslatef(firstColumn * tileWidth, firstRow * tileHeight, 0);
for(int row = firstRow; row <= lastRow; row++) {
final TMXTile[] tmxTileRow = tmxTiles[row];
for(int column = firstColumn; column <= lastColumn; column++) {
final TextureRegion textureRegion = tmxTileRow[column].mTextureRegion;
if(textureRegion != null) {
textureRegion.onApply(pGL);
pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
pGL.glTranslatef(tileWidth, 0, 0);
}
/* Translate one row downwards and the back left to the first column.
* Just like the 'Carriage Return' + 'New Line' (\r\n) on a typewriter. */
pGL.glTranslatef(-visibleTilesTotalWidth, tileHeight, 0);
}
pGL.glLoadIdentity();
}
@Override
protected void onManagedUpdate(final float pSecondsElapsed) {
/* Nothing. */
}
// ===========================================================
// Methods
// ===========================================================
void initializeTMXTileFromXML(final Attributes pAttributes, final ITMXTilePropertiesListener pTMXTilePropertyListener) {
this.addTileByGlobalTileID(SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_TILE_ATTRIBUTE_GID), pTMXTilePropertyListener);
}
void initializeTMXTilesFromDataString(final String pDataString, final String pDataEncoding, final String pDataCompression, final ITMXTilePropertiesListener pTMXTilePropertyListener) throws IOException, IllegalArgumentException {
DataInputStream dataIn = null;
try{
InputStream in = new ByteArrayInputStream(pDataString.getBytes("UTF-8"));
/* Wrap decoding Streams if necessary. */
if(pDataEncoding != null && pDataEncoding.equals(TAG_DATA_ATTRIBUTE_ENCODING_VALUE_BASE64)) {
in = new Base64InputStream(in, Base64.DEFAULT);
}
if(pDataCompression != null){
if(pDataCompression.equals(TAG_DATA_ATTRIBUTE_COMPRESSION_VALUE_GZIP)) {
in = new GZIPInputStream(in);
} else {
throw new IllegalArgumentException("Supplied compression '" + pDataCompression + "' is not supported yet.");
}
}
dataIn = new DataInputStream(in);
while(this.mTilesAdded < this.mGlobalTileIDsExpected) {
final int globalTileID = this.readGlobalTileID(dataIn);
this.addTileByGlobalTileID(globalTileID, pTMXTilePropertyListener);
}
} finally {
StreamUtils.close(dataIn);
}
}
private void addTileByGlobalTileID(final int pGlobalTileID, final ITMXTilePropertiesListener pTMXTilePropertyListener) {
final TMXTiledMap tmxTiledMap = this.mTMXTiledMap;
final int tilesHorizontal = this.mTileColumns;
final int column = this.mTilesAdded % tilesHorizontal;
final int row = this.mTilesAdded / tilesHorizontal;
final TMXTile[][] tmxTiles = this.mTMXTiles;
final TextureRegion tmxTileTextureRegion;
if(pGlobalTileID == 0) {
tmxTileTextureRegion = null;
} else {
tmxTileTextureRegion = tmxTiledMap.getTextureRegionFromGlobalTileID(pGlobalTileID);
}
final TMXTile tmxTile = new TMXTile(pGlobalTileID, column, row, this.mTMXTiledMap.getTileWidth(), this.mTMXTiledMap.getTileHeight(), tmxTileTextureRegion);
tmxTiles[row][column] = tmxTile;
if(pGlobalTileID != 0) {
/* Notify the ITMXTilePropertiesListener if it exists. */
if(pTMXTilePropertyListener != null) {
final TMXProperties<TMXTileProperty> tmxTileProperties = tmxTiledMap.getTMXTileProperties(pGlobalTileID);
if(tmxTileProperties != null) {
pTMXTilePropertyListener.onTMXTileWithPropertiesCreated(tmxTiledMap, this, tmxTile, tmxTileProperties);
}
}
}
this.mTilesAdded++;
}
private int readGlobalTileID(final DataInputStream pDataIn) throws IOException {
final int lowestByte = pDataIn.read();
final int secondLowestByte = pDataIn.read();
final int secondHighestByte = pDataIn.read();
final int highestByte = pDataIn.read();
if(lowestByte < 0 || secondLowestByte < 0 || secondHighestByte < 0 || highestByte < 0) {
throw new IllegalArgumentException("Couldn't read global Tile ID.");
}
return lowestByte | secondLowestByte << 8 |secondHighestByte << 16 | highestByte << 24;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| ricardobaumann/android | worldofgravity-master/src/org/anddev/andengine/entity/layer/tiled/tmx/TMXLayer.java | Java | gpl-2.0 | 11,687 |
/*
Copyright (C) 2003 - 2017 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
#include "replay_helper.hpp"
#include <string>
#include <cassert>
#include "map/location.hpp"
#include "time_of_day.hpp"
#include "resources.hpp"
#include "play_controller.hpp"
config replay_helper::get_recruit(const std::string& type_id, const map_location& loc, const map_location& from)
{
config val;
val["type"] = type_id;
loc.write(val);
config& leader_position = val.add_child("from");
from.write(leader_position);
return val;
}
config replay_helper::get_recall(const std::string& unit_id, const map_location& loc, const map_location& from)
{
config val;
val["value"] = unit_id;
loc.write(val);
config& leader_position = val.add_child("from");
from.write(leader_position);
return val;
}
config replay_helper::get_disband(const std::string& unit_id)
{
config val;
val["value"] = unit_id;
return val;
}
/**
* Records a move that follows the provided @a steps.
* This should be the steps to be taken this turn, ending in an
* apparently-unoccupied (from the moving team's perspective) hex.
*/
config replay_helper::get_movement(const std::vector<map_location>& steps, bool skip_sighted, bool skip_ally_sighted)
{
assert(!steps.empty());
config move;
if(skip_sighted)
{
//note, that skip_ally_sighted has no effect if skip_sighted is true
move["skip_sighted"] = "all";
}
else if(skip_ally_sighted && !skip_sighted)
{
move["skip_sighted"] = "only_ally";
}
else
{
//leave it empty
}
write_locations(steps, move);
return move;
}
config replay_helper::get_attack(const map_location& a, const map_location& b,
int att_weapon, int def_weapon, const std::string& attacker_type_id,
const std::string& defender_type_id, int attacker_lvl,
int defender_lvl, const size_t turn, const time_of_day &t)
{
config move, src, dst;
a.write(src);
b.write(dst);
move.add_child("source",src);
move.add_child("destination",dst);
move["weapon"] = att_weapon;
move["defender_weapon"] = def_weapon;
move["attacker_type"] = attacker_type_id;
move["defender_type"] = defender_type_id;
move["attacker_lvl"] = attacker_lvl;
move["defender_lvl"] = defender_lvl;
move["turn"] = int(turn);
move["tod"] = t.id;
/*
add_unit_checksum(a,current_);
add_unit_checksum(b,current_);
*/
return move;
}
/**
* Records that the player has toggled automatic shroud updates.
*/
config replay_helper::get_auto_shroud(bool turned_on)
{
config child;
child["active"] = turned_on;
return child;
}
/**
* Records that the player has manually updated fog/shroud.
*/
config replay_helper::get_update_shroud()
{
return config();
}
config replay_helper::get_init_side()
{
config init_side;
init_side["side_number"] = resources::controller->current_side();
return init_side;
}
config replay_helper::get_event(const std::string& name, const map_location& loc, const map_location* last_select_loc)
{
config ev;
ev["raise"] = name;
if(loc.valid()) {
config& source = ev.add_child("source");
loc.write(source);
}
if(last_select_loc != nullptr && last_select_loc->valid())
{
config& source = ev.add_child("last_select");
last_select_loc->write(source);
}
return ev;
}
config replay_helper::get_lua_ai(const std::string& lua_code)
{
config child;
child["code"] = lua_code;
return child;
}
| ln-zookeeper/wesnoth | src/replay_helper.cpp | C++ | gpl-2.0 | 3,775 |
/*
* Copyright 2004-2006 Adrian Thurston <thurston@complang.org>
* 2004 Erich Ocean <eric.ocean@ampede.com>
* 2005 Alan West <alan@alanz.com>
*/
/* This file is part of Ragel.
*
* Ragel 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.
*
* Ragel 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 Ragel; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ragel.h"
#include "fflat.h"
#include "redfsm.h"
#include "gendata.h"
using std::endl;
namespace Go {
std::ostream &GoFFlatCodeGen::TO_STATE_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->toStateAction != 0 )
act = state->toStateAction->actListId+1;
out << act;
return out;
}
std::ostream &GoFFlatCodeGen::FROM_STATE_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->fromStateAction != 0 )
act = state->fromStateAction->actListId+1;
out << act;
return out;
}
std::ostream &GoFFlatCodeGen::EOF_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->eofAction != 0 )
act = state->eofAction->actListId+1;
out << act;
return out;
}
/* Write out the function for a transition. */
std::ostream &GoFFlatCodeGen::TRANS_ACTION( RedTransAp *trans )
{
int action = 0;
if ( trans->action != 0 )
action = trans->action->actListId+1;
out << action;
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::TO_STATE_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numToStateRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::FROM_STATE_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numFromStateRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
std::ostream &GoFFlatCodeGen::EOF_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numEofRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, true, false );
}
}
genLineDirective( out );
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numTransRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
void GoFFlatCodeGen::writeData()
{
if ( redFsm->anyConditions() ) {
OPEN_ARRAY( WIDE_ALPH_TYPE(), CK() );
COND_KEYS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondSpan), CSP() );
COND_KEY_SPANS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCond), C() );
CONDS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondIndexOffset), CO() );
COND_INDEX_OFFSET();
CLOSE_ARRAY() <<
endl;
}
OPEN_ARRAY( WIDE_ALPH_TYPE(), K() );
KEYS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxSpan), SP() );
KEY_SPANS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxFlatIndexOffset), IO() );
FLAT_INDEX_OFFSET();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndex), I() );
INDICIES();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxState), TT() );
TRANS_TARGS();
CLOSE_ARRAY() <<
endl;
if ( redFsm->anyActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActListId), TA() );
TRANS_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyToStateActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), TSA() );
TO_STATE_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyFromStateActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), FSA() );
FROM_STATE_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyEofActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActListId), EA() );
EOF_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyEofTrans() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndexOffset+1), ET() );
EOF_TRANS();
CLOSE_ARRAY() <<
endl;
}
STATE_IDS();
}
void GoFFlatCodeGen::writeExec()
{
testEofUsed = false;
outLabelUsed = false;
out <<
" {" << endl <<
" var _slen " << INT() << endl;
if ( redFsm->anyRegCurStateRef() )
out << " var _ps " << INT() << endl;
out << " var _trans " << INT() << endl;
if ( redFsm->anyConditions() )
out << " var _cond " << INT() << endl;
out <<
" var _keys " << INT() << endl <<
" var _inds " << INT() << endl;
if ( redFsm->anyConditions() ) {
out <<
" var _conds " << INT() << endl <<
" var _widec " << WIDE_ALPH_TYPE() << endl;
}
if ( !noEnd ) {
testEofUsed = true;
out <<
" if " << P() << " == " << PE() << " {" << endl <<
" goto _test_eof" << endl <<
" }" << endl;
}
if ( redFsm->errState != 0 ) {
outLabelUsed = true;
out <<
" if " << vCS() << " == " << redFsm->errState->id << " {" << endl <<
" goto _out" << endl <<
" }" << endl;
}
out << "_resume:" << endl;
if ( redFsm->anyFromStateActions() ) {
out <<
" switch " << FSA() << "[" << vCS() << "] {" << endl;
FROM_STATE_ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->anyConditions() )
COND_TRANSLATE();
LOCATE_TRANS();
if ( redFsm->anyEofTrans() )
out << "_eof_trans:" << endl;
if ( redFsm->anyRegCurStateRef() )
out << " _ps = " << vCS() << endl;
out <<
" " << vCS() << " = " << CAST(INT(), TT() + "[_trans]") << endl <<
endl;
if ( redFsm->anyRegActions() ) {
out <<
" if " << TA() << "[_trans] == 0 {" << endl <<
" goto _again" << endl <<
" }" << endl <<
endl <<
" switch " << TA() << "[_trans] {" << endl;
ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->anyRegActions() || redFsm->anyActionGotos() ||
redFsm->anyActionCalls() || redFsm->anyActionRets() )
out << "_again:" << endl;
if ( redFsm->anyToStateActions() ) {
out <<
" switch " << TSA() << "[" << vCS() << "] {" << endl;
TO_STATE_ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->errState != 0 ) {
outLabelUsed = true;
out <<
" if " << vCS() << " == " << redFsm->errState->id << " {" << endl <<
" goto _out" << endl <<
" }" << endl;
}
if ( !noEnd ) {
out <<
" if " << P() << "++; " << P() << " != " << PE() << " {"
" goto _resume" << endl <<
" }" << endl;
}
else {
out <<
" " << P() << "++" << endl <<
" goto _resume" << endl;
}
if ( testEofUsed )
out << " _test_eof: {}" << endl;
if ( redFsm->anyEofTrans() || redFsm->anyEofActions() ) {
out <<
" if " << P() << " == " << vEOF() << " {" << endl;
if ( redFsm->anyEofTrans() ) {
out <<
" if " << ET() << "[" << vCS() << "] > 0 {" << endl <<
" _trans = " << CAST(INT(), ET() + "[" + vCS() + "] - 1") << endl <<
" goto _eof_trans" << endl <<
" }" << endl;
}
if ( redFsm->anyEofActions() ) {
out <<
" switch " << EA() << "[" << vCS() << "] {" << endl;
EOF_ACTION_SWITCH(2);
out <<
" }" << endl;
}
out <<
" }" << endl <<
endl;
}
if ( outLabelUsed )
out << " _out: {}" << endl;
out << " }" << endl;
}
}
| kennytm/ragel | src/go/fflat.cc | C++ | gpl-2.0 | 9,175 |
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2017 RomRaider.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.
*/
package com.romraider.swing;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DecimalFormat;
import javax.swing.JFormattedTextField;
import com.romraider.util.NumberUtil;
public class ECUEditorNumberField extends JFormattedTextField {
private static final long serialVersionUID = 4756399956045598977L;
static DecimalFormat format = new DecimalFormat("#.####");
public ECUEditorNumberField(){
super(format);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(4);
this.addKeyListener(new KeyListener(){
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
//Get separator for the defined locale
char seperator = NumberUtil.getSeperator();
//Replace , with . or vice versa
if ((c == ',' || c == '.') && seperator != c)
e.setKeyChar(seperator);
ECUEditorNumberField field = ECUEditorNumberField.this;
String textValue = field.getText();
int dotCount = textValue.length() - textValue.replace(seperator + "", "").length();
//Only allow one dot
if(e.getKeyChar() == seperator && (dotCount == 0 || field.getSelectionStart() == 0)) return;
//Only one dash allowed at the start
else if(e.getKeyChar()== '-' && (field.getCaretPosition() == 0 || field.getSelectionStart() == 0)) return;
//Only allow numbers
else if(c >= '0' && c <= '9') return;
//Don't allow if input doesn't meet these rules
else e.consume();
}
@Override
public void keyPressed(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent arg0) {
}
});
}
}
| dschultzca/RomRaider | src/main/java/com/romraider/swing/ECUEditorNumberField.java | Java | gpl-2.0 | 2,595 |
#
# Copyright 2016 Red Hat, Inc.
#
# 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
#
# Refer to the README and COPYING files for full details of the license
#
from __future__ import absolute_import
import logging
import time
import six
from vdsm.storage import constants as sc
from vdsm.storage import exception
# SIZE property was deprecated in metadata v5, but we still need this key to
# read and write legacy metadata. To make sure no other code use it and it's
# used only by metadata code, move it here and make it private.
_SIZE = "SIZE"
ATTRIBUTES = {
sc.DOMAIN: ("domain", str),
sc.IMAGE: ("image", str),
sc.PUUID: ("parent", str),
sc.CAPACITY: ("capacity", int),
sc.FORMAT: ("format", str),
sc.TYPE: ("type", str),
sc.VOLTYPE: ("voltype", str),
sc.DISKTYPE: ("disktype", str),
sc.DESCRIPTION: ("description", str),
sc.LEGALITY: ("legality", str),
sc.CTIME: ("ctime", int),
sc.GENERATION: ("generation", int),
sc.SEQUENCE: ("sequence", int),
}
def _lines_to_dict(lines):
md = {}
errors = []
for line in lines:
# Skip a line if there is invalid value.
try:
line = line.decode("utf-8")
except UnicodeDecodeError as e:
errors.append("Invalid line '{}': {}".format(line, e))
continue
if line.startswith("EOF"):
break
if '=' not in line:
continue
key, value = line.split('=', 1)
md[key.strip()] = value.strip()
return md, errors
def parse(lines):
md, errors = _lines_to_dict(lines)
metadata = {}
if "NONE" in md:
# Before 4.20.34-1 (ovirt 4.2.5) volume metadata could be
# cleared by writing invalid metadata when deleting a volume.
# See https://bugzilla.redhat.com/1574631.
errors.append(str(exception.MetadataCleared()))
return {}, errors
# We work internally in bytes, even if old format store
# value in blocks, we will read SIZE instead of CAPACITY
# from non-converted volumes and use it
if _SIZE in md and sc.CAPACITY not in md:
try:
md[sc.CAPACITY] = int(md[_SIZE]) * sc.BLOCK_SIZE_512
except ValueError as e:
errors.append(str(e))
if sc.GENERATION not in md:
md[sc.GENERATION] = sc.DEFAULT_GENERATION
if sc.SEQUENCE not in md:
md[sc.SEQUENCE] = sc.DEFAULT_SEQUENCE
for key, (name, validate) in ATTRIBUTES.items():
try:
# FIXME: remove pylint skip when bug fixed:
# https://github.com/PyCQA/pylint/issues/5113
metadata[name] = validate(md[key]) # pylint: disable=not-callable
except KeyError:
errors.append("Required key '{}' is missing.".format(name))
except ValueError as e:
errors.append("Invalid '{}' value: {}".format(name, str(e)))
return metadata, errors
def dump(lines):
md, errors = parse(lines)
if errors:
logging.warning(
"Invalid metadata found errors=%s", errors)
md["status"] = sc.VOL_STATUS_INVALID
else:
md["status"] = sc.VOL_STATUS_OK
# Do not include domain in dump output.
md.pop("domain", None)
return md
class VolumeMetadata(object):
log = logging.getLogger('storage.volumemetadata')
def __init__(self, domain, image, parent, capacity, format, type, voltype,
disktype, description="", legality=sc.ILLEGAL_VOL, ctime=None,
generation=sc.DEFAULT_GENERATION,
sequence=sc.DEFAULT_SEQUENCE):
# Storage domain UUID
self.domain = domain
# Image UUID
self.image = image
# UUID of the parent volume or BLANK_UUID
self.parent = parent
# Volume capacity in bytes
self.capacity = capacity
# Format (RAW or COW)
self.format = format
# Allocation policy (PREALLOCATED or SPARSE)
self.type = type
# Relationship to other volumes (LEAF, INTERNAL or SHARED)
self.voltype = voltype
# Intended usage of this volume (unused)
self.disktype = disktype
# Free-form description and may be used to store extra metadata
self.description = description
# Indicates if the volume contents should be considered valid
self.legality = legality
# Volume creation time (in seconds since the epoch)
self.ctime = int(time.time()) if ctime is None else ctime
# Generation increments each time certain operations complete
self.generation = generation
# Sequence number of the volume, increased every time a new volume is
# created in an image.
self.sequence = sequence
@classmethod
def from_lines(cls, lines):
'''
Instantiates a VolumeMetadata object from storage read bytes.
Args:
lines: list of key=value entries given as bytes read from storage
metadata section. "EOF" entry terminates parsing.
'''
metadata, errors = parse(lines)
if errors:
raise exception.InvalidMetadata(
"lines={} errors={}".format(lines, errors))
return cls(**metadata)
@property
def description(self):
return self._description
@description.setter
def description(self, desc):
self._description = self.validate_description(desc)
@property
def capacity(self):
return self._capacity
@capacity.setter
def capacity(self, value):
self._capacity = self._validate_integer("capacity", value)
@property
def ctime(self):
return self._ctime
@ctime.setter
def ctime(self, value):
self._ctime = self._validate_integer("ctime", value)
@property
def generation(self):
return self._generation
@generation.setter
def generation(self, value):
self._generation = self._validate_integer("generation", value)
@property
def sequence(self):
return self._sequence
@sequence.setter
def sequence(self, value):
self._sequence = self._validate_integer("sequence", value)
@classmethod
def _validate_integer(cls, property, value):
if not isinstance(value, six.integer_types):
raise AssertionError(
"Invalid value for metadata property {!r}: {!r}".format(
property, value))
return value
@classmethod
def validate_description(cls, desc):
desc = str(desc)
# We cannot fail when the description is too long, since we must
# support older engine that may send such values, or old disks
# with long description.
if len(desc) > sc.DESCRIPTION_SIZE:
cls.log.warning("Description is too long, truncating to %d bytes",
sc.DESCRIPTION_SIZE)
desc = desc[:sc.DESCRIPTION_SIZE]
return desc
def storage_format(self, domain_version, **overrides):
"""
Format metadata parameters into storage format bytes.
VolumeMetadata is quite restrictive and does not allow
you to make an invalid metadata, but sometimes, for example
for a format conversion, you need some additional fields to
be written to the storage. Those fields can be added using
overrides dict.
Raises MetadataOverflowError if formatted metadata is too long.
"""
info = {
sc.CTIME: str(self.ctime),
sc.DESCRIPTION: self.description,
sc.DISKTYPE: self.disktype,
sc.DOMAIN: self.domain,
sc.FORMAT: self.format,
sc.GENERATION: self.generation,
sc.IMAGE: self.image,
sc.LEGALITY: self.legality,
sc.PUUID: self.parent,
sc.TYPE: self.type,
sc.VOLTYPE: self.voltype,
}
if domain_version < 5:
# Always zero on pre v5 domains
# We need to keep MTIME available on pre v5
# domains, as other code is expecting that
# field to exists and will fail without it.
info[sc.MTIME] = 0
# Pre v5 domains should have SIZE in blocks
# instead of CAPACITY in bytes
info[_SIZE] = self.capacity // sc.BLOCK_SIZE_512
else:
info[sc.CAPACITY] = self.capacity
info[sc.SEQUENCE] = self.sequence
info.update(overrides)
keys = sorted(info.keys())
lines = ["%s=%s\n" % (key, info[key]) for key in keys]
lines.append("EOF\n")
data = "".join(lines).encode("utf-8")
if len(data) > sc.METADATA_SIZE:
raise exception.MetadataOverflowError(data)
return data
# Three defs below allow us to imitate a dictionary
# So intstead of providing a method to return a dictionary
# with values, we return self and mimick dict behaviour.
# In the fieldmap we keep mapping between metadata
# field name and our internal field names
#
# TODO: All dict specific code below should be removed, when rest of VDSM
# will be refactored, to use VolumeMetadata properties, instead of dict
_fieldmap = {
sc.FORMAT: 'format',
sc.TYPE: 'type',
sc.VOLTYPE: 'voltype',
sc.DISKTYPE: 'disktype',
sc.CAPACITY: 'capacity',
sc.CTIME: 'ctime',
sc.DOMAIN: 'domain',
sc.IMAGE: 'image',
sc.DESCRIPTION: 'description',
sc.PUUID: 'parent',
sc.LEGALITY: 'legality',
sc.GENERATION: 'generation',
sc.SEQUENCE: "sequence",
}
def __getitem__(self, item):
try:
value = getattr(self, self._fieldmap[item])
except AttributeError:
raise KeyError(item)
# Some fields needs to be converted to string
if item in (sc.CAPACITY, sc.CTIME):
value = str(value)
return value
def __setitem__(self, item, value):
setattr(self, self._fieldmap[item], value)
def get(self, item, default=None):
try:
return self[item]
except KeyError:
return default
def dump(self):
return {
"capacity": self.capacity,
"ctime": self.ctime,
"description": self.description,
"disktype": self.disktype,
"format": self.format,
"generation": self.generation,
"sequence": self.sequence,
"image": self.image,
"legality": self.legality,
"parent": self.parent,
"type": self.type,
"voltype": self.voltype,
}
| oVirt/vdsm | lib/vdsm/storage/volumemetadata.py | Python | gpl-2.0 | 11,350 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization;
namespace IronCow.Rest
{
[DataContract]
public class RawGroup : RawRtmElement
{
[XmlAttribute("name")]
[DataMember]
public string Name { get; set; }
[XmlArray("contacts")]
[XmlArrayItem("contact")]
[DataMember]
public RawContact[] Contacts { get; set; }
}
}
| mbmccormick/Milkman | IronCow/Rest/RawGroup.cs | C# | gpl-2.0 | 489 |
# Allows the creation of infix operators
# Thanks to Ferdinand Jamitzky
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
class Infix(object):
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x: self.function(other, x))
def __or__(self, other):
return self.function(other)
def __rlshift__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __rshift__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
# To create a binary operator just make a function that takes 2 arguments like say
# def my_add (a, b):
# return a + b
#
# Then we get import this...
# from Infix import Infix # Lets us make binary infix style operators
#
# Then we make the operator, lets call it p...
# p = Infix(my_add)
#
# Now to use it just put in
# arg1 |p| arg2
| Kevin-Ray-Johnson/DM_Desk_Calc | Infix.py | Python | gpl-2.0 | 976 |
<?php
/* Place any functions you create here. Note that this is not meant for module functions, which should be placed in the module's php file. */
?> | tslocum/kusaba-releases | inc/func/custom.php | PHP | gpl-2.0 | 155 |
<?php
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package duena
*/
get_header(); ?>
<div id="primary" class="col-md-8 <?php echo esc_attr( of_get_option('blog_sidebar_pos') ) ?>">
<div id="content" class="site-content" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<div class="page_wrap">
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php the_content(); ?>
</div>
<?php
// If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() )
comments_template();
?>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| giaule56/jerry.lee.blog | wp-content/themes/duena/page.php | PHP | gpl-2.0 | 977 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage Yahoo
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Yahoo.php 17687 2009-08-20 12:55:34Z thomas $
*/
/**
* @category Zend
* @package Zend_Service
* @subpackage Yahoo
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_Yahoo
{
/**
* Yahoo Developer Application ID
*
* @var string
*/
public $appId;
/**
* Reference to the REST client
*
* @var Zend_Rest_Client
*/
protected $_rest;
/**
* Sets the application ID and instantiates the REST client
*
* @param string $appId specified the developer's appid
* @return void
*/
public function __construct($appId)
{
$this->appId = (string) $appId;
/**
* @see Zend_Rest_Client
*/
require_once 'Zend/Rest/Client.php';
$this->_rest = new Zend_Rest_Client('http://search.yahooapis.com');
}
/**
* Retrieve Inlink Data from siteexplorer.yahoo.com. A basic query
* consists simply of a URL. Additional options that can be
* specified consist of:
* 'results' => int How many results to return, max is 100
* 'start' => int The start offset for search results
* 'entire_site' => bool Data for the whole site or a single page
* 'omit_inlinks' => (none|domain|subdomain) Filter inlinks from these sources
*
* @param string $query the query being run
* @param array $options any optional parameters
* @return Zend_Service_Yahoo_ResultSet The return set
* @throws Zend_Service_Exception
*/
public function inlinkDataSearch($query, array $options = array())
{
static $defaultOptions = array('results' => '50',
'start' => 1);
$options = $this->_prepareOptions($query, $options, $defaultOptions);
$this->_validateInlinkDataSearch($options);
$this->_rest->getHttpClient()->resetParameters();
$this->_rest->setUri('http://search.yahooapis.com');
$response = $this->_rest->restGet('/SiteExplorerService/V1/inlinkData', $options);
if ($response->isError()) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
$response->getStatus());
}
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
self::_checkErrors($dom);
/**
* @see Zend_Service_Yahoo_InlinkDataResultSet
*/
require_once 'Zend/Service/Yahoo/InlinkDataResultSet.php';
return new Zend_Service_Yahoo_InlinkDataResultSet($dom);
}
/**
* Perform a search of images. The most basic query consists simply
* of a plain text search, but you can also specify the type of
* image, the format, color, etc.
*
* The specific options are:
* 'type' => (all|any|phrase) How to parse the query terms
* 'results' => int How many results to return, max is 50
* 'start' => int The start offset for search results
* 'format' => (any|bmp|gif|jpeg|png) The type of images to search for
* 'coloration' => (any|color|bw) The coloration of images to search for
* 'adult_ok' => bool Flag to allow 'adult' images.
*
* @param string $query the query to be run
* @param array $options an optional array of query options
* @return Zend_Service_Yahoo_ImageResultSet the search results
* @throws Zend_Service_Exception
*/
public function imageSearch($query, array $options = array())
{
static $defaultOptions = array('type' => 'all',
'results' => 10,
'start' => 1,
'format' => 'any',
'coloration' => 'any');
$options = $this->_prepareOptions($query, $options, $defaultOptions);
$this->_validateImageSearch($options);
$this->_rest->getHttpClient()->resetParameters();
$this->_rest->setUri('http://search.yahooapis.com');
$response = $this->_rest->restGet('/ImageSearchService/V1/imageSearch', $options);
if ($response->isError()) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
$response->getStatus());
}
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
self::_checkErrors($dom);
/**
* @see Zend_Service_YahooImageResultSet
*/
require_once 'Zend/Service/Yahoo/ImageResultSet.php';
return new Zend_Service_Yahoo_ImageResultSet($dom);
}
/**
* Perform a search on local.yahoo.com. The basic search
* consists of a query and some fragment of location information;
* for example zipcode, latitude/longitude, or street address.
*
* Query options include:
* 'results' => int How many results to return, max is 50
* 'start' => int The start offset for search results
* 'sort' => (relevance|title|distance|rating) How to order your results
*
* 'radius' => float The radius (in miles) in which to search
*
* 'longitude' => float The longitude of the location to search around
* 'latitude' => float The latitude of the location to search around
*
* 'zip' => string The zipcode to search around
*
* 'street' => string The street address to search around
* 'city' => string The city for address search
* 'state' => string The state for address search
* 'location' => string An adhoc location string to search around
*
* @param string $query The query string you want to run
* @param array $options The search options, including location
* @return Zend_Service_Yahoo_LocalResultSet The results
* @throws Zend_Service_Exception
*/
public function localSearch($query, array $options = array())
{
static $defaultOptions = array('results' => 10,
'start' => 1,
'sort' => 'distance',
'radius' => 5);
$options = $this->_prepareOptions($query, $options, $defaultOptions);
$this->_validateLocalSearch($options);
$this->_rest->getHttpClient()->resetParameters();
$this->_rest->setUri('http://local.yahooapis.com');
$response = $this->_rest->restGet('/LocalSearchService/V1/localSearch', $options);
if ($response->isError()) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
$response->getStatus());
}
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
self::_checkErrors($dom);
/**
* @see Zend_Service_Yahoo_LocalResultSet
*/
require_once 'Zend/Service/Yahoo/LocalResultSet.php';
return new Zend_Service_Yahoo_LocalResultSet($dom);
}
/**
* Execute a search on news.yahoo.com. This method minimally takes a
* text query to search on.
*
* Query options coonsist of:
*
* 'results' => int How many results to return, max is 50
* 'start' => int The start offset for search results
* 'sort' => (rank|date) How to order your results
* 'language' => lang The target document language to match
* 'type' => (all|any|phrase) How the query should be parsed
* 'site' => string A site to which your search should be restricted
*
* @param string $query The query to run
* @param array $options The array of optional parameters
* @return Zend_Service_Yahoo_NewsResultSet The query return set
* @throws Zend_Service_Exception
*/
public function newsSearch($query, array $options = array())
{
static $defaultOptions = array('type' => 'all',
'start' => 1,
'sort' => 'rank');
$options = $this->_prepareOptions($query, $options, $defaultOptions);
$this->_validateNewsSearch($options);
$this->_rest->getHttpClient()->resetParameters();
$this->_rest->setUri('http://search.yahooapis.com');
$response = $this->_rest->restGet('/NewsSearchService/V1/newsSearch', $options);
if ($response->isError()) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
$response->getStatus());
}
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
self::_checkErrors($dom);
/**
* @see Zend_Service_Yahoo_NewsResultSet
*/
require_once 'Zend/Service/Yahoo/NewsResultSet.php';
return new Zend_Service_Yahoo_NewsResultSet($dom);
}
/**
* Retrieve Page Data from siteexplorer.yahoo.com. A basic query
* consists simply of a URL. Additional options that can be
* specified consist of:
* 'results' => int How many results to return, max is 100
* 'start' => int The start offset for search results
* 'domain_only' => bool Data for just the given domain or all sub-domains also
*
* @param string $query the query being run
* @param array $options any optional parameters
* @return Zend_Service_Yahoo_ResultSet The return set
* @throws Zend_Service_Exception
*/
public function pageDataSearch($query, array $options = array())
{
static $defaultOptions = array('results' => '50',
'start' => 1);
$options = $this->_prepareOptions($query, $options, $defaultOptions);
$this->_validatePageDataSearch($options);
$this->_rest->getHttpClient()->resetParameters();
$this->_rest->setUri('http://search.yahooapis.com');
$response = $this->_rest->restGet('/SiteExplorerService/V1/pageData', $options);
if ($response->isError()) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
$response->getStatus());
}
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
self::_checkErrors($dom);
/**
* @see Zend_Service_Yahoo_PageDataResultSet
*/
require_once 'Zend/Service/Yahoo/PageDataResultSet.php';
return new Zend_Service_Yahoo_PageDataResultSet($dom);
}
/**
* Perform a search of videos. The most basic query consists simply
* of a plain text search, but you can also specify the format of
* video.
*
* The specific options are:
* 'type' => (all|any|phrase) How to parse the query terms
* 'results' => int How many results to return, max is 50
* 'start' => int The start offset for search results
* 'format' => (any|avi|flash|mpeg|msmedia|quicktime|realmedia) The type of videos to search for
* 'adult_ok' => bool Flag to allow 'adult' videos.
*
* @param string $query the query to be run
* @param array $options an optional array of query options
* @return Zend_Service_Yahoo_VideoResultSet the search results
* @throws Zend_Service_Exception
*/
public function videoSearch($query, array $options = array())
{
static $defaultOptions = array('type' => 'all',
'results' => 10,
'start' => 1,
'format' => 'any');
$options = $this->_prepareOptions($query, $options, $defaultOptions);
$this->_validateVideoSearch($options);
$this->_rest->getHttpClient()->resetParameters();
$this->_rest->setUri('http://search.yahooapis.com');
$response = $this->_rest->restGet('/VideoSearchService/V1/videoSearch', $options);
if ($response->isError()) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
$response->getStatus());
}
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
self::_checkErrors($dom);
/**
* @see Zend_Service_YahooVideoResultSet
*/
require_once 'Zend/Service/Yahoo/VideoResultSet.php';
return new Zend_Service_Yahoo_VideoResultSet($dom);
}
/**
* Perform a web content search on search.yahoo.com. A basic query
* consists simply of a text query. Additional options that can be
* specified consist of:
* 'results' => int How many results to return, max is 50
* 'start' => int The start offset for search results
* 'language' => lang The target document language to match
* 'type' => (all|any|phrase) How the query should be parsed
* 'site' => string A site to which your search should be restricted
* 'format' => (any|html|msword|pdf|ppt|rss|txt|xls)
* 'adult_ok' => bool permit 'adult' content in the search results
* 'similar_ok' => bool permit similar results in the result set
* 'country' => string The country code for the content searched
* 'license' => (any|cc_any|cc_commercial|cc_modifiable) The license of content being searched
* 'region' => The regional search engine on which the service performs the search. default us.
*
* @param string $query the query being run
* @param array $options any optional parameters
* @return Zend_Service_Yahoo_WebResultSet The return set
* @throws Zend_Service_Exception
*/
public function webSearch($query, array $options = array())
{
static $defaultOptions = array('type' => 'all',
'start' => 1,
'license' => 'any',
'results' => 10,
'format' => 'any');
$options = $this->_prepareOptions($query, $options, $defaultOptions);
$this->_validateWebSearch($options);
$this->_rest->getHttpClient()->resetParameters();
$this->_rest->setUri('http://search.yahooapis.com');
$response = $this->_rest->restGet('/WebSearchService/V1/webSearch', $options);
if ($response->isError()) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
$response->getStatus());
}
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
self::_checkErrors($dom);
/**
* @see Zend_Service_Yahoo_WebResultSet
*/
require_once 'Zend/Service/Yahoo/WebResultSet.php';
return new Zend_Service_Yahoo_WebResultSet($dom);
}
/**
* Returns a reference to the REST client
*
* @return Zend_Rest_Client
*/
public function getRestClient()
{
return $this->_rest;
}
/**
* Validate Inlink Data Search Options
*
* @param array $options
* @return void
* @throws Zend_Service_Exception
*/
protected function _validateInlinkDataSearch(array $options)
{
$validOptions = array('appid', 'query', 'results', 'start', 'entire_site', 'omit_inlinks');
$this->_compareOptions($options, $validOptions);
/**
* @see Zend_Validate_Between
*/
require_once 'Zend/Validate/Between.php';
$between = new Zend_Validate_Between(1, 100, true);
if (isset($options['results']) && !$between->setMin(1)->setMax(100)->isValid($options['results'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
}
if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
}
if (isset($options['omit_inlinks'])) {
$this->_validateInArray('omit_inlinks', $options['omit_inlinks'], array('none', 'domain', 'subdomain'));
}
}
/**
* Validate Image Search Options
*
* @param array $options
* @return void
* @throws Zend_Service_Exception
*/
protected function _validateImageSearch(array $options)
{
$validOptions = array('appid', 'query', 'type', 'results', 'start', 'format', 'coloration', 'adult_ok');
$this->_compareOptions($options, $validOptions);
if (isset($options['type'])) {
switch($options['type']) {
case 'all':
case 'any':
case 'phrase':
break;
default:
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'type': '{$options['type']}'");
}
}
/**
* @see Zend_Validate_Between
*/
require_once 'Zend/Validate/Between.php';
$between = new Zend_Validate_Between(1, 50, true);
if (isset($options['results']) && !$between->setMin(1)->setMax(50)->isValid($options['results'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
}
if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
}
if (isset($options['format'])) {
switch ($options['format']) {
case 'any':
case 'bmp':
case 'gif':
case 'jpeg':
case 'png':
break;
default:
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'format': {$options['format']}");
}
}
if (isset($options['coloration'])) {
switch ($options['coloration']) {
case 'any':
case 'color':
case 'bw':
break;
default:
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'coloration': "
. "{$options['coloration']}");
}
}
}
/**
* Validate Local Search Options
*
* @param array $options
* @return void
* @throws Zend_Service_Exception
*/
protected function _validateLocalSearch(array $options)
{
$validOptions = array('appid', 'query', 'results', 'start', 'sort', 'radius', 'street',
'city', 'state', 'zip', 'location', 'latitude', 'longitude');
$this->_compareOptions($options, $validOptions);
/**
* @see Zend_Validate_Between
*/
require_once 'Zend/Validate/Between.php';
$between = new Zend_Validate_Between(1, 20, true);
if (isset($options['results']) && !$between->setMin(1)->setMax(20)->isValid($options['results'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
}
if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
}
if (isset($options['longitude']) && !$between->setMin(-90)->setMax(90)->isValid($options['longitude'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'longitude': {$options['longitude']}");
}
if (isset($options['latitude']) && !$between->setMin(-180)->setMax(180)->isValid($options['latitude'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'latitude': {$options['latitude']}");
}
if (isset($options['zip']) && !preg_match('/(^\d{5}$)|(^\d{5}-\d{4}$)/', $options['zip'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'zip': {$options['zip']}");
}
$hasLocation = false;
$locationFields = array('street', 'city', 'state', 'zip', 'location');
foreach ($locationFields as $field) {
if (isset($options[$field]) && $options[$field] != '') {
$hasLocation = true;
break;
}
}
if (!$hasLocation && (!isset($options['latitude']) || !isset($options['longitude']))) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('Location data are required but missing');
}
if (!in_array($options['sort'], array('relevance', 'title', 'distance', 'rating'))) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'sort': {$options['sort']}");
}
}
/**
* Validate News Search Options
*
* @param array $options
* @return void
* @throws Zend_Service_Exception
*/
protected function _validateNewsSearch(array $options)
{
$validOptions = array('appid', 'query', 'results', 'start', 'sort', 'language', 'type', 'site');
$this->_compareOptions($options, $validOptions);
/**
* @see Zend_Validate_Between
*/
require_once 'Zend/Validate/Between.php';
$between = new Zend_Validate_Between(1, 50, true);
if (isset($options['results']) && !$between->setMin(1)->setMax(50)->isValid($options['results'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
}
if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
}
if (isset($options['language'])) {
$this->_validateLanguage($options['language']);
}
$this->_validateInArray('sort', $options['sort'], array('rank', 'date'));
$this->_validateInArray('type', $options['type'], array('all', 'any', 'phrase'));
}
/**
* Validate Page Data Search Options
*
* @param array $options
* @return void
* @throws Zend_Service_Exception
*/
protected function _validatePageDataSearch(array $options)
{
$validOptions = array('appid', 'query', 'results', 'start', 'domain_only');
$this->_compareOptions($options, $validOptions);
/**
* @see Zend_Validate_Between
*/
require_once 'Zend/Validate/Between.php';
$between = new Zend_Validate_Between(1, 100, true);
if (isset($options['results']) && !$between->setMin(1)->setMax(100)->isValid($options['results'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
}
if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
}
}
/**
* Validate Video Search Options
*
* @param array $options
* @return void
* @throws Zend_Service_Exception
*/
protected function _validateVideoSearch(array $options)
{
$validOptions = array('appid', 'query', 'type', 'results', 'start', 'format', 'adult_ok');
$this->_compareOptions($options, $validOptions);
if (isset($options['type'])) {
$this->_validateInArray('type', $options['type'], array('all', 'any', 'phrase'));
}
/**
* @see Zend_Validate_Between
*/
require_once 'Zend/Validate/Between.php';
$between = new Zend_Validate_Between(1, 50, true);
if (isset($options['results']) && !$between->setMin(1)->setMax(50)->isValid($options['results'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
}
if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
}
if (isset($options['format'])) {
$this->_validateInArray('format', $options['format'], array('any', 'avi', 'flash', 'mpeg', 'msmedia', 'quicktime', 'realmedia'));
}
}
/**
* Validate Web Search Options
*
* @param array $options
* @return void
* @throws Zend_Service_Exception
*/
protected function _validateWebSearch(array $options)
{
$validOptions = array('appid', 'query', 'results', 'start', 'language', 'type', 'format', 'adult_ok',
'similar_ok', 'country', 'site', 'subscription', 'license', 'region');
$this->_compareOptions($options, $validOptions);
/**
* @see Zend_Validate_Between
*/
require_once 'Zend/Validate/Between.php';
$between = new Zend_Validate_Between(1, 100, true);
if (isset($options['results']) && !$between->setMin(1)->setMax(100)->isValid($options['results'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
}
if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
}
if (isset($options['language'])) {
$this->_validateLanguage($options['language']);
}
$this->_validateInArray('type', $options['type'], array('all', 'any', 'phrase'));
$this->_validateInArray('format', $options['format'], array('any', 'html', 'msword', 'pdf', 'ppt', 'rss',
'txt', 'xls'));
$this->_validateInArray('license', $options['license'], array('any', 'cc_any', 'cc_commercial',
'cc_modifiable'));
if (isset($options['region'])){
$this->_validateInArray('region', $options['region'], array('ar', 'au', 'at', 'br', 'ca', 'ct', 'dk', 'fi',
'fr', 'de', 'in', 'id', 'it', 'my', 'mx',
'nl', 'no', 'ph', 'ru', 'sg', 'es', 'se',
'ch', 'th', 'uk', 'us'));
}
}
/**
* Prepare options for sending to Yahoo!
*
* @param string $query Search Query
* @param array $options User specified options
* @param array $defaultOptions Required/Default options
* @return array
*/
protected function _prepareOptions($query, array $options, array $defaultOptions = array())
{
$options['appid'] = $this->appId;
$options['query'] = (string) $query;
return array_merge($defaultOptions, $options);
}
/**
* Throws an exception if the chosen language is not supported
*
* @param string $lang Language code
* @return void
* @throws Zend_Service_Exception
*/
protected function _validateLanguage($lang)
{
$languages = array('ar', 'bg', 'ca', 'szh', 'tzh', 'hr', 'cs', 'da', 'nl', 'en', 'et', 'fi', 'fr', 'de', 'el',
'he', 'hu', 'is', 'id', 'it', 'ja', 'ko', 'lv', 'lt', 'no', 'fa', 'pl', 'pt', 'ro', 'ru', 'sk', 'sr', 'sl',
'es', 'sv', 'th', 'tr'
);
if (!in_array($lang, $languages)) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("The selected language '$lang' is not supported");
}
}
/**
* Utility function to check for a difference between two arrays.
*
* @param array $options User specified options
* @param array $validOptions Valid options
* @return void
* @throws Zend_Service_Exception if difference is found (e.g., unsupported query option)
*/
protected function _compareOptions(array $options, array $validOptions)
{
$difference = array_diff(array_keys($options), $validOptions);
if ($difference) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception('The following parameters are invalid: ' . join(', ', $difference));
}
}
/**
* Check that a named value is in the given array
*
* @param string $name Name associated with the value
* @param mixed $value Value
* @param array $array Array in which to check for the value
* @return void
* @throws Zend_Service_Exception
*/
protected function _validateInArray($name, $value, array $array)
{
if (!in_array($value, $array)) {
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception("Invalid value for option '$name': $value");
}
}
/**
* Check if response is an error
*
* @param DOMDocument $dom DOM Object representing the result XML
* @return void
* @throws Zend_Service_Exception Thrown when the result from Yahoo! is an error
*/
protected static function _checkErrors(DOMDocument $dom)
{
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('yapi', 'urn:yahoo:api');
if ($xpath->query('//yapi:Error')->length >= 1) {
$message = $xpath->query('//yapi:Error/yapi:Message/text()')->item(0)->data;
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception($message);
}
}
}
| NewTechNetwork/EchoOpen | Zend/Service/Yahoo.php | PHP | gpl-2.0 | 35,352 |
<?php
/*
Plugin Name: Genesis Simple Hooks
Plugin URI: http://www.studiopress.com/plugins/simple-hooks
Description: Genesis Simple Hooks allows you easy access to the 50+ Action Hooks in the Genesis Theme.
Author: Nathan Rice
Author URI: http://www.nathanrice.net/
Version: 2.1.2
Text Domain: genesis-simple-hooks
Domain Path: /languages
License: GNU General Public License v2.0 (or later)
License URI: http://www.opensource.org/licenses/gpl-license.php
*/
//* Define our constants
define( 'SIMPLEHOOKS_SETTINGS_FIELD', 'simplehooks-settings' );
define( 'SIMPLEHOOKS_PLUGIN_DIR', dirname( __FILE__ ) );
register_activation_hook( __FILE__, 'simplehooks_activation' );
/**
* This function runs on plugin activation. It checks to make sure Genesis
* or a Genesis child theme is active. If not, it deactivates itself.
*
* @since 0.1.0
*/
function simplehooks_activation() {
if ( ! defined( 'PARENT_THEME_VERSION' ) || ! version_compare( PARENT_THEME_VERSION, '2.1.0', '>=' ) )
simplehooks_deactivate( '2.1.0', '3.9.2' );
}
/**
* Deactivate Simple Hooks.
*
* This function deactivates Simple Hooks.
*
* @since 1.8.0.2
*/
function simplehooks_deactivate( $genesis_version = '2.1.0', $wp_version = '3.9.2' ) {
deactivate_plugins( plugin_basename( __FILE__ ) );
wp_die( sprintf( __( 'Sorry, you cannot run Simple Hooks without WordPress %s and <a href="%s">Genesis %s</a>, or greater.', 'genesis-simple-hooks' ), $wp_version, 'http://my.studiopress.com/?download_id=91046d629e74d525b3f2978e404e7ffa', $genesis_version ) );
}
add_action( 'plugins_loaded', 'simplehooks_load_textdomain' );
/**
* Load the plugin textdomain
*/
function simplehooks_load_textdomain() {
load_plugin_textdomain( 'genesis-simple-hooks', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' );
}
add_action( 'genesis_init', 'simplehooks_init', 20 );
/**
* Load admin menu and helper functions. Hooked to `genesis_init`.
*
* @since 1.8.0
*/
function simplehooks_init() {
//* Admin Menu
if ( is_admin() )
require_once( SIMPLEHOOKS_PLUGIN_DIR . '/admin.php' );
//* Helper functions
require_once( SIMPLEHOOKS_PLUGIN_DIR . '/functions.php' );
}
add_action( 'genesis_init', 'simplehooks_execute_hooks', 20 );
/**
* The following code loops through all the hooks, and attempts to
* execute the code in the proper location.
*
* @uses simplehooks_execute_hook() as a callback.
*
* @since 0.1
*/
function simplehooks_execute_hooks() {
$hooks = get_option( SIMPLEHOOKS_SETTINGS_FIELD );
foreach ( (array) $hooks as $hook => $array ) {
//* Add new content to hook
if ( simplehooks_get_option( $hook, 'content' ) ) {
add_action( $hook, 'simplehooks_execute_hook' );
}
//* Unhook stuff
if ( isset( $array['unhook'] ) ) {
foreach( (array) $array['unhook'] as $function ) {
remove_action( $hook, $function );
}
}
}
}
/**
* The following function executes any code meant to be hooked.
* It checks to see if shortcodes or PHP should be executed as well.
*
* @uses simplehooks_get_option()
*
* @since 0.1
*/
function simplehooks_execute_hook() {
$hook = current_filter();
$content = simplehooks_get_option( $hook, 'content' );
if( ! $hook || ! $content )
return;
$shortcodes = simplehooks_get_option( $hook, 'shortcodes' );
$php = simplehooks_get_option( $hook, 'php' );
$value = $shortcodes ? do_shortcode( $content ) : $content;
if ( $php )
eval( "?>$value<?php " );
else
echo $value;
} | sanjay-jagdish/barkerby | wp-content/plugins/genesis-simple-hooks/plugin.php | PHP | gpl-2.0 | 3,474 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Downloadable
* @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
$installer = $this;
/* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */
$installer->startSetup();
$installer->addAttribute('catalog_product', 'samples_title', array(
'type' => 'varchar',
'backend' => '',
'frontend' => '',
'label' => 'Samples title',
'input' => '',
'class' => '',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'visible' => false,
'required' => true,
'user_defined' => false,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'unique' => false,
'apply_to' => 'downloadable',
'is_configurable' => false
));
$installer->addAttribute('catalog_product', 'links_title', array(
'type' => 'varchar',
'backend' => '',
'frontend' => '',
'label' => 'Links title',
'input' => '',
'class' => '',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'visible' => false,
'required' => true,
'user_defined' => false,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'unique' => false,
'apply_to' => 'downloadable',
'is_configurable' => false
));
$installer->endSetup();
| tonio-44/tikflak | shop/app/code/core/Mage/Downloadable/sql/downloadable_setup/mysql4-upgrade-0.1.9-0.1.10.php | PHP | gpl-2.0 | 2,818 |
<?php
/** Church Slavic (словѣньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ)
*
* See MessagesQqq.php for message documentation incl. usage of parameters
* To improve a translation please visit http://translatewiki.net
*
* @ingroup Language
* @file
*
* @author Krinkle
* @author Omnipaedista
* @author Svetko
* @author Wolliger Mensch
* @author ОйЛ
*/
$specialPageAliases = array(
'Allpages' => array( 'Вьсѩ_страницѧ' ),
'Categories' => array( 'Катигорїѩ' ),
'Contributions' => array( 'Добродѣꙗниꙗ' ),
'Preferences' => array( 'Строи' ),
'Recentchanges' => array( 'Послѣдьнѩ_мѣнꙑ' ),
'Search' => array( 'Исканиѥ' ),
'Statistics' => array( 'Статїстїка' ),
'Upload' => array( 'Положєниѥ_дѣла' ),
);
$namespaceNames = array(
NS_MEDIA => 'Срѣдьства',
NS_SPECIAL => 'Нарочьна',
NS_TALK => 'Бєсѣда',
NS_USER => 'Польꙃєватєл҄ь',
NS_USER_TALK => 'Польꙃєватєлꙗ_бєсѣда',
NS_PROJECT_TALK => '{{GRAMMAR:genitive|$1}}_бєсѣда',
NS_FILE => 'Дѣло',
NS_FILE_TALK => 'Дѣла_бєсѣда',
NS_MEDIAWIKI => 'MediaWiki',
NS_MEDIAWIKI_TALK => 'MediaWiki_бєсѣда',
NS_TEMPLATE => 'Обраꙁьць',
NS_TEMPLATE_TALK => 'Обраꙁьца_бєсѣда',
NS_HELP => 'Помощь',
NS_HELP_TALK => 'Помощи_бєсѣда',
NS_CATEGORY => 'Катигорїꙗ',
NS_CATEGORY_TALK => 'Катигорїѩ_бєсѣда',
);
$namespaceAliases = array(
'Срѣдьства' => NS_MEDIA,
'Нарочьна' => NS_SPECIAL,
'Бесѣда' => NS_TALK,
'Польѕевател҄ь' => NS_USER,
'Польѕевател_бесѣда' => NS_USER_TALK,
'{{grammar:genitive|$1}}_бесѣда' => NS_PROJECT_TALK,
'Ви́дъ' => NS_FILE,
'Видъ' => NS_FILE,
'Ви́да_бєсѣ́да' => NS_FILE_TALK,
'Вида_бесѣда' => NS_FILE_TALK,
'MediaWiki_бесѣда' => NS_MEDIAWIKI_TALK,
'Образьць' => NS_TEMPLATE,
'Образьца_бесѣда' => NS_TEMPLATE_TALK,
'Помощь' => NS_HELP,
'Помощи_бесѣда' => NS_HELP_TALK,
'Катигорї' => NS_CATEGORY,
'Катигорїѩ_бесѣда' => NS_CATEGORY_TALK,
);
$magicWords = array(
'redirect' => array( '0', '#ПРѢНАПРАВЛЄНИѤ', '#REDIRECT' ),
'language' => array( '0', '#ѨꙀꙐКЪ:', '#LANGUAGE:' ),
);
$separatorTransformTable = array(
',' => ".",
'.' => ','
);
$linkPrefixExtension = true;
$defaultDateFormat = 'mdy';
$dateFormats = array(
'mdy time' => 'H:i',
'mdy date' => 'xg j числа, Y',
'mdy both' => 'H:i, xg j числа, Y',
'dmy time' => 'H:i',
'dmy date' => 'j F Y',
'dmy both' => 'H:i, j F Y',
'ymd time' => 'H:i',
'ymd date' => 'Y F j',
'ymd both' => 'H:i, Y F j',
'ISO 8601 time' => 'xnH:xni:xns',
'ISO 8601 date' => 'xnY-xnm-xnd',
'ISO 8601 both' => 'xnY-xnm-xnd"T"xnH:xni:xns',
);
$linkTrail = '/^([a-zабвгдеєжѕзїіıићклмнопсстѹфхѡѿцчшщъыьѣюѥѧѩѫѭѯѱѳѷѵґѓђёјйљњќуўџэ҄я“»]+)(.*)$/sDu';
$linkPrefixCharset = '„«';
$messages = array(
# User preference toggles
'tog-oldsig' => 'нꙑнѣшьн҄ь аѵтографъ :',
'underline-always' => 'вьсѥгда',
'underline-never' => 'никъгда',
# Dates
'sunday' => 'нєдѣлꙗ',
'monday' => 'понедѣл҄ьникъ',
'tuesday' => 'въторьникъ',
'wednesday' => 'срѣда',
'thursday' => 'чєтврьтъкъ',
'friday' => 'пѧтъкъ',
'saturday' => 'сѫбота',
'sun' => 'н҃д',
'mon' => 'п҃н',
'tue' => 'в҃т',
'wed' => 'с҃р',
'thu' => 'ч҃т',
'fri' => 'п҃т',
'sat' => 'с҃б',
'january' => 'їаноуарїи',
'february' => 'фєвроуарїи',
'march' => 'мартїи',
'april' => 'апрїлїи',
'may_long' => 'маїи',
'june' => 'їоунїи',
'july' => 'їоулїи',
'august' => 'аѷгоустъ',
'september' => 'сєптємврїи',
'october' => 'октѡврїи',
'november' => 'ноємврїи',
'december' => 'дєкємврїи',
'january-gen' => 'їаноуарїꙗ',
'february-gen' => 'фєвроуарїꙗ',
'march-gen' => 'мартїꙗ',
'april-gen' => 'апрїлїꙗ',
'may-gen' => 'маїꙗ',
'june-gen' => 'їоунїꙗ',
'july-gen' => 'їоулїꙗ',
'august-gen' => 'аѷгоуста',
'september-gen' => 'сєптємврїꙗ',
'october-gen' => 'октѡврїꙗ',
'november-gen' => 'ноємврїꙗ',
'december-gen' => 'дєкємврїꙗ',
'jan' => 'ꙗ҃н',
'feb' => 'фє҃в',
'mar' => 'ма҃р',
'apr' => 'ап҃р',
'may' => 'маїи',
'jun' => 'їо҃ун',
'jul' => 'їо҃ул',
'aug' => 'аѵ҃г',
'sep' => 'сє҃п',
'oct' => 'ок҃т',
'nov' => 'но҃є',
'dec' => 'дє҃к',
'january-date' => 'ꙗноуарїꙗ $1 числа',
'february-date' => 'фєвроуарїꙗ $1 числа',
'march-date' => 'мартїꙗ $1 числа',
'april-date' => 'апрїлїꙗ $1 числа',
'may-date' => 'маїꙗ $1 числа',
'june-date' => 'їоунїꙗ $1 числа',
'july-date' => 'їоулїꙗ $1 числа',
'august-date' => 'аѷгоуста $1 числа',
'september-date' => 'сєптємврїꙗ $1 числа',
'october-date' => 'октѡврїꙗ $1 числа',
'november-date' => 'ноємврїꙗ $1 числа',
'december-date' => 'дєкємврїꙗ $1 числа',
# Categories related messages
'pagecategories' => '{{PLURAL:$1|Катигорїꙗ|Катигорїи|Катигорїѩ|Катигорїѩ}}',
'category_header' => 'катигорїѩ ⁖ $1 ⁖ страницѧ',
'subcategories' => 'подъкатигорїѩ',
'category-media-header' => 'катигорїѩ ⁖ $1 ⁖ дѣла',
'category-empty' => "''си катигорїи нꙑнѣ страницѧ и дѣлъ нѣстъ''",
'hidden-categories' => '{{PLURAL:$1|съкрꙑта катигорїꙗ|съкрꙑти катигорїи|съкрꙑтꙑ катигорїѩ}}',
'hidden-category-category' => 'съкрꙑтꙑ катигорїѩ',
'category-subcat-count' => '{{PLURAL:$2|Сѥи катигорїи тъкъмо сꙗ подъкатигорїꙗ ѥстъ|Сѥи катигорїи {{PLURAL:$1|ѥдина подъкатигорїꙗ ѥстъ|2 подъкатигорїи ѥстє|$1 подъкатигорїѩ сѫтъ}} · а вьсѩ жє подъкатигорїѩ число $2 ѥстъ}}',
'listingcontinuesabbrev' => '· вѧщє',
'about' => 'опьсаниѥ',
'article' => 'члѣнъ',
'newwindow' => '(иномь окънѣ)',
'moredotdotdot' => 'вѧщє ···',
'mypage' => 'страница',
'mytalk' => 'бєсѣда',
'navigation' => 'плаваниѥ',
'and' => ' и',
# Cologne Blue skin
'qbedit' => 'исправи',
'qbpageoptions' => 'сꙗ страница',
'qbmyoptions' => 'моꙗ страницѧ',
'faq' => 'чѧстꙑ въпроси',
'faqpage' => 'Project:Чѧстꙑ въпроси',
# Vector skin
'vector-action-addsection' => 'новꙑ бєсѣдꙑ чѧсти сътворѥниѥ',
'vector-action-delete' => 'поничьжєниѥ',
'vector-action-move' => 'прѣимєнованиѥ',
'vector-action-protect' => 'ꙁабранѥниѥ',
'vector-action-unprotect' => 'иꙁмѣни ꙁабранѥниꙗ обраꙁъ',
'vector-view-create' => 'сътворѥниѥ',
'vector-view-edit' => 'исправи',
'vector-view-history' => 'їсторїꙗ',
'vector-view-view' => 'чьтѥниѥ',
'vector-view-viewsource' => 'страницѧ источьнъ обраꙁъ',
'actions' => 'дѣиства',
'namespaces' => 'имєнъ просторꙑ',
'errorpagetitle' => 'блаꙁна',
'tagline' => '{{grammar:genitive|{{SITENAME}}}} страница',
'help' => 'помощь',
'search' => 'исканиѥ',
'searchbutton' => 'ищи',
'go' => 'прѣиди',
'searcharticle' => 'прѣиди',
'history' => 'страницѧ їсторїꙗ',
'history_short' => 'їсторїꙗ',
'printableversion' => 'пєчатьнъ обраꙁъ',
'permalink' => 'въиньна съвѧꙁь',
'print' => 'пєчатаниѥ',
'edit' => 'исправи',
'create' => 'сътворѥниѥ',
'editthispage' => 'си страницѧ исправлѥниѥ',
'create-this-page' => 'си страницѧ сътворѥниѥ',
'delete' => 'поничьжєниѥ',
'deletethispage' => 'си страницѧ поничьжєниѥ',
'protect' => 'ꙁабранѥниѥ',
'protect_change' => 'иꙁмѣнѥниѥ',
'protectthispage' => 'си страницѧ ꙁабранєниѥ',
'unprotect' => 'ꙁабранѥниꙗ обраꙁа иꙁмѣнѥниѥ',
'newpage' => 'нова страница',
'talkpage' => 'си страницѧ бєсѣда',
'talkpagelinktext' => 'бєсѣда',
'specialpage' => 'нарочьна страница',
'personaltools' => 'моꙗ орѫдиꙗ',
'postcomment' => 'нова чѧсть',
'talk' => 'бєсѣда',
'toolbox' => 'орѫдиꙗ',
'otherlanguages' => 'дроугꙑ ѩꙁꙑкꙑ',
'redirectedfrom' => '(прѣнаправлѥниѥ отъ ⁖ $1 ⁖)',
'redirectpagesub' => 'прѣнаправлѥниѥ',
'lastmodifiedat' => 'страницѧ послѣдьнꙗ мѣна сътворѥна $2 · $1 бѣ ⁙',
'jumpto' => 'прѣиди къ :',
'jumptonavigation' => 'плаваниѥ',
'jumptosearch' => 'исканиѥ',
'pool-errorunknown' => 'нєвѣдома блаꙁна',
# All link text and link target definitions of links into project namespace that get used by other message strings, with the exception of user group pages (see grouppage).
'aboutsite' => 'О {{grammar:instrumental|{{SITENAME}}}}',
'aboutpage' => 'Project:О сѥмь опꙑтьствовании',
'copyright' => 'подъ прощєниѥмь $1 пьсано ѥстъ',
'copyrightpage' => '{{ns:project}}:Творьцъ права',
'currentevents' => 'сѫщѧѩ вѣщи',
'currentevents-url' => 'Project:Сѫщѧѩ вѣщи',
'edithelp' => 'помощь по исправлѥниѭ',
'helppage' => 'Help:Каталогъ',
'mainpage' => 'главьна страница',
'mainpage-description' => 'главьна страница',
'policy-url' => 'Project:Полїтїка',
'portal' => 'обьщєниꙗ съвѣтъ',
'portal-url' => 'Project:Обьщєниꙗ съвѣтъ',
'pagetitle' => '$1 · {{SITENAME}}',
'retrievedfrom' => 'поѩто иꙁ ⁖ $1 ⁖',
'youhavenewmessages' => '$1 тєбѣ напьсанꙑ сѫтъ ($2)',
'newmessageslinkplural' => '{{PLURAL:$1|ново напьсаниѥ|нова напьсании|999=новꙑ напьсаниꙗ}}',
'newmessagesdifflinkplural' => '{{PLURAL:$1|послѣдьнꙗ мѣна|послѣдьни мѣни|999=послѣдьн҄ь мѣнъ}}',
'editsection' => 'исправи',
'editold' => 'исправи',
'viewsourceold' => 'страницѧ источьнъ обраꙁъ',
'editlink' => 'исправи',
'viewsourcelink' => 'страницѧ источьнъ обраꙁъ',
'editsectionhint' => 'исправлѥниѥ чѧсти : $1',
'toc' => 'каталогъ',
'showtoc' => 'виждь',
'hidetoc' => 'съкрꙑи',
'viewdeleted' => '$1 видєти хощєши ;',
'red-link-title' => '$1 (си страницѧ нѣстъ)',
# Short words for each namespace, by default used in the namespace tab in monobook
'nstab-main' => 'члѣнъ',
'nstab-user' => 'польꙃєватєл҄ь',
'nstab-media' => 'срѣдьства',
'nstab-special' => 'нарочьна',
'nstab-project' => 'съвѣтъ',
'nstab-image' => 'дѣло',
'nstab-mediawiki' => 'напьсаниѥ',
'nstab-template' => 'обраꙁьць',
'nstab-help' => 'страница помощи',
'nstab-category' => 'катигорїꙗ',
# Main script and global functions
'nosuchspecialpage' => 'си нарочнꙑ страницѧ нѣстъ',
# General errors
'error' => 'блаꙁна',
'internalerror' => 'вънѫтрѣнꙗ блаꙁна',
'badtitle' => 'ꙁъло имѧ',
'viewsource' => 'страницѧ источьнъ обраꙁъ',
'viewsource-title' => 'вижьдь страницѧ ⁖ $1 ⁖ источьнъ обраꙁъ',
# Login and logout pages
'welcomeuser' => 'Добрѣ прити · $1!',
'welcomecreation-msg' => 'твоѥ польꙃєватєльско мѣсто сътворєно ѥстъ ⁙
нꙑнѣ иꙁмѣнити [[Special:Preferences|{{GRAMMAR:genitive|{{SITENAME}}}} строи]] можєши',
'yourname' => 'твоѥ имѧ',
'userlogin-yourname' => 'польꙃєватєлꙗ имѧ',
'userlogin-yourname-ph' => 'твоѥ польꙃєватєлꙗ имѧ напьши',
'yourpassword' => 'таино слово напиши',
'userlogin-yourpassword' => 'таино слово',
'userlogin-yourpassword-ph' => 'твоѥ таино слово напьши',
'createacct-yourpassword-ph' => 'таино слово напьши',
'yourpasswordagain' => 'опакꙑ таиноѥ слово напиши',
'createacct-yourpasswordagain' => 'таина слова оувѣрѥниѥ',
'createacct-yourpasswordagain-ph' => 'опакꙑ жє таино слово напьши',
'login' => 'въниди',
'nav-login-createaccount' => 'въниди / съꙁижди си мѣсто',
'userlogin' => 'въниди / съꙁижди си мѣсто',
'userloginnocreate' => 'въниди',
'logout' => 'ис̾ходъ',
'userlogout' => 'ис̾ходъ',
'nologin' => 'мѣсто ти нѣстъ ли ? $1',
'nologinlink' => 'съꙁижди си мѣсто',
'createaccount' => 'съꙁижди си мѣсто',
'gotaccount' => 'мѣсто ти ѥстъ ли? $1',
'gotaccountlink' => 'въниди',
'helplogin-url' => 'Help:Въниждѥниѥ',
'createaccountreason' => 'какъ съмꙑслъ :',
'createacct-reason' => 'какъ съмꙑслъ',
'createacct-submit' => 'съꙁижди си мѣсто',
'createacct-benefit-heading' => '{{SITENAME}} съꙁьдаѥтъ сѧ чьловѣкꙑ · ижє ꙗко тꙑ сѫтъ',
'createacct-benefit-body1' => '{{PLURAL:$1|мѣна|мѣнꙑ|мѣнъ}}',
'createacct-benefit-body2' => '{{PLURAL:$1|страница|страници|страницѧ}}',
'userexists' => 'сѫщє польꙃєватєлꙗ имѧ пьса ⁙
бѫди добръ · ино сѥ иꙁобрѧщи',
'loginerror' => 'въхода блаꙁна',
'createacct-error' => 'мѣста сътворѥниꙗ блаꙁна',
'loginsuccess' => "'''нꙑнѣ тꙑ {{GENDER|въшьлъ|въшьла}} въ {{grammar:locative|{{SITENAME}}}} подь имьньмъ ⁖ $1 ⁖.'''",
'mailmypassword' => 'посъли ново таино слово',
'accountcreated' => 'мѣсто сътворєно ѥстъ',
'accountcreatedtext' => 'польꙃєватєльско мѣсто [[{{ns:User}}:$1|$1]] ([[{{ns:User talk}}:$1|бєсѣда]]) сътворєно бѣ',
'loginlanguagelabel' => 'ѩꙁꙑкъ : $1',
# Change password dialog
'changepassword' => 'таина словєсє иꙁмѣнѥниѥ',
'resetpass_header' => 'таина слова иꙁмѣнѥниѥ',
'oldpassword' => 'старо таино слово :',
'newpassword' => 'ново таино слово :',
'retypenew' => 'опакꙑ ново таиноѥ слово напиши :',
'resetpass-submit-loggedin' => 'таина словєсє иꙁмѣнѥниѥ',
# Special:PasswordReset
'passwordreset-username' => 'польꙃєватєлꙗ имѧ :',
# Special:ChangeEmail
'changeemail-none' => '(нѣстъ)',
# Edit page toolbar
'link_sample' => 'съвѧꙁи имѧ',
'link_tip' => 'вънѫтрьнꙗ съвѧꙁь',
'extlink_sample' => 'http://www.example.com съвѧꙁи имѧ',
'extlink_tip' => 'вънѣщьнꙗ съвѧꙁь (помьни о http://)',
'media_tip' => 'дѣла съвѧꙁь',
'sig_tip' => 'твои аѵтографъ и нꙑнѣшьна врѣмѧ и дьнь',
# Edit pages
'summary' => 'опьсаниѥ :',
'minoredit' => 'малаꙗ мѣна',
'watchthis' => 'си страницѧ блюдєниѥ',
'savearticle' => 'съхранѥниѥ',
'showpreview' => 'мѣнꙑ поꙁьрѣниѥ (бєꙁ съхранѥниꙗ)',
'blockedtitle' => 'польꙃєватєл҄ь ꙁаграждєнъ ѥстъ',
'loginreqlink' => 'въниди',
'newarticle' => '(новъ)',
'noarticletext' => 'нꙑнѣ с̑ьдє ничєсожє нє напьсано ѥстъ ⁙
[[Special:Search/{{PAGENAME}}|си страницѧ имѧ искати]] дроугꙑ страницѧ ·
<span class="plainlinks">[{{fullurl:{{#Special:Log}}|page={{FULLPAGENAMEE}}}} съвѧꙁанꙑ їсторїѩ видѣти] ·
или [{{fullurl:{{FULLPAGENAME}}|action=edit}} ѭжє исправити]</span> можєши',
'noarticletext-nopermission' => 'нꙑнѣ с̑ьдє ничєсожє нє напьсано ѥстъ ⁙
[[Special:Search/{{PAGENAME}}|си страницѧ имѧ искати]] дроугꙑ страницѧ или
<span class="plainlinks">[{{fullurl:{{#Special:Log}}|page={{FULLPAGENAMEE}}}} съвѧꙁанꙑ їсторїѩ видѣти]</span> можєши ⁙ сътворити жє си страницѧ нє можєши',
'userpage-userdoesnotexist' => 'польꙃєватєльска мѣста ⁖ $1 ⁖ нꙑнѣ нѣстъ ⁙
прѣдъ сътворѥниѥмь или исправлѥниѥмь си страницѧ помꙑсли жє ащє исто тъ дѣиство ноуждьно ли',
'userpage-userdoesnotexist-view' => 'польꙃєватєльско мѣсто ⁖ $1 ⁖ сътворєно нѣстъ',
'clearyourcache' => "'''НАРОЧИТО''': По съхранѥнии можєши обити своѥго съмотрила съхранъ да видѣлъ би мѣнꙑ
* '''Mozilla ли Firefox ли Safari''' ли жьмꙑи ''Shift'' а мꙑшиѭ жьми ''Reload'' или жьми ''Ctrl-F5'' ꙗко жє ''Ctrl-R'' (⌘-R вън Apple Mac)
* '''Google Chrome:''' ли жьмꙑи ''Ctrl-Shift-R'' (⌘-Shift-R въ Mac)
* '''Internet Explorer''' ли жьмꙑи ''Ctrl'' а мꙑшиѭ жьми ''Refresh'' или жьми ''Ctrl-F5''
* '''Опєрꙑ''' польꙃєватєльмъ можєть бꙑти ноужда пльнѣ поничьжити ихъ съмотрила съхранъ въ ''Tools → Preferences'' ⁙",
'updated' => '(оновлѥно ѥстъ)',
'note' => "'''НАРОЧИТО:'''",
'editing' => 'исправлѥниѥ: $1',
'creating' => 'сътворѥниѥ ⁖ $1 ⁖',
'editingsection' => 'исправлѥниѥ ⁖ $1 ⁖ (чѧсть)',
'editingcomment' => 'исправлѥниѥ ⁖ $1 ⁖ (нова чѧсть)',
'yourtext' => 'твоѥ напьсаниѥ',
'templatesused' => 'сѥѩ страницѧ {{PLURAL:$1|сь обраꙁьць польꙃоуѥтъ сѧ ѥстъ|с҄и обраꙁьца польꙃоуѭтъ сѧ ѥстє|с҄и обраꙁьци польꙃоуѭтъ сѧ сѫтъ}} :',
'template-protected' => '(ꙁабранєно ѥстъ)',
'template-semiprotected' => '(чѧстьно ꙁабранѥно)',
'hiddencategories' => 'сꙗ страница въ {{PLURAL:$1|1 съкрꙑтѣи катигорїи|$1 съкрꙑтѣхъ катигорїѩ}} сѧ авлꙗѥтъ :',
'postedit-confirmation' => 'твоꙗ мѣна съхранѥна ѥстъ',
# History pages
'viewpagelogs' => 'си страницѧ їсторїѩ',
'cur' => 'нꙑ҃н',
'last' => 'пс҃лд',
'page_first' => 'прьва страница',
'page_last' => 'послѣдьнꙗ страница',
'history-fieldset-title' => 'виждь мѣнъ їсторїѭ',
'history-show-deleted' => 'тъкъмо поничьжєнꙑ мѣнꙑ',
'histfirst' => 'прьвꙑ',
'histlast' => 'послѣдьнꙗ',
'historysize' => '{{PLURAL:$1|1 баитъ|$1 баита|$1 баитъ}}',
'historyempty' => '(поусто)',
# Revision feed
'history-feed-title' => 'мѣнъ їсторїꙗ',
'history-feed-item-nocomment' => '$1 при $2',
# Revision deletion
'rev-deleted-comment' => '(мѣнꙑ опьсаниѥ съкрꙑто ѥстъ)',
'rev-deleted-user' => '(польꙃєватєлꙗ имѧ съкрꙑто ѥстъ)',
'rev-delundel' => 'каꙁаниѥ / съкрꙑтиѥ',
'rev-showdeleted' => 'виждь',
'revdelete-show-file-submit' => 'да',
'revdelete-radio-set' => 'съкрꙑто',
'revdelete-radio-unset' => 'каꙁано',
'revdelete-log' => 'какъ съмꙑслъ :',
'pagehist' => 'страницѧ їсторїꙗ',
'deletedhist' => 'поничьжєна їсторїꙗ',
'revdelete-otherreason' => 'инъ или допльнитєл҄ьнъ съмꙑслъ :',
'revdelete-reasonotherlist' => 'инъ съмꙑслъ',
# History merging
'mergehistory-reason' => 'какъ съмꙑслъ :',
# Search results
'searchresults' => 'исканиꙗ слѣдьствиѥ',
'searchresults-title' => 'исканиꙗ ⁖ $1 ⁖ слѣдьствиѥ',
'viewprevnext' => 'виждь ($1 {{int:pipe-separator}} $2) ($3)',
'searchmenu-exists' => "'''страница имєньмь ⁖ [[:$1]] ⁖ ѥстъ створѥна ю'''",
'searchmenu-new' => "'''страницѫ ⁖ [[:$1]] ⁖ сътворити можєши'''",
'searchprofile-articles' => 'члѣни',
'searchprofile-project' => 'опꙑтьствовании и помощи страницѧ',
'searchprofile-images' => 'дѣла',
'searchprofile-everything' => 'вьсѩ страницѧ',
'searchprofile-articles-tooltip' => 'ищи въ $1',
'searchprofile-project-tooltip' => 'исканиѥ въ $1',
'searchprofile-images-tooltip' => 'исканиѥ дѣлъ',
'searchprofile-everything-tooltip' => 'ищи вьсѩ страницѧ въкоупомь съ бѣсєдꙑ',
'search-result-size' => '$1 ({{PLURAL:$2|$2 слово|$2 слова|$2 словєсъ}})',
'search-redirect' => '(прѣнаправлєниѥ $1)',
'search-section' => '(чѧсть $1)',
'search-suggest' => '⁖ $1 ⁖ мьниши ли',
'search-interwiki-caption' => 'родьствьна опꙑтьствованиꙗ',
'search-interwiki-more' => '(вѧщє)',
'searchall' => 'вьсꙗ',
'search-nonefound' => 'исканиѥ сꙗ слова ничєсо жє нє авило ѥстъ',
'powersearch-redir' => 'прѣнаправлѥниꙗ',
# Preferences page
'preferences' => 'строи',
'mypreferences' => 'строи',
'prefs-edits' => 'мѣнъ число :',
'prefs-datetime' => 'дьнь и врѣмѧ',
'prefs-rc' => 'послѣдьнѩ мѣнꙑ',
'prefs-watchlist' => 'блюдєниꙗ',
'prefs-resetpass' => 'таина словєсє иꙁмѣнѥниѥ',
'saveprefs' => 'съхранѥниѥ',
'prefs-editing' => 'исправлѥниѥ',
'rows' => 'рѧдꙑ :',
'searchresultshead' => 'исканиѥ',
'savedprefs' => 'твои строи иꙁмѣнєнъ ѥстъ',
'localtime' => 'мѣстьно врѣмѧ :',
'guesstimezone' => 'иꙁ твоѥго жє съмотрила врѣмєни обраꙁа поѩтиѥ',
'timezoneregion-africa' => 'Афрїка',
'timezoneregion-america' => 'Амєрїка',
'timezoneregion-antarctica' => 'Антарктїка',
'timezoneregion-arctic' => 'Арктїка',
'timezoneregion-asia' => 'Асїꙗ',
'timezoneregion-atlantic' => 'Атлантїчьскъ ѡкєанъ',
'timezoneregion-australia' => 'Аѵстралїꙗ',
'timezoneregion-europe' => 'Єѵрѡпа',
'timezoneregion-indian' => 'Їндїискъ ѡкєанъ',
'timezoneregion-pacific' => 'Тихꙑи ѡкєанъ',
'prefs-searchoptions' => 'исканиѥ',
'prefs-namespaces' => 'имєнъ просторꙑ',
'prefs-files' => 'дѣла',
'username' => '{{GENDER:$1|польꙃєватєлꙗ имѧ}} :',
'uid' => '{{GENDER:$1|польꙃєватєлꙗ}} число :',
'prefs-memberingroups' => '{{GENDER:$2|польꙃєватєлꙗ}} {{PLURAL:$1|чинъ|чина|чинꙑ}} :',
'yourrealname' => 'истиньно имѧ :',
'yourlanguage' => 'ѩꙁꙑкъ :',
'yournick' => 'новъ аѵтографъ :',
'yourgender' => 'полъ :',
'gender-male' => 'мѫжъ',
'gender-female' => 'жєна',
'prefs-signature' => 'аѵтографъ',
# User rights
'userrights' => 'чина польꙃєватєлꙗ строи',
'userrights-reason' => 'какъ съмꙑслъ :',
# Groups
'group' => 'чинъ :',
'group-user' => 'польꙃєватєлє',
'group-bot' => 'аѵтомати',
'group-sysop' => 'съмотритєлє',
'group-bureaucrat' => 'чинодатєлє',
'group-user-member' => '{{GENDER:$1|польꙃєватєл҄ь|польꙃєватєл҄ьница}}',
'group-bot-member' => '{{GENDER:$1|аѵтоматъ}}',
'group-sysop-member' => '{{GENDER:$1|съмотритєл҄ь}}',
'group-bureaucrat-member' => '{{GENDER:$1|чинодатєл҄ь}}',
'grouppage-user' => '{{ns:project}}:Польꙃєватєлє',
'grouppage-bot' => '{{ns:project}}:Аѵтомати',
'grouppage-sysop' => '{{ns:project}}:Съмотритєлє',
'grouppage-bureaucrat' => '{{ns:project}}:Чинодатєлє',
# Rights
'right-createaccount' => 'новъ польꙃєватєльскъ мѣстъ сътворѥниѥ',
'right-move' => 'прѣимєнованиѥ страницѧ',
'right-movefile' => 'прѣимєнованиѥ дѣлъ',
'right-upload' => 'положєниѥ дѣлъ',
'right-delete' => 'страницѧ поничьжєниѥ',
# Special:Log/newusers
'newuserlogpage' => 'новъ мѣстъ сътворѥниꙗ їсторїꙗ',
# User rights log
'rightslog' => 'чинодатєльства їсторїꙗ',
# Associated actions - in the sentence "You do not have permission to X"
'action-edit' => 'си страницѧ исправлєниѥ',
# Recent changes
'nchanges' => '$1 {{PLURAL:$1|мѣна|мѣнꙑ|мѣнъ}}',
'recentchanges' => 'послѣдьнѩ мѣнꙑ',
'recentchanges-legend' => 'послѣдьн҄ь мѣнъ строи',
'recentchanges-summary' => 'с҄ьдє послѣдьнѩ мѣнꙑ сѥѩ викиопꙑтьствованиꙗ видѣти можєши',
'recentchanges-label-newpage' => 'по сѥи мѣнꙑ нова страница сътворѥна ѥстъ',
'recentchanges-label-minor' => 'малаꙗ мѣна',
'recentchanges-label-bot' => 'сѭ мѣноу аѵтоматъ сътворилъ',
'rcshowhideminor' => '$1 малꙑ мѣнꙑ',
'rcshowhidebots' => '$1 аѵтоматъ',
'rcshowhideliu' => '$1 польꙃєватєлъ · ѩжє съꙁижьдє сѥ мѣсто · мѣнꙑ',
'rcshowhideanons' => '$1 анѡнѷмьнъ польꙃєватєлъ мѣнꙑ',
'rcshowhidemine' => '$1 моꙗ мѣнꙑ',
'rclinks' => '$1 послѣдьн҄ь мѣнъ · ѩжє $2 послѣдьни дьни створѥнꙑ сѫтъ · каꙁаниѥ<br />$3',
'diff' => 'ра҃ꙁн',
'hist' => 'їс҃т',
'hide' => 'съкрꙑи',
'show' => 'виждь',
'minoreditletter' => 'м҃л',
'newpageletter' => 'н҃в',
'boteditletter' => 'а҃ѵ',
'rc-old-title' => 'напрьва страница створѥна ꙗко ⁖ $1 ⁖',
# Recent changes linked
'recentchangeslinked' => 'съвѧꙁанꙑ страницѧ',
'recentchangeslinked-feed' => 'съвѧꙁанꙑ страницѧ',
'recentchangeslinked-toolbox' => 'съвѧꙁанꙑ страницѧ',
'recentchangeslinked-page' => 'страницѧ имѧ :',
# Upload
'upload' => 'положєниѥ дѣла',
'uploadbtn' => 'положєниѥ дѣла',
'uploadlog' => 'дѣлъ положєниꙗ їсторїꙗ',
'uploadlogpage' => 'дѣлъ положєниꙗ їсторїꙗ',
'filename' => 'дѣла имѧ',
'filedesc' => 'опьсаниѥ',
'fileuploadsummary' => 'опьсаниѥ:',
'savefile' => 'дѣла съхранѥниѥ',
'uploadedimage' => '⁖ [[$1]] ⁖ положєнъ ѥстъ',
'overwroteimage' => 'новъ обраꙁъ ⁖ [[$1]] ⁖ положєнъ ѥстъ',
'upload-source' => 'источьно дѣло',
'sourcefilename' => 'источьна дѣла имꙗ :',
'watchthisupload' => 'си дѣла блюдєниѥ',
'upload-success-subj' => 'дѣло положєно ѥстъ',
'license' => 'прощєниѥ :',
'license-header' => 'прощєниѥ',
# Special:ListFiles
'imgfile' => 'дѣло',
'listfiles' => 'дѣлъ каталогъ',
'listfiles_name' => 'имѧ',
'listfiles_user' => 'польꙃєватєл҄ь',
'listfiles_size' => 'мѣра',
# File description page
'file-anchor-link' => 'дѣло',
'filehist' => 'дѣла їсторїꙗ',
'filehist-deleteone' => 'поничьжєниѥ',
'filehist-current' => 'нꙑнѣщьн҄ь обраꙁъ',
'filehist-datetime' => 'дьнь / врѣмѧ',
'filehist-thumb' => 'малъ обраꙁъ',
'filehist-user' => 'польꙃєватєл҄ь',
'filehist-dimensions' => 'мѣра',
'filehist-filesize' => 'дѣла мѣра',
'filehist-comment' => 'опьсаниѥ',
'imagelinks' => 'дѣла польꙃєваниѥ',
'sharedupload' => 'сѥ дѣло въ $1 съхранѥно ѥстъ дѣла · ѥгожє дроугꙑ опꙑтьствованиѩ польꙃєвати могѫтъ',
# File reversion
'filerevert-comment' => 'какъ съмꙑслъ :',
# File deletion
'filedelete' => 'поничьжєниѥ $1',
'filedelete-legend' => 'дѣла поничьжєниѥ',
'filedelete-comment' => 'какъ съмꙑслъ :',
'filedelete-submit' => 'поничьжєниѥ',
# MIME search
'mimetype' => 'MIME тѷпъ :',
'download' => 'поѩти',
# List redirects
'listredirects' => 'прѣнаправлѥниꙗ',
# Random page
'randompage' => 'страница въ нєꙁаапѫ',
# Random redirect
'randomredirect' => 'прѣнаправлѥниє въ нєꙁаапѫ',
# Statistics
'statistics' => 'статїстїка',
'statistics-header-pages' => 'страницѧ статїстїка',
'statistics-header-edits' => 'мѣнъ статїстїка',
'statistics-header-users' => 'польꙃєватєлъ статїстїка',
'statistics-articles' => 'истиньнꙑ члѣни',
'statistics-pages' => 'страницѧ',
'statistics-pages-desc' => 'вьсѩ страницѧ въкоупомь съ бѣсєдꙑ · прѣнаправлѥниꙗ и инꙑ',
'statistics-files' => 'положєнꙑ дѣла',
'statistics-users-active' => 'дѣꙗтєльнꙑ польꙃєватєлє',
'brokenredirects-edit' => 'исправи',
'brokenredirects-delete' => 'поничьжєниѥ',
# Miscellaneous special pages
'nbytes' => '$1 {{PLURAL:$1|баитъ|баита|баитъ}}',
'ncategories' => '$1 {{PLURAL:$1|катигорїꙗ|катигорїи|катигорїѩ}}',
'nlinks' => '$1 {{PLURAL:$1|съвѧꙁь|съвѧꙁи|съвѧꙁии}}',
'nmembers' => '$1 {{PLURAL:$1|члѣнъ|члѣна|члѣни|члѣнъ}}',
'shortpages' => 'кратъкꙑ страницѧ',
'listusers' => 'польꙃєватєлъ каталогъ',
'usereditcount' => '$1 {{PLURAL:$1|мѣна|мѣнꙑ|мѣнъ}}',
'usercreated' => '{{GENDER:$3|сътворилъ|сътворила}} мѣсто $1 въ $2',
'newpages' => 'нови члѣни',
'newpages-username' => 'польꙃєватєлꙗ имѧ :',
'ancientpages' => 'давьни страницѧ',
'move' => 'прѣимєнованиѥ',
'movethispage' => 'си страницѧ прѣимєнованиѥ',
'pager-newer-n' => '{{PLURAL:$1|нова 1|новꙑ $1|новъ $1}}',
'pager-older-n' => '{{PLURAL:$1|давьнꙗ 1|давьни $1|давьн҄ь $1}}',
# Book sources
'booksources-go' => 'прѣиди',
# Special:Log
'specialloguserlabel' => 'испльнитєл҄ь :',
'speciallogtitlelabel' => 'страницѧ или польꙃєватєлꙗ имѧ :',
'log' => 'їсторїѩ',
'all-logs-page' => 'вьсѩ обьщѧ їсторїѩ',
# Special:AllPages
'allpages' => 'вьсѩ страницѧ',
'alphaindexline' => 'отъ $1 до $2',
'allpagesfrom' => 'страницѧ видѣти хощѫ съ начѧльнами боукъвами :',
'allarticles' => 'вьсѩ страницѧ',
'allpagessubmit' => 'прѣиди',
# Special:Categories
'categories' => 'катигорїѩ',
# Special:DeletedContributions
'deletedcontributions' => 'поничьжєнꙑ добродѣꙗниꙗ',
'deletedcontributions-title' => 'поничьжєнꙑ добродѣꙗниꙗ',
'sp-deletedcontributions-contribs' => 'добродѣꙗниꙗ',
# Special:LinkSearch
'linksearch' => 'вънѣщьн҄ь съвѧꙁь исканиѥ',
'linksearch-ns' => 'имєнъ просторъ :',
'linksearch-ok' => 'ищи',
# Special:ListUsers
'listusers-submit' => 'виждь',
# Special:ListGroupRights
'listgrouprights-members' => '(польꙃєватєлъ каталогъ)',
# Email user
'emailuser' => 'посъли єпїстолѫ',
'emailusername' => 'польꙃєватєлꙗ имѧ :',
'emailfrom' => 'отъ :',
'emailto' => 'къ :',
'emailsubject' => 'ѳєма :',
'emailmessage' => 'напьсаниє :',
'emailsend' => 'посъли',
# Watchlist
'watchlist' => 'блюдєниꙗ',
'mywatchlist' => 'блюдєниꙗ',
'watchlistfor2' => 'дѣлꙗ ⁖ $1 ⁖ $2',
'addedwatchtext' => 'страница ⁖ [[:$1]] ⁖ нꙑнѣ подъ твоимь [[Special:Watchlist|блюдєниѥмь]] ѥстъ ⁙
всꙗ ѥѩ и ѥѩжє бєсѣдꙑ страницѧ мѣнꙑ твоꙗ блюдєнии каталоꙃѣ покаꙁанꙑ бѫдѫтъ',
'removedwatchtext' => 'страница ⁖ [[:$1]] ⁖ нꙑнѣ твоѥго [[Special:Watchlist|блюдєниꙗ]] иꙁнєсєна ѥстъ',
'watch' => 'блюдєниѥ',
'watchthispage' => 'си страницѧ блюдєниѥ',
'unwatch' => 'остави блюдєниѥ',
'watchlist-options' => 'блюдєниѩ строи',
# Displayed when you click the "watch" button and it is in the process of watching
'watching' => 'блюдєниѥ ...',
'unwatching' => 'оставьлєниѥ блюдєниꙗ ...',
'created' => 'сътворѥнъ ѥстъ',
# Delete
'deletepage' => 'поничьжєниѥ',
'excontent' => "вънѫтри бѣ: '$1'",
'excontentauthor' => "вънѫтри бѣ : '$1' (и послѣдьн҄ии дѣтєл҄ь бѣ '[[Special:Contributions/$2|$2]]')",
'delete-legend' => 'поничьжєниѥ',
'actioncomplete' => 'дѣиство сътворєно ѥстъ',
'deletedtext' => 'страница ⁖ $1 ⁖ поничьжєна ѥстъ ⁙
виждь ⁖ $2 ⁖ послѣдьнъ поничьжєниѩ дѣлꙗ',
'dellogpage' => 'поничьжєниꙗ їсторїꙗ',
'deletionlog' => 'поничьжєниꙗ їсторїꙗ',
'deletecomment' => 'какъ съмꙑслъ :',
# Protect
'protectlogpage' => 'ꙁабранѥниꙗ їсторїꙗ',
'protectedarticle' => '⁖ [[$1]] ⁖ ꙁабранѥна ѥстъ',
'prot_1movedto2' => '⁖ [[$1]] ⁖ нарєчєнъ ⁖ [[$2]] ⁖ ѥстъ',
'protectcomment' => 'какъ съмꙑслъ :',
'protect-level-sysop' => 'толико съмотритєлє',
'protect-othertime' => 'ино врѣмѧ :',
'protect-othertime-op' => 'ино врѣмѧ',
'protect-otherreason-op' => 'инъ съмꙑслъ',
'protect-expiry-options' => '1 часъ:1 hour,1 дьнь:1 day,1 сєдмица:1 week,2 сєдмици:2 weeks,1 мѣсѧць:1 month,3 мѣсѧць:3 months,6 мѣсѧць:6 months,1 лѣто:1 year,вѣчьно:infinite',
'pagesize' => '(баитъ)',
# Restrictions (nouns)
'restriction-edit' => 'исправи',
'restriction-move' => 'прѣимєнованиѥ',
'restriction-upload' => 'положєниѥ',
# Undelete
'undeletecomment' => 'какъ съмꙑслъ :',
'undelete-search-submit' => 'ищи',
'undelete-show-file-submit' => 'да',
# Namespace form on various pages
'namespace' => 'имєнъ просторъ:',
'invert' => 'обрати иꙁборъ',
'namespace_association' => 'съвѧꙁанꙑ имєнъ просторꙑ',
'blanknamespace' => '(главьно)',
# Contributions
'contributions' => '{{GENDER:$1|польꙃєватєлꙗ}} добродѣꙗниꙗ',
'contributions-title' => 'польꙃєватєлꙗ ⁖ $1 ⁖ добродѣꙗниꙗ',
'mycontris' => 'добродѣꙗниꙗ',
'contribsub2' => 'польꙃєватєлꙗ имѧ ⁖ {{GENDER:$3|$1}} ⁖ ѥстъ ($2)',
'uctop' => '(нꙑнѣщьн҄ь обраꙁъ)',
'sp-contributions-blocklog' => 'ꙁаграждєниꙗ їсторїꙗ',
'sp-contributions-deleted' => 'поничьжєнꙑ добродѣꙗниꙗ',
'sp-contributions-uploads' => 'положєнꙑ дѣла',
'sp-contributions-logs' => 'їсторїѩ',
'sp-contributions-talk' => 'бєсѣда',
'sp-contributions-username' => 'IP число или польꙃєватєлꙗ имѧ :',
'sp-contributions-submit' => 'ищи',
# What links here
'whatlinkshere' => 'дос҄ьдєщьнѩ съвѧꙁи',
'whatlinkshere-title' => 'страницѧ ижє съ ⁖ $1 ⁖ съвѧꙁи имѫтъ',
'whatlinkshere-page' => 'страница :',
'isredirect' => 'прѣнаправлѥниѥ',
'istemplate' => 'внѫтри страницѧ',
'isimage' => 'дѣла съвѧꙁь',
'whatlinkshere-links' => '← съвѧꙁи',
'whatlinkshere-hideredirs' => '$1 прѣнаправлѥниꙗ',
'whatlinkshere-hidelinks' => '$1 съвѧꙁи',
'whatlinkshere-filters' => 'ситꙑ',
# Block/unblock
'block' => 'ꙁагради польꙃєватєл҄ь',
'blockip' => 'ꙁагради польꙃєватєл҄ь',
'blockip-legend' => 'ꙁагради польꙃєватєл҄ь',
'ipadressorusername' => 'IP число или польꙃєватєлꙗ имѧ :',
'ipbreason' => 'какъ съмꙑслъ :',
'ipbother' => 'ино врѣмѧ :',
'ipboptions' => '2 часа:2 hours,1 дьнь:1 day,3 дьни:3 days,1 сєдмица:1 week,2 сєдмици:2 weeks,1 мѣсѧць:1 month,3 мѣсѧць:3 months,6 мѣсѧць:6 months,1 лѣто:1 year,вѣчьно:infinite',
'ipblocklist' => 'ꙁаграждєнꙑ польꙃєватєлє',
'blocklist-reason' => 'какъ съмꙑслъ',
'ipblocklist-submit' => 'исканиѥ',
'infiniteblock' => 'вѣчьно',
'anononlyblock' => 'тъкъмо анѡнѷмꙑ',
'blocklink' => 'ꙁагради',
'contribslink' => 'добродѣꙗниꙗ',
'blocklogpage' => 'ꙁаграждєниꙗ їсторїꙗ',
'blocklogentry' => 'ꙁаградилъ [[$1]] на врѣмѧ $2 $3',
'block-log-flags-anononly' => 'тъкъмо анѡнѷмьнꙑ польꙃєватєлє',
# Move page
'move-page' => 'прѣимєнованиѥ ⁖ $1 ⁖',
'move-page-legend' => 'страницѧ прѣимєнованиѥ',
'movearticle' => 'страница :',
'newtitle' => 'ново имѧ :',
'move-watch' => 'си страницѧ блюдєниѥ',
'movepagebtn' => 'прѣимєнованиѥ',
'pagemovedsub' => 'прѣимєнованиѥ сътворѥно ѥстъ',
'movepage-moved' => "'''⁖ $1 ⁖ нарєчєнъ ⁖ $2⁖ ѥстъ'''",
'movepage-moved-redirect' => 'прѣнаправлѥниѥ сътворѥно бѣ',
'movetalk' => 'си страницѧ бєсѣдꙑ прѣимєнованиѥ',
'movelogpage' => 'прѣимєнованиꙗ їсторїꙗ',
'movereason' => 'какъ съмꙑслъ :',
'move-leave-redirect' => 'прѣнаправлѥниꙗ сътворѥниѥ',
# Namespace 8 related
'allmessages' => 'сѷстимьнꙑ напьсаниꙗ',
'allmessagesname' => 'имѧ',
'allmessages-language' => 'ѩꙁꙑкъ :',
'allmessages-filter-submit' => 'прѣиди',
# Special:Import
'import-upload-filename' => 'дѣла имѧ :',
# JavaScriptTest
'javascripttest' => 'искоушєниѥ ⁖ JavaScript ⁖',
# Tooltip help for the actions
'tooltip-pt-userpage' => 'твоꙗ польꙃєватєл҄ьска страница',
'tooltip-pt-mytalk' => 'твоꙗ бєсѣдꙑ страница',
'tooltip-pt-preferences' => 'твои строи',
'tooltip-pt-mycontris' => 'твоѩ добродѣꙗнии каталогъ',
'tooltip-pt-logout' => 'ис̾ходъ',
'tooltip-ca-talk' => 'си страницѧ бєсѣда',
'tooltip-ca-viewsource' => 'си страница ꙁабранєна ѥстъ ⁙
ѥѩ источьнъ обраꙁъ видєти можєши',
'tooltip-ca-protect' => 'си страницѧ ꙁабранєниѥ',
'tooltip-ca-delete' => 'си страницѧ поничьжєниѥ',
'tooltip-ca-move' => 'си страницѧ прѣимєнованиѥ',
'tooltip-ca-watch' => 'си страницѧ блюдєниѥ',
'tooltip-search' => 'ищи {{{grammar:genitive|{{SITENAME}}}}} страницѧ',
'tooltip-p-logo' => 'главьна страница',
'tooltip-n-mainpage' => 'виждь главьноу страницѫ',
'tooltip-n-mainpage-description' => 'виждь главьноу страницѫ',
'tooltip-n-recentchanges' => 'послѣдьн҄ь мѣнъ каталогъ',
'tooltip-t-contributions' => 'виждь польꙃєватєлꙗ добродѣꙗнии каталогъ',
'tooltip-t-upload' => 'положєниѥ дѣлъ',
'tooltip-t-specialpages' => 'вьсѣѩ нарочьнъ страницѧ каталогъ',
'tooltip-t-print' => 'сѥѩ страницѧ пєчатьнъ обраꙁъ',
'tooltip-ca-nstab-special' => 'си нарочьна страница ѥстъ · ѥѩжє иꙁмѣнꙗти нє можєши',
'tooltip-ca-nstab-image' => 'виждь дѣла страницѫ',
'tooltip-ca-nstab-category' => 'виждь катигорїѩ страницѫ',
'tooltip-minoredit' => 'оꙁначи ꙗко малоу мѣноу',
'tooltip-save' => 'твоѩ мѣнъ съхранѥниѥ',
'tooltip-watch' => 'си страницѧ блюдєниѥ',
# Info page
'pageinfo-header-edits' => 'мѣнъ їсторїꙗ',
'pageinfo-header-restrictions' => 'страницѧ ꙁабранѥниѥ',
'pageinfo-firstuser' => 'страницѧ творьць',
'pageinfo-toolboxlink' => 'страницѧ плирофорїꙗ',
'pageinfo-contentpage-yes' => 'да',
'pageinfo-protect-cascading-yes' => 'да',
'pageinfo-category-pages' => 'страницѩ число',
'pageinfo-category-files' => 'дѣлъ число',
# Browsing diffs
'previousdiff' => '← давьнꙗ мѣна',
'nextdiff' => 'нова мѣна →',
# Media information
'file-info-size' => '$1 × $2 п҃ѯ · дѣла мѣра : $3 · MIME тѷпъ : $4',
'svg-long-desc' => 'дѣло SVG · обꙑчьнъ обраꙁъ : $1 × $2 п҃ѯ · дѣла мѣра : $3',
'show-big-image' => 'источьнъ дѣла обраꙁъ',
'show-big-image-size' => '$1 × $2 пиѯєлъ',
# Special:NewFiles
'showhidebots' => '($1 аѵтоматъ)',
'ilsubmit' => 'ищи',
# Human-readable timestamps
'monday-at' => 'понєдѣл҄ьникъ · $1',
'tuesday-at' => 'въторьникъ · $1',
'wednesday-at' => 'срѣда · $1',
'thursday-at' => 'чєтврьтъкъ · $1',
'friday-at' => 'пѧтъкъ · $1',
'saturday-at' => 'сѫбота · $1',
'sunday-at' => 'нєдѣлꙗ · $1',
'yesterday-at' => 'вьчєра · $1',
# Exif tags
'exif-artist' => 'творьць',
'exif-languagecode' => 'ѩꙁꙑкъ',
'exif-iimcategory' => 'катигорїꙗ',
# Pseudotags used for GPSSpeedRef
'exif-gpsspeed-k' => 'хїлїомєтрꙑ ꙁа часъ',
# Pseudotags used for GPSDestDistanceRef
'exif-gpsdestdistance-k' => 'хїлїомєтрꙑ',
'exif-iimcategory-edu' => 'навꙑканиѥ',
'exif-iimcategory-hth' => 'съдравиѥ',
'exif-iimcategory-pol' => 'полїтїка',
'exif-iimcategory-rel' => 'вѣра',
'exif-iimcategory-sci' => 'оучєниѥ и тєхнологїꙗ',
'exif-iimcategory-spo' => 'аѳлитїка',
# 'all' in various places, this might be different for inflected languages
'watchlistall2' => 'вьсꙗ',
'namespacesall' => 'вьсꙗ',
'monthsall' => 'вьсѩ',
'unit-pixel' => 'п҃ѯ',
# Multipage image navigation
'imgmultigo' => 'прѣиди',
# Table pager
'table_pager_limit_submit' => 'прѣиди',
# Auto-summaries
'autosumm-new' => 'нова страница ⁖ $1 ⁖ сътворєна ѥстъ',
# Size units
'size-bytes' => '$1 Б҃',
'size-kilobytes' => '$1 Х҃Б',
# Signatures
'signature' => '[[{{ns:user}}:$1|$2]] ([[{{ns:user_talk}}:$1|бєсѣда]])',
# Special:Version
'version' => 'MediaWiki обраꙁъ',
'version-specialpages' => 'нарочьнꙑ страницѧ',
'version-version' => '(обраꙁъ $1)',
'version-license' => 'прощєниѥ',
'version-software-version' => 'обраꙁъ',
# Special:Redirect
'redirect-submit' => 'прѣиди',
'redirect-file' => 'дѣла имѧ',
# Special:FileDuplicateSearch
'fileduplicatesearch-filename' => 'дѣла имѧ :',
'fileduplicatesearch-submit' => 'ищи',
# Special:SpecialPages
'specialpages' => 'нарочьнꙑ страницѧ',
# Special:Tags
'tag-filter' => '[[Special:Tags|мѣтъць]] сито :',
'tags-edit' => 'исправи',
# Database error messages
'dberr-header' => 'Вики тєхнїчьнꙑ отѧжєниꙗ имѣтъ',
# HTML forms
'htmlform-no' => 'нѣтъ',
'htmlform-yes' => 'да',
# New logging system
'logentry-delete-delete' => '$1 {{GENDER:$2|поничьжилъ|поничьжила}} страницѫ ⁖ $3 ⁖',
'logentry-move-move' => '$1 {{GENDER:$2|нарєчє}} страницѫ ⁖ $3 ⁖ имєньмь ⁖ $4 ⁖',
'logentry-move-move-noredirect' => '$1 {{GENDER:$2|нарєчє}} страницѫ ⁖ $3 ⁖ имєньмь ⁖ $4 ⁖ бєꙁ прѣнаправлєниꙗ сътворѥниꙗ',
'logentry-newusers-create' => 'польꙃєватєльско мѣсто ⁖ $1 ⁖ {{GENDER:$2|сътворѥно}} ѥстъ',
# Search suggestions
'searchsuggest-search' => 'исканиѥ',
'searchsuggest-containing' => 'сѥ дрьжащи···',
# API errors
'api-error-unknownerror' => 'нєвѣдома блаꙁна : ⁖ $1 ⁖',
);
| iSCInc/mediawiki-core | languages/messages/MessagesCu.php | PHP | gpl-2.0 | 46,207 |
"""
Represents a group of conduits
Copyright: John Stowers, 2007
License: GPLv2
"""
import traceback
import os
import xml.dom.minidom
import gobject
import logging
log = logging.getLogger("SyncSet")
import conduit
import conduit.Conduit as Conduit
import conduit.Settings as Settings
import conduit.XMLSerialization as XMLSerialization
SETTINGS_VERSION = XMLSerialization.Settings.XML_VERSION
class SyncSet(gobject.GObject):
"""
Represents a group of conduits
"""
__gsignals__ = {
#Fired when a new instantiatable DP becomes available. It is described via
#a wrapper because we do not actually instantiate it till later - to save memory
"conduit-added" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [
gobject.TYPE_PYOBJECT]), # The ConduitModel that was added
"conduit-removed" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [
gobject.TYPE_PYOBJECT]), # The ConduitModel that was removed
}
def __init__(self, moduleManager, syncManager, xmlSettingFilePath="settings.xml"):
gobject.GObject.__init__(self)
self.moduleManager = moduleManager
self.syncManager = syncManager
self.xmlSettingFilePath = xmlSettingFilePath
self.conduits = []
self.moduleManager.connect("dataprovider-available", self.on_dataprovider_available_unavailable)
self.moduleManager.connect("dataprovider-unavailable", self.on_dataprovider_available_unavailable)
# FIXME: temporary hack - need to let factories know about this factory :-\!
self.moduleManager.emit("syncset-added", self)
def _restore_dataprovider(self, cond, wrapperKey, dpName="", dpxml="", trySourceFirst=True):
"""
Adds the dataprovider back onto the canvas at the specifed
location and configures it with the given settings
"""
log.debug("Restoring %s to (source=%s)" % (wrapperKey,trySourceFirst))
wrapper = self.moduleManager.get_module_wrapper_with_instance(wrapperKey)
if dpName:
wrapper.set_name(dpName)
if wrapper is not None:
if dpxml:
for i in dpxml.childNodes:
if i.nodeType == i.ELEMENT_NODE and i.localName == "configuration":
wrapper.set_configuration_xml(xmltext=i.toxml())
cond.add_dataprovider(wrapper, trySourceFirst)
def on_dataprovider_available_unavailable(self, loader, dpw):
"""
Removes all PendingWrappers corresponding to dpw and replaces with new dpw instances
"""
key = dpw.get_key()
for c in self.get_all_conduits():
for dp in c.get_dataproviders_by_key(key):
new = self.moduleManager.get_module_wrapper_with_instance(key)
#retain configuration information
new.set_configuration_xml(dp.get_configuration_xml())
new.set_name(dp.get_name())
c.change_dataprovider(
oldDpw=dp,
newDpw=new
)
def emit(self, *args):
"""
Override the gobject signal emission so that all signals are emitted
from the main loop on an idle handler
"""
gobject.idle_add(gobject.GObject.emit,self,*args)
def create_preconfigured_conduit(self, sourceKey, sinkKey, twoway):
cond = Conduit.Conduit(self.syncManager)
self.add_conduit(cond)
if twoway == True:
cond.enable_two_way_sync()
self._restore_dataprovider(cond, sourceKey, trySourceFirst=True)
self._restore_dataprovider(cond, sinkKey, trySourceFirst=False)
def add_conduit(self, cond):
self.conduits.append(cond)
self.emit("conduit-added", cond)
def remove_conduit(self, cond):
self.emit("conduit-removed", cond)
cond.quit()
self.conduits.remove(cond)
def get_all_conduits(self):
return self.conduits
def get_conduit(self, index):
return self.conduits[index]
def index (self, conduit):
return self.conduits.index(conduit)
def num_conduits(self):
return len(self.conduits)
def clear(self):
for c in self.conduits[:]:
self.remove_conduit(c)
def save_to_xml(self, xmlSettingFilePath=None):
"""
Saves the synchronisation settings (icluding all dataproviders and how
they are connected) to an xml file so that the 'sync set' can
be restored later
"""
if xmlSettingFilePath == None:
xmlSettingFilePath = self.xmlSettingFilePath
log.info("Saving Sync Set to %s" % self.xmlSettingFilePath)
#Build the application settings xml document
doc = xml.dom.minidom.Document()
rootxml = doc.createElement("conduit-application")
rootxml.setAttribute("application-version", conduit.VERSION)
rootxml.setAttribute("settings-version", SETTINGS_VERSION)
doc.appendChild(rootxml)
#Store the conduits
for cond in self.conduits:
conduitxml = doc.createElement("conduit")
conduitxml.setAttribute("uid",cond.uid)
conduitxml.setAttribute("twoway",str(cond.is_two_way()))
conduitxml.setAttribute("autosync",str(cond.do_auto_sync()))
for policyName in Conduit.CONFLICT_POLICY_NAMES:
conduitxml.setAttribute(
"%s_policy" % policyName,
cond.get_policy(policyName)
)
rootxml.appendChild(conduitxml)
#Store the source
source = cond.datasource
if source is not None:
sourcexml = doc.createElement("datasource")
sourcexml.setAttribute("key", source.get_key())
sourcexml.setAttribute("name", source.get_name())
conduitxml.appendChild(sourcexml)
#Store source settings
configxml = xml.dom.minidom.parseString(source.get_configuration_xml())
sourcexml.appendChild(configxml.documentElement)
#Store all sinks
sinksxml = doc.createElement("datasinks")
for sink in cond.datasinks:
sinkxml = doc.createElement("datasink")
sinkxml.setAttribute("key", sink.get_key())
sinkxml.setAttribute("name", sink.get_name())
sinksxml.appendChild(sinkxml)
#Store sink settings
configxml = xml.dom.minidom.parseString(sink.get_configuration_xml())
sinkxml.appendChild(configxml.documentElement)
conduitxml.appendChild(sinksxml)
#Save to disk
try:
file_object = open(xmlSettingFilePath, "w")
file_object.write(doc.toxml())
#file_object.write(doc.toprettyxml())
file_object.close()
except IOError, err:
log.warn("Could not save settings to %s (Error: %s)" % (xmlSettingFilePath, err.strerror))
def restore_from_xml(self, xmlSettingFilePath=None):
"""
Restores sync settings from the xml file
"""
if xmlSettingFilePath == None:
xmlSettingFilePath = self.xmlSettingFilePath
log.info("Restoring Sync Set from %s" % xmlSettingFilePath)
#Check the file exists
if not os.path.isfile(xmlSettingFilePath):
log.info("%s not present" % xmlSettingFilePath)
return
try:
#Open
doc = xml.dom.minidom.parse(xmlSettingFilePath)
#check the xml file is in a version we can read.
if doc.documentElement.hasAttribute("settings-version"):
xml_version = doc.documentElement.getAttribute("settings-version")
try:
xml_version = int(xml_version)
except ValueError, TypeError:
log.error("%s xml file version is not valid" % xmlSettingFilePath)
os.remove(xmlSettingFilePath)
return
if int(SETTINGS_VERSION) < xml_version:
log.warning("%s xml file is incorrect version" % xmlSettingFilePath)
os.remove(xmlSettingFilePath)
return
else:
log.info("%s xml file version not found, assuming too old, removing" % xmlSettingFilePath)
os.remove(xmlSettingFilePath)
return
#Parse...
for conds in doc.getElementsByTagName("conduit"):
#create a new conduit
cond = Conduit.Conduit(self.syncManager, conds.getAttribute("uid"))
self.add_conduit(cond)
#restore conduit specific settings
twoway = Settings.string_to_bool(conds.getAttribute("twoway"))
if twoway == True:
cond.enable_two_way_sync()
auto = Settings.string_to_bool(conds.getAttribute("autosync"))
if auto == True:
cond.enable_auto_sync()
for policyName in Conduit.CONFLICT_POLICY_NAMES:
cond.set_policy(
policyName,
conds.getAttribute("%s_policy" % policyName)
)
#each dataprovider
for i in conds.childNodes:
#keep a ref to the dataproider was added to so that we
#can apply settings to it at the end
#one datasource
if i.nodeType == i.ELEMENT_NODE and i.localName == "datasource":
key = i.getAttribute("key")
name = i.getAttribute("name")
#add to canvas
if len(key) > 0:
self._restore_dataprovider(cond, key, name, i, True)
#many datasinks
elif i.nodeType == i.ELEMENT_NODE and i.localName == "datasinks":
#each datasink
for sink in i.childNodes:
if sink.nodeType == sink.ELEMENT_NODE and sink.localName == "datasink":
key = sink.getAttribute("key")
name = sink.getAttribute("name")
#add to canvas
if len(key) > 0:
self._restore_dataprovider(cond, key, name, sink, False)
except:
log.warn("Error parsing %s. Exception:\n%s" % (xmlSettingFilePath, traceback.format_exc()))
os.remove(xmlSettingFilePath)
def quit(self):
"""
Calls unitialize on all dataproviders
"""
for c in self.conduits:
c.quit()
| GNOME/conduit | conduit/SyncSet.py | Python | gpl-2.0 | 11,163 |
#
# Copyright 2014-2020 Red Hat, Inc.
#
# 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
#
# Refer to the README and COPYING files for full details of the license
#
from __future__ import absolute_import
from __future__ import division
import six
from vdsm.common import exception
from vdsm.common import xmlutils
from vdsm.virt.vmdevices import network, hwclass
from testlib import VdsmTestCase as TestCaseBase, XMLTestCase
from testlib import permutations, expandPermutations
from monkeypatch import MonkeyClass, MonkeyPatchScope
from testValidation import skipif
from vdsm.common import hooks
from vdsm.common import hostdev
from vdsm.common import libvirtconnection
import hostdevlib
@expandPermutations
@MonkeyClass(libvirtconnection, 'get', hostdevlib.Connection)
@MonkeyClass(hostdev, '_sriov_totalvfs', hostdevlib.fake_totalvfs)
@MonkeyClass(hostdev, '_pci_header_type', lambda _: 0)
@MonkeyClass(hooks, 'after_hostdev_list_by_caps', lambda json: json)
@MonkeyClass(hostdev, '_get_udev_block_mapping',
lambda: hostdevlib.UDEV_BLOCK_MAP)
class HostdevTests(TestCaseBase):
def testProcessDeviceParams(self):
deviceXML = hostdev._process_device_params(
libvirtconnection.get().nodeDeviceLookupByName(
hostdevlib.ADDITIONAL_DEVICE).XMLDesc()
)
self.assertEqual(
hostdevlib.ADDITIONAL_DEVICE_PROCESSED,
deviceXML
)
@skipif(six.PY3, "Not relevant in Python 3 libvirt")
# libvirt in Python 3 returns strings, so we don't deal with
# invalid coding anymore.
def testProcessDeviceParamsInvalidEncoding(self):
deviceXML = hostdev._process_device_params(
libvirtconnection.get().nodeDeviceLookupByName(
hostdevlib.COMPUTER_DEVICE).XMLDesc()
)
self.assertEqual(
hostdevlib.COMPUTER_DEVICE_PROCESSED,
deviceXML
)
def testProcessSRIOV_PFDeviceParams(self):
deviceXML = hostdev._process_device_params(
libvirtconnection.get().nodeDeviceLookupByName(
hostdevlib.SRIOV_PF).XMLDesc()
)
self.assertEqual(
hostdevlib.SRIOV_PF_PROCESSED,
deviceXML
)
def testProcessSRIOV_VFDeviceParams(self):
deviceXML = hostdev._process_device_params(
libvirtconnection.get().nodeDeviceLookupByName(
hostdevlib.SRIOV_VF).XMLDesc()
)
self.assertEqual(hostdevlib.SRIOV_VF_PROCESSED, deviceXML)
def testProcessNetDeviceParams(self):
deviceXML = hostdev._process_device_params(
libvirtconnection.get().nodeDeviceLookupByName(
hostdevlib.NET_DEVICE).XMLDesc()
)
self.assertEqual(hostdevlib.NET_DEVICE_PROCESSED, deviceXML)
def testProcessMdevDeviceParams(self):
deviceXML = hostdev._process_device_params(
libvirtconnection.get().nodeDeviceLookupByName(
hostdevlib.MDEV_DEVICE).XMLDesc()
)
self.assertEqual(hostdevlib.MDEV_DEVICE_PROCESSED, deviceXML)
def testGetDevicesFromLibvirt(self):
libvirt_devices, _ = hostdev._get_devices_from_libvirt()
self.assertEqual(hostdevlib.DEVICES_PROCESSED, libvirt_devices)
self.assertEqual(len(libvirt_devices),
len(hostdevlib.PCI_DEVICES) +
len(hostdevlib.USB_DEVICES) +
len(hostdevlib.SCSI_DEVICES))
@permutations([[''], [('pci',)], [('usb_device',)],
[('pci', 'usb_device')]])
def testListByCaps(self, caps):
devices = hostdev.list_by_caps(caps)
for cap in caps:
self.assertTrue(set(hostdevlib.DEVICES_BY_CAPS[cap].keys()).
issubset(set(devices.keys())))
@permutations([
# addr_type, addr, name
('usb', {'bus': '1', 'device': '2'}, 'usb_1_1'),
('usb', {'bus': '1', 'device': '10'}, 'usb_1_1_4'),
('pci', {'slot': '26', 'bus': '0', 'domain': '0', 'function': '0'},
'pci_0000_00_1a_0'),
('scsi', {'bus': '0', 'host': '1', 'lun': '0', 'target': '0'},
'scsi_1_0_0_0'),
])
def test_device_name_from_address(self, addr_type, addr, name):
# we need to make sure we scan all the devices (hence caps=None)
hostdev.list_by_caps()
self.assertEqual(
hostdev.device_name_from_address(addr_type, addr),
name
)
@MonkeyClass(libvirtconnection, 'get', hostdevlib.Connection.get)
@MonkeyClass(hostdev, '_sriov_totalvfs', hostdevlib.fake_totalvfs)
@MonkeyClass(hostdev, '_pci_header_type', lambda _: 0)
@MonkeyClass(hooks, 'after_hostdev_list_by_caps', lambda json: json)
class HostdevPerformanceTests(TestCaseBase):
def test_3k_storage_devices(self):
with hostdevlib.Connection.use_hostdev_tree():
self.assertEqual(
len(hostdev.list_by_caps()),
len(libvirtconnection.get().listAllDevices())
)
@expandPermutations
@MonkeyClass(libvirtconnection, 'get', hostdevlib.Connection)
@MonkeyClass(hostdev, '_sriov_totalvfs', hostdevlib.fake_totalvfs)
@MonkeyClass(hostdev, '_pci_header_type', lambda _: 0)
class HostdevCreationTests(XMLTestCase):
_PCI_ADDRESS = {'slot': '0x02', 'bus': '0x01', 'domain': '0x0000',
'function': '0x0', 'type': 'pci'}
_PCI_ADDRESS_XML = '<address bus="0x01" domain="0x0000" function="0x0" \
slot="0x02" type="pci"/>'
def setUp(self):
self.conf = {
'vmName': 'testVm',
'vmId': '9ffe28b6-6134-4b1e-8804-1185f49c436f',
'smp': '8', 'maxVCpus': '160',
'memSize': '1024', 'memGuaranteedSize': '512'}
# TODO: next 2 tests should reside in their own module (interfaceTests.py)
def testCreateSRIOVVF(self):
dev_spec = {'type': hwclass.NIC, 'device': 'hostdev',
'hostdev': hostdevlib.SRIOV_VF,
'macAddr': 'ff:ff:ff:ff:ff:ff',
'specParams': {'vlanid': 3},
'bootOrder': '9'}
device = network.Interface(self.log, **dev_spec)
self.assertXMLEqual(
xmlutils.tostring(device.getXML()),
hostdevlib.DEVICE_XML[hostdevlib.SRIOV_VF] % ('',))
def testCreateSRIOVVFWithAddress(self):
dev_spec = {'type': hwclass.NIC, 'device': 'hostdev',
'hostdev': hostdevlib.SRIOV_VF,
'macAddr': 'ff:ff:ff:ff:ff:ff',
'specParams': {'vlanid': 3},
'bootOrder': '9', 'address':
{'slot': '0x02', 'bus': '0x01', 'domain': '0x0000',
'function': '0x0', 'type': 'pci'}}
device = network.Interface(self.log, **dev_spec)
self.assertXMLEqual(
xmlutils.tostring(device.getXML()),
hostdevlib.DEVICE_XML[hostdevlib.SRIOV_VF] % (
self._PCI_ADDRESS_XML
)
)
@expandPermutations
@MonkeyClass(hostdev, '_each_supported_mdev_type', hostdevlib.fake_mdev_types)
@MonkeyClass(hostdev, '_mdev_type_details', hostdevlib.fake_mdev_details)
@MonkeyClass(hostdev, '_mdev_device_vendor', hostdevlib.fake_mdev_vendor)
@MonkeyClass(hostdev, '_mdev_type_devices', hostdevlib.fake_mdev_instances)
@MonkeyClass(hostdev, 'supervdsm', hostdevlib.FakeSuperVdsm())
class TestMdev(TestCaseBase):
def setUp(self):
def make_device(name):
mdev_types = [
hostdevlib.FakeMdevType('incompatible-1', 2),
hostdevlib.FakeMdevType('8q', 1),
hostdevlib.FakeMdevType('4q', 2),
hostdevlib.FakeMdevType('incompatible-2', 2),
]
return hostdevlib.FakeMdevDevice(name=name, vendor='0x10de',
mdev_types=mdev_types)
self.devices = [make_device(name) for name in ('card-1', 'card-2',)]
@permutations([
# (mdev_type, mdev_uuid)*, mdev_placement, instances
[[('4q', '4q-1')],
hostdev.MdevPlacement.COMPACT, [['4q-1'], []]],
[[('8q', '8q-1')],
hostdev.MdevPlacement.SEPARATE, [['8q-1'], []]],
[[('4q', '4q-1'), ('4q', '4q-2')],
hostdev.MdevPlacement.COMPACT, [['4q-1', '4q-2'], []]],
[[('4q', '4q-1'), ('8q', '8q-1')],
hostdev.MdevPlacement.COMPACT, [['4q-1'], ['8q-1']]],
[[('4q', '4q-1'), ('4q', '4q-2')],
hostdev.MdevPlacement.SEPARATE, [['4q-1'], ['4q-2']]],
[[('4q', '4q-1'), ('8q', '8q-1'), ('4q', '4q-2')],
hostdev.MdevPlacement.COMPACT, [['4q-1', '4q-2'], ['8q-1']]],
[[('8q', '8q-1'), ('4q', '4q-1'), ('4q', '4q-2')],
hostdev.MdevPlacement.COMPACT, [['8q-1'], ['4q-1', '4q-2']]],
[[('4q', '4q-1'), ('4q', '4q-2'), ('8q', '8q-1')],
hostdev.MdevPlacement.COMPACT, [['4q-1', '4q-2'], ['8q-1']]],
[[('4q', '4q-1'), ('8q', '8q-1'), ('4q', '4q-2')],
hostdev.MdevPlacement.SEPARATE, [['4q-1', '4q-2'], ['8q-1']]],
])
def test_vgpu_placement(self, mdev_specs, mdev_placement, instances):
with MonkeyPatchScope([
(hostdev, '_each_mdev_device', lambda: self.devices)
]):
for mdev_type, mdev_uuid in mdev_specs:
hostdev.spawn_mdev(mdev_type, mdev_uuid, mdev_placement,
self.log)
for inst, dev in zip(instances, self.devices):
dev_inst = []
for mdev_type in dev.mdev_types:
dev_inst.extend(mdev_type.instances)
self.assertEqual(inst, dev_inst)
@permutations([
[hostdev.MdevPlacement.COMPACT],
[hostdev.MdevPlacement.SEPARATE],
])
def test_unsupported_vgpu_placement(self, placement):
with MonkeyPatchScope([
(hostdev, '_each_mdev_device', lambda: self.devices)
]):
self.assertRaises(
exception.ResourceUnavailable,
hostdev.spawn_mdev, 'unsupported', '1234', placement, self.log
)
| oVirt/vdsm | tests/hostdev_test.py | Python | gpl-2.0 | 10,768 |
##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# http://www.morningstarsecurity.com/research/whatweb
##
Plugin.define "OurDisclaimer" do
author "Brendan Coles <bcoles@gmail.com>" # 2010-10-14
version "0.1"
description "OurDisclaimer.com - Third party disclaimer service. - homepage: http://ourdisclaimer.com/"
# 59 results for inurl:"ourdisclaimer.com/?i=" @ 2010-10-14
examples %w|
AshMax123.com
astarabeauty.co.za
CHEMICALPLANTSAFETY.NET
electronicmusic.com
elfulminador.com/disclaimer.html
kjkglobalindustries.com
letterofcredit.biz
metricationmatters.com
STROMBOLI.ORG
WIIWORLD.co.uk
www.CloudTweaks.com
|
matches [
# Get URL # Link & Image method
{ :version=>/<a[^>]+href[\s]*=[\s]*"http:\/\/ourdisclaimer.com\/\?i=([^\"]+)/i },
# Get URL # Iframe method
{ :version=>/<iframe[^>]+src[\s]*=[\s]*"http:\/\/ourdisclaimer.com\/\?i=([^\"]+)/i },
]
end
| tennc/WhatWeb | plugins/OurDisclaimer.rb | Ruby | gpl-2.0 | 1,000 |
<?php
//add extra fields to category edit form hook
add_action('edit_category_form_fields', 'kopa_edit_extra_category_fields');
function kopa_edit_extra_category_fields($tag) { //check for existing featured ID
$t_id = $tag->term_id;
$kopa_category_setting_key = "kopa_category_setting_" . $t_id;
$kopa_setting = get_option('kopa_setting', unserialize(KOPA_DEFAULT_SETTING));
$kopa_category_setting = get_option($kopa_category_setting_key,array());
$kopa_disable = '';
if (empty($kopa_category_setting)) {
$kopa_disable = ' disabled';
$kopa_checked = '';
$kopa_checked_value = "No";
$kopa_category_setting = $kopa_setting["taxonomy"];
} else {
$kopa_checked = 'checked ="checked"';
$kopa_disable = '';
$kopa_checked_value = "Yes";
}
$kopa_template_hierarchy = unserialize(KOPA_TEMPLATE_HIERARCHY);
$kopa_layout = unserialize(KOPA_LAYOUT);
$kopa_sidebar_position = unserialize(KOPA_SIDEBAR_POSITION);
$kopa_sidebar = get_option('kopa_sidebar', unserialize(KOPA_DEFAULT_SIDEBAR));
wp_nonce_field("save_layout_setting", "nonce_id_save");
?>
<tr class="form-field">
<th scope="row" valign="top">
</th>
<td>
<div class="kopa-content-box tab-content kopa-content-main-box" id="kopa-category-edit" class="kopa-category-edit">
<div class="kopa-box-head clearfix">
<h4><?php echo KopaIcon::getIcon('cog'); ?>Custom Setting Layout and Sidebar?</h4>
<input onchange="show_on_checked(jQuery(this));" autocomplete="off" type="checkbox" name="kopa_custom_layout_setting" id="kopa_custom_layout_setting" class="kopa_custom_layout_setting" value="<?php echo $kopa_checked_value; ?>" <?php echo $kopa_checked; ?> >
<label class="kopa-label">Check if you would like to use custom setting</label>
</div><!--kopa-box-head-->
<div class="kopa-box-body clearfix">
<div class="kopa-layout-box pull-left">
<div class="kopa-select-layout-box kopa-element-box">
<span class="kopa-component-title">Select the layout</span>
<select name ="kopa_select_layout" class="kopa-layout-select" onchange="show_onchange(jQuery(this));" autocomplete="off" <?php echo $kopa_disable; ?>>
<?php
foreach ($kopa_template_hierarchy['taxonomy']['layout'] as $keys => $value) {
echo '<option value="' . $value . '"';
if ($value === $kopa_category_setting['layout_id']) {
echo 'selected="selected"';
}
echo '>' . $kopa_layout[$value]['title'] . '</option>';
}
?>
</select>
</div><!--kopa-select-layout-box-->
<?php
foreach ($kopa_template_hierarchy['taxonomy']['layout'] as $keys => $value) {
foreach ($kopa_layout as $layout_key => $layout_value) {
if ($layout_key == $value) {
?>
<div class="<?php echo 'kopa-sidebar-box-wrapper sidebar-position-' . $layout_key; ?>">
<?php
foreach ($layout_value['positions'] as $postion_key => $postion_id) {
?>
<div class="kopa-sidebar-box kopa-element-box">
<span class="kopa-component-title"><?php echo $kopa_sidebar_position[$postion_id]['title']; ?></span>
<label class="kopa-label">Select sidebars</label>
<?php
echo '<select class="kopa-sidebar-select" autocomplete="off" ' . $kopa_disable . '>';
foreach ($kopa_sidebar as $sidebar_list_key => $sidebar_list_value) {
$__selected_sidebar = '';
if ($layout_key === $kopa_category_setting['layout_id']) {
if ($sidebar_list_key === $kopa_category_setting['sidebars'][$postion_key]) {
$__selected_sidebar = 'selected="selected"';
}
}
echo '<option value="'.$sidebar_list_key.'" ' . $__selected_sidebar . '>' . $sidebar_list_value . '</option>';
$__selected_sidebar = '';
}
echo '</select>';
?>
</div><!--kopa-sidebar-box-->
<?php } ?>
</div><!--kopa-sidebar-box-wrapper-->
<?php
}
}
}
?>
</div><!--kopa-layout-box-->
<div class="kopa-thumbnails-box pull-right">
<?php
foreach ($kopa_template_hierarchy['taxonomy']['layout'] as $thumbnails_key => $thumbnails_value) {
?>
<image class="responsive-img <?php echo ' kopa-cpanel-thumbnails kopa-cpanel-thumbnails-' . $thumbnails_value; ?>" src="<?php echo KOPA_CPANEL_IMAGE_DIR . $kopa_layout[$thumbnails_value]['thumbnails']; ?>" class="img-polaroid" alt="">
<?php
}
?>
</div><!--kopa-thumbnails-box-->
</div><!--kopa-box-body-->
</div><!--kopa-content-box-->
</td>
</tr>
<?php
}
// save extra category extra fields hook
add_action('edited_category', 'kopa_save_extra_category_fileds');
// save extra category extra fields callback function
function kopa_save_extra_category_fileds($term_id) {
$kopa_category_setting_key = "kopa_category_setting_" . $term_id;
if (empty($_POST['kopa_custom_layout_setting'])) {
delete_option($kopa_category_setting_key);
}
if (!empty($_POST['kopa_custom_layout_setting']) && !empty($_POST['kopa_select_layout']) && !empty($_POST['sidebar'])) {
if ($_POST['kopa_custom_layout_setting'] == 'Yes') {
$kopa_new_setting = array();
$kopa_new_setting['layout_id'] = $_POST['kopa_select_layout'];
$new_sidebars = ($_POST['sidebar']);
$kopa_new_setting['sidebars'] = array();
foreach ($new_sidebars as $__k => $__v) {
$kopa_new_setting['sidebars'][$__k] = $__v;
}
update_option($kopa_category_setting_key, $kopa_new_setting);
}
}
} | tallman07/demowordpress | wp-content/themes/forceful-lite/library/includes/metabox/category.php | PHP | gpl-2.0 | 7,680 |
<?php
class Kirki_Customize_Textarea_Control extends WP_Customize_Control {
public $type = 'textarea';
public $description = '';
public $subtitle = '';
public $separator = false;
public $required;
public function render_content() { ?>
<label class="customizer-textarea">
<span class="customize-control-title">
<?php echo esc_html( $this->label ); ?>
<?php if ( isset( $this->description ) && '' != $this->description ) { ?>
<a href="#" class="button tooltip" title="<?php echo strip_tags( esc_html( $this->description ) ); ?>">?</a>
<?php } ?>
</span>
<?php if ( '' != $this->subtitle ) : ?>
<div class="customizer-subtitle"><?php echo $this->subtitle; ?></div>
<?php endif; ?>
<textarea class="of-input" rows="5" style="width:100%;" <?php $this->link(); ?>><?php echo esc_textarea( $this->value() ); ?></textarea>
</label>
<?php if ( $this->separator ) echo '<hr class="customizer-separator">'; ?>
<?php foreach ( $this->required as $id => $value ) :
if ( isset($id) && isset($value) && get_theme_mod($id,0)==$value ) { ?>
<script>
jQuery(document).ready(function($) {
$( "#customize-control-<?php echo $this->id; ?>" ).show();
$( "#<?php echo $id . get_theme_mod($id,0); ?>" ).click(function(){
$( "#customize-control-<?php echo $this->id; ?>" ).fadeOut(300);
});
$( "#<?php echo $id . $value; ?>" ).click(function(){
$( "#customize-control-<?php echo $this->id; ?>" ).fadeIn(300);
});
});
</script>
<?php }
if ( isset($id) && isset($value) && get_theme_mod($id,0)!=$value ) { ?>
<script>
jQuery(document).ready(function($) {
$( "#customize-control-<?php echo $this->id; ?>" ).hide();
$( "#<?php echo $id . get_theme_mod($id,0); ?>" ).click(function(){
$( "#customize-control-<?php echo $this->id; ?>" ).fadeOut(300);
});
$( "#<?php echo $id . $value; ?>" ).click(function(){
$( "#customize-control-<?php echo $this->id; ?>" ).fadeIn(300);
});
});
</script>
<?php }
endforeach;
}
}
| telemahos/shoestrap | lib/kirki/includes/controls/textarea.php | PHP | gpl-2.0 | 2,067 |
<?php
/**
* Email Header
*
* @author WooThemes
* @package WooCommerce/Templates/Emails
* @version 2.0.0
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// Unused woocommerce code
// Load colours
// $bg = get_option( 'woocommerce_email_background_color' );
// $body = get_option( 'woocommerce_email_body_background_color' );
// $base = get_option( 'woocommerce_email_base_color' );
// $base_text = woocommerce_light_or_dark( $base, '#202020', '#ffffff' );
// $text = get_option( 'woocommerce_email_text_color' );
// $bg_darker_10 = woocommerce_hex_darker( $bg, 10 );
// $base_lighter_20 = woocommerce_hex_lighter( $base, 20 );
// $text_lighter_20 = woocommerce_hex_lighter( $text, 20 );
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Guymark, Excellence in Audiology</title>
</head>
<body>
<table width="615" border="0" cellspacing="0" cellpadding="0" align="center" style="font-family: sans-serif, Arial;font-size: 13px;text-align: left;color: #303030;line-height: 19px;">
<tr><td height="10" style="text-align: left;"></td></tr>
<tr><td height="135" style="text-align: left;">
<?php
if ( $img = get_option( 'woocommerce_email_header_image' ) ) {
echo '<img src="' . esc_url( $img ) . '" alt="' . get_bloginfo( 'name' ) . '" style="outline: none;padding: 0px;margin: 0px;text-align: left;border: 0px;" />';
}
?>
</td></tr>
<tr><td class="divider2" style="text-align: left;height: 17px;display: block;width: 615px;"></td></tr>
<tr><td style="text-align: left;">
<!-- center content below -->
<table class="shared-ordertable" width="616" border="0" cellspacing="0" cellpadding="0" align="center" style="font-family: sans-serif, Arial;font-size: 13px;text-align: left;color: #303030;line-height: 22px;">
| DesignBP/Guymark | wp-content/themes/guymark/woocommerce/emails/plain/email-header.php | PHP | gpl-2.0 | 1,853 |
$(window).load(function(){FusionCharts.ready(function () {
var revenueChart = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Monthly Revenue",
"subCaption": "Last year",
"xAxisName": "Month",
"yAxisName": "Amount (In USD)",
"numberPrefix": "$",
"theme": "fint",
//Configure x-axis labels to display in staggered mode
"labelDisplay": "stagger",
"staggerLines": "3"
},
"data": [{
"label": "January",
"value": "420000"
}, {
"label": "February",
"value": "810000"
}, {
"label": "March",
"value": "720000"
}, {
"label": "April",
"value": "550000"
}, {
"label": "May",
"value": "910000"
}, {
"label": "June",
"value": "510000"
}, {
"label": "July",
"value": "680000"
}, {
"label": "August",
"value": "620000"
}, {
"label": "September",
"value": "610000"
}, {
"label": "October",
"value": "490000"
}, {
"label": "November",
"value": "900000"
}, {
"label": "December",
"value": "730000"
}]
}
}).render();
});}); | sguha-work/fiddletest | fiddles/Chart/Data-Labels/Configuring-x-axis-data-labels-display---staggered-mode_468/demo.js | JavaScript | gpl-2.0 | 1,780 |
<?php
if ( ! defined( 'myCRED_VERSION' ) ) exit;
/**
* Import: Log Entries
* @since 1.2
* @version 1.2
*/
if ( class_exists( 'WP_Importer' ) ) :
class myCRED_Importer_Log_Entires extends WP_Importer {
var $id;
var $file_url;
var $import_page;
var $delimiter;
var $posts = array();
var $imported;
var $skipped;
/**
* Construct
*/
public function __construct() {
$this->import_page = 'mycred_import_log';
}
/**
* Registered callback function for the WordPress Importer
* Manages the three separate stages of the CSV import process
*/
function load() {
$this->header();
if ( ! empty( $_POST['delimiter'] ) )
$this->delimiter = stripslashes( trim( $_POST['delimiter'] ) );
if ( ! $this->delimiter )
$this->delimiter = ',';
$step = empty( $_GET['step'] ) ? 0 : (int) $_GET['step'];
switch ( $step ) {
case 0 :
$this->greet();
break;
case 1 :
check_admin_referer( 'import-upload' );
if ( $this->handle_upload() ) {
if ( $this->id )
$file = get_attached_file( $this->id );
else
$file = ABSPATH . $this->file_url;
add_filter( 'http_request_timeout', array( $this, 'bump_request_timeout' ) );
if ( function_exists( 'gc_enable' ) )
gc_enable();
@set_time_limit(0);
@ob_flush();
@flush();
$this->import( $file );
}
break;
}
$this->footer();
}
/**
* format_data_from_csv function.
*/
function format_data_from_csv( $data, $enc ) {
return ( $enc == 'UTF-8' ) ? $data : utf8_encode( $data );
}
/**
* import function.
*/
function import( $file ) {
global $wpdb, $mycred;
$this->imported = $this->skipped = 0;
if ( ! is_file( $file ) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'mycred' ) . '</strong><br />';
echo __( 'The file does not exist, please try again.', 'mycred' ) . '</p>';
$this->footer();
die;
}
ini_set( 'auto_detect_line_endings', '1' );
if ( ( $handle = fopen( $file, "r" ) ) !== FALSE ) {
$header = fgetcsv( $handle, 0, $this->delimiter );
if ( sizeof( $header ) == 8 ) {
$loop = 0;
while ( ( $row = fgetcsv( $handle, 0, $this->delimiter ) ) !== FALSE ) {
list( $ref, $ref_id, $user_id, $creds, $ctype, $time, $entry, $data ) = $row;
if ( empty( $ref ) || empty( $user_id ) || empty( $creds ) || $creds === 0 || empty( $time ) ) {
$this->skipped ++;
continue;
}
$wpdb->insert(
$mycred->log_table,
array(
'ref' => $ref,
'ref_id' => absint( $ref_id ),
'user_id' => absint( $user_id ),
'creds' => $mycred->number( $creds ),
'ctype' => sanitize_text_field( $ctype ),
'time' => absint( $time ),
'entry' => trim( $entry ),
'data' => maybe_serialize( $data )
)
);
$loop ++;
$this->imported++;
}
} else {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'mycred' ) . '</strong><br />';
echo __( 'The CSV is invalid.', 'mycred' ) . '</p>';
$this->footer();
die;
}
fclose( $handle );
}
// Show Result
echo '<div class="updated settings-error below-h2"><p>
'.sprintf( __( 'Import complete - A total of <strong>%d</strong> entries were successfully imported. <strong>%d</strong> was skipped.', 'mycred' ), $this->imported, $this->skipped ).'
</p></div>';
$this->import_end();
}
/**
* Performs post-import cleanup of files and the cache
*/
function import_end() {
echo '<p><a href="' . admin_url( 'admin.php?page=myCRED' ) . '" class="button button-large button-primary">' . __( 'View Log', 'mycred' ) . '</a> <a href="' . admin_url( 'import.php' ) . '" class="button button-large button-primary">' . __( 'Import More', 'mycred' ) . '</a></p>';
do_action( 'import_end' );
}
/**
* Handles the CSV upload and initial parsing of the file to prepare for
* displaying author import options
* @return bool False if error uploading or invalid file, true otherwise
*/
function handle_upload() {
if ( empty( $_POST['file_url'] ) ) {
$file = wp_import_handle_upload();
if ( isset( $file['error'] ) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'mycred' ) . '</strong><br />';
echo esc_html( $file['error'] ) . '</p>';
return false;
}
$this->id = (int) $file['id'];
} else {
if ( file_exists( ABSPATH . $_POST['file_url'] ) ) {
$this->file_url = esc_attr( $_POST['file_url'] );
} else {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'mycred' ) . '</strong></p>';
return false;
}
}
return true;
}
/**
* header function.
*/
function header() {
echo '<div class="wrap"><h2>' . __( 'Import Log Entries', 'mycred' ) . '</h2>';
}
/**
* footer function.
*/
function footer() {
echo '</div>';
}
/**
* greet function.
*/
function greet() {
global $mycred;
echo '<div class="narrow">';
echo '<p>' . __( 'Import log entries from a CSV file.', 'mycred' ).'</p>';
$action = 'admin.php?import=mycred_import_log&step=1';
$bytes = apply_filters( 'import_upload_size_limit', wp_max_upload_size() );
$size = size_format( $bytes );
$upload_dir = wp_upload_dir();
if ( ! empty( $upload_dir['error'] ) ) :
?>
<div class="error"><p><?php _e( 'Before you can upload your import file, you will need to fix the following error:', 'mycred' ); ?></p>
<p><strong><?php echo $upload_dir['error']; ?></strong></p></div>
<?php
else :
?>
<form enctype="multipart/form-data" id="import-upload-form" method="post" action="<?php echo esc_attr( wp_nonce_url( $action, 'import-upload' ) ); ?>">
<table class="form-table">
<tbody>
<tr>
<th>
<label for="upload"><?php _e( 'Choose a file from your computer:', 'mycred' ); ?></label>
</th>
<td>
<input type="file" id="upload" name="import" size="25" />
<input type="hidden" name="action" value="save" />
<input type="hidden" name="max_file_size" value="<?php echo $bytes; ?>" />
<small><?php printf( __( 'Maximum size: %s', 'mycred' ), $size ); ?></small>
</td>
</tr>
<tr>
<th>
<label for="file_url"><?php _e( 'OR enter path to file:', 'mycred' ); ?></label>
</th>
<td>
<?php echo ' ' . ABSPATH . ' '; ?><input type="text" id="file_url" name="file_url" size="25" />
</td>
</tr>
<tr>
<th><label><?php _e( 'Delimiter', 'mycred' ); ?></label><br/></th>
<td><input type="text" name="delimiter" placeholder="," size="2" /></td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" class="button" value="<?php esc_attr_e( 'Upload file and import' ); ?>" />
</p>
</form>
<?php
endif;
echo '</div>';
}
/**
* Added to http_request_timeout filter to force timeout at 60 seconds during import
* @return int 60
*/
function bump_request_timeout( $val ) {
return 60;
}
}
endif;
?> | charliegdev/mapleAvantTest | wp-content/plugins/mycred/includes/importers/mycred-log-entries.php | PHP | gpl-2.0 | 7,118 |
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @(#)HeaderTokenizer.java 1.9 02/03/27
*/
package com.sun.xml.internal.messaging.saaj.packaging.mime.internet;
/**
* This class tokenizes RFC822 and MIME headers into the basic
* symbols specified by RFC822 and MIME. <p>
*
* This class handles folded headers (ie headers with embedded
* CRLF SPACE sequences). The folds are removed in the returned
* tokens.
*
* @version 1.9, 02/03/27
* @author John Mani
*/
public class HeaderTokenizer {
/**
* The Token class represents tokens returned by the
* HeaderTokenizer.
*/
public static class Token {
private int type;
private String value;
/**
* Token type indicating an ATOM.
*/
public static final int ATOM = -1;
/**
* Token type indicating a quoted string. The value
* field contains the string without the quotes.
*/
public static final int QUOTEDSTRING = -2;
/**
* Token type indicating a comment. The value field
* contains the comment string without the comment
* start and end symbols.
*/
public static final int COMMENT = -3;
/**
* Token type indicating end of input.
*/
public static final int EOF = -4;
/**
* Constructor.
* @param type Token type
* @param value Token value
*/
public Token(int type, String value) {
this.type = type;
this.value = value;
}
/**
* Return the type of the token. If the token represents a
* delimiter or a control character, the type is that character
* itself, converted to an integer. Otherwise, it's value is
* one of the following:
* <ul>
* <li><code>ATOM</code> A sequence of ASCII characters
* delimited by either SPACE, CTL, "(", <"> or the
* specified SPECIALS
* <li><code>QUOTEDSTRING</code> A sequence of ASCII characters
* within quotes
* <li><code>COMMENT</code> A sequence of ASCII characters
* within "(" and ")".
* <li><code>EOF</code> End of header
* </ul>
*/
public int getType() {
return type;
}
/**
* Returns the value of the token just read. When the current
* token is a quoted string, this field contains the body of the
* string, without the quotes. When the current token is a comment,
* this field contains the body of the comment.
*
* @return token value
*/
public String getValue() {
return value;
}
}
private String string; // the string to be tokenized
private boolean skipComments; // should comments be skipped ?
private String delimiters; // delimiter string
private int currentPos; // current parse position
private int maxPos; // string length
private int nextPos; // track start of next Token for next()
private int peekPos; // track start of next Token for peek()
/**
* RFC822 specials
*/
public final static String RFC822 = "()<>@,;:\\\"\t .[]";
/**
* MIME specials
*/
public final static String MIME = "()<>@,;:\\\"\t []/?=";
// The EOF Token
private final static Token EOFToken = new Token(Token.EOF, null);
/**
* Constructor that takes a rfc822 style header.
*
* @param header The rfc822 header to be tokenized
* @param delimiters Set of delimiter characters
* to be used to delimit ATOMS. These
* are usually <code>RFC822</code> or
* <code>MIME</code>
* @param skipComments If true, comments are skipped and
* not returned as tokens
*/
public HeaderTokenizer(String header, String delimiters,
boolean skipComments) {
string = (header == null) ? "" : header; // paranoia ?!
this.skipComments = skipComments;
this.delimiters = delimiters;
currentPos = nextPos = peekPos = 0;
maxPos = string.length();
}
/**
* Constructor. Comments are ignored and not returned as tokens
*
* @param header The header that is tokenized
* @param delimiters The delimiters to be used
*/
public HeaderTokenizer(String header, String delimiters) {
this(header, delimiters, true);
}
/**
* Constructor. The RFC822 defined delimiters - RFC822 - are
* used to delimit ATOMS. Also comments are skipped and not
* returned as tokens
*/
public HeaderTokenizer(String header) {
this(header, RFC822);
}
/**
* Parses the next token from this String. <p>
*
* Clients sit in a loop calling next() to parse successive
* tokens until an EOF Token is returned.
*
* @return the next Token
* @exception ParseException if the parse fails
*/
public Token next() throws ParseException {
Token tk;
currentPos = nextPos; // setup currentPos
tk = getNext();
nextPos = peekPos = currentPos; // update currentPos and peekPos
return tk;
}
/**
* Peek at the next token, without actually removing the token
* from the parse stream. Invoking this method multiple times
* will return successive tokens, until <code>next()</code> is
* called. <p>
*
* @return the next Token
* @exception ParseException if the parse fails
*/
public Token peek() throws ParseException {
Token tk;
currentPos = peekPos; // setup currentPos
tk = getNext();
peekPos = currentPos; // update peekPos
return tk;
}
/**
* Return the rest of the Header.
*
* @return String rest of header. null is returned if we are
* already at end of header
*/
public String getRemainder() {
return string.substring(nextPos);
}
/*
* Return the next token starting from 'currentPos'. After the
* parse, 'currentPos' is updated to point to the start of the
* next token.
*/
private Token getNext() throws ParseException {
// If we're already at end of string, return EOF
if (currentPos >= maxPos)
return EOFToken;
// Skip white-space, position currentPos beyond the space
if (skipWhiteSpace() == Token.EOF)
return EOFToken;
char c;
int start;
boolean filter = false;
c = string.charAt(currentPos);
// Check or Skip comments and position currentPos
// beyond the comment
while (c == '(') {
// Parsing comment ..
int nesting;
for (start = ++currentPos, nesting = 1;
nesting > 0 && currentPos < maxPos;
currentPos++) {
c = string.charAt(currentPos);
if (c == '\\') { // Escape sequence
currentPos++; // skip the escaped character
filter = true;
} else if (c == '\r')
filter = true;
else if (c == '(')
nesting++;
else if (c == ')')
nesting--;
}
if (nesting != 0)
throw new ParseException("Unbalanced comments");
if (!skipComments) {
// Return the comment, if we are asked to.
// Note that the comment start & end markers are ignored.
String s;
if (filter) // need to go thru the token again.
s = filterToken(string, start, currentPos-1);
else
s = string.substring(start,currentPos-1);
return new Token(Token.COMMENT, s);
}
// Skip any whitespace after the comment.
if (skipWhiteSpace() == Token.EOF)
return EOFToken;
c = string.charAt(currentPos);
}
// Check for quoted-string and position currentPos
// beyond the terminating quote
if (c == '"') {
for (start = ++currentPos; currentPos < maxPos; currentPos++) {
c = string.charAt(currentPos);
if (c == '\\') { // Escape sequence
currentPos++;
filter = true;
} else if (c == '\r')
filter = true;
else if (c == '"') {
currentPos++;
String s;
if (filter)
s = filterToken(string, start, currentPos-1);
else
s = string.substring(start,currentPos-1);
return new Token(Token.QUOTEDSTRING, s);
}
}
throw new ParseException("Unbalanced quoted string");
}
// Check for SPECIAL or CTL
if (c < 040 || c >= 0177 || delimiters.indexOf(c) >= 0) {
currentPos++; // re-position currentPos
char ch[] = new char[1];
ch[0] = c;
return new Token((int)c, new String(ch));
}
// Check for ATOM
for (start = currentPos; currentPos < maxPos; currentPos++) {
c = string.charAt(currentPos);
// ATOM is delimited by either SPACE, CTL, "(", <">
// or the specified SPECIALS
if (c < 040 || c >= 0177 || c == '(' || c == ' ' ||
c == '"' || delimiters.indexOf(c) >= 0)
break;
}
return new Token(Token.ATOM, string.substring(start, currentPos));
}
// Skip SPACE, HT, CR and NL
private int skipWhiteSpace() {
char c;
for (; currentPos < maxPos; currentPos++)
if (((c = string.charAt(currentPos)) != ' ') &&
(c != '\t') && (c != '\r') && (c != '\n'))
return currentPos;
return Token.EOF;
}
/* Process escape sequences and embedded LWSPs from a comment or
* quoted string.
*/
private static String filterToken(String s, int start, int end) {
StringBuffer sb = new StringBuffer();
char c;
boolean gotEscape = false;
boolean gotCR = false;
for (int i = start; i < end; i++) {
c = s.charAt(i);
if (c == '\n' && gotCR) {
// This LF is part of an unescaped
// CRLF sequence (i.e, LWSP). Skip it.
gotCR = false;
continue;
}
gotCR = false;
if (!gotEscape) {
// Previous character was NOT '\'
if (c == '\\') // skip this character
gotEscape = true;
else if (c == '\r') // skip this character
gotCR = true;
else // append this character
sb.append(c);
} else {
// Previous character was '\'. So no need to
// bother with any special processing, just
// append this character
sb.append(c);
gotEscape = false;
}
}
return sb.toString();
}
}
| samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/xml/internal/messaging/saaj/packaging/mime/internet/HeaderTokenizer.java | Java | gpl-2.0 | 12,766 |
/**
* Copyright 2013 Neuroph Project http://neuroph.sourceforge.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuroph.nnet;
import org.neuroph.nnet.learning.ConvolutionalBackpropagation;
import org.neuroph.core.NeuralNetwork;
import org.neuroph.core.Neuron;
import org.neuroph.core.exceptions.VectorSizeMismatchException;
import org.neuroph.nnet.comp.neuron.BiasNeuron;
import org.neuroph.nnet.comp.layer.FeatureMapsLayer;
import org.neuroph.nnet.comp.layer.Layer2D;
/**
* Convolutional neural network with backpropagation algorithm modified for
* convolutional networks.
*
* TODO: provide Hiton, LeCun, AndrewNg implementation specific features
*
* @author Boris Fulurija
* @author Zoran Sevarac
*
* @see ConvolutionalBackpropagation
*/
public class ConvolutionalNetwork extends NeuralNetwork<ConvolutionalBackpropagation> {
private static final long serialVersionUID = -1393907449047650509L;
/**
* Creates empty convolutional network with ConvolutionalBackpropagation learning rule
*/
public ConvolutionalNetwork() {
this.setLearningRule(new ConvolutionalBackpropagation());
}
// This method is not used anywhere...
// public void connectLayers(FeatureMapsLayer fromLayer, FeatureMapsLayer toLayer, int fromFeatureMapIndex, int toFeatureMapIndex) {
// ConvolutionalUtils.connectFeatureMaps(fromLayer, toLayer, fromFeatureMapIndex, toFeatureMapIndex);
// }
/**
* Sets network input, to all feature maps in input layer
* @param inputVector
* @throws VectorSizeMismatchException
*/
@Override
public void setInput(double... inputVector) throws VectorSizeMismatchException {
// if (inputVector.length != getInputNeurons().length) {
// throw new
// VectorSizeMismatchException("Input vector size does not match network input dimension!");
// }
// It would be good if i could do the following:
// int i = 0;
// Layer inputLayer =getLayerAt(0);
// for (Neuron neuron : inputLayer.getNeurons()){
// neuron.setInput(inputVector[i++]);
// }
// But for that getNeuron must be non final method
FeatureMapsLayer inputLayer = (FeatureMapsLayer) getLayerAt(0);
int currentNeuron = 0;
for (int i = 0; i < inputLayer.getNumberOfMaps(); i++) {
Layer2D map = inputLayer.getFeatureMap(i);
for (Neuron neuron : map.getNeurons()) {
if (!(neuron instanceof BiasNeuron))
neuron.setInput(inputVector[currentNeuron++]);
}
}
}
} | dwaybright/StrategicAssaultSimulator | core/src/neuroph_jars/sources/Core/src/main/java/org/neuroph/nnet/ConvolutionalNetwork.java | Java | gpl-2.0 | 2,992 |
<?php
/**
* @package Installer
* @copyright Copyright 2003-2018 Zen Cart Development Team
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version $Id: Author: DrByte Modified in v1.6.0 $
*/
$systemChecker = new systemChecker();
$dbVersion = $systemChecker->findCurrentDbVersion();
logDetails($dbVersion, 'Version detected in database_upgrade/header_php.php');
$versionArray = array();
$versionArray[] = '1.2.6';
$versionArray[] = '1.2.7';
$versionArray[] = '1.3.0';
$versionArray[] = '1.3.5';
$versionArray[] = '1.3.6';
$versionArray[] = '1.3.7';
$versionArray[] = '1.3.8';
$versionArray[] = '1.3.9';
$versionArray[] = '1.5.0';
$versionArray[] = '1.5.1';
$versionArray[] = '1.5.2';
$versionArray[] = '1.5.3';
$versionArray[] = '1.5.4';
$versionArray[] = '1.5.5';
$versionArray[] = '1.5.6';
$versionArray[] = '1.6.0';
//print_r($versionArray);
$key = array_search($dbVersion, $versionArray);
$newArray = array_slice($versionArray, $key + 1);
//print_r($newArray);
// add current IP to the view-in-maintenance-mode list
$systemChecker->updateAdminIpList();
| drbyte/zc-v1-series | zc_install/includes/modules/pages/database_upgrade/header_php.php | PHP | gpl-2.0 | 1,135 |
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2017 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <U2Lang/IntegralBusType.h>
#include "GrouperSlotAttribute.h"
namespace U2 {
GrouperOutSlotAttribute::GrouperOutSlotAttribute(const Descriptor &d, const DataTypePtr type, bool required, const QVariant &defaultValue)
: Attribute(d, type, required, defaultValue)
{
}
GrouperOutSlotAttribute::~GrouperOutSlotAttribute() {
}
Attribute *GrouperOutSlotAttribute::clone() {
return new GrouperOutSlotAttribute(*this);
}
AttributeGroup GrouperOutSlotAttribute::getGroup() {
return GROUPER_SLOT_GROUP;
}
QList<GrouperOutSlot> &GrouperOutSlotAttribute::getOutSlots() {
return outSlots;
}
const QList<GrouperOutSlot> &GrouperOutSlotAttribute::getOutSlots() const {
return outSlots;
}
void GrouperOutSlotAttribute::addOutSlot(const GrouperOutSlot &outSlot) {
outSlots.append(outSlot);
}
void GrouperOutSlotAttribute::updateActorIds(const QMap<ActorId, ActorId> &actorIdsMap) {
QList<GrouperOutSlot> newOutSlots;
foreach (const GrouperOutSlot &gSlot, outSlots) {
QString slotStr = gSlot.getInSlotStr();
slotStr = GrouperOutSlot::readable2busMap(slotStr);
Workflow::IntegralBusType::remapSlotString(slotStr, actorIdsMap);
slotStr = GrouperOutSlot::busMap2readable(slotStr);
GrouperOutSlot newGSlot(gSlot);
newGSlot.setInSlotStr(slotStr);
newOutSlots << newGSlot;
}
outSlots = newOutSlots;
}
GroupSlotAttribute::GroupSlotAttribute(const Descriptor &d, const DataTypePtr type, bool required, const QVariant &defaultValue)
: Attribute(d, type, required, defaultValue)
{
}
Attribute *GroupSlotAttribute::clone() {
return new GroupSlotAttribute(*this);
}
void GroupSlotAttribute::updateActorIds(const QMap<ActorId, ActorId> &actorIdsMap) {
QString slotStr = this->getAttributeValueWithoutScript<QString>();
slotStr = GrouperOutSlot::readable2busMap(slotStr);
Workflow::IntegralBusType::remapSlotString(slotStr, actorIdsMap);
slotStr = GrouperOutSlot::busMap2readable(slotStr);
this->setAttributeValue(slotStr);
}
void GroupSlotAttribute::setAttributeValue(const QVariant &newVal) {
QString slotStr = newVal.toString();
Attribute::setAttributeValue(GrouperOutSlot::busMap2readable(slotStr));
}
} // U2
| ggrekhov/ugene | src/corelibs/U2Lang/src/model/GrouperSlotAttribute.cpp | C++ | gpl-2.0 | 3,081 |
<?php
namespace app\models;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "categories".
*
* @property integer $id
* @property string $name
* @property string $description
* @property string $photo_name
* @property integer $created_by
* @property integer $created_at
*
* @property Apis[] $apis
*/
class Categories extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'categories';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name'], 'required'],
[['description', 'photo_name'], 'string'],
[['created_by', 'created_at'], 'integer'],
[['name'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'updatedAtAttribute' => false,
],
[
'class' => BlameableBehavior::className(),
'updatedByAttribute' => false,
],
'image' => [
'class' => 'rico\yii2images\behaviors\ImageBehave',
]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'description' => 'Description',
'created_by' => 'Created By',
'created_at' => 'Created At',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getApis()
{
return $this->hasMany(Apis::className(), ['category' => 'id']);
}
}
| OPENi-ict/api-builder | models/Categories.php | PHP | gpl-2.0 | 1,798 |
from random import choice
from feedparser import parse
from errbot import botcmd, BotPlugin
class DevOpsBorat(BotPlugin):
"""
Quotes from various dev humour related twitter accounts
"""
@botcmd
def borat(self, mess, args):
"""
Random quotes from the DEVOPS_BORAT twitter account
"""
myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=DEVOPS_BORAT')
items = myfeed['entries']
return choice(items).description
@botcmd
def jesus(self, mess, args):
"""
Random quotes from the devops_jesus twitter account
"""
myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=devops_jesus')
items = myfeed['entries']
return choice(items).description
@botcmd
def yoda(self, mess, args):
"""
Random quotes from the UXYoda twitter account
"""
myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=UXYoda')
items = myfeed['entries']
return choice(items).description
| errbotio/err-devops-borat | devops_borat.py | Python | gpl-2.0 | 1,109 |
<?php
/**
* The Template for displaying all single posts.
*
* @package WordPress
* @subpackage Twenty_Twelve
* @since Twenty Twelve 1.0
*/
get_header(); ?>
<div class="content-wrapper">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'singleportfolio'); ?>
<?php //comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
<div class="content-saparator-line"> <img src="<?php echo get_template_directory_uri(); ?>/images/saprator-circle.jpg" width="27" height="13"> </div>
<div class="our-clients">
<h2>Our Clients</h2>
<div class="client-slider-small-media">
<button class="next-client"> </button>
<button class="prev-client"> </button>
</div>
<div class="clear"></div>
<div class="main-client-slider">
<button class="next-client"> </button>
<div class="slide-images-2">
<ul>
<?php
// The Query
$query = new WP_Query( array('post_type'=>'our_clients', 'order'=>'DESC', 'posts_per_page'=>'-1'));
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<li><img src="<?php echo $url; ?>" alt="img"></li>
<?php
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
</ul>
</div>
<button class="prev-client"> </button>
</div>
</div>
</div>
</div>
<?php //get_sidebar(); ?>
<?php get_footer(); ?> | jamshedvf/vfnew | wp-content/themes/vf/single-portfolio.php | PHP | gpl-2.0 | 1,606 |
/* This file is part of the KDE project
Copyright 2007 Stefan Nikolaus <stefan.nikolaus@kdemail.net>
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 <quuid.h>
#include "kspread_limits.h"
#include "PointStorage.h"
#include "BenchmarkPointStorage.h"
using namespace KSpread;
void PointStorageBenchmark::testInsertionPerformance_loadingLike()
{
PointStorage<int> storage;
int col = 1;
int row = 1;
int cols = 100;
int rows = 10000;
QBENCHMARK {
for (int r = row; r <= rows; ++r) {
for (int c = col; c <= cols; c += 1) {
storage.insert(c, r, c);
}
}
}
}
void PointStorageBenchmark::testInsertionPerformance_singular()
{
PointStorage<int> storage;
QBENCHMARK {
int col = 1 + rand() % 1000;
int row = 1 + rand() % 1000;
int cols = col + 1;
int rows = row + 1;
for (int r = row; r <= rows; ++r) {
for (int c = col; c <= cols; c += 1) {
storage.insert(c, r, c);
}
}
}
}
void PointStorageBenchmark::testLookupPerformance_data()
{
QTest::addColumn<int>("maxrow");
QTest::addColumn<int>("maxcol");
QTest::newRow("very small") << 5 << 5;
QTest::newRow("fit to screen") << 30 << 20;
QTest::newRow("medium") << 100 << 100;
QTest::newRow("large") << 1000 << 1000;
QTest::newRow("typical data: more rows") << 10000 << 100;
QTest::newRow("20 times larger") << 10000 << 2000;
QTest::newRow("not really typical: more columns") << 100 << 10000;
QTest::newRow("hopelessly large") << 8000 << 8000;
QTest::newRow("some complete columns; KS_colMax-10, because of max lookup range of width 10 below") << 10 << 32757;
QTest::newRow("some complete rows; KS_rowMax-10, because of max lookup range of height 10 below") << 32757 << 10;
}
void PointStorageBenchmark::testLookupPerformance()
{
PointStorage<int> storage;
QFETCH(int, maxrow);
QFETCH(int, maxcol);
for (int r = 0; r < maxrow; ++r) {
for (int c = 0; c < maxcol; ++c) {
storage.m_data << c;
storage.m_cols << (c + 1);
}
storage.m_rows << r*maxcol;
}
// qDebug() << endl << qPrintable( storage.dump() );
int v;
int col = 0;
int row = 0;
int cols = 0;
int rows = 0;
QBENCHMARK {
col = 1 + rand() % maxcol;
row = 1 + rand() % maxrow;
cols = col + 1 * (rand() % 10);
rows = row + rand() % 10;
for (int r = row; r <= rows; ++r) {
for (int c = col; c <= cols; c += 1) {
v = storage.lookup(c, r);
}
}
}
}
void PointStorageBenchmark::testInsertColumnsPerformance()
{
PointStorage<int> storage;
for (int c = 0; c < KS_colMax; ++c) {
storage.m_data << 1;
storage.m_cols << 1;
}
storage.m_rows << 0;
QBENCHMARK {
storage.insertColumns(42, 3);
}
}
void PointStorageBenchmark::testDeleteColumnsPerformance()
{
PointStorage<int> storage;
for (int c = 0; c < KS_colMax; ++c) {
storage.m_data << 1;
storage.m_cols << 1;
}
storage.m_rows << 0;
QBENCHMARK {
storage.removeColumns(42, 3);
}
}
void PointStorageBenchmark::testInsertRowsPerformance()
{
PointStorage<int> storage;
for (int r = 0; r < KS_rowMax; ++r) {
storage.m_data << 1;
storage.m_cols << 1;
storage.m_rows << r;
}
QBENCHMARK {
storage.insertRows(42, 3);
}
}
void PointStorageBenchmark::testDeleteRowsPerformance()
{
PointStorage<int> storage;
for (int r = 0; r < KS_rowMax; ++r) {
storage.m_data << 1;
storage.m_cols << 1;
storage.m_rows << r;
}
QBENCHMARK {
storage.removeRows(42, 3);
}
}
void PointStorageBenchmark::testShiftLeftPerformance()
{
PointStorage<int> storage;
for (int c = 0; c < KS_colMax; ++c) {
storage.m_data << 1;
storage.m_cols << 1;
}
storage.m_rows << 0;
QBENCHMARK {
storage.removeShiftLeft(QRect(42, 1, 3, 1));
}
}
void PointStorageBenchmark::testShiftRightPerformance()
{
PointStorage<int> storage;
for (int c = 0; c < KS_colMax; ++c) {
storage.m_data << 1;
storage.m_cols << 1;
}
storage.m_rows << 0;
QBENCHMARK {
storage.insertShiftRight(QRect(42, 1, 3, 1));
}
}
void PointStorageBenchmark::testShiftUpPerformance()
{
PointStorage<int> storage;
for (int r = 0; r < KS_rowMax; ++r) {
storage.m_data << 1;
storage.m_cols << 1;
storage.m_rows << r;
}
QBENCHMARK {
storage.removeShiftUp(QRect(1, 42, 1, 3));
}
}
void PointStorageBenchmark::testShiftDownPerformance()
{
PointStorage<int> storage;
for (int r = 0; r < KS_rowMax; ++r) {
storage.m_data << 1;
storage.m_cols << 1;
storage.m_rows << r;
}
storage.m_rows << 0;
QBENCHMARK {
storage.insertShiftDown(QRect(1, 42, 1, 3));
}
}
void PointStorageBenchmark::testIterationPerformance_data()
{
QTest::addColumn<int>("maxrow");
QTest::addColumn<int>("maxcol");
QTest::newRow("very small") << 5 << 5;
QTest::newRow("fit to screen") << 30 << 20;
QTest::newRow("medium") << 100 << 100;
QTest::newRow("large") << 1000 << 1000;
QTest::newRow("typical data: more rows") << 10000 << 100;
QTest::newRow("20 times larger") << 10000 << 2000;
QTest::newRow("not really typical: more columns") << 100 << 10000;
QTest::newRow("hopelessly large") << 8000 << 8000;
#if 0
QTest::newRow("some complete columns; KS_colMax-10, because of max lookup range of width 10 below") << 10 << 32757;
QTest::newRow("some complete rows; KS_rowMax-10, because of max lookup range of height 10 below") << 32757 << 10;
#endif
}
void PointStorageBenchmark::testIterationPerformance()
{
PointStorage<int> storage;
QFETCH(int, maxrow);
QFETCH(int, maxcol);
storage.clear();
for (int r = 0; r < maxrow; ++r) {
for (int c = 0; c < maxcol; ++c) {
storage.m_data << c;
storage.m_cols << (c + 1);
}
storage.m_rows << r*maxcol;
}
// qDebug() << endl << qPrintable( storage.dump() );
QString prefix = QString("%1 x %2").arg(maxrow).arg(maxcol);
QBENCHMARK {
int v;
for (int i = 0; i < storage.count(); ++i) {
v = storage.data(i);
}
}
}
QTEST_MAIN(PointStorageBenchmark)
#include "BenchmarkPointStorage.moc"
| TheTypoMaster/calligra-history | kspread/tests/BenchmarkPointStorage.cpp | C++ | gpl-2.0 | 7,285 |
/*
* Script element for command execution.
* Copyright (C) 2009-2010 Petr Kubanek <petr@kubanek.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "elementexe.h"
#include "rts2script/execcli.h"
#include "rts2script/script.h"
using namespace rts2script;
using namespace rts2image;
ConnExecute::ConnExecute (Execute *_masterElement, rts2core::Block *_master, const char *_exec):ConnExe (_master, _exec, true)
{
masterElement = _masterElement;
exposure_started = 0;
keep_next_image = false;
waitTargetMove = false;
}
ConnExecute::~ConnExecute ()
{
if (masterElement != NULL)
{
if (masterElement->getClient () != NULL)
masterElement->getClient ()->postEvent (new rts2core::Event (EVENT_COMMAND_OK));
masterElement->deleteExecConn ();
}
for (std::list <Image *>::iterator iter = images.begin (); iter != images.end (); iter++)
{
logStream (MESSAGE_WARNING) << "removing image " << (*iter)->getAbsoluteFileName () << ", you probably don't want this - please make sure images are processed in script" << sendLog;
(*iter)->deleteImage ();
deleteImage (*iter);
}
}
void ConnExecute::postEvent (rts2core::Event *event)
{
switch (event->getType ())
{
case EVENT_MOVE_OK:
if (waitTargetMove)
writeToProcess ("0");
if (masterElement && masterElement->getConnection ())
logStream (MESSAGE_DEBUG) << masterElement->getConnection ()->getName () << " elementexe get EVENT_MOVE_OK" << sendLog;
break;
case EVENT_MOVE_FAILED:
if (waitTargetMove)
{
writeToProcess ("! move failed");
writeToProcess ("ERR");
}
if (masterElement && masterElement->getConnection ())
logStream (MESSAGE_DEBUG) << masterElement->getConnection ()->getName () << " elementexe get EVENT_MOVE_FAILED" << sendLog;
break;
}
ConnExe::postEvent (event);
}
void ConnExecute::notActive ()
{
// waiting for image - this will not be returned
switch (exposure_started)
{
case 1:
writeToProcess ("& exposure interrupted");
exposure_started = -5;
break;
case 2:
writeToProcess ("& readout interruped");
exposure_started = -6;
break;
}
ConnExe::notActive ();
}
void ConnExecute::processCommand (char *cmd)
{
char *imagename;
char *expandPath;
char *device;
char *value;
char *operat;
char *operand;
char *comm;
if (!strcasecmp (cmd, "exposure"))
{
if (!checkActive (true))
return;
if (masterElement == NULL || masterElement->getConnection () == NULL || masterElement->getClient () == NULL)
return;
masterElement->getConnection ()->queCommand (new rts2core::CommandExposure (getMaster (), (rts2core::DevClientCamera *) masterElement->getClient (), BOP_EXPOSURE));
exposure_started = 1;
}
else if (!strcasecmp (cmd, "exposure_wfn") || !strcasecmp (cmd, "exposure_overwrite"))
{
if (!checkActive (true))
return;
if (paramNextString (&imagename))
return;
if (masterElement == NULL || masterElement->getConnection () == NULL || masterElement->getClient () == NULL)
return;
((rts2script::DevClientCameraExec *) masterElement->getClient ())->setExpandPath (imagename);
((rts2script::DevClientCameraExec *) masterElement->getClient ())->setOverwrite (!strcasecmp (cmd, "exposure_overwrite"));
masterElement->getConnection ()->queCommand (new rts2core::CommandExposure (getMaster (), (rts2core::DevClientCamera *) masterElement->getClient (), BOP_EXPOSURE));
keep_next_image = true;
exposure_started = 1;
}
else if (!strcasecmp (cmd, "progress"))
{
double start,end;
if (paramNextDouble (&start) || paramNextDouble (&end) || !paramEnd ())
return;
if (masterElement == NULL || masterElement->getClient () == NULL)
return;
((DevClientCameraExec *) masterElement->getClient ())->scriptProgress (start, end);
}
else if (!strcasecmp (cmd, "radec"))
{
if (!checkActive ())
return;
struct ln_equ_posn radec;
if (paramNextHMS (&radec.ra) || paramNextDMS (&radec.dec) || !paramEnd ())
return;
master->postEvent (new rts2core::Event (EVENT_CHANGE_TARGET, (void *) &radec));
}
else if (!strcasecmp (cmd, "newobs"))
{
if (!checkActive ())
return;
struct ln_equ_posn radec;
if (paramNextHMS (&radec.ra) || paramNextDMS (&radec.dec) || !paramEnd ())
return;
master->postEvent (new rts2core::Event (EVENT_NEW_TARGET, (void *) &radec));
}
else if (!strcasecmp (cmd, "altaz"))
{
if (!checkActive (false))
return;
struct ln_hrz_posn hrz;
if (paramNextDMS (&hrz.alt) || paramNextDMS (&hrz.az) || !paramEnd ())
return;
master->postEvent (new rts2core::Event (EVENT_CHANGE_TARGET_ALTAZ, (void *) &hrz));
}
else if (!strcasecmp (cmd, "newaltaz"))
{
if (!checkActive (false))
return;
struct ln_hrz_posn hrz;
if (paramNextDMS (&hrz.alt) || paramNextDMS (&hrz.az) || !paramEnd ())
return;
master->postEvent (new rts2core::Event (EVENT_NEW_TARGET_ALTAZ, (void *) &hrz));
}
else if (!strcmp (cmd, "dark"))
{
if (paramNextString (&imagename))
return;
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
(*iter)->toDark ();
writeToProcess ((*iter)->getAbsoluteFileName ());
if (masterElement != NULL && masterElement->getClient () != NULL)
((DevClientCameraExec *) masterElement->getClient ())->queImage (*iter);
deleteImage (*iter);
images.erase (iter);
}
else
{
logStream (MESSAGE_ERROR) << "cannot move " << imagename << " to dark path, image was probably already handled (renamed,..)" << sendLog;
}
}
else if (!strcmp (cmd, "flat"))
{
if (paramNextString (&imagename))
return;
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
(*iter)->toFlat ();
writeToProcess ((*iter)->getAbsoluteFileName ());
if (masterElement != NULL && masterElement->getClient () != NULL)
((DevClientCameraExec *) masterElement->getClient ())->queImage (*iter);
deleteImage (*iter);
images.erase (iter);
}
else
{
logStream (MESSAGE_ERROR) << "cannot move " << imagename << " to flat path, image was probably already handled (renamed,..)" << sendLog;
}
}
else if (!strcmp (cmd, "archive"))
{
if (paramNextString (&imagename))
return;
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
(*iter)->toArchive ();
writeToProcess ((*iter)->getAbsoluteFileName ());
deleteImage (*iter);
images.erase (iter);
}
else
{
logStream (MESSAGE_ERROR) << "cannot move " << imagename << " to archive path, image was probably already handled (renamed,..)" << sendLog;
}
}
else if (!strcmp (cmd, "trash"))
{
if (paramNextString (&imagename))
return;
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
(*iter)->toTrash ();
writeToProcess ((*iter)->getAbsoluteFileName ());
deleteImage (*iter);
images.erase (iter);
}
else
{
logStream (MESSAGE_ERROR) << "cannot move " << imagename << " to trash path, image was probably already handled (renamed,..)" << sendLog;
}
}
else if (!strcmp (cmd, "rename"))
{
if (paramNextString (&imagename) || paramNextString (&expandPath))
return;
try
{
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
(*iter)->renameImageExpand (expandPath);
writeToProcess ((*iter)->getAbsoluteFileName ());
deleteImage (*iter);
images.erase (iter);
}
else
{
logStream (MESSAGE_ERROR) << "cannot rename " << imagename << ", image was probably already handled (renamed,..)" << sendLog;
}
}
catch (rts2core::Error &er)
{
writeToProcess ((std::string ("E failed ") + er.what ()).c_str ());
}
}
else if (!strcmp (cmd, "move"))
{
if (paramNextString (&imagename) || paramNextString (&expandPath))
return;
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
(*iter)->renameImageExpand (expandPath);
writeToProcess ((*iter)->getAbsoluteFileName ());
(*iter)->deleteFromDB ();
deleteImage (*iter);
images.erase (iter);
}
else
{
logStream (MESSAGE_ERROR) << "cannot move " << imagename << ", image was probably already handled (renamed,..)" << sendLog;
}
}
else if (!strcmp (cmd, "copy"))
{
if (paramNextString (&imagename) || paramNextString (&expandPath))
return;
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
(*iter)->copyImageExpand (expandPath);
writeToProcess ((*iter)->getAbsoluteFileName ());
}
else
{
logStream (MESSAGE_ERROR) << "cannot copy " << imagename << ", image was probably already handled (renamed,..)" << sendLog;
}
}
else if (!strcmp (cmd, "delete"))
{
if (paramNextString (&imagename))
return;
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
(*iter)->deleteImage ();
deleteImage (*iter);
images.erase (iter);
}
}
else if (!strcmp (cmd, "process"))
{
if (paramNextString (&imagename) || masterElement == NULL || masterElement->getClient () == NULL)
return;
std::list <Image *>::iterator iter = findImage (imagename);
if (iter != images.end ())
{
((DevClientCameraExec *) masterElement->getClient ())->queImage (*iter);
deleteImage (*iter);
images.erase (iter);
}
else
{
logStream (MESSAGE_ERROR) << "cannot process " << imagename << ", image was probably already handled (renamed,..)" << sendLog;
}
}
else if (!strcmp (cmd, "?"))
{
if (paramNextString (&value) || masterElement == NULL || masterElement->getConnection () == NULL)
return;
rts2core::Value *val = masterElement->getConnection()->getValue (value);
if (val)
{
writeToProcess (val->getValue ());
return;
}
writeToProcess ("ERR");
}
else if (!strcmp (cmd, "command"))
{
if (!checkActive (false))
return;
if ((comm = paramNextWholeString ()) == NULL || masterElement == NULL || masterElement->getConnection () == NULL)
return;
masterElement->getConnection ()->queCommand (new rts2core::Command (getMaster (), comm));
}
else if (!strcmp (cmd, "VT"))
{
if (!checkActive (false))
return;
if (paramNextString (&device) || paramNextString (&value) || paramNextString (&operat) || (operand = paramNextWholeString ()) == NULL || masterElement == NULL || masterElement->getClient () == NULL)
return;
int deviceTypeNum = getDeviceType (device);
rts2core::CommandChangeValue cmdch (masterElement->getClient (), std::string (value), *operat, std::string (operand), true);
getMaster ()->queueCommandForType (deviceTypeNum, cmdch);
}
else if (!strcmp (cmd, "value"))
{
if (paramNextString (&value) || paramNextString (&operat) || (operand = paramNextWholeString ()) == NULL || masterElement == NULL || masterElement->getConnection () == NULL || masterElement->getClient () == NULL)
return;
masterElement->getConnection ()->queCommand (new rts2core::CommandChangeValue (masterElement->getClient (), std::string (value), *operat, std::string (operand), true));
}
else if (!strcmp (cmd, "device_by_type"))
{
if (paramNextString (&device))
return;
rts2core::connections_t::iterator iter = getMaster ()->getConnections ()->begin ();
getMaster ()->getOpenConnectionType (getDeviceType (device), iter);
if (iter != getMaster ()->getConnections ()->end ())
writeToProcess ((*iter)->getName ());
else
writeToProcess ("! cannot find device with given name");
}
else if (!strcmp (cmd, "end_script"))
{
masterElement->requestEndScript ();
notActive ();
}
else if (!strcmp (cmd, "end_target"))
{
notActive ();
master->postEvent (new rts2core::Event (EVENT_STOP_OBSERVATION));
}
else if (!strcmp (cmd, "stop_target"))
{
notActive ();
master->postEvent (new rts2core::Event (EVENT_STOP_TARGET));
}
else if (!strcmp (cmd, "wait_target_move"))
{
if (masterElement->getTarget ())
{
if (masterElement->getTarget ()->wasMoved ())
{
writeToProcess ("0");
}
else
{
waitTargetMove = true;
}
}
else
{
writeToProcess ("! there isn't target to wait for");
writeToProcess ("ERR");
}
}
else if (!strcmp (cmd, "target_disable"))
{
if (masterElement->getTarget ())
{
masterElement->getTarget ()->setTargetEnabled (false);
masterElement->getTarget ()->save (true);
}
}
else if (!strcmp (cmd, "target_tempdisable"))
{
int ti;
if (paramNextInteger (&ti) || masterElement->getTarget () == NULL)
return;
time_t now;
time (&now);
now += ti;
masterElement->getTarget ()->setNextObservable (&now);
masterElement->getTarget ()->save (true);
}
else if (!strcmp (cmd, "loopcount"))
{
std::ostringstream os;
if (masterElement == NULL || masterElement->getScript () == NULL)
os << "-1";
else
os << masterElement->getScript ()->getLoopCount ();
writeToProcess (os.str ().c_str ());
}
else if (!strcmp (cmd, "run_device"))
{
if (masterElement == NULL || masterElement->getConnection () == NULL)
writeToProcess ("& not active");
else
writeToProcess (masterElement->getConnection ()->getName ());
}
else
{
ConnExe::processCommand (cmd);
}
}
void ConnExecute::connectionError (int last_data_size)
{
rts2core::ConnFork::connectionError (last_data_size);
// inform master to delete us..
if (masterElement != NULL)
{
if (masterElement->getClient () != NULL)
masterElement->getClient ()->postEvent (new rts2core::Event (EVENT_COMMAND_OK));
if (masterElement)
masterElement->deleteExecConn ();
}
masterElement = NULL;
}
void ConnExecute::errorReported (int current_state, int old_state)
{
switch (exposure_started)
{
case 0:
writeToProcess ("! error detected while running the script");
break;
case 1:
writeToProcess ("exposure_failed");
exposure_started = -1;
break;
case 2:
writeToProcess ("! device failed");
writeToProcess ("ERR");
exposure_started = -2;
break;
}
}
void ConnExecute::exposureEnd (bool expectImage)
{
if (exposure_started == 1)
{
if (expectImage)
{
writeToProcess ("exposure_end");
exposure_started = 2;
}
else
{
writeToProcess ("exposure_end_noimage");
exposure_started = 0;
}
}
else
{
logStream (MESSAGE_WARNING) << "script received end-of-exposure without starting it. This probably signal out-of-sync communication between executor and camera" << sendLog;
}
}
void ConnExecute::exposureFailed ()
{
switch (exposure_started)
{
case 1:
writeToProcess ("exposure_failed");
exposure_started = -3;
break;
case 2:
writeToProcess ("! exposure failed");
writeToProcess ("ERR");
exposure_started = -4;
break;
default:
logStream (MESSAGE_WARNING) << "script received failure of exposure without starting one. This probably signal out-of-sync communication" << sendLog;
}
}
int ConnExecute::processImage (Image *image)
{
if (exposure_started == 2)
{
std::string imgn = image->getAbsoluteFileName ();
if (keep_next_image)
{
keep_next_image = false;
}
else
{
images.push_back (image);
}
image->saveImage ();
writeToProcess ((std::string ("image ") + imgn).c_str ());
exposure_started = 0;
}
else
{
logStream (MESSAGE_WARNING) << "script executes method to start image processing without trigerring an exposure (" << exposure_started << ")" << sendLog;
return -1;
}
return 1;
}
bool ConnExecute::knowImage (Image * image)
{
return (std::find (images.begin (), images.end (), image) != images.end ());
}
std::list <Image *>::iterator ConnExecute::findImage (const char *path)
{
std::list <Image *>::iterator iter;
for (iter = images.begin (); iter != images.end (); iter++)
{
if (!strcmp (path, (*iter)->getAbsoluteFileName ()))
return iter;
}
return iter;
}
Execute::Execute (Script * _script, rts2core::Block * _master, const char *_exec, Rts2Target *_target): Element (_script)
{
connExecute = NULL;
client = NULL;
master = _master;
exec = _exec;
target = _target;
endScript = false;
}
Execute::~Execute ()
{
if (connExecute)
{
errno = 0;
connExecute->nullMasterElement ();
connExecute->endConnection ();
deleteExecConn ();
}
client = NULL;
}
void Execute::errorReported (int current_state, int old_state)
{
if (connExecute)
{
connExecute->errorReported (current_state, old_state);
}
Element::errorReported (current_state, old_state);
}
void Execute::exposureEnd (bool expectImage)
{
if (connExecute)
{
connExecute->exposureEnd (expectImage);
return;
}
Element::exposureEnd (expectImage);
}
void Execute::exposureFailed ()
{
if (connExecute)
{
connExecute->exposureFailed ();
return;
}
Element::exposureFailed ();
}
void Execute::notActive ()
{
if (connExecute)
connExecute->notActive ();
}
int Execute::processImage (Image *image)
{
if (connExecute)
return connExecute->processImage (image);
return Element::processImage (image);
}
bool Execute::knowImage (Image *image)
{
if (connExecute)
return connExecute->knowImage (image);
return Element::knowImage (image);
}
int Execute::defnextCommand (rts2core::DevClient * _client, rts2core::Command ** new_command, char new_device[DEVICE_NAME_SIZE])
{
if (connExecute == NULL)
{
connExecute = new ConnExecute (this, master, exec);
int ret = connExecute->init ();
if (ret)
{
logStream (MESSAGE_ERROR) << "Cannot execute script control command, ending script. Script will not be executed again." << sendLog;
return NEXT_COMMAND_STOP_TARGET;
}
client = _client;
client->getMaster ()->addConnection (connExecute);
}
if (endScript)
{
connExecute->nullMasterElement ();
connExecute = NULL;
return NEXT_COMMAND_END_SCRIPT;
}
if (connExecute->getConnState () == CONN_DELETE)
{
connExecute->nullMasterElement ();
// connExecute will be deleted by rts2core::Block holding connection
connExecute = NULL;
client = NULL;
return NEXT_COMMAND_NEXT;
}
return NEXT_COMMAND_KEEP;
}
| xyficu/rts2 | lib/rts2script/elementexe.cpp | C++ | gpl-2.0 | 18,530 |
#if defined(_WIN64) || defined(WIN64) || defined(_WIN32) || defined(WIN32)
#include <windows.h>
#endif
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#if defined(__unix__) || defined(__unix) || defined(unix) || defined(__linux__) || defined(__linux) || defined(linux)
#include <unistd.h>
#endif
namespace {
namespace local {
} // namespace local
} // unnamed namespace
namespace my_pictorial_structures_revisited {
int pictorial_structures_revisited_partapp_main(int argc, char *argv[]);
} // namespace my_pictorial_structures_revisited
// [ref] ${PictorialStructureRevisited_HOME}/ReadMe.txt
//
// -. to compute part posteriors for a single image
// pictorial_structures_revisited.exe --expopt ./expopt/<EXP_FILENAME> --part_detect --find_obj --first <IMGIDX> --numimgs 1
// examples of <EXP_FILENAME>
// ./expopt/exp_buffy_hog_detections.txt
// ./expopt/exp_ramanan_075.txt
// ./expopt/exp_tud_upright_people.txt
//
// -. to precess the whole dataset
// pictorial_structures_revisited.exe --expopt ./expopt/<EXP_FILENAME> --part_detect --find_obj
//
// -. to evaluate the number of correctly detected parts
// pictorial_structures_revisited.exe --expopt ./expopt/<EXP_FILENAME> --eval_segments --first <IMGIDX> --numimgs 1
// this command will also produce visualization of the max-marginal part estimates in the "part_marginals/seg_eval_images" directory
//
// -. to extract object hypothesis
// pictorial_structures_revisited.exe --expopt ./expopt/<EXP_FILENAME> --save_res
// this will produce annotation files in the same format as training and test data.
//
// -. pretrained model (classifiers and joint parameters)
// ./log_dir/<EXP_NAME>/class
//
// -. at runtime the following directories will be created:
// ./log_dir/<EXP_NAME>/test_scoregrid - location where part detections will be stored
// ./log_dir/<EXP_NAME>/part_marginals - location where part marginals will be stored
// ./log_dir/<EXP_NAME>/part_marginals/seg_eval_images
int pictorial_structures_revisited_main(int argc, char *argv[])
{
#if 0
// testing
const std::string curr_directory("./data/object_representation/pictorial_structures_revisited/code_test");
const std::string exp_filename("./expopt/exp_code_test.txt");
#else
// experiment
const std::string curr_directory("./data/object_representation/pictorial_structures_revisited/partapp-experiments-r2");
const std::string exp_filename("./expopt/exp_buffy_hog_detections.txt");
//const std::string exp_filename("./expopt/exp_ramanan_075.txt");
//const std::string exp_filename("./expopt/exp_tud_upright_people.txt");
#endif
const int first_image_idx = 0;
const int num_images = 1;
std::ostringstream sstream1, sstream2;
sstream1 << first_image_idx;
sstream2 << num_images;
//
#if defined(_WIN64) || defined(WIN64) || defined(_WIN32) || defined(WIN32)
const BOOL retval = SetCurrentDirectoryA(curr_directory.c_str());
#elif defined(__unix__) || defined(__unix) || defined(unix) || defined(__linux__) || defined(__linux) || defined(linux)
const int retval = chdir(curr_directory.c_str());
#endif
#if 1
const int my_argc = 5;
const char *my_argv[my_argc] = {
argv[0],
"--expopt", exp_filename.c_str(),
"--part_detect", "--find_obj"
};
#elif 0
const int my_argc = 9;
const char *my_argv[my_argc] = {
argv[0],
"--expopt", exp_filename.c_str(),
"--part_detect", "--find_obj",
"--first", sstream1.str().c_str(),
"--numimgs", sstream2.str().c_str()
};
#elif 0
const int my_argc = 4;
const char *my_argv[] = {
argv[0],
"--expopt", exp_filename.c_str(),
"--eval_segments"
};
#elif 0
const int my_argc = 8;
const char *my_argv[my_argc] = {
argv[0],
"--expopt", exp_filename.c_str(),
"--eval_segments",
"--first", sstream1.str().c_str(),
"--numimgs", sstream2.str().c_str()
};
#endif
std::cout << "-----------------------------------------" << std::endl;
for (int i = 0; i < my_argc; ++i)
std::cout << "argv[" << i << "] : " << my_argv[i] << std::endl;
const char *home = getenv("HOME");
if (home)
std::cout << "environment variable, HOME = " << home << std::endl;
else
{
std::cout << "environment variable, HOME, is not found" << std::endl;
return -1;
}
std::cout << "-----------------------------------------" << std::endl;
my_pictorial_structures_revisited::pictorial_structures_revisited_partapp_main(my_argc, (char **)my_argv);
return 0;
}
| sangwook236/general-development-and-testing | sw_dev/cpp/rnd/test/object_representation/pictorial_structures_revisited/pictorial_structures_revisited_main.cpp | C++ | gpl-2.0 | 4,524 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Pdf
* @subpackage Annotation
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Link.php 17652 2009-08-17 20:38:15Z mikaelkael $
*/
/** Zend_Pdf_Annotation */
require_once 'Zend/Pdf/Annotation.php';
/** Zend_Pdf_Destination */
require_once 'Zend/Pdf/Destination.php';
/**
* A link annotation represents either a hypertext link to a destination elsewhere in
* the document or an action to be performed.
*
* Only destinations are used now since only GoTo action can be created by user
* in current implementation.
*
* @package Zend_Pdf
* @subpackage Annotation
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Pdf_Annotation_Link extends Zend_Pdf_Annotation
{
/**
* Annotation object constructor
*
* @throws Zend_Pdf_Exception
*/
public function __construct(Zend_Pdf_Element $annotationDictionary)
{
if ($annotationDictionary->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Annotation dictionary resource has to be a dictionary.');
}
if ($annotationDictionary->Subtype === null ||
$annotationDictionary->Subtype->getType() != Zend_Pdf_Element::TYPE_NAME ||
$annotationDictionary->Subtype->value != 'Link') {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Subtype => Link entry is requires');
}
parent::__construct($annotationDictionary);
}
/**
* Create link annotation object
*
* @param float $x1
* @param float $y1
* @param float $x2
* @param float $y2
* @param Zend_Pdf_Target|string $target
* @return Zend_Pdf_Annotation_Link
*/
public static function create($x1, $y1, $x2, $y2, $target)
{
if (is_string($target)) {
require_once 'Zend/Pdf/Destination/Named.php';
$destination = Zend_Pdf_Destination_Named::create($target);
}
if (!$target instanceof Zend_Pdf_Target) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('$target parameter must be a Zend_Pdf_Target object or a string.');
}
$annotationDictionary = new Zend_Pdf_Element_Dictionary();
$annotationDictionary->Type = new Zend_Pdf_Element_Name('Annot');
$annotationDictionary->Subtype = new Zend_Pdf_Element_Name('Link');
$rectangle = new Zend_Pdf_Element_Array();
$rectangle->items[] = new Zend_Pdf_Element_Numeric($x1);
$rectangle->items[] = new Zend_Pdf_Element_Numeric($y1);
$rectangle->items[] = new Zend_Pdf_Element_Numeric($x2);
$rectangle->items[] = new Zend_Pdf_Element_Numeric($y2);
$annotationDictionary->Rect = $rectangle;
if ($target instanceof Zend_Pdf_Destination) {
$annotationDictionary->Dest = $target->getResource();
} else {
$annotationDictionary->A = $target->getResource();
}
return new Zend_Pdf_Annotation_Link($annotationDictionary);
}
/**
* Set link annotation destination
*
* @param Zend_Pdf_Target|string $target
* @return Zend_Pdf_Annotation_Link
*/
public function setDestination($target)
{
if (is_string($target)) {
require_once 'Zend/Pdf/Destination/Named.php';
$destination = Zend_Pdf_Destination_Named::create($target);
}
if (!$target instanceof Zend_Pdf_Target) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('$target parameter must be a Zend_Pdf_Target object or a string.');
}
$this->_annotationDictionary->touch();
$this->_annotationDictionary->Dest = $destination->getResource();
if ($target instanceof Zend_Pdf_Destination) {
$this->_annotationDictionary->Dest = $target->getResource();
$this->_annotationDictionary->A = null;
} else {
$this->_annotationDictionary->Dest = null;
$this->_annotationDictionary->A = $target->getResource();
}
return $this;
}
/**
* Get link annotation destination
*
* @return Zend_Pdf_Target|null
*/
public function getDestination()
{
if ($this->_annotationDictionary->Dest === null &&
$this->_annotationDictionary->A === null) {
return null;
}
if ($this->_annotationDictionary->Dest !== null) {
return Zend_Pdf_Destination::load($this->_annotationDictionary->Dest);
} else {
return Zend_Pdf_Action::load($this->_annotationDictionary->A);
}
}
}
| NewTechNetwork/EchoOpen | Zend/Pdf/Annotation/Link.php | PHP | gpl-2.0 | 5,479 |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
This software is distributed under the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Axel Kohlmeyer (Temple U)
------------------------------------------------------------------------- */
#include "math.h"
#include "pair_lj_smooth_omp.h"
#include "atom.h"
#include "comm.h"
#include "force.h"
#include "neighbor.h"
#include "neigh_list.h"
#include "suffix.h"
using namespace LAMMPS_NS;
/* ---------------------------------------------------------------------- */
PairLJSmoothOMP::PairLJSmoothOMP(LAMMPS *lmp) :
PairLJSmooth(lmp), ThrOMP(lmp, THR_PAIR)
{
suffix_flag |= Suffix::OMP;
respa_enable = 0;
}
/* ---------------------------------------------------------------------- */
void PairLJSmoothOMP::compute(int eflag, int vflag)
{
if (eflag || vflag) {
ev_setup(eflag,vflag);
} else evflag = vflag_fdotr = 0;
const int nall = atom->nlocal + atom->nghost;
const int nthreads = comm->nthreads;
const int inum = list->inum;
#if defined(_OPENMP)
#pragma omp parallel default(none) shared(eflag,vflag)
#endif
{
int ifrom, ito, tid;
loop_setup_thr(ifrom, ito, tid, inum, nthreads);
ThrData *thr = fix->get_thr(tid);
ev_setup_thr(eflag, vflag, nall, eatom, vatom, thr);
if (evflag) {
if (eflag) {
if (force->newton_pair) eval<1,1,1>(ifrom, ito, thr);
else eval<1,1,0>(ifrom, ito, thr);
} else {
if (force->newton_pair) eval<1,0,1>(ifrom, ito, thr);
else eval<1,0,0>(ifrom, ito, thr);
}
} else {
if (force->newton_pair) eval<0,0,1>(ifrom, ito, thr);
else eval<0,0,0>(ifrom, ito, thr);
}
reduce_thr(this, eflag, vflag, thr);
} // end of omp parallel region
}
template <int EVFLAG, int EFLAG, int NEWTON_PAIR>
void PairLJSmoothOMP::eval(int iifrom, int iito, ThrData * const thr)
{
int i,j,ii,jj,jnum,itype,jtype;
double xtmp,ytmp,ztmp,delx,dely,delz,evdwl,fpair;
double rsq,r2inv,r6inv,forcelj,factor_lj;
double r,t,tsq,fskin;
int *ilist,*jlist,*numneigh,**firstneigh;
evdwl = 0.0;
const double * const * const x = atom->x;
double * const * const f = thr->get_f();
const int * const type = atom->type;
const int nlocal = atom->nlocal;
const double * const special_lj = force->special_lj;
double fxtmp,fytmp,fztmp;
ilist = list->ilist;
numneigh = list->numneigh;
firstneigh = list->firstneigh;
// loop over neighbors of my atoms
for (ii = iifrom; ii < iito; ++ii) {
i = ilist[ii];
xtmp = x[i][0];
ytmp = x[i][1];
ztmp = x[i][2];
itype = type[i];
jlist = firstneigh[i];
jnum = numneigh[i];
fxtmp=fytmp=fztmp=0.0;
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
factor_lj = special_lj[sbmask(j)];
j &= NEIGHMASK;
delx = xtmp - x[j][0];
dely = ytmp - x[j][1];
delz = ztmp - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j];
if (rsq < cutsq[itype][jtype]) {
r2inv = 1.0/rsq;
if (rsq < cut_inner_sq[itype][jtype]) {
r6inv = r2inv*r2inv*r2inv;
forcelj = r6inv * (lj1[itype][jtype]*r6inv-lj2[itype][jtype]);
} else {
r = sqrt(rsq);
t = r - cut_inner[itype][jtype];
tsq = t*t;
fskin = ljsw1[itype][jtype] + ljsw2[itype][jtype]*t +
ljsw3[itype][jtype]*tsq + ljsw4[itype][jtype]*tsq*t;
forcelj = fskin*r;
}
fpair = factor_lj*forcelj*r2inv;
fxtmp += delx*fpair;
fytmp += dely*fpair;
fztmp += delz*fpair;
if (NEWTON_PAIR || j < nlocal) {
f[j][0] -= delx*fpair;
f[j][1] -= dely*fpair;
f[j][2] -= delz*fpair;
}
if (EFLAG) {
if (rsq < cut_inner_sq[itype][jtype])
evdwl = r6inv * (lj3[itype][jtype]*r6inv -
lj4[itype][jtype]) - offset[itype][jtype];
else
evdwl = ljsw0[itype][jtype] - ljsw1[itype][jtype]*t -
ljsw2[itype][jtype]*tsq/2.0 - ljsw3[itype][jtype]*tsq*t/3.0 -
ljsw4[itype][jtype]*tsq*tsq/4.0 - offset[itype][jtype];
evdwl *= factor_lj;
}
if (EVFLAG) ev_tally_thr(this,i,j,nlocal,NEWTON_PAIR,
evdwl,0.0,fpair,delx,dely,delz,thr);
}
}
f[i][0] += fxtmp;
f[i][1] += fytmp;
f[i][2] += fztmp;
}
}
/* ---------------------------------------------------------------------- */
double PairLJSmoothOMP::memory_usage()
{
double bytes = memory_usage_thr();
bytes += PairLJSmooth::memory_usage();
return bytes;
}
| tm1249wk/WASHLIGGGHTS-2.3.7 | src/USER-OMP/pair_lj_smooth_omp.cpp | C++ | gpl-2.0 | 4,740 |
/* $Id: tstRTHttp.cpp $ */
/** @file
* IPRT Testcase - Simple cURL testcase.
*/
/*
* Copyright (C) 2012-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/err.h>
#include <iprt/http.h>
#include <iprt/mem.h>
#include <iprt/file.h>
#include <iprt/stream.h>
#include <iprt/string.h>
#include <iprt/initterm.h>
#include <iprt/vfslowlevel.h>
#include <iprt/zip.h>
#define CAFILE_NAME "tstHttp-tempcafile.crt"
static int extractPCA3G5(RTHTTP hHttp, PRTSTREAM CAFile, uint8_t *pu8Buf, size_t cbBuf)
{
uint8_t *abSha1;
size_t cbSha1;
uint8_t *abSha512;
size_t cbSha512;
char *pszBuf = (char*)pu8Buf;
const uint8_t abSha1PCA3G5[] =
{
0x4e, 0xb6, 0xd5, 0x78, 0x49, 0x9b, 0x1c, 0xcf, 0x5f, 0x58,
0x1e, 0xad, 0x56, 0xbe, 0x3d, 0x9b, 0x67, 0x44, 0xa5, 0xe5
};
const uint8_t abSha512PCA3G5[] =
{
0xd4, 0xf8, 0x10, 0x54, 0x72, 0x77, 0x0a, 0x2d,
0xe3, 0x17, 0xb3, 0xcf, 0xed, 0x61, 0xae, 0x5c,
0x5d, 0x3e, 0xde, 0xa1, 0x41, 0x35, 0xb2, 0xdf,
0x60, 0xe2, 0x61, 0xfe, 0x3a, 0xc1, 0x66, 0xa3,
0x3c, 0x88, 0x54, 0x04, 0x4f, 0x1d, 0x13, 0x46,
0xe3, 0x8c, 0x06, 0x92, 0x9d, 0x70, 0x54, 0xc3,
0x44, 0xeb, 0x2c, 0x74, 0x25, 0x9e, 0x5d, 0xfb,
0xd2, 0x6b, 0xa8, 0x9a, 0xf0, 0xb3, 0x6a, 0x01
};
int rc = RTHttpCertDigest(hHttp, pszBuf, cbBuf,
&abSha1, &cbSha1, &abSha512, &cbSha512);
if (RT_SUCCESS(rc))
{
if (cbSha1 != sizeof(abSha1PCA3G5))
{
RTPrintf("Wrong SHA1 digest size of PCA-3G5\n");
rc = VERR_INTERNAL_ERROR;
}
else if (memcmp(abSha1PCA3G5, abSha1, cbSha1))
{
RTPrintf("Wrong SHA1 digest for PCA-3G5:\n"
"Got: %.*Rhxs\n"
"Expected: %.*Rhxs\n",
cbSha1, abSha1, sizeof(abSha1PCA3G5), abSha1PCA3G5);
rc = VERR_INTERNAL_ERROR;
}
if (cbSha512 != sizeof(abSha512PCA3G5))
{
RTPrintf("Wrong SHA512 digest size of PCA-3G5\n");
rc = VERR_INTERNAL_ERROR;
}
else if (memcmp(abSha512PCA3G5, abSha512, cbSha512))
{
RTPrintf("Wrong SHA512 digest for PCA-3G5:\n"
"Got: %.*Rhxs\n"
"Expected: %.*Rhxs\n",
cbSha512, abSha512, sizeof(abSha512PCA3G5), abSha512PCA3G5);
rc = VERR_INTERNAL_ERROR;
}
RTMemFree(abSha1);
RTMemFree(abSha512);
if (RT_SUCCESS(rc))
rc = RTStrmWrite(CAFile, pszBuf, cbBuf);
if (RT_SUCCESS(rc))
rc = RTStrmWrite(CAFile, RTFILE_LINEFEED, strlen(RTFILE_LINEFEED));
}
return rc;
}
static int extractPCA3(RTHTTP hHttp, PRTSTREAM CAFile, uint8_t *pu8Buf, size_t cbBuf)
{
uint8_t *abSha1;
size_t cbSha1;
uint8_t *abSha512;
size_t cbSha512;
char *pszBuf = (char*)pu8Buf;
const uint8_t abSha1PCA3[] =
{
0xa1, 0xdb, 0x63, 0x93, 0x91, 0x6f, 0x17, 0xe4, 0x18, 0x55,
0x09, 0x40, 0x04, 0x15, 0xc7, 0x02, 0x40, 0xb0, 0xae, 0x6b
};
const uint8_t abSha512PCA3[] =
{
0xbb, 0xf7, 0x8a, 0x19, 0x9f, 0x37, 0xee, 0xa2,
0xce, 0xc8, 0xaf, 0xe3, 0xd6, 0x22, 0x54, 0x20,
0x74, 0x67, 0x6e, 0xa5, 0x19, 0xb7, 0x62, 0x1e,
0xc1, 0x2f, 0xd5, 0x08, 0xf4, 0x64, 0xc4, 0xc6,
0xbb, 0xc2, 0xf2, 0x35, 0xe7, 0xbe, 0x32, 0x0b,
0xde, 0xb2, 0xfc, 0x44, 0x92, 0x5b, 0x8b, 0x9b,
0x77, 0xa5, 0x40, 0x22, 0x18, 0x12, 0xcb, 0x3d,
0x0a, 0x67, 0x83, 0x87, 0xc5, 0x45, 0xc4, 0x99
};
int rc = RTHttpCertDigest(hHttp, pszBuf, cbBuf,
&abSha1, &cbSha1, &abSha512, &cbSha512);
if (RT_SUCCESS(rc))
{
if (cbSha1 != sizeof(abSha1PCA3))
{
RTPrintf("Wrong SHA1 digest size of PCA-3\n");
rc = VERR_INTERNAL_ERROR;
}
else if (memcmp(abSha1PCA3, abSha1, cbSha1))
{
RTPrintf("Wrong SHA1 digest for PCA-3:\n"
"Got: %.*Rhxs\n"
"Expected: %.*Rhxs\n",
cbSha1, abSha1, sizeof(abSha1PCA3), abSha1PCA3);
rc = VERR_INTERNAL_ERROR;
}
if (cbSha512 != sizeof(abSha512PCA3))
{
RTPrintf("Wrong SHA512 digest size of PCA-3\n");
rc = VERR_INTERNAL_ERROR;
}
else if (memcmp(abSha512PCA3, abSha512, cbSha512))
{
RTPrintf("Wrong SHA512 digest for PCA-3:\n"
"Got: %.*Rhxs\n"
"Expected: %.*Rhxs\n",
cbSha512, abSha512, sizeof(abSha512PCA3), abSha512PCA3);
rc = VERR_INTERNAL_ERROR;
}
RTMemFree(abSha1);
RTMemFree(abSha512);
if (RT_SUCCESS(rc))
rc = RTStrmWrite(CAFile, pszBuf, cbBuf);
if (RT_SUCCESS(rc))
rc = RTStrmWrite(CAFile, RTFILE_LINEFEED, strlen(RTFILE_LINEFEED));
}
return rc;
}
/*
* Check for HTTP errors, in particular properly display redirections.
*/
static void checkError(RTHTTP hHttp, int rc, const char *pszFile)
{
if (rc == VERR_HTTP_REDIRECTED)
{
char *pszRedirLocation;
int rc2 = RTHttpGetRedirLocation(hHttp, &pszRedirLocation);
if (RT_SUCCESS(rc2))
RTPrintf("Redirected to '%s' trying to fetch '%s'\n", pszRedirLocation, pszFile);
else
RTPrintf("Redirected trying to fetch '%s'\n", pszFile);
RTStrFree(pszRedirLocation);
}
else
RTPrintf("Error %Rrc trying to fetch '%s'\n", rc, pszFile);
}
int main(int argc, char **argv)
{
unsigned cErrors = 0;
RTR3InitExe(argc, &argv, 0);
if (argc <= 1)
{
RTPrintf("usage: %s default\n", argv[0]);
return 1;
}
for (int i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "default"))
;
else
{
RTPrintf("Unknown parameter '%s'\n", argv[i]);
return 1;
}
}
RTHTTP hHttp;
char *pszBuf = NULL;
PRTSTREAM CAFile = NULL;
int rc = RTHttpCreate(&hHttp);
/*
* Create the certificate file
*/
if (RT_SUCCESS(rc))
rc = RTStrmOpen(CAFILE_NAME, "w+b", &CAFile);
if (RT_SUCCESS(rc))
{
/*
* The old way:
*/
/*
* Fetch the root CA certificate (new one, often avoided in cert chains by
* using an intermediate cert which is signed by old root)
*/
if (RT_SUCCESS(rc))
rc = RTHttpGetText(hHttp,
"http://www.verisign.com/repository/roots/root-certificates/PCA-3G5.pem",
&pszBuf);
if (RT_SUCCESS(rc) && pszBuf)
rc = extractPCA3G5(hHttp, CAFile, (uint8_t*)pszBuf, strlen(pszBuf));
else
checkError(hHttp, rc, "PCA-3G5.pem");
if (pszBuf)
{
RTMemFree(pszBuf);
pszBuf = NULL;
}
/*
* Fetch the root CA certificate (old one, but still very widely used)
*/
if (RT_SUCCESS(rc))
rc = RTHttpGetText(hHttp,
"http://www.verisign.com/repository/roots/root-certificates/PCA-3.pem",
&pszBuf);
if (RT_SUCCESS(rc) && pszBuf)
rc = extractPCA3(hHttp, CAFile, (uint8_t*)pszBuf, strlen(pszBuf));
else
checkError(hHttp, rc, "PCA-3.pem");
if (pszBuf)
{
RTMemFree(pszBuf);
pszBuf = NULL;
}
RTPrintf("Old way: rc=%Rrc\n", rc);
/*
* The new way:
*/
void *pu8Buf;
size_t cb;
rc = RTHttpGetBinary(hHttp,
"http://www.verisign.com/support/roots.zip",
&pu8Buf, &cb);
if (RT_SUCCESS(rc) && pu8Buf)
{
void *pvDecomp;
size_t cbDecomp;
rc = RTZipPkzipMemDecompress(&pvDecomp, &cbDecomp, pu8Buf, cb,
"VeriSign Root Certificates/Generation 5 (G5) PCA/VeriSign Class 3 Public Primary Certification Authority - G5.pem");
if (RT_SUCCESS(rc))
{
rc = extractPCA3G5(hHttp, CAFile, (uint8_t*)pvDecomp, cbDecomp);
RTMemFree(pvDecomp);
rc = RTZipPkzipMemDecompress(&pvDecomp, &cbDecomp, pu8Buf, cb,
"VeriSign Root Certificates/Generation 1 (G1) PCAs/Class 3 Public Primary Certification Authority.pem");
if (RT_SUCCESS(rc))
{
rc = extractPCA3(hHttp, CAFile, (uint8_t*)pvDecomp, cbDecomp);
RTMemFree(pvDecomp);
}
}
}
else
checkError(hHttp, rc, "roots.zip");
RTPrintf("New way: rc=%Rrc\n", rc);
}
/*
* Close the certificate file
*/
if (CAFile)
{
RTStrmClose(CAFile);
CAFile = NULL;
}
/*
* Use it
*/
if (RT_SUCCESS(rc))
rc = RTHttpSetCAFile(hHttp, CAFILE_NAME);
/*
* Now try to do the actual HTTPS request
*/
if (RT_SUCCESS(rc))
rc = RTHttpGetText(hHttp,
"https://update.virtualbox.org/query.php?platform=LINUX_32BITS_UBUNTU_12_04&version=4.1.18",
&pszBuf);
if ( RT_FAILURE(rc)
&& rc != VERR_HTTP_COULDNT_CONNECT)
cErrors++;
if (RT_FAILURE(rc))
RTPrintf("Error code: %Rrc\n", rc);
else
{
RTPrintf("Success!\n");
RTPrintf("Got: %s\n", pszBuf);
}
if (pszBuf)
{
RTMemFree(pszBuf);
pszBuf = NULL;
}
RTHttpDestroy(hHttp);
// RTFileDelete(CAFILE_NAME);
return !!cErrors;
}
| sobomax/virtualbox_64bit_edd | src/VBox/Runtime/testcase/tstRTHttp.cpp | C++ | gpl-2.0 | 11,074 |
<?php
/**
* Nette Framework
*
* @copyright Copyright (c) 2004, 2010 David Grudl
* @license http://nette.org/license Nette license
* @link http://nette.org
* @category Nette
* @package Nette\Forms
*/
/**
* Converts a Form into the HTML output.
*
* @copyright Copyright (c) 2004, 2010 David Grudl
* @package Nette\Forms
*/
class ConventionalRenderer extends Object implements IFormRenderer
{
/**
* /--- form.container
*
* /--- if (form.errors) error.container
* .... error.item [.class]
* \---
*
* /--- hidden.container
* .... HIDDEN CONTROLS
* \---
*
* /--- group.container
* .... group.label
* .... group.description
*
* /--- controls.container
*
* /--- pair.container [.required .optional .odd]
*
* /--- label.container
* .... LABEL
* .... label.suffix
* .... label.requiredsuffix
* \---
*
* /--- control.container [.odd]
* .... CONTROL [.required .text .password .file .submit .button]
* .... control.requiredsuffix
* .... control.description
* .... if (control.errors) error.container
* \---
* \---
* \---
* \---
* \--
*
* @var array of HTML tags */
public $wrappers = array(
'form' => array(
'container' => NULL,
'errors' => TRUE,
),
'error' => array(
'container' => 'ul class=error',
'item' => 'li',
),
'group' => array(
'container' => 'fieldset',
'label' => 'legend',
'description' => 'p',
),
'controls' => array(
'container' => 'table',
),
'pair' => array(
'container' => 'tr',
'.required' => 'required',
'.optional' => NULL,
'.odd' => NULL,
),
'control' => array(
'container' => 'td',
'.odd' => NULL,
'errors' => FALSE,
'description' => 'small',
'requiredsuffix' => '',
'.required' => 'required',
'.text' => 'text',
'.password' => 'text',
'.file' => 'text',
'.submit' => 'button',
'.image' => 'imagebutton',
'.button' => 'button',
),
'label' => array(
'container' => 'th',
'suffix' => NULL,
'requiredsuffix' => '',
),
'hidden' => array(
'container' => 'div',
),
);
/** @var Form */
protected $form;
/** @var int */
protected $counter;
/**
* Provides complete form rendering.
* @param Form
* @param string
* @return string
*/
public function render(Form $form, $mode = NULL)
{
if ($this->form !== $form) {
$this->form = $form;
$this->init();
}
$s = '';
if (!$mode || $mode === 'begin') {
$s .= $this->renderBegin();
}
if ((!$mode && $this->getValue('form errors')) || $mode === 'errors') {
$s .= $this->renderErrors();
}
if (!$mode || $mode === 'body') {
$s .= $this->renderBody();
}
if (!$mode || $mode === 'end') {
$s .= $this->renderEnd();
}
return $s;
}
/** @deprecated */
public function setClientScript()
{
trigger_error(__METHOD__ . '() is deprecated; use unobstructive JavaScript instead.', E_USER_WARNING);
return $this;
}
/**
* Initializes form.
* @return void
*/
protected function init()
{
// TODO: only for back compatiblity - remove?
$wrapper = & $this->wrappers['control'];
foreach ($this->form->getControls() as $control) {
if ($control->getOption('required') && isset($wrapper['.required'])) {
$control->getLabelPrototype()->class($wrapper['.required'], TRUE);
}
$el = $control->getControlPrototype();
if ($el->getName() === 'input' && isset($wrapper['.' . $el->type])) {
$el->class($wrapper['.' . $el->type], TRUE);
}
}
}
/**
* Renders form begin.
* @return string
*/
public function renderBegin()
{
$this->counter = 0;
foreach ($this->form->getControls() as $control) {
$control->setOption('rendered', FALSE);
}
if (strcasecmp($this->form->getMethod(), 'get') === 0) {
$el = clone $this->form->getElementPrototype();
$uri = explode('?', (string) $el->action, 2);
$el->action = $uri[0];
$s = '';
if (isset($uri[1])) {
foreach (preg_split('#[;&]#', $uri[1]) as $param) {
$parts = explode('=', $param, 2);
$name = urldecode($parts[0]);
if (!isset($this->form[$name])) {
$s .= Html::el('input', array('type' => 'hidden', 'name' => $name, 'value' => urldecode($parts[1])));
}
}
$s = "\n\t" . $this->getWrapper('hidden container')->setHtml($s);
}
return $el->startTag() . $s;
} else {
return $this->form->getElementPrototype()->startTag();
}
}
/**
* Renders form end.
* @return string
*/
public function renderEnd()
{
$s = '';
foreach ($this->form->getControls() as $control) {
if ($control instanceof HiddenField && !$control->getOption('rendered')) {
$s .= (string) $control->getControl();
}
}
if ($s) {
$s = $this->getWrapper('hidden container')->setHtml($s) . "\n";
}
return $s . $this->form->getElementPrototype()->endTag() . "\n";
}
/**
* Renders validation errors (per form or per control).
* @param IFormControl
* @return string
*/
public function renderErrors(IFormControl $control = NULL)
{
$errors = $control === NULL ? $this->form->getErrors() : $control->getErrors();
if (count($errors)) {
$ul = $this->getWrapper('error container');
$li = $this->getWrapper('error item');
foreach ($errors as $error) {
$item = clone $li;
if ($error instanceof Html) {
$item->add($error);
} else {
$item->setText($error);
}
$ul->add($item);
}
return "\n" . $ul->render(0);
}
}
/**
* Renders form body.
* @return string
*/
public function renderBody()
{
$s = $remains = '';
$defaultContainer = $this->getWrapper('group container');
$translator = $this->form->getTranslator();
foreach ($this->form->getGroups() as $group) {
if (!$group->getControls() || !$group->getOption('visual')) continue;
$container = $group->getOption('container', $defaultContainer);
$container = $container instanceof Html ? clone $container : Html::el($container);
$s .= "\n" . $container->startTag();
$text = $group->getOption('label');
if ($text instanceof Html) {
$s .= $text;
} elseif (is_string($text)) {
if ($translator !== NULL) {
$text = $translator->translate($text);
}
$s .= "\n" . $this->getWrapper('group label')->setText($text) . "\n";
}
$text = $group->getOption('description');
if ($text instanceof Html) {
$s .= $text;
} elseif (is_string($text)) {
if ($translator !== NULL) {
$text = $translator->translate($text);
}
$s .= $this->getWrapper('group description')->setText($text) . "\n";
}
$s .= $this->renderControls($group);
$remains = $container->endTag() . "\n" . $remains;
if (!$group->getOption('embedNext')) {
$s .= $remains;
$remains = '';
}
}
$s .= $remains . $this->renderControls($this->form);
$container = $this->getWrapper('form container');
$container->setHtml($s);
return $container->render(0);
}
/**
* Renders group of controls.
* @param FormContainer|FormGroup
* @return string
*/
public function renderControls($parent)
{
if (!($parent instanceof FormContainer || $parent instanceof FormGroup)) {
throw new InvalidArgumentException("Argument must be FormContainer or FormGroup instance.");
}
$container = $this->getWrapper('controls container');
$buttons = NULL;
foreach ($parent->getControls() as $control) {
if ($control->getOption('rendered') || $control instanceof HiddenField || $control->getForm(FALSE) !== $this->form) {
// skip
} elseif ($control instanceof Button) {
$buttons[] = $control;
} else {
if ($buttons) {
$container->add($this->renderPairMulti($buttons));
$buttons = NULL;
}
$container->add($this->renderPair($control));
}
}
if ($buttons) {
$container->add($this->renderPairMulti($buttons));
}
$s = '';
if (count($container)) {
$s .= "\n" . $container . "\n";
}
return $s;
}
/**
* Renders single visual row.
* @param IFormControl
* @return string
*/
public function renderPair(IFormControl $control)
{
$pair = $this->getWrapper('pair container');
$pair->add($this->renderLabel($control));
$pair->add($this->renderControl($control));
$pair->class($this->getValue($control->getOption('required') ? 'pair .required' : 'pair .optional'), TRUE);
$pair->class($control->getOption('class'), TRUE);
if (++$this->counter % 2) $pair->class($this->getValue('pair .odd'), TRUE);
$pair->id = $control->getOption('id');
return $pair->render(0);
}
/**
* Renders single visual row of multiple controls.
* @param array of IFormControl
* @return string
*/
public function renderPairMulti(array $controls)
{
$s = array();
foreach ($controls as $control) {
if (!($control instanceof IFormControl)) {
throw new InvalidArgumentException("Argument must be array of IFormControl instances.");
}
$s[] = (string) $control->getControl();
}
$pair = $this->getWrapper('pair container');
$pair->add($this->renderLabel($control));
$pair->add($this->getWrapper('control container')->setHtml(implode(" ", $s)));
return $pair->render(0);
}
/**
* Renders 'label' part of visual row of controls.
* @param IFormControl
* @return string
*/
public function renderLabel(IFormControl $control)
{
$head = $this->getWrapper('label container');
if ($control instanceof Checkbox || $control instanceof Button) {
return $head->setHtml(($head->getName() === 'td' || $head->getName() === 'th') ? ' ' : '');
} else {
$label = $control->getLabel();
$suffix = $this->getValue('label suffix') . ($control->getOption('required') ? $this->getValue('label requiredsuffix') : '');
if ($label instanceof Html) {
$label->setHtml($label->getHtml() . $suffix);
$suffix = '';
}
return $head->setHtml((string) $label . $suffix);
}
}
/**
* Renders 'control' part of visual row of controls.
* @param IFormControl
* @return string
*/
public function renderControl(IFormControl $control)
{
$body = $this->getWrapper('control container');
if ($this->counter % 2) $body->class($this->getValue('control .odd'), TRUE);
$description = $control->getOption('description');
if ($description instanceof Html) {
$description = ' ' . $control->getOption('description');
} elseif (is_string($description)) {
$description = ' ' . $this->getWrapper('control description')->setText($control->translate($description));
} else {
$description = '';
}
if ($control->getOption('required')) {
$description = $this->getValue('control requiredsuffix') . $description;
}
if ($this->getValue('control errors')) {
$description .= $this->renderErrors($control);
}
if ($control instanceof Checkbox || $control instanceof Button) {
return $body->setHtml((string) $control->getControl() . (string) $control->getLabel() . $description);
} else {
return $body->setHtml((string) $control->getControl() . $description);
}
}
/**
* @param string
* @return Html
*/
protected function getWrapper($name)
{
$data = $this->getValue($name);
return $data instanceof Html ? clone $data : Html::el($data);
}
/**
* @param string
* @return string
*/
protected function getValue($name)
{
$name = explode(' ', $name);
$data = & $this->wrappers[$name[0]][$name[1]];
return $data;
}
}
| fpytloun/eWide-Client | libs/Nette/Forms/Renderers/ConventionalRenderer.php | PHP | gpl-2.0 | 12,033 |
/***********************************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Copyright (C) 2005-2013 University of Muenster, Germany. *
* Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
* For a list of authors please refer to the file "CREDITS.txt". *
* *
* This file is part of the Voreen software package. Voreen 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. *
* *
* Voreen is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR *
* A PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License in the file *
* "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
* *
* For non-commercial academic use see the license exception specified in the file *
* "LICENSE-academic.txt". To get information about commercial licensing please *
* contact the authors. *
* *
***********************************************************************************/
#include "voreen/qt/widgets/enterexitpushbutton.h"
namespace voreen {
EnterExitPushButton::EnterExitPushButton(QWidget* parent)
: QPushButton(parent)
{}
EnterExitPushButton::EnterExitPushButton(const QString& text, QWidget* parent)
: QPushButton(text, parent)
{}
EnterExitPushButton::EnterExitPushButton(const QIcon& icon, const QString& text, QWidget* parent)
: QPushButton(icon, text, parent)
{}
void EnterExitPushButton::enterEvent(QEvent* event) {
emit enterEventSignal();
QPushButton::enterEvent(event);
}
void EnterExitPushButton::leaveEvent(QEvent* event) {
emit leaveEventSignal();
QPushButton::leaveEvent(event);
}
} // namespace
| bilgili/Voreen | src/qt/widgets/enterexitpushbutton.cpp | C++ | gpl-2.0 | 2,717 |
<?php
if ( ! defined( 'ABSPATH' ) )
exit;
// Tinymce button
add_filter('mce_external_plugins', "firmasite_firmasitebutton_register");
function firmasite_firmasitebutton_register($plugin_array){
if ( ! is_admin() ) return $plugin_array;
global $firmasite_plugin_settings;
$plugin_array["firmasitebutton"] = $firmasite_plugin_settings["url"] . "assets/js/firmasite-button.js";
$plugin_array["firmasiteicons"] = $firmasite_plugin_settings["url"] . "assets/js/firmasite-icons.js";
return $plugin_array;
}
add_filter('tiny_mce_before_init', 'firmasite_firmasitebutton' );
function firmasite_firmasitebutton($init) {
if ( ! is_admin() ) return $init;
global $firmasite_settings;
$init['theme_advanced_buttons1_add_before'] = 'firmasitebutton,firmasiteicons'; // Adds the buttons at the begining. (theme_advanced_buttons2_add adds them at the end)
$init['body_class'] = $init['body_class'] . ' panel panel-default ' . $firmasite_settings["layout_page_class"];
return $init;
}
add_filter('admin_init', "firmasite_plugin_editor_init");
function firmasite_plugin_editor_init() {
global $firmasite_plugin_settings;
wp_localize_script( 'editor', 'firmasitebutton', array(
//'url' => plugin_dir_url( __FILE__ ),
'icons' => __( 'Icons', "firmasite-theme-enhancer" ),
'title' => __( 'Styles', "firmasite-theme-enhancer" ),
'container' => __( 'Container', "firmasite-theme-enhancer" ),
// Well Box
'well' => __( 'Well Box', "firmasite-theme-enhancer" ),
'well_small' => __( 'Small Well Box', "firmasite-theme-enhancer" ),
'well_standard' => __( 'Standard Well Box', "firmasite-theme-enhancer" ),
'well_large' => __( 'Large Well Box', "firmasite-theme-enhancer" ),
// Message Box
'messagebox' => __( 'Message Box', "firmasite-theme-enhancer" ),
'messagebox_alert' => __( 'Alert Box', "firmasite-theme-enhancer" ),
'messagebox_error' => __( 'Alert Box (Danger)', "firmasite-theme-enhancer" ),
'messagebox_success' => __( 'Alert Box (Success)', "firmasite-theme-enhancer" ),
'messagebox_info' => __( 'Alert Box (Information)', "firmasite-theme-enhancer" ),
// Modal Box
'modal' => __( 'Modal Box', "firmasite-theme-enhancer" ),
'modal_header' => __( 'Modal Box (Header)', "firmasite-theme-enhancer" ),
'modal_body' => __( 'Modal Box (Body)', "firmasite-theme-enhancer" ),
'modal_footer' => __( 'Modal Box (Footer)', "firmasite-theme-enhancer" ),
// Text Styles
'text' => __( 'Text Styles', "firmasite-theme-enhancer" ),
// Text Color
'textcolor' => __( 'Text Color', "firmasite-theme-enhancer" ),
'text_muted' => __( 'Muted', "firmasite-theme-enhancer" ),
'text_alert' => __( 'Alert', "firmasite-theme-enhancer" ),
'text_error' => __( 'Danger', "firmasite-theme-enhancer" ),
'text_success' => __( 'Success', "firmasite-theme-enhancer" ),
'text_info' => __( 'Information', "firmasite-theme-enhancer" ),
// Label
'label' => __( 'Label', "firmasite-theme-enhancer" ),
'label_standard' => __( 'Label', "firmasite-theme-enhancer" ),
'label_warning' => __( 'Label (Warning)', "firmasite-theme-enhancer" ),
'label_important' => __( 'Label (Important)', "firmasite-theme-enhancer" ),
'label_success' => __( 'Label (Success)', "firmasite-theme-enhancer" ),
'label_info' => __( 'Label (Info)', "firmasite-theme-enhancer" ),
'label_primary' => __( 'Label (Primary)', "firmasite-theme-enhancer" ),
// Badge
'badge' => __( 'Badge', "firmasite-theme-enhancer" ),
'badge_standard' => __( 'Badge', "firmasite-theme-enhancer" ),
'badge_warning' => __( 'Badge (Warning)', "firmasite-theme-enhancer" ),
'badge_important' => __( 'Badge (Important)', "firmasite-theme-enhancer" ),
'badge_success' => __( 'Badge (Success)', "firmasite-theme-enhancer" ),
'badge_info' => __( 'Badge (Info)', "firmasite-theme-enhancer" ),
'badge_primary' => __( 'Badge (Primary)', "firmasite-theme-enhancer" ),
// Button
'button' => __( 'Link to Button', "firmasite-theme-enhancer" ),
// Button Color
'buttoncolor' => __( 'Button Color', "firmasite-theme-enhancer" ),
'button_standard' => __( 'Standard', "firmasite-theme-enhancer" ),
'button_primary' => __( 'Primary', "firmasite-theme-enhancer" ),
'button_alert' => __( 'Alert', "firmasite-theme-enhancer" ),
'button_error' => __( 'Danger', "firmasite-theme-enhancer" ),
'button_success' => __( 'Success', "firmasite-theme-enhancer" ),
'button_info' => __( 'Information', "firmasite-theme-enhancer" ),
'button_primary' => __( 'Primary', "firmasite-theme-enhancer" ),
// Button Size
'buttonsize' => __( 'Button Size', "firmasite-theme-enhancer" ),
'button_block' => __( 'Block', "firmasite-theme-enhancer" ),
'button_large' => __( 'Large', "firmasite-theme-enhancer" ),
'button_standard' => __( 'Standard', "firmasite-theme-enhancer" ),
'button_small' => __( 'Small', "firmasite-theme-enhancer" ),
'button_mini' => __( 'Mini', "firmasite-theme-enhancer" ),
) );
wp_localize_script( 'editor', 'firmasiteicons', array(
'wp_includes_url' => WPINC,
'title' => __( 'Icons', "firmasite-theme-enhancer" ),
) );
}
| aquarius29/mentorship | wp-content/plugins/firmasite-theme-enhancer/theme-enhancer/functions/tinymce-buttons.php | PHP | gpl-2.0 | 5,329 |
// © 2007 Michele Leroux Bustamante. All rights reserved
// Book: Learning WCF, O'Reilly
// Book Blog: www.thatindigogirl.com
// Michele's Blog: www.dasblonde.net
// IDesign: www.idesign.net
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace InternalClient
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
} | cacotopia/Aquarius | LearningWCF/Labs/Chapter1/MultiContractService/InternalClient/Program.cs | C# | gpl-2.0 | 654 |
/*
* ---------
* |.##> <##.| Open Smart Card Development Platform (www.openscdp.org)
* |# #|
* |# #| Copyright (c) 1999-2006 CardContact Software & System Consulting
* |'##> <##'| Andreas Schwier, 32429 Minden, Germany (www.cardcontact.de)
* ---------
*
* This file is part of OpenSCDP.
*
* OpenSCDP 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.
*
* OpenSCDP 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 OpenSCDP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Support for card verifiable certificates
*
*/
//
// Constructor for CVC object from binary data
//
function CVC(value) {
this.value = new ASN1(value);
// print(this.value);
}
// Some static configuration tables
CVC.prototype.Profiles = new Array();
CVC.prototype.Profiles[3] = new Array();
CVC.prototype.Profiles[3][0] = { name:"CPI", length:1 };
CVC.prototype.Profiles[3][1] = { name:"CAR", length:8 };
CVC.prototype.Profiles[3][2] = { name:"CHR", length:12 };
CVC.prototype.Profiles[3][3] = { name:"CHA", length:7 };
CVC.prototype.Profiles[3][4] = { name:"OID", length:7 };
CVC.prototype.Profiles[3][5] = { name:"MOD", length:128 };
CVC.prototype.Profiles[3][6] = { name:"EXP", length:4 };
CVC.prototype.Profiles[4] = new Array();
CVC.prototype.Profiles[4][0] = { name:"CPI", length:1 };
CVC.prototype.Profiles[4][1] = { name:"CAR", length:8 };
CVC.prototype.Profiles[4][2] = { name:"CHR", length:12 };
CVC.prototype.Profiles[4][3] = { name:"CHA", length:7 };
CVC.prototype.Profiles[4][4] = { name:"OID", length:6 };
CVC.prototype.Profiles[4][5] = { name:"MOD", length:128 };
CVC.prototype.Profiles[4][6] = { name:"EXP", length:4 };
CVC.prototype.Profiles[33] = new Array();
CVC.prototype.Profiles[33][0] = { name:"CPI", length:1 };
CVC.prototype.Profiles[33][1] = { name:"MOD", length:256 };
CVC.prototype.Profiles[33][2] = { name:"EXP", length:4 };
CVC.prototype.Profiles[33][3] = { name:"OID", length:7 };
CVC.prototype.Profiles[33][4] = { name:"CHR", length:8 };
CVC.prototype.Profiles[33][5] = { name:"CAR", length:8 };
CVC.prototype.Profiles[34] = new Array();
CVC.prototype.Profiles[34][0] = { name:"CPI", length:1 };
CVC.prototype.Profiles[34][1] = { name:"MOD", length:256 };
CVC.prototype.Profiles[34][2] = { name:"EXP", length:4 };
CVC.prototype.Profiles[34][3] = { name:"OID", length:6 };
CVC.prototype.Profiles[34][4] = { name:"CHA", length:7 };
CVC.prototype.Profiles[34][5] = { name:"CHR", length:12 };
CVC.prototype.Profiles[34][6] = { name:"CAR", length:8 };
//
// Verify CVC certificate with public key
//
CVC.prototype.verifyWith = function(puk) {
// Get signed content
var signedContent = this.value.get(0).value;
// Decrypt with public key
var crypto = new Crypto();
var plain = crypto.decrypt(puk, Crypto.RSA_ISO9796_2, signedContent);
print("Plain value:");
print(plain);
// Check prefix and postfix byte
if ((plain.byteAt(0) != 0x6A) || (plain.byteAt(plain.length - 1) != 0xBC)) {
throw new GPError("CVC", GPError.CRYPTO_FAILED, -1, "Decrypted CVC shows invalid padding. Probably wrong public key.");
}
this.plainContent = plain;
var cpi = plain.byteAt(1);
var hashlen = (cpi >= 0x20 ? 32 : 20); // Starting with G2 SHA-256 is used
// Extract hash
this.hash = plain.bytes(plain.length - (hashlen + 1), hashlen);
var publicKeyRemainder = this.getPublicKeyRemainder();
// Input to hash is everything in the signed area plus the data in the public key remainder
var certdata = plain.bytes(1, plain.length - (hashlen + 2));
certdata = certdata.concat(publicKeyRemainder);
if (cpi >= 0x20) {
var refhash = crypto.digest(Crypto.SHA_256, certdata);
} else {
var refhash = crypto.digest(Crypto.SHA_1, certdata);
}
if (!refhash.equals(this.hash)) {
print(" Hash = " + this.hash);
print("RefHash = " + refhash);
throw new GPError("CVC", GPError.CRYPTO_FAILED, -2, "Hash value of certificate failed in verification");
}
// Split certificate data into components according to profile
var profile = certdata.byteAt(0);
var profileTemplate = this.Profiles[profile];
var offset = 0;
for (var i = 0; i < profileTemplate.length; i++) {
var name = profileTemplate[i].name;
var len = profileTemplate[i].length;
var val = certdata.bytes(offset, len);
// print(" " + name + " : " + val);
offset += len;
this[name] = val;
}
this.certificateData = certdata;
if (cpi < 0x20) {
if (!this.CAR.equals(this.value.get(2).value)) {
print("Warning: CAR in signed area does not match outer CAR");
}
}
}
CVC.prototype.verifyWithOneOf = function(puklist) {
for (var i = 0; i < puklist.length; i++) {
try {
this.verifyWith(puklist[i]);
break;
}
catch(e) {
if ((e instanceof GPError) && (e.reason == -1)) {
print("Trying next key on the list...");
} else {
throw e;
}
}
}
if (i >= puklist.length) {
throw new GPError("CVC", GPError.CRYPTO_FAILED, -3, "List of possible public keys exhausted. CVC decryption failed.");
}
}
//
// Return signatur data object
//
CVC.prototype.getSignaturDataObject = function() {
return (this.value.get(0));
}
//
// Return the public key remainder
//
CVC.prototype.getPublicKeyRemainderDataObject = function() {
return (this.value.get(1));
}
//
// Return the public key remainder
//
CVC.prototype.getPublicKeyRemainder = function() {
return (this.value.get(1).value);
}
//
// Return the certification authority reference (CAR)
//
CVC.prototype.getCertificationAuthorityReference = function() {
if (this.value.elements > 2) {
return (this.value.get(2).value);
} else {
if (!this.CAR) {
throw new GPError("CVC", GPError.INVALID_USAGE, 0, "Must verify certificate before extracting CAR");
}
return this.CAR;
}
}
//
// Return the certificate holder reference (CHR)
//
CVC.prototype.getCertificateHolderReference = function() {
if (!this.CHR) {
throw new GPError("CVC", GPError.INVALID_USAGE, 0, "Must verify certificate before extracting CHR");
}
return this.CHR;
}
//
// Return public key from certificate
//
CVC.prototype.getPublicKey = function() {
if (!this.MOD) {
throw new GPError("CVC", GPError.INVALID_USAGE, 0, "Must verify certificate before extracting public key");
}
var key = new Key();
key.setType(Key.PUBLIC);
key.setComponent(Key.MODULUS, this.MOD);
key.setComponent(Key.EXPONENT, this.EXP);
return key;
}
//
// Dump content of certificate
//
CVC.prototype.dump = function() {
print(this.value);
if (this.certificateData) {
var profile = this.certificateData.byteAt(0);
var profileTemplate = this.Profiles[profile];
var offset = 0;
for (var i = 0; i < profileTemplate.length; i++) {
print(" " + profileTemplate[i].name + " : " + this.certificateData.bytes(offset, profileTemplate[i].length));
offset += profileTemplate[i].length;
}
print();
}
}
| wesee/scsh-scripts | eGK/cvc.js | JavaScript | gpl-2.0 | 7,514 |
<?php
/**
* Services widget
*
* @package Sydney
*/
class Sydney_Services_Type_B extends WP_Widget {
function sydney_services_type_b() {
$widget_ops = array('classname' => 'sydney_services_b_widget', 'description' => __( 'Show what services you are able to provide.', 'sydney') );
parent::WP_Widget(false, $name = __('Sydney FP: Services type B', 'sydney'), $widget_ops);
$this->alt_option_name = 'sydney_services_b_widget';
add_action( 'save_post', array($this, 'flush_widget_cache') );
add_action( 'deleted_post', array($this, 'flush_widget_cache') );
add_action( 'switch_theme', array($this, 'flush_widget_cache') );
}
function form($instance) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
$number = isset( $instance['number'] ) ? intval( $instance['number'] ) : -1;
$category = isset( $instance['category'] ) ? esc_attr( $instance['category'] ) : '';
$see_all = isset( $instance['see_all'] ) ? esc_url_raw( $instance['see_all'] ) : '';
$see_all_text = isset( $instance['see_all_text'] ) ? esc_html( $instance['see_all_text'] ) : '';
$cols = isset( $instance['cols'] ) ? esc_attr( $instance['cols'] ) : '';
?>
<p><?php _e('In order to display this widget, you must first add some services from your admin area.', 'sydney'); ?></p>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'sydney'); ?></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 $title; ?>" />
</p>
<p><label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of services to show (-1 shows all of them):', 'sydney' ); ?></label>
<input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>
<p><label for="<?php echo $this->get_field_id('see_all'); ?>"><?php _e('The URL for your button [In case you want a button below your services block]', 'sydney'); ?></label>
<input class="widefat custom_media_url" id="<?php echo $this->get_field_id( 'see_all' ); ?>" name="<?php echo $this->get_field_name( 'see_all' ); ?>" type="text" value="<?php echo $see_all; ?>" size="3" /></p>
<p><label for="<?php echo $this->get_field_id('see_all_text'); ?>"><?php _e('The text for the button [Defaults to <em>See all our services</em> if left empty]', 'sydney'); ?></label>
<input class="widefat custom_media_url" id="<?php echo $this->get_field_id( 'see_all_text' ); ?>" name="<?php echo $this->get_field_name( 'see_all_text' ); ?>" type="text" value="<?php echo $see_all_text; ?>" size="3" /></p>
<p><label for="<?php echo $this->get_field_id( 'category' ); ?>"><?php _e( 'Enter the slug for your category or leave empty to show all services.', 'sydney' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'category' ); ?>" name="<?php echo $this->get_field_name( 'category' ); ?>" type="text" value="<?php echo $category; ?>" size="3" /></p>
<p>
<label for="<?php echo $this->get_field_id('cols'); ?>"><?php _e( 'Number of columns:', 'sydney' ); ?></label>
<select name="<?php echo $this->get_field_name('cols'); ?>" id="<?php echo $this->get_field_id('cols'); ?>" class="widefat">
<?php
$options = array('1', '2', '3');
foreach ($options as $option) {
echo '<option value="' . $option . '" id="' . $option . '"', $cols == $option ? ' selected="selected"' : '', '>', esc_attr($option), '</option>';
}
?>
</select>
</p>
<?php
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['number'] = strip_tags($new_instance['number']);
$instance['see_all'] = esc_url_raw( $new_instance['see_all'] );
$instance['see_all_text'] = strip_tags($new_instance['see_all_text']);
$instance['category'] = strip_tags($new_instance['category']);
$instance['cols'] = strip_tags($new_instance['cols']);
$this->flush_widget_cache();
$alloptions = wp_cache_get( 'alloptions', 'options' );
if ( isset($alloptions['sydney_services']) )
delete_option('sydney_services');
return $instance;
}
function flush_widget_cache() {
wp_cache_delete('sydney_services', 'widget');
}
function widget($args, $instance) {
$cache = array();
if ( ! $this->is_preview() ) {
$cache = wp_cache_get( 'sydney_services', 'widget' );
}
if ( ! is_array( $cache ) ) {
$cache = array();
}
if ( ! isset( $args['widget_id'] ) ) {
$args['widget_id'] = $this->id;
}
if ( isset( $cache[ $args['widget_id'] ] ) ) {
echo $cache[ $args['widget_id'] ];
return;
}
ob_start();
extract($args);
$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : '';
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
$see_all = isset( $instance['see_all'] ) ? esc_url($instance['see_all']) : '';
$see_all_text = isset( $instance['see_all_text'] ) ? esc_html($instance['see_all_text']) : '';
$number = ( ! empty( $instance['number'] ) ) ? intval( $instance['number'] ) : -1;
if ( ! $number )
$number = -1;
$category = isset( $instance['category'] ) ? esc_attr($instance['category']) : '';
$cols = isset( $instance['cols'] ) ? esc_attr($instance['cols']) : '';
$services = new WP_Query( array(
'no_found_rows' => true,
'post_status' => 'publish',
'post_type' => 'services',
'posts_per_page' => $number,
'category_name' => $category
) );
if ( $cols == '1' ) {
$cols_no = '';
} elseif ( $cols == '3' ) {
$cols_no = 'col-md-4';
} elseif ( $cols == '2' ) {
$cols_no = 'col-md-6';
}
echo $args['before_widget'];
if ($services->have_posts()) :
?>
<?php if ( $title ) echo $before_title . $title . $after_title; ?>
<div class="roll-icon-list">
<?php while ( $services->have_posts() ) : $services->the_post(); ?>
<?php $icon = get_post_meta( get_the_ID(), 'wpcf-service-icon', true ); ?>
<?php $link = get_post_meta( get_the_ID(), 'wpcf-service-link', true ); ?>
<div class="service clearfix <?php echo $cols_no; ?>">
<div class="list-item">
<?php if ($icon) : ?>
<div class="icon">
<?php echo '<i class="fa ' . esc_html($icon) . '"></i>'; ?>
</div>
<?php endif; ?>
<div class="content">
<h3>
<?php if ($link) : ?>
<a href="<?php echo esc_url($link); ?>"><?php the_title(); ?></a>
<?php else : ?>
<?php the_title(); ?>
<?php endif; ?>
</h3>
<?php the_content(); ?>
</div><!--.info-->
</div>
</div>
<?php endwhile; ?>
</div>
<?php if ($see_all != '') : ?>
<a href="<?php echo esc_url($see_all); ?>" class="roll-button more-button">
<?php if ($see_all_text) : ?>
<?php echo $see_all_text; ?>
<?php else : ?>
<?php echo __('See all our services', 'sydney'); ?>
<?php endif; ?>
</a>
<?php endif; ?>
<?php
wp_reset_postdata();
endif;
echo $args['after_widget'];
if ( ! $this->is_preview() ) {
$cache[ $args['widget_id'] ] = ob_get_flush();
wp_cache_set( 'sydney_services', $cache, 'widget' );
} else {
ob_end_flush();
}
}
} | albertoquijano/JesusGiles | wp-content/themes/sydney/widgets/fp-services-type-b.php | PHP | gpl-2.0 | 7,470 |
/***************************************************************************
qgsrendercontext.cpp
--------------------
begin : March 16, 2008
copyright : (C) 2008 by Marco Hugentobler
email : marco dot hugentobler at karto dot baug dot ethz dot ch
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsrendercontext.h"
#include "qgsmapsettings.h"
#include "qgsexpression.h"
#include "qgsvectorlayer.h"
#include "qgsfeaturefilterprovider.h"
#include "qgslogger.h"
#include "qgspoint.h"
#define POINTS_TO_MM 2.83464567
#define INCH_TO_MM 25.4
QgsRenderContext::QgsRenderContext()
: mFlags( DrawEditingInfo | UseAdvancedEffects | DrawSelection | UseRenderingOptimization )
{
mVectorSimplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification );
// For RenderMetersInMapUnits support, when rendering in Degrees, the Ellipsoid must be set
// - for Previews/Icons the default Extent can be used
mDistanceArea.setEllipsoid( mDistanceArea.sourceCrs().ellipsoidAcronym() );
}
QgsRenderContext::QgsRenderContext( const QgsRenderContext &rh )
: mFlags( rh.mFlags )
, mPainter( rh.mPainter )
, mCoordTransform( rh.mCoordTransform )
, mDistanceArea( rh.mDistanceArea )
, mExtent( rh.mExtent )
, mOriginalMapExtent( rh.mOriginalMapExtent )
, mMapToPixel( rh.mMapToPixel )
, mRenderingStopped( rh.mRenderingStopped )
, mScaleFactor( rh.mScaleFactor )
, mRendererScale( rh.mRendererScale )
, mLabelingEngine( rh.mLabelingEngine )
, mSelectionColor( rh.mSelectionColor )
, mVectorSimplifyMethod( rh.mVectorSimplifyMethod )
, mExpressionContext( rh.mExpressionContext )
, mGeometry( rh.mGeometry )
, mFeatureFilterProvider( rh.mFeatureFilterProvider ? rh.mFeatureFilterProvider->clone() : nullptr )
, mSegmentationTolerance( rh.mSegmentationTolerance )
, mSegmentationToleranceType( rh.mSegmentationToleranceType )
, mTransformContext( rh.mTransformContext )
, mPathResolver( rh.mPathResolver )
, mTextRenderFormat( rh.mTextRenderFormat )
#ifdef QGISDEBUG
, mHasTransformContext( rh.mHasTransformContext )
#endif
{
}
QgsRenderContext &QgsRenderContext::operator=( const QgsRenderContext &rh )
{
mFlags = rh.mFlags;
mPainter = rh.mPainter;
mCoordTransform = rh.mCoordTransform;
mExtent = rh.mExtent;
mOriginalMapExtent = rh.mOriginalMapExtent;
mMapToPixel = rh.mMapToPixel;
mRenderingStopped = rh.mRenderingStopped;
mScaleFactor = rh.mScaleFactor;
mRendererScale = rh.mRendererScale;
mLabelingEngine = rh.mLabelingEngine;
mSelectionColor = rh.mSelectionColor;
mVectorSimplifyMethod = rh.mVectorSimplifyMethod;
mExpressionContext = rh.mExpressionContext;
mGeometry = rh.mGeometry;
mFeatureFilterProvider.reset( rh.mFeatureFilterProvider ? rh.mFeatureFilterProvider->clone() : nullptr );
mSegmentationTolerance = rh.mSegmentationTolerance;
mSegmentationToleranceType = rh.mSegmentationToleranceType;
mDistanceArea = rh.mDistanceArea;
mTransformContext = rh.mTransformContext;
mPathResolver = rh.mPathResolver;
mTextRenderFormat = rh.mTextRenderFormat;
#ifdef QGISDEBUG
mHasTransformContext = rh.mHasTransformContext;
#endif
return *this;
}
QgsRenderContext QgsRenderContext::fromQPainter( QPainter *painter )
{
QgsRenderContext context;
context.setPainter( painter );
if ( painter && painter->device() )
{
context.setScaleFactor( painter->device()->logicalDpiX() / 25.4 );
}
else
{
context.setScaleFactor( 3.465 ); //assume 88 dpi as standard value
}
if ( painter && painter->renderHints() & QPainter::Antialiasing )
{
context.setFlag( QgsRenderContext::Antialiasing, true );
}
return context;
}
QgsCoordinateTransformContext QgsRenderContext::transformContext() const
{
#ifdef QGISDEBUG
if ( !mHasTransformContext )
QgsDebugMsgLevel( QStringLiteral( "No QgsCoordinateTransformContext context set for transform" ), 4 );
#endif
return mTransformContext;
}
void QgsRenderContext::setTransformContext( const QgsCoordinateTransformContext &context )
{
mTransformContext = context;
#ifdef QGISDEBUG
mHasTransformContext = true;
#endif
}
void QgsRenderContext::setFlags( QgsRenderContext::Flags flags )
{
mFlags = flags;
}
void QgsRenderContext::setFlag( QgsRenderContext::Flag flag, bool on )
{
if ( on )
mFlags |= flag;
else
mFlags &= ~flag;
}
QgsRenderContext::Flags QgsRenderContext::flags() const
{
return mFlags;
}
bool QgsRenderContext::testFlag( QgsRenderContext::Flag flag ) const
{
return mFlags.testFlag( flag );
}
QgsRenderContext QgsRenderContext::fromMapSettings( const QgsMapSettings &mapSettings )
{
QgsRenderContext ctx;
ctx.setMapToPixel( mapSettings.mapToPixel() );
ctx.setExtent( mapSettings.visibleExtent() );
ctx.setMapExtent( mapSettings.visibleExtent() );
ctx.setFlag( DrawEditingInfo, mapSettings.testFlag( QgsMapSettings::DrawEditingInfo ) );
ctx.setFlag( ForceVectorOutput, mapSettings.testFlag( QgsMapSettings::ForceVectorOutput ) );
ctx.setFlag( UseAdvancedEffects, mapSettings.testFlag( QgsMapSettings::UseAdvancedEffects ) );
ctx.setFlag( UseRenderingOptimization, mapSettings.testFlag( QgsMapSettings::UseRenderingOptimization ) );
ctx.setCoordinateTransform( QgsCoordinateTransform() );
ctx.setSelectionColor( mapSettings.selectionColor() );
ctx.setFlag( DrawSelection, mapSettings.testFlag( QgsMapSettings::DrawSelection ) );
ctx.setFlag( DrawSymbolBounds, mapSettings.testFlag( QgsMapSettings::DrawSymbolBounds ) );
ctx.setFlag( RenderMapTile, mapSettings.testFlag( QgsMapSettings::RenderMapTile ) );
ctx.setFlag( Antialiasing, mapSettings.testFlag( QgsMapSettings::Antialiasing ) );
ctx.setFlag( RenderPartialOutput, mapSettings.testFlag( QgsMapSettings::RenderPartialOutput ) );
ctx.setFlag( RenderPreviewJob, mapSettings.testFlag( QgsMapSettings::RenderPreviewJob ) );
ctx.setScaleFactor( mapSettings.outputDpi() / 25.4 ); // = pixels per mm
ctx.setRendererScale( mapSettings.scale() );
ctx.setExpressionContext( mapSettings.expressionContext() );
ctx.setSegmentationTolerance( mapSettings.segmentationTolerance() );
ctx.setSegmentationToleranceType( mapSettings.segmentationToleranceType() );
ctx.mDistanceArea.setSourceCrs( mapSettings.destinationCrs(), mapSettings.transformContext() );
ctx.mDistanceArea.setEllipsoid( mapSettings.ellipsoid() );
ctx.setTransformContext( mapSettings.transformContext() );
ctx.setPathResolver( mapSettings.pathResolver() );
ctx.setTextRenderFormat( mapSettings.textRenderFormat() );
//this flag is only for stopping during the current rendering progress,
//so must be false at every new render operation
ctx.setRenderingStopped( false );
return ctx;
}
bool QgsRenderContext::forceVectorOutput() const
{
return mFlags.testFlag( ForceVectorOutput );
}
bool QgsRenderContext::useAdvancedEffects() const
{
return mFlags.testFlag( UseAdvancedEffects );
}
void QgsRenderContext::setUseAdvancedEffects( bool enabled )
{
setFlag( UseAdvancedEffects, enabled );
}
bool QgsRenderContext::drawEditingInformation() const
{
return mFlags.testFlag( DrawEditingInfo );
}
bool QgsRenderContext::showSelection() const
{
return mFlags.testFlag( DrawSelection );
}
void QgsRenderContext::setCoordinateTransform( const QgsCoordinateTransform &t )
{
mCoordTransform = t;
}
void QgsRenderContext::setDrawEditingInformation( bool b )
{
setFlag( DrawEditingInfo, b );
}
void QgsRenderContext::setForceVectorOutput( bool force )
{
setFlag( ForceVectorOutput, force );
}
void QgsRenderContext::setShowSelection( const bool showSelection )
{
setFlag( DrawSelection, showSelection );
}
bool QgsRenderContext::useRenderingOptimization() const
{
return mFlags.testFlag( UseRenderingOptimization );
}
void QgsRenderContext::setUseRenderingOptimization( bool enabled )
{
setFlag( UseRenderingOptimization, enabled );
}
void QgsRenderContext::setFeatureFilterProvider( const QgsFeatureFilterProvider *ffp )
{
if ( ffp )
{
mFeatureFilterProvider.reset( ffp->clone() );
}
else
{
mFeatureFilterProvider.reset( nullptr );
}
}
const QgsFeatureFilterProvider *QgsRenderContext::featureFilterProvider() const
{
return mFeatureFilterProvider.get();
}
double QgsRenderContext::convertToPainterUnits( double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale ) const
{
double conversionFactor = 1.0;
switch ( unit )
{
case QgsUnitTypes::RenderMillimeters:
conversionFactor = mScaleFactor;
break;
case QgsUnitTypes::RenderPoints:
conversionFactor = mScaleFactor / POINTS_TO_MM;
break;
case QgsUnitTypes::RenderInches:
conversionFactor = mScaleFactor * INCH_TO_MM;
break;
case QgsUnitTypes::RenderMetersInMapUnits:
{
size = convertMetersToMapUnits( size );
unit = QgsUnitTypes::RenderMapUnits;
// Fall through to RenderMapUnits with size in meters converted to size in MapUnits
FALLTHROUGH
}
case QgsUnitTypes::RenderMapUnits:
{
double mup = scale.computeMapUnitsPerPixel( *this );
if ( mup > 0 )
{
conversionFactor = 1.0 / mup;
}
else
{
conversionFactor = 1.0;
}
break;
}
case QgsUnitTypes::RenderPixels:
conversionFactor = 1.0;
break;
case QgsUnitTypes::RenderUnknownUnit:
case QgsUnitTypes::RenderPercentage:
//no sensible value
conversionFactor = 1.0;
break;
}
double convertedSize = size * conversionFactor;
if ( unit == QgsUnitTypes::RenderMapUnits )
{
//check max/min size
if ( scale.minSizeMMEnabled )
convertedSize = std::max( convertedSize, scale.minSizeMM * mScaleFactor );
if ( scale.maxSizeMMEnabled )
convertedSize = std::min( convertedSize, scale.maxSizeMM * mScaleFactor );
}
return convertedSize;
}
double QgsRenderContext::convertToMapUnits( double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale ) const
{
double mup = mMapToPixel.mapUnitsPerPixel();
switch ( unit )
{
case QgsUnitTypes::RenderMetersInMapUnits:
{
size = convertMetersToMapUnits( size );
// Fall through to RenderMapUnits with values of meters converted to MapUnits
FALLTHROUGH
}
case QgsUnitTypes::RenderMapUnits:
{
// check scale
double minSizeMU = std::numeric_limits<double>::lowest();
if ( scale.minSizeMMEnabled )
{
minSizeMU = scale.minSizeMM * mScaleFactor * mup;
}
if ( !qgsDoubleNear( scale.minScale, 0.0 ) )
{
minSizeMU = std::max( minSizeMU, size * ( mRendererScale / scale.minScale ) );
}
size = std::max( size, minSizeMU );
double maxSizeMU = std::numeric_limits<double>::max();
if ( scale.maxSizeMMEnabled )
{
maxSizeMU = scale.maxSizeMM * mScaleFactor * mup;
}
if ( !qgsDoubleNear( scale.maxScale, 0.0 ) )
{
maxSizeMU = std::min( maxSizeMU, size * ( mRendererScale / scale.maxScale ) );
}
size = std::min( size, maxSizeMU );
return size;
}
case QgsUnitTypes::RenderMillimeters:
{
return size * mScaleFactor * mup;
}
case QgsUnitTypes::RenderPoints:
{
return size * mScaleFactor * mup / POINTS_TO_MM;
}
case QgsUnitTypes::RenderInches:
{
return size * mScaleFactor * mup * INCH_TO_MM;
}
case QgsUnitTypes::RenderPixels:
{
return size * mup;
}
case QgsUnitTypes::RenderUnknownUnit:
case QgsUnitTypes::RenderPercentage:
//no sensible value
return 0.0;
}
return 0.0;
}
double QgsRenderContext::convertFromMapUnits( double sizeInMapUnits, QgsUnitTypes::RenderUnit outputUnit ) const
{
double mup = mMapToPixel.mapUnitsPerPixel();
switch ( outputUnit )
{
case QgsUnitTypes::RenderMetersInMapUnits:
{
return sizeInMapUnits / convertMetersToMapUnits( 1.0 );
}
case QgsUnitTypes::RenderMapUnits:
{
return sizeInMapUnits;
}
case QgsUnitTypes::RenderMillimeters:
{
return sizeInMapUnits / ( mScaleFactor * mup );
}
case QgsUnitTypes::RenderPoints:
{
return sizeInMapUnits / ( mScaleFactor * mup / POINTS_TO_MM );
}
case QgsUnitTypes::RenderInches:
{
return sizeInMapUnits / ( mScaleFactor * mup * INCH_TO_MM );
}
case QgsUnitTypes::RenderPixels:
{
return sizeInMapUnits / mup;
}
case QgsUnitTypes::RenderUnknownUnit:
case QgsUnitTypes::RenderPercentage:
//no sensible value
return 0.0;
}
return 0.0;
}
double QgsRenderContext::convertMetersToMapUnits( double meters ) const
{
switch ( mDistanceArea.sourceCrs().mapUnits() )
{
case QgsUnitTypes::DistanceMeters:
return meters;
case QgsUnitTypes::DistanceDegrees:
{
QgsPointXY pointCenter = mExtent.center();
// The Extent is in the sourceCrs(), when different from destinationCrs()
// - the point must be transformed, since DistanceArea uses the destinationCrs()
// Note: the default QgsCoordinateTransform() : authid() will return an empty String
if ( !mCoordTransform.isShortCircuited() )
{
pointCenter = mCoordTransform.transform( pointCenter );
}
return mDistanceArea.measureLineProjected( pointCenter, meters );
}
case QgsUnitTypes::DistanceKilometers:
case QgsUnitTypes::DistanceFeet:
case QgsUnitTypes::DistanceNauticalMiles:
case QgsUnitTypes::DistanceYards:
case QgsUnitTypes::DistanceMiles:
case QgsUnitTypes::DistanceCentimeters:
case QgsUnitTypes::DistanceMillimeters:
case QgsUnitTypes::DistanceUnknownUnit:
return ( meters * QgsUnitTypes::fromUnitToUnitFactor( QgsUnitTypes::DistanceMeters, mDistanceArea.sourceCrs().mapUnits() ) );
}
return meters;
}
| m-kuhn/QGIS | src/core/qgsrendercontext.cpp | C++ | gpl-2.0 | 14,525 |
<?php
class Message
{
function __construct()
{
}
function get_message()
{
$message="";
if(isset($_SESSION['message'][0]) && $_SESSION['message'][0]!="")
{
$cpt=0;
foreach($_SESSION['message'] as $messagecour)
{
$message.="<div class='message indent ".$_SESSION['typemessage'][$cpt]."'>";
$message.=$messagecour;
$message.="</div>";
}
}
$_SESSION['message']=array();
$_SESSION['typemessage']=array();
return $message;
}
function set_message($message="",$typemessage="alert")
{
$_SESSION['message'][]=$message;
$_SESSION['typemessage'][]=$typemessage;
}
}
?> | RoDKoDRoK/RoDKoDRoK-packages | connector.message/static/default/core/src/mainclass/indexclass/class.message.php | PHP | gpl-2.0 | 637 |
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* 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
*
*/
/*!
* @file StereoscopicsManager.cpp
* @brief This class acts as container for stereoscopic related functions
*/
#include <stdlib.h>
#include "StereoscopicsManager.h"
#include "Application.h"
#include "ServiceBroker.h"
#include "messaging/ApplicationMessenger.h"
#include "dialogs/GUIDialogKaiToast.h"
#include "dialogs/GUIDialogSelect.h"
#include "GUIInfoManager.h"
#include "GUIUserMessages.h"
#include "guilib/LocalizeStrings.h"
#include "input/Key.h"
#include "guilib/GUIWindowManager.h"
#include "settings/AdvancedSettings.h"
#include "settings/lib/Setting.h"
#include "settings/Settings.h"
#include "rendering/RenderSystem.h"
#include "utils/log.h"
#include "utils/RegExp.h"
#include "utils/StringUtils.h"
#include "utils/Variant.h"
#include "windowing/WindowingFactory.h"
#include "guiinfo/GUIInfoLabels.h"
using namespace KODI::MESSAGING;
struct StereoModeMap
{
const char* name;
RENDER_STEREO_MODE mode;
};
static const struct StereoModeMap VideoModeToGuiModeMap[] =
{
{ "mono", RENDER_STEREO_MODE_OFF },
{ "left_right", RENDER_STEREO_MODE_SPLIT_VERTICAL },
{ "right_left", RENDER_STEREO_MODE_SPLIT_VERTICAL },
{ "top_bottom", RENDER_STEREO_MODE_SPLIT_HORIZONTAL },
{ "bottom_top", RENDER_STEREO_MODE_SPLIT_HORIZONTAL },
{ "checkerboard_rl", RENDER_STEREO_MODE_CHECKERBOARD },
{ "checkerboard_lr", RENDER_STEREO_MODE_CHECKERBOARD },
{ "row_interleaved_rl", RENDER_STEREO_MODE_INTERLACED },
{ "row_interleaved_lr", RENDER_STEREO_MODE_INTERLACED },
{ "col_interleaved_rl", RENDER_STEREO_MODE_OFF }, // unsupported
{ "col_interleaved_lr", RENDER_STEREO_MODE_OFF }, // unsupported
{ "anaglyph_cyan_red", RENDER_STEREO_MODE_ANAGLYPH_RED_CYAN },
{ "anaglyph_green_magenta", RENDER_STEREO_MODE_ANAGLYPH_GREEN_MAGENTA },
{ "anaglyph_yellow_blue", RENDER_STEREO_MODE_ANAGLYPH_YELLOW_BLUE },
#ifndef TARGET_RASPBERRY_PI
{ "block_lr", RENDER_STEREO_MODE_HARDWAREBASED },
{ "block_rl", RENDER_STEREO_MODE_HARDWAREBASED },
#else
{ "block_lr", RENDER_STEREO_MODE_SPLIT_HORIZONTAL }, // fallback
{ "block_rl", RENDER_STEREO_MODE_SPLIT_HORIZONTAL }, // fallback
#endif
{}
};
static const struct StereoModeMap StringToGuiModeMap[] =
{
{ "off", RENDER_STEREO_MODE_OFF },
{ "split_vertical", RENDER_STEREO_MODE_SPLIT_VERTICAL },
{ "side_by_side", RENDER_STEREO_MODE_SPLIT_VERTICAL }, // alias
{ "sbs", RENDER_STEREO_MODE_SPLIT_VERTICAL }, // alias
{ "split_horizontal", RENDER_STEREO_MODE_SPLIT_HORIZONTAL },
{ "over_under", RENDER_STEREO_MODE_SPLIT_HORIZONTAL }, // alias
{ "tab", RENDER_STEREO_MODE_SPLIT_HORIZONTAL }, // alias
{ "row_interleaved", RENDER_STEREO_MODE_INTERLACED },
{ "interlaced", RENDER_STEREO_MODE_INTERLACED }, // alias
{ "checkerboard", RENDER_STEREO_MODE_CHECKERBOARD },
{ "anaglyph_cyan_red", RENDER_STEREO_MODE_ANAGLYPH_RED_CYAN },
{ "anaglyph_green_magenta", RENDER_STEREO_MODE_ANAGLYPH_GREEN_MAGENTA },
{ "anaglyph_yellow_blue", RENDER_STEREO_MODE_ANAGLYPH_YELLOW_BLUE },
{ "hardware_based", RENDER_STEREO_MODE_HARDWAREBASED },
{ "monoscopic", RENDER_STEREO_MODE_MONO },
{}
};
CStereoscopicsManager::CStereoscopicsManager(void)
{
m_stereoModeSetByUser = RENDER_STEREO_MODE_UNDEFINED;
m_lastStereoModeSetByUser = RENDER_STEREO_MODE_UNDEFINED;
}
CStereoscopicsManager::~CStereoscopicsManager(void) = default;
CStereoscopicsManager& CStereoscopicsManager::GetInstance()
{
static CStereoscopicsManager sStereoscopicsManager;
return sStereoscopicsManager;
}
void CStereoscopicsManager::Initialize(void)
{
// turn off stereo mode on XBMC startup
CLog::Log(LOGDEBUG, "StereoscopicsManager::%s: stereo:%d", __FUNCTION__, RENDER_STEREO_MODE_OFF);
SetStereoMode(RENDER_STEREO_MODE_OFF);
}
RENDER_STEREO_MODE CStereoscopicsManager::GetStereoMode(void)
{
return (RENDER_STEREO_MODE) CServiceBroker::GetSettings().GetInt(CSettings::SETTING_VIDEOSCREEN_STEREOSCOPICMODE);
}
void CStereoscopicsManager::SetStereoModeByUser(const RENDER_STEREO_MODE &mode)
{
// only update last user mode if desired mode is different from current
if (mode != m_stereoModeSetByUser)
m_lastStereoModeSetByUser = m_stereoModeSetByUser;
m_stereoModeSetByUser = mode;
CLog::Log(LOGDEBUG, "StereoscopicsManager::%s: stereo:%d", __FUNCTION__, mode);
SetStereoMode(mode);
}
void CStereoscopicsManager::SetStereoMode(const RENDER_STEREO_MODE &mode)
{
RENDER_STEREO_MODE currentMode = GetStereoMode();
RENDER_STEREO_MODE applyMode = mode;
// resolve automatic mode before applying
if (mode == RENDER_STEREO_MODE_AUTO)
applyMode = GetStereoModeOfPlayingVideo();
if (applyMode != currentMode && applyMode >= RENDER_STEREO_MODE_OFF)
{
if (!g_Windowing.SupportsStereo(applyMode))
return;
CServiceBroker::GetSettings().SetInt(CSettings::SETTING_VIDEOSCREEN_STEREOSCOPICMODE, applyMode);
}
}
RENDER_STEREO_MODE CStereoscopicsManager::GetNextSupportedStereoMode(const RENDER_STEREO_MODE ¤tMode, int step)
{
RENDER_STEREO_MODE mode = currentMode;
do {
mode = (RENDER_STEREO_MODE) ((mode + step) % RENDER_STEREO_MODE_COUNT);
if(g_Windowing.SupportsStereo(mode))
break;
} while (mode != currentMode);
return mode;
}
std::string CStereoscopicsManager::DetectStereoModeByString(const std::string &needle)
{
std::string stereoMode = "mono";
std::string searchString(needle);
CRegExp re(true);
if (!re.RegComp(g_advancedSettings.m_stereoscopicregex_3d.c_str()))
{
CLog::Log(LOGERROR, "%s: Invalid RegExp for matching 3d content:'%s'", __FUNCTION__, g_advancedSettings.m_stereoscopicregex_3d.c_str());
return stereoMode;
}
if (re.RegFind(searchString) == -1)
return stereoMode; // no match found for 3d content, assume mono mode
if (!re.RegComp(g_advancedSettings.m_stereoscopicregex_sbs.c_str()))
{
CLog::Log(LOGERROR, "%s: Invalid RegExp for matching 3d SBS content:'%s'", __FUNCTION__, g_advancedSettings.m_stereoscopicregex_sbs.c_str());
return stereoMode;
}
if (re.RegFind(searchString) > -1)
{
stereoMode = "left_right";
return stereoMode;
}
if (!re.RegComp(g_advancedSettings.m_stereoscopicregex_tab.c_str()))
{
CLog::Log(LOGERROR, "%s: Invalid RegExp for matching 3d TAB content:'%s'", __FUNCTION__, g_advancedSettings.m_stereoscopicregex_tab.c_str());
return stereoMode;
}
if (re.RegFind(searchString) > -1)
stereoMode = "top_bottom";
if (!re.RegComp(g_advancedSettings.m_stereoscopicregex_mvc.c_str()))
{
CLog::Log(LOGERROR, "%s: Invalid RegExp for matching 3d MVC content:'%s'", __FUNCTION__, g_advancedSettings.m_stereoscopicregex_mvc.c_str());
return stereoMode;
}
if (re.RegFind(searchString) > -1)
stereoMode = "left_right";
return stereoMode;
}
RENDER_STEREO_MODE CStereoscopicsManager::GetStereoModeByUserChoice(const std::string &heading)
{
RENDER_STEREO_MODE mode = GetStereoMode();
// if no stereo mode is set already, suggest mode of current video by preselecting it
if (mode == RENDER_STEREO_MODE_OFF)
mode = GetStereoModeOfPlayingVideo();
CGUIDialogSelect* pDlgSelect = g_windowManager.GetWindow<CGUIDialogSelect>(WINDOW_DIALOG_SELECT);
pDlgSelect->Reset();
if (heading.empty())
pDlgSelect->SetHeading(CVariant{g_localizeStrings.Get(36528)});
else
pDlgSelect->SetHeading(CVariant{heading});
// prepare selectable stereo modes
std::vector<RENDER_STEREO_MODE> selectableModes;
for (int i = RENDER_STEREO_MODE_OFF; i < RENDER_STEREO_MODE_COUNT; i++)
{
RENDER_STEREO_MODE selectableMode = (RENDER_STEREO_MODE) i;
if (g_Windowing.SupportsStereo(selectableMode))
{
selectableModes.push_back(selectableMode);
std::string label = GetLabelForStereoMode((RENDER_STEREO_MODE) i);
pDlgSelect->Add( label );
if (mode == selectableMode)
pDlgSelect->SetSelected( label );
}
// inject AUTO pseudo mode after OFF
if (i == RENDER_STEREO_MODE_OFF)
{
selectableModes.push_back(RENDER_STEREO_MODE_AUTO);
pDlgSelect->Add(GetLabelForStereoMode(RENDER_STEREO_MODE_AUTO));
}
}
pDlgSelect->Open();
int iItem = pDlgSelect->GetSelectedItem();
if (iItem > -1 && pDlgSelect->IsConfirmed())
mode = (RENDER_STEREO_MODE) selectableModes[iItem];
else
mode = GetStereoMode();
return mode;
}
RENDER_STEREO_MODE CStereoscopicsManager::GetStereoModeOfPlayingVideo(void)
{
RENDER_STEREO_MODE mode = RENDER_STEREO_MODE_OFF;
std::string playerMode = GetVideoStereoMode();
if (!playerMode.empty())
{
int convertedMode = ConvertVideoToGuiStereoMode(playerMode);
if (convertedMode > -1)
mode = (RENDER_STEREO_MODE) convertedMode;
}
CLog::Log(LOGDEBUG, "StereoscopicsManager: autodetected stereo mode for movie mode %s is: %s", playerMode.c_str(), ConvertGuiStereoModeToString(mode));
return mode;
}
const std::string &CStereoscopicsManager::GetLabelForStereoMode(const RENDER_STEREO_MODE &mode) const
{
int msgId;
switch(mode) {
case RENDER_STEREO_MODE_AUTO:
msgId = 36532;
break;
case RENDER_STEREO_MODE_ANAGLYPH_YELLOW_BLUE:
msgId = 36510;
break;
case RENDER_STEREO_MODE_INTERLACED:
msgId = 36507;
break;
case RENDER_STEREO_MODE_CHECKERBOARD:
msgId = 36511;
break;
case RENDER_STEREO_MODE_HARDWAREBASED:
msgId = 36508;
break;
case RENDER_STEREO_MODE_MONO:
msgId = 36509;
break;
default:
msgId = 36502 + mode;
}
return g_localizeStrings.Get(msgId);
}
RENDER_STEREO_MODE CStereoscopicsManager::GetPreferredPlaybackMode(void)
{
return (RENDER_STEREO_MODE) CServiceBroker::GetSettings().GetInt(CSettings::SETTING_VIDEOSCREEN_PREFEREDSTEREOSCOPICMODE);
}
int CStereoscopicsManager::ConvertVideoToGuiStereoMode(const std::string &mode)
{
size_t i = 0;
while (VideoModeToGuiModeMap[i].name)
{
if (mode == VideoModeToGuiModeMap[i].name && g_Windowing.SupportsStereo(VideoModeToGuiModeMap[i].mode))
return VideoModeToGuiModeMap[i].mode;
i++;
}
return -1;
}
int CStereoscopicsManager::ConvertStringToGuiStereoMode(const std::string &mode)
{
size_t i = 0;
while (StringToGuiModeMap[i].name)
{
if (mode == StringToGuiModeMap[i].name)
return StringToGuiModeMap[i].mode;
i++;
}
return ConvertVideoToGuiStereoMode(mode);
}
const char* CStereoscopicsManager::ConvertGuiStereoModeToString(const RENDER_STEREO_MODE &mode)
{
size_t i = 0;
while (StringToGuiModeMap[i].name)
{
if (StringToGuiModeMap[i].mode == mode)
return StringToGuiModeMap[i].name;
i++;
}
return "";
}
std::string CStereoscopicsManager::NormalizeStereoMode(const std::string &mode)
{
if (!mode.empty() && mode != "mono")
{
int guiMode = ConvertStringToGuiStereoMode(mode);
if (guiMode > -1)
return ConvertGuiStereoModeToString((RENDER_STEREO_MODE) guiMode);
else
return mode;
}
return "mono";
}
CAction CStereoscopicsManager::ConvertActionCommandToAction(const std::string &command, const std::string ¶meter)
{
std::string cmd = command;
std::string para = parameter;
StringUtils::ToLower(cmd);
StringUtils::ToLower(para);
if (cmd == "setstereomode")
{
int actionId = -1;
if (para == "next")
actionId = ACTION_STEREOMODE_NEXT;
else if (para == "previous")
actionId = ACTION_STEREOMODE_PREVIOUS;
else if (para == "toggle")
actionId = ACTION_STEREOMODE_TOGGLE;
else if (para == "select")
actionId = ACTION_STEREOMODE_SELECT;
else if (para == "tomono")
actionId = ACTION_STEREOMODE_TOMONO;
// already have a valid actionID return it
if (actionId > -1)
return CAction(actionId);
// still no valid action ID, check if parameter is a supported stereomode
if (ConvertStringToGuiStereoMode(para) > -1)
return CAction(ACTION_STEREOMODE_SET, para);
}
return CAction(ACTION_NONE);
}
void CStereoscopicsManager::OnSettingChanged(std::shared_ptr<const CSetting> setting)
{
if (setting == NULL)
return;
const std::string &settingId = setting->GetId();
if (settingId == CSettings::SETTING_VIDEOSCREEN_STEREOSCOPICMODE)
{
RENDER_STEREO_MODE mode = GetStereoMode();
CLog::Log(LOGDEBUG, "StereoscopicsManager: stereo mode setting changed to %s", ConvertGuiStereoModeToString(mode));
ApplyStereoMode(mode);
}
}
bool CStereoscopicsManager::OnMessage(CGUIMessage &message)
{
switch (message.GetMessage())
{
case GUI_MSG_PLAYBACK_STARTED:
OnPlaybackStarted();
break;
case GUI_MSG_PLAYBACK_STOPPED:
case GUI_MSG_PLAYLISTPLAYER_STOPPED:
OnPlaybackStopped();
break;
}
return false;
}
bool CStereoscopicsManager::OnAction(const CAction &action)
{
RENDER_STEREO_MODE mode = GetStereoMode();
if (action.GetID() == ACTION_STEREOMODE_NEXT)
{
SetStereoModeByUser(GetNextSupportedStereoMode(mode));
return true;
}
else if (action.GetID() == ACTION_STEREOMODE_PREVIOUS)
{
SetStereoModeByUser(GetNextSupportedStereoMode(mode, RENDER_STEREO_MODE_COUNT - 1));
return true;
}
else if (action.GetID() == ACTION_STEREOMODE_TOGGLE)
{
if (mode == RENDER_STEREO_MODE_OFF)
{
RENDER_STEREO_MODE targetMode = GetPreferredPlaybackMode();
// if user selected a specific mode before, make sure to
// switch back into that mode on toggle.
if (m_stereoModeSetByUser != RENDER_STEREO_MODE_UNDEFINED)
{
// if user mode is set to OFF, he manually turned it off before. In this case use the last user applied mode
if (m_stereoModeSetByUser != RENDER_STEREO_MODE_OFF)
targetMode = m_stereoModeSetByUser;
else if (m_lastStereoModeSetByUser != RENDER_STEREO_MODE_UNDEFINED && m_lastStereoModeSetByUser != RENDER_STEREO_MODE_OFF)
targetMode = m_lastStereoModeSetByUser;
}
SetStereoModeByUser(targetMode);
}
else
{
SetStereoModeByUser(RENDER_STEREO_MODE_OFF);
}
return true;
}
else if (action.GetID() == ACTION_STEREOMODE_SELECT)
{
SetStereoModeByUser(GetStereoModeByUserChoice());
return true;
}
else if (action.GetID() == ACTION_STEREOMODE_TOMONO)
{
if (mode == RENDER_STEREO_MODE_MONO)
{
RENDER_STEREO_MODE targetMode = GetPreferredPlaybackMode();
// if we have an old userdefined stereomode, use that one as toggle target
if (m_stereoModeSetByUser != RENDER_STEREO_MODE_UNDEFINED)
{
// if user mode is set to OFF, he manually turned it off before. In this case use the last user applied mode
if (m_stereoModeSetByUser != RENDER_STEREO_MODE_OFF && m_stereoModeSetByUser != mode)
targetMode = m_stereoModeSetByUser;
else if (m_lastStereoModeSetByUser != RENDER_STEREO_MODE_UNDEFINED && m_lastStereoModeSetByUser != RENDER_STEREO_MODE_OFF && m_lastStereoModeSetByUser != mode)
targetMode = m_lastStereoModeSetByUser;
}
SetStereoModeByUser(targetMode);
}
else
{
SetStereoModeByUser(RENDER_STEREO_MODE_MONO);
}
return true;
}
else if (action.GetID() == ACTION_STEREOMODE_SET)
{
int stereoMode = ConvertStringToGuiStereoMode(action.GetName());
if (stereoMode > -1)
SetStereoModeByUser( (RENDER_STEREO_MODE) stereoMode );
return true;
}
return false;
}
void CStereoscopicsManager::ApplyStereoMode(const RENDER_STEREO_MODE &mode, bool notify)
{
RENDER_STEREO_MODE currentMode = g_graphicsContext.GetStereoMode();
CLog::Log(LOGDEBUG, "StereoscopicsManager::ApplyStereoMode: trying to apply stereo mode. Current: %s | Target: %s", ConvertGuiStereoModeToString(currentMode), ConvertGuiStereoModeToString(mode));
if (currentMode != mode)
{
CLog::Log(LOGDEBUG, "StereoscopicsManager::%s: stereo:%d", __FUNCTION__, mode);
g_graphicsContext.SetNextStereoMode(mode);
CLog::Log(LOGDEBUG, "StereoscopicsManager: stereo mode changed to %s", ConvertGuiStereoModeToString(mode));
if (notify)
CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(36501), GetLabelForStereoMode(mode));
}
}
std::string CStereoscopicsManager::GetVideoStereoMode()
{
std::string playerMode;
if (g_application.m_pPlayer->IsPlaying())
{
SPlayerVideoStreamInfo videoInfo;
g_application.m_pPlayer->GetVideoStreamInfo(CURRENT_STREAM, videoInfo);
playerMode = videoInfo.stereoMode;
}
return playerMode;
}
bool CStereoscopicsManager::IsVideoStereoscopic()
{
std::string mode = GetVideoStereoMode();
return !mode.empty() && mode != "mono";
}
void CStereoscopicsManager::OnPlaybackStarted(void)
{
STEREOSCOPIC_PLAYBACK_MODE playbackMode = (STEREOSCOPIC_PLAYBACK_MODE) CServiceBroker::GetSettings().GetInt(CSettings::SETTING_VIDEOPLAYER_STEREOSCOPICPLAYBACKMODE);
RENDER_STEREO_MODE mode = GetStereoMode();
// early return if playback mode should be ignored and we're in no stereoscopic mode right now
if (playbackMode == STEREOSCOPIC_PLAYBACK_MODE_IGNORE && mode == RENDER_STEREO_MODE_OFF)
return;
if (!CStereoscopicsManager::IsVideoStereoscopic())
{
// exit stereo mode if started item is not stereoscopic
// and if user prefers to stop 3D playback when movie is finished
if (mode != RENDER_STEREO_MODE_OFF && CServiceBroker::GetSettings().GetBool(CSettings::SETTING_VIDEOPLAYER_QUITSTEREOMODEONSTOP))
{
CLog::Log(LOGDEBUG, "StereoscopicsManager::%s: stereo:%d", __FUNCTION__, RENDER_STEREO_MODE_OFF);
SetStereoMode(RENDER_STEREO_MODE_OFF);
}
return;
}
// if we're not in stereomode yet, restore previously selected stereo mode in case it was user selected
if (m_stereoModeSetByUser != RENDER_STEREO_MODE_UNDEFINED)
{
CLog::Log(LOGDEBUG, "StereoscopicsManager::%s: stereo:%d", __FUNCTION__, m_stereoModeSetByUser);
SetStereoMode(m_stereoModeSetByUser);
return;
}
RENDER_STEREO_MODE preferred = GetPreferredPlaybackMode();
RENDER_STEREO_MODE playing = GetStereoModeOfPlayingVideo();
if (mode != RENDER_STEREO_MODE_OFF)
{
// don't change mode if user selected to not exit stereomode on playback stop
// users selecting this option usually have to manually switch their TV into 3D mode
// and would be annoyed by having to switch TV modes when next movies comes up
// @todo probably add a new setting for just this behavior
if (CServiceBroker::GetSettings().GetBool(CSettings::SETTING_VIDEOPLAYER_QUITSTEREOMODEONSTOP) == false)
return;
// only change to new stereo mode if not yet in preferred stereo mode
if (mode == preferred || (preferred == RENDER_STEREO_MODE_AUTO && mode == playing))
return;
}
switch (playbackMode)
{
case STEREOSCOPIC_PLAYBACK_MODE_ASK: // Ask
{
CApplicationMessenger::GetInstance().SendMsg(TMSG_MEDIA_PAUSE);
CGUIDialogSelect* pDlgSelect = g_windowManager.GetWindow<CGUIDialogSelect>(WINDOW_DIALOG_SELECT);
pDlgSelect->Reset();
pDlgSelect->SetHeading(CVariant{g_localizeStrings.Get(36527)});
int idx_playing = -1;
// add choices
int idx_preferred = pDlgSelect->Add(g_localizeStrings.Get(36524) // preferred
+ " ("
+ GetLabelForStereoMode(preferred)
+ ")");
int idx_mono = pDlgSelect->Add(GetLabelForStereoMode(RENDER_STEREO_MODE_MONO)); // mono / 2d
if (playing != RENDER_STEREO_MODE_OFF && playing != preferred && preferred != RENDER_STEREO_MODE_AUTO && g_Windowing.SupportsStereo(playing)) // same as movie
idx_playing = pDlgSelect->Add(g_localizeStrings.Get(36532)
+ " ("
+ GetLabelForStereoMode(playing)
+ ")");
int idx_select = pDlgSelect->Add( g_localizeStrings.Get(36531) ); // other / select
pDlgSelect->Open();
if(pDlgSelect->IsConfirmed())
{
int iItem = pDlgSelect->GetSelectedItem();
if (iItem == idx_preferred) mode = preferred;
else if (iItem == idx_mono) mode = RENDER_STEREO_MODE_MONO;
else if (iItem == idx_playing) mode = RENDER_STEREO_MODE_AUTO;
else if (iItem == idx_select) mode = GetStereoModeByUserChoice();
SetStereoModeByUser( mode );
}
CApplicationMessenger::GetInstance().SendMsg(TMSG_MEDIA_UNPAUSE);
}
break;
case STEREOSCOPIC_PLAYBACK_MODE_PREFERRED: // Stereoscopic
CLog::Log(LOGDEBUG, "StereoscopicsManager::%s: stereo:%d", __FUNCTION__, preferred);
SetStereoMode( preferred );
break;
case 2: // Mono
CLog::Log(LOGDEBUG, "StereoscopicsManager::%s: stereo:%d", __FUNCTION__, RENDER_STEREO_MODE_MONO);
SetStereoMode( RENDER_STEREO_MODE_MONO );
break;
default:
break;
}
}
void CStereoscopicsManager::OnPlaybackStopped(void)
{
RENDER_STEREO_MODE mode = GetStereoMode();
if (CServiceBroker::GetSettings().GetBool(CSettings::SETTING_VIDEOPLAYER_QUITSTEREOMODEONSTOP) && mode != RENDER_STEREO_MODE_OFF)
{
CLog::Log(LOGDEBUG, "StereoscopicsManager::%s: stereo:%d", __FUNCTION__, RENDER_STEREO_MODE_OFF);
SetStereoMode(RENDER_STEREO_MODE_OFF);
}
// reset user modes on playback end to start over new on next playback and not end up in a probably unwanted mode
if (m_stereoModeSetByUser != RENDER_STEREO_MODE_OFF)
m_lastStereoModeSetByUser = m_stereoModeSetByUser;
m_stereoModeSetByUser = RENDER_STEREO_MODE_UNDEFINED;
}
| popcornmix/xbmc | xbmc/guilib/StereoscopicsManager.cpp | C++ | gpl-2.0 | 22,607 |
/* ====================================================================
* Limited Evaluation License:
*
* This software is open source, but licensed. The license with this package
* is an evaluation license, which may not be used for productive systems. If
* you want a full license, please contact us.
*
* The exclusive owner of this work is the OpenRate project.
* This work, including all associated documents and components
* is Copyright of the OpenRate project 2006-2015.
*
* The following restrictions apply unless they are expressly relaxed in a
* contractual agreement between the license holder or one of its officially
* assigned agents and you or your organisation:
*
* 1) This work may not be disclosed, either in full or in part, in any form
* electronic or physical, to any third party. This includes both in the
* form of source code and compiled modules.
* 2) This work contains trade secrets in the form of architecture, algorithms
* methods and technologies. These trade secrets may not be disclosed to
* third parties in any form, either directly or in summary or paraphrased
* form, nor may these trade secrets be used to construct products of a
* similar or competing nature either by you or third parties.
* 3) This work may not be included in full or in part in any application.
* 4) You may not remove or alter any proprietary legends or notices contained
* in or on this work.
* 5) This software may not be reverse-engineered or otherwise decompiled, if
* you received this work in a compiled form.
* 6) This work is licensed, not sold. Possession of this software does not
* imply or grant any right to you.
* 7) You agree to disclose any changes to this work to the copyright holder
* and that the copyright holder may include any such changes at its own
* discretion into the work
* 8) You agree not to derive other works from the trade secrets in this work,
* and that any such derivation may make you liable to pay damages to the
* copyright holder
* 9) You agree to use this software exclusively for evaluation purposes, and
* that you shall not use this software to derive commercial profit or
* support your business or personal activities.
*
* This software is provided "as is" and any expressed or impled warranties,
* including, but not limited to, the impled warranties of merchantability
* and fitness for a particular purpose are disclaimed. In no event shall
* The OpenRate Project or its officially assigned agents be liable to 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 any business interruption) however caused
* and on 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.
* This software contains portions by The Apache Software Foundation, Robert
* Half International.
* ====================================================================
*/
package OpenRate.record.flexRecord;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This class defines the structures and mappings that allow us to construct
* record definitions on the fly
*
* @author TGDSPIA1
*/
public class RecordBlockDef
{
int NumberOfFields = 0;
String[] FieldNames;
int[] FieldTypes;
// the field separator for this block
String Separator = null;
// This is the name of the block
String BlockName;
// The mapping information that we will do when creating a new block of
// this type. This is an ArrayList so that we hold all of the fields that are
// to be mapped in a list.
ArrayList<MapElement> Mapping;
// The ChildTemplates hashmap contains the definitions of the child blocks
HashMap<String, RecordBlockDef> ChildTemplates;
// This is the index to allow us to find the field names quickly. This takes
// the full path name and returns the block reference and the field info
// (Offset, type)
HashMap<String, Integer> FieldNameIndex;
}
| skymania/OpenRate | src/main/java/OpenRate/record/flexRecord/RecordBlockDef.java | Java | gpl-2.0 | 4,229 |
using System;
using Nequeo.Cryptography.Key.Crypto.Digests;
using Nequeo.Cryptography.Key.Crypto.Parameters;
using Nequeo.Cryptography.Key.Security;
using Nequeo.Cryptography.Key.Utilities;
namespace Nequeo.Cryptography.Key.Crypto.Signers
{
/// <summary> ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3).
/// <p>
/// Note: the usual length for the salt is the length of the hash
/// function used in bytes.</p>
/// </summary>
public class Iso9796d2PssSigner
: ISignerWithRecovery
{
/// <summary>
/// Return a reference to the recoveredMessage message.
/// </summary>
/// <returns>The full/partial recoveredMessage message.</returns>
/// <seealso cref="ISignerWithRecovery.GetRecoveredMessage"/>
public byte[] GetRecoveredMessage()
{
return recoveredMessage;
}
public const int TrailerImplicit = 0xBC;
public const int TrailerRipeMD160 = 0x31CC;
public const int TrailerRipeMD128 = 0x32CC;
public const int TrailerSha1 = 0x33CC;
private IDigest digest;
private IAsymmetricBlockCipher cipher;
private SecureRandom random;
private byte[] standardSalt;
private int hLen;
private int trailer;
private int keyBits;
private byte[] block;
private byte[] mBuf;
private int messageLength;
private readonly int saltLength;
private bool fullMessage;
private byte[] recoveredMessage;
/// <summary>
/// Generate a signer for the with either implicit or explicit trailers
/// for ISO9796-2, scheme 2 or 3.
/// </summary>
/// <param name="cipher">base cipher to use for signature creation/verification</param>
/// <param name="digest">digest to use.</param>
/// <param name="saltLength">length of salt in bytes.</param>
/// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param>
public Iso9796d2PssSigner(
IAsymmetricBlockCipher cipher,
IDigest digest,
int saltLength,
bool isImplicit)
{
this.cipher = cipher;
this.digest = digest;
this.hLen = digest.GetDigestSize();
this.saltLength = saltLength;
if (isImplicit)
{
trailer = TrailerImplicit;
}
else
{
if (digest is Sha1Digest)
{
trailer = TrailerSha1;
}
else if (digest is RipeMD160Digest)
{
trailer = TrailerRipeMD160;
}
else if (digest is RipeMD128Digest)
{
trailer = TrailerRipeMD128;
}
else
{
throw new ArgumentException("no valid trailer for digest");
}
}
}
/// <summary> Constructor for a signer with an explicit digest trailer.
///
/// </summary>
/// <param name="cipher">cipher to use.
/// </param>
/// <param name="digest">digest to sign with.
/// </param>
/// <param name="saltLength">length of salt in bytes.
/// </param>
public Iso9796d2PssSigner(
IAsymmetricBlockCipher cipher,
IDigest digest,
int saltLength)
: this(cipher, digest, saltLength, false)
{
}
public string AlgorithmName
{
get { return digest.AlgorithmName + "with" + "ISO9796-2S2"; }
}
/// <summary>Initialise the signer.</summary>
/// <param name="forSigning">true if for signing, false if for verification.</param>
/// <param name="parameters">parameters for signature generation/verification. If the
/// parameters are for generation they should be a ParametersWithRandom,
/// a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters
/// are passed in a SecureRandom will be created.
/// </param>
/// <exception cref="ArgumentException">if wrong parameter type or a fixed
/// salt is passed in which is the wrong length.
/// </exception>
public virtual void Init(
bool forSigning,
ICipherParameters parameters)
{
RsaKeyParameters kParam;
if (parameters is ParametersWithRandom)
{
ParametersWithRandom p = (ParametersWithRandom) parameters;
kParam = (RsaKeyParameters) p.Parameters;
if (forSigning)
{
random = p.Random;
}
}
else if (parameters is ParametersWithSalt)
{
if (!forSigning)
throw new ArgumentException("ParametersWithSalt only valid for signing", "parameters");
ParametersWithSalt p = (ParametersWithSalt) parameters;
kParam = (RsaKeyParameters) p.Parameters;
standardSalt = p.GetSalt();
if (standardSalt.Length != saltLength)
throw new ArgumentException("Fixed salt is of wrong length");
}
else
{
kParam = (RsaKeyParameters) parameters;
if (forSigning)
{
random = new SecureRandom();
}
}
cipher.Init(forSigning, kParam);
keyBits = kParam.Modulus.BitLength;
block = new byte[(keyBits + 7) / 8];
if (trailer == TrailerImplicit)
{
mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 1];
}
else
{
mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 2];
}
Reset();
}
/// <summary> compare two byte arrays - constant time.</summary>
private bool IsSameAs(byte[] a, byte[] b)
{
if (messageLength != b.Length)
{
return false;
}
bool isOkay = true;
for (int i = 0; i != b.Length; i++)
{
if (a[i] != b[i])
{
isOkay = false;
}
}
return isOkay;
}
/// <summary> clear possible sensitive data</summary>
private void ClearBlock(
byte[] block)
{
Array.Clear(block, 0, block.Length);
}
public virtual void UpdateWithRecoveredMessage(
byte[] signature)
{
// TODO
throw Platform.CreateNotImplementedException("UpdateWithRecoveredMessage");
}
/// <summary> update the internal digest with the byte b</summary>
public virtual void Update(
byte input)
{
if (messageLength < mBuf.Length)
{
mBuf[messageLength++] = input;
}
else
{
digest.Update(input);
}
}
/// <summary> update the internal digest with the byte array in</summary>
public virtual void BlockUpdate(
byte[] input,
int inOff,
int length)
{
while (length > 0 && messageLength < mBuf.Length)
{
this.Update(input[inOff]);
inOff++;
length--;
}
if (length > 0)
{
digest.BlockUpdate(input, inOff, length);
}
}
/// <summary> reset the internal state</summary>
public virtual void Reset()
{
digest.Reset();
messageLength = 0;
if (mBuf != null)
{
ClearBlock(mBuf);
}
if (recoveredMessage != null)
{
ClearBlock(recoveredMessage);
recoveredMessage = null;
}
fullMessage = false;
}
/// <summary> Generate a signature for the loaded message using the key we were
/// initialised with.
/// </summary>
public byte[] GenerateSignature()
{
int digSize = digest.GetDigestSize();
byte[] m2Hash = new byte[digSize];
digest.DoFinal(m2Hash, 0);
byte[] C = new byte[8];
LtoOSP(messageLength * 8, C);
digest.BlockUpdate(C, 0, C.Length);
digest.BlockUpdate(mBuf, 0, messageLength);
digest.BlockUpdate(m2Hash, 0, m2Hash.Length);
byte[] salt;
if (standardSalt != null)
{
salt = standardSalt;
}
else
{
salt = new byte[saltLength];
random.NextBytes(salt);
}
digest.BlockUpdate(salt, 0, salt.Length);
byte[] hash = new byte[digest.GetDigestSize()];
digest.DoFinal(hash, 0);
int tLength = 2;
if (trailer == TrailerImplicit)
{
tLength = 1;
}
int off = block.Length - messageLength - salt.Length - hLen - tLength - 1;
block[off] = (byte) (0x01);
Array.Copy(mBuf, 0, block, off + 1, messageLength);
Array.Copy(salt, 0, block, off + 1 + messageLength, salt.Length);
byte[] dbMask = MaskGeneratorFunction1(hash, 0, hash.Length, block.Length - hLen - tLength);
for (int i = 0; i != dbMask.Length; i++)
{
block[i] ^= dbMask[i];
}
Array.Copy(hash, 0, block, block.Length - hLen - tLength, hLen);
if (trailer == TrailerImplicit)
{
block[block.Length - 1] = (byte)TrailerImplicit;
}
else
{
block[block.Length - 2] = (byte) ((uint)trailer >> 8);
block[block.Length - 1] = (byte) trailer;
}
block[0] &= (byte) (0x7f);
byte[] b = cipher.ProcessBlock(block, 0, block.Length);
ClearBlock(mBuf);
ClearBlock(block);
messageLength = 0;
return b;
}
/// <summary> return true if the signature represents a ISO9796-2 signature
/// for the passed in message.
/// </summary>
public virtual bool VerifySignature(
byte[] signature)
{
byte[] block = cipher.ProcessBlock(signature, 0, signature.Length);
//
// adjust block size for leading zeroes if necessary
//
int expectedSize = (keyBits + 7) / 8;
if (block.Length < expectedSize)
{
byte[] tmp = new byte[expectedSize];
block.CopyTo(tmp, tmp.Length - block.Length);
ClearBlock(block);
block = tmp;
}
int tLength;
if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
{
tLength = 1;
}
else
{
int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);
switch (sigTrail)
{
case TrailerRipeMD160:
if (!(digest is RipeMD160Digest))
{
throw new ArgumentException("signer should be initialised with RipeMD160");
}
break;
case TrailerSha1:
if (!(digest is Sha1Digest))
{
throw new ArgumentException("signer should be initialised with SHA1");
}
break;
case TrailerRipeMD128:
if (!(digest is RipeMD128Digest))
{
throw new ArgumentException("signer should be initialised with RipeMD128");
}
break;
default:
throw new ArgumentException("unrecognised hash in signature");
}
tLength = 2;
}
//
// calculate H(m2)
//
byte[] m2Hash = new byte[hLen];
digest.DoFinal(m2Hash, 0);
//
// remove the mask
//
byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - tLength, hLen, block.Length - hLen - tLength);
for (int i = 0; i != dbMask.Length; i++)
{
block[i] ^= dbMask[i];
}
block[0] &= 0x7f;
//
// find out how much padding we've got
//
int mStart = 0;
while (mStart < block.Length)
{
if (block[mStart++] == 0x01)
break;
}
if (mStart >= block.Length)
{
ClearBlock(block);
return false;
}
fullMessage = (mStart > 1);
// TODO Should we check if a standardSalt was set and, if so, use its length instead?
recoveredMessage = new byte[dbMask.Length - mStart - saltLength];
Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
//
// check the hashes
//
byte[] C = new byte[8];
LtoOSP(recoveredMessage.Length * 8, C);
digest.BlockUpdate(C, 0, C.Length);
if (recoveredMessage.Length != 0)
{
digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length);
}
digest.BlockUpdate(m2Hash, 0, m2Hash.Length);
// Update for the salt
digest.BlockUpdate(block, mStart + recoveredMessage.Length, saltLength);
byte[] hash = new byte[digest.GetDigestSize()];
digest.DoFinal(hash, 0);
int off = block.Length - tLength - hash.Length;
// TODO ConstantTimeAreEqual with offset for one array
bool isOkay = true;
for (int i = 0; i != hash.Length; i++)
{
if (hash[i] != block[off + i])
{
isOkay = false;
}
}
ClearBlock(block);
ClearBlock(hash);
if (!isOkay)
{
fullMessage = false;
ClearBlock(recoveredMessage);
return false;
}
//
// if they've input a message check what we've recovered against
// what was input.
//
if (messageLength != 0)
{
if (!IsSameAs(mBuf, recoveredMessage))
{
ClearBlock(mBuf);
return false;
}
messageLength = 0;
}
ClearBlock(mBuf);
return true;
}
/// <summary>
/// Return true if the full message was recoveredMessage.
/// </summary>
/// <returns>true on full message recovery, false otherwise, or if not sure.</returns>
/// <seealso cref="ISignerWithRecovery.HasFullMessage"/>
public virtual bool HasFullMessage()
{
return fullMessage;
}
/// <summary> int to octet string.</summary>
/// <summary> int to octet string.</summary>
private void ItoOSP(
int i,
byte[] sp)
{
sp[0] = (byte)((uint)i >> 24);
sp[1] = (byte)((uint)i >> 16);
sp[2] = (byte)((uint)i >> 8);
sp[3] = (byte)((uint)i >> 0);
}
/// <summary> long to octet string.</summary>
private void LtoOSP(long l, byte[] sp)
{
sp[0] = (byte)((ulong)l >> 56);
sp[1] = (byte)((ulong)l >> 48);
sp[2] = (byte)((ulong)l >> 40);
sp[3] = (byte)((ulong)l >> 32);
sp[4] = (byte)((ulong)l >> 24);
sp[5] = (byte)((ulong)l >> 16);
sp[6] = (byte)((ulong)l >> 8);
sp[7] = (byte)((ulong)l >> 0);
}
/// <summary> mask generator function, as described in Pkcs1v2.</summary>
private byte[] MaskGeneratorFunction1(
byte[] Z,
int zOff,
int zLen,
int length)
{
byte[] mask = new byte[length];
byte[] hashBuf = new byte[hLen];
byte[] C = new byte[4];
int counter = 0;
digest.Reset();
do
{
ItoOSP(counter, C);
digest.BlockUpdate(Z, zOff, zLen);
digest.BlockUpdate(C, 0, C.Length);
digest.DoFinal(hashBuf, 0);
Array.Copy(hashBuf, 0, mask, counter * hLen, hLen);
}
while (++counter < (length / hLen));
if ((counter * hLen) < length)
{
ItoOSP(counter, C);
digest.BlockUpdate(Z, zOff, zLen);
digest.BlockUpdate(C, 0, C.Length);
digest.DoFinal(hashBuf, 0);
Array.Copy(hashBuf, 0, mask, counter * hLen, mask.Length - (counter * hLen));
}
return mask;
}
}
}
| drazenzadravec/nequeo | Source/Components/Cryptography/Nequeo.Cryptography/Nequeo.Cryptography.Key/crypto/signers/Iso9796d2PssSigner.cs | C# | gpl-2.0 | 14,080 |
/*
* *************************************************************************
* NetworkBrowserFragment.java
* **************************************************************************
* Copyright © 2015 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* 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.videolan.vlc.gui.browser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import org.videolan.vlc.media.MediaDatabase;
import org.videolan.vlc.media.MediaWrapper;
import org.videolan.vlc.R;
import org.videolan.vlc.util.AndroidDevices;
import java.util.ArrayList;
public class NetworkBrowserFragment extends BaseBrowserFragment {
public NetworkBrowserFragment() {
ROOT = "smb";
mHandler = new BrowserFragmentHandler(this);
mAdapter = new NetworkBrowserAdapter(this);
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (mMrl == null)
mMrl = ROOT;
mRoot = ROOT.equals(mMrl);
}
public void onStart(){
super.onStart();
//Handle network connection state
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(networkReceiver, filter);
}
@Override
protected Fragment createFragment() {
return new NetworkBrowserFragment();
}
@Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(networkReceiver);
}
@Override
protected void update() {
if (!AndroidDevices.hasLANConnection())
updateEmptyView();
else
super.update();
}
protected void updateDisplay() {
if (mRoot)
updateFavorites();
mAdapter.notifyDataSetChanged();
parseSubDirectories();
}
@Override
protected void browseRoot() {
ArrayList<MediaWrapper> favs = MediaDatabase.getInstance().getAllNetworkFav();
if (!favs.isEmpty()) {
mFavorites = favs.size();
for (MediaWrapper fav : favs) {
mAdapter.addItem(fav, false, true);
}
mAdapter.addItem("Network favorites", false, true);
}
mMediaBrowser.discoverNetworkShares();
}
@Override
protected String getCategoryTitle() {
return getString(R.string.network_browsing);
}
private void updateFavorites(){
ArrayList<MediaWrapper> favs = MediaDatabase.getInstance().getAllNetworkFav();
int newSize = favs.size(), totalSize = mAdapter.getItemCount();
if (newSize == 0 && mFavorites == 0)
return;
for (int i = 1 ; i <= mFavorites ; ++i){ //remove former favorites
mAdapter.removeItem(totalSize-i, mReadyToDisplay);
}
if (newSize == 0)
mAdapter.removeItem(totalSize-mFavorites-1, mReadyToDisplay); //also remove separator if no more fav
else {
if (mFavorites == 0)
mAdapter.addItem("Network favorites", false, false); //add header if needed
for (MediaWrapper fav : favs)
mAdapter.addItem(fav, false, false); //add new favorites
}
mFavorites = newSize; //update count
}
public void toggleFavorite() {
MediaDatabase db = MediaDatabase.getInstance();
if (db.networkFavExists(mCurrentMedia.getUri()))
db.deleteNetworkFav(mCurrentMedia.getUri());
else
db.addNetworkFavItem(mCurrentMedia.getUri(), mCurrentMedia.getTitle());
getActivity().supportInvalidateOptionsMenu();
}
/**
* Update views visibility and emptiness info
*/
protected void updateEmptyView() {
if (AndroidDevices.hasLANConnection()) {
if (mAdapter.isEmpty()) {
mEmptyView.setText(mRoot ? R.string.network_shares_discovery : R.string.network_empty);
mEmptyView.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
mSwipeRefreshLayout.setEnabled(false);
} else {
if (mEmptyView.getVisibility() == View.VISIBLE) {
mEmptyView.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setEnabled(true);
}
}
} else {
if (mEmptyView.getVisibility() == View.GONE) {
mEmptyView.setText(R.string.network_connection_needed);
mEmptyView.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
mSwipeRefreshLayout.setEnabled(false);
}
}
}
private final BroadcastReceiver networkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (mReadyToDisplay && ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
update();
}
}
};
}
| marek-g/libvlc-signio | vlc-android/src/org/videolan/vlc/gui/browser/NetworkBrowserFragment.java | Java | gpl-2.0 | 6,093 |
/******************************************************************************
* Icinga 2 *
* Copyright (C) 2012-2016 Icinga Development Team (https://www.icinga.org/) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
#ifndef TLSUTILITY_H
#define TLSUTILITY_H
#include "base/i2-base.hpp"
#include "base/object.hpp"
#include "base/string.hpp"
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/comp.h>
#include <openssl/sha.h>
#include <openssl/x509v3.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/exception/info.hpp>
namespace icinga
{
void I2_BASE_API InitializeOpenSSL(void);
boost::shared_ptr<SSL_CTX> I2_BASE_API MakeSSLContext(const String& pubkey = String(), const String& privkey = String(), const String& cakey = String());
void I2_BASE_API AddCRLToSSLContext(const boost::shared_ptr<SSL_CTX>& context, const String& crlPath);
void I2_BASE_API SetCipherListToSSLContext(const boost::shared_ptr<SSL_CTX>& context, const String& cipherList);
void I2_BASE_API SetTlsProtocolminToSSLContext(const boost::shared_ptr<SSL_CTX>& context, const String& tlsProtocolmin);
String I2_BASE_API GetCertificateCN(const boost::shared_ptr<X509>& certificate);
boost::shared_ptr<X509> I2_BASE_API GetX509Certificate(const String& pemfile);
int I2_BASE_API MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile = String(), const String& certfile = String(), bool ca = false);
boost::shared_ptr<X509> I2_BASE_API CreateCert(EVP_PKEY *pubkey, X509_NAME *subject, X509_NAME *issuer, EVP_PKEY *cakey, bool ca);
String I2_BASE_API GetIcingaCADir(void);
String I2_BASE_API CertificateToString(const boost::shared_ptr<X509>& cert);
boost::shared_ptr<X509> I2_BASE_API CreateCertIcingaCA(EVP_PKEY *pubkey, X509_NAME *subject);
String I2_BASE_API PBKDF2_SHA1(const String& password, const String& salt, int iterations);
String I2_BASE_API SHA1(const String& s);
String I2_BASE_API SHA256(const String& s);
String I2_BASE_API RandomString(int length);
class I2_BASE_API openssl_error : virtual public std::exception, virtual public boost::exception { };
struct errinfo_openssl_error_;
typedef boost::error_info<struct errinfo_openssl_error_, unsigned long> errinfo_openssl_error;
inline std::string to_string(const errinfo_openssl_error& e)
{
std::ostringstream tmp;
int code = e.value();
char errbuf[120];
const char *message = ERR_error_string(code, errbuf);
if (message == NULL)
message = "Unknown error.";
tmp << code << ", \"" << message << "\"";
return "[errinfo_openssl_error]" + tmp.str() + "\n";
}
}
#endif /* TLSUTILITY_H */
| lazyfrosch/debian-icinga2 | lib/base/tlsutility.hpp | C++ | gpl-2.0 | 3,886 |
##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# http://www.morningstarsecurity.com/research/whatweb
##
# Version 0.2 # 2011-02-24 #
# Updated version detection
##
Plugin.define "PHP-Live" do
author "Brendan Coles <bcoles@gmail.com>" # 2010-09-03
version "0.2"
description "PHP Live! enables live help and live customer support communication directly from your website. - homepage: http://www.phplivesupport.com/"
# Google results as at 2010-08-31 #
# 158 for "powered by PHP Live!" -Vulnerability
# 7 for "powered by PHP Live!" intitle:"Knowledge BASE (FAQ)" inurl:knowledge_search.php
# 14 for "powered by PHP Live!" (intitle:"Request Live! Support"|"Please leave a message") inurl:request_email.php
# Dorks #
dorks [
'"powered by PHP Live!" -Vulnerability'
]
# Examples #
examples %w|
74.208.90.54:400/rep.ipmanage.net/httpdocs/phplive/admin/traffic/knowledge_search.php
jswcrm.com/livechat/request_email.php
lib207.lib.wwu.edu/phplive/request_email.php
live.trainingjolt.com/request_email.php
livehelp.vi.virginia.gov/admin/traffic/knowledge_search.php
livehelp.preferred-care-pharmacy.com/message_box.php
phplive.prostarcrm.com/message_box.php
phplive.sig-support.com/rus/admin/traffic/knowledge_search.php
secure.westnic.net/livesupport/request_email.php
talk.lifechurch.tv/phplive/request_email.php
www.megrisoft.com/livesupport/request_email.php
www.activitydirectorsnetwork.com/phplive/admin/traffic/knowledge_search.php
www.vividracing.com/phplive/request_email.php
www.lccavia.ru/support/request_email.php
www.hthengineering.com/phplive/message_box.php
www.phplivesupport.co.uk/phplive/admin/traffic/knowledge_search.php
www.activitydirectorsnetwork.com/phplive/admin/traffic/knowledge_search.php
www.nutridirect.co.uk/phplive/admin/traffic/knowledge_search.php
www.indecenciashop.com.br/phplive/admin/traffic/knowledge_search.php
www.guestcentric.com/support/request_email.php
www.toureast.com/en/chatlive/request_email.php
www.edunet-help.com/request_email.php
www.lbsib.com/support/request_email.php
www.hotelangelshome.com/support/request_email.php
www.robotsetup.com/support/request_email.php
|
# Matches #
matches [
# Javascript
{ :text=>'// image is NOT CACHED (Netscape problem). keep this or bad things could happen' },
# HTML Comments
{ :text=>'<!-- copyright OSI Codes Inc. http://www.osicodes.com [DO NOT DELETE] -->' },
{ :text=>'<!-- copyright OSI Codes, http://www.osicodes.com [DO NOT DELETE] -->' },
{ :text=>'<!-- BEGIN PHP Live! Code, copyright 2001 OSI Codes -->' },
{ :text=>'<!-- END PHP Live! Code, copyright 2001 OSI Codes -->' },
# FAQ # Default Title
{ :text=>'<title> Knowledge BASE (FAQ) </title>' },
# Error page
{ :text=>'<font color="#FF0000">[Configuration Error: config files not found!] Exiting' },
# Version Detection # Powered by text
{ :version=>/ <div id="copyright">Powered by <a href='http:\/\/www.phplivesupport.com\/\?link' target='newwin'>PHP Live\!<\/a> v([\d\.]+) © OSI Codes Inc.<\/div>/ },
]
end
| tennc/WhatWeb | plugins/PHP-Live.rb | Ruby | gpl-2.0 | 3,117 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright held by original author
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Class
Foam::primitiveMeshGeometry
Description
Updateable mesh geometry + checking routines.
SourceFiles
primitiveMeshGeometry.C
\*---------------------------------------------------------------------------*/
#ifndef primitiveMeshGeometry_H
#define primitiveMeshGeometry_H
#include "pointFields.H"
#include "HashSet.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class primitiveMeshGeometry Declaration
\*---------------------------------------------------------------------------*/
class primitiveMeshGeometry
{
//- Reference to primitiveMesh.
const primitiveMesh& mesh_;
//- Uptodate copy of face areas
vectorField faceAreas_;
//- Uptodate copy of face centres
vectorField faceCentres_;
//- Uptodate copy of cell centres
vectorField cellCentres_;
//- Uptodate copy of cell volumes
scalarField cellVolumes_;
// Private Member Functions
//- Update face areas and centres on selected faces.
void updateFaceCentresAndAreas
(
const pointField& p,
const labelList& changedFaces
);
//- Update cell volumes and centres on selected cells. Requires
// cells and faces to be consistent set.
void updateCellCentresAndVols
(
const labelList& changedCells,
const labelList& changedFaces
);
public:
ClassName("primitiveMeshGeometry");
// Constructors
//- Construct from mesh
primitiveMeshGeometry(const primitiveMesh&);
// Member Functions
// Access
const primitiveMesh& mesh() const
{
return mesh_;
}
const vectorField& faceAreas() const
{
return faceAreas_;
}
const vectorField& faceCentres() const
{
return faceCentres_;
}
const vectorField& cellCentres() const
{
return cellCentres_;
}
const scalarField& cellVolumes() const
{
return cellVolumes_;
}
// Edit
//- Take over properties from mesh
void correct();
//- Recalculate on selected faces. Recalculates cell properties
// on owner and neighbour of these cells.
void correct
(
const pointField& p,
const labelList& changedFaces
);
//- Helper function: get affected cells from faces
labelList affectedCells(const labelList& changedFaces) const;
// Checking of selected faces with supplied geometry (mesh only used for
// topology). Parallel aware.
static bool checkFaceDotProduct
(
const bool report,
const scalar orthWarn,
const primitiveMesh&,
const vectorField& cellCentres,
const vectorField& faceAreas,
const labelList& checkFaces,
labelHashSet* setPtr
);
static bool checkFacePyramids
(
const bool report,
const scalar minPyrVol,
const primitiveMesh&,
const vectorField& cellCentres,
const pointField& p,
const labelList& checkFaces,
labelHashSet*
);
static bool checkFaceSkewness
(
const bool report,
const scalar internalSkew,
const scalar boundarySkew,
const primitiveMesh& mesh,
const vectorField& cellCentres,
const vectorField& faceCentres,
const vectorField& faceAreas,
const labelList& checkFaces,
labelHashSet* setPtr
);
static bool checkFaceWeights
(
const bool report,
const scalar warnWeight,
const primitiveMesh& mesh,
const vectorField& cellCentres,
const vectorField& faceCentres,
const vectorField& faceAreas,
const labelList& checkFaces,
labelHashSet* setPtr
);
static bool checkFaceAngles
(
const bool report,
const scalar maxDeg,
const primitiveMesh& mesh,
const vectorField& faceAreas,
const pointField& p,
const labelList& checkFaces,
labelHashSet* setPtr
);
//static bool checkFaceFlatness
//(
// const bool report,
// const scalar warnFlatness,
// const primitiveMesh&,
// const vectorField& faceAreas,
// const vectorField& faceCentres,
// const pointField& p,
// const labelList& checkFaces,
// labelHashSet* setPtr
//);
static bool checkFaceTwist
(
const bool report,
const scalar minTwist,
const primitiveMesh&,
const vectorField& faceAreas,
const vectorField& faceCentres,
const pointField& p,
const labelList& checkFaces,
labelHashSet* setPtr
);
static bool checkFaceArea
(
const bool report,
const scalar minArea,
const primitiveMesh&,
const vectorField& faceAreas,
const labelList& checkFaces,
labelHashSet* setPtr
);
static bool checkCellDeterminant
(
const bool report,
const scalar minDet,
const primitiveMesh&,
const vectorField& faceAreas,
const labelList& checkFaces,
const labelList& affectedCells,
labelHashSet* setPtr
);
// Checking of selected faces with local geometry. Uses above static
// functions. Parallel aware.
bool checkFaceDotProduct
(
const bool report,
const scalar orthWarn,
const labelList& checkFaces,
labelHashSet* setPtr
) const;
bool checkFacePyramids
(
const bool report,
const scalar minPyrVol,
const pointField& p,
const labelList& checkFaces,
labelHashSet* setPtr
) const;
bool checkFaceSkewness
(
const bool report,
const scalar internalSkew,
const scalar boundarySkew,
const labelList& checkFaces,
labelHashSet* setPtr
) const;
bool checkFaceWeights
(
const bool report,
const scalar warnWeight,
const labelList& checkFaces,
labelHashSet* setPtr
) const;
bool checkFaceAngles
(
const bool report,
const scalar maxDeg,
const pointField& p,
const labelList& checkFaces,
labelHashSet* setPtr
) const;
//bool checkFaceFlatness
//(
// const bool report,
// const scalar warnFlatness,
// const pointField& p,
// const labelList& checkFaces,
// labelHashSet* setPtr
//) const;
bool checkFaceTwist
(
const bool report,
const scalar minTwist,
const pointField& p,
const labelList& checkFaces,
labelHashSet* setPtr
) const;
bool checkFaceArea
(
const bool report,
const scalar minArea,
const labelList& checkFaces,
labelHashSet* setPtr
) const;
bool checkCellDeterminant
(
const bool report,
const scalar warnDet,
const labelList& checkFaces,
const labelList& affectedCells,
labelHashSet* setPtr
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| CFDEMproject/OpenFOAM-1.6-ext | src/meshTools/primitiveMeshGeometry/primitiveMeshGeometry.H | C++ | gpl-2.0 | 10,206 |
/*
* Copyright 2006-2018 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 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.
*
* MZmine 2 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 MZmine 2; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.sf.mzmine.modules.rawdatamethods.exportscans;
import java.util.Collection;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.ArrayUtils;
import net.sf.mzmine.datamodel.MZmineProject;
import net.sf.mzmine.datamodel.RawDataFile;
import net.sf.mzmine.datamodel.Scan;
import net.sf.mzmine.modules.MZmineModuleCategory;
import net.sf.mzmine.modules.MZmineProcessingModule;
import net.sf.mzmine.parameters.ParameterSet;
import net.sf.mzmine.parameters.parametertypes.selectors.ScanSelection;
import net.sf.mzmine.taskcontrol.Task;
import net.sf.mzmine.util.ExitCode;
/**
* Exports scans around a center time
*/
public class ExportScansFromRawFilesModule implements MZmineProcessingModule {
private static final String MODULE_NAME = "Export scans into one file";
private static final String MODULE_DESCRIPTION = "Export scans or mass lists into one file ";
@Override
public @Nonnull String getName() {
return MODULE_NAME;
}
@Override
public @Nonnull String getDescription() {
return MODULE_DESCRIPTION;
}
@Override
@Nonnull
public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
@Nonnull Collection<Task> tasks) {
ScanSelection select =
parameters.getParameter(ExportScansFromRawFilesParameters.scanSelect).getValue();
Scan[] scans = new Scan[0];
for (RawDataFile raw : parameters.getParameter(ExportScansFromRawFilesParameters.dataFiles)
.getValue().getMatchingRawDataFiles()) {
scans = ArrayUtils.addAll(scans, select.getMatchingScans(raw));
}
ExportScansTask task = new ExportScansTask(scans, parameters);
tasks.add(task);
return ExitCode.OK;
}
@Override
public @Nonnull MZmineModuleCategory getModuleCategory() {
return MZmineModuleCategory.RAWDATA;
}
@Override
public @Nonnull Class<? extends ParameterSet> getParameterSetClass() {
return ExportScansFromRawFilesParameters.class;
}
}
| du-lab/mzmine2 | src/main/java/net/sf/mzmine/modules/rawdatamethods/exportscans/ExportScansFromRawFilesModule.java | Java | gpl-2.0 | 2,761 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Tax
* @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
$installer = $this;
/* $installer Mage_Core_Model_Resource_Setup */
$installer->startSetup();
$installer->run("DROP TABLE IF EXISTS {$this->getTable('tax_class_group')};");
$installer->endSetup();
| tonio-44/tikflak | shop/app/code/core/Mage/Tax/sql/tax_setup/mysql4-upgrade-0.6.1-0.7.0.php | PHP | gpl-2.0 | 1,168 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Search_Lucene
* @subpackage Search
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Wildcard.php 17687 2009-08-20 12:55:34Z thomas $
*/
/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';
/** Zend_Search_Lucene_Search_Query_MultiTerm */
require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';
/**
* @category Zend
* @package Zend_Search_Lucene
* @subpackage Search
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Search_Lucene_Search_Query_Wildcard extends Zend_Search_Lucene_Search_Query
{
/**
* Search pattern.
*
* Field has to be fully specified or has to be null
* Text may contain '*' or '?' symbols
*
* @var Zend_Search_Lucene_Index_Term
*/
private $_pattern;
/**
* Matched terms.
*
* Matched terms list.
* It's filled during the search (rewrite operation) and may be used for search result
* post-processing
*
* Array of Zend_Search_Lucene_Index_Term objects
*
* @var array
*/
private $_matches = null;
/**
* Minimum term prefix length (number of minimum non-wildcard characters)
*
* @var integer
*/
private static $_minPrefixLength = 3;
/**
* Zend_Search_Lucene_Search_Query_Wildcard constructor.
*
* @param Zend_Search_Lucene_Index_Term $pattern
*/
public function __construct(Zend_Search_Lucene_Index_Term $pattern)
{
$this->_pattern = $pattern;
}
/**
* Get minimum prefix length
*
* @return integer
*/
public static function getMinPrefixLength()
{
return self::$_minPrefixLength;
}
/**
* Set minimum prefix length
*
* @param integer $minPrefixLength
*/
public static function setMinPrefixLength($minPrefixLength)
{
self::$_minPrefixLength = $minPrefixLength;
}
/**
* Get terms prefix
*
* @param string $word
* @return string
*/
private static function _getPrefix($word)
{
$questionMarkPosition = strpos($word, '?');
$astrericPosition = strpos($word, '*');
if ($questionMarkPosition !== false) {
if ($astrericPosition !== false) {
return substr($word, 0, min($questionMarkPosition, $astrericPosition));
}
return substr($word, 0, $questionMarkPosition);
} else if ($astrericPosition !== false) {
return substr($word, 0, $astrericPosition);
}
return $word;
}
/**
* Re-write query into primitive queries in the context of specified index
*
* @param Zend_Search_Lucene_Interface $index
* @return Zend_Search_Lucene_Search_Query
* @throws Zend_Search_Lucene_Exception
*/
public function rewrite(Zend_Search_Lucene_Interface $index)
{
$this->_matches = array();
if ($this->_pattern->field === null) {
// Search through all fields
$fields = $index->getFieldNames(true /* indexed fields list */);
} else {
$fields = array($this->_pattern->field);
}
$prefix = self::_getPrefix($this->_pattern->text);
$prefixLength = strlen($prefix);
$matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/';
if ($prefixLength < self::$_minPrefixLength) {
throw new Zend_Search_Lucene_Exception('At least ' . self::$_minPrefixLength . ' non-wildcard characters are required at the beginning of pattern.');
}
/** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */
if (@preg_match('/\pL/u', 'a') == 1) {
// PCRE unicode support is turned on
// add Unicode modifier to the match expression
$matchExpression .= 'u';
}
$maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit();
foreach ($fields as $field) {
$index->resetTermsStream();
if ($prefix != '') {
$index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field));
while ($index->currentTerm() !== null &&
$index->currentTerm()->field == $field &&
substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) {
if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
$this->_matches[] = $index->currentTerm();
if ($maxTerms != 0 && count($this->_matches) > $maxTerms) {
throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
}
}
$index->nextTerm();
}
} else {
$index->skipTo(new Zend_Search_Lucene_Index_Term('', $field));
while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) {
if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
$this->_matches[] = $index->currentTerm();
if ($maxTerms != 0 && count($this->_matches) > $maxTerms) {
throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
}
}
$index->nextTerm();
}
}
$index->closeTermsStream();
}
if (count($this->_matches) == 0) {
return new Zend_Search_Lucene_Search_Query_Empty();
} else if (count($this->_matches) == 1) {
return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches));
} else {
$rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($this->_matches as $matchedTerm) {
$rewrittenQuery->addTerm($matchedTerm);
}
return $rewrittenQuery;
}
}
/**
* Optimize query in the context of specified index
*
* @param Zend_Search_Lucene_Interface $index
* @return Zend_Search_Lucene_Search_Query
*/
public function optimize(Zend_Search_Lucene_Interface $index)
{
throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
}
/**
* Returns query pattern
*
* @return Zend_Search_Lucene_Index_Term
*/
public function getPattern()
{
return $this->_pattern;
}
/**
* Return query terms
*
* @return array
* @throws Zend_Search_Lucene_Exception
*/
public function getQueryTerms()
{
if ($this->_matches === null) {
throw new Zend_Search_Lucene_Exception('Search has to be performed first to get matched terms');
}
return $this->_matches;
}
/**
* Constructs an appropriate Weight implementation for this query.
*
* @param Zend_Search_Lucene_Interface $reader
* @return Zend_Search_Lucene_Search_Weight
* @throws Zend_Search_Lucene_Exception
*/
public function createWeight(Zend_Search_Lucene_Interface $reader)
{
throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
}
/**
* Execute query in context of index reader
* It also initializes necessary internal structures
*
* @param Zend_Search_Lucene_Interface $reader
* @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
* @throws Zend_Search_Lucene_Exception
*/
public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
{
throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
}
/**
* Get document ids likely matching the query
*
* It's an array with document ids as keys (performance considerations)
*
* @return array
* @throws Zend_Search_Lucene_Exception
*/
public function matchedDocs()
{
throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
}
/**
* Score specified document
*
* @param integer $docId
* @param Zend_Search_Lucene_Interface $reader
* @return float
* @throws Zend_Search_Lucene_Exception
*/
public function score($docId, Zend_Search_Lucene_Interface $reader)
{
throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
}
/**
* Query specific matches highlighting
*
* @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting)
*/
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter)
{
$words = array();
$matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/';
if (@preg_match('/\pL/u', 'a') == 1) {
// PCRE unicode support is turned on
// add Unicode modifier to the match expression
$matchExpression .= 'u';
}
$docBody = $highlighter->getDocument()->getFieldUtf8Value('body');
$tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8');
foreach ($tokens as $token) {
if (preg_match($matchExpression, $token->getTermText()) === 1) {
$words[] = $token->getTermText();
}
}
$highlighter->highlight($words);
}
/**
* Print a query
*
* @return string
*/
public function __toString()
{
// It's used only for query visualisation, so we don't care about characters escaping
if ($this->_pattern->field !== null) {
$query = $this->_pattern->field . ':';
} else {
$query = '';
}
$query .= $this->_pattern->text;
if ($this->getBoost() != 1) {
$query = $query . '^' . round($this->getBoost(), 4);
}
return $query;
}
}
| NewTechNetwork/EchoOpen | Zend/Search/Lucene/Search/Query/Wildcard.php | PHP | gpl-2.0 | 11,239 |
<?php
/**
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
*
* @author Axel Kirch <axel@globeglotter.com>
* @author MaWi <drmaxxis@gmail.com>
* @author lp <spam@lukpopp.ch>
* @author Martin <martin@andev.de>
* @author F. Mueller-Donath <j.felix@mueller-donath.de>
* @author Andreas Gohr <andi@splitbrain.org>
* @author Christof <gagi@fin.de>
* @author Anika Henke <anika@selfthinker.org>
* @author Esther Brunner <esther@kaffeehaus.ch>
* @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
* @author Michael Klier <chi@chimeric.de>
* @author Leo Moll <leo@yeasoft.com>
* @author Florian Anderiasch <fa@art-core.org>
* @author Robin Kluth <commi1993@gmail.com>
* @author Arne Pelka <mail@arnepelka.de>
* @author Alexander Fischer <tbanus@os-forge.net>
* @author Juergen Schwarzer <jschwarzer@freenet.de>
* @author Marcel Metz <marcel_metz@gmx.de>
* @author Matthias Schulte <dokuwiki@lupo49.de>
* @author Christian Wichmann <nospam@zone0.de>
* @author Pierre Corell <info@joomla-praxis.de>
* @author Frank Loizzi <contact@software.bacal.de>
* @author Volker Bödker <volker@boedker.de>
* @author Janosch <janosch@moinzen.de>
* @author rnck <dokuwiki@rnck.de>
*/
$lang['encoding'] = 'utf-8';
$lang['direction'] = 'ltr';
$lang['doublequoteopening'] = '„';
$lang['doublequoteclosing'] = '“';
$lang['singlequoteopening'] = '‚';
$lang['singlequoteclosing'] = '‘';
$lang['apostrophe'] = '’';
$lang['btn_edit'] = 'Diese Seite bearbeiten';
$lang['btn_source'] = 'Quelltext anzeigen';
$lang['btn_show'] = 'Seite anzeigen';
$lang['btn_create'] = 'Seite anlegen';
$lang['btn_search'] = 'Suchen';
$lang['btn_save'] = 'Speichern';
$lang['btn_preview'] = 'Vorschau';
$lang['btn_top'] = 'Nach oben';
$lang['btn_newer'] = '<< jüngere Änderungen';
$lang['btn_older'] = 'ältere Änderungen >>';
$lang['btn_revs'] = 'Ältere Versionen';
$lang['btn_recent'] = 'Letzte Änderungen';
$lang['btn_upload'] = 'Hochladen';
$lang['btn_cancel'] = 'Abbrechen';
$lang['btn_index'] = 'Übersicht';
$lang['btn_secedit'] = 'Bearbeiten';
$lang['btn_login'] = 'Anmelden';
$lang['btn_logout'] = 'Abmelden';
$lang['btn_admin'] = 'Admin';
$lang['btn_update'] = 'Aktualisieren';
$lang['btn_delete'] = 'Löschen';
$lang['btn_back'] = 'Zurück';
$lang['btn_backlink'] = 'Links hierher';
$lang['btn_subscribe'] = 'Aboverwaltung';
$lang['btn_profile'] = 'Benutzerprofil';
$lang['btn_reset'] = 'Zurücksetzen';
$lang['btn_resendpwd'] = 'Neues Passwort festlegen';
$lang['btn_draft'] = 'Entwurf bearbeiten';
$lang['btn_recover'] = 'Entwurf wiederherstellen';
$lang['btn_draftdel'] = 'Entwurf löschen';
$lang['btn_revert'] = 'Wiederherstellen';
$lang['btn_register'] = 'Registrieren';
$lang['btn_apply'] = 'Übernehmen';
$lang['btn_media'] = 'Medien-Manager';
$lang['btn_deleteuser'] = 'Benutzerprofil löschen';
$lang['btn_img_backto'] = 'Zurück zu %s';
$lang['btn_mediaManager'] = 'Im Medien-Manager anzeigen';
$lang['loggedinas'] = 'Angemeldet als:';
$lang['user'] = 'Benutzername';
$lang['pass'] = 'Passwort';
$lang['newpass'] = 'Neues Passwort';
$lang['oldpass'] = 'Bestätigen (Altes Passwort)';
$lang['passchk'] = 'Passwort erneut eingeben';
$lang['remember'] = 'Angemeldet bleiben';
$lang['fullname'] = 'Voller Name';
$lang['email'] = 'E-Mail';
$lang['profile'] = 'Benutzerprofil';
$lang['badlogin'] = 'Benutzername oder Passwort sind falsch.';
$lang['badpassconfirm'] = 'Das Passwort war falsch.';
$lang['minoredit'] = 'Kleine Änderung';
$lang['draftdate'] = 'Entwurf automatisch gesichert am';
$lang['nosecedit'] = 'Diese Seite wurde inzwischen geändert. Weil deshalb ein oder mehrere Abschnitte veraltet sind, wurde die Seite komplett neu geladen.';
$lang['searchcreatepage'] = 'Falls der gesuchte Begriff nicht gefunden wurde, kannst du die nach deiner Anfrage benannte Seite %s umgehend neu anlegen.';
$lang['search_fullresults'] = 'Volltextergebnisse';
$lang['js']['search_toggle_tools'] = 'Suchwerkzeuge umschalten';
$lang['js']['willexpire'] = 'Die Sperre zur Bearbeitung dieser Seite läuft in einer Minute ab.\nUm Bearbeitungskonflikte zu vermeiden, solltest du sie durch einen Klick auf den Vorschau-Knopf verlängern.';
$lang['js']['notsavedyet'] = 'Nicht gespeicherte Änderungen gehen verloren!';
$lang['js']['searchmedia'] = 'Suche nach Dateien';
$lang['js']['keepopen'] = 'Fenster nach Auswahl nicht schließen';
$lang['js']['hidedetails'] = 'Details ausblenden';
$lang['js']['mediatitle'] = 'Link-Eigenschaften';
$lang['js']['mediadisplay'] = 'Linktyp';
$lang['js']['mediaalign'] = 'Ausrichtung';
$lang['js']['mediasize'] = 'Bildgröße';
$lang['js']['mediatarget'] = 'Linkziel';
$lang['js']['mediaclose'] = 'Schließen';
$lang['js']['mediainsert'] = 'Einfügen';
$lang['js']['mediadisplayimg'] = 'Bild anzeigen';
$lang['js']['mediadisplaylnk'] = 'Nur den Link anzeigen';
$lang['js']['mediasmall'] = 'Bild in kleiner Auflösung';
$lang['js']['mediamedium'] = 'Bild in mittlerer Auflösung';
$lang['js']['medialarge'] = 'Bild in hoher Auflösung';
$lang['js']['mediaoriginal'] = 'Originalauflösung';
$lang['js']['medialnk'] = 'Link zur Detailseite';
$lang['js']['mediadirect'] = 'Direkter Link zum Original';
$lang['js']['medianolnk'] = 'Kein Link';
$lang['js']['medianolink'] = 'Bild nicht verlinken';
$lang['js']['medialeft'] = 'Bild linksbündig ausrichten.';
$lang['js']['mediaright'] = 'Bild rechtsbündig ausrichten.';
$lang['js']['mediacenter'] = 'Bild horizontal zentriert ausrichten';
$lang['js']['medianoalign'] = 'Bild ohne bestimmte Ausrichtung lassen';
$lang['js']['nosmblinks'] = 'Das Verlinken von Windows-Freigaben funktioniert nur im Microsoft Internet-Explorer.\nDer Link kann jedoch zum Einfügen kopiert werden.';
$lang['js']['linkwiz'] = 'Link-Assistent';
$lang['js']['linkto'] = 'Link zu:';
$lang['js']['del_confirm'] = 'Die ausgewählten Dateien wirklich löschen?';
$lang['js']['restore_confirm'] = 'Wirklich diese Version wiederherstellen?';
$lang['js']['media_diff'] = 'Unterschiede anzeigen:';
$lang['js']['media_diff_both'] = 'Nebeneinander';
$lang['js']['media_diff_opacity'] = 'Überblenden';
$lang['js']['media_diff_portions'] = 'Übergang';
$lang['js']['media_select'] = 'Dateien auswählen…';
$lang['js']['media_upload_btn'] = 'Hochladen';
$lang['js']['media_done_btn'] = 'Fertig';
$lang['js']['media_drop'] = 'Dateien hier hinziehen um sie hochzuladen';
$lang['js']['media_cancel'] = 'Entfernen';
$lang['js']['media_overwrt'] = 'Existierende Dateien überschreiben';
$lang['search_exact_match'] = 'Genaue Treffer';
$lang['search_starts_with'] = 'Beginnt mit';
$lang['search_ends_with'] = 'Endet mit';
$lang['search_contains'] = 'Enthält';
$lang['search_custom_match'] = 'Angepasst ';
$lang['search_any_ns'] = 'Alle Namensräume';
$lang['search_any_time'] = 'Jederzeit';
$lang['search_past_7_days'] = 'Letzte Woche';
$lang['search_past_month'] = 'Letzter Monat';
$lang['search_past_year'] = 'Letztes Jahr';
$lang['search_sort_by_hits'] = 'Sortiere nach Treffer';
$lang['search_sort_by_mtime'] = 'Sortiere nach letzter Änderung';
$lang['regmissing'] = 'Alle Felder müssen ausgefüllt werden';
$lang['reguexists'] = 'Der Benutzername existiert leider schon.';
$lang['regsuccess'] = 'Der neue Benutzer wurde angelegt und das Passwort per E-Mail versandt.';
$lang['regsuccess2'] = 'Der neue Benutzer wurde angelegt.';
$lang['regfail'] = 'Der Benutzer konnte nicht erstellt werden.';
$lang['regmailfail'] = 'Offenbar ist ein Fehler beim Versenden der Passwortmail aufgetreten. Bitte wende dich an den Wiki-Admin.';
$lang['regbadmail'] = 'Die angegebene Mail-Adresse scheint ungültig zu sein. Falls dies ein Fehler ist, wende dich bitte an den Wiki-Admin.';
$lang['regbadpass'] = 'Die beiden eingegeben Passwörter stimmen nicht überein. Bitte versuche es noch einmal.';
$lang['regpwmail'] = 'Ihr DokuWiki-Passwort';
$lang['reghere'] = 'Du hast noch keinen Zugang? Hier registrieren';
$lang['profna'] = 'Änderung des Benutzerprofils in diesem Wiki nicht möglich.';
$lang['profnochange'] = 'Keine Änderungen, nichts zu tun.';
$lang['profnoempty'] = 'Es muss ein Name oder eine E-Mail Adresse angegeben werden.';
$lang['profchanged'] = 'Benutzerprofil erfolgreich geändert.';
$lang['profnodelete'] = 'Dieses Wiki unterstützt nicht das Löschen von Benutzern.';
$lang['profdeleteuser'] = 'Benutzerprofil löschen';
$lang['profdeleted'] = 'Dein Benutzerprofil wurde im Wiki gelöscht.';
$lang['profconfdelete'] = 'Ich möchte mein Benutzerprofil löschen.<br/> Diese Aktion ist nicht umkehrbar.';
$lang['profconfdeletemissing'] = 'Bestätigungs-Checkbox wurde nicht angehakt.';
$lang['proffail'] = 'Das Benutzerprofil wurde nicht aktualisiert.';
$lang['pwdforget'] = 'Passwort vergessen? Fordere ein neues an';
$lang['resendna'] = 'Passwörter versenden ist in diesem Wiki nicht möglich.';
$lang['resendpwd'] = 'Neues Passwort setzen für';
$lang['resendpwdmissing'] = 'Es tut mir leid, aber du musst alle Felder ausfüllen.';
$lang['resendpwdnouser'] = 'Es tut mir leid, aber der Benutzer existiert nicht in unserer Datenbank.';
$lang['resendpwdbadauth'] = 'Es tut mir leid, aber dieser Authentifizierungscode ist ungültig. Stelle sicher, dass du den kompletten Bestätigungslink verwendet haben.';
$lang['resendpwdconfirm'] = 'Ein Bestätigungslink wurde per E-Mail versandt.';
$lang['resendpwdsuccess'] = 'Dein neues Passwort wurde per E-Mail versandt.';
$lang['license'] = 'Falls nicht anders bezeichnet, ist der Inhalt dieses Wikis unter der folgenden Lizenz veröffentlicht:';
$lang['licenseok'] = 'Hinweis: Durch das Bearbeiten dieser Seite gibst du dein Einverständnis, dass dein Inhalt unter der folgenden Lizenz veröffentlicht wird:';
$lang['searchmedia'] = 'Suche nach Datei:';
$lang['searchmedia_in'] = 'Suche in %s';
$lang['txt_upload'] = 'Datei zum Hochladen auswählen:';
$lang['txt_filename'] = 'Hochladen als (optional):';
$lang['txt_overwrt'] = 'Bestehende Datei überschreiben';
$lang['maxuploadsize'] = 'Max. %s pro Datei-Upload.';
$lang['allowedmime'] = 'Liste der erlaubten Dateiendungen';
$lang['lockedby'] = 'Momentan gesperrt von:';
$lang['lockexpire'] = 'Sperre läuft ab am:';
$lang['rssfailed'] = 'Es ist ein Fehler beim Laden des Feeds aufgetreten: ';
$lang['nothingfound'] = 'Nichts gefunden.';
$lang['mediaselect'] = 'Dateiauswahl';
$lang['uploadsucc'] = 'Datei wurde erfolgreich hochgeladen';
$lang['uploadfail'] = 'Hochladen fehlgeschlagen. Keine Berechtigung?';
$lang['uploadwrong'] = 'Hochladen verweigert. Diese Dateiendung ist nicht erlaubt.';
$lang['uploadexist'] = 'Datei existiert bereits. Keine Änderungen vorgenommen.';
$lang['uploadbadcontent'] = 'Die hochgeladenen Daten stimmen nicht mit der Dateiendung %s überein.';
$lang['uploadspam'] = 'Hochladen verweigert: Treffer auf der Spamliste.';
$lang['uploadxss'] = 'Hochladen verweigert: Daten scheinen Schadcode zu enthalten.';
$lang['uploadsize'] = 'Die hochgeladene Datei war zu groß. (max. %s)';
$lang['deletesucc'] = 'Die Datei "%s" wurde gelöscht.';
$lang['deletefail'] = '"%s" konnte nicht gelöscht werden. Keine Berechtigung?.';
$lang['mediainuse'] = 'Die Datei "%s" wurde nicht gelöscht. Sie wird noch verwendet.';
$lang['namespaces'] = 'Namensräume';
$lang['mediafiles'] = 'Vorhandene Dateien in';
$lang['accessdenied'] = 'Du hast keinen Zugriff auf diese Seite';
$lang['mediausage'] = 'Syntax zum Verwenden dieser Datei:';
$lang['mediaview'] = 'Originaldatei öffnen';
$lang['mediaroot'] = 'Wurzel';
$lang['mediaupload'] = 'Lade hier eine Datei in den momentanen Namensraum hoch. Um Unterordner zu erstellen, stelle diese dem Dateinamen durch Doppelpunkt getrennt voran, nachdem Du die Datei ausgewählt hast.';
$lang['mediaextchange'] = 'Dateiendung vom .%s nach .%s geändert!';
$lang['reference'] = 'Verwendung von';
$lang['ref_inuse'] = 'Diese Datei kann nicht gelöscht werden, da sie noch von folgenden Seiten benutzt wird:';
$lang['ref_hidden'] = 'Einige Verweise sind auf Seiten, für die du keine Leseberechtigung hast.';
$lang['hits'] = 'Treffer';
$lang['quickhits'] = 'Passende Seitennamen';
$lang['toc'] = 'Inhaltsverzeichnis';
$lang['current'] = 'aktuell';
$lang['yours'] = 'Deine Version';
$lang['diff'] = 'Zeige Unterschiede zu aktueller Version';
$lang['diff2'] = 'Zeige Unterschiede der ausgewählten Versionen';
$lang['difflink'] = 'Link zu der Vergleichsansicht';
$lang['diff_type'] = 'Unterschiede anzeigen:';
$lang['diff_inline'] = 'Inline';
$lang['diff_side'] = 'Nebeneinander';
$lang['diffprevrev'] = 'Vorherige Überarbeitung';
$lang['diffnextrev'] = 'Nächste Überarbeitung';
$lang['difflastrev'] = 'Letzte Überarbeitung';
$lang['diffbothprevrev'] = 'Beide Seiten, vorherige Überarbeitung';
$lang['diffbothnextrev'] = 'Beide Seiten, nächste Überarbeitung';
$lang['line'] = 'Zeile';
$lang['breadcrumb'] = 'Zuletzt angesehen:';
$lang['youarehere'] = 'Du befindest dich hier:';
$lang['lastmod'] = 'Zuletzt geändert:';
$lang['by'] = 'von';
$lang['deleted'] = 'gelöscht';
$lang['created'] = 'angelegt';
$lang['restored'] = 'alte Version wiederhergestellt (%s)';
$lang['external_edit'] = 'Externe Bearbeitung';
$lang['summary'] = 'Zusammenfassung';
$lang['noflash'] = 'Das <a href="http://www.adobe.com/products/flashplayer/">Adobe Flash Plugin</a> wird benötigt, um diesen Inhalt anzuzeigen.';
$lang['download'] = 'Schnipsel herunterladen';
$lang['tools'] = 'Werkzeuge';
$lang['user_tools'] = 'Benutzer-Werkzeuge';
$lang['site_tools'] = 'Webseiten-Werkzeuge';
$lang['page_tools'] = 'Seiten-Werkzeuge';
$lang['skip_to_content'] = 'zum Inhalt springen';
$lang['sidebar'] = 'Seitenleiste';
$lang['mail_newpage'] = 'Neue Seite:';
$lang['mail_changed'] = 'Seite geändert:';
$lang['mail_subscribe_list'] = 'Geänderte Seiten im Namensraum:';
$lang['mail_new_user'] = 'Neuer Benutzer:';
$lang['mail_upload'] = 'Datei hochgeladen:';
$lang['changes_type'] = 'Änderungen anzeigen von';
$lang['pages_changes'] = 'Seiten';
$lang['media_changes'] = 'Mediendateien';
$lang['both_changes'] = 'Beides, Seiten- und Mediendateien';
$lang['qb_bold'] = 'Fetter Text';
$lang['qb_italic'] = 'Kursiver Text';
$lang['qb_underl'] = 'Unterstrichener Text';
$lang['qb_code'] = 'Code Text';
$lang['qb_strike'] = 'Durchgestrichener Text';
$lang['qb_h1'] = 'Level 1 Überschrift';
$lang['qb_h2'] = 'Level 2 Überschrift';
$lang['qb_h3'] = 'Level 3 Überschrift';
$lang['qb_h4'] = 'Level 4 Überschrift';
$lang['qb_h5'] = 'Level 5 Überschrift';
$lang['qb_h'] = 'Überschrift';
$lang['qb_hs'] = 'Wähle eine Überschrift';
$lang['qb_hplus'] = 'Überschrift eine Ebene höher';
$lang['qb_hminus'] = 'Überschrift eine Ebene runter';
$lang['qb_hequal'] = 'Überschrift auf selber Ebene';
$lang['qb_link'] = 'Interner Link';
$lang['qb_extlink'] = 'Externer Link';
$lang['qb_hr'] = 'Horizontale Linie';
$lang['qb_ol'] = 'Nummerierter Listenpunkt';
$lang['qb_ul'] = 'Listenpunkt';
$lang['qb_media'] = 'Bilder und andere Dateien hinzufügen';
$lang['qb_sig'] = 'Unterschrift einfügen';
$lang['qb_smileys'] = 'Smileys';
$lang['qb_chars'] = 'Sonderzeichen';
$lang['upperns'] = 'Gehe zum übergeordneten Namensraum';
$lang['metaedit'] = 'Metadaten bearbeiten';
$lang['metasaveerr'] = 'Die Metadaten konnten nicht gesichert werden';
$lang['metasaveok'] = 'Metadaten gesichert';
$lang['img_title'] = 'Titel:';
$lang['img_caption'] = 'Bildunterschrift:';
$lang['img_date'] = 'Datum:';
$lang['img_fname'] = 'Dateiname:';
$lang['img_fsize'] = 'Größe:';
$lang['img_artist'] = 'Fotograf:';
$lang['img_copyr'] = 'Copyright:';
$lang['img_format'] = 'Format:';
$lang['img_camera'] = 'Kamera:';
$lang['img_keywords'] = 'Schlagwörter:';
$lang['img_width'] = 'Breite:';
$lang['img_height'] = 'Höhe:';
$lang['subscr_subscribe_success'] = 'Die Seite %s wurde zur Abonnementliste von %s hinzugefügt';
$lang['subscr_subscribe_error'] = 'Fehler beim Hinzufügen von %s zur Abonnementliste von %s';
$lang['subscr_subscribe_noaddress'] = 'In deinem Account ist keine E-Mail-Adresse hinterlegt. Dadurch kann die Seite nicht abonniert werden';
$lang['subscr_unsubscribe_success'] = 'Die Seite %s wurde von der Abonnementliste von %s entfernt';
$lang['subscr_unsubscribe_error'] = 'Fehler beim Entfernen von %s von der Abonnementliste von %s';
$lang['subscr_already_subscribed'] = '%s ist bereits auf der Abonnementliste von %s';
$lang['subscr_not_subscribed'] = '%s ist nicht auf der Abonnementliste von %s';
$lang['subscr_m_not_subscribed'] = 'Du hast kein Abonnement von dieser Seite oder dem Namensraum.';
$lang['subscr_m_new_header'] = 'Abonnementen hinzufügen';
$lang['subscr_m_current_header'] = 'Aktive Abonnements';
$lang['subscr_m_unsubscribe'] = 'Abbestellen';
$lang['subscr_m_subscribe'] = 'Abonnieren';
$lang['subscr_m_receive'] = 'Erhalten';
$lang['subscr_style_every'] = 'E-Mail bei jeder Änderung';
$lang['subscr_style_digest'] = 'E-Mail mit zusammengefasster Übersicht der Seitenänderungen (alle %.2f Tage)';
$lang['subscr_style_list'] = 'Auflistung aller geänderten Seiten seit der letzten E-Mail (alle %.2f Tage)';
$lang['authtempfail'] = 'Benutzerüberprüfung momentan nicht möglich. Falls das Problem andauert, wende dich an den Admin.';
$lang['i_chooselang'] = 'Wähle deine Sprache';
$lang['i_installer'] = 'DokuWiki-Installation';
$lang['i_wikiname'] = 'Wiki-Name';
$lang['i_enableacl'] = 'Zugriffskontrolle (ACL) aktivieren (empfohlen)';
$lang['i_superuser'] = 'Benutzername des Administrators';
$lang['i_problems'] = 'Das Installationsprogramm hat unten aufgeführte Probleme festgestellt, die zunächst behoben werden müssen, bevor du mit der Installation fortfahren kannst.';
$lang['i_modified'] = 'Aus Sicherheitsgründen arbeitet dieses Skript nur mit einer neuen bzw. nicht modifizierten DokuWiki-Installation. Du solltest entweder alle Dateien noch einmal frisch installieren oder die <a href="http://dokuwiki.org/install">Dokuwiki-Installationsanleitung</a> konsultieren.';
$lang['i_funcna'] = 'Die PHP-Funktion <code>%s</code> ist nicht verfügbar. Unter Umständen wurde sie von deinem Hoster deaktiviert?';
$lang['i_disabled'] = 'Es wurde von deinem Provider deaktiviert.';
$lang['i_funcnmail'] = '<b>Hinweis:</b> Die PHP-Funktion "mail()" ist nicht verfügbar. %s Alternativ kansnt du das <a href="https://www.dokuwiki.org/plugin:smtp">SMTP-Plugin</a> installieren.';
$lang['i_phpver'] = 'Deine PHP-Version <code>%s</code> ist niedriger als die benötigte Version <code>%s</code>. Bitte aktualisiere deine PHP-Installation.';
$lang['i_mbfuncoverload'] = 'mbstring.func_overload muss in php.in deaktiviert werden um DokuWiki auszuführen.';
$lang['i_urandom'] = 'DokuWiki kann keine kryptografisch sicheren Werte für Cookies generieren. Möglicherweise möchtest du die "open_basedir"-Einstellungen in der zutreffenden php.ini auf korrekten Zugriff auf <code>/ dev/urandom</ code> überprüfen.';
$lang['i_permfail'] = '<code>%s</code> ist nicht durch DokuWiki beschreibbar. Du musst die Berechtigungen dieses Ordners ändern!';
$lang['i_confexists'] = '<code>%s</code> existiert bereits';
$lang['i_writeerr'] = '<code>%s</code> konnte nicht erzeugt werden. Du solltest die Verzeichnis-/Datei-Rechte überprüfen und die Datei manuell anlegen.';
$lang['i_badhash'] = 'Unbekannte oder modifizierte dokuwiki.php (Hash=<code>%s</code>)';
$lang['i_badval'] = '<code>%s</code> - unerlaubter oder leerer Wert';
$lang['i_success'] = 'Die Konfiguration wurde erfolgreich abgeschlossen. Du kannst jetzt die install.php löschen. Dein <a href="doku.php?id=wiki:welcome">neues DokuWiki</a> ist jetzt für dich bereit.';
$lang['i_failure'] = 'Es sind Fehler beim Schreiben der Konfigurationsdateien aufgetreten. Du musst diese von Hand beheben, bevor du dein <a href="doku.php?id=wiki:welcome">neues DokuWiki</a> nutzen kannst.';
$lang['i_policy'] = 'Anfangseinstellungen der Zugriffskontrolle (ACL)';
$lang['i_pol0'] = 'Offenes Wiki (lesen, schreiben und hochladen für alle Benutzer)';
$lang['i_pol1'] = 'Öffentliches Wiki (Lesen für alle, Schreiben und Hochladen nur für registrierte Benutzer)';
$lang['i_pol2'] = 'Geschlossenes Wiki (Lesen, Schreiben und Hochladen nur für registrierte Benutzer)';
$lang['i_allowreg'] = 'Benutzer können sich selbst registrieren';
$lang['i_retry'] = 'Wiederholen';
$lang['i_license'] = 'Bitte wähle die Lizenz aus unter der die Wiki-Inhalte veröffentlicht werden sollen:';
$lang['i_license_none'] = 'Keine Lizenzinformationen anzeigen';
$lang['i_pop_field'] = 'Bitte helfe uns, die DokuWiki-Erfahrung zu verbessern';
$lang['i_pop_label'] = 'Sende einmal im Monat anonyme Nutzungsdaten an die DokuWiki Entwickler';
$lang['recent_global'] = 'Im Moment siehst du die Änderungen im Namensraum <b>%s</b>. Du kannst auch <a href="%s">die Änderungen im gesamten Wiki sehen</a>.';
$lang['years'] = 'vor %d Jahren';
$lang['months'] = 'vor %d Monaten';
$lang['weeks'] = 'vor %d Wochen';
$lang['days'] = 'vor %d Tagen';
$lang['hours'] = 'vor %d Stunden';
$lang['minutes'] = 'vor %d Minuten';
$lang['seconds'] = 'vor %d Sekunden';
$lang['wordblock'] = 'Deine Bearbeitung wurde nicht gespeichert, da sie gesperrten Text enthielt (Spam).';
$lang['media_uploadtab'] = 'Hochladen';
$lang['media_searchtab'] = 'Suchen';
$lang['media_file'] = 'Datei';
$lang['media_viewtab'] = 'Anzeigen';
$lang['media_edittab'] = 'Bearbeiten';
$lang['media_historytab'] = 'Verlauf';
$lang['media_list_thumbs'] = 'Medien anzeigen als Miniaturansicht';
$lang['media_list_rows'] = 'Medien anzeigen als Listenansicht';
$lang['media_sort_name'] = 'Sortieren nach Name';
$lang['media_sort_date'] = 'Sortieren nach Datum';
$lang['media_namespaces'] = 'Namensraum wählen';
$lang['media_files'] = 'Medien im Namensraum <strong>%s</strong>.';
$lang['media_upload'] = 'In den <strong>%s</strong> Namensraum hochladen.';
$lang['media_search'] = 'Im Namensraum <strong>%s</strong> suchen.';
$lang['media_view'] = '%s';
$lang['media_viewold'] = '%s in %s';
$lang['media_edit'] = '%s bearbeiten';
$lang['media_history'] = 'Versionen von %s';
$lang['media_meta_edited'] = 'Meta-Informationen bearbeitet';
$lang['media_perm_read'] = 'Du besitzt nicht die notwendigen Berechtigungen um die Datei anzuzeigen.';
$lang['media_perm_upload'] = 'Du besitzt nicht die notwendigen Berechtigungen um Dateien hochzuladen.';
$lang['media_update'] = 'Neue Version hochladen';
$lang['media_restore'] = 'Diese Version wiederherstellen';
$lang['media_acl_warning'] = 'Diese Liste ist möglicherweise nicht vollständig. Versteckte und durch ACL gesperrte Seiten werden nicht angezeigt.';
$lang['email_fail'] = 'PHP-Funktion "mail ()" fehlt oder ist deaktiviert. Die folgende E-Mail wurde nicht gesendet:';
$lang['currentns'] = 'Aktueller Namensraum';
$lang['searchresult'] = 'Suchergebnis';
$lang['plainhtml'] = 'Reines HTML';
$lang['wikimarkup'] = 'Wiki Markup';
$lang['page_nonexist_rev'] = 'Seite existierte nicht an der Stelle %s. Sie wurde an folgende Stelle erstellt: <a href="%s">%s</a>.';
$lang['unable_to_parse_date'] = 'Parameter "%s" kann nicht geparsed werden.';
$lang['email_signature_text'] = 'Diese E-Mail wurde erzeugt vom DokuWiki unter
@DOKUWIKIURL@';
| mprins/dokuwiki | inc/lang/de-informal/lang.php | PHP | gpl-2.0 | 26,205 |
<?php
// Fix for symlinked plugins from
// http://wordpress.stackexchange.com/questions/15202/plugins-in-symlinked-directories
global $wp_flickr_press_file;
$wp_flickr_press_file = __FILE__;
if ( isset( $mu_plugin ) ) {
$wp_flickr_press_file = $mu_plugin;
}
if ( isset( $network_plugin ) ) {
$wp_flickr_press_file = $network_plugin;
}
if ( isset( $plugin ) ) {
$wp_flickr_press_file = $plugin;
}
if ( ! file_exists(dirname($wp_flickr_press_file).'/libs/phpflickr/phpFlickr.php') ) {
$wp_flickr_press_file = __FILE__;
}
require_once(dirname($wp_flickr_press_file).'/libs/phpflickr/phpFlickr.php');
class FlickrPress {
// constants
const VERSION = '1.9.6';
const NAME = 'FlickrPress';
const PREFIX = 'wpfp_';
const MEDIA_BUTTON_TYPE = 'flickr_media';
const TEXT_DOMAIN = 'wp-flickr-press';
private static $flickr;
public static $SIZE_LABELS = array(
'sq' => 'Square',
't' => 'Thumbnail',
's' => 'Small',
'm' => 'Medium',
'z' => 'Medium 640',
'l' => 'Large',
'o' => 'Original',
);
public static $SIZES = array(
'sq' => 'url_sq',
't' => 'url_t',
's' => 'url_s',
'm' => 'url_m',
'z' => 'url_z',
'l' => 'url_l',
'o' => 'url_o',
);
public static $LINK_TYPE_LABELS = array(
'none' => 'None',
'file' => 'File URL',
'page' => 'Page URL',
);
private function __construct() {
}
public static function init() {
self::loadLanguages();
self::addEvents();
self::$flickr = new phpFlickr(FlickrPress::getApiKey(), FlickrPress::getApiSecret());
if (self::getOAuthToken()) {
self::$flickr->token = self::getOAuthToken();
}
if (self::isCacheEnabled()) {
self::$flickr->enableCache(FlickrPress::getCacheType(), FlickrPress::getCacheConnection());
}
}
public static function clearCache() {
$cacheDir = self::getCacheConnection();
if (strlen($cacheDir)==0 || !is_writeable($cacheDir)) {
return;
}
$dir = dir($cacheDir);
while ( ($file=$dir->read()) !== false ) {
if (preg_match('/^.*\.cache$/', $file)) {
unlink("{$cacheDir}{$file}");
}
}
}
public static function isCacheEnabled() {
return true;
}
public static function getClient() {
return self::$flickr;
}
public static function getDir() {
global $wp_flickr_press_file;
return plugin_dir_path($wp_flickr_press_file);
}
public static function getCacheType() {
return 'fs';
}
public static function getCacheConnection() {
global $wp_flickr_press_file;
return plugin_dir_path($wp_flickr_press_file).'/cache/';
}
public static function getApiKey() {
return get_option(self::getKey('api_key'));
}
public static function getApiSecret() {
return get_option(self::getKey('api_secret'));
}
public static function getUserId() {
return get_option(self::getKey('user_id'));
}
public static function enablePathAlias() {
return get_option(self::getKey('enable_path_alias')) == '1';
}
public static function getUsername() {
return get_option(self::getKey('username'));
}
public static function getOAuthToken() {
return get_option(self::getKey('oauth_token'));
}
public static function getPluginUrl() {
global $wp_flickr_press_file;
return plugins_url('', $wp_flickr_press_file );
}
public static function getDefaultTarget() {
return get_option(self::getKey('default_target'), '');
}
public static function getDefaultAlign() {
return get_option(self::getKey('default_align'), 'none');
}
public static function getDefaultSize() {
return get_option(self::getKey('default_size'), 'Medium');
}
public static function getDefaulSearchType() {
return get_option(self::getKey('default_search_type'), 'list');
}
public static function getInsertTemplate() {
return get_option(self::getKey('insert_template'), '[img]');
}
public static function getDefaultSort() {
return get_option(self::getKey('default_sort'), 'date-posted-desc');
}
public static function getQuickSettings() {
return get_option(self::getKey('quick_settings'), 0);
}
public static function getDefaultLink() {
return get_option(self::getKey('default_link'), 'page');
}
public static function getDefaultLinkValue($photo, $photos) {
$linkType = self::getDefaultLink();
$link = '';
switch ($linkType) {
case 'file':
$link = self::getPhotoUrl($photo, self::getDefaultFileURLSize());
break;
case 'page':
$link = self::getPhotoPageUrl($photo, $photos);
break;
}
return $link;
}
public static function getDefaultLinkRel() {
return get_option(self::getKey('default_link_rel'), '');
}
public static function getDefaultLinkClass() {
return get_option(self::getKey('default_link_class'), '');
}
public static function getDefaultFileURLSize() {
return get_option(self::getKey('default_file_url_size'), 'm');
}
public static function getExtendLinkPropertiesJson() {
return get_option(self::getKey('extend_link_properties'), '[]');
}
public static function getExtendLinkPropertiesArray() {
$properties = json_decode( self::getExtendLinkPropertiesJson() );
return is_array($properties) ? $properties : array();
}
public static function getExtendImagePropertiesJson() {
return get_option(self::getKey('extend_image_properties'), '[]');
}
public static function getExtendImagePropertiesArray() {
$properties = json_decode( self::getExtendImagePropertiesJson() );
return is_array($properties) ? $properties : array();
}
public static function getKey($key) {
return self::PREFIX . $key;
}
private static function addEvents() {
// load action or filter
require_once(self::getDir().'/FpPostEvent.php');
add_action('media_buttons_context', array('FpPostEvent', 'addButtons'));
add_action('media_upload_flickr_media', array('FpPostEvent', 'mediaUploadFlickrMedia'));
add_filter('wp_fullscreen_buttons', array('FpPostEvent', 'addButtonsFullScreen'));
add_filter(self::MEDIA_BUTTON_TYPE.'_upload_iframe_src', array('FpPostEvent', 'getUploadIframeSrc'));
add_action('admin_head-post.php', array('FpPostEvent', 'loadScripts'));
add_action('admin_head-post-new.php', array('FpPostEvent', 'loadScripts'));
require_once(self::getDir().'/FpAdminSettingEvent.php');
add_action('admin_menu', array('FpAdminSettingEvent', 'addMenu'));
add_filter('whitelist_options', array('FpAdminSettingEvent', 'addWhitelistOptions'));
// admin actions
add_action('admin_action_wpfp_media_upload', array(__CLASS__, 'adminActionWpfpMediaUpload'));
add_action('admin_action_wpfp_flickr_oauth', array(__CLASS__, 'adminActionWpfpFlickrOauth'));
add_action('admin_action_wpfp_flickr_oauth_callback', array(__CLASS__, 'adminActionWpfpFlickrOauthCallback'));
}
public static function adminActionWpfpMediaUpload() {
require_once(self::getDir().'/media-upload.php');
}
public static function adminActionWpfpFlickrOauth() {
require_once(self::getDir().'/flickr_oauth.php');
}
public static function adminActionWpfpFlickrOauthCallback() {
require_once(self::getDir().'/flickr_oauth_callback.php');
}
public static function getPhotoUrl($photo, $size='m') {
if ( $size != 'o' && empty( $photo[self::$SIZES[$size]] ) ) {
$keys = array_keys(self::$SIZES);
$idx = array_search($size, $keys);
for ($i=$idx+1; $i<count($keys); $i++) {
$s = $keys[$i];
if(!empty($photo[self::$SIZES[$s]])) {
return self::getPhotoUrl($photo, $s);
}
}
return '';
} else {
return $photo[self::$SIZES[$size]];
}
}
public static function getPhotoPageUrl($photo, $photos) {
$id = $photo['id'];
$pathKey = self::enablePathAlias() ? 'pathalias' : 'owner';
$owner = isset($photo[$pathKey]) ? $photo[$pathKey] : false;
if (!$owner && isset($photos[$pathKey])) {
$owner = $photos[$pathKey];
}
$url = "http://www.flickr.com/photos/$owner/$id";
return $url;
}
public static function loadLanguages() {
load_plugin_textdomain(self::TEXT_DOMAIN, false, 'wp-flickr-press/languages');
}
}
?>
| ulearn/spanishblogwp | wp-content/plugins/wp-flickr-press/FlickrPress.php | PHP | gpl-2.0 | 7,882 |
/**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2014 Mark Samman <mark.samman@gmail.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.
*/
#include "otpch.h"
#include "configmanager.h"
#include "databasemanager.h"
#include "enums.h"
#include "luascript.h"
#include "tools.h"
extern ConfigManager g_config;
bool DatabaseManager::optimizeTables()
{
Database* db = Database::getInstance();
std::ostringstream query;
query << "SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = " << db->escapeString(g_config.getString(ConfigManager::MYSQL_DB)) << " AND `DATA_FREE` > 0";
DBResult* result = db->storeQuery(query.str());
if (!result) {
return false;
}
do {
std::string tableName = result->getDataString("TABLE_NAME");
std::cout << "> Optimizing table " << tableName << "..." << std::flush;
query.str("");
query << "OPTIMIZE TABLE `" << tableName << '`';
if (db->executeQuery(query.str())) {
std::cout << " [success]" << std::endl;
} else {
std::cout << " [failed]" << std::endl;
}
} while (result->next());
db->freeResult(result);
return true;
}
bool DatabaseManager::tableExists(const std::string& tableName)
{
Database* db = Database::getInstance();
std::ostringstream query;
query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db->escapeString(g_config.getString(ConfigManager::MYSQL_DB)) << " AND `TABLE_NAME` = " << db->escapeString(tableName);
DBResult* result = db->storeQuery(query.str());
if (!result) {
return false;
}
db->freeResult(result);
return true;
}
bool DatabaseManager::isDatabaseSetup()
{
Database* db = Database::getInstance();
std::ostringstream query;
query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db->escapeString(g_config.getString(ConfigManager::MYSQL_DB));
DBResult* result = db->storeQuery(query.str());
if (!result) {
return false;
}
db->freeResult(result);
return true;
}
int32_t DatabaseManager::getDatabaseVersion()
{
if (!tableExists("server_config")) {
Database* db = Database::getInstance();
db->executeQuery("CREATE TABLE `server_config` (`config` VARCHAR(50) NOT nullptr, `value` VARCHAR(256) NOT nullptr DEFAULT '', UNIQUE(`config`)) ENGINE = InnoDB");
db->executeQuery("INSERT INTO `server_config` VALUES ('db_version', 0)");
return 0;
}
int32_t version = 0;
if (getDatabaseConfig("db_version", version)) {
return version;
}
return -1;
}
void DatabaseManager::updateDatabase()
{
lua_State* L = luaL_newstate();
if (!L) {
return;
}
luaL_openlibs(L);
#ifndef LUAJIT_VERSION
//bit operations for Lua, based on bitlib project release 24
//bit.bnot, bit.band, bit.bor, bit.bxor, bit.lshift, bit.rshift
luaL_register(L, "bit", LuaScriptInterface::luaBitReg);
#endif
//db table
luaL_register(L, "db", LuaScriptInterface::luaDatabaseTable);
//result table
luaL_register(L, "result", LuaScriptInterface::luaResultTable);
int32_t version = getDatabaseVersion();
do {
std::ostringstream ss;
ss << "data/migrations/" << version << ".lua";
if (luaL_dofile(L, ss.str().c_str()) != 0) {
std::cout << "[Error - DatabaseManager::updateDatabase - Version: " << version << "] " << lua_tostring(L, -1) << std::endl;
break;
}
if (!LuaScriptInterface::reserveScriptEnv()) {
break;
}
lua_getglobal(L, "onUpdateDatabase");
if (lua_pcall(L, 0, 1, 0) != 0) {
LuaScriptInterface::resetScriptEnv();
std::cout << "[Error - DatabaseManager::updateDatabase - Version: " << version << "] " << lua_tostring(L, -1) << std::endl;
break;
}
if (!LuaScriptInterface::popBoolean(L)) {
LuaScriptInterface::resetScriptEnv();
break;
}
version++;
std::cout << "> Database has been updated to version " << version << '.' << std::endl;
registerDatabaseConfig("db_version", version);
LuaScriptInterface::resetScriptEnv();
} while (true);
lua_close(L);
}
bool DatabaseManager::getDatabaseConfig(const std::string& config, int32_t& value)
{
Database* db = Database::getInstance();
std::ostringstream query;
query << "SELECT `value` FROM `server_config` WHERE `config` = " << db->escapeString(config);
DBResult* result = db->storeQuery(query.str());
if (!result) {
return false;
}
value = result->getDataInt("value");
db->freeResult(result);
return true;
}
void DatabaseManager::registerDatabaseConfig(const std::string& config, int32_t value)
{
Database* db = Database::getInstance();
std::ostringstream query;
int32_t tmp;
if (!getDatabaseConfig(config, tmp)) {
query << "INSERT INTO `server_config` VALUES (" << db->escapeString(config) << ", '" << value << "')";
} else {
query << "UPDATE `server_config` SET `value` = '" << value << "' WHERE `config` = " << db->escapeString(config);
}
db->executeQuery(query.str());
}
| viciv/clansxsrc | src/databasemanager.cpp | C++ | gpl-2.0 | 5,541 |
<?php
/**
* @version SEBLOD 3.x Core ~ $Id: format.php sebastienheraud $
* @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder)
* @url https://www.seblod.com
* @editor Octopoos - www.octopoos.com
* @copyright Copyright (C) 2009 - 2018 SEBLOD. All Rights Reserved.
* @license GNU General Public License version 2 or later; see _LICENSE.php
**/
defined( '_JEXEC' ) or die;
// JCckCryptFormat
abstract class JCckCryptFormat
{
// decode
public static function decrypt( $data )
{
}
// encode
public static function encrypt( $data )
{
}
}
?> | Octopoos/SEBLOD | libraries/cms/cck/dev/crypt/format.php | PHP | gpl-2.0 | 599 |
<?php
// $Id: node.tpl.php,v 1.5 2007/10/11 09:51:29 goba Exp $
?>
<div id="node-<?php print $node->nid; ?>" class="node<?php if ($sticky) { print ' sticky'; } ?><?php if (!$status) { print ' node-unpublished'; } ?>">
</div>
| skotin/EW | themes/basic/node-persona.tpl.php | PHP | gpl-2.0 | 227 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.notification;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.opennms.core.resource.Vault;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.opennms.core.utils.DBUtils;
public class NotificationModel extends Object {
private static final Logger LOG = LoggerFactory.getLogger(NotificationModel.class);
private static final String USERID = "userID";
private static final String NOTICE_TIME = "notifytime";
private static final String TXT_MESG = "textMsg";
private static final String NUM_MESG = "numericMsg";
private static final String NOTIFY = "notifyID";
private static final String TIME = "pageTime";
private static final String REPLYTIME = "respondTime";
private static final String ANS_BY = "answeredBy";
private static final String CONTACT = "contactInfo";
private static final String NODE = "nodeID";
private static final String INTERFACE = "interfaceID";
private static final String SERVICE = "serviceID";
private static final String MEDIA = "media";
private static final String EVENTID = "eventid";
private static final String SELECT = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid from NOTIFICATIONS";
private static final String NOTICE_ID = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid from NOTIFICATIONS where NOTIFYID = ?";
private static final String SENT_TO = "SELECT userid, notifytime, media, contactinfo FROM usersnotified WHERE notifyid=?";
private static final String INSERT_NOTIFY = "INSERT INTO NOTIFICATIONS (notifyid, textmsg, numericmsg, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid) VALUES (NEXTVAL('notifyNxtId'), ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String OUTSTANDING = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid FROM NOTIFICATIONS WHERE respondTime is NULL";
private static final String OUTSTANDING_COUNT = "SELECT COUNT(notifyid) AS TOTAL FROM NOTIFICATIONS WHERE respondTime is NULL";
private static final String USER_OUTSTANDING = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid FROM NOTIFICATIONS WHERE (respondTime is NULL) AND notifications.notifyid in (SELECT DISTINCT usersnotified.notifyid FROM usersnotified WHERE usersnotified.userid=?)";
private static final String USER_OUTSTANDING_COUNT = "SELECT COUNT(notifyid) AS TOTAL FROM NOTIFICATIONS WHERE (respondTime is NULL) AND notifications.notifyid in (SELECT DISTINCT usersnotified.notifyid FROM usersnotified WHERE usersnotified.userid=?)";
/**
* <p>getNoticeInfo</p>
*
* @param id a int.
* @return a {@link org.opennms.web.notification.Notification} object.
* @throws java.sql.SQLException if any.
*/
public Notification getNoticeInfo(int id) throws SQLException {
Notification nbean = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
final Connection conn = Vault.getDbConnection();
final DBUtils d = new DBUtils(getClass(), conn);
try {
pstmt = conn.prepareStatement(NOTICE_ID);
d.watch(pstmt);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
d.watch(rs);
Notification[] n = rs2NotifyBean(conn, rs);
if (n.length > 0) {
nbean = n[0];
} else {
nbean = new Notification();
}
rs.close();
pstmt.close();
// create the list of users the page was sent to
final PreparedStatement sentTo = conn.prepareStatement(SENT_TO);
d.watch(sentTo);
sentTo.setInt(1, id);
final ResultSet sentToResults = sentTo.executeQuery();
d.watch(sentToResults);
final List<NoticeSentTo> sentToList = new ArrayList<NoticeSentTo>();
while (sentToResults.next()) {
NoticeSentTo newSentTo = new NoticeSentTo();
newSentTo.setUserId(sentToResults.getString(USERID));
Timestamp ts = sentToResults.getTimestamp(NOTICE_TIME);
if (ts != null) {
newSentTo.setTime(ts.getTime());
} else {
newSentTo.setTime(0);
}
newSentTo.setMedia(sentToResults.getString(MEDIA));
newSentTo.setContactInfo(sentToResults.getString(CONTACT));
sentToList.add(newSentTo);
}
nbean.m_sentTo = sentToList;
} catch (SQLException e) {
LOG.error("Problem getting data from the notifications table: {}", e, e);
throw e;
} finally {
d.cleanUp();
}
return nbean;
}
/**
* <p>allNotifications</p>
*
* @return an array of {@link org.opennms.web.notification.Notification} objects.
* @throws java.sql.SQLException if any.
*/
public Notification[] allNotifications() throws SQLException {
return this.allNotifications(null);
}
/**
* Return all notifications, both outstanding and acknowledged.
*
* @param order a {@link java.lang.String} object.
* @return an array of {@link org.opennms.web.notification.Notification} objects.
* @throws java.sql.SQLException if any.
*/
public Notification[] allNotifications(String order) throws SQLException {
Notification[] notices = null;
final Connection conn = Vault.getDbConnection();
final DBUtils d = new DBUtils(getClass(), conn);
try {
final Statement stmt = conn.createStatement();
d.watch(stmt);
// oh man this is lame, but it'll be a DAO soon right? right? :P
String query = SELECT;
if (order != null) {
if (order.equalsIgnoreCase("asc")) {
query += " ORDER BY pagetime ASC";
} else if (order.equalsIgnoreCase("desc")) {
query += " ORDER BY pagetime DESC";
}
}
query += ";";
final ResultSet rs = stmt.executeQuery(query);
d.watch(rs);
notices = rs2NotifyBean(conn, rs);
} catch (SQLException e) {
LOG.error("allNotifications: Problem getting data from the notifications table: {}", e, e);
throw e;
} finally {
d.cleanUp();
}
return (notices);
}
private String getServiceName(Connection conn, Integer id) {
if (id == null) {
return null;
}
String serviceName = null;
PreparedStatement ps = null;
ResultSet rs = null;
final DBUtils d = new DBUtils(getClass());
try {
ps = conn.prepareStatement("SELECT servicename from service where serviceid = ?");
d.watch(ps);
ps.setInt(1, id);
rs = ps.executeQuery();
d.watch(rs);
if (rs.next()) {
serviceName = rs.getString("servicename");
}
} catch (SQLException e) {
LOG.warn("unable to get service name for service ID '{}'", id, e);
} finally {
d.cleanUp();
}
return serviceName;
}
/**
* Returns the data from the result set as an array of
* Notification objects. The ResultSet must be positioned before
* the first result before calling this method (this is the case right
* after calling java.sql.Connection#createStatement and friends or
* after calling java.sql.ResultSet#beforeFirst).
*
* @param conn a {@link java.sql.Connection} object.
* @param rs a {@link java.sql.ResultSet} object.
* @return an array of {@link org.opennms.web.notification.Notification} objects.
* @throws java.sql.SQLException if any.
*/
protected Notification[] rs2NotifyBean(Connection conn, ResultSet rs) throws SQLException {
Notification[] notices = null;
Vector<Notification> vector = new Vector<Notification>();
try {
while (rs.next()) {
Notification nbean = new Notification();
nbean.m_timeReply = 0;
nbean.m_txtMsg = rs.getString(TXT_MESG);
nbean.m_numMsg = rs.getString(NUM_MESG);
nbean.m_notifyID = rs.getInt(NOTIFY);
if (rs.getTimestamp(TIME) != null) {
nbean.m_timeSent = rs.getTimestamp(TIME).getTime();
}
if (rs.getTimestamp(REPLYTIME) != null) {
nbean.m_timeReply = rs.getTimestamp(REPLYTIME).getTime();
}
nbean.m_responder = rs.getString(ANS_BY);
nbean.m_nodeID = rs.getInt(NODE);
nbean.m_interfaceID = rs.getString(INTERFACE);
nbean.m_serviceId = rs.getInt(SERVICE);
nbean.m_eventId = rs.getInt(EVENTID);
nbean.m_serviceName = getServiceName(conn, nbean.m_serviceId);
vector.addElement(nbean);
}
} catch (SQLException e) {
LOG.error("Error occurred in rs2NotifyBean: {}", e, e);
throw e;
}
notices = new Notification[vector.size()];
for (int i = 0; i < notices.length; i++) {
notices[i] = vector.elementAt(i);
}
return notices;
}
/**
* This method returns the count of all outstanding notices.
*
* @return an array of {@link org.opennms.web.notification.Notification} objects.
* @throws java.sql.SQLException if any.
*/
public Notification[] getOutstandingNotices() throws SQLException {
Notification[] notices = null;
final Connection conn = Vault.getDbConnection();
final DBUtils d = new DBUtils(getClass(), conn);
try {
final Statement stmt = conn.createStatement();
d.watch(stmt);
final ResultSet rs = stmt.executeQuery(OUTSTANDING);
d.watch(rs);
notices = rs2NotifyBean(conn, rs);
} catch (SQLException e) {
LOG.error("Problem getting data from the notifications table: {}", e, e);
throw e;
} finally {
d.cleanUp();
}
return notices;
}
/**
* This method returns notices not yet acknowledged.
*
* @return a int.
* @throws java.sql.SQLException if any.
*/
public int getOutstandingNoticeCount() throws SQLException {
int count = 0;
final Connection conn = Vault.getDbConnection();
final DBUtils d = new DBUtils(getClass(), conn);
try {
final Statement stmt = conn.createStatement();
d.watch(stmt);
final ResultSet rs = stmt.executeQuery(OUTSTANDING_COUNT);
d.watch(rs);
if (rs.next()) {
count = rs.getInt("TOTAL");
}
} catch (SQLException e) {
LOG.error("Problem getting data from the notifications table: {}", e, e);
throw e;
} finally {
d.cleanUp();
}
return count;
}
/**
* This method returns notices not yet acknowledged.
*
* @param username a {@link java.lang.String} object.
* @return a int.
* @throws java.sql.SQLException if any.
*/
public int getOutstandingNoticeCount(String username) throws SQLException {
if (username == null) {
throw new IllegalArgumentException("Cannot take null parameters.");
}
int count = 0;
final Connection conn = Vault.getDbConnection();
final DBUtils d = new DBUtils(getClass(), conn);
try {
final PreparedStatement pstmt = conn.prepareStatement(USER_OUTSTANDING_COUNT);
d.watch(pstmt);
pstmt.setString(1, username);
final ResultSet rs = pstmt.executeQuery();
d.watch(rs);
if (rs.next()) {
count = rs.getInt("TOTAL");
}
} catch (SQLException e) {
LOG.error("Problem getting data from the notifications table: {}", e, e);
throw e;
} finally {
d.cleanUp();
}
return (count);
}
/**
* This method returns notices not yet acknowledged.
*
* @param name a {@link java.lang.String} object.
* @return an array of {@link org.opennms.web.notification.Notification} objects.
* @throws java.sql.SQLException if any.
*/
public Notification[] getOutstandingNotices(String name) throws SQLException {
Notification[] notices = null;
final Connection conn = Vault.getDbConnection();
final DBUtils d = new DBUtils(getClass(), conn);
try {
final PreparedStatement pstmt = conn.prepareStatement(USER_OUTSTANDING);
d.watch(pstmt);
pstmt.setString(1, name);
final ResultSet rs = pstmt.executeQuery();
d.watch(rs);
notices = rs2NotifyBean(conn, rs);
} catch (SQLException e) {
LOG.error("Problem getting data from the notifications table: {}", e, e);
throw e;
} finally {
d.cleanUp();
}
return (notices);
}
/**
* This method updates the table when the user acknowledges the pager
* information.
*
* @param name a {@link java.lang.String} object.
* @param noticeId a int.
* @throws java.sql.SQLException if any.
*/
public void acknowledged(String name, int noticeId) throws SQLException {
if (name == null) {
throw new IllegalArgumentException("Cannot take null parameters.");
}
final Connection conn = Vault.getDbConnection();
final DBUtils d = new DBUtils(getClass(), conn);
try {
final PreparedStatement pstmt = conn.prepareStatement("UPDATE notifications SET respondtime = ? , answeredby = ? WHERE notifyid= ?");
d.watch(pstmt);
pstmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pstmt.setString(2, name);
pstmt.setInt(3, noticeId);
pstmt.execute();
} catch (SQLException e) {
LOG.error("Problem acknowledging notification {} as answered by '{}': {}", noticeId, name, e, e);
throw e;
} finally {
d.cleanUp();
}
}
/**
* This method helps insert into the database.
*
* @param nbean a {@link org.opennms.web.notification.Notification} object.
* @throws java.sql.SQLException if any.
*/
public void insert(Notification nbean) throws SQLException {
if (nbean == null || nbean.m_txtMsg == null) {
throw new IllegalArgumentException("Cannot take null parameters.");
}
final Connection conn = Vault.getDbConnection();
final DBUtils d = new DBUtils(getClass(), conn);
try {
final PreparedStatement pstmt = conn.prepareStatement(INSERT_NOTIFY);
d.watch(pstmt);
pstmt.setString(1, nbean.m_txtMsg);
pstmt.setString(2, nbean.m_numMsg);
pstmt.setLong(3, nbean.m_timeSent);
pstmt.setLong(4, nbean.m_timeReply);
pstmt.setString(5, nbean.m_responder);
pstmt.setInt(6, nbean.m_nodeID);
pstmt.setString(7, nbean.m_interfaceID);
pstmt.setInt(8, nbean.m_serviceId);
pstmt.setInt(9, nbean.m_eventId);
pstmt.execute();
} catch (SQLException e) {
LOG.error("Problem getting data from the notifications table: {}", e, e);
throw e;
} finally {
d.cleanUp();
}
}
}
| rfdrake/opennms | opennms-webapp/src/main/java/org/opennms/web/notification/NotificationModel.java | Java | gpl-2.0 | 17,508 |
/*
* Copyright 2017 OICR
*
* 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 io.logstash.appender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.Appender;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.AbstractAppenderFactory;
import io.dropwizard.logging.async.AsyncAppenderFactory;
import io.dropwizard.logging.filter.LevelFilterFactory;
import io.dropwizard.logging.layout.LayoutFactory;
import java.net.InetSocketAddress;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import net.logstash.logback.appender.LogstashTcpSocketAppender;
import net.logstash.logback.encoder.LogstashEncoder;
/**
* Custom log appender that pushes the logs to logstash.
* Specify the host and optional port in the application configuration file.
*/
@JsonTypeName("logstash")
public class LogstashAppenderFactory extends AbstractAppenderFactory {
private static final int MAX_PORT = 65535;
private static final int MIN_PORT = 1;
@NotNull
protected String host;
@Min(MIN_PORT)
@Max(MAX_PORT)
protected int port;
@Min(MIN_PORT)
@Max(MAX_PORT)
public LogstashAppenderFactory() {
this.port = LogstashTcpSocketAppender.DEFAULT_PORT;
}
@JsonProperty
public String getHost() {
return host;
}
@JsonProperty
public void setHost(String host) {
this.host = host;
}
@JsonProperty
public int getPort() {
return port;
}
@JsonProperty
public void setPort(int port) {
this.port = port;
}
@Override
public Appender build(LoggerContext context, String s, LayoutFactory layoutFactory, LevelFilterFactory levelFilterFactory,
AsyncAppenderFactory asyncAppenderFactory) {
final LogstashTcpSocketAppender appender = new LogstashTcpSocketAppender();
final LogstashEncoder encoder = new LogstashEncoder();
encoder.setIncludeContext(true);
// Mapped Diagnostic Context
encoder.setIncludeMdc(true);
encoder.setIncludeCallerData(false);
appender.setContext(context);
appender.addDestinations(new InetSocketAddress(host, port));
appender.setIncludeCallerData(false);
appender.setQueueSize(LogstashTcpSocketAppender.DEFAULT_QUEUE_SIZE);
appender.addFilter(levelFilterFactory.build(Level.ALL));
appender.setEncoder(encoder);
encoder.start();
appender.start();
return wrapAsync(appender, asyncAppenderFactory);
}
}
| CancerCollaboratory/dockstore | dockstore-webservice/src/main/java/io/logstash/appender/LogstashAppenderFactory.java | Java | gpl-2.0 | 3,238 |
#
# Licensed under the GNU General Public License Version 3
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright 2013 Aron Parsons <aronparsons@gmail.com>
# Copyright (c) 2011--2015 Red Hat, Inc.
#
# NOTE: the 'self' variable is an instance of SpacewalkShell
# wildcard import
# pylint: disable=W0401,W0614
# unused argument
# pylint: disable=W0613
# invalid function name
# pylint: disable=C0103
import logging
import readline
import shlex
from getpass import getpass
from ConfigParser import NoOptionError
from spacecmd.utils import *
from time import sleep
import xmlrpclib
# list of system selection options for the help output
HELP_SYSTEM_OPTS = '''<SYSTEMS> can be any of the following:
name
ssm (see 'help ssm')
search:QUERY (see 'help system_search')
group:GROUP
channel:CHANNEL
'''
HELP_TIME_OPTS = '''Dates can be any of the following:
Explicit Dates:
Dates can be expressed as explicit date strings in the YYYYMMDD[HHMM]
format. The year, month and day are required, while the hours and
minutes are not; the hours and minutes will default to 0000 if no
values are provided.
Deltas:
Dates can be expressed as delta values. For example, '2h' would
mean 2 hours in the future. You can also use negative values to
express times in the past (e.g., -7d would be one week ago).
Units:
s -> seconds
m -> minutes
h -> hours
d -> days
'''
####################
# life of caches in seconds
SYSTEM_CACHE_TTL = 3600
PACKAGE_CACHE_TTL = 86400
ERRATA_CACHE_TTL = 86400
MINIMUM_API_VERSION = 10.8
SEPARATOR = '\n' + '#' * 30 + '\n'
####################
ENTITLEMENTS = ['enterprise_entitled',
'virtualization_host'
]
SYSTEM_SEARCH_FIELDS = ['id', 'name', 'ip', 'hostname',
'device', 'vendor', 'driver', 'uuid']
####################
def help_systems(self):
print HELP_SYSTEM_OPTS
def help_time(self):
print HELP_TIME_OPTS
####################
def help_clear(self):
print 'clear: clear the screen'
print 'usage: clear'
def do_clear(self, args):
os.system('clear')
####################
def help_clear_caches(self):
print 'clear_caches: Clear the internal caches kept for systems' + \
' and packages'
print 'usage: clear_caches'
def do_clear_caches(self, args):
self.clear_system_cache()
self.clear_package_cache()
self.clear_errata_cache()
####################
def help_get_apiversion(self):
print 'get_apiversion: Display the API version of the server'
print 'usage: get_apiversion'
def do_get_apiversion(self, args):
print self.client.api.getVersion()
####################
def help_get_serverversion(self):
print 'get_serverversion: Display the version of the server'
print 'usage: get_serverversion'
def do_get_serverversion(self, args):
print self.client.api.systemVersion()
####################
def help_get_certificateexpiration(self):
print 'get_certificateexpiration: Print the expiration date of the'
print " server's entitlement certificate"
print 'usage: get_certificateexpiration'
def do_get_certificateexpiration(self, args):
date = self.client.satellite.getCertificateExpirationDate(self.session)
print date
####################
def help_list_proxies(self):
print 'list_proxies: List the proxies wihtin the user\'s organization '
print 'usage: list_proxies'
def do_list_proxies(self, args):
proxies = self.client.satellite.listProxies(self.session)
print proxies
####################
def help_get_session(self):
print 'get_session: Show the current session string'
print 'usage: get_session'
def do_get_session(self, args):
if self.session:
print self.session
else:
logging.error('No session found')
####################
def help_help(self):
print 'help: Show help for the given command'
print 'usage: help COMMAND'
####################
def help_history(self):
print 'history: List your command history'
print 'usage: history'
def do_history(self, args):
for i in range(1, readline.get_current_history_length()):
print '%s %s' % (str(i).rjust(4), readline.get_history_item(i))
####################
def help_toggle_confirmations(self):
print 'toggle_confirmations: Toggle confirmation messages on/off'
print 'usage: toggle_confirmations'
def do_toggle_confirmations(self, args):
if self.options.yes:
self.options.yes = False
print 'Confirmation messages are enabled'
else:
self.options.yes = True
logging.warning('Confirmation messages are DISABLED!')
####################
def help_login(self):
print 'login: Connect to a Spacewalk server'
print 'usage: login [USERNAME] [SERVER]'
def do_login(self, args):
(args, _options) = parse_arguments(args)
# logout before logging in again
if len(self.session):
logging.warning('You are already logged in')
return True
# an argument passed to the function get precedence
if len(args) == 2:
server = args[1]
else:
# use the server we were already using
server = self.config['server']
# bail out if not server was given
if not server:
logging.warning('No server specified')
return False
# load the server-specific configuration
self.load_config_section(server)
# an argument passed to the function get precedence
if len(args):
username = args[0]
elif self.config.has_key('username'):
# use the username from before
username = self.config['username']
elif self.options.username:
# use the username from before
username = self.options.username
else:
username = ''
# set the protocol
if self.config.has_key('nossl') and self.config['nossl']:
proto = 'http'
else:
proto = 'https'
server_url = '%s://%s/rpc/api' % (proto, server)
# this will enable spewing out all client/server traffic
verbose_xmlrpc = False
if self.options.debug > 1:
verbose_xmlrpc = True
# connect to the server
logging.debug('Connecting to %s', server_url)
self.client = xmlrpclib.Server(server_url, verbose=verbose_xmlrpc)
# check the API to verify connectivity
try:
self.api_version = self.client.api.getVersion()
logging.debug('Server API Version = %s', self.api_version)
except xmlrpclib.Fault, e:
if self.options.debug > 0:
logging.exception(e)
logging.error('Failed to connect to %s', server_url)
self.client = None
return False
# ensure the server is recent enough
if self.api_version < self.MINIMUM_API_VERSION:
logging.error('API (%s) is too old (>= %s required)',
self.api_version, self.MINIMUM_API_VERSION)
self.client = None
return False
# store the session file in the server's own directory
session_file = os.path.join(self.conf_dir, server, 'session')
# retrieve a cached session
if os.path.isfile(session_file) and not self.options.password:
try:
sessionfile = open(session_file, 'r')
# read the session (format = username:session)
for line in sessionfile:
parts = line.split(':')
# if a username was passed, make sure it matches
if len(username):
if parts[0] == username:
self.session = parts[1]
else:
# get the username from the cache if one
# wasn't passed by the user
username = parts[0]
self.session = parts[1]
sessionfile.close()
except IOError:
logging.error('Could not read %s', session_file)
# check the cached credentials by doing an API call
if self.session:
try:
logging.debug('Using cached credentials from %s', session_file)
self.client.user.listAssignableRoles(self.session)
except xmlrpclib.Fault:
logging.warning('Cached credentials are invalid')
self.current_user = ''
self.session = ''
# attempt to login if we don't have a valid session yet
if not len(self.session):
if len(username):
logging.info('Spacewalk Username: %s', username)
else:
username = prompt_user('Spacewalk Username:', noblank=True)
if self.options.password:
password = self.options.password
# remove this from the options so that if 'login' is called
# again, the user is prompted for the information
self.options.password = None
elif self.config.has_key('password'):
password = self.config['password']
else:
password = getpass('Spacewalk Password: ')
# login to the server
try:
self.session = self.client.auth.login(username, password)
# don't keep the password around
password = None
except xmlrpclib.Fault:
logging.error('Invalid credentials')
return False
try:
# make sure ~/.spacecmd/<server> exists
conf_dir = os.path.join(self.conf_dir, server)
if not os.path.isdir(conf_dir):
os.mkdir(conf_dir, 0700)
# add the new cache to the file
line = '%s:%s\n' % (username, self.session)
# write the new cache file out
sessionfile = open(session_file, 'w')
sessionfile.write(line)
sessionfile.close()
except IOError:
logging.error('Could not write session file')
# load the system/package/errata caches
self.load_caches(server)
# keep track of who we are and who we're connected to
self.current_user = username
self.server = server
logging.info('Connected to %s as %s', server_url, username)
return True
####################
def help_logout(self):
print 'logout: Disconnect from the server'
print 'usage: logout'
def do_logout(self, args):
if self.session:
self.client.auth.logout(self.session)
self.session = ''
self.current_user = ''
self.server = ''
self.do_clear_caches('')
####################
def help_whoami(self):
print 'whoami: Print the name of the currently logged in user'
print 'usage: whoami'
def do_whoami(self, args):
if len(self.current_user):
print self.current_user
else:
logging.warning("You are not logged in")
####################
def help_whoamitalkingto(self):
print 'whoamitalkingto: Print the name of the server'
print 'usage: whoamitalkingto'
def do_whoamitalkingto(self, args):
if len(self.server):
print self.server
else:
logging.warning('Yourself')
####################
def tab_complete_errata(self, text):
options = self.do_errata_list('', True)
options.append('search:')
return tab_completer(options, text)
def tab_complete_systems(self, text):
if re.match('group:', text):
# prepend 'group' to each item for tab completion
groups = ['group:%s' % g for g in self.do_group_list('', True)]
return tab_completer(groups, text)
elif re.match('channel:', text):
# prepend 'channel' to each item for tab completion
channels = ['channel:%s' % s
for s in self.do_softwarechannel_list('', True)]
return tab_completer(channels, text)
elif re.match('search:', text):
# prepend 'search' to each item for tab completion
fields = ['search:%s:' % f for f in self.SYSTEM_SEARCH_FIELDS]
return tab_completer(fields, text)
else:
options = self.get_system_names()
# add our special search options
options.extend(['group:', 'channel:', 'search:'])
return tab_completer(options, text)
def remove_last_history_item(self):
last = readline.get_current_history_length() - 1
if last >= 0:
readline.remove_history_item(last)
def clear_errata_cache(self):
self.all_errata = {}
self.errata_cache_expire = datetime.now()
self.save_errata_cache()
def get_errata_names(self):
return sorted([e.get('advisory_name') for e in self.all_errata])
def get_erratum_id(self, name):
if name in self.all_errata:
return self.all_errata[name]['id']
def get_erratum_name(self, erratum_id):
for erratum in self.all_errata:
if self.all_errata[erratum]['id'] == erratum_id:
return erratum
def generate_errata_cache(self, force=False):
if not force and datetime.now() < self.errata_cache_expire:
return
if not self.options.quiet:
# tell the user what's going on
self.replace_line_buffer('** Generating errata cache **')
channels = self.client.channel.listSoftwareChannels(self.session)
channels = [c.get('label') for c in channels]
for c in channels:
try:
errata = \
self.client.channel.software.listErrata(self.session, c)
except xmlrpclib.Fault:
logging.debug('No access to %s', c)
continue
for erratum in errata:
if erratum.get('advisory_name') not in self.all_errata:
self.all_errata[erratum.get('advisory_name')] = \
{'id': erratum.get('id'),
'advisory_name': erratum.get('advisory_name'),
'advisory_type': erratum.get('advisory_type'),
'date': erratum.get('date'),
'advisory_synopsis': erratum.get('advisory_synopsis')}
self.errata_cache_expire = \
datetime.now() + timedelta(self.ERRATA_CACHE_TTL)
self.save_errata_cache()
if not self.options.quiet:
# restore the original line buffer
self.replace_line_buffer()
def save_errata_cache(self):
save_cache(self.errata_cache_file,
self.all_errata,
self.errata_cache_expire)
def clear_package_cache(self):
self.all_packages_short = {}
self.all_packages = {}
self.all_packages_by_id = {}
self.package_cache_expire = datetime.now()
self.save_package_caches()
def generate_package_cache(self, force=False):
if not force and datetime.now() < self.package_cache_expire:
return
if not self.options.quiet:
# tell the user what's going on
self.replace_line_buffer('** Generating package cache **')
channels = self.client.channel.listSoftwareChannels(self.session)
channels = [c.get('label') for c in channels]
for c in channels:
try:
packages = \
self.client.channel.software.listAllPackages(self.session, c)
except xmlrpclib.Fault:
logging.debug('No access to %s', c)
continue
for p in packages:
if not p.get('name') in self.all_packages_short:
self.all_packages_short[p.get('name')] = ''
longname = build_package_names(p)
if not longname in self.all_packages:
self.all_packages[longname] = [p.get('id')]
else:
self.all_packages[longname].append(p.get('id'))
# keep a reverse dictionary so we can lookup package names by ID
self.all_packages_by_id = {}
for (k, v) in self.all_packages.iteritems():
for i in v:
self.all_packages_by_id[i] = k
self.package_cache_expire = \
datetime.now() + timedelta(seconds=self.PACKAGE_CACHE_TTL)
self.save_package_caches()
if not self.options.quiet:
# restore the original line buffer
self.replace_line_buffer()
def save_package_caches(self):
# store the cache to disk to speed things up
save_cache(self.packages_short_cache_file,
self.all_packages_short,
self.package_cache_expire)
save_cache(self.packages_long_cache_file,
self.all_packages,
self.package_cache_expire)
save_cache(self.packages_by_id_cache_file,
self.all_packages_by_id,
self.package_cache_expire)
# create a global list of all available package names
def get_package_names(self, longnames=False):
self.generate_package_cache()
if longnames:
return self.all_packages.keys()
else:
return self.all_packages_short
def get_package_id(self, name):
self.generate_package_cache()
try:
return set(self.all_packages[name])
except KeyError:
return
def get_package_name(self, package_id):
self.generate_package_cache()
try:
return self.all_packages_by_id[package_id]
except KeyError:
return
def clear_system_cache(self):
self.all_systems = {}
self.system_cache_expire = datetime.now()
self.save_system_cache()
def generate_system_cache(self, force=False, delay=0):
if not force and datetime.now() < self.system_cache_expire:
return
if not self.options.quiet:
# tell the user what's going on
self.replace_line_buffer('** Generating system cache **')
# we might need to wait for some systems to delete
if delay:
sleep(delay)
systems = self.client.system.listSystems(self.session)
self.all_systems = {}
for s in systems:
self.all_systems[s.get('id')] = s.get('name')
self.system_cache_expire = \
datetime.now() + timedelta(seconds=self.SYSTEM_CACHE_TTL)
self.save_system_cache()
if not self.options.quiet:
# restore the original line buffer
self.replace_line_buffer()
def save_system_cache(self):
save_cache(self.system_cache_file,
self.all_systems,
self.system_cache_expire)
def load_caches(self, server):
conf_dir = os.path.join(self.conf_dir, server)
try:
if not os.path.isdir(conf_dir):
os.mkdir(conf_dir, 0700)
except OSError:
logging.error('Could not create directory %s', conf_dir)
return
self.ssm_cache_file = os.path.join(conf_dir, 'ssm')
self.system_cache_file = os.path.join(conf_dir, 'systems')
self.errata_cache_file = os.path.join(conf_dir, 'errata')
self.packages_long_cache_file = os.path.join(conf_dir, 'packages_long')
self.packages_by_id_cache_file = \
os.path.join(conf_dir, 'packages_by_id')
self.packages_short_cache_file = \
os.path.join(conf_dir, 'packages_short')
# load self.ssm from disk
(self.ssm, _ignore) = load_cache(self.ssm_cache_file)
# update the prompt now that we loaded the SSM
self.postcmd(False, '')
# load self.all_systems from disk
(self.all_systems, self.system_cache_expire) = \
load_cache(self.system_cache_file)
# load self.all_errata from disk
(self.all_errata, self.errata_cache_expire) = \
load_cache(self.errata_cache_file)
# load self.all_packages_short from disk
(self.all_packages_short, self.package_cache_expire) = \
load_cache(self.packages_short_cache_file)
# load self.all_packages from disk
(self.all_packages, self.package_cache_expire) = \
load_cache(self.packages_long_cache_file)
# load self.all_packages_by_id from disk
(self.all_packages_by_id, self.package_cache_expire) = \
load_cache(self.packages_by_id_cache_file)
def get_system_names(self):
self.generate_system_cache()
return self.all_systems.values()
# check for duplicate system names and return the system ID
def get_system_id(self, name):
self.generate_system_cache()
try:
# check if we were passed a system instead of a name
system_id = int(name)
if system_id in self.all_systems:
return system_id
except ValueError:
pass
# get a set of matching systems to check for duplicate names
systems = []
for system_id in self.all_systems:
if name == self.all_systems[system_id]:
systems.append(system_id)
if len(systems) == 1:
return systems[0]
elif not len(systems):
logging.warning("Can't find system ID for %s", name)
return 0
else:
logging.warning('Duplicate system profile names found!')
logging.warning("Please reference systems by ID or resolve the")
logging.warning("underlying issue with 'system_delete' or 'system_rename'")
id_list = '%s = ' % name
for system_id in systems:
id_list = id_list + '%i, ' % system_id
logging.warning('')
logging.warning(id_list[:-2])
return 0
def get_system_name(self, system_id):
self.generate_system_cache()
try:
return self.all_systems[system_id]
except KeyError:
return
def get_org_id(self, name):
details = self.client.org.getDetails(self.session, name)
return details.get('id')
def expand_errata(self, args):
if not isinstance(args, list):
args = args.split()
self.generate_errata_cache()
if len(args) == 0:
return self.all_errata
errata = []
for item in args:
if re.match('search:', item):
item = re.sub('search:', '', item)
errata.extend(self.do_errata_search(item, True))
else:
errata.append(item)
matches = filter_results(self.all_errata, errata)
return matches
def expand_systems(self, args):
if not isinstance(args, list):
args = shlex.split(args)
systems = []
system_ids = []
for item in args:
if re.match('ssm', item, re.I):
systems.extend(self.ssm)
elif re.match('group:', item):
item = re.sub('group:', '', item)
members = self.do_group_listsystems("'%s'" % item, True)
if len(members):
systems.extend([re.escape(m) for m in members])
else:
logging.warning('No systems in group %s', item)
elif re.match('search:', item):
query = item.split(':', 1)[1]
results = self.do_system_search(query, True)
if len(results):
systems.extend([re.escape(r) for r in results])
elif re.match('channel:', item):
item = re.sub('channel:', '', item)
members = self.do_softwarechannel_listsystems(item, True)
if len(members):
systems.extend([re.escape(m) for m in members])
else:
logging.warning('No systems subscribed to %s', item)
else:
# translate system IDs that the user passes
try:
sys_id = int(item)
system_ids.append(sys_id)
except ValueError:
# just a system name
systems.append(item)
matches = filter_results(self.get_system_names(), systems)
return list(set(matches + system_ids))
def list_base_channels(self):
all_channels = self.client.channel.listSoftwareChannels(self.session)
base_channels = []
for c in all_channels:
if not c.get('parent_label'):
base_channels.append(c.get('label'))
return base_channels
def list_child_channels(self, system=None, parent=None, subscribed=False):
channels = []
if system:
system_id = self.get_system_id(system)
if not system_id:
return
if subscribed:
channels = \
self.client.system.listSubscribedChildChannels(self.session,
system_id)
else:
channels = self.client.system.listSubscribableChildChannels(
self.session, system_id)
elif parent:
all_channels = \
self.client.channel.listSoftwareChannels(self.session)
for c in all_channels:
if parent == c.get('parent_label'):
channels.append(c)
else:
# get all channels that have a parent
all_channels = \
self.client.channel.listSoftwareChannels(self.session)
for c in all_channels:
if c.get('parent_label'):
channels.append(c)
return [c.get('label') for c in channels]
def user_confirm(self, prompt='Is this ok [y/N]:', nospacer=False,
integer=False, ignore_yes=False):
if self.options.yes and not ignore_yes:
return True
if nospacer:
answer = prompt_user('%s' % prompt)
else:
answer = prompt_user('\n%s' % prompt)
if re.match('y', answer, re.I):
if integer:
return 1
else:
return True
else:
if integer:
return 0
else:
return False
# check if the available API is recent enough
def check_api_version(self, want):
want_parts = [int(i) for i in want.split('.')]
have_parts = [int(i) for i in self.api_version.split('.')]
if len(have_parts) == 2 and len(want_parts) == 2:
if have_parts[0] == want_parts[0]:
# compare minor versions if majors are the same
return have_parts[1] >= want_parts[1]
else:
# only compare major versions if they differ
return have_parts[0] >= want_parts[0]
else:
# compare the whole value
return float(self.api_version) >= float(want)
# replace the current line buffer
def replace_line_buffer(self, msg=None):
# restore the old buffer if we weren't given a new line
if not msg:
msg = readline.get_line_buffer()
# don't print a prompt if there wasn't one to begin with
if len(readline.get_line_buffer()):
new_line = '%s%s' % (self.prompt, msg)
else:
new_line = '%s' % msg
# clear the current line
self.stdout.write('\r'.ljust(len(self.current_line) + 1))
self.stdout.flush()
# write the new line
self.stdout.write('\r%s' % new_line)
self.stdout.flush()
# keep track of what is displayed so we can clear it later
self.current_line = new_line
def load_config_section(self, section):
config_opts = ['server', 'username', 'password', 'nossl']
if not self.config_parser.has_section(section):
logging.debug('Configuration section [%s] does not exist', section)
return
logging.debug('Loading configuration section [%s]', section)
for key in config_opts:
# don't override command-line options
if self.options.__dict__[key]:
# set the config value to the command-line argument
self.config[key] = self.options.__dict__[key]
else:
try:
self.config[key] = self.config_parser.get(section, key)
except NoOptionError:
pass
# handle the nossl boolean
if self.config.has_key('nossl') and isinstance(self.config['nossl'], str):
if re.match('^1|y|true$', self.config['nossl'], re.I):
self.config['nossl'] = True
else:
self.config['nossl'] = False
# Obfuscate the password with asterisks
config_debug = self.config.copy()
if config_debug.has_key('password'):
config_debug['password'] = "*" * len(config_debug['password'])
logging.debug('Current Configuration: %s', config_debug)
| xkollar/spacewalk | spacecmd/src/lib/misc.py | Python | gpl-2.0 | 28,096 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Adminhtml form container block
*
* @category Mage
* @package Mage_Adminhtml
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Adminhtml_Block_Widget_Form_Container extends Mage_Adminhtml_Block_Widget_Container
{
protected $_objectId = 'id';
protected $_formScripts = array();
protected $_formInitScripts = array();
protected $_mode = 'edit';
protected $_blockGroup = 'adminhtml';
public function __construct()
{
parent::__construct();
if (!$this->hasData('template')) {
$this->setTemplate('widget/form/container.phtml');
}
$this->_addButton('back', array(
'label' => Mage::helper('adminhtml')->__('Back'),
'onclick' => 'setLocation(\'' . $this->getBackUrl() . '\')',
'class' => 'back',
), -1);
$this->_addButton('reset', array(
'label' => Mage::helper('adminhtml')->__('Reset'),
'onclick' => 'setLocation(window.location.href)',
), -1);
$objId = $this->getRequest()->getParam($this->_objectId);
if (! empty($objId)) {
$this->_addButton('delete', array(
'label' => Mage::helper('adminhtml')->__('Delete'),
'class' => 'delete',
'onclick' => 'deleteConfirm(\''. Mage::helper('adminhtml')->__('Are you sure you want to do this?')
.'\', \'' . $this->getDeleteUrl() . '\')',
));
}
$this->_addButton('save', array(
'label' => Mage::helper('adminhtml')->__('Save'),
'onclick' => 'editForm.submit();',
'class' => 'save',
), 1);
}
protected function _prepareLayout()
{
if ($this->_blockGroup && $this->_controller && $this->_mode) {
$this->setChild('form', $this->getLayout()->createBlock($this->_blockGroup . '/' . $this->_controller . '_' . $this->_mode . '_form'));
}
return parent::_prepareLayout();
}
/**
* Get URL for back (reset) button
*
* @return string
*/
public function getBackUrl()
{
return $this->getUrl('*/*/');
}
public function getDeleteUrl()
{
return $this->getUrl('*/*/delete', array($this->_objectId => $this->getRequest()->getParam($this->_objectId)));
}
/**
* Get form save URL
*
* @deprecated
* @see getFormActionUrl()
* @return string
*/
public function getSaveUrl()
{
return $this->getFormActionUrl();
}
/**
* Get form action URL
*
* @return string
*/
public function getFormActionUrl()
{
if ($this->hasFormActionUrl()) {
return $this->getData('form_action_url');
}
return $this->getUrl('*/' . $this->_controller . '/save');
}
public function getFormHtml()
{
$this->getChild('form')->setData('action', $this->getSaveUrl());
return $this->getChildHtml('form');
}
public function getFormInitScripts()
{
if ( !empty($this->_formInitScripts) && is_array($this->_formInitScripts) ) {
return '<script type="text/javascript">' . implode("\n", $this->_formInitScripts) . '</script>';
}
return '';
}
public function getFormScripts()
{
if ( !empty($this->_formScripts) && is_array($this->_formScripts) ) {
return '<script type="text/javascript">' . implode("\n", $this->_formScripts) . '</script>';
}
return '';
}
public function getHeaderWidth()
{
return '';
}
public function getHeaderCssClass()
{
return 'icon-head head-' . strtr($this->_controller, '_', '-');
}
public function getHeaderHtml()
{
return '<h3 class="' . $this->getHeaderCssClass() . '">' . $this->getHeaderText() . '</h3>';
}
/**
* Set data object and pass it to form
*
* @param Varien_Object $object
* @return Mage_Adminhtml_Block_Widget_Form_Container
*/
public function setDataObject($object)
{
$this->getChild('form')->setDataObject($object);
return $this->setData('data_object', $object);
}
}
| tonio-44/tikflak | shop/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php | PHP | gpl-2.0 | 5,256 |
<?php
/**
* Template Name: LANG_CP_LISTVIEW_STYLE_TABLE
* Template Type: content
*/
if( $ctype['options']['list_show_filter'] ) {
$this->renderAsset('ui/filter-panel', array(
'css_prefix' => $ctype['name'],
'page_url' => $page_url,
'fields' => $fields,
'props_fields' => $props_fields,
'props' => $props,
'filters' => $filters,
'ext_hidden_params' => $ext_hidden_params,
'is_expanded' => $ctype['options']['list_expand_filter']
));
}
?>
<?php if ($items){ ?>
<div class="content_list table <?php echo $ctype['name']; ?>_list">
<table>
<thead>
<tr>
<?php if (isset($fields['photo']) && $fields['photo']['is_in_list']){ ?>
<th> </th>
<?php } ?>
<?php if ($ctype['is_rating']){ ?>
<th><?php echo LANG_RATING; ?></th>
<?php } ?>
<?php foreach($fields as $name => $field){ ?>
<?php if ($field['is_system'] || !$field['is_in_list']) { unset($fields[$name]); continue; } ?>
<?php if ($field['groups_read'] && !$user->isInGroups($field['groups_read'])) { unset($fields[$name]); continue; } ?>
<?php
if (!isset($field['options']['label_in_list'])) {
$label_pos = 'none';
} else {
$label_pos = $field['options']['label_in_list'];
}
?>
<th>
<?php echo $label_pos!='none' ? $field['title'] : ' '; ?>
</th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach($items as $item){ ?>
<tr<?php if (!empty($item['is_vip'])){ ?> class="is_vip"<?php } ?>>
<?php if (isset($fields['photo']) && $fields['photo']['is_in_list']){ ?>
<td class="photo">
<a href="<?php echo href_to($ctype['name'], $item['slug'].'.html'); ?>">
<?php if (!empty($item['photo'])){ ?>
<?php echo html_image($item['photo'], $fields['photo']['options']['size_teaser'], $item['title']); ?>
<?php unset($item['photo']); ?>
<?php } ?>
</a>
</td>
<?php } ?>
<?php if (!empty($item['rating_widget'])){ ?>
<td class="rating">
<?php echo $item['rating_widget']; ?>
</td>
<?php } ?>
<?php foreach($fields as $field){ ?>
<?php if (!isset($item[$field['name']]) || (!$item[$field['name']] && $item[$field['name']] !== '0')) {
echo '<td> </td>'; continue;
} ?>
<td class="field ft_<?php echo $field['type']; ?> f_<?php echo $field['name']; ?>">
<?php if ($field['name'] == 'title' && $ctype['options']['item_on']){ ?>
<h2>
<?php if ($item['parent_id']){ ?>
<a class="parent_title" href="<?php echo rel_to_href($item['parent_url']); ?>"><?php html($item['parent_title']); ?></a>
→
<?php } ?>
<a href="<?php echo href_to($ctype['name'], $item['slug'].'.html'); ?>"><?php html($item[$field['name']]); ?></a>
</h2>
<?php } else { ?>
<?php echo $field['handler']->setItem($item)->parseTeaser($item[$field['name']]); ?>
<?php } ?>
</td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php if ($perpage < $total) { ?>
<?php echo html_pagebar($page, $perpage, $total, $page_url, array_merge($filters, $ext_hidden_params)); ?>
<?php } ?>
<?php } else {
if(!empty($ctype['labels']['many'])){
echo sprintf(LANG_TARGET_LIST_EMPTY, $ctype['labels']['many']);
} else {
echo LANG_LIST_EMPTY;
}
}
| Loadir/icms2 | templates/default/content/default_list_table.tpl.php | PHP | gpl-2.0 | 4,849 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "Polar/PolarGlue.hpp"
#include "Polar/PolarFileGlue.hpp"
#include "Polar/Polar.hpp"
#include "Polar/PolarStore.hpp"
#include "Parser.hpp"
#include "Profile/Profile.hpp"
#include "IO/ConfiguredFile.hpp"
#include "IO/LineReader.hpp"
#include "Dialogs/Message.hpp"
#include "Language/Language.hpp"
#include "Util/StringCompare.hxx"
#include <memory>
namespace PolarGlue
{
bool LoadFromOldProfile(PolarInfo &polar);
}
PolarInfo
PolarGlue::GetDefault()
{
// Return LS8 polar
return PolarStore::GetItem(56).ToPolarInfo();
}
static bool
ReadPolarFileFromProfile(PolarInfo &polar)
{
std::unique_ptr<NLineReader> reader(OpenConfiguredTextFileA(ProfileKeys::PolarFile));
return reader && PolarGlue::LoadFromFile(polar, *reader);
}
bool
PolarGlue::LoadFromOldProfile(PolarInfo &polar)
{
unsigned polar_id;
if (!Profile::Get(ProfileKeys::PolarID, polar_id))
return false;
if (polar_id == 6)
return ReadPolarFileFromProfile(polar);
if (polar_id == 0)
polar_id = 45;
else if (polar_id == 1)
polar_id = 16;
else if (polar_id == 2)
polar_id = 56;
else if (polar_id == 3)
polar_id = 19;
else if (polar_id == 4)
polar_id = 55;
else if (polar_id == 5)
polar_id = 118;
else {
polar_id -= 7;
if (polar_id >= PolarStore::Count())
return false;
}
polar = PolarStore::GetItem(polar_id).ToPolarInfo();
return true;
}
bool
PolarGlue::LoadFromProfile(PolarInfo &polar)
{
const char *polar_string = Profile::Get(ProfileKeys::Polar);
if (polar_string != nullptr && !StringIsEmpty(polar_string) &&
ParsePolar(polar, polar_string)) {
return true;
}
return LoadFromOldProfile(polar);
}
PolarInfo
PolarGlue::LoadFromProfile()
{
PolarInfo polar;
if (!LoadFromProfile(polar) || !polar.IsValid()) {
if (Profile::Exists(ProfileKeys::Polar) || Profile::Exists(ProfileKeys::PolarID))
ShowMessageBox(_("Polar has invalid coefficients.\nUsing LS8 polar instead!"),
_("Warning"), MB_OK);
polar = GetDefault();
}
return polar;
}
| glukolog/xcsoar | src/Polar/PolarGlue.cpp | C++ | gpl-2.0 | 2,948 |
package at.micsti.mymusic;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ChartArtistAdapter extends ArrayAdapter<ChartArtist> {
public ChartArtistAdapter(Context context, ArrayList<ChartArtist> artists) {
super(context, R.layout.item_chart_artist, artists);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
ChartArtist chartArtist = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_chart_artist, parent, false);
}
// Lookup view for data population
TextView artistRank = (TextView) convertView.findViewById(R.id.artistRank);
TextView artistDiff = (TextView) convertView.findViewById(R.id.artistDiff);
TextView artistName = (TextView) convertView.findViewById(R.id.artistName);
TextView artistPlayCount = (TextView) convertView.findViewById(R.id.artistPlayCount);
// Populate the data into the template view using the data object
artistRank.setText(String.valueOf(chartArtist.getRank()));
artistDiff.setText(String.valueOf(chartArtist.getRankDiff()));
artistName.setText(chartArtist.getArtistName());
artistPlayCount.setText(String.valueOf(chartArtist.getPlayedCount()));
// Return the completed view to render on screen
return convertView;
}
}
| MICSTI/my-mobile-music | src/at/micsti/mymusic/ChartArtistAdapter.java | Java | gpl-2.0 | 1,719 |
<?php
drupal_add_js(drupal_get_path('module', 'image_poll') .'/js/image_poll.js');
/**
* @file
* Default template for an Image Poll when results are not available.
*
* Conditions under which template will display:
* 1. When results are set to 'Never' - results will only be visible to those
* with permission to view them.
* 2. When results are set to 'After Close' - results will only be visible when
* poll is set to closed.
*
* Variables available:
* - $votes
* - $nid: Node id of the poll.
* - $cancel_form: Provides a form for deleting user's votes when they have
* permission to do so.
*
* An array containing unique ids of the choice(s) selected by the user.
* - $data:
* object containing the following fields.
* choices:
* array containing:
* choice_id = the unique hex id of the choice
* choice = The text for a given choice.
* write_in = a boolean value indicating whether or not the choice was a
* write in.
* mode: The mode used to store the vote: normal, cookie, unlimited
* cookie_duration: (int) If mode is cookie, the number of minutes to delay votes.
* state: Is the poll 'open' or 'close'
* behavior: approval or pool - determines how to treat multiple vote/user
* tally. When plugin is installed, voting will default to tabulating
* values returned from voting API.
* max_choices: (int) How many choices a user can select per vote.
* show_results: When to display results - aftervote, afterclose or never.
* write_in: Boolean - all write-in voting.
* block: Boolean - Poll can be displayed as a block.
*/
?>
<div class="poll-noresult" id="image_poll-<?php print $nid; ?>">
<?php if ($data->show_results == 'never'): ?>
<p><?php print t('The results of this poll are not available.'); ?></p>
<?php endif; ?>
<?php if ($votes): ?>
<div class="poll-message"><?php print t('Thank you for voting.'); ?></div>
<?php endif; ?>
<?php print $cancel_form; ?>
</div> | cfdp/uddannelsesuge | sites/all/modules/image_poll/templates/image_poll-noresults.tpl.php | PHP | gpl-2.0 | 2,124 |
package org.deuce.transform.asm;
/**
* A structure to hold a tuple of class and its bytecode.
* @author guy
* @since 1.1
*/
public class ClassByteCode{
final private String className;
final private byte[] bytecode;
public ClassByteCode(String className, byte[] bytecode){
this.className = className;
this.bytecode = bytecode;
}
public String getClassName() {
return className;
}
public byte[] getBytecode() {
return bytecode;
}
}
| tauprojects/mpp | src/main/java/org/deuce/transform/asm/ClassByteCode.java | Java | gpl-2.0 | 457 |
<?php
defined('SAGEPAY_SDK_PATH') || exit('No direct script access.');
/**
* Details of the shopping basket item
*
* @category Payment
* @package Sagepay
* @copyright (c) 2013, Sage Pay Europe Ltd.
*/
class SagepayItem
{
/**
* The item description
*
* @var string
*/
private $_description = '';
/**
* The unique product identifier code
*
* @var string
*/
private $_productSku;
/**
* Item product code
*
* @var string
*/
private $_productCode;
/**
* Quantity of the item ordered
*
* @var integer
*/
private $_quantity = 0;
/**
* The cost of the item before tax
*
* @var float
*/
private $_unitNetAmount = 0.0;
/**
* The amount of tax on the item
*
* @var float
*/
private $_unitTaxAmount = 0.0;
/**
* The total cost of the item with tax
*
* @var float
*/
private $_unitGrossAmount;
/**
* The total cost of the line including quantity and tax
*
* @var float
*/
private $_totalGrossAmount;
/**
* The first name of the recipient of this item
*
* @var string
*/
private $_recipientFName;
/**
* The last name of the recipient of this item
*
* @var string
*/
private $_recipientLName;
/**
* The middle initial of the recipient of this item
*
* @var string
*/
private $_recipientMName;
/**
* The salutation of the recipient of this item
*
* @var string
*/
private $_recipientSal;
/**
* The email of the recipient of this item
*
* @var string
*/
private $_recipientEmail;
/**
* The phone number of the recipient of this item
*
* @var string
*/
private $_recipientPhone;
/**
* The first address line of the recipient of this item
*
* @var string
*/
private $_recipientAdd1;
/**
* The second address line of the recipient of this item
*
* @var string
*/
private $_recipientAdd2;
/**
* The city of the recipient of this item
*
* @var string
*/
private $_recipientCity;
/**
* If in the US, the 2 letter code for the state of the recipient of this item
*
* @var string
*/
private $_recipientState;
/**
* The 2 letter country code (ISO 3166) of the recipient of this item
*
* @var string
*/
private $_recipientCountry;
/**
* The postcode of the recipient of this item
*
* @var string
*/
private $_recipientPostCode;
/**
* The shipping item number
*
* @var string
*/
private $_itemShipNo;
/**
* Gift message associated with this item
*
* @var string
*/
private $_itemGiftMsg;
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->_description;
}
/**
* Set description
*
* @param string $description
*/
public function setDescription($description)
{
$this->_description = $description;
}
/**
* Get unique product identifier code
*
* @return string
*/
public function getProductSku()
{
return $this->_productSku;
}
/**
* Set unique product identifier code
*
* @param string $productSku
*/
public function setProductSku($productSku)
{
$this->_productSku = $productSku;
}
/**
* Get product code
*
* @return string
*/
public function getProductCode()
{
return $this->_productCode;
}
/**
* Set product code
*
* @param string $productCode
*/
public function setProductCode($productCode)
{
$this->_productCode = $productCode;
}
/**
* Get quantity of the item ordered
*
* @return integer
*/
public function getQuantity()
{
return $this->_quantity;
}
/**
* Set quantity of the item ordered
*
* @param integer $quantity
*/
public function setQuantity($quantity)
{
$this->_quantity = intval($quantity);
}
/**
* Get cost of the item before tax
*
* @return float
*/
public function getUnitNetAmount()
{
return $this->_unitNetAmount;
}
/**
* Set cost of the item before tax
*
* @param float $unitNetAmount
*/
public function setUnitNetAmount($unitNetAmount)
{
$this->_unitNetAmount = floatval($unitNetAmount);
}
/**
* Get amount of tax on the item
*
* @return float
*/
public function getUnitTaxAmount()
{
return $this->_unitTaxAmount;
}
/**
* Set amount of tax on the item
*
* @param float $unitTaxAmount
*/
public function setUnitTaxAmount($unitTaxAmount)
{
$this->_unitTaxAmount = floatval($unitTaxAmount);
}
/**
* Get total cost of the item with tax
*
* @return float
*/
public function getUnitGrossAmount()
{
return $this->_unitNetAmount + $this->_unitTaxAmount;
}
/**
* Get total cost of the line including quantity and tax
*
* @return float
*/
public function getTotalGrossAmount()
{
return $this->getUnitGrossAmount() * $this->getQuantity();
}
/**
* Get first name of the recipient of this item
*
* @return string
*/
public function getRecipientFName()
{
return $this->_recipientFName;
}
/**
* Set first name of the recipient of this item
*
* @param string $recipientFName
*/
public function setRecipientFName($recipientFName)
{
$this->_recipientFName = $recipientFName;
}
/**
* Get last name of the recipient of this item
*
* @return string
*/
public function getRecipientLName()
{
return $this->_recipientLName;
}
/**
* Set last name of the recipient of this item
*
* @param string $recipientLName
*/
public function setRecipientLName($recipientLName)
{
$this->_recipientLName = $recipientLName;
}
/**
* Get middle initial of the recipient of this item
*
* @return string
*/
public function getRecipientMName()
{
return $this->_recipientMName;
}
/**
* Set middle initial of the recipient of this item
*
* @param string $recipientMName
*/
public function setRecipientMName($recipientMName)
{
$this->_recipientMName = $recipientMName;
}
/**
* Get salutation of the recipient of this item
*
* @return string
*/
public function getRecipientSal()
{
return $this->_recipientSal;
}
/**
* Set salutation of the recipient of this item
*
* @param string $recipientSal
*/
public function setRecipientSal($recipientSal)
{
$this->_recipientSal = $recipientSal;
}
/**
* Get email of the recipient of this item
*
* @return string
*/
public function getRecipientEmail()
{
return $this->_recipientEmail;
}
/**
* Set email of the recipient of this item
*
* @param string $recipientEmail
*/
public function setRecipientEmail($recipientEmail)
{
$this->_recipientEmail = $recipientEmail;
}
/**
* Get phone number of the recipient of this item
*
* @return string
*/
public function getRecipientPhone()
{
return $this->_recipientPhone;
}
/**
* Set phone number of the recipient of this item
*
* @param string $recipientPhone
*/
public function setRecipientPhone($recipientPhone)
{
$this->_recipientPhone = $recipientPhone;
}
/**
* Get first address line of the recipient of this item
*
* @return string
*/
public function getRecipientAdd1()
{
return $this->_recipientAdd1;
}
/**
* Set first address line of the recipient of this item
*
* @param string $recipientAdd1
*/
public function setRecipientAdd1($recipientAdd1)
{
$this->_recipientAdd1 = $recipientAdd1;
}
/**
* Get second address line of the recipient of this item
*
* @return string
*/
public function getRecipientAdd2()
{
return $this->_recipientAdd2;
}
/**
* Set second address line of the recipient of this item
*
* @param string $recipientAdd2
*/
public function setRecipientAdd2($recipientAdd2)
{
$this->_recipientAdd2 = $recipientAdd2;
}
/**
* Get city of the recipient of this item
*
* @return string
*/
public function getRecipientCity()
{
return $this->_recipientCity;
}
/**
* Set city of the recipient of this item
*
* @param string $recipientCity
*/
public function setRecipientCity($recipientCity)
{
$this->_recipientCity = $recipientCity;
}
/**
* Get code for the state of the recipient of this item
*
* @return string
*/
public function getRecipientState()
{
return $this->_recipientState;
}
/**
* Set code for the state of the recipient of this item
*
* @param string $recipientState
*/
public function setRecipientState($recipientState)
{
$this->_recipientState = $recipientState;
}
/**
* Get country code of the recipient of this item
*
* @return string
*/
public function getRecipientCountry()
{
return $this->_recipientCountry;
}
/**
* Set country code of the recipient of this item
*
* @param string $recipientCountry
*/
public function setRecipientCountry($recipientCountry)
{
$this->_recipientCountry = $recipientCountry;
}
/**
* Get postcode of the recipient of this item
*
* @return string
*/
public function getRecipientPostCode()
{
return $this->_recipientPostCode;
}
/**
* Set postcode of the recipient of this item
*
* @param string $recipientPostCode
*/
public function setRecipientPostCode($recipientPostCode)
{
$this->_recipientPostCode = $recipientPostCode;
}
/**
* Get shipping item number
*
* @return string
*/
public function getItemShipNo()
{
return $this->_itemShipNo;
}
/**
* Set shipping item number
*
* @param string $itemShipNo
*/
public function setItemShipNo($itemShipNo)
{
$this->_itemShipNo = $itemShipNo;
}
/**
* Get gift message associated with this item
*
* @return string
*/
public function getItemGiftMsg()
{
return $this->_itemGiftMsg;
}
/**
* Set gift message associated with this item
*
* @param string $itemGiftMsg
*/
public function setItemGiftMsg($itemGiftMsg)
{
$this->_itemGiftMsg = $itemGiftMsg;
}
/**
* Create a DOMNode from property
*
* @param DOMDocument $basket
*
* @return DOMNode
*/
public function asDomElement(DOMDocument $basket)
{
$item = $basket->createElement('item');
$props = get_class_vars('SagepayItem');
foreach ($props as $name => $value)
{
$name = substr($name, 1);
if (substr($name, 0, 9) === 'recipient')
{
continue;
}
$getter = "get" . strtoupper($name);
$value = $this->$getter();
$node = null;
if (is_string($value) || is_int($value))
{
$node = $basket->createElement($name, trim($value));
}
else if (is_float($value))
{
$node = $basket->createElement($name, number_format($value, 2));
}
if ($node !== null)
{
$item->appendChild($node);
}
}
return $item;
}
/**
* Return a array of the item properties
*
* @return array
*/
public function asArray()
{
return array(
'item' => $this->getDescription(),
'quantity' => $this->getQuantity(),
'value' => $this->getUnitNetAmount(),
'tax' => $this->getUnitTaxAmount(),
'itemTotal' => $this->getUnitGrossAmount(),
'lineTotal' => $this->getTotalGrossAmount()
);
}
}
| domowit/BOOTSTRAP_V2 | wp-content/plugins/events-made-easy/payment_gateways/sagepay/api/lib/classes/item.php | PHP | gpl-2.0 | 13,502 |
<?php
namespace Engelsystem\Helpers\Translation;
use Exception;
class TranslationNotFound extends Exception
{
}
| engelsystem/engelsystem | src/Helpers/Translation/TranslationNotFound.php | PHP | gpl-2.0 | 115 |
package net.minecraft.item;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
public class ItemBlock extends Item
{
protected final Block field_150939_a;
private static final String __OBFID = "CL_00001772";
public ItemBlock(Block p_i45328_1_)
{
this.field_150939_a = p_i45328_1_;
}
/**
* Sets the unlocalized name of this item to the string passed as the parameter, prefixed by "item."
*/
public ItemBlock setUnlocalizedName(String p_77655_1_)
{
super.setUnlocalizedName(p_77655_1_);
return this;
}
/**
* Callback for item usage. If the item does something special on right clicking, he will have one of those. Return
* True if something happen and false if it don't. This is for ITEMS, not BLOCKS
*/
public boolean onItemUse(ItemStack p_77648_1_, EntityPlayer p_77648_2_, World p_77648_3_, int p_77648_4_, int p_77648_5_, int p_77648_6_, int p_77648_7_, float p_77648_8_, float p_77648_9_, float p_77648_10_)
{
Block var11 = p_77648_3_.getBlock(p_77648_4_, p_77648_5_, p_77648_6_);
if (var11 == Blocks.snow_layer && (p_77648_3_.getBlockMetadata(p_77648_4_, p_77648_5_, p_77648_6_) & 7) < 1)
{
p_77648_7_ = 1;
}
else if (var11 != Blocks.vine && var11 != Blocks.tallgrass && var11 != Blocks.deadbush)
{
if (p_77648_7_ == 0)
{
--p_77648_5_;
}
if (p_77648_7_ == 1)
{
++p_77648_5_;
}
if (p_77648_7_ == 2)
{
--p_77648_6_;
}
if (p_77648_7_ == 3)
{
++p_77648_6_;
}
if (p_77648_7_ == 4)
{
--p_77648_4_;
}
if (p_77648_7_ == 5)
{
++p_77648_4_;
}
}
if (p_77648_1_.stackSize == 0)
{
return false;
}
else if (!p_77648_2_.canPlayerEdit(p_77648_4_, p_77648_5_, p_77648_6_, p_77648_7_, p_77648_1_))
{
return false;
}
else if (p_77648_5_ == 255 && this.field_150939_a.getMaterial().isSolid())
{
return false;
}
else if (p_77648_3_.func_147472_a(this.field_150939_a, p_77648_4_, p_77648_5_, p_77648_6_, false, p_77648_7_, p_77648_2_, p_77648_1_))
{
int var12 = this.getMetadata(p_77648_1_.getItemDamage());
int var13 = this.field_150939_a.onBlockPlaced(p_77648_3_, p_77648_4_, p_77648_5_, p_77648_6_, p_77648_7_, p_77648_8_, p_77648_9_, p_77648_10_, var12);
if (p_77648_3_.setBlock(p_77648_4_, p_77648_5_, p_77648_6_, this.field_150939_a, var13, 3))
{
if (p_77648_3_.getBlock(p_77648_4_, p_77648_5_, p_77648_6_) == this.field_150939_a)
{
this.field_150939_a.onBlockPlacedBy(p_77648_3_, p_77648_4_, p_77648_5_, p_77648_6_, p_77648_2_, p_77648_1_);
this.field_150939_a.onPostBlockPlaced(p_77648_3_, p_77648_4_, p_77648_5_, p_77648_6_, var13);
}
p_77648_3_.playSoundEffect((double)((float)p_77648_4_ + 0.5F), (double)((float)p_77648_5_ + 0.5F), (double)((float)p_77648_6_ + 0.5F), this.field_150939_a.stepSound.func_150496_b(), (this.field_150939_a.stepSound.getVolume() + 1.0F) / 2.0F, this.field_150939_a.stepSound.getFrequency() * 0.8F);
--p_77648_1_.stackSize;
}
return true;
}
else
{
return false;
}
}
/**
* Returns the unlocalized name of this item. This version accepts an ItemStack so different stacks can have
* different names based on their damage or NBT.
*/
public String getUnlocalizedName(ItemStack p_77667_1_)
{
return this.field_150939_a.getUnlocalizedName();
}
/**
* Returns the unlocalized name of this item.
*/
public String getUnlocalizedName()
{
return this.field_150939_a.getUnlocalizedName();
}
}
| Myrninvollo/Server | src/net/minecraft/item/ItemBlock.java | Java | gpl-2.0 | 4,231 |
/*
* Copyright (C) 2005-2008 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "GUISliderControl.h"
#include "utils/GUIInfoManager.h"
#include "Key.h"
#include "MathUtils.h"
CGUISliderControl::CGUISliderControl(int parentID, int controlID, float posX, float posY, float width, float height, const CTextureInfo& backGroundTexture, const CTextureInfo& nibTexture, const CTextureInfo& nibTextureFocus, int iType)
: CGUIControl(parentID, controlID, posX, posY, width, height)
, m_guiBackground(posX, posY, width, height, backGroundTexture)
, m_guiMid(posX, posY, width, height, nibTexture)
, m_guiMidFocus(posX, posY, width, height, nibTextureFocus)
{
m_iType = iType;
m_iPercent = 0;
m_iStart = 0;
m_iEnd = 100;
m_fStart = 0.0f;
m_fEnd = 1.0f;
m_fInterval = 0.1f;
m_iValue = 0;
m_fValue = 0.0;
ControlType = GUICONTROL_SLIDER;
m_iInfoCode = 0;
}
CGUISliderControl::~CGUISliderControl(void)
{
}
void CGUISliderControl::Render()
{
m_guiBackground.SetPosition( m_posX, m_posY );
if (m_iInfoCode)
SetIntValue(g_infoManager.GetInt(m_iInfoCode));
float fScaleX = m_width == 0 ? 1.0f : m_width / m_guiBackground.GetTextureWidth();
float fScaleY = m_height == 0 ? 1.0f : m_height / m_guiBackground.GetTextureHeight();
m_guiBackground.SetHeight(m_height);
m_guiBackground.SetWidth(m_width);
m_guiBackground.Render();
float fWidth = (m_guiBackground.GetTextureWidth() - m_guiMid.GetTextureWidth())*fScaleX;
float fPos = m_guiBackground.GetXPosition() + GetProportion() * fWidth;
if ((int)fWidth > 1)
{
if (m_bHasFocus && !IsDisabled())
{
m_guiMidFocus.SetPosition(fPos, m_guiBackground.GetYPosition() );
m_guiMidFocus.SetWidth(m_guiMidFocus.GetTextureWidth() * fScaleX);
m_guiMidFocus.SetHeight(m_guiMidFocus.GetTextureHeight() * fScaleY);
m_guiMidFocus.Render();
}
else
{
m_guiMid.SetPosition(fPos, m_guiBackground.GetYPosition() );
m_guiMid.SetWidth(m_guiMid.GetTextureWidth()*fScaleX);
m_guiMid.SetHeight(m_guiMid.GetTextureHeight()*fScaleY);
m_guiMid.Render();
}
}
CGUIControl::Render();
}
bool CGUISliderControl::OnMessage(CGUIMessage& message)
{
if (message.GetControlId() == GetID() )
{
switch (message.GetMessage())
{
case GUI_MSG_ITEM_SELECT:
SetPercentage( message.GetParam1() );
return true;
break;
case GUI_MSG_LABEL_RESET:
{
SetPercentage(0);
return true;
}
break;
}
}
return CGUIControl::OnMessage(message);
}
bool CGUISliderControl::OnAction(const CAction &action)
{
switch ( action.GetID() )
{
case ACTION_MOVE_LEFT:
//case ACTION_OSD_SHOW_VALUE_MIN:
Move( -1);
return true;
break;
case ACTION_MOVE_RIGHT:
//case ACTION_OSD_SHOW_VALUE_PLUS:
Move(1);
return true;
break;
default:
return CGUIControl::OnAction(action);
}
}
void CGUISliderControl::Move(int iNumSteps)
{
switch (m_iType)
{
case SPIN_CONTROL_TYPE_FLOAT:
m_fValue += m_fInterval * iNumSteps;
if (m_fValue < m_fStart) m_fValue = m_fStart;
if (m_fValue > m_fEnd) m_fValue = m_fEnd;
break;
case SPIN_CONTROL_TYPE_INT:
m_iValue += iNumSteps;
if (m_iValue < m_iStart) m_iValue = m_iStart;
if (m_iValue > m_iEnd) m_iValue = m_iEnd;
break;
default:
m_iPercent += iNumSteps;
if (m_iPercent < 0) m_iPercent = 0;
if (m_iPercent > 100) m_iPercent = 100;
break;
}
SEND_CLICK_MESSAGE(GetID(), GetParentID(), MathUtils::round_int(100*GetProportion()));
}
void CGUISliderControl::SetPercentage(int iPercent)
{
if (iPercent > 100) iPercent = 100;
if (iPercent < 0) iPercent = 0;
m_iPercent = iPercent;
}
int CGUISliderControl::GetPercentage() const
{
return m_iPercent;
}
void CGUISliderControl::SetIntValue(int iValue)
{
if (m_iType == SPIN_CONTROL_TYPE_FLOAT)
m_fValue = (float)iValue;
else if (m_iType == SPIN_CONTROL_TYPE_INT)
m_iValue = iValue;
else
SetPercentage(iValue);
}
int CGUISliderControl::GetIntValue() const
{
if (m_iType == SPIN_CONTROL_TYPE_FLOAT)
return (int)m_fValue;
else if (m_iType == SPIN_CONTROL_TYPE_INT)
return m_iValue;
else
return m_iPercent;
}
void CGUISliderControl::SetFloatValue(float fValue)
{
if (m_iType == SPIN_CONTROL_TYPE_FLOAT)
m_fValue = fValue;
else if (m_iType == SPIN_CONTROL_TYPE_INT)
m_iValue = (int)fValue;
else
SetPercentage((int)fValue);
}
float CGUISliderControl::GetFloatValue() const
{
if (m_iType == SPIN_CONTROL_TYPE_FLOAT)
return m_fValue;
else if (m_iType == SPIN_CONTROL_TYPE_INT)
return (float)m_iValue;
else
return (float)m_iPercent;
}
void CGUISliderControl::SetFloatInterval(float fInterval)
{
m_fInterval = fInterval;
}
void CGUISliderControl::SetRange(int iStart, int iEnd)
{
if (m_iType == SPIN_CONTROL_TYPE_FLOAT)
SetFloatRange((float)iStart,(float)iEnd);
else
{
m_iStart = iStart;
m_iEnd = iEnd;
}
}
void CGUISliderControl::SetFloatRange(float fStart, float fEnd)
{
if (m_iType == SPIN_CONTROL_TYPE_INT)
SetRange((int)fStart, (int)fEnd);
else
{
m_fStart = fStart;
m_fEnd = fEnd;
}
}
void CGUISliderControl::FreeResources(bool immediately)
{
CGUIControl::FreeResources(immediately);
m_guiBackground.FreeResources(immediately);
m_guiMid.FreeResources(immediately);
m_guiMidFocus.FreeResources(immediately);
}
void CGUISliderControl::DynamicResourceAlloc(bool bOnOff)
{
CGUIControl::DynamicResourceAlloc(bOnOff);
m_guiBackground.DynamicResourceAlloc(bOnOff);
m_guiMid.DynamicResourceAlloc(bOnOff);
m_guiMidFocus.DynamicResourceAlloc(bOnOff);
}
void CGUISliderControl::AllocResources()
{
CGUIControl::AllocResources();
m_guiBackground.AllocResources();
m_guiMid.AllocResources();
m_guiMidFocus.AllocResources();
}
void CGUISliderControl::SetInvalid()
{
CGUIControl::SetInvalid();
m_guiBackground.SetInvalid();
m_guiMid.SetInvalid();
m_guiMidFocus.SetInvalid();
}
bool CGUISliderControl::HitTest(const CPoint &point) const
{
if (m_guiBackground.HitTest(point)) return true;
if (m_guiMid.HitTest(point)) return true;
return false;
}
void CGUISliderControl::SetFromPosition(const CPoint &point)
{
float fPercent = (point.x - m_guiBackground.GetXPosition()) / m_guiBackground.GetWidth();
if (fPercent < 0) fPercent = 0;
if (fPercent > 1) fPercent = 1;
switch (m_iType)
{
case SPIN_CONTROL_TYPE_FLOAT:
m_fValue = m_fStart + (m_fEnd - m_fStart) * fPercent;
break;
case SPIN_CONTROL_TYPE_INT:
m_iValue = (int)(m_iStart + (float)(m_iEnd - m_iStart) * fPercent + 0.49f);
break;
default:
m_iPercent = (int)(fPercent * 100 + 0.49f);
break;
}
SEND_CLICK_MESSAGE(GetID(), GetParentID(), MathUtils::round_int(fPercent));
}
EVENT_RESULT CGUISliderControl::OnMouseEvent(const CPoint &point, const CMouseEvent &event)
{
if (event.m_id == ACTION_MOUSE_DRAG)
{
if (event.m_state == 1)
{ // grab exclusive access
CGUIMessage msg(GUI_MSG_EXCLUSIVE_MOUSE, GetID(), GetParentID());
SendWindowMessage(msg);
}
else if (event.m_state == 3)
{ // release exclusive access
CGUIMessage msg(GUI_MSG_EXCLUSIVE_MOUSE, 0, GetParentID());
SendWindowMessage(msg);
}
SetFromPosition(point);
return EVENT_RESULT_HANDLED;
}
else if (event.m_id == ACTION_MOUSE_LEFT_CLICK && m_guiBackground.HitTest(point))
{
SetFromPosition(point);
return EVENT_RESULT_HANDLED;
}
else if (event.m_id == ACTION_MOUSE_WHEEL_UP)
{
Move(10);
return EVENT_RESULT_HANDLED;
}
else if (event.m_id == ACTION_MOUSE_WHEEL_DOWN)
{
Move(-10);
return EVENT_RESULT_HANDLED;
}
return EVENT_RESULT_UNHANDLED;
}
void CGUISliderControl::SetInfo(int iInfo)
{
m_iInfoCode = iInfo;
}
CStdString CGUISliderControl::GetDescription() const
{
if (!m_textValue.IsEmpty())
return m_textValue;
CStdString description;
if (m_iType == SPIN_CONTROL_TYPE_FLOAT)
description.Format("%2.2f", m_fValue);
else if (m_iType == SPIN_CONTROL_TYPE_INT)
description.Format("%i", m_iValue);
else
description.Format("%i%%", m_iPercent);
return description;
}
void CGUISliderControl::UpdateColors()
{
CGUIControl::UpdateColors();
m_guiBackground.SetDiffuseColor(m_diffuseColor);
m_guiMid.SetDiffuseColor(m_diffuseColor);
m_guiMidFocus.SetDiffuseColor(m_diffuseColor);
}
float CGUISliderControl::GetProportion() const
{
if (m_iType == SPIN_CONTROL_TYPE_FLOAT)
return (m_fValue - m_fStart) / (m_fEnd - m_fStart);
else if (m_iType == SPIN_CONTROL_TYPE_INT)
return (float)(m_iValue - m_iStart) / (float)(m_iEnd - m_iStart);
return 0.01f * m_iPercent;
}
| xbmc/atv2 | guilib/GUISliderControl.cpp | C++ | gpl-2.0 | 9,442 |
<?php
/**
* @package Template Overrides - RocketTheme
* @version 1.6.5 December 12, 2011
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*
* Rockettheme Gantry Template uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system
*
*/
// no direct access
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT.DS.'helpers');
// Create shortcuts to some parameters.
$params = $this->item->params;
$canEdit = $this->item->params->get('access-edit');
$user = JFactory::getUser();
$publishdate = version_compare(JVERSION,'1.7.3','<') ? 'COM_CONTENT_PUBLISHED_DATE' : 'COM_CONTENT_PUBLISHED_DATE_ON';
?>
<div class="rt-article">
<div class="item-page">
<?php /** Begin Page Title **/ if ($this->params->get('show_page_heading', 1)) : ?>
<h1 class="rt-pagetitle">
<?php echo $this->escape($this->params->get('page_heading')); ?>
</h1>
<?php /** End Page Title **/ endif; ?>
<div class="article-header">
<?php /** Begin Article Title **/ if ($params->get('show_title')) : ?>
<div class="module-title"><div class="module-title2"><div class="module-title3">
<h1 class="title">
<?php if ($params->get('link_titles') && !empty($this->item->readmore_link)) : ?>
<a href="<?php echo $this->item->readmore_link; ?>">
<?php echo $this->escape($this->item->title); ?></a>
<?php else : ?>
<?php echo $this->escape($this->item->title); ?>
<?php endif; ?>
</h1>
</div></div></div>
<?php /** End Article Title **/ endif; ?>
<div class="clear"></div>
<?php $useDefList = (($params->get('show_author')) OR ($params->get('show_create_date')) OR ($params->get('show_modify_date')) OR ($params->get('show_publish_date'))
OR ($params->get('show_hits')) || ($canEdit || $params->get('show_print_icon') || $params->get('show_email_icon'))); ?>
<?php /** Begin Article Info **/ if ($useDefList) : ?>
<div class="rt-articleinfo">
<div class="rt-articleinfo-text"><div class="rt-articleinfo-text2">
<?php if ($params->get('show_create_date')) : ?>
<div class="rt-date-posted">
<?php echo JHtml::_('date',$this->item->created, JText::_('DATE_FORMAT_LC3')); ?>
</div>
<?php endif; ?>
<?php if ($params->get('show_modify_date')) : ?>
<div class="rt-date-modified">
<?php echo JText::sprintf('COM_CONTENT_LAST_UPDATED', JHtml::_('date',$this->item->modified, JText::_('DATE_FORMAT_LC3'))); ?>
</div>
<?php endif; ?>
<?php if ($params->get('show_author') && !empty($this->item->author )) : ?>
<div class="rt-author">
<?php $author = $this->item->author; ?>
<?php $author = ($this->item->created_by_alias ? $this->item->created_by_alias : $author);?>
<?php if (!empty($this->item->contactid ) && $params->get('link_author') == true):?>
<?php echo JHtml::_('link',JRoute::_('index.php?option=com_contact&view=contact&id='.$this->item->contactid),$author); ?>
<?php else :?>
<?php echo $author; ?>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($params->get('show_publish_date')) : ?>
<div class="rt-date-published">
<?php echo JText::sprintf($publishdate, JHtml::_('date',$this->item->publish_up, JText::_('DATE_FORMAT_LC3'))); ?>
</div>
<?php endif; ?>
<?php if ($params->get('show_hits')) : ?>
<div class="rt-hits">
<?php echo JText::sprintf('COM_CONTENT_ARTICLE_HITS', $this->item->hits); ?>
</div>
<?php endif; ?>
</div></div>
<?php /** Begin Article Icons **/ if ($canEdit || $params->get('show_print_icon') || $params->get('show_email_icon')) : ?>
<div class="rt-article-icons">
<ul class="actions">
<?php if (!$this->print) : ?>
<?php if ($params->get('show_print_icon')) : ?>
<li class="print-icon">
<?php echo JHtml::_('icon.print_popup', $this->item, $params); ?>
</li>
<?php endif; ?>
<?php if ($params->get('show_email_icon')) : ?>
<li class="email-icon">
<?php echo JHtml::_('icon.email', $this->item, $params); ?>
</li>
<?php endif; ?>
<?php if ($canEdit) : ?>
<li class="edit-icon">
<?php echo JHtml::_('icon.edit', $this->item, $params); ?>
</li>
<?php endif; ?>
<?php else : ?>
<li>
<?php echo JHtml::_('icon.print_screen', $this->item, $params); ?>
</li>
<?php endif; ?>
</ul>
</div>
<?php /** End Article Icons **/ endif; ?>
<div class="clear"></div>
</div>
<?php endif; ?>
</div>
<?php if (!$params->get('show_intro')) :
echo $this->item->event->afterDisplayTitle;
endif; ?>
<?php echo $this->item->event->beforeDisplayContent; ?>
<?php if (isset ($this->item->toc)) : ?>
<?php echo $this->item->toc; ?>
<?php endif; ?>
<?php if ($params->get('access-view')):?>
<?php echo $this->item->text; ?>
<?php //optional teaser intro text for guests ?>
<?php elseif ($params->get('show_noauth') == true AND $user->get('guest') ) : ?>
<?php echo $this->item->introtext; ?>
<?php //Optional link to let them register to see the whole article. ?>
<?php if ($params->get('show_readmore') && $this->item->fulltext != null) :
$link1 = JRoute::_('index.php?option=com_users&view=login');
$link = new JURI($link1);?>
<p class="readmore">
<a href="<?php echo $link; ?>">
<?php $attribs = json_decode($this->item->attribs); ?>
<?php
if ($attribs->alternative_readmore == null) :
echo JText::_('COM_CONTENT_REGISTER_TO_READ_MORE');
elseif ($readmore = $this->item->alternative_readmore) :
echo $readmore;
if ($params->get('show_readmore_title', 0) != 0) :
echo JHtml::_('string.truncate', ($this->item->title), $params->get('readmore_limit'));
endif;
elseif ($params->get('show_readmore_title', 0) == 0) :
echo JText::sprintf('COM_CONTENT_READ_MORE_TITLE');
else :
echo JText::_('COM_CONTENT_READ_MORE');
echo JHtml::_('string.truncate', ($this->item->title), $params->get('readmore_limit'));
endif; ?></a>
</p>
<?php endif; ?>
<?php endif; ?>
<?php echo $this->item->event->afterDisplayContent; ?>
<?php if ($params->get('show_parent_category') && $this->item->parent_slug != '1:root') : ?>
<div class="rt-parent-category">
<?php $title = $this->escape($this->item->parent_title);
$url = '<a href="'.JRoute::_(ContentHelperRoute::getCategoryRoute($this->item->parent_slug)).'">'.$title.'</a>';?>
<?php if ($params->get('link_parent_category') AND $this->item->parent_slug) : ?>
<?php echo JText::sprintf('COM_CONTENT_PARENT', $url); ?>
<?php else : ?>
<?php echo JText::sprintf('COM_CONTENT_PARENT', $title); ?>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($params->get('show_category')) : ?>
<div class="rt-category">
<?php $title = $this->escape($this->item->category_title);
$url = '<a href="'.JRoute::_(ContentHelperRoute::getCategoryRoute($this->item->catslug)).'">'.$title.'</a>';?>
<?php if ($params->get('link_category') AND $this->item->catslug) : ?>
<?php echo JText::sprintf('COM_CONTENT_CATEGORY', $url); ?>
<?php else : ?>
<?php echo JText::sprintf('COM_CONTENT_CATEGORY', $title); ?>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div> | shatilov/snipebaby | templates/rt_modulus_j16/html/com_content/article/default.php | PHP | gpl-2.0 | 7,505 |
/*
* Simplified Chinese translation
* By DavidHu
* 09 April 2007
*/
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">加载中...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.Grid){
Ext.grid.Grid.prototype.ddText = "{0} 选择行";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "关闭";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "输入值非法";
}
Date.monthNames = [
"一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"
];
Date.dayNames = [
"日",
"一",
"二",
"三",
"四",
"五",
"六"
];
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "确定",
cancel : "取消",
yes : "是",
no : "否"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "y年m月d日");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "今天",
minText : "日期在最小日期之前",
maxText : "日期在最大日期之后",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : '下月 (Control+Right)',
prevText : '上月 (Control+Left)',
monthYearText : '选择一个月 (Control+Up/Down 来改变年)',
todayTip : "{0} (空格键选择)",
format : "y年m月d日"
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "第",
afterPageText : "页,共 {0} 页",
firstText : "第一页",
prevText : "前一页",
nextText : "下一页",
lastText : "最后页",
refreshText : "刷新",
displayMsg : "显示 {0} - {1},共 {2} 条",
emptyMsg : '没有数据需要显示'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "该输入项的最小长度是 {0}",
maxLengthText : "该输入项的最大长度是 {0}",
blankText : "该输入项为必输项",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "该输入项的最小值是 {0}",
maxText : "该输入项的最大值是 {0}",
nanText : "{0} 不是有效数值"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "禁用",
disabledDatesText : "禁用",
minText : "该输入项的日期必须在 {0} 之后",
maxText : "该输入项的日期必须在 {0} 之前",
invalidText : "{0} 是无效的日期 - 必须符合格式: {1}",
format : "y年m月d日"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "加载...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : '该输入项必须是电子邮件地址,格式如: "user@domain.com"',
urlText : '该输入项必须是URL地址,格式如: "http:/'+'/www.domain.com"',
alphaText : '该输入项只能包含字符和_',
alphanumText : '该输入项只能包含字符,数字和_'
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "正序",
sortDescText : "逆序",
lockText : "锁列",
unlockText : "解锁列",
columnsText : "列"
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "名称",
valueText : "值",
dateFormat : "y年m月d日"
});
}
if(Ext.layout.BorderLayout.SplitRegion){
Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
splitTip : "拖动来改变尺寸.",
collapsibleSplitTip : "拖动来改变尺寸. 双击隐藏."
});
}
| jreadstone/zsyproject | WebRoot/resource/commonjs/ext-lang-zh_CN.js | JavaScript | gpl-2.0 | 4,293 |
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2020 RomRaider.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.
*/
package com.romraider.logger.ecu.comms.io.protocol;
import java.util.Collection;
import com.romraider.logger.ecu.comms.manager.PollingState;
import com.romraider.logger.ecu.comms.query.EcuQuery;
import com.romraider.logger.ecu.definition.Module;
public interface LoggerProtocolDS2 extends LoggerProtocol {
byte[] constructReadProcedureRequest(Module module,
Collection<EcuQuery> queries);
byte[] constructReadAddressResponse(
Collection<EcuQuery> queries, int requestSize);
byte[] constructReadGroupRequest(
Module module, String group);
byte[] constructReadGroupResponse(
Collection<EcuQuery> queries, int requestSize);
byte[] constructReadMemoryRequest(
Module module, Collection<EcuQuery> queryList);
byte[] constructReadMemoryRange(Module module,
Collection<EcuQuery> queries, int length);
public byte[] constructReadMemoryRangeResponse(int requestSize, int length);
void processReadAddressResponse(Collection<EcuQuery> queries,
byte[] response, PollingState pollState);
void processReadMemoryRangeResponse(Collection<EcuQuery> queries, byte[] response);
byte[] constructSetAddressRequest(
Module module, Collection<EcuQuery> queryList);
byte[] constructSetAddressResponse(int length);
void validateSetAddressResponse(byte[] response);
}
| dschultzca/RomRaider | src/main/java/com/romraider/logger/ecu/comms/io/protocol/LoggerProtocolDS2.java | Java | gpl-2.0 | 2,226 |
<?php
class Photonic_Options_Manager {
var $options, $tab, $tab_options, $reverse_options, $shown_options, $option_defaults, $allowed_values, $hidden_options, $nested_options, $displayed_sections;
var $option_structure, $previous_displayed_section, $file, $tab_name;
function Photonic_Options_Manager($file) {
global $photonic_setup_options, $photonic_generic_options, $photonic_flickr_options, $photonic_picasa_options, $photonic_500px_options, $photonic_smugmug_options, $photonic_instagram_options, $photonic_zenfolio_options;
$options_page_array = array(
'generic-options.php' => $photonic_generic_options,
'flickr-options.php' => $photonic_flickr_options,
'picasa-options.php' => $photonic_picasa_options,
'500px-options.php' => $photonic_500px_options,
'smugmug-options.php' => $photonic_smugmug_options,
'instagram-options.php' => $photonic_instagram_options,
'zenfolio-options.php' => $photonic_zenfolio_options,
);
$tab_name_array = array(
'generic-options.php' => 'Generic Options',
'flickr-options.php' => 'Flickr Options',
'picasa-options.php' => 'Picasa Options',
'500px-options.php' => '500px Options',
'smugmug-options.php' => 'SmugMug Options',
'instagram-options.php' => 'Instagram Options',
'zenfolio-options.php' => 'Zenfolio Options',
);
$this->file = $file;
$this->tab = 'generic-options.php';
if (isset($_REQUEST['tab']) && array_key_exists($_REQUEST['tab'], $options_page_array)) {
$this->tab = $_REQUEST['tab'];
}
$this->tab_options = $options_page_array[$this->tab];
$this->tab_name = $tab_name_array[$this->tab];
$this->options = $photonic_setup_options;
$this->reverse_options = array();
$this->nested_options = array();
$this->displayed_sections = 0;
$this->option_structure = $this->get_option_structure();
$all_options = get_option('photonic_options');
if (!isset($all_options)) {
$this->hidden_options = array();
}
else {
$this->hidden_options = $all_options;
}
foreach ($this->tab_options as $option) {
if (isset($option['id'])) {
$this->shown_options[] = $option['id'];
if (isset($this->hidden_options[$option['id']])) unset($this->hidden_options[$option['id']]);
}
}
foreach ($photonic_setup_options as $option) {
if (isset($option['category']) && !isset($this->nested_options[$option['category']])) {
$this->nested_options[$option['category']] = array();
}
if (isset($option['id'])) {
$this->reverse_options[$option['id']] = $option['type'];
if (isset($option['std'])) {
$this->option_defaults[$option['id']] = $option['std'];
}
if (isset($option['options'])) {
$this->allowed_values[$option['id']] = $option['options'];
}
if (isset($option['grouping'])) {
if (!isset($this->nested_options[$option['grouping']])) {
$this->nested_options[$option['grouping']] = array();
}
$this->nested_options[$option['grouping']][] = $option['id'];
}
}
}
}
function render_options_page() {
?>
<div class="photonic-wrap">
<div class="photonic-tabbed-options">
<div class="photonic-header-nav">
<div class="photonic-header-nav-top fix">
<h2 class='photonic-header-1'>Photonic</h2>
<div class='donate fix'>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="paypal-submit" >
<input type="hidden" name="cmd" value="_s-xclick"/>
<input type="hidden" name="hosted_button_id" value="9018267"/>
<ul>
<li class='announcements'><a href='http://aquoid.com/news'>Announcements</a></li>
<li class='support'><a href='http://aquoid.com/forum'>Support Forum</a></li>
<li class='coffee'><input type='submit' name='submit' value='Like Photonic? Buy me a coffee!' /></li>
</ul>
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"/>
</form>
</div><!-- donate -->
</div>
<div class="photonic-options-header-bar fix">
<ul class='photonic-options-header-bar'>
<li><a class='photonic-load-page <?php if ($this->tab == 'generic-options.php') echo 'current-tab'; ?>' id='photonic-options-generic' href='?page=photonic-options-manager&tab=generic-options.php'><span class="icon"> </span> Generic Options</a></li>
<li><a class='photonic-load-page <?php if ($this->tab == 'flickr-options.php') echo 'current-tab'; ?>' id='photonic-options-flickr' href='?page=photonic-options-manager&tab=flickr-options.php'><span class="icon"> </span> Flickr</a></li>
<li><a class='photonic-load-page <?php if ($this->tab == 'picasa-options.php') echo 'current-tab'; ?>' id='photonic-options-picasa' href='?page=photonic-options-manager&tab=picasa-options.php'><span class="icon"> </span> Picasa</a></li>
<li><a class='photonic-load-page <?php if ($this->tab == '500px-options.php') echo 'current-tab'; ?>' id='photonic-options-500px' href='?page=photonic-options-manager&tab=500px-options.php'><span class="icon"> </span> 500px</a></li>
<li><a class='photonic-load-page <?php if ($this->tab == 'smugmug-options.php') echo 'current-tab'; ?>' id='photonic-options-smugmug' href='?page=photonic-options-manager&tab=smugmug-options.php'><span class="icon"> </span> SmugMug</a></li>
<li><a class='photonic-load-page <?php if ($this->tab == 'instagram-options.php') echo 'current-tab'; ?>' id='photonic-options-instagram' href='?page=photonic-options-manager&tab=instagram-options.php'><span class="icon"> </span> Instagram</a></li>
<li><a class='photonic-load-page <?php if ($this->tab == 'zenfolio-options.php') echo 'current-tab'; ?>' id='photonic-options-zenfolio' href='?page=photonic-options-manager&tab=zenfolio-options.php'><span class="icon"> </span> Zenfolio</a></li>
</ul>
</div>
</div>
<?php
$option_structure = $this->get_option_structure();
$group = substr($this->tab, 0, stripos($this->tab, '.'));
echo "<div class='photonic-options photonic-options-$group' id='photonic-options'>";
echo "<div class='photonic-options-page-header fix'>\n";
echo "<h1>{$this->tab_name}</h1>\n";
echo "</div><!-- photonic-options-page-header -->\n";
echo "<ul class='photonic-section-tabs'>";
foreach ($option_structure as $l1_slug => $l1) {
echo "<li><a href='#$l1_slug'>" . $l1['name'] . "</a></li>\n";
}
echo "</ul>";
do_settings_sections($this->file);
echo "</form>\n";
echo "</div><!-- main-content -->\n";
echo "</div><!-- /#photonic-options -->\n";
?>
</div><!-- /#photonic-tabbed-options -->
</div>
<?php
}
function render_helpers() { ?>
<div class="photonic-wrap">
<div class="photonic-tabbed-options" style='position: relative; display: inline-block; '>
<div class="photonic-waiting"><img src="<?php echo plugins_url('/include/images/downloading-dots.gif', __FILE__); ?>" alt='waiting'/></div>
<form method="post" id="photonic-helper-form">
<div class="photonic-header-nav">
<div class="photonic-header-nav-top fix">
<h2 class='photonic-header-1'>Photonic</h2>
</div>
</div>
<h3 class="photonic-helper-header">Flickr</h3>
<div class="photonic-helper-box left">
<?php $this->display_flickr_id_helper(); ?>
</div>
<div class="photonic-helper-box right">
<?php $this->display_flickr_group_helper(); ?>
</div>
<h3 class="photonic-helper-header">Instagram</h3>
<div class="photonic-helper-box left">
<?php $this->display_instagram_id_helper(); ?>
</div>
<div class="photonic-helper-box right">
<?php $this->display_instagram_location_helper(); ?>
</div>
<h3 class="photonic-helper-header">Zenfolio</h3>
<div class="photonic-helper-box left">
<?php $this->display_zenfolio_category_helper(); ?>
</div>
</form>
</div>
</div>
<?php
}
function display_flickr_id_helper() {
global $photonic_flickr_api_key;
if (!isset($photonic_flickr_api_key)) {
_e('Please set up your Flickr API Key under <em>Photonic → Settings → Flickr → Flickr Settings</em>', 'photonic');
}
else {
_e('<h3>Flickr User ID Finder</h3>', 'photonic');
_e('<label>Enter your Flickr photostream URL and click "Find"', 'photonic');
echo '<input type="text" value="http://www.flickr.com/photos/username/" id="photonic-flickr-user" name="photonic-flickr-user"/>';
echo '</label>';
echo '<input type="button" value="'.__('Find', 'photonic').'" id="photonic-flickr-user-find" class="photonic-helper-button"/>';
echo '<div class="result"> </div>';
}
}
function display_flickr_group_helper() {
global $photonic_flickr_api_key;
if (!isset($photonic_flickr_api_key)) {
_e('Please set up your Flickr API Key under <em>Photonic → Settings → Flickr → Flickr Settings</em>', 'photonic');
}
else {
_e('<h3>Flickr Group ID Finder</h3>', 'photonic');
_e('<label>Enter your Flickr group URL and click "Find"', 'photonic');
echo '<input type="text" value="http://www.flickr.com/groups/groupname/" id="photonic-flickr-group" name="photonic-flickr-group"/>';
echo '</label>';
echo '<input type="button" value="'.__('Find', 'photonic').'" id="photonic-flickr-group-find" class="photonic-helper-button"/>';
echo '<div class="result"> </div>';
}
}
function display_instagram_id_helper() {
global $photonic_instagram_client_id;
if (!isset($photonic_instagram_client_id)) {
_e('Please set up your Instagram Client ID under <em>Photonic → Settings → Instagram → Instagram Settings</em>', 'photonic');
}
else {
_e('<h3>Instagram ID Finder</h3>', 'photonic');
_e('<label>Enter your Instagram login id and click "Find"', 'photonic');
echo '<input type="text" value="login-id" id="photonic-instagram-user" name="photonic-instagram-user"/>';
echo '</label>';
echo '<input type="button" value="'.__('Find', 'photonic').'" id="photonic-instagram-user-find" class="photonic-helper-button"/>';
echo '<div class="result"> </div>';
}
}
function display_instagram_location_helper() {
global $photonic_instagram_client_id;
if (!isset($photonic_instagram_client_id)) {
_e('Please set up your Instagram Client ID under <em>Photonic → Settings → Instagram → Instagram Settings</em>', 'photonic');
}
else {
_e('<h3>Instagram Location Finder</h3>', 'photonic');
echo '<div class="location-fields">';
echo '<div class="location"><label>'.__('Latitude', 'photonic').'<br/><input type="text" id="photonic-instagram-lat" name="photonic-instagram-lat"></label></div>';
echo '<div class="location"><label>'.__('Longitude', 'photonic').'<br/><input type="text" id="photonic-instagram-lng" name="photonic-instagram-lng"></label></div>';
echo '<div class="fs-separator"><span>'.__('OR', 'photonic').'</span></div>';
echo '<div class="location"><label>'.__('FourSquare ID', 'photonic').'<br/><input type="text" id="photonic-instagram-fsid" name="photonic-instagram-fsid"></label></div>';
echo '</div>';
echo '<input type="button" value="'.__('Find', 'photonic').'" id="photonic-instagram-location-find" class="photonic-helper-button"/>';
echo '<div class="result"> </div>';
}
}
function display_zenfolio_category_helper() {
_e('<h3>Zenfolio Categories</h3>', 'photonic');
echo '<input type="button" value="'.__('List', 'photonic').'" id="photonic-zenfolio-categories-find" class="photonic-helper-button"/>';
echo '<div class="result"> </div>';
}
function init() {
foreach ($this->option_structure as $slug => $option) {
register_setting('photonic_options-'.$slug, 'photonic_options', array(&$this, 'validate_options'));
add_settings_section($slug, "", array(&$this, "create_settings_section"), $this->file);
$this->add_settings_fields($slug, $this->file);
}
}
function validate_options($options) {
foreach ($options as $option => $option_value) {
if (isset($this->reverse_options[$option])) {
//Sanitize options
switch ($this->reverse_options[$option]) {
// For all text type of options make sure that the eventual text is properly escaped.
case "text":
case "textarea":
case "slider":
case "color-picker":
case "background":
case "border":
case "font":
case "upload":
$options[$option] = esc_attr($option_value);
break;
case "select":
case "radio":
if (isset($this->allowed_values[$option])) {
if (!array_key_exists($option_value, $this->allowed_values[$option])) {
$options[$option] = $this->option_defaults[$option];
}
}
break;
case "multi-select":
$selections = explode(',', $option_value);
$final_selections = array();
foreach ($selections as $selection) {
if (array_key_exists($selection, $this->allowed_values[$option])) {
$final_selections[] = $selection;
}
}
$options[$option] = implode(',', $final_selections);
break;
case "sortable-list":
$selections = explode(',', $option_value);
$final_selections = array();
$master_list = $this->option_defaults[$option]; // Sortable lists don't have their values in ['options']
foreach ($selections as $selection) {
if (array_key_exists($selection, $master_list)) {
$final_selections[] = $selection;
}
}
$options[$option] = implode(',', $final_selections);
break;
case "checkbox":
if (!in_array($option_value, array('on', 'off', 'true', 'false')) && isset($this->option_defaults[$option])) {
$options[$option] = $this->option_defaults[$option];
}
break;
}
}
}
/* The Settings API does an update_option($option, $value), overwriting the $photonic_options array with the values on THIS page
* This is problematic because all options are stored in a single array, but are displayed on different options pages.
* Hence the overwrite kills the options from the other pages.
* So this is a workaround to include the options from other pages as hidden fields on this page, so that the array gets properly updated.
* The alternative would be to separate options for each page, but that would cause a migration headache for current users.
*/
if (isset($this->hidden_options) && is_array($this->hidden_options)) {
foreach ($this->hidden_options as $hidden_option => $hidden_value) {
if (strlen($hidden_option) >= 7 && (substr($hidden_option, 0, 7) == 'submit-' || substr($hidden_option, 0, 6) == 'reset-')) {
continue;
}
$options[$hidden_option] = esc_attr($hidden_value);
}
}
foreach ($this->nested_options as $section => $children) {
if (isset($options['submit-'.$section])) {
$options['last-set-section'] = $section;
if (substr($options['submit-'.$section], 0, 9) == 'Save page' || substr($options['submit-'.$section], 0, 10) == 'Reset page') {
global $photonic_options;
foreach ($this->nested_options as $inner_section => $inner_children) {
if ($inner_section != $section) {
foreach ($inner_children as $inner_child) {
if (isset($photonic_options[$inner_child])) {
$options[$inner_child] = $photonic_options[$inner_child];
}
}
}
}
if (substr($options['submit-'.$section], 0, 10) == 'Reset page') {
unset($options['submit-'.$section]);
// This is a reset for an individual section. So we will unset the child fields.
foreach ($children as $child) {
unset($options[$child]);
}
}
unset($options['submit-'.$section]);
}
else if (substr($options['submit-'.$section], 0, 12) == 'Save changes') {
unset($options['submit-'.$section]);
}
else if (substr($options['submit-'.$section], 0, 13) == 'Reset changes') {
unset($options['submit-'.$section]);
// This is a reset for all options in the sub-menu. So we will unset all child fields.
foreach ($this->nested_options as $section => $children) {
foreach ($children as $child) {
unset($options[$child]);
}
}
}
else if (substr($options['submit-'.$section], 0, 6) == 'Delete') {
return;
}
break;
}
}
return $options;
}
function get_option_structure() {
if (isset($this->option_structure)) {
return $this->option_structure;
}
$options = $this->tab_options;
$option_structure = array();
foreach ($options as $value) {
switch ($value['type']) {
case "title":
$option_structure[$value['category']] = array();
$option_structure[$value['category']]['slug'] = $value['category'];
$option_structure[$value['category']]['name'] = $value['name'];
$option_structure[$value['category']]['children'] = array();
break;
case "section":
// $option_structure[$value['parent']]['children'][$value['category']] = $value['name'];
$option_structure[$value['category']] = array();
$option_structure[$value['category']]['slug'] = $value['category'];
$option_structure[$value['category']]['name'] = $value['name'];
$option_structure[$value['category']]['children'] = array();
if (isset($value['help'])) $option_structure[$value['category']]['help'] = $value['help'];
if (isset($value['buttons'])) $option_structure[$value['category']]['buttons'] = $value['buttons'];
break;
default:
// $option_structure[$value['grouping']]['children'][$value['name']] = $value['name'];
if (isset($value['id'])) {
$option_structure[$value['grouping']]['children'][$value['id']] = $value['name'];
}
}
}
return $option_structure;
}
function evaluate_conditions($conditions) {
// Operators: NOT, OR, AND, NOR, NAND. XOR is too complex
if (isset($conditions['operator'])) {
$operator = $conditions['operator'];
}
else {
$operator = 'OR';
}
$nested_conditions = $conditions['conditions'];
if (isset($nested_conditions['operator'])) {
return $this->evaluate_conditions($nested_conditions);
}
else {
$evals = array();
foreach ($nested_conditions as $variable => $check_value) {
$photonic_variable = 'photonic_'.$variable;
global $$photonic_variable;
$actual_value = $$photonic_variable;
if ($operator == 'NOT') {
return $actual_value != $check_value;
}
else {
$evals[] = $actual_value == $check_value ? 1 : 0;
}
}
return $this->array_join_boolean($evals, $operator);
}
}
function array_join_boolean($conditions, $operator) {
if (count($conditions) == 1) {
return $conditions[0];
}
else {
$first = $conditions[0];
$rest = array_slice($conditions, 1);
if ($operator == 'AND') {
$result = $first * $this->array_join_boolean($rest, $operator);
return $result != 0;
}
else if ($operator == 'NOR') {
$result = $first + $this->array_join_boolean($rest, $operator);
return $result == 0;
}
else if ($operator == 'NAND') {
$result = $first * $this->array_join_boolean($rest, $operator);
return $result == 0;
}
else { // Everything else is treated as OR
$result = $first + $this->array_join_boolean($rest, $operator);
return $result != 0;
}
}
}
function add_settings_fields($section, $page) {
$ctr = 0;
foreach ($this->tab_options as $value) {
if (isset($value['conditional']) && true === $value['conditional']) {
$show = true;
if (isset($value['conditions'])) {
$conditions = $value['conditions'];
$show = $this->evaluate_conditions($conditions);
}
if (!$show) {
continue;
}
}
$ctr++;
switch ($value['type']) {
case "section":
add_settings_field('', '', array(&$this, "create_title"), $page, $section, $value);
break;
case "blurb";
add_settings_field($value['grouping'].'-'.$ctr, '', array(&$this, "create_section_for_blurb"), $page, $value['grouping'], $value);
break;
case "text";
add_settings_field($value['id'], '', array(&$this, "create_section_for_text"), $page, $value['grouping'], $value);
break;
case "textarea";
add_settings_field($value['id'], '', array(&$this, "create_section_for_textarea"), $page, $value['grouping'], $value);
break;
case "select":
add_settings_field($value['id'], '', array(&$this, "create_section_for_select"), $page, $value['grouping'], $value);
break;
case "radio":
add_settings_field($value['id'], '', array(&$this, "create_section_for_radio"), $page, $value['grouping'], $value);
// add_settings_field($value['id'], '', array(&$this, "create_section_for_radio"), $parent, 'default', $value);
break;
case "slider":
add_settings_field($value['id'], '', array(&$this, "create_section_for_slider"), $page, $value['grouping'], $value);
// add_settings_field($value['id'], '', array(&$this, "create_section_for_slider"), $parent, $section, $value);
break;
case "color-picker":
add_settings_field($value['id'], '', array(&$this, "create_section_for_color_picker"), $page, $value['grouping'], $value);
break;
case "checkbox":
add_settings_field($value['id'], '', array(&$this, "create_section_for_checkbox"), $page, $value['grouping'], $value);
break;
case "border":
add_settings_field($value['id'], '', array(&$this, "create_section_for_border"), $page, $value['grouping'], $value);
break;
case "background":
add_settings_field($value['id'], '', array(&$this, "create_section_for_background"), $page, $value['grouping'], $value);
break;
case "padding":
add_settings_field($value['id'], '', array(&$this, "create_section_for_padding"), $page, $value['grouping'], $value);
break;
case "ajax-button":
add_settings_field($value['id'], '', array(&$this, "create_section_for_ajax_button"), $page, $value['grouping'], $value);
break;
case 'oauth-authorize':
add_settings_field($value['id'], '', array(&$this, "create_section_for_oauth_authorization"), $page, $value['grouping'], $value);
break;
}
}
}
function create_title($value) {
//echo '<h2 class="photonic-header-1">'.$value['name']."</h2>\n";
}
function create_section_for_radio($value) {
global $photonic_options;
$this->create_opening_tag($value);
foreach ($value['options'] as $option_value => $option_text) {
$option_value = stripslashes($option_value);
if (isset($photonic_options[$value['id']])) {
$checked = checked(stripslashes($photonic_options[$value['id']]), $option_value, false);
}
else {
$checked = checked($value['std'], $option_value, false);
}
echo '<div class="photonic-radio"><label><input type="radio" name="photonic_options['.$value['id'].']" value="'.$option_value.'" '.$checked."/>".$option_text."</label></div>\n";
}
$this->create_closing_tag($value);
}
function create_section_for_text($value) {
global $photonic_options;
$this->create_opening_tag($value);
if (!isset($photonic_options[$value['id']])) {
$text = $value['std'];
}
else {
$text = $photonic_options[$value['id']];
$text = stripslashes($text);
$text = esc_attr($text);
}
echo '<input type="text" name="photonic_options['.$value['id'].']" value="'.$text.'" />'."\n";
if (isset($value['hint'])) {
echo " « ".$value['hint']."<br />\n";
}
$this->create_closing_tag($value);
}
function create_section_for_textarea($value) {
global $photonic_options;
$this->create_opening_tag($value);
echo '<textarea name="photonic_options['.$value['id'].']" cols="" rows="">'."\n";
if (isset($photonic_options[$value['id']]) && $photonic_options[$value['id']] != "") {
$text = stripslashes($photonic_options[$value['id']]);
$text = esc_attr($text);
echo $text;
}
else {
echo $value['std'];
}
echo '</textarea>';
if (isset($value['hint'])) {
echo " « ".$value['hint']."<br />\n";
}
$this->create_closing_tag($value);
}
function create_section_for_select($value) {
global $photonic_options;
$this->create_opening_tag($value);
echo '<select name="photonic_options['.$value['id'].']">'."\n";
foreach ($value['options'] as $option_value => $option_text) {
echo "<option ";
if (isset($photonic_options[$value['id']])) {
selected($photonic_options[$value['id']], $option_value);
}
else {
selected($value['std'], $option_value);
}
echo " value='$option_value' >".$option_text."</option>\n";
}
echo "</select>\n";
$this->create_closing_tag($value);
}
/**
* Renders an option whose type is "slider". Invoked by add_settings_field.
*
* @param $value
* @return void
*/
function create_section_for_slider($value) {
global $photonic_options;
$this->create_opening_tag($value);
$options = $value['options'];
if (!isset($photonic_options[$value['id']])) {
$default = $value['std'];
}
else {
$default = $photonic_options[$value['id']];
}
?>
<script type="text/javascript">
$j = jQuery.noConflict();
$j(document).ready(function() {
$j("#<?php echo $value['id']; ?>-slider").slider({
range: "<?php echo $options['range']; ?>",
value: <?php echo (int)$default; ?>,
min: <?php echo $options['min']; ?>,
max: <?php echo $options['max']; ?>,
step: <?php echo $options['step']; ?>,
slide: function(event, ui) {
$j("input#<?php echo $value['id']; ?>").val(ui.value);
}
});
});
</script>
<div class='slider'>
<p>
<input type="text" id="<?php echo $value['id']; ?>" name="photonic_options[<?php echo $value['id']; ?>]" value="<?php echo $default; ?>" class='slidertext' /> <?php echo $options['unit'];?>
</p>
<div id="<?php echo $value['id']; ?>-slider" style="width:<?php echo $options['size'];?>;"></div>
</div>
<?php
$this->create_closing_tag($value);
}
function create_section_for_color_picker($value) {
global $photonic_options;
$this->create_opening_tag($value);
if (!isset($photonic_options[$value['id']])) {
$color_value = $value['std'];
}
else {
$color_value = $photonic_options[$value['id']];
}
if (substr($color_value, 0, 1) != '#') {
$color_value = "#$color_value";
}
echo '<div class="color-picker">'."\n";
echo '<input type="text" id="'.$value['id'].'" name="photonic_options['.$value['id'].']" value="'.$color_value.'" class="color color-'.$value['id'].'" /> <br/>'."\n";
echo "<strong>Default: ".$value['std']."</strong> (You can copy and paste this into the box above)\n";
echo "</div>\n";
$this->create_closing_tag($value);
}
function create_settings_section($section) {
$option_structure = $this->option_structure;
if ($this->displayed_sections != 0) {
echo "</form>\n";
echo "</div><!-- main-content -->\n";
}
echo "<div id='{$section['id']}' class='photonic-options-panel'> <!-- main-content -->\n";
echo "<form method=\"post\" action=\"options.php\" id=\"photonic-options-form-{$section['id']}\" class='photonic-options-form'>\n";
echo '<h3>' . $option_structure[$section['id']]['name'] . "</h3>\n";
/*
* We store all options in one array, but display them across multiple pages. Hence we need the following hack.
* We are registering the same setting across multiple pages, hence we need to pass the "page" parameter to options.php.
* Otherwise options.php returns an error saying "Options page not found"
*/
echo "<input type='hidden' name='page' value='" . esc_attr($_REQUEST['page']) . "' />\n";
if (!isset($_REQUEST['tab'])) {
$tab = 'theme-options-intro.php';
}
else {
$tab = esc_attr($_REQUEST['tab']);
}
echo "<input type='hidden' name='tab' value='" . $tab . "' />\n";
settings_fields("photonic_options-{$section['id']}");
if (!isset($option_structure[$section['id']]['buttons']) ||
($option_structure[$section['id']]['buttons'] != 'no-buttons' && $option_structure[$section['id']]['buttons'] != 'special-buttons')) {
echo "<div class=\"photonic-button-toggler fix\"><a href='#' class='photonic-button-toggler-{$section['id']}'><span class='photonic-button-toggler-{$section['id']}'>Save / Reset</span></a></div>\n";
echo "<div class=\"photonic-button-bar photonic-button-bar-{$section['id']}\" title='Save / Reset'>\n";
echo "<h2 class='fix'><a href='#'><img src='".plugins_url('/include/images/remove.png', __FILE__)."' alt='Close' /></a>Save / Reset</h2>\n";
echo "<input name=\"photonic_options[submit-{$section['id']}]\" type='submit' value=\"Save page '".esc_attr($option_structure[$section['id']]['name'])."'\" class=\"button photonic-button-section\" />\n";
echo "<input name=\"photonic_options[submit-{$section['id']}]\" type='submit' value=\"Reset page '".esc_attr($option_structure[$section['id']]['name'])."'\" class=\"button photonic-button-section\" />\n";
echo "<input name=\"photonic_options[submit-{$section['id']}]\" type='submit' value=\"Delete all options\" class=\"button photonic-button-all\" />\n";
echo "</div><!-- photonic-button-bar -->\n";
}
$this->displayed_sections++;
$this->previous_displayed_section = $section['id'];
}
function create_section_for_blurb($value) {
$this->create_opening_tag($value);
$this->create_closing_tag($value);
}
/**
* Renders an option whose type is "checkbox". Invoked by add_settings_field.
*
* @param $value
* @return void
*/
function create_section_for_checkbox($value) {
global $photonic_options;
$checked = '';
if (isset($photonic_options[$value['id']])) {
$checked = checked(stripslashes($photonic_options[$value['id']]), 'on', false);
}
$this->create_opening_tag($value);
echo '<label><input type="checkbox" name="photonic_options['.$value['id'].']" '.$checked."/>{$value['desc']}</label>\n";
$this->create_closing_tag($value);
}
/**
* Renders an option whose type is "border". Invoked by add_settings_field.
*
* @param $value
* @return void
*/
function create_section_for_border($value) {
global $photonic_options;
$this->create_opening_tag($value);
$original = $value['std'];
if (!isset($photonic_options[$value['id']])) {
$default = $value['std'];
$default_txt = "";
foreach ($value['std'] as $edge => $edge_val) {
$default_txt .= $edge.'::';
foreach ($edge_val as $opt => $opt_val) {
$default_txt .= $opt . "=" . $opt_val . ";";
}
$default_txt .= "||";
}
}
else {
$default_txt = $photonic_options[$value['id']];
$default = $default_txt;
$edge_array = explode('||', $default);
$default = array();
if (is_array($edge_array)) {
foreach ($edge_array as $edge_vals) {
if (trim($edge_vals) != '') {
$edge_val_array = explode('::', $edge_vals);
if (is_array($edge_val_array) && count($edge_val_array) > 1) {
$vals = explode(';', $edge_val_array[1]);
$default[$edge_val_array[0]] = array();
foreach ($vals as $val) {
$pair = explode("=", $val);
if (isset($pair[0]) && isset($pair[1])) {
$default[$edge_val_array[0]][$pair[0]] = $pair[1];
}
else if (isset($pair[0]) && !isset($pair[1])) {
$default[$edge_val_array[0]][$pair[0]] = "";
}
}
}
}
}
}
}
$edges = array('top' => 'Top', 'right' => 'Right', 'bottom' => 'Bottom', 'left' => 'Left');
$styles = array("none" => "No border",
"hidden" => "Hidden",
"dotted" => "Dotted",
"dashed" => "Dashed",
"solid" => "Solid",
"double" => "Double",
"grove" => "Groove",
"ridge" => "Ridge",
"inset" => "Inset",
"outset" => "Outset");
$border_width_units = array("px" => "Pixels (px)", "em" => "Em");
foreach ($value['options'] as $option_value => $option_text) {
if (isset($photonic_options[$value['id']])) {
$checked = checked($photonic_options[$value['id']], $option_value, false);
}
else {
$checked = checked($value['std'], $option_value, false);
}
echo '<div class="photonic-radio"><input type="radio" name="'.$value['id'].'" value="'.$option_value.'" '.$checked."/>".$option_text."</div>\n";
}
?>
<div class='photonic-border-options'>
<p>For any edge set style to "No Border" if you don't want a border.</p>
<table class='opt-sub-table-5'>
<col class='opt-sub-table-col-51'/>
<col class='opt-sub-table-col-5'/>
<col class='opt-sub-table-col-5'/>
<col class='opt-sub-table-col-5'/>
<col class='opt-sub-table-col-5'/>
<tr>
<th scope="col"> </th>
<th scope="col">Border Style</th>
<th scope="col">Color</th>
<th scope="col">Border Width</th>
<th scope="col">Border Width Units</th>
</tr>
<?php
foreach ($edges as $edge => $edge_text) {
?>
<tr>
<th scope="row"><?php echo $edge_text." border"; ?></th>
<td valign='top'>
<select name="<?php echo $value['id'].'-'.$edge; ?>-style" id="<?php echo $value['id'].'-'.$edge; ?>-style" >
<?php
foreach ($styles as $option_value => $option_text) {
echo "<option ";
if (isset($default[$edge]) && isset($default[$edge]['style'])) {
selected($default[$edge]['style'], $option_value);
}
echo " value='$option_value' >".$option_text."</option>\n";
}
?>
</select>
</td>
<td valign='top'>
<div class="color-picker-group">
<input type="radio" name="<?php echo $value['id'].'-'.$edge; ?>-colortype" value="transparent" <?php checked($default[$edge]['colortype'], 'transparent'); ?> /> Transparent / No color<br/>
<input type="radio" name="<?php echo $value['id'].'-'.$edge; ?>-colortype" value="custom" <?php checked($default[$edge]['colortype'], 'custom'); ?>/> Custom
<input type="text" id="<?php echo $value['id'].'-'.$edge; ?>-color" name="<?php echo $value['id']; ?>-color" value="<?php echo $default[$edge]['color']; ?>" class="color" /><br />
Default: <span> <?php echo $original[$edge]['color']; ?> </span>
</div>
</td>
<td valign='top'>
<input type="text" id="<?php echo $value['id'].'-'.$edge; ?>-border-width" name="<?php echo $value['id'].'-'.$edge; ?>-border-width" value="<?php echo $default[$edge]['border-width']; ?>" /><br />
</td>
<td valign='top'>
<select name="<?php echo $value['id'].'-'.$edge; ?>-border-width-type" id="<?php echo $value['id'].'-'.$edge; ?>-border-width-type" >
<?php
foreach ($border_width_units as $option_value => $option_text) {
echo "<option ";
selected($default[$edge]['border-width-type'], $option_value);
echo " value='$option_value' >".$option_text."</option>\n";
}
?>
</select>
</td>
</tr>
<?php
}
?>
</table>
<input type='hidden' id="<?php echo $value['id']; ?>" name="photonic_options[<?php echo $value['id']; ?>]" value="<?php echo $default_txt; ?>" />
</div>
<?php
$this->create_closing_tag($value);
}
/**
* Renders an option whose type is "background". Invoked by add_settings_field.
*
* @param $value
* @return void
*/
function create_section_for_background($value) {
global $photonic_options;
$this->create_opening_tag($value);
$original = $value['std'];
if (!isset($photonic_options[$value['id']])) {
$default = $value['std'];
$default_txt = "";
foreach ($value['std'] as $opt => $opt_val) {
$default_txt .= $opt."=".$opt_val.";";
}
}
else {
$default_txt = $photonic_options[$value['id']];
$default = $default_txt;
$vals = explode(";", $default);
$default = array();
foreach ($vals as $val) {
$pair = explode("=", $val);
if (isset($pair[0]) && isset($pair[1])) {
$default[$pair[0]] = $pair[1];
}
else if (isset($pair[0]) && !isset($pair[1])) {
$default[$pair[0]] = "";
}
}
}
$repeats = array("repeat" => "Repeat horizontally and vertically",
"repeat-x" => "Repeat horizontally only",
"repeat-y" => "Repeat vertically only",
"no-repeat" => "Do not repeat");
$positions = array("top left" => "Top left",
"top center" => "Top center",
"top right" => "Top right",
"center left" => "Center left",
"center center" => "Middle of the page",
"center right" => "Center right",
"bottom left" => "Bottom left",
"bottom center" => "Bottom center",
"bottom right" => "Bottom right");
foreach ($value['options'] as $option_value => $option_text) {
if (isset($photonic_options[$value['id']])) {
$checked = checked($photonic_options[$value['id']], $option_value, false);
}
else {
$checked = checked($value['std'], $option_value, false);
}
echo '<div class="photonic-radio"><input type="radio" name="'.$value['id'].'" value="'.$option_value.'" '.$checked."/>".$option_text."</div>\n";
}
?>
<div class='photonic-background-options'>
<table class='opt-sub-table'>
<col class='opt-sub-table-cols'/>
<col class='opt-sub-table-cols'/>
<tr>
<td valign='top'>
<div class="color-picker-group">
<strong>Background Color:</strong><br />
<input type="radio" name="<?php echo $value['id']; ?>-colortype" value="transparent" <?php checked($default['colortype'], 'transparent'); ?> /> Transparent / No color<br/>
<input type="radio" name="<?php echo $value['id']; ?>-colortype" value="custom" <?php checked($default['colortype'], 'custom'); ?>/> Custom
<input type="text" id="<?php echo $value['id']; ?>-bgcolor" name="<?php echo $value['id']; ?>-bgcolor" value="<?php echo $default['color']; ?>" class="color" /><br />
Default: <span> <?php echo $original['color']; ?> </span>
</div>
</td>
<td valign='top'>
<strong>Image URL:</strong><br />
<?php $this->display_upload_field($default['image'], $value['id']."-bgimg", $value['id']."-bgimg"); ?>
</td>
</tr>
<tr>
<td valign='top'>
<strong>Image Position:</strong><br />
<select name="<?php echo $value['id']; ?>-position" id="<?php echo $value['id']; ?>-position" >
<?php
foreach ($positions as $option_value => $option_text) {
echo "<option ";
selected($default['position'], $option_value);
echo " value='$option_value' >".$option_text."</option>\n";
}
?>
</select>
</td>
<td valign='top'>
<strong>Image Repeat:</strong><br />
<select name="<?php echo $value['id']; ?>-repeat" id="<?php echo $value['id']; ?>-repeat" >
<?php
foreach ($repeats as $option_value => $option_text) {
echo "<option ";
selected($default['repeat'], $option_value);
echo " value='$option_value' >".$option_text."</option>\n";
}
?>
</select>
</td>
</tr>
<tr>
<td valign='top' colspan='2'>
<script type="text/javascript">
$j = jQuery.noConflict();
$j(document).ready(function() {
$j("#<?php echo $value['id']; ?>-transslider").slider({
range: "min",
value: <?php echo (int)$default['trans']; ?>,
min: 0,
max: 100,
step: 1,
slide: function(event, ui) {
$j("input#<?php echo $value['id']; ?>-trans").val(ui.value);
$j("#<?php echo $value['id']; ?>").val('color=' + $j("#<?php echo $value['id']; ?>-bgcolor").val() + ';' +
'colortype=' + $j("input[name=<?php echo $value['id']; ?>-colortype]:checked").val() + ';' +
'image=' + $j("#<?php echo $value['id']; ?>-bgimg").val() + ';' +
'position=' + $j("#<?php echo $value['id']; ?>-position").val() + ';' +
'repeat=' + $j("#<?php echo $value['id']; ?>-repeat").val() + ';' +
'trans=' + $j("#<?php echo $value['id']; ?>-trans").val() + ';'
);
}
});
});
</script>
<div class='slider'>
<p>
<strong>Layer Transparency (not for IE):</strong>
<input type="text" id="<?php echo $value['id']; ?>-trans" name="<?php echo $value['id']; ?>-trans" value="<?php echo $default['trans']; ?>" class='slidertext' />
</p>
<div id="<?php echo $value['id']; ?>-transslider" class='transslider'></div>
</div>
</td>
</tr>
</table>
<input type='hidden' id="<?php echo $value['id']; ?>" name="photonic_options[<?php echo $value['id']; ?>]" value="<?php echo $default_txt; ?>" />
</div>
<?php
$this->create_closing_tag($value);
}
/**
* Renders an option whose type is "background". Invoked by add_settings_field.
*
* @param $value
* @return void
*/
function create_section_for_padding($value) {
global $photonic_options;
$this->create_opening_tag($value);
if (!isset($photonic_options[$value['id']])) {
$default = $value['std'];
$default_txt = "";
foreach ($value['std'] as $edge => $edge_val) {
$default_txt .= $edge.'::';
foreach ($edge_val as $opt => $opt_val) {
$default_txt .= $opt . "=" . $opt_val . ";";
}
$default_txt .= "||";
}
}
else {
$default_txt = $photonic_options[$value['id']];
$default = $default_txt;
$edge_array = explode('||', $default);
$default = array();
if (is_array($edge_array)) {
foreach ($edge_array as $edge_vals) {
if (trim($edge_vals) != '') {
$edge_val_array = explode('::', $edge_vals);
if (is_array($edge_val_array) && count($edge_val_array) > 1) {
$vals = explode(';', $edge_val_array[1]);
$default[$edge_val_array[0]] = array();
foreach ($vals as $val) {
$pair = explode("=", $val);
if (isset($pair[0]) && isset($pair[1])) {
$default[$edge_val_array[0]][$pair[0]] = $pair[1];
}
else if (isset($pair[0]) && !isset($pair[1])) {
$default[$edge_val_array[0]][$pair[0]] = "";
}
}
}
}
}
}
}
$edges = array('top' => 'Top', 'right' => 'Right', 'bottom' => 'Bottom', 'left' => 'Left');
$padding_units = array("px" => "Pixels (px)", "em" => "Em");
foreach ($value['options'] as $option_value => $option_text) {
if (isset($photonic_options[$value['id']])) {
$checked = checked($photonic_options[$value['id']], $option_value, false);
}
else {
$checked = checked($value['std'], $option_value, false);
}
echo '<div class="photonic-radio"><input type="radio" name="'.$value['id'].'" value="'.$option_value.'" '.$checked."/>".$option_text."</div>\n";
}
?>
<div class='photonic-padding-options'>
<table class='opt-sub-table-5'>
<col class='opt-sub-table-col-51'/>
<col class='opt-sub-table-col-5'/>
<col class='opt-sub-table-col-5'/>
<tr>
<th scope="col"> </th>
<th scope="col">Padding</th>
<th scope="col">Padding Units</th>
</tr>
<?php
foreach ($edges as $edge => $edge_text) {
?>
<tr>
<th scope="row"><?php echo $edge_text." padding"; ?></th>
<td valign='top'>
<input type="text" id="<?php echo $value['id'].'-'.$edge; ?>-padding" name="<?php echo $value['id'].'-'.$edge; ?>-padding" value="<?php echo $default[$edge]['padding']; ?>" /><br />
</td>
<td valign='top'>
<select name="<?php echo $value['id'].'-'.$edge; ?>-padding-type" id="<?php echo $value['id'].'-'.$edge; ?>-padding-type" >
<?php
foreach ($padding_units as $option_value => $option_text) {
echo "<option ";
selected($default[$edge]['padding-type'], $option_value);
echo " value='$option_value' >".$option_text."</option>\n";
}
?>
</select>
</td>
</tr>
<?php
}
?>
</table>
<input type='hidden' id="<?php echo $value['id']; ?>" name="photonic_options[<?php echo $value['id']; ?>]" value="<?php echo $default_txt; ?>" />
</div>
<?php
$this->create_closing_tag($value);
}
function create_section_for_ajax_button($value) {
$this->create_opening_tag($value);
//echo "<a href='' "
$this->create_closing_tag($value);
}
function create_section_for_oauth_authorization($value) {
$this->create_opening_tag($value);
echo "<a class='button oauth-authorize smugmug' href='".$value['link']."'>".$value['std']."</a>";
$this->create_closing_tag($value);
}
/**
* Creates the opening markup for each option.
*
* @param $value
* @return void
*/
function create_opening_tag($value) {
echo "<div class='photonic-section fix'>\n";
if (isset($value['name'])) {
echo "<h3>" . $value['name'] . "</h3>\n";
}
if (isset($value['desc']) && $value['type'] != 'checkbox') {
echo $value['desc']."<br />";
}
if (isset($value['note'])) {
echo "<span class=\"note\">".$value['note']."</span><br />";
}
}
/**
* Creates the closing markup for each option.
*
* @param $value
* @return void
*/
function create_closing_tag($value) {
echo "</div><!-- photonic-section -->\n";
}
/**
* This method displays an upload field and button. This has been separated from the create_section_for_upload method,
* because this is used by the create_section_for_background as well.
*
* @param $upload
* @param $id
* @param $name
* @param null $hint
* @return void
*/
function display_upload_field($upload, $id, $name, $hint = null) {
echo '<input type="text" name="'.$name.'" id="'.$id.'" value="'.$upload.'" />'."\n";
if ($hint != null) {
echo " « ".$hint."<br />\n";
}
}
function invoke_helper() {
if (isset($_POST['helper']) && !empty($_POST['helper'])) {
$helper = $_POST['helper'];
$photonic_options = get_option('photonic_options');
switch ($helper) {
case 'photonic-flickr-user-find':
$flickr_api_key = $photonic_options['flickr_api_key'];
$user = isset($_POST['photonic-flickr-user']) ? $_POST['photonic-flickr-user'] : '';
$url = 'https://api.flickr.com/services/rest/?format=json&nojsoncallback=1&api_key='.$flickr_api_key.'&method=flickr.urls.lookupUser&url='.$user;
$this->execute_query('flickr', $url, 'flickr.urls.lookupUser');
break;
case 'photonic-flickr-group-find':
$flickr_api_key = $photonic_options['flickr_api_key'];
$group = isset($_POST['photonic-flickr-group']) ? $_POST['photonic-flickr-group'] : '';
$url = 'https://api.flickr.com/services/rest/?format=json&nojsoncallback=1&api_key='.$flickr_api_key.'&method=flickr.urls.lookupGroup&url='.$group;
$this->execute_query('flickr', $url, 'flickr.urls.lookupGroup');
break;
case 'photonic-instagram-user-find':
$instagram_client_id = $photonic_options['instagram_client_id'];
$user = isset($_POST['photonic-instagram-user']) ? $_POST['photonic-instagram-user'] : '';
$url = 'https://api.instagram.com/v1/users/search?client_id='.$instagram_client_id.'&q='.$user;
$this->execute_query('instagram', $url, 'users/search');
break;
case 'photonic-instagram-location-find':
$instagram_client_id = $photonic_options['instagram_client_id'];
$lat = isset($_POST['photonic-instagram-lat']) ? $_POST['photonic-instagram-lat'] : '';
$lng = isset($_POST['photonic-instagram-lng']) ? $_POST['photonic-instagram-lng'] : '';
$fs_id = isset($_POST['photonic-instagram-fsid']) ? $_POST['photonic-instagram-fsid'] : '';
$url = 'https://api.instagram.com/v1/locations/search?client_id='.$instagram_client_id.'&lat='.$lat.'&lng='.$lng.'&foursquare_v2_id='.$fs_id;
$this->execute_query('instagram', $url, 'locations/search');
break;
case 'photonic-zenfolio-categories-find':
$url = 'https://api.zenfolio.com/api/1.6/zfapi.asmx/GetCategories';
$this->execute_query('zenfolio', $url, 'GetCategories');
break;
}
}
die();
}
function execute_query($where, $url, $method) {
$response = wp_remote_request($url, array('sslverify' => false));
if (!is_wp_error($response)) {
if (isset($response['response']) && isset($response['response']['code'])) {
if ($response['response']['code'] == 200) {
if (isset($response['body'])) {
if ($where == 'flickr') {
$this->execute_flickr_query($response['body'], $method);
}
else if ($where == 'instagram') {
$this->execute_instagram_query($response['body'], $method);
}
else if ($where == 'zenfolio') {
$this->execute_zenfolio_query($response['body'], $method);
}
}
else {
_e('<span class="found-id-text">No response from server!</span>', 'photonic');
}
}
else {
echo '<span class="found-id-text">'.$response['response']['message'].'</span>';
}
}
else {
_e('<span class="found-id-text">No response from server!</span>', 'photonic');
}
}
else {
_e('<span class="found-id-text">Cannot connect to the server. Please try later.</span>', 'photonic');
}
}
function execute_flickr_query($body, $method) {
$body = json_decode($body);
if (isset($body->stat) && $body->stat == 'fail') {
echo '<span class="found-id-text">'.$body->message.'</span>';
}
else {
if ($method == 'flickr.urls.lookupUser') {
if (isset($body->user)) {
echo '<span class="found-id-text">'.__('User ID:', 'photonic').'</span> <span class="found-id"><code>'.$body->user->id.'</code></span>';
}
}
else if ($method == 'flickr.urls.lookupGroup') {
if (isset($body->group)) {
echo '<span class="found-id-text">'.__('Group ID:', 'photonic').'</span> <span class="found-id"><code>'.$body->group->id.'</code></span>';
}
}
}
}
function execute_instagram_query($body, $method) {
$body = json_decode($body);
if (isset($body->meta) && isset($body->meta->code) && $body->meta->code == 200 && isset($body->data)) {
$data = $body->data;
if (count($data) == 0) {
if ($method == 'users/search') {
_e('<span class="found-id-text">User not found</span>', 'photonic');
}
else if ($method = 'locations/search') {
_e('<span class="found-id-text">Location not found</span>', 'photonic');
}
}
else if (count($data) == 1) {
if ($method == 'users/search') {
$user = $data[0];
$text = '<code>'.$user->id.'</code> ('.(!empty($user->full_name) ? $user->full_name : $user->username).')';
echo '<span class="found-id-text">'.__('User ID:', 'photonic').'</span> <span class="found-id">'.$text.'</span>';
}
else if ($method == 'locations/search') {
$location = $data[0];
$text = '<code>'.$location->id.'</code> ('.(!empty($location->name) ? $location->name : __('Name not available', 'photonic')).')';
echo '<span class="found-id-text">'.__('Location ID:', 'photonic').'</span> <span class="found-id">'.$text.'</span>';
}
}
else if (count($data) > 1) {
if ($method == 'users/search') {
$text = array();
foreach ($data as $user) {
$text[] = '<code>'.$user->id.'</code> ('.(!empty($user->full_name) ? $user->full_name : $user->username).')';
}
echo '<span class="found-id-text">'.__('Matching users:', 'photonic').'</span> <span class="found-id">'.implode(', ', $text).'</span>';
}
else if ($method == 'locations/search') {
$text = array();
foreach ($data as $location) {
$text[] = '<code>'.$location->id.'</code> ('.(!empty($location->name) ? $location->name : __('Name not available', 'photonic')).')';
}
echo '<span class="found-id-text">'.__('Matching locations:', 'photonic').'</span> <span class="found-id">'.implode(', ', $text).'</span>';
}
}
}
}
function execute_zenfolio_query($body, $method) {
if ($method == 'GetCategories') {
$response = simplexml_load_string($body);
if (!empty($response->Category)) {
$categories = $response->Category;
echo "<ul class='photonic-scroll-panel'>\n";
foreach ($categories as $category) {
echo "<li>{$category->DisplayName} – {$category->Code}</li>\n";
}
echo "</ul>\n";
}
}
}
}
| proj-2014/vlan247-test-wp2 | wp-content/plugins/tmp/photonic/photonic-options-manager.php | PHP | gpl-2.0 | 51,468 |
package com.aelitis.azureus.core.speedmanager.impl.v2;
import org.gudy.azureus2.core3.util.SystemTime;
import com.aelitis.azureus.core.speedmanager.SpeedManagerLimitEstimate;
import com.aelitis.azureus.core.speedmanager.SpeedManagerPingMapper;
import com.aelitis.azureus.core.speedmanager.SpeedManager;
import com.aelitis.azureus.core.speedmanager.impl.SpeedManagerAlgorithmProviderAdapter;
import java.util.List;
import java.util.ArrayList;
/**
* Created on Jul 16, 2007
* Created by Alan Snyder
* Copyright (C) 2007 Aelitis, All Rights Reserved.
* <p/>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* 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.
* <p/>
* AELITIS, SAS au capital de 63.529,40 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*/
public class PingSpaceMon
{
private static final long INTERVAL = 1000 * 60 * 15L;
long nextCheck = System.currentTimeMillis() + INTERVAL;
TransferMode mode;
List listeners = new ArrayList();//List<PSMonitorListener>
public void addListener(PSMonitorListener listener){
//don't register the same listener twice.
for(int i=0; i<listeners.size(); i++){
PSMonitorListener t = (PSMonitorListener) listeners.get(i);
if( t==listener ){
SpeedManagerLogger.trace("Not logging same listener twice. listener="+listener.toString());
return;
}
}
listeners.add( listener );
}
public boolean removeListener(PSMonitorListener listener){
return listeners.remove(listener);
}
boolean checkForLowerLimits(){
long curr = SystemTime.getCurrentTime();
if( curr > nextCheck ){
SpeedManagerLogger.trace("PingSpaceMon checking for lower limits.");
for(int i=0; i<listeners.size(); i++ ){
PSMonitorListener l =(PSMonitorListener) listeners.get(i);
if(l!=null){
l.notifyUpload( getUploadEstCapacity() );
}else{
SpeedManagerLogger.trace("listener index _"+i+"_ was null.");
}
}
resetTimer();
return true;
}
return false;
}
/**
*
* @param tMode -
* @return - true if is has a new mode, and the clock starts over.
*/
boolean updateStatus(TransferMode tMode){
if(mode==null){
mode=tMode;
return true;
}
if( mode.getMode() != tMode.getMode() ){
mode = tMode;
resetTimer();
return true;
}
return checkForLowerLimits();
}//updateStatus
void resetTimer(){
long curr = SystemTime.getCurrentTime();
nextCheck = curr + INTERVAL;
SpeedManagerLogger.trace("Monitor resetting time. Next check in interval.");
}
/**
* Get the current estimated upload limit from the ping mapper.
* @param - true if the long-term persistent result should be used.
* @return - SpeedManagerLimitEstimate.
*/
public static SpeedManagerLimitEstimate getUploadLimit(boolean persistent){
try{
SMInstance pm = SMInstance.getInstance();
SpeedManagerAlgorithmProviderAdapter adapter = pm.getAdapter();
SpeedManagerPingMapper persistentMap = adapter.getPingMapper();
SpeedManagerLimitEstimate upEst = persistentMap.getEstimatedUploadLimit(true);
return upEst;
}catch(Throwable t){
//log this event and
SpeedManagerLogger.log( t.toString() );
t.printStackTrace();
//something to return 1 and -1.0f results.
return new DefaultLimitEstimate();
}
}//getUploadLimit
public static SpeedManagerLimitEstimate getUploadEstCapacity()
{
try{
SMInstance pm = SMInstance.getInstance();
SpeedManagerAlgorithmProviderAdapter adapter = pm.getAdapter();
SpeedManager sm = adapter.getSpeedManager();
SpeedManagerLimitEstimate upEstCapacity = sm.getEstimatedUploadCapacityBytesPerSec();
return upEstCapacity;
}catch(Throwable t){
//log this event and
SpeedManagerLogger.log( t.toString() );
t.printStackTrace();
//something to return 1 and -1.0f results.
return new DefaultLimitEstimate();
}
}
/**
* Get the current estimated download limit from the ping mapper.
* @return - SpeedManagerLimitEstimate
*/
public static SpeedManagerLimitEstimate getDownloadLimit(){
try{
SMInstance pm = SMInstance.getInstance();
SpeedManagerAlgorithmProviderAdapter adapter = pm.getAdapter();
SpeedManagerPingMapper persistentMap = adapter.getPingMapper();
SpeedManagerLimitEstimate downEst = persistentMap.getEstimatedDownloadLimit(true);
return downEst;
}catch(Throwable t){
//log this event and
SpeedManagerLogger.log( t.toString() );
t.printStackTrace();
//something to return 0 and -1.0f results.
return new DefaultLimitEstimate();
}
}//getDownloadLimit
/**
* Get the estimated download capacity from the SpeedManager.
* @return - SpeedManagerLimitEstimate
*/
public static SpeedManagerLimitEstimate getDownloadEstCapacity()
{
try{
SMInstance pm = SMInstance.getInstance();
SpeedManagerAlgorithmProviderAdapter adapter = pm.getAdapter();
SpeedManager sm = adapter.getSpeedManager();
SpeedManagerLimitEstimate downEstCapacity = sm.getEstimatedDownloadCapacityBytesPerSec();
return downEstCapacity;
}catch(Throwable t){
//log this event and
SpeedManagerLogger.log( t.toString() );
t.printStackTrace();
//something to return 0 and -1.0f results.
return new DefaultLimitEstimate();
}
}
static class DefaultLimitEstimate implements SpeedManagerLimitEstimate
{
public int getBytesPerSec() {
return 1;
}
public float getEstimateType() {
return -1.0f;
}
public float getMetricRating() {
return -1.0f;
}
public int[][] getSegments() {
return new int[0][];
}
public long getWhen(){ return(0);}
public String getString() {
return "default";
}
}//class
}
| AcademicTorrents/AcademicTorrents-Downloader | vuze/com/aelitis/azureus/core/speedmanager/impl/v2/PingSpaceMon.java | Java | gpl-2.0 | 7,240 |
// -*- related-file-name: "../../lib/etheraddress64.cc" -*-
#ifndef CLICK_ETHERADDRESS64_HH
#define CLICK_ETHERADDRESS64_HH
#include <click/string.hh>
#include <click/glue.hh>
#include <click/type_traits.hh>
#if !CLICK_TOOL
# include <click/nameinfo.hh>
# include <click/standard/addressinfo.hh>
#endif
CLICK_DECLS
class EtherAddress64 {
public:
typedef uninitialized_type uninitialized_t;
/** @brief Construct an EtherAddress64 equal to 00-00-00-00-00-00-00-00. */
inline EtherAddress64() {
_data[0] = _data[1] = _data[2] = _data[3] = 0;
}
/** @brief Construct an EtherAddress from data.
* @param data the address data, in network byte order
*
* The bytes data[0]...data[7] are used to construct the address. */
explicit inline EtherAddress64(const unsigned char *data) {
memcpy(_data, data, 7);
}
/** @brief Construct an uninitialized EtherAddress64. */
inline EtherAddress64(const uninitialized_type &unused) {
(void) unused;
}
/** @brief Return the broadcast EtherAddress64, FF-FF-FF-FF-FF-FF-FF-FF. */
static EtherAddress64 make_broadcast() {
return EtherAddress64(0xFFFF);
}
typedef bool (EtherAddress64::*unspecified_bool_type)() const;
/** @brief Return true iff the address is not 00-00-00-00-00-00. */
inline operator unspecified_bool_type() const {
return _data[0] || _data[1] || _data[2] ? &EtherAddress64::is_group : 0;
}
/** @brief Return true iff this address is a group address.
*
* Group addresses have the low-order bit of the first byte set to 1, as
* in 01-00-00-00-00-00-00-00 or 03-00-00-02-04-09-04-02. */
inline bool is_group() const {
return data()[0] & 1;
}
/** @brief Return true iff this address is a "local" address.
*
* Local addresses have the next-to-lowest-order bit of the first byte set
* to 1. */
inline bool is_local() const {
return data()[0] & 2;
}
/** @brief Return true iff this address is the broadcast address.
*
* The Ethernet broadcast address is FF-FF-FF-FF-FF-FF-FF-FF. */
inline bool is_broadcast() const {
return _data[0] + _data[1] + _data[2] + _data[3] == 0x03FC;
}
/** @brief Return a pointer to the address data. */
inline unsigned char *data() {
return reinterpret_cast<unsigned char *>(_data);
}
/** @overload */
inline const unsigned char *data() const {
return reinterpret_cast<const unsigned char *>(_data);
}
/** @brief Return a pointer to the address data, as an array of
* uint16_ts. */
inline const uint16_t *sdata() const {
return _data;
}
/** @brief Hash function. */
inline size_t hashcode() const {
return (_data[2] | ((size_t) _data[1] << 16)) ^ ((size_t) _data[0] << 9);
}
/** @brief Unparse this address into a dash-separated hex String.
*
* Examples include "00-00-00-00-00-00-00-00" and "00-05-4E-50-3C-1A-BB-CC".
*
* @note The IEEE standard for printing Ethernet addresses uses dashes as
* separators, not colons. Use unparse_colon() to unparse into the
* nonstandard colon-separated form. */
inline String unparse() const {
return unparse_dash();
}
/** @brief Unparse this address into a colon-separated hex String.
*
* Examples include "00:00:00:00:00:00:00:00" and "00:05:4E:50:3C:1A:BB:CC".
*
* @note Use unparse() to create the IEEE standard dash-separated form. */
String unparse_colon() const;
/** @brief Unparse this address into a dash-separated hex String.
*
* Examples include "00-00-00-00-00-00-00-00" and "00-05-4E-50-3C-1A-BB-CC".
*
* @note This is the IEEE standard for printing Ethernet addresses.
* @sa unparse_colon */
String unparse_dash() const;
typedef const EtherAddress64 ¶meter_type;
private:
uint16_t _data[4];
EtherAddress64(uint16_t m) {
_data[0] = _data[1] = _data[2] = _data[3] = m;
}
} CLICK_SIZE_PACKED_ATTRIBUTE;
/** @relates EtherAddress64
@brief Compares two EtherAddress64 objects for equality. */
inline bool operator==(const EtherAddress64 &a, const EtherAddress64 &b) {
return (a.sdata()[0] == b.sdata()[0] &&
a.sdata()[1] == b.sdata()[1] &&
a.sdata()[2] == b.sdata()[2] &&
a.sdata()[3] == b.sdata()[3]);
}
/** @relates EtherAddress64
@brief Compares two EtherAddress64 objects for inequality. */
inline bool operator!=(const EtherAddress64 &a, const EtherAddress64 &b) {
return !(a == b);
}
class ArgContext;
class Args;
extern const ArgContext blank_args;
/** @class EtherAddress64Arg
@brief Parser class for Ethernet addresses.
This is the default parser for objects of EtherAddress64 type. For 8-byte
arrays like "click_ether::ether_shost" and "click_ether::ether_dhost", you
must pass an EtherAddressArg() explicitly:
@code
struct click_ether ethh;
... Args(...) ...
.read_mp("SRC", EtherAddressArg(), ethh.ether_shost)
...
@endcode */
class EtherAddress64Arg {
public:
typedef void enable_direct_parse;
static bool parse(const String &str, EtherAddress64 &value,
const ArgContext &args = blank_args);
static bool parse(const String &str, unsigned char *value,
const ArgContext &args = blank_args) {
return parse(str, *reinterpret_cast<EtherAddress64 *>(value), args);
}
static bool direct_parse(const String &str, EtherAddress64 &value,
Args &args);
static bool direct_parse(const String &str, unsigned char *value,
Args &args) {
return direct_parse(str, *reinterpret_cast<EtherAddress64 *>(value),
args);
}
};
template<> struct DefaultArg<EtherAddress64> : public EtherAddress64Arg {};
template<> struct has_trivial_copy<EtherAddress64> : public true_type {};
CLICK_ENDDECLS
#endif
| freedreamer/aa-click | include/click/etheraddress64.hh | C++ | gpl-2.0 | 5,515 |
package edu.stanford.nlp.ling.tokensregex;
import edu.stanford.nlp.ling.tokensregex.types.Expressions;
import edu.stanford.nlp.ling.tokensregex.types.Tags;
import edu.stanford.nlp.pipeline.CoreMapAggregator;
import edu.stanford.nlp.pipeline.CoreMapAttributeAggregator;
import java.util.function.Function;
import edu.stanford.nlp.process.CoreLabelTokenFactory;
import edu.stanford.nlp.util.Pair;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Holds environment variables to be used for compiling string into a pattern.
* Use {@link EnvLookup} to perform actual lookup (it will provide reasonable defaults)
*
* <p>
* Some of the types of variables to bind are:
* <ul>
* <li><code>SequencePattern</code> (compiled pattern)</li>
* <li><code>PatternExpr</code> (sequence pattern expression - precompiled)</li>
* <li><code>NodePattern</code> (pattern for matching one element)</li>
* <li><code>Class</code> (binding of CoreMap attribute to java Class)</li>
* </ul>
* </p>
*/
public class Env {
/**
* Parser that converts a string into a SequencePattern.
* @see edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser
*/
SequencePattern.Parser parser;
/**
* Mapping of variable names to their values
*/
Map<String, Object> variables = new HashMap<>();//Generics.newHashMap();
/**
* Mapping of per thread temporary variables to their values
*/
ThreadLocal<Map<String,Object>> threadLocalVariables = new ThreadLocal<>();
/**
* Mapping of variables that can be expanded in a regular expression for strings,
* to their regular expressions.
* The variable name must start with "$" and include only the alphanumeric characters
* (it should follow the pattern <code>$[A-Za-z0-9_]+</code>).
* Each variable is mapped to a pair, consisting of the <code>Pattern</code> representing
* the name of the variable to be replaced, and a <code>String</code> representing the
* regular expression (escaped) that is used to replace the name of the variable.
*/
Map<String, Pair<Pattern,String>> stringRegexVariables = new HashMap<>();//Generics.newHashMap();
/**
* Default parameters (used when reading in rules for {@link SequenceMatchRules}.
*/
public Map<String, Object> defaults = new HashMap<>();//Generics.newHashMap();
/**
* Default flags to use for string regular expressions match
* @see java.util.regex.Pattern#compile(String,int)
*/
public int defaultStringPatternFlags = 0;
/**
* Default flags to use for string literal match
* @see NodePattern#CASE_INSENSITIVE
*/
public int defaultStringMatchFlags = 0;
public Class sequenceMatchResultExtractor;
public Class stringMatchResultExtractor;
/**
* Annotation key to use to getting tokens (default is CoreAnnotations.TokensAnnotation.class)
*/
public Class defaultTokensAnnotationKey;
/**
* Annotation key to use to getting text (default is CoreAnnotations.TextAnnotation.class)
*/
public Class defaultTextAnnotationKey;
/**
* List of keys indicating the per-token annotations (default is null).
* If specified, each token will be annotated with the extracted results from the
* {@link #defaultResultsAnnotationExtractor}.
* If null, then individual tokens that are matched are not annotated.
*/
public List<Class> defaultTokensResultAnnotationKey;
/**
* List of keys indicating what fields should be annotated for the aggregated CoreMap.
* If specified, the aggregated CoreMap is annotated with the extracted results from the
* {@link #defaultResultsAnnotationExtractor}.
* If null, then the aggregated CoreMap is not annotated.
*/
public List<Class> defaultResultAnnotationKey;
/**
* Annotation key to use during composite phase for storing matched sequences and to match against.
*/
public Class defaultNestedResultsAnnotationKey;
/**
* How should the tokens be aggregated when collapsing a sequence of tokens into one CoreMap
*/
public Map<Class, CoreMapAttributeAggregator> defaultTokensAggregators;
private CoreMapAggregator defaultTokensAggregator;
/**
* Whether we should merge and output CoreLabels or not
*/
public boolean aggregateToTokens;
/**
* How annotations are extracted from the MatchedExpression.
* If the result type is a List and more than one annotation key is specified,
* then the result is paired with the annotation key.
* Example: If annotation key is [ner,normalized] and result is [CITY,San Francisco]
* then the final CoreMap will have ner=CITY, normalized=San Francisco.
* Otherwise, the result is treated as one object (all keys will be assigned that value).
*/
Function<MatchedExpression,?> defaultResultsAnnotationExtractor;
/**
* Interface for performing custom binding of values to the environment
*/
public interface Binder {
void init(String prefix, Properties props);
void bind(Env env);
}
public Env(SequencePattern.Parser p) { this.parser = p; }
public void initDefaultBindings() {
bind("FALSE", Expressions.FALSE);
bind("TRUE", Expressions.TRUE);
bind("NIL", Expressions.NIL);
bind("ENV", this);
bind("tags", Tags.TagsAnnotation.class);
}
public Map<String, Object> getDefaults() {
return defaults;
}
public void setDefaults(Map<String, Object> defaults) {
this.defaults = defaults;
}
public Map<Class, CoreMapAttributeAggregator> getDefaultTokensAggregators() {
return defaultTokensAggregators;
}
public void setDefaultTokensAggregators(Map<Class, CoreMapAttributeAggregator> defaultTokensAggregators) {
this.defaultTokensAggregators = defaultTokensAggregators;
}
public CoreMapAggregator getDefaultTokensAggregator() {
if (defaultTokensAggregator == null && (defaultTokensAggregators != null || aggregateToTokens)) {
CoreLabelTokenFactory tokenFactory = (aggregateToTokens)? new CoreLabelTokenFactory():null;
Map<Class, CoreMapAttributeAggregator> aggregators = defaultTokensAggregators;
if (aggregators == null) {
aggregators = CoreMapAttributeAggregator.DEFAULT_NUMERIC_TOKENS_AGGREGATORS;
}
defaultTokensAggregator = CoreMapAggregator.getAggregator(aggregators, null, tokenFactory);
}
return defaultTokensAggregator;
}
public Class getDefaultTextAnnotationKey() {
return defaultTextAnnotationKey;
}
public void setDefaultTextAnnotationKey(Class defaultTextAnnotationKey) {
this.defaultTextAnnotationKey = defaultTextAnnotationKey;
}
public Class getDefaultTokensAnnotationKey() {
return defaultTokensAnnotationKey;
}
public void setDefaultTokensAnnotationKey(Class defaultTokensAnnotationKey) {
this.defaultTokensAnnotationKey = defaultTokensAnnotationKey;
}
public List<Class> getDefaultTokensResultAnnotationKey() {
return defaultTokensResultAnnotationKey;
}
public void setDefaultTokensResultAnnotationKey(Class... defaultTokensResultAnnotationKey) {
this.defaultTokensResultAnnotationKey = Arrays.asList(defaultTokensResultAnnotationKey);
}
public void setDefaultTokensResultAnnotationKey(List<Class> defaultTokensResultAnnotationKey) {
this.defaultTokensResultAnnotationKey = defaultTokensResultAnnotationKey;
}
public List<Class> getDefaultResultAnnotationKey() {
return defaultResultAnnotationKey;
}
public void setDefaultResultAnnotationKey(Class... defaultResultAnnotationKey) {
this.defaultResultAnnotationKey = Arrays.asList(defaultResultAnnotationKey);
}
public void setDefaultResultAnnotationKey(List<Class> defaultResultAnnotationKey) {
this.defaultResultAnnotationKey = defaultResultAnnotationKey;
}
public Class getDefaultNestedResultsAnnotationKey() {
return defaultNestedResultsAnnotationKey;
}
public void setDefaultNestedResultsAnnotationKey(Class defaultNestedResultsAnnotationKey) {
this.defaultNestedResultsAnnotationKey = defaultNestedResultsAnnotationKey;
}
public Function<MatchedExpression, ?> getDefaultResultsAnnotationExtractor() {
return defaultResultsAnnotationExtractor;
}
public void setDefaultResultsAnnotationExtractor(Function<MatchedExpression, ?> defaultResultsAnnotationExtractor) {
this.defaultResultsAnnotationExtractor = defaultResultsAnnotationExtractor;
}
public Class getSequenceMatchResultExtractor() {
return sequenceMatchResultExtractor;
}
public void setSequenceMatchResultExtractor(Class sequenceMatchResultExtractor) {
this.sequenceMatchResultExtractor = sequenceMatchResultExtractor;
}
public Class getStringMatchResultExtractor() {
return stringMatchResultExtractor;
}
public void setStringMatchResultExtractor(Class stringMatchResultExtractor) {
this.stringMatchResultExtractor = stringMatchResultExtractor;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public void clearVariables() {
this.variables.clear();
}
public int getDefaultStringPatternFlags() {
return defaultStringPatternFlags;
}
public void setDefaultStringPatternFlags(int defaultStringPatternFlags) {
this.defaultStringPatternFlags = defaultStringPatternFlags;
}
public int getDefaultStringMatchFlags() {
return defaultStringMatchFlags;
}
public void setDefaultStringMatchFlags(int defaultStringMatchFlags) {
this.defaultStringMatchFlags = defaultStringMatchFlags;
}
private static final Pattern STRING_REGEX_VAR_NAME_PATTERN = Pattern.compile("\\$[A-Za-z0-9_]+");
public void bindStringRegex(String var, String regex)
{
// Enforce requirements on variable names ($alphanumeric_)
if (!STRING_REGEX_VAR_NAME_PATTERN.matcher(var).matches()) {
throw new IllegalArgumentException("StringRegex binding error: Invalid variable name " + var);
}
Pattern varPattern = Pattern.compile(Pattern.quote(var));
String replace = Matcher.quoteReplacement(regex);
stringRegexVariables.put(var, new Pair<>(varPattern, replace));
}
public String expandStringRegex(String regex) {
// Replace all variables in regex
String expanded = regex;
for (Map.Entry<String, Pair<Pattern, String>> stringPairEntry : stringRegexVariables.entrySet()) {
Pair<Pattern,String> p = stringPairEntry.getValue();
expanded = p.first().matcher(expanded).replaceAll(p.second());
}
return expanded;
}
public Pattern getStringPattern(String regex)
{
String expanded = expandStringRegex(regex);
return Pattern.compile(expanded, defaultStringPatternFlags);
}
public void bind(String name, Object obj) {
if (obj != null) {
variables.put(name, obj);
} else {
variables.remove(name);
}
}
public void bind(String name, SequencePattern pattern) {
bind(name, pattern.getPatternExpr());
}
public void unbind(String name) {
bind(name, null);
}
public NodePattern getNodePattern(String name)
{
Object obj = variables.get(name);
if (obj != null) {
if (obj instanceof SequencePattern) {
SequencePattern seqPattern = (SequencePattern) obj;
if (seqPattern.getPatternExpr() instanceof SequencePattern.NodePatternExpr) {
return ((SequencePattern.NodePatternExpr) seqPattern.getPatternExpr()).nodePattern;
} else {
throw new Error("Invalid node pattern class: " + seqPattern.getPatternExpr().getClass() + " for variable " + name);
}
} else if (obj instanceof SequencePattern.NodePatternExpr) {
SequencePattern.NodePatternExpr pe = (SequencePattern.NodePatternExpr) obj;
return pe.nodePattern;
} else if (obj instanceof NodePattern) {
return (NodePattern) obj;
} else if (obj instanceof String) {
try {
SequencePattern.NodePatternExpr pe = (SequencePattern.NodePatternExpr) parser.parseNode(this, (String) obj);
return pe.nodePattern;
} catch (Exception pex) {
throw new RuntimeException("Error parsing " + obj + " to node pattern", pex);
}
} else {
throw new Error("Invalid node pattern variable class: " + obj.getClass() + " for variable " + name);
}
}
return null;
}
public SequencePattern.PatternExpr getSequencePatternExpr(String name, boolean copy)
{
Object obj = variables.get(name);
if (obj != null) {
if (obj instanceof SequencePattern) {
SequencePattern seqPattern = (SequencePattern) obj;
return seqPattern.getPatternExpr();
} else if (obj instanceof SequencePattern.PatternExpr) {
SequencePattern.PatternExpr pe = (SequencePattern.PatternExpr) obj;
return (copy)? pe.copy():pe;
} else if (obj instanceof NodePattern) {
return new SequencePattern.NodePatternExpr( (NodePattern) obj);
} else if (obj instanceof String) {
try {
return parser.parseSequence(this, (String) obj);
} catch (Exception pex) {
throw new RuntimeException("Error parsing " + obj + " to sequence pattern", pex);
}
} else {
throw new Error("Invalid sequence pattern variable class: " + obj.getClass());
}
}
return null;
}
public Object get(String name)
{
return variables.get(name);
}
// Functions for storing temporary thread specific variables
// that are used when running tokensregex
public void push(String name, Object value) {
Map<String,Object> vars = threadLocalVariables.get();
if (vars == null) {
threadLocalVariables.set(vars = new HashMap<>()); //Generics.newHashMap());
}
Stack<Object> stack = (Stack<Object>) vars.get(name);
if (stack == null) {
vars.put(name, stack = new Stack<>());
}
stack.push(value);
}
public Object pop(String name) {
Map<String,Object> vars = threadLocalVariables.get();
if (vars == null) return null;
Stack<Object> stack = (Stack<Object>) vars.get(name);
if (stack == null || stack.isEmpty()) {
return null;
} else {
return stack.pop();
}
}
public Object peek(String name) {
Map<String,Object> vars = threadLocalVariables.get();
if (vars == null) return null;
Stack<Object> stack = (Stack<Object>) vars.get(name);
if (stack == null || stack.isEmpty()) {
return null;
} else {
return stack.peek();
}
}
}
| hbbpb/stanford-corenlp-gv | src/edu/stanford/nlp/ling/tokensregex/Env.java | Java | gpl-2.0 | 14,483 |
/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <NdbDictionary.hpp>
/*
* Move data between "compatible" tables.
*
* Uses batches of insert-into-target / delete-from-source.
* Compared to copying alter table, the advantages are
* 1) does not need double storage 2) can be restarted
* after temporary failure.
*
* Use init() to define source / target and then move_data().
* Methods return -1 on error and 0 on success. On temporary
* error call move_data() again to continue.
*
* Use get_error() for details. Negative error code means
* non-recoverable error. Positive error code is ndb error
* which may be temporary.
*
* Like ndb_restore, remaps columns based on name.
*
* Used from ndb_restore for char<->text conversion. Here
* user pre-creates the new table and then loads data into it
* via ndb_restore -r. This first loads data into a temporary
* "staging table" which has same structure as table in backup.
* Then move_data() is called to move data into the new table.
*
* Current version handles data conversions between all char,
* binary, text, blob types.
*
* The conversion methods should be unified with ndb_restore.
* Missing cases (date and numeric types) should be added.
*/
struct Ndb_move_data {
struct Opts {
enum {
MD_ABORT_ON_ERROR = 0x1,
MD_EXCLUDE_MISSING_COLUMNS = 0x2,
MD_ATTRIBUTE_PROMOTION = 0x4,
MD_ATTRIBUTE_DEMOTION = 0x8
};
int flags;
// for parsing --staging-tries (but caller handles retries)
struct Tries {
int maxtries; // 0 = no limit
int mindelay;
int maxdelay;
Tries() : maxtries(0), mindelay(1000), maxdelay(60*1000) {}
};
Opts();
};
struct Stat {
Uint64 rows_moved; // in current move_data() call
Uint64 rows_total; // total moved so far
Uint64 truncated; // truncated attributes so far
Stat();
};
struct Error {
enum {
InvalidState = -101,
InvalidSource = -102,
InvalidTarget = -103,
UnsupportedConversion = -201,
NoExcludeMissingFlag = -202,
NoPromotionFlag = -203,
NoDemotionFlag = -204,
DataTruncated = -301
};
int line;
int code;
char message[512];
NdbError ndberror; // valid if code > 0
bool is_temporary() const;
Error();
};
Ndb_move_data();
~Ndb_move_data();
int init(const NdbDictionary::Table* source,
const NdbDictionary::Table* target);
void set_opts_flags(int flags);
static void unparse_opts_tries(char* opt, const Opts::Tries& ot);
static int parse_opts_tries(const char* opt, Opts::Tries& retry);
int move_data(Ndb* ndb);
void error_insert(); // insert random temporary error
const Stat& get_stat();
const Error& get_error();
private:
const NdbDictionary::Table* m_source; // source rows moved from
const NdbDictionary::Table* m_target; // target rows moved to
struct Attr {
enum {
TypeNone = 0,
TypeArray,
TypeBlob,
TypeOther
};
const NdbDictionary::Column* column;
const char* name;
int id; // own id (array index)
int map_id; // column id in other table
int type;
Uint32 size_in_bytes;
Uint32 length_bytes;
Uint32 data_size; // size_in_bytes - length_bytes
int pad_char;
bool equal; // attr1,attr2 equal non-blobs
Attr();
};
Attr* m_sourceattr;
Attr* m_targetattr;
void set_type(Attr& attr, const NdbDictionary::Column* c);
int check_nopk(const Attr& attr1, const Attr& attr2);
int check_promotion(const Attr& attr1, const Attr& attr2);
int check_demotion(const Attr& attr1, const Attr& attr2);
int check_sizes(const Attr& attr1, const Attr& attr2);
int check_unsupported(const Attr& attr1, const Attr& attr2);
int check_tables();
struct Data {
char* data;
Data* next;
Data();
~Data();
};
Data* m_data; // blob data for the batch, used for blob2blob
char* alloc_data(Uint32 n);
void release_data();
struct Op {
Ndb* ndb;
NdbTransaction* scantrans;
NdbScanOperation* scanop;
NdbTransaction* updatetrans;
NdbOperation* updateop;
union Value {
NdbRecAttr* ra;
NdbBlob* bh;
};
Value* values;
int buflen;
char* buf1;
char* buf2;
Uint32 rows_in_batch;
Uint32 truncated_in_batch;
bool end_of_scan;
Op();
~Op();
};
Op m_op;
int start_scan();
int copy_other_to_other(const Attr& attr1, const Attr& attr2);
int copy_data_to_array(const char* data1, const Attr& attr2,
Uint32 length1, Uint32 length1x);
int copy_array_to_array(const Attr& attr1, const Attr& attr2);
int copy_array_to_blob(const Attr& attr1, const Attr& attr2);
int copy_blob_to_array(const Attr& attr1, const Attr& attr2);
int copy_blob_to_blob(const Attr& attr1, const Attr& attr2);
int copy_attr(const Attr& attr1, const Attr& attr2);
int move_row();
int move_batch();
void close_op(Ndb* ndb, int ret);
Opts m_opts;
Stat m_stat;
Error m_error;
void set_error_line(int line);
void set_error_code(int code, const char* fmt, ...);
void set_error_code(const NdbError& ndberror);
void reset_error();
friend class NdbOut& operator<<(NdbOut&, const Error&);
bool m_error_insert;
void invoke_error_insert();
void abort_on_error();
};
| ForcerKing/ShaoqunXu-mysql5.7 | storage/ndb/tools/ndb_lib_move_data.hpp | C++ | gpl-2.0 | 5,975 |
/* $Id: symlink-posix.cpp $ */
/** @file
* IPRT - Symbolic Links, POSIX.
*/
/*
* Copyright (C) 2010-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP RTLOGGROUP_SYMLINK
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iprt/symlink.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/log.h>
#include <iprt/mem.h>
#include <iprt/string.h>
#include "internal/path.h"
RTDECL(bool) RTSymlinkExists(const char *pszSymlink)
{
bool fRc = false;
char const *pszNativeSymlink;
int rc = rtPathToNative(&pszNativeSymlink, pszSymlink, NULL);
if (RT_SUCCESS(rc))
{
struct stat s;
fRc = !lstat(pszNativeSymlink, &s)
&& S_ISLNK(s.st_mode);
rtPathFreeNative(pszNativeSymlink, pszSymlink);
}
LogFlow(("RTSymlinkExists(%p={%s}): returns %RTbool\n", pszSymlink, pszSymlink, fRc));
return fRc;
}
RTDECL(bool) RTSymlinkIsDangling(const char *pszSymlink)
{
bool fRc = false;
char const *pszNativeSymlink;
int rc = rtPathToNative(&pszNativeSymlink, pszSymlink, NULL);
if (RT_SUCCESS(rc))
{
struct stat s;
fRc = !lstat(pszNativeSymlink, &s)
&& S_ISLNK(s.st_mode);
if (fRc)
{
errno = 0;
fRc = stat(pszNativeSymlink, &s) != 0
&& ( errno == ENOENT
|| errno == ENOTDIR
|| errno == ELOOP);
}
rtPathFreeNative(pszNativeSymlink, pszSymlink);
}
LogFlow(("RTSymlinkIsDangling(%p={%s}): returns %RTbool\n", pszSymlink, pszSymlink, fRc));
return fRc;
}
RTDECL(int) RTSymlinkCreate(const char *pszSymlink, const char *pszTarget, RTSYMLINKTYPE enmType, uint32_t fCreate)
{
/*
* Validate the input.
*/
AssertReturn(enmType > RTSYMLINKTYPE_INVALID && enmType < RTSYMLINKTYPE_END, VERR_INVALID_PARAMETER);
AssertPtrReturn(pszSymlink, VERR_INVALID_POINTER);
AssertPtrReturn(pszTarget, VERR_INVALID_POINTER);
/*
* Convert the paths.
*/
char const *pszNativeSymlink;
int rc = rtPathToNative(&pszNativeSymlink, pszSymlink, NULL);
if (RT_SUCCESS(rc))
{
const char *pszNativeTarget;
rc = rtPathToNative(&pszNativeTarget, pszTarget, NULL);
if (RT_SUCCESS(rc))
{
/*
* Create the link.
*/
if (symlink(pszNativeTarget, pszNativeSymlink) == 0)
rc = VINF_SUCCESS;
else
rc = RTErrConvertFromErrno(errno);
rtPathFreeNative(pszNativeTarget, pszTarget);
}
rtPathFreeNative(pszNativeSymlink, pszSymlink);
}
LogFlow(("RTSymlinkCreate(%p={%s}, %p={%s}, %d, %#x): returns %Rrc\n", pszSymlink, pszSymlink, pszTarget, pszTarget, enmType, fCreate, rc));
return rc;
}
RTDECL(int) RTSymlinkDelete(const char *pszSymlink, uint32_t fDelete)
{
char const *pszNativeSymlink;
int rc = rtPathToNative(&pszNativeSymlink, pszSymlink, NULL);
if (RT_SUCCESS(rc))
{
struct stat s;
if (!lstat(pszNativeSymlink, &s))
{
if (S_ISLNK(s.st_mode))
{
if (unlink(pszNativeSymlink) == 0)
rc = VINF_SUCCESS;
else
rc = RTErrConvertFromErrno(errno);
}
else
rc = VERR_NOT_SYMLINK;
}
else
rc = RTErrConvertFromErrno(errno);
rtPathFreeNative(pszNativeSymlink, pszSymlink);
}
LogFlow(("RTSymlinkDelete(%p={%s}, #%x): returns %Rrc\n", pszSymlink, pszSymlink, fDelete, rc));
return rc;
}
RTDECL(int) RTSymlinkRead(const char *pszSymlink, char *pszTarget, size_t cbTarget, uint32_t fRead)
{
char *pszMyTarget;
int rc = RTSymlinkReadA(pszSymlink, &pszMyTarget);
if (RT_SUCCESS(rc))
{
rc = RTStrCopy(pszTarget, cbTarget, pszMyTarget);
RTStrFree(pszMyTarget);
}
LogFlow(("RTSymlinkRead(%p={%s}): returns %Rrc\n", pszSymlink, pszSymlink, rc));
return rc;
}
RTDECL(int) RTSymlinkReadA(const char *pszSymlink, char **ppszTarget)
{
AssertPtr(ppszTarget);
char const *pszNativeSymlink;
int rc = rtPathToNative(&pszNativeSymlink, pszSymlink, NULL);
if (RT_SUCCESS(rc))
{
/* Guess the initial buffer size. */
ssize_t cbBuf;
struct stat s;
if (!lstat(pszNativeSymlink, &s))
cbBuf = RT_MIN(RT_ALIGN_Z(s.st_size, 64), 64);
else
cbBuf = 1024;
/* Read loop that grows the buffer. */
char *pszBuf = NULL;
for (;;)
{
RTMemTmpFree(pszBuf);
pszBuf = (char *)RTMemTmpAlloc(cbBuf);
if (pszBuf)
{
ssize_t cbReturned = readlink(pszNativeSymlink, pszBuf, cbBuf);
if (cbReturned >= cbBuf)
{
/* Increase the buffer size and try again */
cbBuf *= 2;
continue;
}
if (cbReturned > 0)
{
pszBuf[cbReturned] = '\0';
rc = rtPathFromNativeDup(ppszTarget, pszBuf, pszSymlink);
}
else if (errno == EINVAL)
rc = VERR_NOT_SYMLINK;
else
rc = RTErrConvertFromErrno(errno);
}
else
rc = VERR_NO_TMP_MEMORY;
break;
} /* for loop */
RTMemTmpFree(pszBuf);
rtPathFreeNative(pszNativeSymlink, pszSymlink);
}
if (RT_SUCCESS(rc))
LogFlow(("RTSymlinkReadA(%p={%s},%p): returns %Rrc *ppszTarget=%p:{%s}\n", pszSymlink, pszSymlink, ppszTarget, rc, *ppszTarget, *ppszTarget));
else
LogFlow(("RTSymlinkReadA(%p={%s},%p): returns %Rrc\n", pszSymlink, pszSymlink, ppszTarget, rc));
return rc;
}
| sobomax/virtualbox_64bit_edd | src/VBox/Runtime/r3/posix/symlink-posix.cpp | C++ | gpl-2.0 | 7,083 |
/*
Copyright (c) 2004-2008, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/book/dojo-book-0-9/introduction/licensing
*/
if(!dojo._hasResource["dijit.form.TimeTextBox"]){
dojo._hasResource["dijit.form.TimeTextBox"]=true;
dojo.provide("dijit.form.TimeTextBox");
dojo.require("dijit._TimePicker");
dojo.require("dijit.form._DateTimeTextBox");
dojo.declare("dijit.form.TimeTextBox",dijit.form._DateTimeTextBox,{popupClass:"dijit._TimePicker",_selector:"time"});
}
| btribulski/girlsknowhow | sites/all/modules/civicrm/packages/dojo/dijit/form/TimeTextBox.js | JavaScript | gpl-2.0 | 623 |
/*
* Copyright (c) 2013, 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.
*/
/*
* @test WhiteBox
* @bug 8011675
* @summary verify that whitebox can be used even if not all functions are declared in java-part
* @author igor.ignatyev@oracle.com
* @library /testlibrary
* @compile WhiteBox.java
* @run main ClassFileInstaller sun.hotspot.WhiteBox
* @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI sun.hotspot.WhiteBox
* @clean sun.hotspot.WhiteBox
*/
package sun.hotspot;
public class WhiteBox {
private static native void registerNatives();
static { registerNatives(); }
public native int notExistedMethod();
public native int getHeapOopSize();
public static void main(String[] args) {
WhiteBox wb = new WhiteBox();
if (wb.getHeapOopSize() < 0) {
throw new Error("wb.getHeapOopSize() < 0");
}
boolean catched = false;
try {
wb.notExistedMethod();
} catch (UnsatisfiedLinkError e) {
catched = true;
}
if (!catched) {
throw new Error("wb.notExistedMethod() was invoked");
}
}
}
| netroby/jdk9-shenandoah-hotspot | test/sanity/WhiteBox.java | Java | gpl-2.0 | 2,149 |
var searchData=
[
['queuefree',['queueFree',['../struct_ticker_state.html#a942a4c5388669138ad9518b3e14c3cb4',1,'TickerState']]],
['queueused',['queueUsed',['../struct_ticker_state.html#a99d84731b9512a573efd4d40d1ce6b07',1,'TickerState']]]
];
| Code-Forge-Lab/Arduino | arduino library/libraries/SSD1306Ascii-SmallSize10/doc/html/search/functions_a.js | JavaScript | gpl-2.0 | 246 |
# -*- encoding: utf-8 -*-
from openerp.osv import fields, osv
from openerp.tools.translate import _
class sale_order_line(osv.Model):
"""
OpenERP Model : sale_order_line
"""
_inherit = 'sale.order.line'
_columns = {
'att_bro': fields.boolean('Attach Brochure', required=False, help="""If you check this
option, the first attachment related to the product_id marked as brochure will be printed
as extra info with sale order"""),
}
class sale_order(osv.Model):
"""
OpenERP Model : sale_order_line
"""
_inherit = 'sale.order'
def print_with_attachment(self, cr, user, ids, context={}):
for o in self.browse(cr, user, ids, context):
for ol in o.order_line:
if ol.att_bro:
print "Im Here i will go to print %s " % ol.name
return True
def __get_company_object(self, cr, uid):
user = self.pool.get('res.users').browse(cr, uid, uid)
print user
if not user.company_id:
raise except_osv(_('ERROR !'), _(
'There is no company configured for this user'))
return user.company_id
def _get_report_name(self, cr, uid, context):
report = self.__get_company_object(cr, uid).sale_report_id
if not report:
rep_id = self.pool.get("ir.actions.report.xml").search(
cr, uid, [('model', '=', 'sale.order'), ], order="id")[0]
report = self.pool.get(
"ir.actions.report.xml").browse(cr, uid, rep_id)
return report.report_name
def print_quotation(self, cr, uid, ids, context=None):
pq = super(sale_order, self).print_quotation(cr,uid,ids, context)
return {'type': 'ir.actions.report.xml', 'report_name': self._get_report_name(cr, uid,
context), 'datas': pq['datas'], 'nodestroy': True}
| 3dfxsoftware/cbss-addons | sale_multicompany_report/order.py | Python | gpl-2.0 | 1,880 |
<?php
/**
*
* @package phpBB3
* @version $Id$
* @copyright (c) 2005 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
exit;
}
/**
* Transfer class, wrapper for ftp/sftp/ssh
* @package phpBB3
*/
class transfer
{
var $connection;
var $host;
var $port;
var $username;
var $password;
var $timeout;
var $root_path;
var $tmp_path;
var $file_perms;
var $dir_perms;
/**
* Constructor - init some basic values
*/
function transfer()
{
global $phpbb_root_path;
$this->file_perms = 0644;
$this->dir_perms = 0777;
// We use the store directory as temporary path to circumvent open basedir restrictions
$this->tmp_path = $phpbb_root_path . 'store/';
}
/**
* Write file to location
*/
function write_file($destination_file = '', $contents = '')
{
global $phpbb_root_path;
$destination_file = $this->root_path . str_replace($phpbb_root_path, '', $destination_file);
// need to create a temp file and then move that temp file.
// ftp functions can only move files around and can't create.
// This means that the users will need to have access to write
// temporary files or have write access on a folder within phpBB
// like the cache folder. If the user can't do either, then
// he/she needs to use the fsock ftp method
$temp_name = tempnam($this->tmp_path, 'transfer_');
@unlink($temp_name);
$fp = @fopen($temp_name, 'w');
if (!$fp)
{
trigger_error('Unable to create temporary file ' . $temp_name, E_USER_ERROR);
}
@fwrite($fp, $contents);
@fclose($fp);
$result = $this->overwrite_file($temp_name, $destination_file);
// remove temporary file now
@unlink($temp_name);
return $result;
}
/**
* Moving file into location. If the destination file already exists it gets overwritten
*/
function overwrite_file($source_file, $destination_file)
{
/**
* @todo generally think about overwriting files in another way, by creating a temporary file and then renaming it
* @todo check for the destination file existance too
*/
$this->_delete($destination_file);
$result = $this->_put($source_file, $destination_file);
$this->_chmod($destination_file, $this->file_perms);
return $result;
}
/**
* Create directory structure
*/
function make_dir($dir)
{
global $phpbb_root_path;
$dir = str_replace($phpbb_root_path, '', $dir);
$dir = explode('/', $dir);
$dirs = '';
for ($i = 0, $total = sizeof($dir); $i < $total; $i++)
{
$result = true;
if (strpos($dir[$i], '.') === 0)
{
continue;
}
$cur_dir = $dir[$i] . '/';
if (!file_exists($phpbb_root_path . $dirs . $cur_dir))
{
// create the directory
$result = $this->_mkdir($dir[$i]);
$this->_chmod($dir[$i], $this->dir_perms);
}
$this->_chdir($this->root_path . $dirs . $dir[$i]);
$dirs .= $cur_dir;
}
$this->_chdir($this->root_path);
/**
* @todo stack result into array to make sure every path creation has been taken care of
*/
return $result;
}
/**
* Copy file from source location to destination location
*/
function copy_file($from_loc, $to_loc)
{
global $phpbb_root_path;
$from_loc = ((strpos($from_loc, $phpbb_root_path) !== 0) ? $phpbb_root_path : '') . $from_loc;
$to_loc = $this->root_path . str_replace($phpbb_root_path, '', $to_loc);
if (!file_exists($from_loc))
{
return false;
}
$result = $this->overwrite_file($from_loc, $to_loc);
return $result;
}
/**
* Remove file
*/
function delete_file($file)
{
global $phpbb_root_path;
$file = $this->root_path . str_replace($phpbb_root_path, '', $file);
return $this->_delete($file);
}
/**
* Remove directory
* @todo remove child directories?
*/
function remove_dir($dir)
{
global $phpbb_root_path;
$dir = $this->root_path . str_replace($phpbb_root_path, '', $dir);
return $this->_rmdir($dir);
}
/**
* Rename a file or folder
*/
function rename($old_handle, $new_handle)
{
global $phpbb_root_path;
$old_handle = $this->root_path . str_replace($phpbb_root_path, '', $old_handle);
return $this->_rename($old_handle, $new_handle);
}
/**
* Check if a specified file exist...
*/
function file_exists($directory, $filename)
{
global $phpbb_root_path;
$directory = $this->root_path . str_replace($phpbb_root_path, '', $directory);
$this->_chdir($directory);
$result = $this->_ls();
if ($result !== false && is_array($result))
{
return (in_array($filename, $result)) ? true : false;
}
return false;
}
/**
* Open session
*/
function open_session()
{
return $this->_init();
}
/**
* Close current session
*/
function close_session()
{
return $this->_close();
}
/**
* Determine methods able to be used
*/
function methods()
{
$methods = array();
$disabled_functions = explode(',', @ini_get('disable_functions'));
if (@extension_loaded('ftp'))
{
$methods[] = 'ftp';
}
if (!in_array('fsockopen', $disabled_functions))
{
$methods[] = 'ftp_fsock';
}
return $methods;
}
}
/**
* FTP transfer class
* @package phpBB3
*/
class ftp extends transfer
{
/**
* Standard parameters for FTP session
*/
function ftp($host, $username, $password, $root_path, $port = 21, $timeout = 10)
{
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
$this->timeout = $timeout;
// Make sure $this->root_path is layed out the same way as the $user->page['root_script_path'] value (/ at the end)
$this->root_path = str_replace('\\', '/', $this->root_path);
if (!empty($root_path))
{
$this->root_path = (($root_path[0] != '/' ) ? '/' : '') . $root_path . ((substr($root_path, -1, 1) == '/') ? '' : '/');
}
// Init some needed values
transfer::transfer();
return;
}
/**
* Requests data
*/
function data()
{
global $user;
return array(
'host' => 'localhost',
'username' => 'anonymous',
'password' => '',
'root_path' => $user->page['root_script_path'],
'port' => 21,
'timeout' => 10
);
}
/**
* Init FTP Session
* @access private
*/
function _init()
{
// connect to the server
$this->connection = @ftp_connect($this->host, $this->port, $this->timeout);
if (!$this->connection)
{
return 'ERR_CONNECTING_SERVER';
}
// login to the server
if (!@ftp_login($this->connection, $this->username, $this->password))
{
return 'ERR_UNABLE_TO_LOGIN';
}
// attempt to turn pasv mode on
@ftp_pasv($this->connection, true);
// change to the root directory
if (!$this->_chdir($this->root_path))
{
return 'ERR_CHANGING_DIRECTORY';
}
return true;
}
/**
* Create Directory (MKDIR)
* @access private
*/
function _mkdir($dir)
{
return @ftp_mkdir($this->connection, $dir);
}
/**
* Remove directory (RMDIR)
* @access private
*/
function _rmdir($dir)
{
return @ftp_rmdir($this->connection, $dir);
}
/**
* Rename file
* @access private
*/
function _rename($old_handle, $new_handle)
{
return @ftp_rename($this->connection, $old_handle, $new_handle);
}
/**
* Change current working directory (CHDIR)
* @access private
*/
function _chdir($dir = '')
{
if ($dir && $dir !== '/')
{
if (substr($dir, -1, 1) == '/')
{
$dir = substr($dir, 0, -1);
}
}
return @ftp_chdir($this->connection, $dir);
}
/**
* change file permissions (CHMOD)
* @access private
*/
function _chmod($file, $perms)
{
if (function_exists('ftp_chmod'))
{
$err = @ftp_chmod($this->connection, $perms, $file);
}
else
{
// Unfortunatly CHMOD is not expecting an octal value...
// We need to transform the integer (which was an octal) to an octal representation (to get the int) and then pass as is. ;)
$chmod_cmd = 'CHMOD ' . base_convert($perms, 10, 8) . ' ' . $file;
$err = $this->_site($chmod_cmd);
}
return $err;
}
/**
* Upload file to location (PUT)
* @access private
*/
function _put($from_file, $to_file)
{
// get the file extension
$file_extension = strtolower(substr(strrchr($to_file, '.'), 1));
// We only use the BINARY file mode to cicumvent rewrite actions from ftp server (mostly linefeeds being replaced)
$mode = FTP_BINARY;
$to_dir = dirname($to_file);
$to_file = basename($to_file);
$this->_chdir($to_dir);
$result = @ftp_put($this->connection, $to_file, $from_file, $mode);
$this->_chdir($this->root_path);
return $result;
}
/**
* Delete file (DELETE)
* @access private
*/
function _delete($file)
{
return @ftp_delete($this->connection, $file);
}
/**
* Close ftp session (CLOSE)
* @access private
*/
function _close()
{
if (!$this->connection)
{
return false;
}
return @ftp_quit($this->connection);
}
/**
* Return current working directory (CWD)
* At the moment not used by parent class
* @access private
*/
function _cwd()
{
return @ftp_pwd($this->connection);
}
/**
* Return list of files in a given directory (LS)
* @access private
*/
function _ls($dir = './')
{
$list = @ftp_nlist($this->connection, $dir);
// See bug #46295 - Some FTP daemons don't like './'
if ($dir === './')
{
// Let's try some alternatives
$list = (empty($list)) ? @ftp_nlist($this->connection, '.') : $list;
$list = (empty($list)) ? @ftp_nlist($this->connection, '') : $list;
}
// Return on error
if ($list === false)
{
return false;
}
// Remove path if prepended
foreach ($list as $key => $item)
{
// Use same separator for item and dir
$item = str_replace('\\', '/', $item);
$dir = str_replace('\\', '/', $dir);
if (!empty($dir) && strpos($item, $dir) === 0)
{
$item = substr($item, strlen($dir));
}
$list[$key] = $item;
}
return $list;
}
/**
* FTP SITE command (ftp-only function)
* @access private
*/
function _site($command)
{
return @ftp_site($this->connection, $command);
}
}
/**
* FTP fsock transfer class
*
* @author wGEric
* @package phpBB3
*/
class ftp_fsock extends transfer
{
var $data_connection;
/**
* Standard parameters for FTP session
*/
function ftp_fsock($host, $username, $password, $root_path, $port = 21, $timeout = 10)
{
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
$this->timeout = $timeout;
// Make sure $this->root_path is layed out the same way as the $user->page['root_script_path'] value (/ at the end)
$this->root_path = str_replace('\\', '/', $this->root_path);
if (!empty($root_path))
{
$this->root_path = (($root_path[0] != '/' ) ? '/' : '') . $root_path . ((substr($root_path, -1, 1) == '/') ? '' : '/');
}
// Init some needed values
transfer::transfer();
return;
}
/**
* Requests data
*/
function data()
{
global $user;
return array(
'host' => 'localhost',
'username' => 'anonymous',
'password' => '',
'root_path' => $user->page['root_script_path'],
'port' => 21,
'timeout' => 10
);
}
/**
* Init FTP Session
* @access private
*/
function _init()
{
$errno = 0;
$errstr = '';
// connect to the server
$this->connection = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
if (!$this->connection || !$this->_check_command())
{
return 'ERR_CONNECTING_SERVER';
}
@stream_set_timeout($this->connection, $this->timeout);
// login
if (!$this->_send_command('USER', $this->username))
{
return 'ERR_UNABLE_TO_LOGIN';
}
if (!$this->_send_command('PASS', $this->password))
{
return 'ERR_UNABLE_TO_LOGIN';
}
// change to the root directory
if (!$this->_chdir($this->root_path))
{
return 'ERR_CHANGING_DIRECTORY';
}
return true;
}
/**
* Create Directory (MKDIR)
* @access private
*/
function _mkdir($dir)
{
return $this->_send_command('MKD', $dir);
}
/**
* Remove directory (RMDIR)
* @access private
*/
function _rmdir($dir)
{
return $this->_send_command('RMD', $dir);
}
/**
* Rename File
* @access private
*/
function _rename($old_handle, $new_handle)
{
$this->_send_command('RNFR', $old_handle);
return $this->_send_command('RNTO', $new_handle);
}
/**
* Change current working directory (CHDIR)
* @access private
*/
function _chdir($dir = '')
{
if ($dir && $dir !== '/')
{
if (substr($dir, -1, 1) == '/')
{
$dir = substr($dir, 0, -1);
}
}
return $this->_send_command('CWD', $dir);
}
/**
* change file permissions (CHMOD)
* @access private
*/
function _chmod($file, $perms)
{
// Unfortunatly CHMOD is not expecting an octal value...
// We need to transform the integer (which was an octal) to an octal representation (to get the int) and then pass as is. ;)
return $this->_send_command('SITE CHMOD', base_convert($perms, 10, 8) . ' ' . $file);
}
/**
* Upload file to location (PUT)
* @access private
*/
function _put($from_file, $to_file)
{
// We only use the BINARY file mode to cicumvent rewrite actions from ftp server (mostly linefeeds being replaced)
// 'I' == BINARY
// 'A' == ASCII
if (!$this->_send_command('TYPE', 'I'))
{
return false;
}
// open the connection to send file over
if (!$this->_open_data_connection())
{
return false;
}
$this->_send_command('STOR', $to_file, false);
// send the file
$fp = @fopen($from_file, 'rb');
while (!@feof($fp))
{
@fwrite($this->data_connection, @fread($fp, 4096));
}
@fclose($fp);
// close connection
$this->_close_data_connection();
return $this->_check_command();
}
/**
* Delete file (DELETE)
* @access private
*/
function _delete($file)
{
return $this->_send_command('DELE', $file);
}
/**
* Close ftp session (CLOSE)
* @access private
*/
function _close()
{
if (!$this->connection)
{
return false;
}
return $this->_send_command('QUIT');
}
/**
* Return current working directory (CWD)
* At the moment not used by parent class
* @access private
*/
function _cwd()
{
$this->_send_command('PWD', '', false);
return preg_replace('#^[0-9]{3} "(.+)" .+\r\n#', '\\1', $this->_check_command(true));
}
/**
* Return list of files in a given directory (LS)
* @access private
*/
function _ls($dir = './')
{
if (!$this->_open_data_connection())
{
return false;
}
$this->_send_command('NLST', $dir);
$list = array();
while (!@feof($this->data_connection))
{
$filename = preg_replace('#[\r\n]#', '', @fgets($this->data_connection, 512));
if ($filename !== '')
{
$list[] = $filename;
}
}
$this->_close_data_connection();
// Clear buffer
$this->_check_command();
// See bug #46295 - Some FTP daemons don't like './'
if ($dir === './' && empty($list))
{
// Let's try some alternatives
$list = $this->_ls('.');
if (empty($list))
{
$list = $this->_ls('');
}
return $list;
}
// Remove path if prepended
foreach ($list as $key => $item)
{
// Use same separator for item and dir
$item = str_replace('\\', '/', $item);
$dir = str_replace('\\', '/', $dir);
if (!empty($dir) && strpos($item, $dir) === 0)
{
$item = substr($item, strlen($dir));
}
$list[$key] = $item;
}
return $list;
}
/**
* Send a command to server (FTP fsock only function)
* @access private
*/
function _send_command($command, $args = '', $check = true)
{
if (!empty($args))
{
$command = "$command $args";
}
fwrite($this->connection, $command . "\r\n");
if ($check === true && !$this->_check_command())
{
return false;
}
return true;
}
/**
* Opens a connection to send data (FTP fosck only function)
* @access private
*/
function _open_data_connection()
{
// Try to find out whether we have a IPv4 or IPv6 (control) connection
if (function_exists('stream_socket_get_name'))
{
$socket_name = stream_socket_get_name($this->connection, true);
$server_ip = substr($socket_name, 0, strrpos($socket_name, ':'));
}
if (!isset($server_ip) || preg_match(get_preg_expression('ipv4'), $server_ip))
{
// Passive mode
$this->_send_command('PASV', '', false);
if (!$ip_port = $this->_check_command(true))
{
return false;
}
// open the connection to start sending the file
if (!preg_match('#[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+#', $ip_port, $temp))
{
// bad ip and port
return false;
}
$temp = explode(',', $temp[0]);
$server_ip = $temp[0] . '.' . $temp[1] . '.' . $temp[2] . '.' . $temp[3];
$server_port = $temp[4] * 256 + $temp[5];
}
else
{
// Extended Passive Mode - RFC2428
$this->_send_command('EPSV', '', false);
if (!$epsv_response = $this->_check_command(true))
{
return false;
}
// Response looks like "229 Entering Extended Passive Mode (|||12345|)"
// where 12345 is the tcp port for the data connection
if (!preg_match('#\(\|\|\|([0-9]+)\|\)#', $epsv_response, $match))
{
return false;
}
$server_port = (int) $match[1];
// fsockopen expects IPv6 address in square brackets
$server_ip = "[$server_ip]";
}
$errno = 0;
$errstr = '';
if (!$this->data_connection = @fsockopen($server_ip, $server_port, $errno, $errstr, $this->timeout))
{
return false;
}
@stream_set_timeout($this->data_connection, $this->timeout);
return true;
}
/**
* Closes a connection used to send data
* @access private
*/
function _close_data_connection()
{
return @fclose($this->data_connection);
}
/**
* Check to make sure command was successful (FTP fsock only function)
* @access private
*/
function _check_command($return = false)
{
$response = '';
do
{
$result = @fgets($this->connection, 512);
$response .= $result;
}
while (substr($result, 3, 1) !== ' ');
if (!preg_match('#^[123]#', $response))
{
return false;
}
return ($return) ? $response : true;
}
}
?> | max41479/phpbb_wow | includes/functions_transfer.php | PHP | gpl-2.0 | 18,778 |
// JavaScript Document
jQuery(document).ready(function(){
var ap_methods = {
load_sub_items: function(type){
jQuery.post(ajaxurl, {action: 'ap_tax_types',"type":type}, function(response) {
response = jQuery.parseJSON(response);
if(response.msg){
var data = response.data;
var selected = response.selected;
var items = '';
jQuery.each(data, function(i, v){
var is_selected = '';
jQuery.each(selected, function(is, vs){
if(vs==i)
is_selected = 'selected="selected"';
});
items+='<option value="'+i+'" '+is_selected+'>'+v+'</option>';
});
jQuery('#tax_types_selector').html(items);
jQuery('div.ap_tax_types').show();
}
});
}
}
jQuery('#tax_selector').live('change',function(){
var type = jQuery(this).val();
if(type.length>0)
ap_methods.load_sub_items(type);
});
}); | inobrega/brasilprofissoes | wp-content/plugins/alphabetic-pagination/scripts.js | JavaScript | gpl-2.0 | 1,009 |
/***************************************************************************
qgsvectortilemvtencoder.cpp
--------------------------------------
Date : April 2020
Copyright : (C) 2020 by Martin Dobias
Email : wonder dot sk at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsvectortilemvtencoder.h"
#include "qgsfeedback.h"
#include "qgslinestring.h"
#include "qgslogger.h"
#include "qgsmultilinestring.h"
#include "qgsmultipoint.h"
#include "qgsmultipolygon.h"
#include "qgspolygon.h"
#include "qgsvectorlayer.h"
#include "qgsvectortilemvtutils.h"
//! Helper class for writing of geometry commands
struct MVTGeometryWriter
{
vector_tile::Tile_Feature *feature = nullptr;
int resolution;
double tileXMin, tileYMax, tileDX, tileDY;
QPoint cursor;
MVTGeometryWriter( vector_tile::Tile_Feature *f, int res, const QgsRectangle &tileExtent )
: feature( f )
, resolution( res )
, tileXMin( tileExtent.xMinimum() )
, tileYMax( tileExtent.yMaximum() )
, tileDX( tileExtent.width() )
, tileDY( tileExtent.height() )
{
}
void addMoveTo( int count )
{
feature->add_geometry( 1 | ( count << 3 ) );
}
void addLineTo( int count )
{
feature->add_geometry( 2 | ( count << 3 ) );
}
void addClosePath()
{
feature->add_geometry( 7 | ( 1 << 3 ) );
}
void addPoint( const QgsPoint &pt )
{
addPoint( mapToTileCoordinates( pt.x(), pt.y() ) );
}
void addPoint( const QPoint &pt )
{
const qint32 vx = pt.x() - cursor.x();
const qint32 vy = pt.y() - cursor.y();
// (quint32)(-(qint32)((quint32)vx >> 31)) is a C/C++ compliant way
// of doing vx >> 31, which is undefined behavior since vx is signed
feature->add_geometry( ( ( quint32 )vx << 1 ) ^ ( ( quint32 )( -( qint32 )( ( quint32 )vx >> 31 ) ) ) );
feature->add_geometry( ( ( quint32 )vy << 1 ) ^ ( ( quint32 )( -( qint32 )( ( quint32 )vy >> 31 ) ) ) );
cursor = pt;
}
QPoint mapToTileCoordinates( double x, double y )
{
return QPoint( static_cast<int>( round( ( x - tileXMin ) * resolution / tileDX ) ),
static_cast<int>( round( ( tileYMax - y ) * resolution / tileDY ) ) );
}
};
static void encodeLineString( const QgsLineString *lineString, bool isRing, bool reversed, MVTGeometryWriter &geomWriter )
{
int count = lineString->numPoints();
const double *xData = lineString->xData();
const double *yData = lineString->yData();
if ( isRing )
count--; // the last point in linear ring is repeated - but not in MVT
// de-duplicate points
QVector<QPoint> tilePoints;
QPoint last( -9999, -9999 );
tilePoints.reserve( count );
for ( int i = 0; i < count; ++i )
{
const QPoint pt = geomWriter.mapToTileCoordinates( xData[i], yData[i] );
if ( pt == last )
continue;
tilePoints << pt;
last = pt;
}
count = tilePoints.count();
geomWriter.addMoveTo( 1 );
geomWriter.addPoint( tilePoints[0] );
geomWriter.addLineTo( count - 1 );
if ( reversed )
{
for ( int i = count - 1; i >= 1; --i )
geomWriter.addPoint( tilePoints[i] );
}
else
{
for ( int i = 1; i < count; ++i )
geomWriter.addPoint( tilePoints[i] );
}
}
static void encodePolygon( const QgsPolygon *polygon, MVTGeometryWriter &geomWriter )
{
const QgsLineString *exteriorRing = qgsgeometry_cast<const QgsLineString *>( polygon->exteriorRing() );
encodeLineString( exteriorRing, true, !QgsVectorTileMVTUtils::isExteriorRing( exteriorRing ), geomWriter );
geomWriter.addClosePath();
for ( int i = 0; i < polygon->numInteriorRings(); ++i )
{
const QgsLineString *interiorRing = qgsgeometry_cast<const QgsLineString *>( polygon->interiorRing( i ) );
encodeLineString( interiorRing, true, QgsVectorTileMVTUtils::isExteriorRing( interiorRing ), geomWriter );
geomWriter.addClosePath();
}
}
//
QgsVectorTileMVTEncoder::QgsVectorTileMVTEncoder( QgsTileXYZ tileID )
: mTileID( tileID )
{
const QgsTileMatrix tm = QgsTileMatrix::fromWebMercator( mTileID.zoomLevel() );
mTileExtent = tm.tileExtent( mTileID );
}
void QgsVectorTileMVTEncoder::addLayer( QgsVectorLayer *layer, QgsFeedback *feedback, QString filterExpression, QString layerName )
{
if ( feedback && feedback->isCanceled() )
return;
const QgsCoordinateTransform ct( layer->crs(), QgsCoordinateReferenceSystem( "EPSG:3857" ), mTransformContext );
QgsRectangle layerTileExtent = mTileExtent;
try
{
layerTileExtent = ct.transformBoundingBox( layerTileExtent, QgsCoordinateTransform::ReverseTransform );
if ( !layerTileExtent.intersects( layer->extent() ) )
{
return; // tile is completely outside of the layer'e extent
}
}
catch ( const QgsCsException & )
{
QgsDebugMsg( "Failed to reproject tile extent to the layer" );
return;
}
if ( layerName.isEmpty() )
layerName = layer->name();
// add buffer to both filter extent in layer CRS (for feature request) and tile extent in target CRS (for clipping)
const double bufferRatio = static_cast<double>( mBuffer ) / mResolution;
QgsRectangle tileExtent = mTileExtent;
tileExtent.grow( bufferRatio * mTileExtent.width() );
layerTileExtent.grow( bufferRatio * std::max( layerTileExtent.width(), layerTileExtent.height() ) );
QgsFeatureRequest request;
request.setFilterRect( layerTileExtent );
if ( !filterExpression.isEmpty() )
request.setFilterExpression( filterExpression );
QgsFeatureIterator fit = layer->getFeatures( request );
QgsFeature f;
if ( !fit.nextFeature( f ) )
{
return; // nothing to write - do not add the layer at all
}
vector_tile::Tile_Layer *tileLayer = tile.add_layers();
tileLayer->set_name( layerName.toUtf8() );
tileLayer->set_version( 2 ); // 2 means MVT spec version 2.1
tileLayer->set_extent( static_cast<::google::protobuf::uint32>( mResolution ) );
const QgsFields fields = layer->fields();
for ( int i = 0; i < fields.count(); ++i )
{
tileLayer->add_keys( fields[i].name().toUtf8() );
}
do
{
if ( feedback && feedback->isCanceled() )
break;
QgsGeometry g = f.geometry();
// reproject
try
{
g.transform( ct );
}
catch ( const QgsCsException & )
{
QgsDebugMsg( "Failed to reproject geometry " + QString::number( f.id() ) );
continue;
}
// clip
g = g.clipped( tileExtent );
f.setGeometry( g );
addFeature( tileLayer, f );
}
while ( fit.nextFeature( f ) );
mKnownValues.clear();
}
void QgsVectorTileMVTEncoder::addFeature( vector_tile::Tile_Layer *tileLayer, const QgsFeature &f )
{
QgsGeometry g = f.geometry();
const QgsWkbTypes::GeometryType geomType = g.type();
const double onePixel = mTileExtent.width() / mResolution;
if ( geomType == QgsWkbTypes::LineGeometry )
{
if ( g.length() < onePixel )
return; // too short
}
else if ( geomType == QgsWkbTypes::PolygonGeometry )
{
if ( g.area() < onePixel * onePixel )
return; // too small
}
vector_tile::Tile_Feature *feature = tileLayer->add_features();
feature->set_id( static_cast<quint64>( f.id() ) );
//
// encode attributes
//
const QgsAttributes attrs = f.attributes();
for ( int i = 0; i < attrs.count(); ++i )
{
const QVariant v = attrs.at( i );
if ( !v.isValid() || v.isNull() )
continue;
int valueIndex;
if ( mKnownValues.contains( v ) )
{
valueIndex = mKnownValues[v];
}
else
{
vector_tile::Tile_Value *value = tileLayer->add_values();
valueIndex = tileLayer->values_size() - 1;
mKnownValues[v] = valueIndex;
if ( v.type() == QVariant::Double )
value->set_double_value( v.toDouble() );
else if ( v.type() == QVariant::Int )
value->set_int_value( v.toInt() );
else if ( v.type() == QVariant::Bool )
value->set_bool_value( v.toBool() );
else
value->set_string_value( v.toString().toUtf8().toStdString() );
}
feature->add_tags( static_cast<quint32>( i ) );
feature->add_tags( static_cast<quint32>( valueIndex ) );
}
//
// encode geometry
//
vector_tile::Tile_GeomType mvtGeomType = vector_tile::Tile_GeomType_UNKNOWN;
if ( geomType == QgsWkbTypes::PointGeometry )
mvtGeomType = vector_tile::Tile_GeomType_POINT;
else if ( geomType == QgsWkbTypes::LineGeometry )
mvtGeomType = vector_tile::Tile_GeomType_LINESTRING;
else if ( geomType == QgsWkbTypes::PolygonGeometry )
mvtGeomType = vector_tile::Tile_GeomType_POLYGON;
feature->set_type( mvtGeomType );
if ( QgsWkbTypes::isCurvedType( g.wkbType() ) )
{
g = QgsGeometry( g.get()->segmentize() );
}
MVTGeometryWriter geomWriter( feature, mResolution, mTileExtent );
const QgsAbstractGeometry *geom = g.constGet();
switch ( QgsWkbTypes::flatType( g.wkbType() ) )
{
case QgsWkbTypes::Point:
{
const QgsPoint *pt = static_cast<const QgsPoint *>( geom );
geomWriter.addMoveTo( 1 );
geomWriter.addPoint( *pt );
}
break;
case QgsWkbTypes::LineString:
{
encodeLineString( qgsgeometry_cast<const QgsLineString *>( geom ), true, false, geomWriter );
}
break;
case QgsWkbTypes::Polygon:
{
encodePolygon( static_cast<const QgsPolygon *>( geom ), geomWriter );
}
break;
case QgsWkbTypes::MultiPoint:
{
const QgsMultiPoint *mpt = static_cast<const QgsMultiPoint *>( geom );
geomWriter.addMoveTo( mpt->numGeometries() );
for ( int i = 0; i < mpt->numGeometries(); ++i )
geomWriter.addPoint( *mpt->pointN( i ) );
}
break;
case QgsWkbTypes::MultiLineString:
{
const QgsMultiLineString *mls = qgsgeometry_cast<const QgsMultiLineString *>( geom );
for ( int i = 0; i < mls->numGeometries(); ++i )
{
encodeLineString( mls->lineStringN( i ), true, false, geomWriter );
}
}
break;
case QgsWkbTypes::MultiPolygon:
{
const QgsMultiPolygon *mp = qgsgeometry_cast<const QgsMultiPolygon *>( geom );
for ( int i = 0; i < mp->numGeometries(); ++i )
{
encodePolygon( mp->polygonN( i ), geomWriter );
}
}
break;
default:
break;
}
}
QByteArray QgsVectorTileMVTEncoder::encode() const
{
return QByteArray::fromStdString( tile.SerializeAsString() );
}
| nyalldawson/QGIS | src/core/vectortile/qgsvectortilemvtencoder.cpp | C++ | gpl-2.0 | 10,948 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Tristan Fischer (sphere@dersphere.de)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 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/>.
#
import re
from xbmcswift2 import Plugin, xbmc, xbmcgui
from resources.lib import scraper
STRINGS = {
'page': 30000,
'search': 30001,
'show_my_favs': 30002,
'no_scraper_found': 30003,
'add_to_my_favs': 30004,
'del_from_my_favs': 30005,
'no_my_favs': 30006,
'use_context_menu': 30007,
'to_add': 30008,
}
plugin = Plugin()
@plugin.route('/')
def show_categories():
items = [{
'label': category['title'],
'path': plugin.url_for(
endpoint='show_path',
path=category['path']
)
} for category in scraper.get_categories()]
items.append({
'label': _('search'),
'path': plugin.url_for('video_search')
})
items.append({
'label': _('show_my_favs'),
'path': plugin.url_for('show_my_favs')
})
return plugin.finish(items)
@plugin.route('/search/')
def video_search():
search_string = __keyboard(_('search'))
if search_string:
__log('search gots a string: "%s"' % search_string)
url = plugin.url_for(
endpoint='video_search_result',
search_string=search_string
)
plugin.redirect(url)
@plugin.route('/search/<search_string>/')
def video_search_result(search_string):
path = scraper.get_search_path(search_string)
return show_path(path)
@plugin.route('/my_favs/')
def show_my_favs():
def context_menu(item_path):
context_menu = [(
_('del_from_my_favs'),
'XBMC.RunPlugin(%s)' % plugin.url_for('del_from_my_favs',
item_path=item_path),
)]
return context_menu
my_fav_items = plugin.get_storage('my_fav_items')
items = my_fav_items.values()
for item in items:
item['context_menu'] = context_menu(item['path'])
if not items:
dialog = xbmcgui.Dialog()
dialog.ok(_('no_my_favs'), _('use_context_menu'), _('to_add'))
return
return plugin.finish(items)
@plugin.route('/path/<path>/')
def show_path(path):
try:
items, next_page, prev_page = scraper.get_path(path)
except NotImplementedError:
plugin.notify(msg=_('no_scraper_found'), title='Path: %s' % path)
else:
return __add_items(items, next_page, prev_page)
def __add_items(entries, next_page=None, prev_page=None):
my_fav_items = plugin.get_storage('my_fav_items')
def context_menu(item_path, video_id):
if not item_path in my_fav_items:
context_menu = [(
_('add_to_my_favs'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='add_to_my_favs',
item_path=item_path
),
)]
else:
context_menu = [(
_('del_from_my_favs'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='del_from_my_favs',
item_path=item_path
),
)]
return context_menu
def format_episode_title(title):
if fix_show_title and '-' in title and ('Folge' in title or 'Staffel' in title):
title, show = title.rsplit('-', 1)
title = title.replace('Staffel ', 'S').replace(' Folge ', 'E')
title = title.replace('Folge ', 'E').replace('Ganze Folge', '')
return u'%s %s' % (show.strip(), title.strip())
return title
def better_thumbnail(thumb_url):
if 'web/' in thumb_url and not thumb_url.startswith('http://is'):
thumb_url = thumb_url.replace('http://i', 'http://is')
thumb_url = re.sub('mv/web/[0-9]+', 'de', thumb_url)
thumb_url = thumb_url.replace('.jpg', '.jpg_hq.jpg')
return thumb_url
fix_show_title = plugin.get_setting('fix_show_title', bool)
temp_items = plugin.get_storage('temp_items')
temp_items.clear()
items = []
has_icons = False
i = 0
for i, entry in enumerate(entries):
if not has_icons and entry.get('thumb'):
has_icons = True
if entry['is_folder']:
items.append({
'label': entry['title'],
'thumbnail': entry.get('thumb', 'DefaultFolder.png'),
'info': {'count': i + 1},
'path': plugin.url_for(
endpoint='show_path',
path=entry['path']
)
})
else:
items.append({
'label': format_episode_title(entry['title']),
'thumbnail': better_thumbnail(
entry.get('thumb', 'DefaultVideo.png')
),
'icon': entry.get('thumb', 'DefaultVideo.png'),
'info': {
'video_id': entry['video_id'],
'count': i + 1,
'plot': entry.get('description', ''),
'studio': entry.get('author', {}).get('name', ''),
'date': entry.get('date', ''),
'year': int(entry.get('year', 0)),
'rating': float(entry.get('rating', 0)),
'votes': unicode(entry.get('votes')),
'views': unicode(entry.get('views', 0))
},
'stream_info': {
'video': {'duration': entry.get('duration', 0)}
},
'is_playable': True,
'path': plugin.url_for(
endpoint='watch_video',
video_id=entry['video_id']
)
})
if prev_page:
items.append({
'label': '<< %s %s <<' % (_('page'), prev_page['number']),
'info': {'count': 0},
'thumbnail': 'DefaultFolder.png',
'path': plugin.url_for(
endpoint='show_path',
path=prev_page['path'],
update='true',
)
})
if next_page:
items.append({
'label': '>> %s %s >>' % (_('page'), next_page['number']),
'thumbnail': 'DefaultFolder.png',
'info': {'count': i + 2},
'path': plugin.url_for(
endpoint='show_path',
path=next_page['path'],
update='true',
)
})
for item in items:
temp_items[item['path']] = item
item['context_menu'] = context_menu(
item['path'], item['info'].get('video_id')
)
temp_items.sync()
update_on_pageswitch = plugin.get_setting('update_on_pageswitch', bool)
is_update = update_on_pageswitch and 'update' in plugin.request.args
finish_kwargs = {
'sort_methods': ('playlist_order', 'label'),
'update_listing': is_update
}
if has_icons and plugin.get_setting('force_viewmode', bool):
finish_kwargs['view_mode'] = 'thumbnail'
return plugin.finish(items, **finish_kwargs)
@plugin.route('/video/<video_id>/play')
def watch_video(video_id):
video = scraper.get_video(video_id)
if 'hls_playlist' in video:
__log('watch_video using HLS')
video_url = video['hls_playlist']
elif not video['rtmpurl']:
__log('watch_video using FLV')
video_url = video['filepath'] + video['file']
else:
__log('watch_video using RTMPE or RTMPT')
video_url = (
'%(rtmpurl)s '
'tcUrl=%(rtmpurl)s '
'swfVfy=%(swfobj)s '
'pageUrl=%(pageurl)s '
'playpath=%(playpath)s'
) % video
__log('watch_video finished with url: %s' % video_url)
return plugin.set_resolved_url(video_url)
@plugin.route('/my_favs/add/<item_path>')
def add_to_my_favs(item_path):
my_fav_items = plugin.get_storage('my_fav_items')
temp_items = plugin.get_storage('temp_items')
my_fav_items[item_path] = temp_items[item_path]
my_fav_items.sync()
@plugin.route('/my_favs/del/<item_path>')
def del_from_my_favs(item_path):
my_fav_items = plugin.get_storage('my_fav_items')
if item_path in my_fav_items:
del my_fav_items[item_path]
my_fav_items.sync()
def __keyboard(title, text=''):
keyboard = xbmc.Keyboard(text, title)
keyboard.doModal()
if keyboard.isConfirmed() and keyboard.getText():
return keyboard.getText()
def _(string_id):
if string_id in STRINGS:
return plugin.get_string(STRINGS[string_id])
else:
plugin.log.warning('String is missing: %s' % string_id)
return string_id
def __log(text):
plugin.log.info(text)
if __name__ == '__main__':
try:
plugin.run()
except scraper.NetworkError:
plugin.notify(msg=_('network_error'))
| noba3/KoTos | addons/plugin.video.myvideo_de/addon.py | Python | gpl-2.0 | 9,503 |
<?php
###########################################################################
# ASTPP - Open Source Voip Billing
# Copyright (C) 2004, Aleph Communications
#
# Contributor(s)
# "iNextrix Technologies Pvt. Ltd - <astpp@inextrix.com>"
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details..
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
############################################################################
class DID_model extends CI_Model {
function DID_model() {
parent::__construct();
}
function add_did($add_array) {
unset($add_array["action"]);
$add_array['assign_date']=gmdate('Y-m-d H:i:s');
$this->db->insert("dids", $add_array);
return true;
}
function insert_pricelist() {
$insert_array = array('name' => 'default', 'markup' => '', 'inc' => '');
return $this->db->insert_id();
}
function edit_did($data, $id,$number) {
// echo '<pre>'; print_r($data); exit;
unset($data["action"]);
$this->db->where("number", $number);
$this->db->where("id", $id);
return $this->db->update("dids", $data);
//echo $this->db->last_query(); exit;
}
function getdid_list($flag, $start = 0, $limit = 0) {
$this->db_model->build_search('did_list_search');
if($this->session->userdata('logintype') == 1 || $this->session->userdata('logintype') == 5)
{
if($this->session->userdata["accountinfo"]['reseller_id'] != 0)
{
$parent_id = $this->session->userdata["accountinfo"]['reseller_id'];
}else{
$parent_id = 0;
}
$where = array('reseller_id' => $this->session->userdata["accountinfo"]['id'],"parent_id"=>$parent_id);
if ($flag) {
$query = $this->db_model->select("*,note as number,reseller_id as accountid", "reseller_pricing", $where, "note", "desc", $limit, $start);
} else {
$query = $this->db_model->countQuery("*", "reseller_pricing", $where);
}
return $query;
}
else
{
if ($flag) {
$this->db->select('dids.id,dids.connectcost,dids.includedseconds,dids.number,dids.extensions,dids.call_type,dids.country_id,dids.inc,dids.cost,dids.setup,dids.monthlycost,dids.status,(CASE when parent_id > 0 THEN (SELECT reseller_id as accountid from reseller_pricing where dids.number=reseller_pricing.note AND reseller_pricing.parent_id=0) ELSE dids.accountid END ) as accountid');
$query=$this->db->get('dids');
} else {
$query = $this->db_model->countQuery("*", "dids");
}
return $query;
}
}
function remove_did($id) {
$this->db->where("id", $id);
$this->db->delete("dids");
return true;
}
function get_coutry_id_by_name($field_value) {
$this->db->where("country", ucfirst($field_value));
$query = $this->db->get('countrycode');
$data = $query->result();
if ($query->num_rows > 0)
return $data[0]->id;
else
return '';
}
function bulk_insert_dids($field_value) {
$this->db->insert_batch('dids', $field_value);
$affected_row = $this->db->affected_rows();
return $affected_row;
}
function get_account($accountdata) {
$q = "SELECT * FROM accounts WHERE number = '" . $this->db->escape_str($accountdata) . "' AND status = 0";
$query = $this->db->query($q);
if ($query->num_rows() > 0) {
$row = $query->row_array();
return $row;
}
$q = "SELECT * FROM accounts WHERE cc = '" . $this->db->escape_str($accountdata) . "' AND status = 0";
$query = $this->db->query($q);
if ($query->num_rows() > 0) {
$row = $query->row_array();
return $row;
}
$q = "SELECT * FROM accounts WHERE accountid = '" . $this->db->escape_str($accountdata) . "' AND status = 0";
$query = $this->db->query($q);
if ($query->num_rows() > 0) {
$row = $query->row_array();
return $row;
}
return NULL;
}
function get_did_reseller_new($did, $reseller_id = "") {
$sql = "SELECT dids.number AS number, "
. "reseller_pricing.monthlycost AS monthlycost, "
. "reseller_pricing.prorate AS prorate, "
. "reseller_pricing.setup AS setup, "
. "reseller_pricing.cost AS cost, "
. "reseller_pricing.connectcost AS connectcost, "
. "reseller_pricing.includedseconds AS includedseconds, "
. "reseller_pricing.inc AS inc, "
. "reseller_pricing.disconnectionfee AS disconnectionfee, "
. "dids.provider_id AS provider_id, "
. "dids.country_id AS country_id, "
. "dids.city AS city, "
. "dids.province AS province, "
. "dids.extensions AS extensions, "
. "dids.accountid AS account, "
. "dids.variables AS variables, "
. "dids.options AS options, "
. "dids.maxchannels AS maxchannels, "
. "dids.chargeonallocation AS chargeonallocation, "
. "dids.allocation_bill_status AS allocation_bill_status, "
. "dids.limittime AS limittime, "
. "dids.dial_as AS dial_as, "
. "dids.status AS status "
. "FROM dids, reseller_pricing "
. "WHERE dids.id = " . $did
. " AND reseller_pricing.type = '1' AND reseller_pricing.reseller_id = "
. $reseller_id;
// . " AND reseller_pricing.note = "
// . $did
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
return $query->row_array();
}
//return $this->db_get_arrays($sql);
}
function get_did_by_number($number) {
$this->db->where("id", $number);
$this->db->or_where("number", $number);
$query = $this->db->get("dids");
// echo $this->db->last_query();exit;
if ($query->num_rows() > 0)
return $query->row_array();
else
return false;
}
// function edit_reseller_pricing($post)
// {
//
// }
function edit_did_reseller($did_id,$post) {
$accountinfo = $this->session->userdata('accountinfo');
$where_array=array('reseller_id' => $accountinfo['id'], 'note' => $post['number'], 'type' => '1');
$this->db->where($where_array);
$flag='0';
$query = $this->db->get('reseller_pricing');
// echo $query->num_rows();
// exit;
if($query->num_rows() > 0){
// $this->delete_pricing_reseller($accountinfo['id'], $post['number']);
$flag='1';
}
$this->insert_reseller_pricing($accountinfo, $post);
// $this->update_dids_reseller($post);
// $query_pricelist = $this->db_model->getSelect("*", "pricelists", array('name' => $accountinfo['number']));
// if ($query_pricelist->num_rows > 0) {
// $result_pricelist = $query_pricelist->result_array();
// $pricelist_id = $result_pricelist[0]['id'];
// }
// $this->delete_routes($accountinfo['number'], $post['number'], $pricelist_id);
// $this->insert_routes($post, $pricelist_id,$accountinfo['id']);
return $flag;
}
function delete_pricing_reseller($username, $number) {
$where = array('reseller_id' => $username, 'note' => $number, 'type' => '1');
$this->db->where($where);
$this->db->delete('reseller_pricing');
return true;
}
function insert_reseller_pricing($accountinfo, $post) {
$insert_array = array('reseller_id' => $accountinfo['id'], 'type' => '1', 'note' => $post['number'],
'parent_id'=>$accountinfo['reseller_id'],
'monthlycost' => $post['monthlycost'],
'prorate' => $post['prorate'],
'setup' => $post['setup'],
'cost' => $post['cost'],
'inc' => $post['inc'],
'extensions'=>$post['extensions'],
'call_type'=>$post['call_type'],
'disconnectionfee' => $post['disconnectionfee'],
'connectcost' => $post['connectcost'],
'includedseconds' => $post['includedseconds'],
'status' => '0',
'assign_date'=>gmdate('Y-m-d H:i:s'));
$this->db->insert('reseller_pricing', $insert_array);
return true;
}
function update_dids_reseller($post) {
$where = array('id' => $post['did_id']);
$update_array = array('dial_as' => $post['dial_as'], 'extensions' => $post['extension']);
$this->db->where($where);
$this->db->update('dids', $update_array);
}
function delete_routes($id, $number, $pricelist_id) {
$number = "^" . $number . ".*";
$where = array('pricelist_id' => $pricelist_id, 'pattern' => $number);
$this->db->where($where);
$this->db->delete('routes');
}
function insert_routes($post, $pricelist_id) {
$commment = "DID:" . $post['country'] . "," . $post['province'] . "," . $post['city'];
$insert_array = array('pattern' => "^" . $post['number'] . ".*", 'comment' => $commment, 'pricelist_id' => $pricelist_id,
'connectcost' => $post['connectcost'], 'includedseconds' => $post['included'], 'cost' => $post['cost'], 'inc' => $post['inc']);
$this->db->insert('routes', $insert_array);
return true;
}
function remove_did_pricing($array_did, $reseller_id) {
$reseller_ids=$this->common->subreseller_list($reseller_id);
$where="note = ".$array_did['number']." AND reseller_id IN ($reseller_ids) OR note= ".$array_did['number']." AND parent_id IN ($reseller_ids)";
$this->db->where($where);
$this->db->delete('reseller_pricing');
$accountinfo=$this->session->userdata('accountinfo');
$reseller_id =$accountinfo['type'] != 1 ? 0 : $accountinfo['reseller_id'];
$update_array = array('accountid'=>"0",'parent_id'=>$reseller_id);
$where_dids = array("number" => $array_did['number']);
$where_dids='number = '.$array_did['number']." AND parent_id IN ($reseller_ids)";
$this->db->where($where_dids);
$this->db->update('dids', $update_array);
return true;
}
function add_invoice_data($accountid,$charge_type,$description,$credit)
{
$insert_array = array('accountid' => $accountid,
'charge_type' => $charge_type,
'description' => $description,
'credit' => $credit,
'charge_id' => '0',
'package_id' => '0'
);
$this->db->insert('invoice_item', $insert_array);
return true;
}
function check_unique_did($number)
{
$where=array('number'=>$number);
$query = $this->db_model->countQuery("*", "dids", $where);
return $query;
}
}
| bmurkoff/ASTPP | web_interface/astpp/application/modules/did/models/did_model.php | PHP | gpl-2.0 | 11,467 |
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "storage/DevicegraphImpl.h"
#include "storage/Environment.h"
#include "storage/Storage.h"
#include "storage/Action.h"
#include "storage/Pool.h"
#include "storage/Devices/DeviceImpl.h"
#include "storage/Devices/BlkDevice.h"
#include "storage/Devices/Partitionable.h"
#include "storage/Devices/PartitionTable.h"
#include "storage/Devices/LvmVgImpl.h"
#include "storage/Devices/LvmPvImpl.h"
#include "storage/Devices/BcacheCsetImpl.h"
#include "storage/Filesystems/BlkFilesystem.h"
#include "storage/Filesystems/Btrfs.h"
#include "storage/Filesystems/BtrfsSubvolume.h"
#include "storage/Filesystems/MountPoint.h"
#include "storage/Utils/Mockup.h"
#include "storage/Utils/Format.h"
#include "testsuite/helpers/TsCmp.h"
using namespace std;
namespace storage
{
std::ostream&
operator<<(std::ostream& out, const TsCmp& ts_cmp)
{
out << endl;
for (const string& error : ts_cmp.errors)
out << error << endl;
return out;
}
TsCmpDevicegraph::TsCmpDevicegraph(const Devicegraph& lhs, Devicegraph& rhs)
{
adjust_sids(lhs, rhs);
if (lhs != rhs)
{
ostringstream tmp1;
lhs.get_impl().log_diff(tmp1, rhs.get_impl());
string tmp2 = tmp1.str();
boost::split(errors, tmp2, boost::is_any_of("\n"), boost::token_compress_on);
}
}
/**
* This function adjusts the sids which is needed when devices are detected in a
* differnet order than expected. Block devices use the name for identification, most
* others a uuid or a path. Some types are not handled at all, e.g. Nfs.
*
* The function makes assumptions that break in the general case and does no error
* checking. It can even ruin the devicegraph.
*
* Only enable it when you know what you are doing!
*/
void
TsCmpDevicegraph::adjust_sids(const Devicegraph& lhs, Devicegraph& rhs) const
{
#if 0
for (Device* device_rhs : Device::get_all(&rhs))
{
// BlkDevices
if (is_blk_device(device_rhs))
{
BlkDevice* blk_device_rhs = to_blk_device(device_rhs);
const BlkDevice* blk_device_lhs = BlkDevice::find_by_name(&lhs, blk_device_rhs->get_name());
adjust_sid(blk_device_lhs, blk_device_rhs);
// PartitionTables
if (is_partitionable(blk_device_lhs) && is_partitionable(blk_device_rhs))
{
const Partitionable* partitionable_lhs = to_partitionable(blk_device_lhs);
Partitionable* partitionable_rhs = to_partitionable(blk_device_rhs);
if (partitionable_lhs->has_partition_table() && partitionable_rhs->has_partition_table())
adjust_sid(partitionable_lhs->get_partition_table(), partitionable_rhs->get_partition_table());
}
}
// LvmVgs
if (is_lvm_vg(device_rhs))
{
LvmVg* lvm_vg_rhs = to_lvm_vg(device_rhs);
const LvmVg* lvm_vg_lhs = LvmVg::Impl::find_by_uuid(&lhs, lvm_vg_rhs->get_impl().get_uuid());
adjust_sid(lvm_vg_lhs, lvm_vg_rhs);
}
// LvmPvs
if (is_lvm_pv(device_rhs))
{
LvmPv* lvm_pv_rhs = to_lvm_pv(device_rhs);
const LvmPv* lvm_pv_lhs = LvmPv::Impl::find_by_uuid(&lhs, lvm_pv_rhs->get_impl().get_uuid());
adjust_sid(lvm_pv_lhs, lvm_pv_rhs);
}
// BcacheCset
if (is_bcache_cset(device_rhs))
{
BcacheCset* bcache_cset_rhs = to_bcache_cset(device_rhs);
const BcacheCset* bcache_cset_lhs = BcacheCset::Impl::find_by_uuid(&lhs, bcache_cset_rhs->get_uuid());
adjust_sid(bcache_cset_lhs, bcache_cset_rhs);
}
// BlkFilesystems
if (is_blk_filesystem(device_rhs))
{
BlkFilesystem* blk_filesystem_rhs = to_blk_filesystem(device_rhs);
const BlkFilesystem* blk_filesystem_lhs = BlkFilesystem::find_by_uuid(&lhs, blk_filesystem_rhs->get_uuid()).front();
adjust_sid(blk_filesystem_lhs, blk_filesystem_rhs);
// BtrfsSubvolumes
if (is_btrfs(blk_filesystem_lhs) && is_btrfs(blk_filesystem_rhs))
{
const Btrfs* btrfs_lhs = to_btrfs(blk_filesystem_lhs);
Btrfs* btrfs_rhs = to_btrfs(blk_filesystem_rhs);
for (BtrfsSubvolume* btrfs_subvolume_rhs : btrfs_rhs->get_btrfs_subvolumes())
{
const BtrfsSubvolume* btrfs_subvolume_lhs = btrfs_lhs->find_btrfs_subvolume_by_path(btrfs_subvolume_rhs->get_path());
adjust_sid(btrfs_subvolume_lhs, btrfs_subvolume_rhs);
}
}
}
// MountPoints
if (is_mount_point(device_rhs))
{
MountPoint* mount_point_rhs = to_mount_point(device_rhs);
const MountPoint* mount_point_lhs = MountPoint::find_by_path(&lhs, mount_point_rhs->get_path()).front();
adjust_sid(mount_point_lhs, mount_point_rhs);
}
}
#endif
}
void
TsCmpDevicegraph::adjust_sid(const Device* lhs, Device* rhs) const
{
if (lhs->get_sid() != rhs->get_sid())
{
cout << "adjust sid " << rhs->get_impl().get_classname() << " ("
<< rhs->get_displayname() << ") " << rhs->get_sid() << " -> "
<< lhs->get_sid() << endl;
rhs->get_impl().set_sid(lhs->get_sid());
}
}
TsCmpActiongraph::Expected::Expected(const string& filename)
{
std::ifstream fin(filename);
if (!fin)
ST_THROW(Exception("failed to load " + filename));
string line;
while (getline(fin, line))
{
if (!line.empty() && !boost::starts_with(line, "#"))
lines.push_back(line);
}
}
TsCmpActiongraph::TsCmpActiongraph(const string& name, bool commit)
{
Environment environment(true, ProbeMode::READ_DEVICEGRAPH, TargetMode::DIRECT);
environment.set_devicegraph_filename(name + "-probed.xml");
storage = make_unique<Storage>(environment);
storage->probe();
storage->get_staging()->load(name + "-staging.xml");
probed = storage->get_probed();
staging = storage->get_staging();
actiongraph = storage->calculate_actiongraph();
if (access(DOT_BIN, X_OK) == 0)
{
probed->write_graphviz(name + "-probed.gv", get_debug_devicegraph_style_callbacks(), View::ALL);
system((DOT_BIN " -Tsvg < " + name + "-probed.gv > " + name + "-probed.svg").c_str());
staging->write_graphviz(name + "-staging.gv", get_debug_devicegraph_style_callbacks(), View::ALL);
system((DOT_BIN " -Tsvg < " + name + "-staging.gv > " + name + "-staging.svg").c_str());
actiongraph->write_graphviz(name + "-action.gv", get_debug_actiongraph_style_callbacks());
system((DOT_BIN " -Tsvg < " + name + "-action.gv > " + name + "-action.svg").c_str());
}
TsCmpActiongraph::Expected expected(name + "-expected.txt");
const CommitData commit_data(actiongraph->get_impl(), Tense::SIMPLE_PRESENT);
cmp(commit_data, expected);
// smoke test for compound actions
for (const CompoundAction* compound_action : actiongraph->get_compound_actions())
compound_action->sentence();
if (!commit)
return;
Mockup::set_mode(Mockup::Mode::PLAYBACK);
Mockup::load(name + "-mockup.xml");
CommitOptions commit_options(false);
storage->commit(commit_options);
Mockup::occams_razor();
}
void
TsCmpActiongraph::cmp(const CommitData& commit_data, const Expected& expected)
{
for (const string& line : expected.lines)
entries.push_back(Entry(line));
check();
cmp_texts(commit_data);
if (!ok())
return;
cmp_dependencies(commit_data);
}
TsCmpActiongraph::Entry::Entry(const string& line)
{
string::size_type pos1 = line.find('-');
if (pos1 == string::npos)
ST_THROW(Exception("parse error, did not find '-'"));
string::size_type pos2 = line.rfind("->");
if (pos2 == string::npos)
ST_THROW(Exception("parse error, did not find '->'"));
id = boost::trim_copy(line.substr(0, pos1), locale::classic());
text = boost::trim_copy(line.substr(pos1 + 1, pos2 - pos1 - 1), locale::classic());
string tmp = boost::trim_copy(line.substr(pos2 + 2), locale::classic());
if (!tmp.empty())
boost::split(dep_ids, tmp, boost::is_any_of(" "), boost::token_compress_on);
}
void
TsCmpActiongraph::check() const
{
set<string> ids;
set<string> texts;
for (const Entry& entry : entries)
{
if (!ids.insert(entry.id).second)
ST_THROW(Exception("duplicate id"));
if (!texts.insert(entry.text).second)
ST_THROW(Exception("duplicate text"));
}
for (const Entry& entry : entries)
{
for (const string& dep_id : entry.dep_ids)
{
if (ids.find(dep_id) == ids.end())
ST_THROW(Exception("unknown dependency-id"));
}
}
}
string
TsCmpActiongraph::text(const CommitData& commit_data, Actiongraph::Impl::vertex_descriptor vertex) const
{
const Action::Base* action = commit_data.actiongraph[vertex];
return action->debug_text(commit_data);
}
void
TsCmpActiongraph::cmp_texts(const CommitData& commit_data)
{
set<string> tmp1;
for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
tmp1.insert(text(commit_data, vertex));
set<string> tmp2;
for (const Entry& entry : entries)
tmp2.insert(entry.text);
if (tmp1 != tmp2)
{
errors.push_back("action texts differ");
vector<string> diff1;
set_difference(tmp2.begin(), tmp2.end(), tmp1.begin(), tmp1.end(), back_inserter(diff1));
for (const string& error : diff1)
errors.push_back("- " + error);
vector<string> diff2;
set_difference(tmp1.begin(), tmp1.end(), tmp2.begin(), tmp2.end(), back_inserter(diff2));
for (const string& error : diff2)
errors.push_back("+ " + error);
}
}
void
TsCmpActiongraph::cmp_dependencies(const CommitData& commit_data)
{
map<string, string> text_to_id;
for (const Entry& entry : entries)
text_to_id[entry.text] = entry.id;
map<string, Actiongraph::Impl::vertex_descriptor> text_to_vertex;
for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
text_to_vertex[text(commit_data, vertex)] = vertex;
for (const Entry& entry : entries)
{
Actiongraph::Impl::vertex_descriptor vertex = text_to_vertex[entry.text];
set<string> tmp;
for (Actiongraph::Impl::vertex_descriptor child : commit_data.actiongraph.children(vertex))
tmp.insert(text_to_id[text(commit_data, child)]);
if (tmp != entry.dep_ids)
{
errors.push_back("wrong dependencies for '" + entry.text + "'");
errors.push_back("- " + boost::join(tmp, " "));
errors.push_back("+ " + boost::join(entry.dep_ids, " "));
}
}
}
string
required_features(const Devicegraph* devicegraph)
{
return get_used_features_names(devicegraph->used_features(UsedFeaturesDependencyType::REQUIRED));
}
string
suggested_features(const Devicegraph* devicegraph)
{
return get_used_features_names(devicegraph->used_features(UsedFeaturesDependencyType::SUGGESTED));
}
string
features(const Actiongraph* actiongraph)
{
return get_used_features_names(actiongraph->used_features());
}
string
pools(Storage* storage)
{
const Devicegraph* probed = storage->get_probed();
storage->generate_pools(probed);
string ret;
for (const map<string, const Pool*>::value_type tmp : storage->get_pools())
{
if (!ret.empty())
ret += ", ";
ret += sformat("%s [%d]", tmp.first, tmp.second->get_devices(probed).size());
}
return ret;
}
}
| aschnell/libstorage-ng | testsuite/helpers/TsCmp.cc | C++ | gpl-2.0 | 11,231 |
</div>
</div>
</div>
<footer id="footer">
<div class="container">
© <?php echo date('Y'); ?> <a rel="nofollow" href="<?php $this->options->siteUrl(); ?>"><?php $this->options->title(); ?></a>.
</div>
</footer>
</div>
<div class="site-search">
<script type="text/javascript" src="<?php $this->options->themeUrl('index.js'); ?>"></script>
<script type="text/javascript">
if (window!=top){top.location.href = window.location.href;}
</script>
</div>
<p class="link-back2top"><a href="#" title="Back to top">Back to top</a></p>
<script>
$(".link-back2top").hide();
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$(".link-back2top").fadeIn();
} else {
$(".link-back2top").fadeOut();
}
});
$(".link-back2top a").click(function() {
$("body,html").animate({
scrollTop: 0
},
800);
return false;
});
</script>
<?php $this->footer(); ?>
</body>
</html>
| fffddgx/blog.dufei.cc | usr/themes/navy/footer.php | PHP | gpl-2.0 | 968 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Ralph Eisenbach
#
# This plugin is based on the plugin for ZoomPlayer
# by Lars-Peter Voss <bitmonster@eventghost.net>
#
# This file is a plugin for EventGhost.
# Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/>
#
# EventGhost 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.
#
# EventGhost 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 EventGhost. If not, see <http://www.gnu.org/licenses/>.
eg.RegisterPlugin(
name = "TheaterTek",
author = "SurFan",
version = "0.0.1",
kind = "program",
guid = "{EF830DA5-EF08-4050-BAE0-D5FC0057D149}",
canMultiLoad = True,
createMacrosOnAdd = True,
description = (
'Adds actions to control <a href="http://www.theatertek.com/">TheaterTek</a>.'
'\n\n<p><b>Notice:</b><br>'
'To make it work, you have to enable TCP control in TheaterTek. '
),
url = "http://www.eventghost.net/forum/viewtopic.php?t=559",
icon = (
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAACGElEQVR42m1RPWhaURQ+"
"gg6lCjooxnZIH9iARAi9QqwQTcBmioNQcWskwxV5i+AgDqHERZdsEfreUE3BDFJI4XUq"
"EeqeizjUnw6CKO1SUJ4lWKR5PXotjaZ3eefv+873nafT6/XT6dRkMp1+PgUA0Svy9Ozs"
"zfY2cbvdmLpcri/VOsyfDgiAxGP8SpgyxmSQFyUGQAjE2a0yWQJQoBL5i+MNWbeIcCAO"
"qwCNaLMkPhsilFyTa9zjiXtmXQeAcg9AGEoB5mBwAChHk7TBYBAIBNLpNJYvUhfq1x/L"
"Hti/7Yebh6VSCekbbxvomM+dn5df7b9cNY3ckWGkUqkgq9fgxUI2m81kMni0VqtVr9cP"
"PPt3NjCghEpUUhTl5ONJ0BLsdrsIlmVZFEWn09lsNtHYHEABvoO0JlFKY7FYuVxGbi4m"
"l8uFw+F8Pu/z+bCL4DkgBHRtxo0TuH0ymdjt9uMPxxs/N7BSLBbREpeMyxcA7bUGyw9t"
"7Jp2G41Gv9/vdDpcVTKZ5JIIxcMCE64ESzCIw8OrYdfSxTLqsVqttVotkUiYzeZQKKQz"
"Go3j8dhgMBwVjrZ+b/V6PVSMqd/vr1arGHAzKAan2+227vbb5K6Sd5/er68/xlMiIJVK"
"CYJgs9kikQiy4ImeOTZXARyzs/McR1VVLRQKaGBv7wWy+J/O/sx/APjGD39dXio3NyrG"
"o9EoGo0+efCIt/4ArUT50E11E2MAAAAASUVORK5CYII="
),
)
# ===================================================================
# TheaterTek TCP/IP Interface
# ===================================================================
"""\
IP COMMANDS
-----------
TT->AP Sent from TT to client application
AP->TT Sent from client application to TT
TT<-->AP Sent from TT and can be polled by client.
Commands are sent ASCII in the form:
4 byte command, space, {parameter} CRLF
A successful command returns:
Command, space, 0
OR
Command, space, response
An unsuccessful command returns:
Command, space, -1
Example:
0000 // Client app
0000 TheaterTek DVD // Returned value
Enum values
-----------
IP_MEDIASTATE 0=Stopped/NoMedia, 1=Playing, 2=paused, 3=FF, 4=RW
IP_FULLSCREEN 0=Minimized, 1=Windowed, 2=Fullscreen
IP_GETPRIVATE Allows client to set/get a private string up to 1024 bytes on TT. This data persists as long as TT is running.
#define IP_APPLICATION 0 // TT<-->AP Application name
#define IP_VERSION 1 // TT<-->AP Application version
#define IP_FLASH 500 // TT<-->AP OSD Flash message
#define IP_FULLSCREEN 510 // TT<-->AP Fullscreen/windowed status
#define IP_MEDIASTATE 1000 // TT<-->AP State enum
#define IP_MEDIATIME 1010 // TT<-->AP Media time (hh:mm:ss / hh:mm:ss)
#define IP_MEDIAPOS 1020 // AP->TT Set media time (hh:mm:ss)
#define IP_ENDOFMEDIA 1030 // TT->AP Signals end of media
#define IP_FORMAT 1040 // TT->AP (0=NTSC, 1=PAL)
#define IP_GETAR 1300 // TT<-->AP Return Current AR (name)
#define IP_ARCOUNT 1310 // AP->TT AR Count
#define IP_ARNAMES 1320 // AP->TT AR Names (name|name)
#define IP_SETAR 1330 // AP->TT Set Current AR (number)
#define IP_CURFILE 1400 // TT<-->AP Current file
#define IP_DISKINSERTION 1410 // TT->AP Disk inserted
#define IP_DISKEJECTION 1420 // TT->AP Disk ejected
#define IP_DVDUNIQUEID 1500 // AP->TT DVD unique ID
#define IP_DVDTITLE 1510 // TT<-->AP Current Title
#define IP_DVDTITLECOUNT 1520 // AP->TT Title count
#define IP_DVDPLAYTITLE 1530 // AP->TT Play Title
#define IP_DVDCHAPTER 1600 // TT<-->AP Current Chapter
#define IP_DVDCHAPTERCOUNT 1610 // AP->TT Chapter count
#define IP_DVDPLAYCHAPTER 1620 // AP->TT Play chapter
#define IP_DVDPLAYTITCHAP 1630 // AP->TT Play Chapter in Title (Chapter Title)
#define IP_DVDAUDIO 1700 // TT<-->AP Current audio stream
#define IP_DVDSETAUDIO 1710 // AP->TT Set audio stream
#define IP_DVDAUDIOCOUNT 1720 // AP->TT Audio stream count
#define IP_DVDAUDIONAMES 1730 // AP->TT Audio stream names (name|name)
#define IP_DVDSUBTITLE 1800 // TT<-->AP Current subtitle stream
#define IP_DVDSETSUBTITLE 1810 // AP->TT Set subtitle stream, -1 to disable
#define IP_DVDSUBTITLECOUNT 1820 // AP->TT Subtitle stream count
#define IP_DVDSUBTITLENAMES 1830 // AP->TT Subtitle names (name|name)
#define IP_DVDANGLE 1900 // TT<-->AP Current angle
#define IP_DVDSETANGLE 1910 // AP->TT Set angle
#define IP_DVDANGLECOUNT 1920 // AP->TT Angle count
#define IP_DVDMENUMODE 2000 // TT<-->AP Menu mode
#define IP_DOMAIN 2010 // TT->AP DVD Domain
#define IP_GETVOLUME 2100 // TT<-->AP Get Current volume
#define IP_SETVOLUME 2110 // AP->TT Set Current volume
#define IP_GETAUDIOOUTPUT 2120 // AP->TT Get Current audio output
#define IP_SETAUDIOOUTPUT 2130 // AP->TT Set audio output
#define IP_ADDBOOKMARK 2200 // AP->TT Add a bookmark
#define IP_NEXTBOOKMARK 2210 // AP->TT Next bookmark
#define IP_PREVBOOKMARK 2220 // AP->TT Previous bookmark
#define IP_PLAYFILE 3000 // AP->TT Play file
#define IP_ADDFILE 3010 // AP->TT Add file to playlist
#define IP_CLEARLIST 3020 // AP->TT Clear playlist
#define IP_GETINDEX 3030 // AP->TT Current item index
#define IP_PLAYATINDEX 3040 // AP->TT Play item at index
#define IP_GETLISTCOUNT 3050 // AP->TT Current list count
#define IP_GETLIST 3060 // AP->TT Get playlist (name|name)
#define IP_DELATINDEX 3070 // AP->TT Delete file at index
#define IP_SETPRIVATE 4000 // AP->TT Private app string
#define IP_GETPRIVATE 4010 // AP->TT Private app string
#define IP_WM_COMMAND 5000 // AP->TT Internal command
#define IP_KEYPRESS 5010 // AP->TT Key code
#define IP_SENDMSG 5020 // AP->TT Send message
#define IP_POSTMSG 5030 // AP->TT Post message
Auto Killer Commands
--------------------
#define IP_LAUNCH 8000 // AP->AK
#define IP_QUIT 8010 // AP->AK
#define IP_MOUNTDISK 8020 // AP->AK Changer#, Slot#
#define IP_UNMOUNTDISK 8030 // AP->AK Changer# ->Slot#
#define IP_EJECTDISK 8040 // AP->AK Changer#, Slot#
#define IP_GETSLOTDATA 8050 // AP->AK Changer#, Slot#
#define IP_GETDRIVEDATA 8060 // AP->AK Changer# ->DriveData
#define IP_CHECKCHANGED 8070 // AP->AK
#define IP_REBUILDDATA 8080 // AP->AK
#define IP_DATACHANGED 8100 // AK->AP Notification of data change
#define IP_COUNTCHANGERS 8110 // AP->AK
WM_COMMANDS
-----------
#define ID_PLAY 32771
#define ID_STOP 32772
#define ID_PAUSE 32773
#define ID_NEXT 32774
#define ID_PREVIOUS 32775
#define ID_EXIT 32776
#define ID_FF 32777
#define ID_RW 32778
#define ID_MENU_LIST 32779
#define ID_TITLE_MENU 32780
#define ID_FF_1X 32782
#define ID_FF_2X 32784
#define ID_FF_5X 32785
#define ID_FF_10X 32786
#define ID_FF_20X 32787
#define ID_FF_SLOW 32788
#define ID_RW_1X 32790
#define ID_RW_2X 32791
#define ID_RW_5X 32792
#define ID_RW_10X 32793
#define ID_RW_20X 32794
#define ID_ROOT_MENU 32796
#define ID_AUDIO_MENU 32797
#define ID_SUBTITLE_MENU 32798
#define ID_CHAPTER_MENU 32799
#define ID_CC_ON 32804
#define ID_CC_OFF 32805
#define ID_ABOUT 32807
#define ID_SUB_OFF 32808
#define ID_ASPECT_DEFINE 32810
#define ID_ASPECT_ANAM 32811
#define ID_ASPECT_NONANAM 32812
#define ID_ASPECT_LETTERBOX 32813
#define ID_BOOK_ADD 32814
#define ID_BUTTON32819 32819
#define ID_BUTTON32820 32820
#define ID_ONSCREEN 32821
#define ID_VID_BRIGHTNESS 32824
#define ID_VID_CONTRAST 32825
#define ID_VID_HUE 32826
#define ID_VID_SATURATION 32827
#define ID_OVERSCAN 32828
#define ID_VID_GAMMA 32829
#define ID_MENU_CHAPTER 32830
#define ID_MENU_AUDIO 32831
#define ID_MENU_ANGLE 32832
#define ID_MENU_FF 32833
#define ID_MENU_SUBTITLES 32834
#define ID_CLOSED_CAPTIONS 32835
#define ID_BOOK_DELETE 32836
#define ID_ANGLE_MENU 32837
#define ID_RESUME 32838
#define ID_MENU_TITLE 32839
#define ID_SETUP 32841
#define ID_ADJUSTVIDEO 32842
#define ID_ASPECT_LOCK 32843
#define ID_SETSTARTPOINT 32846
#define ID_K_RETURN 32849
#define ID_K_UP 32850
#define ID_K_DOWN 32851
#define ID_K_LEFT 32852
#define ID_K_RIGHT 32853
#define ID_K_FF 32854
#define ID_K_RW 32855
#define ID_K_ESCAPE 32856
#define ID_NEXTAR 32857
#define ID_INFO 32858
#define ID_ARFIRST 32859
#define ID_AR2 32860
#define ID_AR3 32861
#define ID_AR4 32862
#define ID_AR5 32863
#define ID_AR6 32864
#define ID_AR7 32865
#define ID_AR8 32866
#define ID_AR9 32867
#define ID_ARLAST 32868
#define ID_EJECT 32870
#define ID_CONTEXT 32872
#define ID_ALTEXIT 32873
#define ID_MINIMIZE 32874
#define ID_NEXTSUB 32875
#define ID_NEXTAUDIO 32876
#define ID_REPLAY 32877
#define ID_JUMP 32878
#define ID_FRAMESTEP 32879
#define ID_ABREPEAT 32880
#define ID_CHAPTITREP 32881
#define ID_NEXT_ANGLE 32883
#define ID_OPEN 32884
#define ID_NEXT_TIT 32885
#define ID_STATS 32886
#define ID_CAPTURE 32887
#define ID_BK_RESUME 32888
#define ID_DEINTERLACE 32889
#define ID_VOLUP 32891
#define ID_VOLDOWN 32892
#define ID_NEXTDISK 32893
#define ID_SHOWTIME 32894
#define ID_CC_NUDGE_UP 32895
#define ID_CC_NUDGE_DOWN 32896
#define ID_UPGRADE 32897
#define ID_NEXT_FILE 32898
#define ID_PREVIOUS_FILE 32899
#define ID_TSPROG 32901
#define ID_PREV_TIT 32902
#define ID_SLOW 32904
#define ID_CCTOGGLE 32905
#define ID_AR11 32906
#define ID_AR12 32907
#define ID_AR13 32908
#define ID_AR14 32909
#define ID_AR15 32910
#define ID_AR16 32911
#define ID_AR17 32912
#define ID_AR18 32913
#define ID_AR19 32914
#define ID_AR20 32915
#define ID_VMRSTATS 32916
#define ID_LIPDOWN 32917
#define ID_LIPUP 32918
#define ID_MUTE 32919
#define ID_BLANKING 32920
#define ID_TOGGLE 32922
#define ID_MOVELEFT 32924
#define ID_MOVERIGHT 32925
#define ID_MOVEUP 32926
#define ID_MOVEDOWN 32927
#define ID_H_EXPAND 32928
#define ID_H_CONTRACT 32929
#define ID_V_EXPAND 32930
#define ID_V_CONTRACT 32931
#define ID_ZOOM_IN 32932
#define ID_ZOOM_OUT 32933
#define ID_BL_LEFT 32934
#define ID_BL_RIGHT 32935
#define ID_BT_UP 32936
#define ID_BT_DOWN 32937
#define ID_BR_LEFT 32938
#define ID_BR_RIGHT 32939
#define ID_BB_UP 32940
#define ID_BB_DOWN 32941
#define ID_STREAM 32943
"""
import asynchat
import socket
import asyncore
import threading
import new
ttRequests = (
('IP_APPLICATION', '0000', 'Request Application name'),
('IP_VERSION', '0001', 'Request Application version'),
('IP_FULLSCREEN', '0510', 'Request Fullscreen/windowed status'),
('IP_MEDIASTATE', '1000', 'Request MediaState'),
('IP_MEDIATIME', '1010', 'Request Media time'),
('IP_ENDOFMEDIA', '1030', 'End of media'),
('IP_FORMAT', '1040', 'Request Video Format'),
('IP_GETAR', '1300', 'Request Current Aspect Ratio'),
('IP_ARCOUNT', '1310', 'Request Aspect Ratio Count'),
('IP_ARNAMES', '1320', 'ARequest Aspect Ratio Names'),
('IP_CURFILE', '1400', 'Request Current file'),
('IP_DISKINSERTION', '1410', 'Disk inserted'),
('IP_DISKEJECTION', '1420', 'Disk ejected'),
('IP_DVDUNIQUEID', '1500', 'DVD unique ID'),
('IP_DVDTITLE', '1510', 'Request Current Title'),
('IP_DVDTITLECOUNT', '1520', 'Request Title count'),
('IP_DVDCHAPTER', '1600', 'Request Current Chapter'),
('IP_DVDCHAPTERCOUNT', '1610', 'Request Chapter count'),
('IP_DVDAUDIO', '1700', 'Request Current audio stream'),
('IP_DVDAUDIOCOUNT', '1720', 'Request Audio stream count'),
('IP_DVDAUDIONAMES', '1730', 'Request Audio stream names'),
('IP_DVDSUBTITLE', '1800', 'Request Current subtitle stream'),
('IP_DVDSUBTITLECOUNT', '1820', 'Request Subtitle stream count'),
('IP_DVDSUBTITLENAMES', '1830', 'Request Subtitle names (name|name)'),
('IP_DVDANGLE', '1900', 'Request Current angle'),
('IP_DVDANGLECOUNT', '1920', 'Request Angle count'),
('IP_DVDMENUMODE', '2000', 'Request Menu mode'),
('IP_DOMAIN', '2010', 'Request DVD Domain'),
('IP_GETVOLUME', '2100', 'Request Current volume'),
('IP_GETAUDIOOUTPUT', '2120', 'Request Current audio output'),
('IP_GETLISTCOUNT', '3050', 'Request Current list count'),
('IP_GETLIST', '3060', 'Request playlist'),
('IP_GETPRIVATE', '4010', 'Request Private app string'),
('IP_COUNTCHANGERS', '8110', 'CountChangers'),
)
ttCommands = (
('IP_FLASH', '0500', 'OSD Flash message','Message'),
('IP_MEDIAPOS', '1020', 'Set media time', 'Time(hh:mm:ss)'),
('IP_SETAR', '1330', 'Set Current AR', 'AR number'),
('IP_DVDPLAYTITLE', '1530', 'Play Title', 'Title Number'),
('IP_DVDPLAYCHAPTER', '1620', 'Play chapter', 'Chapter number'),
('IP_DVDPLAYTITCHAP', '1630', 'Play Chapter in Title', 'Title/Chapter (space delimited)'),
('IP_DVDSETAUDIO', '1710', 'Set audio stream','Stream number'),
('IP_DVDSETSUBTITLE', '1810', 'Set subtitle stream', 'Stream number (-1 to disable)'),
('IP_DVDSETANGLE', '1910', 'Set angle', 'Angle'),
('IP_SETVOLUME', '2110', 'Set Current volume', 'Volume'),
('IP_SETAUDIOOUTPUT', '2130', 'Set audio output', 'Audio Output'),
('IP_ADDBOOKMARK', '2200', 'Add a bookmark', ''),
('IP_NEXTBOOKMARK', '2210', 'Next bookmark', ''),
('IP_PREVBOOKMARK', '2220', 'Previous bookmark', ''),
('IP_PLAYFILE', '3000', 'Play file', 'Filename'),
('IP_ADDFILE', '3010', 'Add file to playlist', 'Filename'),
('IP_CLEARLIST', '3020', 'Clear playlist', ''),
('IP_PLAYATINDEX', '3040', 'Play item at index', 'Index'),
('IP_GETINDEX', '3030', 'Current item index', 'Index'),
('IP_DELATINDEX', '3070', 'Delete file at index', 'Index'),
('IP_SETPRIVATE', '4000', 'Private app string', 'String'),
('IP_KEYPRESS', '5010', 'Key code', 'Key-Code'),
('ID_PLAY', '32771', 'Play', ''),
('ID_STOP', '32772', 'Stop', ''),
('ID_PAUSE', '32773', 'Pause', ''),
('ID_NEXT', '32774', 'Next', ''),
('ID_PREVIOUS', '32775', 'Previous', ''),
('ID_EXIT', '32776', 'Exit', ''),
('ID_FF', '32777', 'FastForward', ''),
('ID_RW', '32778', 'Fast Rewind', ''),
('ID_MENU_LIST', '32779', 'Menu List', ''),
('ID_TITLE_MENU', '32780', 'Title Menu', ''),
('ID_FF_1X', '32782', 'Normal Play', ''),
('ID_FF_2X', '32784', 'Fast Forward 2x', ''),
('ID_FF_5X', '32785', 'Fast Forward 5x', ''),
('ID_FF_10X', '32786', 'Fast Forward 10x', ''),
('ID_FF_20X', '32787', 'Fast Forward 20x', ''),
('ID_FF_SLOW', '32788', 'Fast Forward Slow', ''),
('ID_RW_1X', '32790', 'Reverse Play', ''),
('ID_RW_2X', '32791', 'Fast Reverse 2X', ''),
('ID_RW_5X', '32792', 'Faste Reverse 5X', ''),
('ID_RW_10X', '32793', 'Fast Reverse 10X', ''),
('ID_RW_20X', '32794', 'Fast Reverse 20X', ''),
('ID_ROOT_MENU', '32796', 'Root Menu', ''),
('ID_AUDIO_MENU', '32797', 'Audio Menu', ''),
('ID_SUBTITLE_MENU', '32798', 'Subtitle Menu', ''),
('ID_CHAPTER_MENU', '32799', 'Chapter Menu', ''),
('ID_CC_ON', '32804', 'Closed Captions On', ''),
('ID_CC_OFF', '32805', 'Closed Captions Off', ''),
('ID_ABOUT', '32807', 'About', ''),
('ID_SUB_OFF', '32808', 'Subtitles Off', ''),
('ID_ASPECT_DEFINE', '32810', 'Define Aspect Ratio', ''),
('ID_ASPECT_ANAM', '32811', 'AR anamorph', ''),
('ID_ASPECT_NONANAM', '32812', 'AR non anamorph', ''),
('ID_ASPECT_LETTERBOX', '32813', 'AR Letterbox', ''),
('ID_BOOK_ADD', '32814', 'Add Bookmark', ''),
('ID_BUTTON32819', '32819', 'BUTTON32819', ''),
('ID_BUTTON32820', '32820', 'BUTTON32820', ''),
('ID_ONSCREEN', '32821', 'On Screen', ''),
('ID_VID_BRIGHTNESS', '32824', 'Brightness', ''),
('ID_VID_CONTRAST', '32825', 'Contrast', ''),
('ID_VID_HUE', '32826', 'Hue', ''),
('ID_VID_SATURATION', '32827', 'Saturation', ''),
('ID_OVERSCAN', '32828', 'Overscan', ''),
('ID_VID_GAMMA', '32829', 'Gamma', ''),
('ID_MENU_CHAPTER', '32830', 'Menu Chapter', ''),
('ID_MENU_AUDIO', '32831', 'Menu Audio', ''),
('ID_MENU_ANGLE', '32832', 'Menu Angle', ''),
('ID_MENU_FF', '32833', 'Menu FF', ''),
('ID_MENU_SUBTITLES', '32834', 'Menu Subtitles', ''),
('ID_CLOSED_CAPTIONS', '32835', 'Closed Captions', ''),
('ID_BOOK_DELETE', '32836', 'Delete Bookmark', ''),
('ID_ANGLE_MENU', '32837', 'Angle Menu', ''),
('ID_RESUME', '32838', 'Resume', ''),
('ID_MENU_TITLE', '32839', 'Menu Title', ''),
('ID_SETUP', '32841', 'Setup', ''),
('ID_ADJUSTVIDEO', '32842', 'Adjust Video', ''),
('ID_ASPECT_LOCK', '32843', 'Lock Aspect ratio', ''),
('ID_SETSTARTPOINT', '32846', 'Set Startpoint', ''),
('ID_K_RETURN', '32849', 'Key Return', ''),
('ID_K_UP', '32850', 'Key Up', ''),
('ID_K_DOWN', '32851', 'Key Down', ''),
('ID_K_LEFT', '32852', 'Key Left', ''),
('ID_K_RIGHT', '32853', 'Key Right', ''),
('ID_K_FF', '32854', 'Key FastForward', ''),
('ID_K_RW', '32855', 'Key Rewind', ''),
('ID_K_ESCAPE', '32856', 'Key Escape', ''),
('ID_NEXTAR', '32857', 'Next Aspect ratio', ''),
('ID_INFO', '32858', 'Info', ''),
('ID_ARFIRST', '32859', 'First Aspect Ratio', ''),
('ID_AR2', '32860', 'Aspect ratio 2', ''),
('ID_AR3', '32861', 'Aspect ratio 3', ''),
('ID_AR4', '32862', 'Aspect ratio 4', ''),
('ID_AR5', '32863', 'Aspect ratio 5', ''),
('ID_AR6', '32864', 'Aspect ratio 6', ''),
('ID_AR7', '32865', 'Aspect ratio 7', ''),
('ID_AR8', '32866', 'Aspect ratio 8', ''),
('ID_AR9', '32867', 'Aspect ratio 9', ''),
('ID_ARLAST', '32868', 'Last Aspect ratio', ''),
('ID_EJECT', '32870', 'Eject', ''),
('ID_CONTEXT', '32872', 'Context', ''),
('ID_ALTEXIT', '32873', 'ALT Exit', ''),
('ID_MINIMIZE', '32874', 'Minimize', ''),
('ID_NEXTSUB', '32875', 'Next Subtitle', ''),
('ID_NEXTAUDIO', '32876', 'Next Audio', ''),
('ID_REPLAY', '32877', 'Replay', ''),
('ID_JUMP', '32878', 'Jump', ''),
('ID_FRAMESTEP', '32879', 'Framestep', ''),
('ID_ABREPEAT', '32880', 'A/B-Repeat', ''),
('ID_CHAPTITREP', '32881', 'Chapter Title Repeat', ''),
('ID_NEXT_ANGLE', '32883', 'Next Angle', ''),
('ID_OPEN', '32884', 'Open', ''),
('ID_NEXT_TIT', '32885', 'Next Title', ''),
('ID_STATS', '32886', 'Statistics', ''),
('ID_CAPTURE', '32887', 'Capture', ''),
('ID_BK_RESUME', '32888', 'BK Resume', ''),
('ID_DEINTERLACE', '32889', 'Deinterlace', ''),
('ID_VOLUP', '32891', 'Volume Up', ''),
('ID_VOLDOWN', '32892', 'Volume Down', ''),
('ID_NEXTDISK', '32893', 'Next Disk', ''),
('ID_SHOWTIME', '32894', 'Show Time', ''),
('ID_CC_NUDGE_UP', '32895', 'CC Nudge Up', ''),
('ID_CC_NUDGE_DOWN', '32896', 'CC Nudge Down', ''),
('ID_UPGRADE', '32897', 'Upgrade', ''),
('ID_NEXT_FILE', '32898', 'Next File', ''),
('ID_PREVIOUS_FILE', '32899', 'Previous File', ''),
('ID_TSPROG', '32901', 'TSPROG', ''),
('ID_PREV_TIT', '32902', 'Previous Title', ''),
('ID_SLOW', '32904', 'Slow', ''),
('ID_CCTOGGLE', '32905', 'Closed Captions Toggle', ''),
('ID_AR11', '32906', 'Aspect ratio 11', ''),
('ID_AR12', '32907', 'Aspect ratio 12', ''),
('ID_AR13', '32908', 'Aspect ratio 13', ''),
('ID_AR14', '32909', 'Aspect ratio 14', ''),
('ID_AR15', '32910', 'Aspect ratio 15', ''),
('ID_AR16', '32911', 'Aspect ratio 16', ''),
('ID_AR17', '32912', 'Aspect ratio 17', ''),
('ID_AR18', '32913', 'Aspect ratio 18', ''),
('ID_AR19', '32914', 'Aspect ratio 19', ''),
('ID_AR20', '32915', 'Aspect ratio 20', ''),
('ID_VMRSTATS', '32916', 'VMR Statistics', ''),
('ID_LIPDOWN', '32917', 'Lipsync down', ''),
('ID_LIPUP', '32918', 'Lipsync Up', ''),
('ID_MUTE', '32919', 'Mute', ''),
('ID_BLANKING', '32920', 'Blanking', ''),
('ID_TOGGLE', '32922', 'Toggle', ''),
('ID_MOVELEFT', '32924', 'Move Left', ''),
('ID_MOVERIGHT', '32925', 'Move Right', ''),
('ID_MOVEUP', '32926', 'Move Up', ''),
('ID_MOVEDOWN', '32927', 'Move Down', ''),
('ID_H_EXPAND', '32928', 'Horizontal Expand', ''),
('ID_H_CONTRACT', '32929', 'Horizontal Contract', ''),
('ID_V_EXPAND', '32930', 'Vertical Expand', ''),
('ID_V_CONTRACT', '32931', 'Vertical Contract', ''),
('ID_ZOOM_IN', '32932', 'Zoom In', ''),
('ID_ZOOM_OUT', '32933', 'Zoom Out', ''),
('ID_BL_LEFT', '32934', 'BL_LEFT', ''),
('ID_BL_RIGHT', '32935', 'BL_RIGHT', ''),
('ID_BT_UP', '32936', 'BT_UP', ''),
('ID_BT_DOWN', '32937', 'BT_DOWN', ''),
('ID_BR_LEFT', '32938', 'BR_LEFT', ''),
('ID_BR_RIGHT', '32939', 'BR_RIGHT', ''),
('ID_BB_UP', '32940', 'BB_UP', ''),
('ID_BB_DOWN', '32941', 'BB_DOWN', ''),
('ID_STREAM', 32943, 'STREAM', ''),
)
ttAutoKillerAndChangerCommands = (
('IP_LAUNCH', '8000', 'Launch AutoKiller'),
('IP_QUIT', '8010', 'Quit Autokiller'),
('IP_MOUNTDISK', '8020', 'Mount Disk', 'Changer/Slot (comma delimited)'),
('IP_UNMOUNTDISK', '8030', 'Unmount Disk', 'Changer/Slot (comma delimited)'),
('IP_EJECTDISK', '8040', 'Eject Disk', 'Changer/Slot (comma delimited)'),
('IP_GETSLOTDATA', '8050', 'GETSLOTDATA', 'Changer, Slot'),
('IP_GETDRIVEDATA', '8060', 'GETDRIVEDATA', 'Changer ->DriveData'),
('IP_CHECKCHANGED', '8070', 'CHECKCHANGED'),
('IP_REBUILDDATA', '8080', 'REBUILDDATA'),
('IP_DATACHANGED', '8100', 'Notification of data change'),
)
class TheaterTekSession(asynchat.async_chat):
"""
Handles a Theatertek TCP/IP session.
"""
def __init__ (self, plugin, address):
self.plugin = plugin
# Call constructor of the parent class
asynchat.async_chat.__init__(self)
# Set up input line terminator
self.set_terminator('\r\n')
# Initialize input data buffer
self.buffer = ''
# create and connect a socket
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
eg.RestartAsyncore()
self.settimeout(1.0)
try:
self.connect(address)
except:
pass
def handle_connect(self):
"""
Called when the active opener's socket actually makes a connection.
"""
self.plugin.TriggerEvent("Connected")
def handle_expt(self):
# connection failed
self.plugin.isSessionRunning = False
self.plugin.TriggerEvent("NoConnection")
self.close()
def handle_close(self):
"""
Called when the channel is closed.
"""
self.plugin.isSessionRunning = False
self.plugin.TriggerEvent("ConnectionLost")
self.close()
def collect_incoming_data(self, data):
"""
Called with data holding an arbitrary amount of received data.
"""
self.buffer = self.buffer + data
def found_terminator(self):
"""
Called when the incoming data stream matches the termination
condition set by set_terminator.
"""
# call the plugins handler method
self.plugin.ValueUpdate(self.buffer)
# reset the buffer
self.buffer = ''
class stdAction(eg.ActionClass):
def __call__(self):
self.plugin.DoCommand(self.value)
class stdActionWithStringParameter(eg.ActionWithStringParameter):
def __call__(self, Param):
self.plugin.DoCommand(self.value + " " + Param)
class wmAction(eg.ActionClass):
def __call__(self):
self.plugin.DoCommand("5000 " + self.value)
class TheaterTek(eg.PluginClass):
def __init__(self):
self.host = "localhost"
self.port = 2663
self.isSessionRunning = False
self.timeline = ""
self.waitStr = None
self.waitFlag = threading.Event()
self.PlayState = -1
self.lastMessage = {}
self.lastSubtitleNum = 0
self.lastSubtitlesEnabled = False
self.lastAudioTrackNum = 0
group = self.AddGroup('Requests')
for className, scancode, descr in ttRequests:
clsAttributes = dict(name=descr, value=scancode)
cls = new.classobj(className, (stdAction,), clsAttributes)
group.AddAction(cls)
group = self.AddGroup('Commands')
for className, scancode, descr, ParamDescr in ttCommands:
clsAttributes = dict(name=descr, value=scancode)
if ParamDescr == "":
if className[0:3] == "IP_":
cls = new.classobj(className, (stdAction,), clsAttributes)
else:
cls = new.classobj(className, (wmAction,), clsAttributes)
else:
cls = new.classobj(className, (stdActionWithStringParameter,), clsAttributes)
cls.parameterDescription = ParamDescr
group.AddAction(cls)
def __start__(
self,
host="localhost",
port=2663,
dummy1=None,
dummy2=None,
useNewEvents=False
):
self.host = host
self.port = port
self.events = self.ttEvents
ttEvents = {
"0000": "ApplicationName",
"0001": "Version",
"0500": "OSD",
"0510": (
"WindowState",
{
"0": "Minimized",
"1": "Windowed",
"2": "Fullscreen"
},
),
"1000": (
"MediaState",
{
"0": "Stopped",
"1": "Playing",
"2": "Paused",
"3": "FF",
"4": "RW"
},
),
"1010": "MediaTime",
"1030": "EndOfMedia",
"1040": (
"Format",
{
"0": "NTSC",
"1": "PAL",
},
),
"1300": "AspectRatio",
"1310": "AspectRatioCount",
"1320": "AspectRatioNames",
"1400": "Currentfile",
"1410": "DiskInserted",
"1420": "DiskEjected",
"1500": "DVDUniqueID",
"1510": "CurrentTitle",
"1520": "TitleCount",
"1600": "CurrentChapter",
"1610": "ChapterCount",
"1700": "CurrentAudioStream",
"1720": "AudioStreamCount",
"1730": "AudioStreamNames",
"1800": "CurrentSubtitleStream",
"1820": "SubtitleStreamCount",
"1830": "SubtitleNames",
"1900": "CurrentAngle",
"1920": "AngleCount",
"2000": (
"MenuMode",
{
"0": "Off",
"1": "On",
},
),
"2010": "DVDDomain",
"2100": "CurrentVolume",
"2120": "CurrentAudioOutput",
"3050": "CurrentListCount",
"3060": "Playlist",
"4010": "PrivateAppString",
"8110": "CountChangers",
}
def ValueUpdate(self, text):
if text == self.waitStr:
self.waitStr = None
self.waitFlag.set()
return
header = text[0:4]
state = text[5:].decode('utf-8')
self.lastMessage[header] = state
ttEvent = self.ttEvents.get(header, None)
if ttEvent is not None:
if type(ttEvent) == type({}):
eventString = ttEvent.get(state, None)
if eventString is not None:
self.TriggerEvent(eventString)
else:
self.TriggerEvent(header, [state])
elif type(ttEvent) == type(()):
suffix2 = ttEvent[1].get(state, None)
if suffix2 is not None:
self.TriggerEvent(ttEvent[0] + "." + suffix2)
else:
self.TriggerEvent(ttEvent[0] + "." + str(state))
else:
if state == "":
self.TriggerEvent(ttEvent)
else:
self.TriggerEvent(ttEvent, [state])
return
else:
self.TriggerEvent(header, [state])
@eg.LogIt
def DoCommand(self, cmdstr):
self.waitFlag.clear()
self.waitStr = cmdstr
if not self.isSessionRunning:
self.session = TheaterTekSession(self, (self.host, self.port))
self.isSessionRunning = True
try:
self.session.sendall(cmdstr + "\r\n")
except:
self.isSessionRunning = False
self.TriggerEvent('close')
self.session.close()
self.waitFlag.wait(1.0)
self.waitStr = None
self.waitFlag.set()
def SetOSD(self, text):
self.DoCommand("1200 " + text)
def Configure(
self,
host="localhost",
port=2663,
dummy1=None,
dummy2=None
):
panel = eg.ConfigPanel(self)
hostEdit = panel.TextCtrl(host)
portEdit = panel.SpinIntCtrl(port, max=65535)
panel.AddLine("TCP/IP host:", hostEdit)
panel.AddLine("TCP/IP port:", portEdit)
while panel.Affirmed():
panel.SetResult(
hostEdit.GetValue(),
portEdit.GetValue(),
None,
None
)
class MyCommand(eg.ActionWithStringParameter):
name = "Raw Command"
def __call__(self, cmd):
self.plugin.DoCommand(cmd)
| EventGhost/EventGhost | plugins/TheaterTek/__init__.py | Python | gpl-2.0 | 31,794 |
<?php
/*
Plugin Name: Social Discussion
Description: Synchronizes the relevant discussion from social networks in a separate tab on your page. <br /><strong>Requires <em>Custom Comments Template</em> add-on to be activated.</strong>
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: Ve Bailovity (Incsub)
*/
/**
* Handles admin pages, settings and procedures.
*/
class Wdcp_Sd_AdminPages {
private $_data;
private function __construct () {
$this->_data = new Wdcp_Options;
}
public static function serve () {
$me = new Wdcp_Sd_AdminPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_action('wdcp-options-plugins_options', array($this, 'register_settings'));
$services = $this->_data->get_option('sd_services');
$services = $services ? $services : array();
if (in_array('facebook', $services)) {
add_action('wdcp-remote_comment_posted-facebook', array($this, 'handle_facebook_comment_sent'), 10, 3);
}
if (in_array('twitter', $services)) {
add_action('wdcp-remote_comment_posted-twitter', array($this, 'handle_twitter_comment_sent'), 10, 3);
}
}
/* ----- Comments posted handlers -----*/
function handle_facebook_comment_sent ($comment_id, $result, $data) {
$this->_handle_comment_sent($comment_id, 'facebook', $result['id'], $data);
}
function handle_twitter_comment_sent ($comment_id, $result, $data) {
$this->_handle_comment_sent($comment_id, 'twitter', @$result->id_str, $data);
}
/**
* Adds Social Discussion root entry.
*/
private function _handle_comment_sent ($comment_id, $type, $remote_id, $data) {
if (!$remote_id) return false;
$post = array(
'post_content' => $data['comment_content'],
'post_type' => 'wdcp_social_discussion_root',
'post_status' => 'publish',
);
$post_id = wp_insert_post($post);
$meta = array(
'sd_type' => $type,
'remote_id' => $remote_id,
);
update_post_meta($post_id, 'wdcp_sd_meta', $meta);
add_comment_meta($comment_id, 'wdcp_sd_root', $post_id) ;
}
/* ----- Settings ----- */
function register_settings () {
add_settings_section('wdcp_sd_settings', __('Social Discussion', 'wdcp'), array($this, 'check_cct_presence'), 'wdcp_options');
if (!class_exists('Wdcp_Cct_Admin_Pages')) return false;
add_settings_field('wdcp_sd_services', __('Sync discussions from these services', 'wdcp'), array($this, 'create_services_box'), 'wdcp_options', 'wdcp_sd_settings');
add_settings_field('wdcp_sd_default_service', __('Default discussion tab', 'wdcp'), array($this, 'create_default_service_box'), 'wdcp_options', 'wdcp_sd_settings');
add_settings_field('wdcp_sd_schedule', __('Schedule', 'wdcp'), array($this, 'create_schedule_box'), 'wdcp_options', 'wdcp_sd_settings');
add_settings_field('wdcp_sd_override_theme', __('Appearance', 'wdcp'), array($this, 'create_override_theme_box'), 'wdcp_options', 'wdcp_sd_settings');
}
function check_cct_presence () {
if (class_exists('Wdcp_Cct_Admin_Pages')) return true;
echo '<div class="error below-h2"><p>' . __('Please, activate the <b>Custom Comments Template</b> add-on.', 'wdcp') . '</p></div>';
}
function create_services_box () {
$_services = array(
'facebook' => __('Facebook', 'wdcp'),
'twitter' => __('Twitter', 'wdcp'),
);
$services = $this->_data->get_option('sd_services');
$services = $services ? $services : array();
foreach ($_services as $service => $label) {
$checked = in_array($service, $services) ? 'checked="checked"' : '';
echo '' .
"<input type='checkbox' name='wdcp_options[sd_services][]' value='{$service}' id='sd_services-{$service}' {$checked} />" .
' ' .
"<label for='sd_services-{$service}'>{$label}</label>" .
"<br />";
}
echo '<div><small>' . __('Please select service(s) you wish to sync social discussion with.', 'wdcp') . '</small></div>';
}
function create_default_service_box () {
$_services = array(
'facebook' => __('Facebook', 'wdcp'),
'twitter' => __('Twitter', 'wdcp'),
'comments' => __('WordPress Comments', 'wdcp'),
);
$default = $this->_data->get_option('sd_default_service');
$default = $default ? $default : 'comments';
foreach ($_services as $service => $label) {
$checked = ($service == $default) ? 'checked="checked"' : '';
echo '' .
"<input type='radio' name='wdcp_options[sd_default_service]' value='{$service}' id='sd_default_service-{$service}' {$checked} />" .
' ' .
"<label for='sd_default_service-{$service}'>{$label}</label>" .
"<br />";
}
echo '<div><small>' . __('The discussion panel you select here will be open by default on page load.', 'wdcp') . '</small></div>';
}
function create_schedule_box () {
$_schedules = array(
'0' => __('Hourly', 'wdcp'),
'10800' => __('Every 3 hours', 'wdcp'),
'21600' => __('Every 6 hours', 'wdcp'),
'43200' => __('Every 12 hours', 'wdcp'),
'86400' => __('Daily', 'wdcp'),
);
$default = $this->_data->get_option('wdcp_sd_poll_interval');
echo '<select name="wdcp_options[wdcp_sd_poll_interval]">';
foreach ($_schedules as $lag => $lbl) {
$sel = ($lag == $default) ? 'selected="selected"' : '';
echo "<option value='{$lag}' {$sel}>{$lbl} </option>";
}
echo '</select>';
echo '<div><small>' . __('Discussions from your selected networks will be synced this often with your other comments.', 'wdcp') . '</small></div>';
// Limit
$_limits = array(1, 5, 10, 15, 20, 25, 30, 40, 50);
$limit = (int)$this->_data->get_option('sd_limit');
$limit = $limit ? $limit : Wdcp_Sd_Importer::PROCESSING_SCOPE_LIMIT;
echo '<label for="wdcp-sd_limit">' . __('Limit import to this many latest comments:', 'wdcp') . '</label> ';
echo '<select name="wdcp_options[sd_limit]" id="wdcp-sd_limit">';
foreach ($_limits as $lim) {
$sel = ($lim == $limit) ? 'selected="selected"' : '';
echo "<option value='{$lim}' {$sel}>{$lim}</option>";
}
echo '</select>';
echo '<div><small>' . __('Discussion import takes time, so it is a good idea to limit its scope.', 'wdcp') . '</small></div>';
echo '<div><small>' . __('This option lets you choose how many of your latest social comments will be polled for discussion updates.', 'wdcp') . '</small></div>';
}
function create_override_theme_box () {
$checked = $this->_data->get_option('sd_theme_override') ? 'checked="checked"' : '';
echo '' .
'<input type="hidden" name="wdcp_options[sd_theme_override]" value="" />' .
"<input type='checkbox' name='wdcp_options[sd_theme_override]' id='wdcp-sd_theme_override' value='1' {$checked} />" .
' ' .
'<label for="wdcp-sd_theme_override">' . __('Do not load styles - my theme already has all the styles I need', 'wdcp') . '</label>' .
'<div><small>' . __('If you check this option, no social discussion style will be loaded.', 'wdcp') . '</small></div>' .
'';
}
}
/**
* Handles public pages - appearance and requests.
*/
class Wdcp_Sd_PublicPages {
private $_data;
private $_db;
private $_services;
private function __construct () {
global $wpdb;
$this->_data = new Wdcp_Options;
$this->_db = $wpdb;
$services = $this->_data->get_option('sd_services');
$services = $services ? $services : array();
$services[] = 'comments';
$this->_services = $services;
}
public static function serve () {
$me = new Wdcp_Sd_PublicPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_filter('wdcp-wordpress_custom_icon_selector', array($this, 'add_custom_icon_selector'));
add_action('wdcp-load_scripts-public', array($this, 'js_load_scripts'));
add_action('wdcp-load_styles-public', array($this, 'css_load_styles'));
add_action('wdcp-cct-comments_top', array($this, 'comments_top'));
add_action('wdcp-cct-comments_bottom', array($this, 'comments_bottom'));
}
function add_custom_icon_selector ($selector) {
$sd_selector = "#wdcp-sd-discussion_switcher li a#wdcp-sd-discussion-comments-switch";
return $selector ? "{$selector}, {$sd_selector}" : $sd_selector;
}
function js_load_scripts () {
$default = $this->_data->get_option('sd_default_service');
$default = $default ? $default : 'comments';
printf(
'<script type="text/javascript">
var _wdcp_sd = {
"default_service": "%s"
};
</script>',
$default
);
wp_enqueue_script('wdcp-sd-discussion', WDCP_PLUGIN_URL . '/js/discussion.js', array('jquery'));
}
function css_load_styles () {
$override = $this->_data->get_option('sd_theme_override');
if (!current_theme_supports('wdcp-sd-discussion') && !$override) {
wp_enqueue_style('wdcp-sd-discussion', WDCP_PLUGIN_URL . '/css/discussion.css');
}
}
function comments_top ($post_id) {
echo '<ul id="wdcp-sd-discussion_switcher">';
foreach ($this->_services as $service) {
echo "<li><a href='#discussion-{$service}' data-discussion_service='{$service}' id='wdcp-sd-discussion-{$service}-switch'><span>" . ucfirst($service) . '</span></a></li>';
}
echo '</ul>';
echo '<div style="clear:left"></div>';
echo '<div id="wdcp-sd-discussion-comments" class="wdcp-sd-discussion">';
}
function comments_bottom ($post_id) {
echo '</div>'; // #wdcp-sd-discussion-comments
foreach ($this->_services as $service) {
if ('comments' == $service) continue;
echo "<div id='wdcp-sd-discussion-{$service}' class='wdcp-sd-discussion'>";
$this->_get_discussion_for_service($post_id, $service);
echo '</div>';
}
}
private function _get_discussion_for_service ($post_id, $service) {
$post_id = (int)$post_id;
if (!$post_id) return false;
$root_ids = $this->_db->get_col("SELECT meta_value FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key = 'wdcp_sd_root' AND c.comment_post_ID={$post_id} AND c.comment_ID = mc.comment_id");
$root_ids = $root_ids ? $root_ids : array();
switch ($service) {
case 'facebook': return $this->_get_facebook_discussion($root_ids);
case 'twitter': return $this->_get_twitter_discussion($root_ids);
}
return false;
}
private function _get_facebook_discussion ($post_ids) {
foreach ($post_ids as $post_id) {
$post = get_post($post_id);
$meta = get_post_meta($post_id, 'wdcp_sd_meta', true);
if ('facebook' != $meta['sd_type']) continue;
$comments = $this->_db->get_results(
"SELECT * FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key='wdcp_sd_facebook_remote_id' AND c.comment_post_ID={$post_id} AND c.comment_ID=mc.comment_id"
);
$this->_show_post_as_comment($post, 'facebook', $comments);
}
}
private function _get_twitter_discussion ($post_ids) {
foreach ($post_ids as $post_id) {
$post = get_post($post_id);
$meta = get_post_meta($post_id, 'wdcp_sd_meta', true);
if ('twitter' != $meta['sd_type']) continue;
$comments = $this->_db->get_results(
"SELECT * FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key='wdcp_sd_twitter_remote_id' AND c.comment_post_ID={$post_id} AND c.comment_ID=mc.comment_id"
);
$this->_show_post_as_comment($post, 'twitter', $comments);
}
}
private function _show_post_as_comment ($post, $type, $comments) {
$post_id = (int)$post->ID;
$comment = $this->_db->get_row("SELECT * FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key='wdcp_sd_root' AND mc.meta_value={$post_id} AND c.comment_ID=mc.comment_id");
$meta = get_comment_meta($comment->comment_ID, 'wdcp_comment', true);
if ('facebook' == $type) {
$uid = $meta['wdcp_fb_author_id'];
$avatar = "<img class='avatar avatar-40 photo' width='40' height='40' src='http://graph.facebook.com/{$uid}/picture' />";
} else if ('twitter' == $type) {
$url = $meta['wdcp_tw_avatar'];
$avatar = "<img class='avatar avatar-40 photo' width='40' height='40' src='{$url}' />";
}
echo '<ul><li>';
include WDCP_PLUGIN_BASE_DIR . '/lib/forms/wdcp-social_discussion_root_comment.php';
echo '<ul>';
if ('facebook' == $type) {
foreach ($comments as $comment) {
$uid = get_comment_meta($comment->comment_ID, 'wdcp_fb_author_id', true);
$avatar = "<img class='avatar avatar-40 photo' width='40' height='40' src='http://graph.facebook.com/{$uid}/picture' />";
include WDCP_PLUGIN_BASE_DIR . '/lib/forms/wdcp-social_discussion_comment.php';
}
} else if ('twitter' == $type) {
foreach ($comments as $comment) {
$url = esc_url(get_comment_meta($comment->comment_ID, 'wdcp_tw_avatar', true));
$avatar = "<img class='avatar avatar-40 photo' width='40' height='40' src='{$url}' />";
include WDCP_PLUGIN_BASE_DIR . '/lib/forms/wdcp-social_discussion_comment.php';
}
}
echo '</ul>';
echo '</li></ul>';
}
}
/**
* Handles comments import from supported social networks.
*/
class Wdcp_Sd_Importer {
const PROCESSING_SCOPE_LIMIT = 10;
private $_data;
private $_db;
private $_services;
private function __construct () {
global $wpdb;
$this->_data = new Wdcp_Options;
$this->_db = $wpdb;
}
public static function serve () {
$me = new Wdcp_Sd_Importer;
add_action('wdcp-sd_import_comments', array($me, 'import'));
if (!wp_next_scheduled('wdcp-sd_import_comments')) wp_schedule_event(time()+600, 'hourly', 'wdcp-sd_import_comments');
return $me;
}
public function import () {
$services = $this->_data->get_option('sd_services');
$services = $services ? $services : array();
$this->_services = $services;
$limit = (int)$this->_data->get_option('sd_limit');
$limit = $limit ? $limit : self::PROCESSING_SCOPE_LIMIT;
$post_ids = $this->_db->get_col("SELECT DISTINCT meta_value FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key = 'wdcp_sd_root' AND c.comment_ID = mc.comment_id ORDER BY c.comment_date LIMIT {$limit}");
foreach ($post_ids as $post_id) {
$this->_process_discussion($post_id);
}
}
private function _process_discussion ($post_id) {
$post_id = (int)$post_id;
if (!$post_id) return false;
$now = time();
$meta = get_post_meta($post_id, 'wdcp_sd_meta', true);
if (!isset($meta['sd_type']) || !in_array($meta['sd_type'], $this->_services)) return false; // Don't sync this
$last_polled = (int)get_post_meta($post_id, 'wdcp_sd_last_polled', true);
if ($last_polled + (int)$this->_data->get_option('wdcp_sd_poll_interval') > $now) return false; // No need to poll this item
$this->_fetch_discussion($post_id, $meta['remote_id'], $meta['sd_type']);
update_post_meta($post_id, 'wdcp_sd_last_polled', $now);
}
private function _fetch_discussion ($post_id, $remote_id, $type) {
switch ($type) {
case "facebook": return $this->_fetch_facebook_discussion($post_id, $remote_id);
case "twitter": return $this->_fetch_twitter_discussion($post_id, $remote_id);
}
return false;
}
private function _fetch_facebook_discussion ($post_id, $item_id) {
if (!$item_id) return false;
$token = WDCP_APP_ID . '|' . WDCP_APP_SECRET;
$res = wp_remote_get("https://graph.facebook.com/{$item_id}/comments?access_token={$token}", array(
'method' => 'GET',
'timeout' => '5',
'redirection' => '5',
'user-agent' => 'wdcp-sd',
'blocking' => true,
'compress' => false,
'decompress' => true,
'sslverify' => false
));
if (is_wp_error($res)) return false; // Request fail
if ((int)$res['response']['code'] != 200) return false; // Request fail
$body = @json_decode($res['body']);
if (empty($body->data)) return false; // No data found
foreach ($body->data as $item) {
if ($this->_comment_already_imported($item->id, 'facebook')) continue; // We already have this comment, continue.
$data = array(
'comment_post_ID' => $post_id,
'comment_author' => $item->from->name,
'comment_author_url' => 'http://www.facebook.com/profile.php?id=' . $item->from->id,
'comment_content' => $item->message,
'comment_type' => 'wdcp_sd_imported',
'comment_date' => date('Y-m-d H:i:s', strtotime($item->created_time)),
);
$meta = array (
'wdcp_fb_author_id' => $item->from->id,
'wdcp_sd_facebook_remote_id' => $item->id,
);
$comment_id = wp_insert_comment($data);
if (!$comment_id) continue;
foreach ($meta as $mkey => $mval) add_comment_meta($comment_id, $mkey, $mval);
}
}
private function _fetch_twitter_discussion ($post_id, $item_id) {
if (!$item_id) return false;
$res = wp_remote_get(
"http://api.twitter.com/1/statuses/show.json?id={$item_id}", array(
'method' => 'GET',
'timeout' => '5',
'redirection' => '5',
'user-agent' => 'wdcp-sd',
'blocking' => true,
'compress' => false,
'decompress' => true,
'sslverify' => false
)
);
if (is_wp_error($res)) return false; // Request fail
if ((int)$res['response']['code'] != 200) return false; // Request fail
$tweet = @json_decode($res['body']);
$user = $tweet->user->name;
$res = wp_remote_get(
"http://search.twitter.com/search.json?q=to:{$user}", array(
'method' => 'GET',
'timeout' => '5',
'redirection' => '5',
'user-agent' => 'wdcp-sd',
'blocking' => true,
'compress' => false,
'decompress' => true,
'sslverify' => false
)
);
if (is_wp_error($res)) return false; // Request fail
if ((int)$res['response']['code'] != 200) return false; // Request fail
$body = @json_decode($res['body']);
$results = @$body->results ? array_reverse($body->results) : array();
foreach ($results as $item) {
if ($this->_comment_already_imported($item->id_str, 'twitter')) continue; // We already have this comment, continue.
$data = array(
'comment_post_ID' => $post_id,
'comment_author' => $item->from_user,
'comment_author_url' => 'http://www.twitter.com/' . $item->from_user,
'comment_content' => $item->text,
'comment_type' => 'wdcp_sd_imported',
'comment_date' => date('Y-m-d H:i:s', strtotime($item->created_at)),
);
$meta = array (
'wdcp_tw_avatar' => $item->profile_image_url,
'wdcp_sd_twitter_remote_id' => $item->id_str,
);
$comment_id = wp_insert_comment($data);
if (!$comment_id) continue;
foreach ($meta as $mkey => $mval) add_comment_meta($comment_id, $mkey, $mval);
}
}
private function _comment_already_imported ($remote_id, $type) {
$id_str = "wdcp_sd_{$type}_remote_id";
$remote_id = esc_sql($remote_id);
return $this->_db->get_var("SELECT comment_id FROM {$this->_db->commentmeta} WHERE meta_key='{$id_str}' AND meta_value='{$remote_id}'");
}
}
Wdcp_Sd_Importer::serve();
if (is_admin()) Wdcp_Sd_AdminPages::serve();
else Wdcp_Sd_PublicPages::serve();
| bfay/peanut | wp-content/plugins/comments-plus/lib/plugins/wdcp-social_discussion.php | PHP | gpl-2.0 | 19,115 |
<?php
echo "Hello Joomla!"; | Fogush/timetable | tmp/install_518fb38d40ebc/mod_testmodule/mod_testmodule.php | PHP | gpl-2.0 | 27 |