repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
chujieyang/ice
|
cpp/src/Ice/EventHandler.cpp
|
920
|
// **********************************************************************
//
// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
#include <Ice/EventHandler.h>
#include <Ice/Instance.h>
using namespace std;
using namespace Ice;
using namespace IceInternal;
IceUtil::Shared* IceInternal::upCast(EventHandler* p) { return p; }
IceInternal::EventHandler::EventHandler() :
#if defined(ICE_USE_IOCP) || defined(ICE_OS_WINRT)
_ready(SocketOperationNone),
_pending(SocketOperationNone),
_started(SocketOperationNone),
_finish(false),
#else
_disabled(SocketOperationNone),
#endif
_hasMoreData(false),
_registered(SocketOperationNone)
{
}
IceInternal::EventHandler::~EventHandler()
{
}
|
gpl-2.0
|
svn2github/voreen
|
src/core/datastructures/datetime.cpp
|
5867
|
/**********************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Created between 2005 and 2012 by The Voreen Team *
* as listed in CREDITS.TXT <http://www.voreen.org> *
* *
* 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 program. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
* The authors reserve all rights not expressly granted herein. 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/core/datastructures/datetime.h"
#include "voreen/core/io/serialization/xmlserializer.h"
#include "voreen/core/io/serialization/xmldeserializer.h"
#include <sstream>
#include <cstdio>
namespace voreen {
const std::string DateTime::loggerCat_ = "voreen.DateTime";
DateTime::DateTime(Type type /*= DATETIME*/)
: type_(type)
{
setDateTime(0, 0, 0, 0, 0, 0);
}
DateTime::DateTime(int year, int month, int day, int hour, int min, int sec)
: type_(DATETIME)
{
setDateTime(year, month, day, hour, min, sec);
}
DateTime::DateTime(time_t timestamp)
: type_(DATETIME)
{
setTimestamp(timestamp);
}
DateTime DateTime::createDate(int year, int month, int day) {
DateTime dateTime(DATE);
dateTime.setDate(year, month, day);
return dateTime;
}
DateTime DateTime::createTime(int hour, int minute, int second) {
DateTime dateTime(TIME);
dateTime.setTime(hour, minute, second);
return dateTime;
}
std::ostream& operator<<(std::ostream& os, const DateTime& dateTime) {
return os << dateTime.toString();
}
std::string DateTime::toString() const {
char* charString = new char[30];
if (type_ == DATETIME)
sprintf(charString, "%04d-%02d-%02d %02d:%02d:%02d",
getYear(), getMonth(), getDay(), getHour(), getMinute(), getSecond());
else if (type_ == DATE)
sprintf(charString, "%04d-%02d-%02d", getYear(), getMonth(), getDay());
else if (type_ == TIME)
sprintf(charString, "%02d:%02d:%02d", getHour(), getMinute(), getSecond());
else {
LERRORC("voreen.DateTime", "invalid type");
}
std::string result(charString);
delete[] charString;
return result;
}
DateTime::Type DateTime::getType() const {
return type_;
}
void DateTime::setDateTime(int year, int month, int day, int hour, int min, int sec) {
year_ = year;
month_ = month;
day_ = day;
hour_ = hour;
minute_ = min;
second_ = sec;
}
void DateTime::setDate(int year, int month, int day) {
if (type_ == TIME) {
LWARNINGC("voreen.DateTime", "setDate() used on instance of type TIME");
}
year_ = year;
month_ = month;
day_ = day;
}
void DateTime::setTime(int hour, int min, int sec) {
if (type_ == DATE) {
LWARNINGC("voreen.DateTime", "setDate() used on instance of type DATE");
}
hour_ = hour;
minute_ = min;
second_ = sec;
}
int DateTime::getYear() const {
return year_;
}
int DateTime::getMonth() const {
return month_;
}
int DateTime::getDay() const {
return day_;
}
int DateTime::getHour() const {
return hour_;
}
int DateTime::getMinute() const {
return minute_;
}
int DateTime::getSecond() const {
return second_;
}
void DateTime::setTimestamp(time_t timestamp) {
tm* t = gmtime(×tamp);
setDateTime(
t->tm_year + 1900,
t->tm_mon + 1,
t->tm_mday,
t->tm_hour,
t->tm_min,
t->tm_sec);
}
time_t DateTime::getTimestamp() const {
tm dateTime;
dateTime.tm_year = year_ - 1900;
dateTime.tm_mon = month_ - 1;
dateTime.tm_mday = day_;
dateTime.tm_hour = hour_;
dateTime.tm_min = minute_;
dateTime.tm_sec = second_;
return mktime(&dateTime);
}
void DateTime::serialize(XmlSerializer& s) const {
s.serialize("type", type_);
s.serialize("year", year_);
s.serialize("month", month_);
s.serialize("day", day_);
s.serialize("hour", hour_);
s.serialize("minute", minute_);
s.serialize("second", second_);
}
void DateTime::deserialize(XmlDeserializer& s) {
int typeInt = 0;
s.optionalDeserialize<int>("type", typeInt, DATETIME);
type_ = Type(typeInt);
s.deserialize("year", year_);
s.deserialize("month", month_);
s.deserialize("day", day_);
s.deserialize("hour", hour_);
s.deserialize("minute", minute_);
s.deserialize("second", second_);
}
} // namespace
|
gpl-2.0
|
quang-ha/lammps
|
src/USER-MISC/fix_flow_gauss.cpp
|
7270
|
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing authors: Steven E. Strong and Joel D. Eaves
Joel.Eaves@Colorado.edu
------------------------------------------------------------------------- */
#include <cstdlib>
#include <cstring>
#include "fix_flow_gauss.h"
#include "atom.h"
#include "force.h"
#include "group.h"
#include "comm.h"
#include "update.h"
#include "domain.h"
#include "error.h"
#include "citeme.h"
#include "respa.h"
using namespace LAMMPS_NS;
using namespace FixConst;
static const char cite_flow_gauss[] =
"Gaussian dynamics package:\n\n"
"@Article{strong_water_2017,\n"
"title = {The Dynamics of Water in Porous Two-Dimensional Crystals},\n"
"volume = {121},\n"
"number = {1},\n"
"url = {http://dx.doi.org/10.1021/acs.jpcb.6b09387},\n"
"doi = {10.1021/acs.jpcb.6b09387},\n"
"urldate = {2016-12-07},\n"
"journal = {J. Phys. Chem. B},\n"
"author = {Strong, Steven E. and Eaves, Joel D.},\n"
"year = {2017},\n"
"pages = {189--207}\n"
"}\n\n";
FixFlowGauss::FixFlowGauss(LAMMPS *lmp, int narg, char **arg) :
Fix(lmp, narg, arg)
{
if (lmp->citeme) lmp->citeme->add(cite_flow_gauss);
if (narg < 6) error->all(FLERR,"Not enough input arguments");
// a group which conserves momentum must also conserve particle number
dynamic_group_allow = 0;
scalar_flag = 1;
vector_flag = 1;
extscalar = 1;
extvector = 1;
size_vector = 3;
global_freq = 1; //data available every timestep
respa_level_support = 1;
//default respa level=outermost level is set in init()
dimension = domain->dimension;
//get inputs
int tmpFlag;
for (int ii=0; ii<3; ii++)
{
tmpFlag=force->inumeric(FLERR,arg[3+ii]);
if (tmpFlag==1 || tmpFlag==0)
flow[ii]=tmpFlag;
else
error->all(FLERR,"Constraint flags must be 1 or 0");
}
// by default, do not compute work done
workflag=0;
// process optional keyword
int iarg = 6;
while (iarg < narg) {
if ( strcmp(arg[iarg],"energy") == 0 ) {
if ( iarg+2 > narg ) error->all(FLERR,"Illegal energy keyword");
if ( strcmp(arg[iarg+1],"yes") == 0 ) workflag = 1;
else if ( strcmp(arg[iarg+1],"no") != 0 )
error->all(FLERR,"Illegal energy keyword");
iarg += 2;
} else error->all(FLERR,"Illegal fix flow/gauss command");
}
//error checking
if (dimension == 2) {
if (flow[2])
error->all(FLERR,"Can't constrain z flow in 2d simulation");
}
dt=update->dt;
pe_tot=0.0;
}
/* ---------------------------------------------------------------------- */
int FixFlowGauss::setmask()
{
int mask = 0;
mask |= POST_FORCE;
mask |= THERMO_ENERGY;
mask |= POST_FORCE_RESPA;
return mask;
}
/* ---------------------------------------------------------------------- */
void FixFlowGauss::init()
{
//if respa level specified by fix_modify, then override default (outermost)
//if specified level too high, set to max level
if (strstr(update->integrate_style,"respa")) {
ilevel_respa = ((Respa *) update->integrate)->nlevels-1;
if (respa_level >= 0)
ilevel_respa = MIN(respa_level,ilevel_respa);
}
}
/* ----------------------------------------------------------------------
setup is called after the initial evaluation of forces before a run, so we
must remove the total force here too
------------------------------------------------------------------------- */
void FixFlowGauss::setup(int vflag)
{
//need to compute work done if set fix_modify energy yes
if (thermo_energy)
workflag=1;
//get total mass of group
mTot=group->mass(igroup);
if (mTot <= 0.0)
error->all(FLERR,"Invalid group mass in fix flow/gauss");
if (strstr(update->integrate_style,"respa")) {
((Respa *) update->integrate)->copy_flevel_f(ilevel_respa);
post_force_respa(vflag,ilevel_respa,0);
((Respa *) update->integrate)->copy_f_flevel(ilevel_respa);
}
else
post_force(vflag);
}
/* ----------------------------------------------------------------------
this is where Gaussian dynamics constraint is applied
------------------------------------------------------------------------- */
void FixFlowGauss::post_force(int /*vflag*/)
{
double **f = atom->f;
double **v = atom->v;
int *mask = atom->mask;
int *type = atom->type;
double *mass = atom->mass;
double *rmass = atom->rmass;
int nlocal = atom->nlocal;
int ii,jj;
//find the total force on all atoms
//initialize to zero
double f_thisProc[3];
for (ii=0; ii<3; ii++)
f_thisProc[ii]=0.0;
//add all forces on each processor
for(ii=0; ii<nlocal; ii++)
if (mask[ii] & groupbit)
for (jj=0; jj<3; jj++)
if (flow[jj])
f_thisProc[jj] += f[ii][jj];
//add the processor sums together
MPI_Allreduce(f_thisProc, f_tot, 3, MPI_DOUBLE, MPI_SUM, world);
//compute applied acceleration
for (ii=0; ii<3; ii++)
a_app[ii] = -f_tot[ii] / mTot;
//apply added accelleration to each atom
double f_app[3];
double peAdded=0.0;
for( ii = 0; ii<nlocal; ii++)
if (mask[ii] & groupbit) {
if (rmass) {
f_app[0] = a_app[0]*rmass[ii];
f_app[1] = a_app[1]*rmass[ii];
f_app[2] = a_app[2]*rmass[ii];
} else {
f_app[0] = a_app[0]*mass[type[ii]];
f_app[1] = a_app[1]*mass[type[ii]];
f_app[2] = a_app[2]*mass[type[ii]];
}
f[ii][0] += f_app[0]; //f_app[jj] is 0 if flow[jj] is false
f[ii][1] += f_app[1];
f[ii][2] += f_app[2];
//calculate added energy, since more costly, only do this if requested
if (workflag)
peAdded += f_app[0]*v[ii][0] + f_app[1]*v[ii][1] + f_app[2]*v[ii][2];
}
//finish calculation of work done, sum over all procs
if (workflag) {
double pe_tmp=0.0;
MPI_Allreduce(&peAdded,&pe_tmp,1,MPI_DOUBLE,MPI_SUM,world);
pe_tot += pe_tmp;
}
}
void FixFlowGauss::post_force_respa(int vflag, int ilevel, int /*iloop*/)
{
if (ilevel == ilevel_respa) post_force(vflag);
}
/* ----------------------------------------------------------------------
negative of work done by this fix
This is only computed if requested, either with fix_modify energy yes, or with the energy keyword. Otherwise returns 0.
------------------------------------------------------------------------- */
double FixFlowGauss::compute_scalar()
{
return -pe_tot*dt;
}
/* ----------------------------------------------------------------------
return components of applied force
------------------------------------------------------------------------- */
double FixFlowGauss::compute_vector(int n)
{
return -f_tot[n];
}
|
gpl-2.0
|
lokanaft/icms2
|
system/languages/en/controllers/messages/messages.php
|
3380
|
<?php
define('LANG_MESSAGES_CONTROLLER', 'Private messages');
define('LANG_PM_MY_MESSAGES', 'My Messages');
define('LANG_PM_NO_MESSAGES', 'You have no private messages');
define('LANG_PM_NO_NOTICES', 'No notifications');
define('LANG_PM_NO_ACCESS', 'Private messages are not available for your group');
define('LANG_PM_SHOW_OLDER_MESSAGES', 'Show previous messages ↑');
define('LANG_PM_ACTION_IGNORE', 'Ignore');
define('LANG_PM_ACTION_FORGIVE', 'Unignore');
define('LANG_PM_DELETE_CONTACT', 'Delete contact');
define('LANG_PM_DELETE_CONTACT_CONFIRM','Delete the contact from the list?');
define('LANG_PM_IGNORE_CONTACT_CONFIRM','Add the contact to the blacklist? You will not receive messages from this user');
define('LANG_PM_SEND_TO_USER', 'Write a message');
define('LANG_PM_SEND_ERROR', 'Message send error');
define('LANG_PM_YOU_ARE_IGNORED', 'This user added you to the blacklist');
define('LANG_PM_CONTACT_IS_IGNORED', 'This user is in your blacklist');
define('LANG_PM_CONTACT_IS_PRIVATE', 'This user accepts messages only from friends');
define('LANG_PM_LIMIT', 'Number of messages shown at a time');
define('LANG_PM_TIME_DELETE_OLD', 'How to store deleted messages?');
define('LANG_PM_TIME_DELETE_OLD_HINT', '0 - always keep');
define('LANG_PM_REFRESH_TIME', 'New messages requests interval');
define('LANG_PM_REALTIME_MODE', 'Realtime mode');
define('LANG_PM_REALTIME_MODE_SOCKET', 'Socket server [not available]');
define('LANG_PM_REALTIME_SOCKET_HOST', 'Socket server host');
define('LANG_PM_REALTIME_SOCKET_PORT', 'Socket server port');
define('LANG_PM_USE_QUEUE', 'Use the queue system to send e-mail');
define('LANG_PM_PRIVACY_CONTACT', 'Who can send private messages to you?');
define('LANG_PM_NOTIFY_NEW', 'Notify on new messages');
define('LANG_PM_DESKTOP_NOTIFY_NEW', 'Messages from %s');
define('LANG_PM_USER_SEARCH', 'Start typing the name...');
define('LANG_PM_IS_DELETE', 'Message is deleted.');
define('LANG_PM_DO_RESTORE', ' <a href="#" onclick="return icms.messages.restoreMsg(this);">Restore</a>');
define('LANG_PM_CLEAR_NOTICE', 'Clear all notifications');
define('LANG_PM_CLEAR_NOTICE_CONFIRM', 'Really clear all notifications?');
define('LANG_PM_PMAILING', 'Mass send messages');
define('LANG_PM_PMAILING_GROUPS', 'User groups for mailing');
define('LANG_PM_PMAILING_TYPE', 'How to send a message');
define('LANG_PM_PMAILING_TYPE_NOTIFY', 'As notification');
define('LANG_PM_PMAILING_TYPE_MESSAGE', 'As a private message');
define('LANG_PM_PMAILING_SENDED', '%s sended');
define('LANG_PM_NOTIFY', 'notification|notification|notifications');
define('LANG_PM_MESSAGE', 'message|message|messages');
define('LANG_PM_SENDER_USER_ID', 'From whose name should I send');
define('LANG_PM_SENDER_USER_ID_HINT', 'Enter the user email. If not specified, the message will be sent from you.');
define('LANG_PM_PMAILING_NOT_RECIPIENTS', 'No recipients according to specified criteria');
|
gpl-2.0
|
burguin/test01
|
typo3/sysext/extbase/Tests/Unit/Core/BootstrapTest.php
|
3301
|
<?php
namespace TYPO3\CMS\Extbase\Tests\Unit\Core;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
/**
* Test case
*/
class BootstrapTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
{
/**
* @var array A backup of registered singleton instances
*/
protected $singletonInstances = array();
/**
* Sets up this testcase
*/
protected function setUp()
{
$this->singletonInstances = \TYPO3\CMS\Core\Utility\GeneralUtility::getSingletonInstances();
}
protected function tearDown()
{
\TYPO3\CMS\Core\Utility\GeneralUtility::purgeInstances();
\TYPO3\CMS\Core\Utility\GeneralUtility::resetSingletonInstances($this->singletonInstances);
parent::tearDown();
}
/**
* @test
*/
public function configureObjectManagerRespectsOverridingOfAlternativeObjectRegistrationViaPluginConfiguration()
{
/** @var $objectContainer \TYPO3\CMS\Extbase\Object\Container\Container|\PHPUnit_Framework_MockObject_MockObject */
$objectContainer = $this->getMock(\TYPO3\CMS\Extbase\Object\Container\Container::class, array('registerImplementation'));
$objectContainer->expects($this->once())->method('registerImplementation')->with(\TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface::class, 'TYPO3\CMS\Extbase\Persistence\Reddis\PersistenceManager');
\TYPO3\CMS\Core\Utility\GeneralUtility::setSingletonInstance(\TYPO3\CMS\Extbase\Object\Container\Container::class, $objectContainer);
$frameworkSettings['objects'] = array(
'TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface.' => array(
'className' => 'TYPO3\CMS\Extbase\Persistence\Reddis\PersistenceManager'
)
);
/** @var $configurationManagerMock \TYPO3\CMS\Extbase\Configuration\ConfigurationManager|\PHPUnit_Framework_MockObject_MockObject|\TYPO3\CMS\Core\Tests\AccessibleObjectInterface */
$configurationManagerMock = $this->getAccessibleMock(\TYPO3\CMS\Extbase\Configuration\ConfigurationManager::class, array('getConfiguration'));
$configurationManagerMock->expects($this->any())->method('getConfiguration')->with('Framework')->will($this->returnValue($frameworkSettings));
/** @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManager */
$objectManager = $this->getMock(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
/** @var $bootstrapMock \TYPO3\CMS\Extbase\Core\Bootstrap|\PHPUnit_Framework_MockObject_MockObject|\TYPO3\CMS\Core\Tests\AccessibleObjectInterface */
$bootstrapMock = $this->getAccessibleMock(\TYPO3\CMS\Extbase\Core\Bootstrap::class, array('inject'));
$bootstrapMock->_set('objectManager', $objectManager);
$bootstrapMock->_set('configurationManager', $configurationManagerMock);
$bootstrapMock->configureObjectManager();
}
}
|
gpl-2.0
|
sribits/ctorrent
|
bencode.cpp
|
5631
|
#include "./def.h"
#include "bencode.h"
#ifndef WINDOWS
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <limits.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifndef HAVE_SNPRINTF
#include "compat.h"
#endif
static const char* next_key(const char *keylist)
{
for(;*keylist && *keylist != KEY_SP; keylist++);
if(*keylist) keylist++;
return keylist;
}
static size_t compare_key(const char *key,size_t keylen,const char *keylist)
{
for(;keylen && *keylist && *key==*keylist;keylen--,key++,keylist++) ;
if(!keylen) if(*keylist && *keylist!=KEY_SP) return 1;
return keylen;
}
size_t buf_long(const char *b,size_t len,char beginchar,char endchar,int64_t *pi)
{
const char *p = b;
const char *psave;
if(2 > len) return 0; /* buffer too small */
if( beginchar ){
if(*p != beginchar) return 0;
p++; len--;
}
for(psave = p; len && isdigit(*p); p++,len--) ;
if(!len || MAX_INT_SIZ < (p - psave) || *p != endchar) return 0;
if( pi ){
if( beginchar ) *pi = strtoll(b + 1,(char**) 0,10);
else *pi=strtoll(b,(char**) 0,10);
}
return (size_t)( p - b + 1 );
}
size_t buf_int(const char *b,size_t len,char beginchar,char endchar,size_t *pi)
{
size_t r;
if( pi ){
int64_t pl;
r = buf_long(b,len,beginchar,endchar,&pl);
*pi = (size_t) pl;
}else{
r = buf_long(b,len,beginchar,endchar,(int64_t*) 0);
}
return r;
}
size_t buf_str(const char *b,size_t len,const char **pstr,size_t* slen)
{
size_t rl,sl;
rl = buf_int(b,len,0,':',&sl);
if( !rl ) return 0;
if(len < rl + sl) return 0;
if(pstr) *pstr = b + rl;
if(slen) *slen = sl;
return( rl + sl );
}
size_t decode_int(const char *b,size_t len)
{
return(buf_long(b,len,'i','e',(int64_t*) 0));
}
size_t decode_str(const char *b,size_t len)
{
return (buf_str(b,len,(const char**) 0,(size_t*) 0));
}
size_t decode_dict(const char *b,size_t len,const char *keylist)
{
size_t rl,dl,nl;
const char *pkey;
dl = 0;
if(2 > len || *b != 'd') return 0;
dl++; len--;
for(;len && *(b + dl) != 'e';){
rl = buf_str(b + dl,len,&pkey,&nl);
if( !rl || KEYNAME_SIZ < nl) return 0;
dl += rl;
len -= rl;
if(keylist && compare_key(pkey,nl,keylist) == 0){
pkey = next_key(keylist);
if(! *pkey ) return dl;
rl = decode_dict(b + dl,len, pkey);
if( !rl ) return 0;
return dl + rl;
}
rl = decode_rev(b + dl,len,(const char*) 0);
if( !rl ) return 0;
dl += rl;len -= rl;
}
if( !len || keylist) return 0;
return dl + 1; /* add the last char 'e' */
}
size_t decode_list(const char *b,size_t len,const char *keylist)
{
size_t ll,rl;
ll = 0;
if(2 > len || *b != 'l') return 0;
len--; ll++;
for(;len && *(b + ll) != 'e';){
rl = decode_rev(b + ll,len,keylist);
if( !rl ) return 0;
ll += rl; len -= rl;
}
if( !len ) return 0;
return ll + 1; /* add last char 'e' */
}
size_t decode_rev(const char *b,size_t len,const char *keylist)
{
if( !b ) return 0;
switch( *b ){
case 'i': return decode_int(b,len);
case 'd': return decode_dict(b,len,keylist);
case 'l': return decode_list(b,len,keylist);
default: return decode_str(b,len);
}
}
size_t decode_query(const char *b,size_t len,const char *keylist,const char **ps,size_t *pi,int64_t *pl,int method)
{
size_t pos;
char kl[KEYNAME_LISTSIZ];
strcpy(kl,keylist);
pos = decode_rev(b, len, kl);
if( !pos ) return 0;
switch(method){
case QUERY_STR: return(buf_str(b + pos,len - pos, ps, pi));
case QUERY_INT: return(buf_int(b + pos,len - pos, 'i', 'e', pi));
case QUERY_POS:
if(pi) *pi = decode_rev(b + pos, len - pos, (const char*) 0);
return pos;
case QUERY_LONG: return(buf_long(b + pos,len - pos, 'i', 'e', pl));
default: return 0;
}
}
size_t bencode_buf(const char *buf,size_t len,FILE *fp)
{
char slen[MAX_INT_SIZ];
if( MAX_INT_SIZ <= snprintf(slen, MAX_INT_SIZ, "%d:", (int)len) ) return 0;
if( fwrite( slen, strlen(slen), 1, fp) != 1) return 0;
if( fwrite(buf, len, 1, fp) != 1 ) return 0;
return 1;
}
size_t bencode_str(const char *str, FILE *fp)
{
return bencode_buf(str, strlen(str), fp);
}
size_t bencode_int(const uint64_t integer, FILE *fp)
{
char buf[MAX_INT_SIZ];
if( EOF == fputc('i', fp)) return 0;
if( MAX_INT_SIZ <=
snprintf(buf, MAX_INT_SIZ, "%llu", (unsigned long long)integer) )
return 0;
if( fwrite(buf, strlen(buf), 1, fp) != 1 ) return 0;
return (EOF == fputc('e', fp)) ? 0: 1;
}
size_t bencode_begin_dict(FILE *fp)
{
return (EOF == fputc('d',fp)) ? 0 : 1;
}
size_t bencode_begin_list(FILE *fp)
{
return (EOF == fputc('l',fp)) ? 0 : 1;
}
size_t bencode_end_dict_list(FILE *fp)
{
return (EOF == fputc('e',fp)) ? 0 : 1;
}
size_t bencode_path2list(const char *pathname, FILE *fp)
{
const char *pn;
const char *p = pathname;
if( bencode_begin_list(fp) != 1 ) return 0;
for(; *p;){
pn = strchr(p, PATH_SP);
if( pn ){
if( bencode_buf(p, pn - p, fp) != 1) return 0;
p = pn + 1;
}else{
if( bencode_str(p, fp) != 1) return 0;
break;
}
}
return bencode_end_dict_list(fp);
}
size_t decode_list2path(const char *b, size_t n, char *pathname)
{
const char *pb = b;
const char *s = (char *) 0;
size_t r,q;
if( 'l' != *pb ) return 0;
pb++;
n--;
if( !n ) return 0;
for(; n;){
if(!(r = buf_str(pb, n, &s, &q)) ) return 0;
memcpy(pathname, s, q);
pathname += q;
pb += r; n -= r;
if( 'e' != *pb ){*pathname = PATH_SP, pathname++;} else break;
}
*pathname = '\0';
return (pb - b + 1);
}
|
gpl-2.0
|
gromver/yii2-platform-basic
|
modules/news/views/frontend/post/index.php
|
694
|
<?php
/**
* @var $this yii\web\View
*/
use yii\helpers\Html;
/** @var \gromver\platform\basic\modules\menu\models\MenuItem $menu */
$menu = Yii::$app->menuManager->getActiveMenu();
if ($menu) {
$this->title = $menu->isProperContext() ? $menu->title : Yii::t('gromver.platform', 'News');
$this->params['breadcrumbs'] = $menu->getBreadcrumbs($menu->isApplicableContext());
} else {
$this->title = Yii::t('gromver.platform', 'News');
}
//$this->params['breadcrumbs'][] = $this->title;
echo Html::tag('h2', Html::encode($this->title));
echo \gromver\platform\basic\modules\news\widgets\PostList::widget([
'id' => 'post-index',
'context' => $menu ? $menu->path : null,
]);
|
gpl-2.0
|
trasher/glpi
|
front/ruleasset.form.php
|
1297
|
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2021 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
include ('../inc/includes.php');
$rulecollection = new RuleAssetCollection();
include (GLPI_ROOT . "/front/rule.common.form.php");
|
gpl-2.0
|
damianob/xcsoar
|
src/Replay/DemoReplay.hpp
|
1472
|
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2012 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.
}
*/
#ifndef DEMO_REPLAY_HPP
#define DEMO_REPLAY_HPP
#include "AbstractReplay.hpp"
#include "TaskAutoPilot.hpp"
#include "AircraftSim.hpp"
class DemoReplay: public AbstractReplay
{
public:
AutopilotParameters parms;
TaskAutoPilot autopilot;
AircraftSim aircraft;
DemoReplay();
virtual void Start() = 0;
virtual bool Update() = 0;
void Stop();
protected:
virtual void OnStop() = 0;
void Start(const TaskAccessor& task, const GeoPoint& default_location);
bool Update(TaskAccessor& task);
virtual bool UpdateTime();
virtual void ResetTime();
};
#endif
|
gpl-2.0
|
SuriyaaKudoIsc/wikia-app-test
|
extensions/Wikidata/Database scripts/Incremental/ReadPatch.php
|
4846
|
<?php
/* Read a .sql file and apply it to tables with the defined prefix.
NOTE: Since LocalSettings.php loads App.php, which depends on a whole lot of
Wikidata crud, in some circumstances (when your code refers to tables that
no longer exist) it may be wise to comment out the require_once line
in LocalSettings.php which loads App.php before running this script.
*/
define( 'MEDIAWIKI', true );
ob_end_flush();
$wgUseMasterForMaintenance = true;
$sep = PATH_SEPARATOR;
$IP = realpath( dirname( __FILE__ ) . "/../../../../" );
$currentdir = dirname( __FILE__ );
chdir( $IP );
ini_set( 'include_path', ".$sep$IP$sep$IP/extensions/Wikidata/OmegaWiki$sep$IP/includes$sep$IP/languages$sep$IP/maintenance" );
require_once( "Defines.php" );
require_once( "ProfilerStub.php" );
require_once( "LocalSettings.php" );
require_once( "Setup.php" );
require_once( "StartProfiler.php" );
require_once( "Exception.php" );
require_once( "GlobalFunctions.php" );
require_once( "Database.php" );
include_once( "AdminSettings.php" );
global
$wgCommandLineMode, $wgUser, $numberOfBytes;
function ReadSQLFile( $database, $pattern, $prefix, $filename ) {
$fp = fopen( $filename, 'r' );
if ( false === $fp ) {
return "Could not open \"{$filename}\".\n";
}
$cmd = "";
$done = false;
while ( ! feof( $fp ) ) {
$line = trim( fgets( $fp, 1024 ) );
$sl = strlen( $line ) - 1;
if ( $sl < 0 ) { continue; }
if ( '-' == $line { 0 } && '-' == $line { 1 } ) { continue; }
if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
$done = true;
$line = substr( $line, 0, $sl );
}
if ( '' != $cmd ) { $cmd .= ' '; }
$cmd .= "$line\n";
if ( $done ) {
$cmd = str_replace( ';;', ";", $cmd );
$cmd = trim( str_replace( $pattern, $prefix, $cmd ) );
$res = $database->query( $cmd );
if ( false === $res ) {
return "Query \"{$cmd}\" failed with error code \".\n";
}
$cmd = '';
$done = false;
}
}
fclose( $fp );
return true;
}
function getUserId( $userName ) {
$dbr = wfGetDB( DB_SLAVE );
$result = $dbr->query( "select user_id from user where user_name = '$userName'" );
if ( $row = $dbr->fetchObject( $result ) ) {
return $row->user_id;
}
else {
return - 1;
}
}
function setUser( $userid ) {
global $wgUser;
$wgUser->setId( $userid );
$wgUser->loadFromId();
}
function setDefaultDC( $dc ) {
global $wgUser, $wdDefaultViewDataSet;
$groups = $wgUser->getGroups();
foreach ( $groups as $group ) {
$wdGroupDefaultView[$group] = $dc;
}
$wdDefaultViewDataSet = $dc;
}
$dbclass = 'Database' . ucfirst( $wgDBtype ) ;
$database = $wgDBname;
$user = $wgDBadminuser;
$password = $wgDBadminpassword;
$server = $wgDBserver;
# Parse arguments
for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
if ( substr( $arg, 0, 8 ) == '-dataset' ) {
$prefix = next( $argv );
$wdPrefix = $prefix . "_";
}
else if ( substr( $arg, 0, 9 ) == '-template' ) {
$wdTemplate = next( $argv );
}
else if ( substr( $arg, 0, 7 ) == '-server' ) {
$server = next( $argv );
}
else if ( substr( $arg, 0, 9 ) == '-database' ) {
$database = next( $argv );
}
else if ( substr( $arg, 0, 5 ) == '-user' ) {
$user = next( $argv );
}
else if ( substr( $arg, 0, 9 ) == '-password' ) {
$password = next( $argv );
} else {
$args[] = $arg;
}
}
if ( !isset( $wdTemplate ) ) {
echo( "SQL template should be provided!\n" );
echo( "usage: ReadPatch.php -dataset <prefix> -template <sql template> [-server <server> -database <database> -user <username> -password <password>]\n" );
exit();
}
if ( !isset( $wdPrefix ) ) {
echo( "database prefix should be provided!\n" );
echo( "usage: ReadPatch.php -dataset <prefix> -template <sql template> [-server <server> -database <database> -user <username> -password <password>]\n" );
exit();
}
# Do a pre-emptive check to ensure we've got credentials supplied
# We can't, at this stage, check them, but we can detect their absence,
# which seems to cause most of the problems people whinge about
if ( !isset( $user ) || !isset( $password ) ) {
echo( "No superuser credentials could be found. Please provide the details\n" );
echo( "of a user with appropriate permissions to update the database. See\n" );
echo( "AdminSettings.sample for more details.\n\n" );
exit();
}
# Attempt to connect to the database as a privileged user
# This will vomit up an error if there are permissions problems
$wdDatabase = new $dbclass( $server, $user, $password, $database );
if ( !$wdDatabase->isOpen() ) {
# Appears to have failed
echo( "A connection to the database could not be established. Check the\n" );
echo( "values of \$wgDBadminuser and \$wgDBadminpassword.\n" );
exit();
}
ReadSQLFile( $wdDatabase, "/*\$wdPrefix*/", $wdPrefix, $currentdir . DIRECTORY_SEPARATOR . $wdTemplate );
$wdDatabase->close();
?>
|
gpl-2.0
|
ygstand/test2
|
modules/contrib/panelizer/src/Tests/PanelizerNodeFunctionalTest.php
|
5364
|
<?php
namespace Drupal\panelizer\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Basic functional tests of using Panelizer with nodes.
*
* @group panelizer
*/
class PanelizerNodeFunctionalTest extends WebTestBase {
use PanelizerTestTrait;
/**
* {@inheritdoc}
*/
protected $profile = 'standard';
/**
* {@inheritdoc}
*/
public static $modules = [
'block',
'ctools',
'ctools_block',
'layout_plugin',
'node',
'panelizer',
'panelizer_test',
'panels',
'panels_ipe',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$user = $this->drupalCreateUser([
'administer node display',
'administer nodes',
'administer content types',
'create page content',
'create article content',
'administer panelizer',
'access panels in-place editing',
'view the administration theme',
]);
$this->drupalLogin($user);
}
/**
* Tests the admin interface to set a default layout for a bundle.
*/
public function testWizardUI() {
$this->panelize('article', NULL, [
'panelizer[custom]' => TRUE,
]);
// Enter the wizard.
$this->drupalGet('admin/structure/panelizer/edit/node__article__default__default');
$this->assertResponse(200);
$this->assertText('Wizard Information');
$this->assertField('edit-label');
// Contexts step.
$this->clickLink('Contexts');
$this->assertText('@panelizer.entity_context:entity', 'The current entity context is present.');
// Layout selection step.
$this->clickLink('Layout');
$this->assertField('edit-update-layout');
// Content step. Add the Node block to the top region.
$this->clickLink('Content');
$this->clickLink('Add new block');
$this->clickLink('Title');
$edit = [
'region' => 'middle',
];
$this->drupalPostForm(NULL, $edit, t('Add block'));
$this->assertResponse(200);
// Finish the wizard.
$this->drupalPostForm(NULL, [], t('Update and save'));
$this->assertResponse(200);
// Confirm this returned to the main wizard page.
$this->assertText('Wizard Information');
$this->assertField('edit-label');
// Return to the Manage Display page, which is where the Cancel button
// currently sends you. That's a UX WTF and should be fixed...
$this->drupalPostForm(NULL, [], t('Cancel'));
$this->assertResponse(200);
// Confirm the page is back to the content type settings page.
$this->assertFieldChecked('edit-panelizer-custom');
return;
// Now change and save the general setting.
$edit = [
'panelizer[custom]' => FALSE,
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertResponse(200);
$this->assertNoFieldChecked('edit-panelizer-custom');
// Add another block at the Content step and then save changes.
$this->drupalGet('admin/structure/panelizer/edit/node__article__default__default/content');
$this->assertResponse(200);
$this->clickLink('Add new block');
$this->clickLink('Body');
$edit = [
'region' => 'middle',
];
$this->drupalPostForm(NULL, $edit, t('Add block'));
$this->assertResponse(200);
$this->assertText('entity_field:node:body', 'The body block was added successfully.');
$this->drupalPostForm(NULL, [], t('Save'));
$this->assertResponse(200);
$this->clickLink('Content');
$this->assertText('entity_field:node:body', 'The body block was saved successfully.');
// Check that the Manage Display tab changed now that Panelizer is set up.
// Also, the field display table should be hidden.
$this->assertNoRaw('<div id="field-display-overview-wrapper">');
// Disable Panelizer for the default display mode. This should bring back
// the field overview table at Manage Display and not display the link to
// edit the default Panelizer layout.
$this->unpanelize('article');
$this->assertNoLinkByHref('admin/structure/panelizer/edit/node__article__default');
$this->assertRaw('<div id="field-display-overview-wrapper">');
}
/**
* Tests rendering a node with Panelizer default.
*/
public function _testPanelizerDefault() {
$this->panelize('page', NULL, ['panelizer[custom]' => TRUE]);
/** @var \Drupal\panelizer\PanelizerInterface $panelizer */
$panelizer = $this->container->get('panelizer');
$displays = $panelizer->getDefaultPanelsDisplays('node', 'page', 'default');
$display = $displays['default'];
$display->addBlock([
'id' => 'panelizer_test',
'label' => 'Panelizer test',
'provider' => 'block_content',
'region' => 'middle',
]);
$panelizer->setDefaultPanelsDisplay('default', 'node', 'page', 'default', $display);
// Create a node, and check that the IPE is visible on it.
$node = $this->drupalCreateNode(['type' => 'page']);
$out = $this->drupalGet('node/' . $node->id());
$this->assertResponse(200);
$this->verbose($out);
$elements = $this->xpath('//*[@id="panels-ipe-content"]');
if (is_array($elements)) {
$this->assertIdentical(count($elements), 1);
}
else {
$this->fail('Could not parse page content.');
}
// Check that the block we added is visible.
$this->assertText('Panelizer test');
$this->assertText('Abracadabra');
}
}
|
gpl-2.0
|
TheZoker/anspress
|
theme/default/edit.php
|
280
|
<?php
/**
* Edit page
*
* @link http://anspress.io
* @since 2.0.1
* @license GPL 2+
* @package AnsPress
*/
if($editing_post->post_type == 'question')
ap_edit_question_form();
elseif($editing_post->post_type == 'answer')
ap_edit_answer_form($editing_post->post_parent);
|
gpl-2.0
|
paolodedios/uncrustify
|
tests/expected/cpp/30918-Issue_2345-4.cpp
|
59
|
namespace fooD {
void a();
void b();
void c();
void d();
}
|
gpl-2.0
|
hexgnu/Bueno
|
page.php
|
1362
|
<?php get_header(); ?>
<div id="content" class="col-full">
<div id="main" class="col-left">
<?php if ( get_option( 'woo_breadcrumbs' ) == 'true') { yoast_breadcrumb('<div id="breadcrumb"><p>','</p></div>'); } ?>
<?php if (have_posts()) : $count = 0; ?>
<?php while (have_posts()) : the_post(); $count++; ?>
<div class="post">
<h1 class="title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
<div class="entry">
<?php the_content(); ?>
</div>
</div><!-- /.post -->
<?php if ('open' == $post->comment_status) : ?>
<?php comments_template(); ?>
<?php endif; ?>
<?php endwhile; else: ?>
<div class="post">
<p><?php _e('Sorry, no posts matched your criteria.', 'woothemes') ?></p>
</div><!-- /.post -->
<?php endif; ?>
</div><!-- /#main -->
<?php get_sidebar(); ?>
</div><!-- /#content -->
<?php get_footer(); ?>
|
gpl-2.0
|
ampproject/amp-wp
|
templates/meta-taxonomy.php
|
1402
|
<?php
/**
* Post taxonomy term list template part.
*
* 🚫🚫🚫
* DO NOT EDIT THIS FILE WHILE INSIDE THE PLUGIN! Changes You make will be lost when a new version
* of the AMP plugin is released. You need to copy this file out of the plugin and put it into your
* custom theme, for example. To learn about how to customize these Reader-mode AMP templates, please
* see: https://amp-wp.org/documentation/how-the-plugin-works/classic-templates/
* 🚫🚫🚫
*
* @package AMP
*/
/**
* Context.
*
* @var AMP_Post_Template $this
*/
$categories = get_the_category_list( _x( ', ', 'Used between list items, there is a space after the comma.', 'amp' ), '', $this->ID );
?>
<?php if ( $categories ) : ?>
<div class="amp-wp-meta amp-wp-tax-category">
<?php
/* translators: %s: list of categories. */
printf( esc_html__( 'Categories: %s', 'amp' ), $categories ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
?>
</div>
<?php endif; ?>
<?php
$tags = get_the_tag_list(
'',
_x( ', ', 'Used between list items, there is a space after the comma.', 'amp' ),
'',
$this->ID
);
?>
<?php if ( $tags && ! is_wp_error( $tags ) ) : ?>
<div class="amp-wp-meta amp-wp-tax-tag">
<?php
/* translators: %s: list of tags. */
printf( esc_html__( 'Tags: %s', 'amp' ), $tags ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
?>
</div>
<?php endif; ?>
|
gpl-2.0
|
haiweiosu/Angular2.0-Simple-Project-Demo
|
node_modules/angular2/src/core/compiler/shadow_css.d.ts
|
578
|
/**
* This file is a port of shadowCSS from webcomponents.js to TypeScript.
*
* Please make sure to keep to edits in sync with the source file.
*
* Source:
* https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
*
* The original file level comment is reproduced below
*/
export declare class ShadowCss {
strictStyling: boolean;
constructor();
shimStyle(style: string, selector: string, hostSelector?: string): string;
shimCssText(cssText: string, selector: string, hostSelector?: string): string;
}
|
gpl-2.0
|
Taichi-SHINDO/jdk9-jdk
|
src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java
|
44025
|
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.provider.certpath.ldap;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.util.*;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NameNotFoundException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.*;
import javax.security.auth.x500.X500Principal;
import sun.misc.HexDumpEncoder;
import sun.security.provider.certpath.X509CertificatePair;
import sun.security.util.Cache;
import sun.security.util.Debug;
import sun.security.x509.X500Name;
/**
* A <code>CertStore</code> that retrieves <code>Certificates</code> and
* <code>CRL</code>s from an LDAP directory, using the PKIX LDAP V2 Schema
* (RFC 2587):
* <a href="http://www.ietf.org/rfc/rfc2587.txt">
* http://www.ietf.org/rfc/rfc2587.txt</a>.
* <p>
* Before calling the {@link #engineGetCertificates engineGetCertificates} or
* {@link #engineGetCRLs engineGetCRLs} methods, the
* {@link #LDAPCertStore(CertStoreParameters)
* LDAPCertStore(CertStoreParameters)} constructor is called to create the
* <code>CertStore</code> and establish the DNS name and port of the LDAP
* server from which <code>Certificate</code>s and <code>CRL</code>s will be
* retrieved.
* <p>
* <b>Concurrent Access</b>
* <p>
* As described in the javadoc for <code>CertStoreSpi</code>, the
* <code>engineGetCertificates</code> and <code>engineGetCRLs</code> methods
* must be thread-safe. That is, multiple threads may concurrently
* invoke these methods on a single <code>LDAPCertStore</code> object
* (or more than one) with no ill effects. This allows a
* <code>CertPathBuilder</code> to search for a CRL while simultaneously
* searching for further certificates, for instance.
* <p>
* This is achieved by adding the <code>synchronized</code> keyword to the
* <code>engineGetCertificates</code> and <code>engineGetCRLs</code> methods.
* <p>
* This classes uses caching and requests multiple attributes at once to
* minimize LDAP round trips. The cache is associated with the CertStore
* instance. It uses soft references to hold the values to minimize impact
* on footprint and currently has a maximum size of 750 attributes and a
* 30 second default lifetime.
* <p>
* We always request CA certificates, cross certificate pairs, and ARLs in
* a single LDAP request when any one of them is needed. The reason is that
* we typically need all of them anyway and requesting them in one go can
* reduce the number of requests to a third. Even if we don't need them,
* these attributes are typically small enough not to cause a noticeable
* overhead. In addition, when the prefetchCRLs flag is true, we also request
* the full CRLs. It is currently false initially but set to true once any
* request for an ARL to the server returns an null value. The reason is
* that CRLs could be rather large but are rarely used. This implementation
* should improve performance in most cases.
*
* @see java.security.cert.CertStore
*
* @since 1.4
* @author Steve Hanna
* @author Andreas Sterbenz
*/
public final class LDAPCertStore extends CertStoreSpi {
private static final Debug debug = Debug.getInstance("certpath");
private final static boolean DEBUG = false;
/**
* LDAP attribute identifiers.
*/
private static final String USER_CERT = "userCertificate;binary";
private static final String CA_CERT = "cACertificate;binary";
private static final String CROSS_CERT = "crossCertificatePair;binary";
private static final String CRL = "certificateRevocationList;binary";
private static final String ARL = "authorityRevocationList;binary";
private static final String DELTA_CRL = "deltaRevocationList;binary";
// Constants for various empty values
private final static String[] STRING0 = new String[0];
private final static byte[][] BB0 = new byte[0][];
private final static Attributes EMPTY_ATTRIBUTES = new BasicAttributes();
// cache related constants
private final static int DEFAULT_CACHE_SIZE = 750;
private final static int DEFAULT_CACHE_LIFETIME = 30;
private final static int LIFETIME;
private final static String PROP_LIFETIME =
"sun.security.certpath.ldap.cache.lifetime";
/*
* Internal system property, that when set to "true", disables the
* JNDI application resource files lookup to prevent recursion issues
* when validating signed JARs with LDAP URLs in certificates.
*/
private final static String PROP_DISABLE_APP_RESOURCE_FILES =
"sun.security.certpath.ldap.disable.app.resource.files";
static {
String s = AccessController.doPrivileged(
(PrivilegedAction<String>) () -> System.getProperty(PROP_LIFETIME));
if (s != null) {
LIFETIME = Integer.parseInt(s); // throws NumberFormatException
} else {
LIFETIME = DEFAULT_CACHE_LIFETIME;
}
}
/**
* The CertificateFactory used to decode certificates from
* their binary stored form.
*/
private CertificateFactory cf;
/**
* The JNDI directory context.
*/
private DirContext ctx;
/**
* Flag indicating whether we should prefetch CRLs.
*/
private boolean prefetchCRLs = false;
private final Cache<String, byte[][]> valueCache;
private int cacheHits = 0;
private int cacheMisses = 0;
private int requests = 0;
/**
* Creates a <code>CertStore</code> with the specified parameters.
* For this class, the parameters object must be an instance of
* <code>LDAPCertStoreParameters</code>.
*
* @param params the algorithm parameters
* @exception InvalidAlgorithmParameterException if params is not an
* instance of <code>LDAPCertStoreParameters</code>
*/
public LDAPCertStore(CertStoreParameters params)
throws InvalidAlgorithmParameterException {
super(params);
if (!(params instanceof LDAPCertStoreParameters))
throw new InvalidAlgorithmParameterException(
"parameters must be LDAPCertStoreParameters");
LDAPCertStoreParameters lparams = (LDAPCertStoreParameters) params;
// Create InitialDirContext needed to communicate with the server
createInitialDirContext(lparams.getServerName(), lparams.getPort());
// Create CertificateFactory for use later on
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new InvalidAlgorithmParameterException(
"unable to create CertificateFactory for X.509");
}
if (LIFETIME == 0) {
valueCache = Cache.newNullCache();
} else if (LIFETIME < 0) {
valueCache = Cache.newSoftMemoryCache(DEFAULT_CACHE_SIZE);
} else {
valueCache = Cache.newSoftMemoryCache(DEFAULT_CACHE_SIZE, LIFETIME);
}
}
/**
* Returns an LDAP CertStore. This method consults a cache of
* CertStores (shared per JVM) using the LDAP server/port as a key.
*/
private static final Cache<LDAPCertStoreParameters, CertStore>
certStoreCache = Cache.newSoftMemoryCache(185);
static synchronized CertStore getInstance(LDAPCertStoreParameters params)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
CertStore lcs = certStoreCache.get(params);
if (lcs == null) {
lcs = CertStore.getInstance("LDAP", params);
certStoreCache.put(params, lcs);
} else {
if (debug != null) {
debug.println("LDAPCertStore.getInstance: cache hit");
}
}
return lcs;
}
/**
* Create InitialDirContext.
*
* @param server Server DNS name hosting LDAP service
* @param port Port at which server listens for requests
* @throws InvalidAlgorithmParameterException if creation fails
*/
private void createInitialDirContext(String server, int port)
throws InvalidAlgorithmParameterException {
String url = "ldap://" + server + ":" + port;
Hashtable<String,Object> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
// If property is set to true, disable application resource file lookup.
boolean disableAppResourceFiles = AccessController.doPrivileged(
(PrivilegedAction<Boolean>) () -> Boolean.getBoolean(PROP_DISABLE_APP_RESOURCE_FILES));
if (disableAppResourceFiles) {
if (debug != null) {
debug.println("LDAPCertStore disabling app resource files");
}
env.put("com.sun.naming.disable.app.resource.files", "true");
}
try {
ctx = new InitialDirContext(env);
/*
* By default, follow referrals unless application has
* overridden property in an application resource file.
*/
Hashtable<?,?> currentEnv = ctx.getEnvironment();
if (currentEnv.get(Context.REFERRAL) == null) {
ctx.addToEnvironment(Context.REFERRAL, "follow");
}
} catch (NamingException e) {
if (debug != null) {
debug.println("LDAPCertStore.engineInit about to throw "
+ "InvalidAlgorithmParameterException");
e.printStackTrace();
}
Exception ee = new InvalidAlgorithmParameterException
("unable to create InitialDirContext using supplied parameters");
ee.initCause(e);
throw (InvalidAlgorithmParameterException)ee;
}
}
/**
* Private class encapsulating the actual LDAP operations and cache
* handling. Use:
*
* LDAPRequest request = new LDAPRequest(dn);
* request.addRequestedAttribute(CROSS_CERT);
* request.addRequestedAttribute(CA_CERT);
* byte[][] crossValues = request.getValues(CROSS_CERT);
* byte[][] caValues = request.getValues(CA_CERT);
*
* At most one LDAP request is sent for each instance created. If all
* getValues() calls can be satisfied from the cache, no request
* is sent at all. If a request is sent, all requested attributes
* are always added to the cache irrespective of whether the getValues()
* method is called.
*/
private class LDAPRequest {
private final String name;
private Map<String, byte[][]> valueMap;
private final List<String> requestedAttributes;
LDAPRequest(String name) {
this.name = name;
requestedAttributes = new ArrayList<>(5);
}
String getName() {
return name;
}
void addRequestedAttribute(String attrId) {
if (valueMap != null) {
throw new IllegalStateException("Request already sent");
}
requestedAttributes.add(attrId);
}
/**
* Gets one or more binary values from an attribute.
*
* @param name the location holding the attribute
* @param attrId the attribute identifier
* @return an array of binary values (byte arrays)
* @throws NamingException if a naming exception occurs
*/
byte[][] getValues(String attrId) throws NamingException {
if (DEBUG && ((cacheHits + cacheMisses) % 50 == 0)) {
System.out.println("Cache hits: " + cacheHits + "; misses: "
+ cacheMisses);
}
String cacheKey = name + "|" + attrId;
byte[][] values = valueCache.get(cacheKey);
if (values != null) {
cacheHits++;
return values;
}
cacheMisses++;
Map<String, byte[][]> attrs = getValueMap();
values = attrs.get(attrId);
return values;
}
/**
* Get a map containing the values for this request. The first time
* this method is called on an object, the LDAP request is sent,
* the results parsed and added to a private map and also to the
* cache of this LDAPCertStore. Subsequent calls return the private
* map immediately.
*
* The map contains an entry for each requested attribute. The
* attribute name is the key, values are byte[][]. If there are no
* values for that attribute, values are byte[0][].
*
* @return the value Map
* @throws NamingException if a naming exception occurs
*/
private Map<String, byte[][]> getValueMap() throws NamingException {
if (valueMap != null) {
return valueMap;
}
if (DEBUG) {
System.out.println("Request: " + name + ":" + requestedAttributes);
requests++;
if (requests % 5 == 0) {
System.out.println("LDAP requests: " + requests);
}
}
valueMap = new HashMap<>(8);
String[] attrIds = requestedAttributes.toArray(STRING0);
Attributes attrs;
try {
attrs = ctx.getAttributes(name, attrIds);
} catch (NameNotFoundException e) {
// name does not exist on this LDAP server
// treat same as not attributes found
attrs = EMPTY_ATTRIBUTES;
}
for (String attrId : requestedAttributes) {
Attribute attr = attrs.get(attrId);
byte[][] values = getAttributeValues(attr);
cacheAttribute(attrId, values);
valueMap.put(attrId, values);
}
return valueMap;
}
/**
* Add the values to the cache.
*/
private void cacheAttribute(String attrId, byte[][] values) {
String cacheKey = name + "|" + attrId;
valueCache.put(cacheKey, values);
}
/**
* Get the values for the given attribute. If the attribute is null
* or does not contain any values, a zero length byte array is
* returned. NOTE that it is assumed that all values are byte arrays.
*/
private byte[][] getAttributeValues(Attribute attr)
throws NamingException {
byte[][] values;
if (attr == null) {
values = BB0;
} else {
values = new byte[attr.size()][];
int i = 0;
NamingEnumeration<?> enum_ = attr.getAll();
while (enum_.hasMore()) {
Object obj = enum_.next();
if (debug != null) {
if (obj instanceof String) {
debug.println("LDAPCertStore.getAttrValues() "
+ "enum.next is a string!: " + obj);
}
}
byte[] value = (byte[])obj;
values[i++] = value;
}
}
return values;
}
}
/*
* Gets certificates from an attribute id and location in the LDAP
* directory. Returns a Collection containing only the Certificates that
* match the specified CertSelector.
*
* @param name the location holding the attribute
* @param id the attribute identifier
* @param sel a CertSelector that the Certificates must match
* @return a Collection of Certificates found
* @throws CertStoreException if an exception occurs
*/
private Collection<X509Certificate> getCertificates(LDAPRequest request,
String id, X509CertSelector sel) throws CertStoreException {
/* fetch encoded certs from storage */
byte[][] encodedCert;
try {
encodedCert = request.getValues(id);
} catch (NamingException namingEx) {
throw new CertStoreException(namingEx);
}
int n = encodedCert.length;
if (n == 0) {
return Collections.emptySet();
}
List<X509Certificate> certs = new ArrayList<>(n);
/* decode certs and check if they satisfy selector */
for (int i = 0; i < n; i++) {
ByteArrayInputStream bais = new ByteArrayInputStream(encodedCert[i]);
try {
Certificate cert = cf.generateCertificate(bais);
if (sel.match(cert)) {
certs.add((X509Certificate)cert);
}
} catch (CertificateException e) {
if (debug != null) {
debug.println("LDAPCertStore.getCertificates() encountered "
+ "exception while parsing cert, skipping the bad data: ");
HexDumpEncoder encoder = new HexDumpEncoder();
debug.println(
"[ " + encoder.encodeBuffer(encodedCert[i]) + " ]");
}
}
}
return certs;
}
/*
* Gets certificate pairs from an attribute id and location in the LDAP
* directory.
*
* @param name the location holding the attribute
* @param id the attribute identifier
* @return a Collection of X509CertificatePairs found
* @throws CertStoreException if an exception occurs
*/
private Collection<X509CertificatePair> getCertPairs(
LDAPRequest request, String id) throws CertStoreException {
/* fetch the encoded cert pairs from storage */
byte[][] encodedCertPair;
try {
encodedCertPair = request.getValues(id);
} catch (NamingException namingEx) {
throw new CertStoreException(namingEx);
}
int n = encodedCertPair.length;
if (n == 0) {
return Collections.emptySet();
}
List<X509CertificatePair> certPairs = new ArrayList<>(n);
/* decode each cert pair and add it to the Collection */
for (int i = 0; i < n; i++) {
try {
X509CertificatePair certPair =
X509CertificatePair.generateCertificatePair(encodedCertPair[i]);
certPairs.add(certPair);
} catch (CertificateException e) {
if (debug != null) {
debug.println(
"LDAPCertStore.getCertPairs() encountered exception "
+ "while parsing cert, skipping the bad data: ");
HexDumpEncoder encoder = new HexDumpEncoder();
debug.println(
"[ " + encoder.encodeBuffer(encodedCertPair[i]) + " ]");
}
}
}
return certPairs;
}
/*
* Looks at certificate pairs stored in the crossCertificatePair attribute
* at the specified location in the LDAP directory. Returns a Collection
* containing all Certificates stored in the forward component that match
* the forward CertSelector and all Certificates stored in the reverse
* component that match the reverse CertSelector.
* <p>
* If either forward or reverse is null, all certificates from the
* corresponding component will be rejected.
*
* @param name the location to look in
* @param forward the forward CertSelector (or null)
* @param reverse the reverse CertSelector (or null)
* @return a Collection of Certificates found
* @throws CertStoreException if an exception occurs
*/
private Collection<X509Certificate> getMatchingCrossCerts(
LDAPRequest request, X509CertSelector forward,
X509CertSelector reverse)
throws CertStoreException {
// Get the cert pairs
Collection<X509CertificatePair> certPairs =
getCertPairs(request, CROSS_CERT);
// Find Certificates that match and put them in a list
ArrayList<X509Certificate> matchingCerts = new ArrayList<>();
for (X509CertificatePair certPair : certPairs) {
X509Certificate cert;
if (forward != null) {
cert = certPair.getForward();
if ((cert != null) && forward.match(cert)) {
matchingCerts.add(cert);
}
}
if (reverse != null) {
cert = certPair.getReverse();
if ((cert != null) && reverse.match(cert)) {
matchingCerts.add(cert);
}
}
}
return matchingCerts;
}
/**
* Returns a <code>Collection</code> of <code>Certificate</code>s that
* match the specified selector. If no <code>Certificate</code>s
* match the selector, an empty <code>Collection</code> will be returned.
* <p>
* It is not practical to search every entry in the LDAP database for
* matching <code>Certificate</code>s. Instead, the <code>CertSelector</code>
* is examined in order to determine where matching <code>Certificate</code>s
* are likely to be found (according to the PKIX LDAPv2 schema, RFC 2587).
* If the subject is specified, its directory entry is searched. If the
* issuer is specified, its directory entry is searched. If neither the
* subject nor the issuer are specified (or the selector is not an
* <code>X509CertSelector</code>), a <code>CertStoreException</code> is
* thrown.
*
* @param selector a <code>CertSelector</code> used to select which
* <code>Certificate</code>s should be returned.
* @return a <code>Collection</code> of <code>Certificate</code>s that
* match the specified selector
* @throws CertStoreException if an exception occurs
*/
public synchronized Collection<X509Certificate> engineGetCertificates
(CertSelector selector) throws CertStoreException {
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() selector: "
+ String.valueOf(selector));
}
if (selector == null) {
selector = new X509CertSelector();
}
if (!(selector instanceof X509CertSelector)) {
throw new CertStoreException("LDAPCertStore needs an X509CertSelector " +
"to find certs");
}
X509CertSelector xsel = (X509CertSelector) selector;
int basicConstraints = xsel.getBasicConstraints();
String subject = xsel.getSubjectAsString();
String issuer = xsel.getIssuerAsString();
HashSet<X509Certificate> certs = new HashSet<>();
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() basicConstraints: "
+ basicConstraints);
}
// basicConstraints:
// -2: only EE certs accepted
// -1: no check is done
// 0: any CA certificate accepted
// >1: certificate's basicConstraints extension pathlen must match
if (subject != null) {
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() "
+ "subject is not null");
}
LDAPRequest request = new LDAPRequest(subject);
if (basicConstraints > -2) {
request.addRequestedAttribute(CROSS_CERT);
request.addRequestedAttribute(CA_CERT);
request.addRequestedAttribute(ARL);
if (prefetchCRLs) {
request.addRequestedAttribute(CRL);
}
}
if (basicConstraints < 0) {
request.addRequestedAttribute(USER_CERT);
}
if (basicConstraints > -2) {
certs.addAll(getMatchingCrossCerts(request, xsel, null));
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() after "
+ "getMatchingCrossCerts(subject,xsel,null),certs.size(): "
+ certs.size());
}
certs.addAll(getCertificates(request, CA_CERT, xsel));
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() after "
+ "getCertificates(subject,CA_CERT,xsel),certs.size(): "
+ certs.size());
}
}
if (basicConstraints < 0) {
certs.addAll(getCertificates(request, USER_CERT, xsel));
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() after "
+ "getCertificates(subject,USER_CERT, xsel),certs.size(): "
+ certs.size());
}
}
} else {
if (debug != null) {
debug.println
("LDAPCertStore.engineGetCertificates() subject is null");
}
if (basicConstraints == -2) {
throw new CertStoreException("need subject to find EE certs");
}
if (issuer == null) {
throw new CertStoreException("need subject or issuer to find certs");
}
}
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() about to "
+ "getMatchingCrossCerts...");
}
if ((issuer != null) && (basicConstraints > -2)) {
LDAPRequest request = new LDAPRequest(issuer);
request.addRequestedAttribute(CROSS_CERT);
request.addRequestedAttribute(CA_CERT);
request.addRequestedAttribute(ARL);
if (prefetchCRLs) {
request.addRequestedAttribute(CRL);
}
certs.addAll(getMatchingCrossCerts(request, null, xsel));
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() after "
+ "getMatchingCrossCerts(issuer,null,xsel),certs.size(): "
+ certs.size());
}
certs.addAll(getCertificates(request, CA_CERT, xsel));
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() after "
+ "getCertificates(issuer,CA_CERT,xsel),certs.size(): "
+ certs.size());
}
}
if (debug != null) {
debug.println("LDAPCertStore.engineGetCertificates() returning certs");
}
return certs;
}
/*
* Gets CRLs from an attribute id and location in the LDAP directory.
* Returns a Collection containing only the CRLs that match the
* specified CRLSelector.
*
* @param name the location holding the attribute
* @param id the attribute identifier
* @param sel a CRLSelector that the CRLs must match
* @return a Collection of CRLs found
* @throws CertStoreException if an exception occurs
*/
private Collection<X509CRL> getCRLs(LDAPRequest request, String id,
X509CRLSelector sel) throws CertStoreException {
/* fetch the encoded crls from storage */
byte[][] encodedCRL;
try {
encodedCRL = request.getValues(id);
} catch (NamingException namingEx) {
throw new CertStoreException(namingEx);
}
int n = encodedCRL.length;
if (n == 0) {
return Collections.emptySet();
}
List<X509CRL> crls = new ArrayList<>(n);
/* decode each crl and check if it matches selector */
for (int i = 0; i < n; i++) {
try {
CRL crl = cf.generateCRL(new ByteArrayInputStream(encodedCRL[i]));
if (sel.match(crl)) {
crls.add((X509CRL)crl);
}
} catch (CRLException e) {
if (debug != null) {
debug.println("LDAPCertStore.getCRLs() encountered exception"
+ " while parsing CRL, skipping the bad data: ");
HexDumpEncoder encoder = new HexDumpEncoder();
debug.println("[ " + encoder.encodeBuffer(encodedCRL[i]) + " ]");
}
}
}
return crls;
}
/**
* Returns a <code>Collection</code> of <code>CRL</code>s that
* match the specified selector. If no <code>CRL</code>s
* match the selector, an empty <code>Collection</code> will be returned.
* <p>
* It is not practical to search every entry in the LDAP database for
* matching <code>CRL</code>s. Instead, the <code>CRLSelector</code>
* is examined in order to determine where matching <code>CRL</code>s
* are likely to be found (according to the PKIX LDAPv2 schema, RFC 2587).
* If issuerNames or certChecking are specified, the issuer's directory
* entry is searched. If neither issuerNames or certChecking are specified
* (or the selector is not an <code>X509CRLSelector</code>), a
* <code>CertStoreException</code> is thrown.
*
* @param selector A <code>CRLSelector</code> used to select which
* <code>CRL</code>s should be returned. Specify <code>null</code>
* to return all <code>CRL</code>s.
* @return A <code>Collection</code> of <code>CRL</code>s that
* match the specified selector
* @throws CertStoreException if an exception occurs
*/
public synchronized Collection<X509CRL> engineGetCRLs(CRLSelector selector)
throws CertStoreException {
if (debug != null) {
debug.println("LDAPCertStore.engineGetCRLs() selector: "
+ selector);
}
// Set up selector and collection to hold CRLs
if (selector == null) {
selector = new X509CRLSelector();
}
if (!(selector instanceof X509CRLSelector)) {
throw new CertStoreException("need X509CRLSelector to find CRLs");
}
X509CRLSelector xsel = (X509CRLSelector) selector;
HashSet<X509CRL> crls = new HashSet<>();
// Look in directory entry for issuer of cert we're checking.
Collection<Object> issuerNames;
X509Certificate certChecking = xsel.getCertificateChecking();
if (certChecking != null) {
issuerNames = new HashSet<>();
X500Principal issuer = certChecking.getIssuerX500Principal();
issuerNames.add(issuer.getName(X500Principal.RFC2253));
} else {
// But if we don't know which cert we're checking, try the directory
// entries of all acceptable CRL issuers
issuerNames = xsel.getIssuerNames();
if (issuerNames == null) {
throw new CertStoreException("need issuerNames or certChecking to "
+ "find CRLs");
}
}
for (Object nameObject : issuerNames) {
String issuerName;
if (nameObject instanceof byte[]) {
try {
X500Principal issuer = new X500Principal((byte[])nameObject);
issuerName = issuer.getName(X500Principal.RFC2253);
} catch (IllegalArgumentException e) {
continue;
}
} else {
issuerName = (String)nameObject;
}
// If all we want is CA certs, try to get the (probably shorter) ARL
Collection<X509CRL> entryCRLs = Collections.emptySet();
if (certChecking == null || certChecking.getBasicConstraints() != -1) {
LDAPRequest request = new LDAPRequest(issuerName);
request.addRequestedAttribute(CROSS_CERT);
request.addRequestedAttribute(CA_CERT);
request.addRequestedAttribute(ARL);
if (prefetchCRLs) {
request.addRequestedAttribute(CRL);
}
try {
entryCRLs = getCRLs(request, ARL, xsel);
if (entryCRLs.isEmpty()) {
// no ARLs found. We assume that means that there are
// no ARLs on this server at all and prefetch the CRLs.
prefetchCRLs = true;
} else {
crls.addAll(entryCRLs);
}
} catch (CertStoreException e) {
if (debug != null) {
debug.println("LDAPCertStore.engineGetCRLs non-fatal error "
+ "retrieving ARLs:" + e);
e.printStackTrace();
}
}
}
// Otherwise, get the CRL
// if certChecking is null, we don't know if we should look in ARL or CRL
// attribute, so check both for matching CRLs.
if (entryCRLs.isEmpty() || certChecking == null) {
LDAPRequest request = new LDAPRequest(issuerName);
request.addRequestedAttribute(CRL);
entryCRLs = getCRLs(request, CRL, xsel);
crls.addAll(entryCRLs);
}
}
return crls;
}
// converts an LDAP URI into LDAPCertStoreParameters
static LDAPCertStoreParameters getParameters(URI uri) {
String host = uri.getHost();
if (host == null) {
return new SunLDAPCertStoreParameters();
} else {
int port = uri.getPort();
return (port == -1
? new SunLDAPCertStoreParameters(host)
: new SunLDAPCertStoreParameters(host, port));
}
}
/*
* Subclass of LDAPCertStoreParameters with overridden equals/hashCode
* methods. This is necessary because the parameters are used as
* keys in the LDAPCertStore cache.
*/
private static class SunLDAPCertStoreParameters
extends LDAPCertStoreParameters {
private volatile int hashCode = 0;
SunLDAPCertStoreParameters(String serverName, int port) {
super(serverName, port);
}
SunLDAPCertStoreParameters(String serverName) {
super(serverName);
}
SunLDAPCertStoreParameters() {
super();
}
public boolean equals(Object obj) {
if (!(obj instanceof LDAPCertStoreParameters)) {
return false;
}
LDAPCertStoreParameters params = (LDAPCertStoreParameters) obj;
return (getPort() == params.getPort() &&
getServerName().equalsIgnoreCase(params.getServerName()));
}
public int hashCode() {
if (hashCode == 0) {
int result = 17;
result = 37*result + getPort();
result = 37*result +
getServerName().toLowerCase(Locale.ENGLISH).hashCode();
hashCode = result;
}
return hashCode;
}
}
/*
* This inner class wraps an existing X509CertSelector and adds
* additional criteria to match on when the certificate's subject is
* different than the LDAP Distinguished Name entry. The LDAPCertStore
* implementation uses the subject DN as the directory entry for
* looking up certificates. This can be problematic if the certificates
* that you want to fetch have a different subject DN than the entry
* where they are stored. You could set the selector's subject to the
* LDAP DN entry, but then the resulting match would fail to find the
* desired certificates because the subject DNs would not match. This
* class avoids that problem by introducing a certSubject which should
* be set to the certificate's subject DN when it is different than
* the LDAP DN.
*/
static class LDAPCertSelector extends X509CertSelector {
private X500Principal certSubject;
private X509CertSelector selector;
private X500Principal subject;
/**
* Creates an LDAPCertSelector.
*
* @param selector the X509CertSelector to wrap
* @param certSubject the subject DN of the certificate that you want
* to retrieve via LDAP
* @param ldapDN the LDAP DN where the certificate is stored
*/
LDAPCertSelector(X509CertSelector selector, X500Principal certSubject,
String ldapDN) throws IOException {
this.selector = selector == null ? new X509CertSelector() : selector;
this.certSubject = certSubject;
this.subject = new X500Name(ldapDN).asX500Principal();
}
// we only override the get (accessor methods) since the set methods
// will not be invoked by the code that uses this LDAPCertSelector.
public X509Certificate getCertificate() {
return selector.getCertificate();
}
public BigInteger getSerialNumber() {
return selector.getSerialNumber();
}
public X500Principal getIssuer() {
return selector.getIssuer();
}
public String getIssuerAsString() {
return selector.getIssuerAsString();
}
public byte[] getIssuerAsBytes() throws IOException {
return selector.getIssuerAsBytes();
}
public X500Principal getSubject() {
// return the ldap DN
return subject;
}
public String getSubjectAsString() {
// return the ldap DN
return subject.getName();
}
public byte[] getSubjectAsBytes() throws IOException {
// return the encoded ldap DN
return subject.getEncoded();
}
public byte[] getSubjectKeyIdentifier() {
return selector.getSubjectKeyIdentifier();
}
public byte[] getAuthorityKeyIdentifier() {
return selector.getAuthorityKeyIdentifier();
}
public Date getCertificateValid() {
return selector.getCertificateValid();
}
public Date getPrivateKeyValid() {
return selector.getPrivateKeyValid();
}
public String getSubjectPublicKeyAlgID() {
return selector.getSubjectPublicKeyAlgID();
}
public PublicKey getSubjectPublicKey() {
return selector.getSubjectPublicKey();
}
public boolean[] getKeyUsage() {
return selector.getKeyUsage();
}
public Set<String> getExtendedKeyUsage() {
return selector.getExtendedKeyUsage();
}
public boolean getMatchAllSubjectAltNames() {
return selector.getMatchAllSubjectAltNames();
}
public Collection<List<?>> getSubjectAlternativeNames() {
return selector.getSubjectAlternativeNames();
}
public byte[] getNameConstraints() {
return selector.getNameConstraints();
}
public int getBasicConstraints() {
return selector.getBasicConstraints();
}
public Set<String> getPolicy() {
return selector.getPolicy();
}
public Collection<List<?>> getPathToNames() {
return selector.getPathToNames();
}
public boolean match(Certificate cert) {
// temporarily set the subject criterion to the certSubject
// so that match will not reject the desired certificates
selector.setSubject(certSubject);
boolean match = selector.match(cert);
selector.setSubject(subject);
return match;
}
}
/**
* This class has the same purpose as LDAPCertSelector except it is for
* X.509 CRLs.
*/
static class LDAPCRLSelector extends X509CRLSelector {
private X509CRLSelector selector;
private Collection<X500Principal> certIssuers;
private Collection<X500Principal> issuers;
private HashSet<Object> issuerNames;
/**
* Creates an LDAPCRLSelector.
*
* @param selector the X509CRLSelector to wrap
* @param certIssuers the issuer DNs of the CRLs that you want
* to retrieve via LDAP
* @param ldapDN the LDAP DN where the CRL is stored
*/
LDAPCRLSelector(X509CRLSelector selector,
Collection<X500Principal> certIssuers, String ldapDN)
throws IOException {
this.selector = selector == null ? new X509CRLSelector() : selector;
this.certIssuers = certIssuers;
issuerNames = new HashSet<>();
issuerNames.add(ldapDN);
issuers = new HashSet<>();
issuers.add(new X500Name(ldapDN).asX500Principal());
}
// we only override the get (accessor methods) since the set methods
// will not be invoked by the code that uses this LDAPCRLSelector.
public Collection<X500Principal> getIssuers() {
// return the ldap DN
return Collections.unmodifiableCollection(issuers);
}
public Collection<Object> getIssuerNames() {
// return the ldap DN
return Collections.unmodifiableCollection(issuerNames);
}
public BigInteger getMinCRL() {
return selector.getMinCRL();
}
public BigInteger getMaxCRL() {
return selector.getMaxCRL();
}
public Date getDateAndTime() {
return selector.getDateAndTime();
}
public X509Certificate getCertificateChecking() {
return selector.getCertificateChecking();
}
public boolean match(CRL crl) {
// temporarily set the issuer criterion to the certIssuers
// so that match will not reject the desired CRL
selector.setIssuers(certIssuers);
boolean match = selector.match(crl);
selector.setIssuers(issuers);
return match;
}
}
}
|
gpl-2.0
|
JT5D/Alfred-Popclip-Sublime
|
Sublime Text 2/Git/status.py
|
2111
|
import os
import re
import sublime
from git import GitWindowCommand, git_root
class GitStatusCommand(GitWindowCommand):
force_open = False
def run(self):
self.run_command(['git', 'status', '--porcelain'], self.status_done)
def status_done(self, result):
self.results = filter(self.status_filter, result.rstrip().split('\n'))
if len(self.results):
self.show_status_list()
else:
sublime.status_message("Nothing to show")
def show_status_list(self):
self.quick_panel(self.results, self.panel_done,
sublime.MONOSPACE_FONT)
def status_filter(self, item):
# for this class we don't actually care
if not re.match(r'^[ MADRCU?!]{1,2}\s+.*', item):
return False
return len(item) > 0
def panel_done(self, picked):
if 0 > picked < len(self.results):
return
picked_file = self.results[picked]
# first 2 characters are status codes, the third is a space
picked_status = picked_file[:2]
picked_file = picked_file[3:]
self.panel_followup(picked_status, picked_file, picked)
def panel_followup(self, picked_status, picked_file, picked_index):
# split out solely so I can override it for laughs
s = sublime.load_settings("Git.sublime-settings")
root = git_root(self.get_working_dir())
if picked_status == '??' or s.get('status_opens_file') or self.force_open:
if(os.path.isfile(os.path.join(root, picked_file))):
self.window.open_file(os.path.join(root, picked_file))
else:
self.run_command(['git', 'diff', '--no-color', '--', picked_file.strip('"')],
self.diff_done, working_dir=root)
def diff_done(self, result):
if not result.strip():
return
self.scratch(result, title="Git Diff")
class GitOpenModifiedFilesCommand(GitStatusCommand):
force_open = True
def show_status_list(self):
for line_index in range(0, len(self.results)):
self.panel_done(line_index)
|
gpl-2.0
|
ctrueden/bioformats
|
components/formats-gpl/test/loci/formats/utests/MDBServiceTest.java
|
3323
|
/*
* #%L
* OME Bio-Formats package for reading and converting biological file formats.
* %%
* Copyright (C) 2005 - 2013 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.formats.utests;
import static org.testng.AssertJUnit.assertEquals;
import java.io.IOException;
import java.net.URL;
import java.util.Vector;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.services.MDBService;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/test/loci/formats/utests/MDBServiceTest.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/test/loci/formats/utests/MDBServiceTest.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Chris Allan <callan at blackcat dot ca>
*/
public class MDBServiceTest {
private static final String[] COLUMNS = new String[] {
"ID", "text column", "number column", "date column", "currency column",
"boolean column", "OLE column", "memo column"
};
private static final String[][] ROWS = new String[][] {
{"1", "row 1, column 1", "1", "3/14/1999 0:0:0", "6.6600", "1", null, "foo"},
{"2", "row 2, column 1", "2", "8/1/2008 0:0:0", "0.3700", "0", null, "bar"},
{"3", "row 3, column 1", "3", "9/21/2001 0:0:0", "1000000.0000", "1", null, "baz"},
};
private static final String TEST_FILE = "test.mdb";
private MDBService service;
@BeforeMethod
public void setUp() throws DependencyException, IOException {
ServiceFactory sf = new ServiceFactory();
service = sf.getInstance(MDBService.class);
URL file = this.getClass().getResource(TEST_FILE);
service.initialize(file.getPath());
}
@Test
public void testData() throws IOException {
Vector<Vector<String[]>> data = service.parseDatabase();
assertEquals(1, data.size());
Vector<String[]> table = data.get(0);
assertEquals(4, table.size());
String[] columnNames = table.get(0);
assertEquals(COLUMNS.length + 1, columnNames.length);
assertEquals("test table", columnNames[0]);
for (int i=1; i<columnNames.length; i++) {
assertEquals(columnNames[i], COLUMNS[i - 1]);
}
for (int i=1; i<table.size(); i++) {
String[] row = table.get(i);
for (int col=0; col<row.length; col++) {
assertEquals(ROWS[i - 1][col], row[col]);
}
}
}
}
|
gpl-2.0
|
BenMacLean/beyondBiceps
|
wp-content/plugins/easy-google-fonts/views/customizer/control/positioning/margin/left.php
|
1079
|
<?php
/**
* Left Margin Control
*
* Outputs a jquery ui slider to allow the
* user to control the left margin of an
* element.
*
* @package Easy_Google_Fonts
* @author Sunny Johal - Titanium Themes <support@titaniumthemes.com>
* @license GPL-2.0+
* @link http://wordpress.org/plugins/easy-google-fonts/
* @copyright Copyright (c) 2016, Titanium Themes
* @version 1.4.1
*
*/
?>
<#
// Get settings and defaults.
var egfMarginLeft = typeof egfSettings.margin_left !== "undefined" ? egfSettings.margin_left : data.egf_defaults.margin_left;
#>
<div class="egf-font-slider-control egf-margin-left-slider">
<span class="egf-slider-title"><?php _e( 'Left', 'easy-google-fonts' ); ?></span>
<div class="egf-font-slider-display">
<span>{{ egfMarginLeft.amount }}{{ egfMarginLeft.unit }}</span> | <a class="egf-font-slider-reset" href="#"><?php _e( 'Reset', 'easy-google-fonts' ); ?></a>
</div>
<div class="egf-clear" ></div>
<!-- Slider -->
<div class="egf-slider" value="{{ egfMarginLeft.amount }}"></div>
<div class="egf-clear"></div>
</div>
|
gpl-2.0
|
janicak/C-Db
|
sites/all/modules/openid_selector/openid_selector_fbconnect.js
|
1106
|
(function ($) {
openid.fbconnect_replace_i = -1;
var replace_id = null;
for (var provider_id in providers_large) {
openid.fbconnect_replace_i++;
replace_id = provider_id;
}
var replace_providers = {};
replace_providers[replace_id] = providers_large[replace_id];
providers_small = $.extend(replace_providers, providers_small);
delete providers_large[replace_id];
providers_large.facebook = {
name: 'Facebook',
url: "javascript: FB.login(function (response) { facebook_onlogin_ready(); });"
};
openid.getBoxHTML__fbconnect = openid.getBoxHTML;
openid.getBoxHTML = function (box_id, provider, box_size, index) {
if (box_id == 'facebook') {
var no_sprite = this.no_sprite;
this.no_sprite = true;
var result = this.getBoxHTML__fbconnect(box_id, provider, box_size, index);
this.no_sprite = no_sprite;
return result;
} else
if (index >= this.fbconnect_replace_i) {
index--;
}
return this.getBoxHTML__fbconnect(box_id, provider, box_size, index);
}
Drupal.behaviors.openid_selector_fbconnect = { attach: function (context) {
$('#fbconnect_button').hide();
}}
})(jQuery);
|
gpl-2.0
|
kosmosby/medicine-prof
|
components/com_comprofiler/plugin/user/plug_cbgroupjive/templates/default/overview_message.php
|
3343
|
<?php
if ( ! ( defined( '_VALID_CB' ) || defined( '_JEXEC' ) || defined( '_VALID_MOS' ) ) ) { die( 'Direct Access to this location is not allowed.' ); }
class HTML_groupjiveOverviewMessage {
/**
* render frontend overview message
*
* @param array $input
* @param moscomprofilerUser $user
* @param object $plugin
*/
static function showOverviewMessage( $input, $user, $plugin ) {
global $_CB_framework;
$generalTitle = $plugin->params->get( 'general_title', $plugin->name );
$pageTitle = CBTxt::P( 'Message [category]', array( '[category]' => cbgjClass::getOverride( 'category', true ) ) );
$_CB_framework->setPageTitle( htmlspecialchars( $pageTitle ) );
if ( $generalTitle != '' ) {
$_CB_framework->appendPathWay( htmlspecialchars( CBTxt::T( $generalTitle ) ), cbgjClass::getPluginURL() );
}
$_CB_framework->appendPathWay( htmlspecialchars( cbgjClass::getOverride( 'category', true ) . ' ' . cbgjClass::getOverride( 'overview' ) ), cbgjClass::getPluginURL( array( 'overview' ) ) );
$_CB_framework->appendPathWay( htmlspecialchars( $pageTitle ), cbgjClass::getPluginURL( array( 'overview', 'message' ) ) );
$return = '<div class="gjOverviewMessage">'
. '<form action="' . cbgjClass::getPluginURL( array( 'overview', 'send' ) ) . '" method="post" enctype="multipart/form-data" name="gjForm" id="gjForm" class="gjForm form-horizontal">'
. '<legend class="gjEditTitle">' . $pageTitle . '</legend>'
. '<div class="gjEditContentInput control-group">'
. '<label class="gjEditContentInputTitle control-label">' . CBTxt::Th( 'Subject' ) . '</label>'
. '<div class="gjEditContentInputField controls">'
. $input['subject']
. '<span class="gjEditContentInputIcon help-inline">'
. cbgjClass::getIcon( null, CBTxt::T( 'Required' ), 'icon-star' )
. cbgjClass::getIcon( CBTxt::P( 'Input [categories] message subject.', array( '[categories]' => cbgjClass::getOverride( 'category', true ) ) ) )
. '</span>'
. '</div>'
. '</div>'
. '<div class="gjEditContentInput control-group">'
. '<label class="gjEditContentInputTitle control-label">' . CBTxt::Th( 'Body' ) . '</label>'
. '<div class="gjEditContentInputField controls">'
. $input['body']
. '<span class="gjEditContentInputIcon help-inline">'
. cbgjClass::getIcon( null, CBTxt::T( 'Required' ), 'icon-star' )
. cbgjClass::getIcon( CBTxt::P( 'Input [categories] message body.', array( '[categories]' => cbgjClass::getOverride( 'category', true ) ) ) )
. '</span>'
. '</div>'
. '</div>'
. '<div class="gjButtonWrapper form-actions">'
. '<input type="submit" value="' . htmlspecialchars( CBTxt::T( 'Send Message' ) ) . '" class="gjButton gjButtonSubmit btn btn-primary" /> '
. '<input type="button" value="' . htmlspecialchars( CBTxt::T( 'Cancel' ) ) . '" class="gjButton gjButtonCancel btn btn-mini" onclick="' . cbgjClass::getPluginURL( array( 'overview' ), CBTxt::T( 'Are you sure you want to cancel? All unsaved data will be lost!' ) ) . '" />'
. '</div>'
. cbGetSpoofInputTag( 'plugin' )
. '</form>'
. '</div>';
echo $return;
}
}
?>
|
gpl-2.0
|
AndriyTsok/atsok.net
|
vendor/bundle/ruby/2.4.0/gems/nuggets-1.0.0/lib/nuggets/env/user_home.rb
|
79
|
require 'nuggets/env/user_home_mixin'
ENV.extend(Nuggets::Env::UserHomeMixin)
|
gpl-2.0
|
svn2github/voreen
|
modules/plotting/utils/parser/plotfunctiontoken.cpp
|
3254
|
/**********************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Created between 2005 and 2012 by The Voreen Team *
* as listed in CREDITS.TXT <http://www.voreen.org> *
* *
* 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 program. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
* The authors reserve all rights not expressly granted herein. 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 "plotfunctiontoken.h"
namespace voreen {
namespace glslparser {
//---------- FunctionToken ---------------------------------------------------
FunctionToken::FunctionToken(const int tokenID, const std::string& value, const int index)
: IdentifierToken(tokenID,value)
, index_(index)
{}
Token* FunctionToken::getCopy() const {
return new FunctionToken(getTokenID(),getValue(),index_);
}
int FunctionToken::getIndex() {
return index_;
}
//---------- VariablesToken ---------------------------------------------------
VariablesToken::VariablesToken(const int tokenID, const std::string& value)
: IdentifierToken(tokenID,value)
{}
Token* VariablesToken::getCopy() const {
return new VariablesToken(getTokenID(),getValue());
}
//---------- OperatorToken ---------------------------------------------------
OperatorToken::OperatorToken(const int tokenID, const char value, const int parameter)
: GenericToken<char>(tokenID,value)
, parameter_(parameter)
{}
Token* OperatorToken::getCopy() const {
return new OperatorToken(getTokenID(),getValue(),parameter_);
}
void OperatorToken::setParameter(int parameter) {
parameter_ = parameter;
}
int OperatorToken::getParameter() {
return parameter_;
}
} // namespace glslparser
} // namespace voreen
|
gpl-2.0
|
kylecunningham/agk3
|
examples/AGK/misc/number_to_words.py
|
899
|
def number_to_words(number):
number=int(number)
ones=["one","two","three","four","five","six","seven","eight","nine"]
teens=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
tens=["twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"]
if number<10:
return ones[number-1]
elif number<20:
return teens[number-10]
elif number<100:
return tens[number//10-2]+(" "+number_to_words(number%10) if number%10!=0 else "")
elif number<1000:
return number_to_words(number//100)+" hundred"+(" "+number_to_words(number%100) if number%100!=0 else "")
elif number<1000000:
return number_to_words(number//1000)+" thousand"+(" "+number_to_words(number%1000) if number%1000!=0 else "")
elif number<1000000000:
return number_to_words(number//1000000)+" million"+(" "+number_to_words(number%1000000) if number%1000000!=0 else "")
|
gpl-2.0
|
tav/confluence
|
languages/messages/MessagesCrh_cyrl.php
|
179277
|
<?php
/** Crimean Turkish (Cyrillic) (Qırımtatarca (Cyrillic))
*
* See MessagesQqq.php for message documentation incl. usage of parameters
* To improve a translation please visit http://translatewiki.net
*
* @ingroup Language
* @file
*
* @author AlefZet
* @author Alessandro
* @author Don Alessandro
* @author Urhixidur
*/
$fallback = 'ru';
$fallback8bitEncoding = 'windows-1251';
$separatorTransformTable = array(',' => '.', '.' => ',' );
$linkTrail = '/^([a-zâçğıñöşüа-яё“»]+)(.*)$/sDu';
$namespaceNames = array(
NS_MEDIA => 'Медиа',
NS_SPECIAL => 'Махсус',
NS_MAIN => '',
NS_TALK => 'Музакере',
NS_USER => 'Къулланыджы',
NS_USER_TALK => 'Къулланыджы_музакереси',
# NS_PROJECT set by $wgMetaNamespace
NS_PROJECT_TALK => '$1_музакереси',
NS_FILE => 'Ресим',
NS_FILE_TALK => 'Ресим_музакереси',
NS_MEDIAWIKI => 'МедиаВики',
NS_MEDIAWIKI_TALK => 'МедиаВики_музакереси',
NS_TEMPLATE => 'Шаблон',
NS_TEMPLATE_TALK => 'Шаблон_музакереси',
NS_HELP => 'Ярдым',
NS_HELP_TALK => 'Ярдым_музакереси',
NS_CATEGORY => 'Категория',
NS_CATEGORY_TALK => 'Категория_музакереси',
);
# Aliases to latin namespaces
$namespaceAliases = array(
"Media" => NS_MEDIA,
"Mahsus" => NS_SPECIAL,
"Muzakere" => NS_TALK,
"Qullanıcı" => NS_USER,
"Qullanıcı_muzakeresi" => NS_USER_TALK,
"$1_muzakeresi" => NS_PROJECT_TALK,
"Resim" => NS_FILE,
"Resim_muzakeresi" => NS_FILE_TALK,
"MediaViki" => NS_MEDIAWIKI,
"MediaViki_muzakeresi" => NS_MEDIAWIKI_TALK,
'Şablon' => NS_TEMPLATE,
'Şablon_muzakeresi' => NS_TEMPLATE_TALK,
'Yardım' => NS_HELP,
'Yardım_muzakeresi' => NS_HELP_TALK,
'Kategoriya' => NS_CATEGORY,
'Kategoriya_muzakeresi' => NS_CATEGORY_TALK,
);
$datePreferences = array(
'default',
'mdy',
'dmy',
'ymd',
'yyyy-mm-dd',
'ISO 8601',
);
$defaultDateFormat = 'ymd';
$datePreferenceMigrationMap = array(
'default',
'mdy',
'dmy',
'ymd'
);
$dateFormats = array(
'mdy time' => 'H:i',
'mdy date' => 'F j Y "с."',
'mdy both' => 'H:i, F 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 "с." xg j',
'ymd both' => 'H:i, Y "с." xg j',
'yyyy-mm-dd time' => 'xnH:xni:xns',
'yyyy-mm-dd date' => 'xnY-xnm-xnd',
'yyyy-mm-dd both' => 'xnH:xni:xns, xnY-xnm-xnd',
'ISO 8601 time' => 'xnH:xni:xns',
'ISO 8601 date' => 'xnY.xnm.xnd',
'ISO 8601 both' => 'xnY.xnm.xnd"T"xnH:xni:xns',
);
$messages = array(
# User preference toggles
'tog-underline' => 'Багълантыларнынъ тюбюни сызув:',
'tog-highlightbroken' => 'Бош багълантыларны <a href="" class="new">бу шекильде</a> (альтернатив: <a href="" class="internal">бу шекильде</a>) косьтер.',
'tog-justify' => 'Параграф эки якъкъа яслап тиз',
'tog-hideminor' => 'Кичик денъишикликлерни "Сонъки денъишикликлер" саифесинде гизле',
'tog-hidepatrolled' => 'Сонъки денъишикликлер косьтергенде тешкерильген денъишикликлерни гизле',
'tog-newpageshidepatrolled' => 'Янъы саифелер косьтергенде тешкерильген саифелерни гизле',
'tog-extendwatchlist' => 'Козетюв джедвелини, тек сонъки дегиль, бутюн денъишикликлерни корьмек ичюн кенишлет',
'tog-usenewrc' => 'Тафсилятлы сонъки денъишикликлер джедвелини къуллан (JavaScript керек)',
'tog-numberheadings' => 'Серлеваларны автоматик номераландыр',
'tog-showtoolbar' => 'Денъишиклик япкъан вакъытта ярдымджы дёгмелерни косьтер. (JavaScript)',
'tog-editondblclick' => 'Саифени чифт басып денъиштирмеге башла (JavaScript)',
'tog-editsection' => 'Болюклерни [денъиштир] багълантыларны иле денъиштирме акъкъы бер',
'tog-editsectiononrightclick' => 'Болюк серлевасына онъ басып болюкте денъишикликке рухсет бер. (JavaScript)',
'tog-showtoc' => 'Мундеридже джедвели косьтер (3 данеден зияде серлевасы олгъан саифелер ичюн)',
'tog-rememberpassword' => 'Парольни хатырла',
'tog-editwidth' => 'Язув пенджересини бутюн экранны толдураджакъ шекильде кенишлет',
'tog-watchcreations' => 'Мен яраткъан саифелерни козетюв джедвелиме кирсет',
'tog-watchdefault' => 'Мен денъиштирген саифелерни козетюв джедвелиме кирсет',
'tog-watchmoves' => 'Меним тарафымдан ады денъиштирильген саифелерни козетюв джедвелиме кирсет',
'tog-watchdeletion' => 'Мен ёкъ эткен саифелерни козетюв джедвелиме кирсет',
'tog-minordefault' => 'Япкъан денъишикликлеримни кичик денъишиклик оларакъ ишаретле',
'tog-previewontop' => 'Бакъып чыкъувны язув пенджеренинъ устюнде косьтер',
'tog-previewonfirst' => 'Денъиштирмеде бакъып чыкъувны косьтер',
'tog-nocache' => 'Саифелерни хатырлама',
'tog-enotifwatchlistpages' => 'Саифе денъишикликлеринде манъа e-mail ёлла',
'tog-enotifusertalkpages' => 'Къулланыджы саифемде денъишиклик олгъанда манъа e-mail ёлла',
'tog-enotifminoredits' => 'Саифелерде кичик денъишиклик олгъанда да манъа e-mail ёлла',
'tog-enotifrevealaddr' => 'Бильдирюв мектюплеринде e-mail адресимни косьтер',
'tog-shownumberswatching' => 'Козеткен къулланыджы сайысыны косьтер',
'tog-fancysig' => 'Имза викиметин киби олсун (автоматик багъланты олмаз)',
'tog-externaleditor' => 'Денъишикликлерни башкъа эдитор программасы иле яп',
'tog-externaldiff' => 'Тенъештирмелерни тыш программагъа яптыр.',
'tog-showjumplinks' => '«Бар» багълантысыны фааллештир',
'tog-uselivepreview' => 'Джанлы бакъып чыкъув хусусиетини къуллан (JavaScript) (даа денъеме алында)',
'tog-forceeditsummary' => 'Денъишиклик къыскъа тарифини бош ташлагъанда мени тенбиле',
'tog-watchlisthideown' => 'Козетюв джедвелимден меним денъишикликлеримни гизле',
'tog-watchlisthidebots' => 'Козетюв джедвелимден бот денъишикликлерини гизле',
'tog-watchlisthideminor' => 'Козетюв джедвелимден кичик денъишикликлерни гизле',
'tog-watchlisthideliu' => 'Козетюв джедвелимде къайдлы къулланыджылар тарафындан япылгъан денъишикликлерни косьтерме',
'tog-watchlisthideanons' => 'Козетюв джедвелимде къайдсыз (аноним) къулланыджылар тарафындан япылгъан денъишикликлерни косьтерме',
'tog-watchlisthidepatrolled' => 'Козетюв джедвелинде тешкерильген денъишикликлерни гизле',
'tog-nolangconversion' => 'Язув системасы вариантлары денъиштирювни ишлетме',
'tog-ccmeonemails' => 'Дигер къулланыджыларгъа ёллагъан мектюплеримнинъ копияларыны манъа да ёлла',
'tog-diffonly' => 'Тенъештирме саифелеринде саифенинъ эсас мундериджесини косьтерме',
'tog-showhiddencats' => 'Гизли категорияларны косьтер',
'tog-norollbackdiff' => 'Лягъу этильген денъишикликлерни косьтерме',
'underline-always' => 'Даима',
'underline-never' => 'Асла',
'underline-default' => 'Браузер къарар берсин',
# 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' => 'дек',
# Categories related messages
'pagecategories' => '{{PLURAL:$1|Саифенинъ категориясы|Саифенинъ категориялары}}',
'category_header' => '"$1" категориясындаки саифелер',
'subcategories' => 'Алт категориялар',
'category-media-header' => '"$1" категориясындаки медиа файллары',
'category-empty' => "''Ишбу категорияда ич бир саифе я да медиа файл ёкъ.''",
'hidden-categories' => 'Гизли {{PLURAL:$1|категория|категориялар}}',
'hidden-category-category' => 'Гизли категориялар', # Name of the category where hidden categories will be listed
'category-subcat-count' => '{{PLURAL:$2|Бу категорияда тек бир ашагъыдаки алт категория бар.|Бу категориядаки топлам $2 алт категориядан ашагъыдаки $1 алт категория косьтерильген.}}',
'category-subcat-count-limited' => 'Бу категорияда ашагъыдаки {{PLURAL:$1|1|$1}} алт категория бар.',
'category-article-count' => '{{PLURAL:$2|Бу категорияда тек бир ашагъыдаки саифе бар.|Бу категориядаки топлам $2 саифеден ашагъыдаки $1 саифе косьтерильген.}}',
'category-article-count-limited' => 'Бу категорияда ашагъыдаки {{PLURAL:$1|1|$1}} саифе бар.',
'category-file-count' => '{{PLURAL:$2|Бу категорияда тек бир ашагъыдаки файл бар.|Бу категориядаки топлам $2 файлдан ашагъыдаки $1 файл косьтерильген.}}',
'category-file-count-limited' => 'Бу категорияда ашагъыдаки {{PLURAL:$1|1|$1}} файл бар.',
'listingcontinuesabbrev' => ' (девам)',
'linkprefix' => '/^(.*?)([a-zâçğıñöşüA-ZÂÇĞİÑÖŞÜa-яёА-ЯЁ«„]+)$/sDu',
'mainpagetext' => "'''MediaWiki мувафакъиетнен къурулды.'''",
'mainpagedocfooter' => "Бу викининъ ёл-ёругъыны [http://meta.wikimedia.org/wiki/Help:Contents User's Guide къулланыджы къылавузындан] огренип оласынъыз.
== Базы файдалы сайтлар ==
* [http://www.mediawiki.org/wiki/Manual:Configuration_settings Олуджы сазламалар джедвели];
* [http://www.mediawiki.org/wiki/Manual:FAQ MediaWiki боюнджа сыкъ берильген суаллернен джеваплар];
* [https://lists.wikimedia.org/mailman/listinfo/mediawiki-announce MediaWiki-нинъ янъы версияларынынъ чыкъувындан хабер йиберюв].",
'about' => 'Акъкъында',
'article' => 'Саифе',
'newwindow' => '(янъы бир пенджереде ачылыр)',
'cancel' => 'Лягъу',
'qbfind' => 'Тап',
'qbbrowse' => 'Бакъып чыкъ',
'qbedit' => 'Денъиштир',
'qbpageoptions' => 'Бу саифе',
'qbpageinfo' => 'Багълам',
'qbmyoptions' => 'Саифелерим',
'qbspecialpages' => 'Махсус саифелер',
'moredotdotdot' => 'Даа...',
'mypage' => 'Саифем',
'mytalk' => 'Музакере саифем',
'anontalk' => 'Бу IP-нинъ музакереси',
'navigation' => 'Сайтта ёл тапув',
'and' => ' ве',
# Metadata in edit box
'metadata_help' => 'Мета малюматы:',
'errorpagetitle' => 'Хата',
'returnto' => '$1.',
'tagline' => '{{GRAMMAR:ablative|{{SITENAME}}}}',
'help' => 'Ярдым',
'search' => 'Къыдырув',
'searchbutton' => 'Къыдыр',
'go' => 'Бар',
'searcharticle' => 'Бар',
'history' => 'Саифенинъ кечмиши',
'history_short' => 'Кечмиш',
'updatedmarker' => 'сонъки зияретимден сонъ янъаргъан',
'info_short' => 'Малюмат',
'printableversion' => 'Басылмагъа уйгъун корюниш',
'permalink' => 'Сонъки алына багъланты',
'print' => 'Бастыр',
'edit' => 'Денъиштир',
'create' => 'Ярат',
'editthispage' => 'Саифени денъиштир',
'create-this-page' => 'Бу саифени ярат',
'delete' => 'Ёкъ эт',
'deletethispage' => 'Саифени ёкъ эт',
'undelete_short' => '{{PLURAL:$1|1|$1}} денъишикликни кери кетир',
'protect' => 'Къорчала',
'protect_change' => 'денъиштир',
'protectthispage' => 'Саифени къорчалав алтына ал',
'unprotect' => 'Къорчалавны чыкъар',
'unprotectthispage' => 'Саифе къорчалавыны чыкъар',
'newpage' => 'Янъы саифе',
'talkpage' => 'Саифени музакере эт',
'talkpagelinktext' => 'Музакере',
'specialpage' => 'Махсус Саифе',
'personaltools' => 'Шахсий алетлер',
'postcomment' => 'Янъы болюк',
'articlepage' => 'Саифеге бар',
'talk' => 'Музакере',
'views' => 'Корюнишлер',
'toolbox' => 'Алетлер',
'userpage' => 'Къулланыджы саифесини косьтер',
'projectpage' => 'Лейха саифесини косьтер',
'imagepage' => 'Файл саифесини косьтер',
'mediawikipage' => 'Беянат саифесини косьтер',
'templatepage' => 'Шаблон саифесини косьтер',
'viewhelppage' => 'Ярдым саифесини косьтер',
'categorypage' => 'Категория саифесини косьтер',
'viewtalkpage' => 'Музакере саифесини косьтер',
'otherlanguages' => 'Дигер тиллерде',
'redirectedfrom' => '($1 саифесинден ёлланды)',
'redirectpagesub' => 'Ёллама саифеси',
'lastmodifiedat' => 'Бу саифе сонъки оларакъ $1, $2 тарихында янъарды.', # $1 date, $2 time
'viewcount' => 'Бу саифе {{PLURAL:$1|1|$1}} дефа иришильген.',
'protectedpage' => 'Къорчалавлы саифе',
'jumpto' => 'Бунъа бар:',
'jumptonavigation' => 'къуллан',
'jumptosearch' => 'къыдыр',
# 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) and the disambiguation template definition (see disambiguations).
'aboutsite' => '{{SITENAME}} акъкъында',
'aboutpage' => 'Project:Акъкъында',
'copyright' => 'Малюмат $1 бинаэн кечилип ола.',
'copyrightpagename' => '{{SITENAME}} муэллифлик акълары',
'copyrightpage' => '{{ns:project}}:Муэллифлик акълары',
'currentevents' => 'Агъымдаки вакъиалар',
'currentevents-url' => 'Project:Агъымдаки вакъиалар',
'disclaimers' => 'Джевапкярлыкъ реди',
'disclaimerpage' => 'Project:Умумий Малюмат Мукъавелеси',
'edithelp' => 'Саифелер насыл денъиштирилир?',
'edithelppage' => 'Help:Саифе насыл денъиштирилир',
'faq' => 'Сыкъ берильген суаллер',
'faqpage' => 'Project:Сыкъ берильген суаллер',
'helppage' => 'Help:Мундеридже',
'mainpage' => 'Баш Саифе',
'mainpage-description' => 'Баш Саифе',
'policy-url' => 'Project:Къаиделер',
'portal' => 'Джемаат порталы',
'portal-url' => 'Project:Джемаат порталы',
'privacy' => 'Гизлилик эсасы',
'privacypage' => 'Project:Гизлилик эсасы',
'badaccess' => 'Изин хатасы',
'badaccess-group0' => 'Япаджакъ олгъан арекетинъизни япмагъа акъкъынъыз ёкъ.',
'badaccess-groups' => 'Япаджакъ олгъан арекетинъизни тек ашагъыдаки {{PLURAL:$2|1|$2}} группагъа аза олгъан къулланыджылары япып олалар: $1.',
'versionrequired' => 'MediaWiki-нинъ $1 версиясы керек',
'versionrequiredtext' => 'Бу саифени къулланмакъ ичюн MediaWiki-нинъ $1 версиясы керек. [[Special:Version|Версия]] саифесине бакъ.',
'ok' => 'Ок',
'retrievedfrom' => 'Менба – "$1"',
'youhavenewmessages' => 'Янъы $1 бар ($2).',
'newmessageslink' => 'беянатынъыз',
'newmessagesdifflink' => 'музакере саифенъизнинъ сонъки денъишиклиги',
'youhavenewmessagesmulti' => '$1 саифесинде янъы беянатынъыз бар.',
'editsection' => 'денъиштир',
'editold' => 'денъиштир',
'viewsourceold' => 'менбаны корь',
'editlink' => 'денъиштир',
'viewsourcelink' => 'менба кодуны косьтер',
'editsectionhint' => 'Денъиштирильген болюк: $1',
'toc' => 'Мундеридже',
'showtoc' => 'косьтер',
'hidetoc' => 'гизле',
'thisisdeleted' => '$1 корьмеге я да кери кетирмеге истейсинъизми?',
'viewdeleted' => '$1 корь?',
'restorelink' => 'ёкъ этильген {{PLURAL:$1|1|$1}} денъишиклиги',
'feedlinks' => 'Бу шекильде:',
'feed-invalid' => 'Абуне каналынынъ чешити янълыштыр.',
'feed-unavailable' => 'Синдикация ленталары къулланылып оламай.',
'site-rss-feed' => '$1 RSS лентасы',
'site-atom-feed' => '$1 Atom лентасы',
'page-rss-feed' => '«$1» - RSS лентасы',
'page-atom-feed' => '«$1» - Atom лентасы',
'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
'nosuchaction' => 'Ойле арекет ёкъ',
'nosuchactiontext' => 'URL-де бильдирильген арекет рухсетсиз.
Бельки де URL-ни янълыш язгъандырсыз, я да догъру олмагъан бир багълантыны къуллангъандырсыз.
Бу, {{SITENAME}} сайтындаки бир хатаны да косьтерип ола.',
'nosuchspecialpage' => 'Бу исимде бир махсус саифе ёкъ',
'nospecialpagetext' => '<strong>Тапылмагъан бир махсус саифеге кирдинъиз.</strong>
Бар олгъан бутюн махсус саифелерни [[Special:SpecialPages|{{int:specialpages}}]] саифесинде корип олурсынъыз.',
# General errors
'error' => 'Хата',
'databaseerror' => 'Малюмат базасынынъ хатасы',
'dberrortext' => 'Малюмат базасындан сораткъанда синтаксис хатасы олды.
Бу язылымдаки бир хата ола биле.
"<tt>$2</tt>" функциясындан олгъан малюмат базасындан сонъки соратма:
<blockquote><tt>$1</tt></blockquote>.
Малюмат базасынынъ бильдирген хатасы "<tt>$3: $4</tt>".',
'dberrortextcl' => 'Малюмат базасындан сораткъанда синтаксис хатасы олды.
Малюмат базасындан сонъки соратма:
«$1»
Къулланылгъан функция «$2».
Малюмат базасынынъ бильдирген хатасы «$3: $4».',
'noconnect' => 'Багъышланъыз! Техникий проблемалар себебинден wiki малюмат базасынынъ серверинен багълынып оламай. <br /> $1',
'nodb' => '$1 малюмат базасыны сайламагъа чаре ёкъ',
'cachederror' => 'Ашагъыда сиз истеген саифенинъ кэширленген копиясыдыр. Бунынъ ичюн о эскирген ола биле.',
'laggedslavemode' => 'Дикъкъат! Бу саифеде сонъки янъарув олмай биле.',
'readonly' => 'Малюмат базасы килитленди',
'enterlockreason' => 'Блок этювнинъ себебини ве девамыны кирсетинъиз.',
'readonlytext' => 'План ишлемелеринден себеп малюмат базасы вакътынджа блок этильди. Ишлемелер тамамлангъан сонъ нормаль алына къайтаджакъ.
Малюмат базасыны килитлеген идареджининъ анълатмасы: $1',
'missing-article' => 'Малюмат базасында тапылмасы керек олгъан саифенинъ метни тапылмады, «$1» $2.
Адетиндже ёкъ этильген саифенинъ кечмиш саифесине эскирген багълантынен кечип бакъкъанда бу шей олып чыкъа.
Меселе бунда олмаса, ихтималы бар ки, программада бир хата тапкъандырсынъыз.
Лютфен, URL язып бундан [[Special:ListUsers/sysop|идареджиге]] хабер беринъиз.',
'missingarticle-rev' => '(версия № $1)',
'missingarticle-diff' => '(фаркъ: $1, $2)',
'readonly_lag' => 'Малюмат базасынынъ экилемджи сервери бирлемджи серверинен синхронизирленгендже малюмат базасы денъиштирильмемеси ичюн автоматик оларакъ блок этильди.',
'internalerror' => 'Ички хата',
'internalerror_info' => 'Ички хата: $1',
'filecopyerror' => '"$1" файлы "$2" файлына копияланып оламай.',
'filerenameerror' => 'файлнынъ "$1" деген ады "$2" оларакъ денъиштирилип оламай.',
'filedeleteerror' => '"$1" файлы ёкъ этилип оламай.',
'directorycreateerror' => '"$1" директориясы яратылып оламай.',
'filenotfound' => '"$1" файлы тапылып оламай.',
'fileexistserror' => '"$1" файлы сакъланып оламай. Ойле файл энди мевджут.',
'unexpected' => 'бекленмеген дегер: "$1"="$2".',
'formerror' => 'Хата: форманынъ малюматыны ёлламакънынъ ич чареси ёкъ',
'badarticleerror' => 'Сиз япмагъа истеген ишлев бу саифеде япылып оламай.',
'cannotdelete' => 'Бельгиленген саифе я да корюниш ёкъ этилип оламады. (башкъа бир къулланыджы тарафындан ёкъ этильген ола билир).',
'badtitle' => 'Рухсетсиз серлева',
'badtitletext' => 'Истенильген саифе ады догъру дегиль, о боштыр, яхут тиллерара багъланты я да викилерара багъланты догъру язылмагъан. Ихтималы бар ки, саифе адында ясакълангъан ишаретлер бар.',
'perfcached' => 'Малюматлар даа эвельджеден азырлангъан ола билир. Бу себептен эскирген ола билир!',
'perfcachedts' => 'Ашагъыда кэште сакълангъан малюмат булуна, сонъки янъарув заманы: $1.',
'querypage-no-updates' => 'Бу саифени денъиштирмеге шимди изин ёкъ. Бу малюмат аман янъартылмайджакъ.',
'wrong_wfQuery_params' => 'wfQuery() функциясы ичюн изинсиз параметрлер<br />
Функция: $1<br />
Соратма: $2',
'viewsource' => 'менба кодуны косьтер',
'viewsourcefor' => '$1 ичюн',
'actionthrottled' => 'Арекет токъталды',
'actionthrottledtext' => 'Спамгъа къаршы куреш себебинден бу арекетни аз вакъыт ичинде чокъ кере текрарлап оламайсынъыз. Мумкюн олгъан къарардан зияде арекет яптынъыз. Бир къач дакъкъадан сонъ текрарлап бакъынъыз.',
'protectedpagetext' => 'Бу саифени кимсе денъиштирмесин деп о блок этильди.',
'viewsourcetext' => 'Саифенинъ кодуны козьден кечирип копиялай билесинъиз:',
'protectedinterface' => 'Бу саифеде система интерфейсининъ метини булунгъаны ичюн мында хата чыкъмасын деп денъишиклик япмакъ ясакъ.',
'editinginterface' => "'''Тенби''': MediaWiki система беянатылы бир саифени денъиштирмектесинъиз. Бу саифедеки денъишикликлер къулланыджы интерфейс корюнишини дигер къулланыджылар ичюн де денъиштиреджек. Лютфен, терджимелер ичюн [http://translatewiki.net/wiki/Main_Page?setlang=crh translatewiki.net] сайтыны (MediaWiki ресмий локализация лейхасы) къулланынъыз.",
'sqlhidden' => '(SQL истинтагъы сакълы)',
'cascadeprotected' => 'Бу саифени денъиштирип оламазсынъыз, чюнки каскад къорчалав алтында булунгъан {{PLURAL:$1|саифеге|саифелерге}} менсюптир:
$2',
'namespaceprotected' => "'''$1''' исим фезасында саифелер денъиштирмеге акъкъынъыз ёкъ.",
'customcssjsprotected' => 'Бу саифеде дигер къулланыджынынъ шахсий сазламалары бар олгъаны ичюн саифени денъиштирип оламазсынъыз.',
'ns-specialprotected' => '{{ns:special}} исим фезасындаки саифелерни денъиштирмек ясакъ.',
'titleprotected' => "Бойле серлеванен саифе яратмакъ ясакътыр. Ясакълагъан: [[User:$1|$1]].
Себеп: ''$2''.",
# Virus scanner
'virus-badscanner' => "Янълыш сазлама. Билинмеген вирус сканери: ''$1''",
'virus-scanfailed' => 'скан этюв мувафакъиетсиз (код $1)',
'virus-unknownscanner' => 'билинмеген антивирус:',
# Login and logout pages
'logouttitle' => 'Отурымны къапат',
'logouttext' => "'''Отурымны къапаттынъыз.'''
Шимди {{SITENAME}} сайтыны аноним оларакъ къулланып оласынъыз, я да янъыдан [[Special:UserLogin|отурым ачып]] оласынъыз (истер айны къулланыджы адынен, истер башкъа бир къулланыджы адынен). Web браузеринъиз кэшини темизлегендже базы саифелер санки аля даа отурымынъыз ачыкъ экен киби корюнип олур.",
'welcomecreation' => '== Хош кельдинъиз, $1! ==
Эсабынъыз ачылды.
Бу сайтнынъ [[Special:Preferences|сазламаларыны]] шахсынъызгъа коре денъиштирмеге унутманъыз.',
'loginpagetitle' => 'Отурым ач',
'yourname' => 'Къулланыджы адынъыз',
'yourpassword' => 'Паролинъиз',
'yourpasswordagain' => 'Парольни бир даа язынъыз:',
'remembermypassword' => 'Бу компьютерде мени хатырла',
'yourdomainname' => 'Домен адынъыз',
'externaldberror' => 'Отурымынъыз ачылгъанда бир хата олды. Бу тыш эсабынъызгъа денъишиклик япмагъа акъкъынъыз олмаювындан мейдангъа келип ола.',
'login' => 'Кириш',
'nav-login-createaccount' => 'Кириш / Къайд олув',
'loginprompt' => 'Отурым ачмакъ ичюн «cookies»ге изин бермелисинъиз.',
'userlogin' => 'Кириш / Къайд олув',
'logout' => 'Чыкъыш',
'userlogout' => 'Чыкъыш',
'notloggedin' => 'Отурым ачмадынъыз.',
'nologin' => "Даа эсап ачмадынъызмы? '''$1'''.",
'nologinlink' => 'Къайд ол',
'createaccount' => 'Янъы эсап ач',
'gotaccount' => "Даа эвель эсап ачкъан эдинъизми? '''$1'''.",
'gotaccountlink' => 'Отурым ачынъыз',
'createaccountmail' => 'e-mail вастасынен',
'badretype' => 'Кирсеткен пароллеринъиз айны дегиль.',
'userexists' => 'Кирсеткен къулланыджы адынъыз энди къулланыла.
Башкъа бир къулланыджы ады сайланъыз.',
'youremail' => 'E-mail адресинъиз:',
'username' => 'Къулланыджы ады:',
'uid' => 'Къайд номери:',
'prefs-memberingroups' => 'Азасы олгъан {{PLURAL:$1|группа|группалар}}:',
'yourrealname' => 'Керчек адынъыз:',
'yourlanguage' => 'Интерфейс тили:',
'yourvariant' => 'Тиль сайлавы:',
'yournick' => 'Сизинъ лагъабынъыз (имзаларда косьтериледжек):',
'badsig' => 'Янълыш имза. HTML тэглерининъ догърулыгъыны бакъынъыз.',
'badsiglength' => 'Къарардан зияде узун имзадыр, {{PLURAL:$1|1|$1}} зияде ишареттен ибарет олмасы мумкюн дегиль.',
'yourgender' => 'Джынсынъыз:',
'gender-unknown' => 'Бильдирильмеген',
'gender-male' => 'Эркек',
'gender-female' => 'Къадын',
'prefs-help-gender' => 'Меджбурий дегиль: wiki тарафындан догъру джыныс адреслеви ичюн къулланыла. Бу малюмат умумий оладжакъ.',
'email' => 'E-mail',
'prefs-help-realname' => 'Керчек адынъыз (меджбурий дегильдир).
Эгер бильдирсенъиз, саифелердеки денъишикликлерин кимнинъ япкъаныны косьтермек ичюн къулланыладжакъ.',
'loginerror' => 'Отурым ачма хатасы',
'prefs-help-email' => 'E-mail (меджбурий дегильдир). E-mail адреси бильдирильген олса, шимдики паролинъизни унутсанъыз, янъы бир пароль истеп оласынъыз.
Бундан гъайры бу викидеки саифенъизден башкъа къулланыджыларгъа сизнен багъланмагъа имкян береджек. E-mail адресинъиз башкъа къулланыджыларгъа косьтерильмейджек.',
'prefs-help-email-required' => 'E-mail адреси лязим.',
'nocookiesnew' => 'Къулланыджы эсабы ачылгъан, факъат танытылмагъан. {{SITENAME}} къулланыджыларны танытмакъ ичюн «cookies»ни къуллана. Сизде бу функция къапалы вазиеттедир. «Cookies» функциясыны ишлетип текрар янъы адынъыз ве паролинъизнен тырышып бакъыныз.',
'nocookieslogin' => '{{SITENAME}} «cookies»ни къуллана. Сизде бу функция къапалы вазиеттедир. «Cookies» функциясыны ишлетип текрар тырышып бакъынъыз.',
'noname' => 'Догъру къулланыджы адыны кирсетмединъиз.',
'loginsuccesstitle' => 'Кириш япылды',
'loginsuccess' => "'''$1 адынен {{SITENAME}} сайтында чалышып оласынъыз.'''",
'nosuchuser' => '«$1» адлы къулланыджы ёкъ.
Къулланыджы адларында буюк ве кичик арифлер арасында фаркъ бар.
Догъру язгъанынъызны тешкеринъиз я да [[Special:UserLogin/signup|янъы къулланыджы эсабыны ачынъыз]].',
'nosuchusershort' => '«<nowiki>$1</nowiki>» адлы къулланыджы тапыламады. Адынъызны догъру язгъанынъыздан эмин олунъыз.',
'nouserspecified' => 'Къулланыджы адыны кирсетмек керексинъиз.',
'wrongpassword' => 'Кирсеткен паролинъиз янълыштыр. Лютфен, текрар этинъиз.',
'wrongpasswordempty' => 'Кирсеткен паролинъиз боштыр.
Лютфен, текрар этинъиз.',
'passwordtooshort' => 'Паролинъиз пек къыскъа. Энъ аз $1 ариф ве я ракъамдан ибарет олмалы.',
'mailmypassword' => 'Янъы пароль йибер',
'passwordremindertitle' => '{{grammar:genitive|{{SITENAME}}}} къулланыджынынъ пароль хатырлатувы',
'passwordremindertext' => 'Бирев (бельки де бу сизсинъиз, $1 IP адресинден) {{SITENAME}} сайты ичюн ($4) янъы къулланыджы паролини истеди.
$2 къулланыджысына вакътынджа <code>$3</code> пароли яратылды. Эгер бу керчектен де сизинъ истегинъиз олгъан олса, отурым ачып янъы бир пароль яратманъыз керектир. Мувакъкъат паролинъизнинъ муддети {{PLURAL:$5|1 кунь|$5 кунь}} ичинде доладжакъ.
Эгер де янъы пароль талап этмеген олсанъыз я да эски паролинъизни хатырлап энди оны денъиштирмеге истемесенъиз, бу мектюпни дикъкъаткъа алмайып эски паролинъизни къулланмагъа девам этип оласынъыз.',
'noemail' => '$1 адлы къулланыджы ичюн e-mail бильдирильмеди.',
'passwordsent' => 'Янъы пароль e-mail ёлунен къулланыджынынъ бильдирген $1 адресине йиберильди. Парольни алгъан сонъ текрар кириш япынъыз.',
'blocked-mailpassword' => 'IP адресинъизден саифелер денъиштирюв ясакълы, пароль хатырлатув функциясы да блок этильди.',
'eauthentsent' => 'Бильдирильген e-mail адресине ичинде тасдыкъ коду олгъан бир мектюп ёлланды. Сиз шу мектюпте язылгъан арекетлерни япып бу e-mail адресининъ саиби керчектен де сиз олгъанынъызны тасдыкълагъан сонъ башкъа мектюп ёлланып олур.',
'throttled-mailpassword' => 'Пароль хатырлатув функциясы энди сонъки {{PLURAL:$1|1|$1}} саат девамында ишлетильген эди. {{PLURAL:$1|1|$1}} саат ичинде тек бир хатырлатув ишлетмек мумкюн.',
'mailerror' => 'Почта йиберильгенде бир хата мейдангъа кельди: $1',
'acct_creation_throttle_hit' => 'Сизинъ IP адресинъизни къулланып бу викини зиярет эткенлер сонъки куньде {{PLURAL:$1|1 эсап|$1 эсап}} яратты. Бу вакъыт аралыгъында бир IP-ден даа чокъ эсап яратмакъ мумкюн дегиль.
Нетиджеде, бу IP адресини къуллангъан зияретчилер шимди даа зияде эсап ачып оламазлар.',
'emailauthenticated' => 'E-mail адресинъиз $2 $3 тарихында тасдыкъланды.',
'emailnotauthenticated' => 'E-mail адресинъиз тасдыкъланмады, викининъ e-mail иле багълы функциялары чалышмайджакъ.',
'noemailprefs' => 'Бу функцияларнынъ чалышмасы ичюн сазламаларынъызда бир e-mail адреси бильдиринъиз.',
'emailconfirmlink' => 'E-mail адресинъизни тасдыкъланъыз',
'invalidemailaddress' => 'Язгъан адресинъиз e-mail стандартларында олмагъаны ичюн къабул этильмеди. Лютфен, догъру адресни язынъыз я да къутуны бош къалдырынъыз.',
'accountcreated' => 'Эсап ачылды',
'accountcreatedtext' => '$1 ичюн бир къулланыджы эсабы ачылды.',
'createaccount-title' => '{{SITENAME}} сайтында янъы бир эсап яратылувы',
'createaccount-text' => 'Бирев сизинъ e-mail адресини бильдирип {{SITENAME}} сайтында ($4) "$2" адлы бир эсап яратты.
Шу эсап ичюн пароль будыр: "$3".
Сиз шимди отурым ачып паролинъизни денъиштирмек керексинъиз.
Шу эсап хата оларакъ яратылгъан олса бу мектюпке къулакъ асмайып оласынъыз.',
'login-throttled' => 'Якъын заманда пек чокъ кере кирмеге тырыштынъыз.
Лютфен, къайта кирмезден эвель бираз бекленъиз.',
'loginlanguagelabel' => 'Тиль: $1',
# Password reset dialog
'resetpass' => 'Парольни денъиштир',
'resetpass_announce' => 'Мувакъкъат код вастасынен кирдинъиз. Киришни тамамламакъ ичюн янъы парольни мында къоюнъыз:',
'resetpass_header' => 'Эсапнынъ паролини денъиштир',
'oldpassword' => 'Эски пароль',
'newpassword' => 'Янъы пароль',
'retypenew' => 'Янъы парольни текрар язынъыз',
'resetpass_submit' => 'Пароль къойып кир',
'resetpass_success' => 'Паролинъиз мувафакъиетнен денъиштирильди! Отурымынъыз ачылмакъта...',
'resetpass_bad_temporary' => 'Мувакъкъат паролинъиз янълыштыр. Ола билир ки, сиз энди паролинъизни мувафакъиетнен денъиштирген я да e-mail-ге янъы бир пароль ёлламагъа риджа эткендирсинъиз.',
'resetpass_forbidden' => 'Пароль денъиштирмек ясакъ',
'resetpass-no-info' => 'Бу саифеге догърудан иришмек ичюн отурым ачмакъ керексинъиз.',
'resetpass-submit-loggedin' => 'Парольни денъиштир',
'resetpass-wrong-oldpass' => 'Рухсетсиз мувакъкъат я да шимдики пароль.
Паролинъизни энди мувафакъиетнен денъиштирдинъиз я да янъы бир мувакъкъат пароль истединъиз.',
'resetpass-temp-password' => 'Мувакъкъат пароль:',
# Edit page toolbar
'bold_sample' => 'Къалын язылыш',
'bold_tip' => 'Къалын язылыш',
'italic_sample' => 'Италик (курсив) язылыш',
'italic_tip' => 'Италик (курсив) язылыш',
'link_sample' => 'Саифенинъ серлевасы',
'link_tip' => 'Ички багъланты',
'extlink_sample' => 'http://www.example.com саифенинъ серлевасы',
'extlink_tip' => 'Тыш багъланты (Адрес огюне http:// къоймагъа унутманъыз)',
'headline_sample' => 'Серлева язысы',
'headline_tip' => '2-нджи севие серлева',
'math_sample' => 'Бу ерге формуланы кирсетинъиз',
'math_tip' => 'Риязий (математик) формула (LaTeX форматында)',
'nowiki_sample' => 'Сербест формат метининъизни мында язынъыз.',
'nowiki_tip' => 'вики формат этювини игнор эт',
'image_sample' => 'Resim.jpg',
'image_tip' => 'Эндирильген файл',
'media_sample' => 'Ses.ogg',
'media_tip' => 'Медиа файлына багъланты',
'sig_tip' => 'Имзанъыз ве тарих',
'hr_tip' => 'Горизонталь сызыкъ (пек сыкъ къулланманъыз)',
# Edit pages
'summary' => 'Денъишиклик къыскъа тасвири:',
'subject' => 'Мевзу/серлева:',
'minoredit' => 'Кичик денъишиклик',
'watchthis' => 'Саифени козет',
'savearticle' => 'Саифени сакъла',
'preview' => 'Бакъып чыкъув',
'showpreview' => 'Бакъып чыкъ',
'showlivepreview' => 'Тез бакъып чыкъув',
'showdiff' => 'Денъишикликлерни косьтер',
'anoneditwarning' => "'''Дикъкъат''': Отурым ачмагъанынъыздан себеп денъишиклик тарихына сизинъ IP адресинъиз язылыр.",
'missingsummary' => "'''Хатырлатма.''' Денъиштирмелеринъизни къыскъадан тариф этмединъиз. «Саифени сакъла» дёгмесине текрар басув иле денъиштирмелеринъиз тефсирсиз сакъланаджакълар.",
'missingcommenttext' => 'Лютфен, ашагъыда тефсир язынъыз.',
'missingcommentheader' => "'''Хатырлатма:''' Тефсир серлевасыны язмадынъыз. «Саифени сакъла» дёгмесине текрар баскъан сонъ тефсиринъиз серлевасыз сакъланыр.",
'summary-preview' => 'Бакъып чыкъув тасвири:',
'subject-preview' => 'Бакъып чыкъув серлевасы:',
'blockedtitle' => 'Къулланыджы блок этильди.',
'blockedtext' => "'''Эсабынъыз я да IP адресинъиз блок этильди.'''
Блок япкъан идареджи: $1 .
Блок себеби: ''«$2»''.
* Блокнынъ башы: $8
* Блокнынъ сонъу: $6
* Блок этильген: $7
Блок этювни музакере этмек ичюн $1 къулланыджысына я да башкъа эр анги [[{{MediaWiki:Grouppage-sysop}}|идареджиге]] мектюп ёллап оласынъыз.
Дикъкъат этинъиз ки, къайд олунмагъан ве e-mail адресинъизни [[Special:Preferences|шахсий сазламаларда]] тасдыкъламагъан алда, эм де блок этильгенде сизге мектюп ёлламакъ ясакъ этильген олса, идареджиге мектюп ёллап оламазсынъыз.
Шимдики IP адресинъиз — $3, блок этюв идентификаторы — #$5. Лютфен, идареджилерге мектюплеринъизде бу малюматны бильдиринъиз.",
'autoblockedtext' => 'IP адресинъиз эвельде блок этильген къулланыджылардан бири тарафындан къулланылгъаны ичюн автоматик оларакъ блок этильди. Оны блок эткен идареджи ($1) бойле себепни бильдирди:
:«$2»
* Блокнынъ башы: $8
* Блокнынъ сонъу: $6
* Блок этильген: $7
Блок этювни музакере этмек ичюн $1 къулланыджысына я да башкъа эр анги [[{{MediaWiki:Grouppage-sysop}}|идареджиге]] мектюп ёллап оласынъыз.
Дикъкъат этинъиз ки, къайд олунмагъан ве e-mail адресинъизни [[Special:Preferences|шахсий сазламаларда]] тасдыкъламагъан алда, эм де блок этильгенде сизге мектюп ёлламакъ ясакъ этильген олса, идареджиге мектюп ёллап оламазсынъыз.
Шимдики IP адресинъиз — $3, блок этюв идентификаторы — #$5. Лютфен, идареджилерге мектюплеринъизде оны бильдиринъиз.',
'blockednoreason' => 'себеп бильдирильмеди',
'blockedoriginalsource' => 'Ашагъыда «$1» саифесининъ метини булуна.',
'blockededitsource' => "Ашагъыда «$1» саифесиндеки '''япкъан денъиштирмелеринъизнинъ''' метини булуна.",
'whitelistedittitle' => 'Денъиштирмек ичюн отурым ачмалысынъыз',
'whitelistedittext' => 'Саифени денъиштирмек ичюн $1 керексинъиз.',
'confirmedittitle' => 'E-mail адресини тасдыкъламакъ лязимдир',
'confirmedittext' => 'Саифени денъиштирмеден эвель e-mail адресинъизни тасдыкъламалысынъыз. Лютфен, [[Special:Preferences|сазламалар саифесинде]] e-mail адресинъизни кирсетинъиз ве тасдыкъланъыз.',
'nosuchsectiontitle' => 'Ойле болюк ёкъ',
'nosuchsectiontext' => 'Бар олмагъан болюкни денъиштирип бакътынъыз.',
'loginreqtitle' => 'Отурым ачмалысынъыз',
'loginreqlink' => 'кириш',
'loginreqpagetext' => 'Башкъа саифелерни бакъмакъ ичюн $1 борджлусынъыз.',
'accmailtitle' => 'Пароль ёлланды',
'accmailtext' => "[[User talk:$1|$1]] ичюн тесадуфий ишаретлерден яратылгъан пароль $2 адресине ёлланды.
Бу янъы эсап ичюн пароль, кириш япкъандан сонъ ''[[Special:ChangePassword|парольни денъиштир]]'' болюгинде денъиштирилип олур.",
'newarticle' => '(Янъы)',
'newarticletext' => "Сиз бу багълантынен шимдилик ёкъ олгъан саифеге авуштынъыз. Янъы бир саифе яратмакъ ичюн ашагъыда булунгъан пенджереге метин язынъыз (тафсилятлы малюмат алмакъ ичюн [[{{MediaWiki:Helppage}}|ярдым саифесине]] бакъынъыз). Бу саифеге тесадюфен авушкъан олсанъыз, браузеринъиздеки '''кери''' дёгмесине басынъыз.",
'anontalkpagetext' => "----''Бу музакере саифеси шимдилик къайд олунмагъан я да отурымыны ачмагъан адсыз (аноним) къулланыджыгъа менсюптир. Идентификация ичюн IP адрес ишлетиле. Бир IP адресинден бир къач къулланыджы файдаланып ола.
Эгер сиз аноним къулланыджы олсанъыз ве сизге кельген беянатларны янълыштан кельгенини беллесенъиз, лютфен, артыкъ бунынъ киби къарышыкълыкъ олмасын деп [[Special:UserLogin|отурым ачынъыз]].''",
'noarticletext' => 'Бу саифе шимди боштыр. Бу серлеваны башкъа саифелерде [[Special:Search/{{PAGENAME}}|къыдырып оласынъыз]], <span class="plainlinks">[{{fullurl:{{#Special:Log}}|page={{FULLPAGENAMEE}}}} багълы журнал къайдларыны къыдырып оласынъыз] я да бу саифени озюнъиз [{{fullurl:{{FULLPAGENAME}}|action=edit}} язып оласынъыз]</span>.',
'userpage-userdoesnotexist' => '"$1" адлы къулланыджы ёкътыр. Тамам бу саифени денъиштирмеге истегенинъизни тешкеринъиз.',
'clearyourcache' => "'''Ихтар:''' Сазламаларынъызны сакълагъандан сонъ денъишикликлерни корьмек ичюн браузеринъизнинъ кэшини темизлемек керексинъиз.
'''Mozilla / Firefox / Safari:''' ''Shift'' басылы экенде саифени янъыдан юклеп я да ''Ctrl-Shift-R'' япып (Macintosh ичюн ''Command-R'');
'''Konqueror:''' саифени янъыдан юкле дёгмесине я да F5 басып;
'''Opera:''' ''Tools → Preferences'' менюсинде кэшни темизлеп;
'''Internet Explorer:''' ''Ctrl'' басылы экенде саифени янъыдан юклеп я да ''Ctrl-F5'' басып.",
'usercssjsyoucanpreview' => "'''Тевсие:''' Саифени сакъламаздан эвель '''бакъып чыкъ''' дёгмесине басып япкъан янъы саифенъизни козьден кечиринъиз.",
'usercsspreview' => "'''Унутманъыз, бу тек бакъып чыкъув - къулланыджы CSS файлынъыз аля даа сакъланмады!'''",
'userjspreview' => "'''Унутманъыз, сиз шимди тек тест этесинъиз я да бакъып чыкъув коресинъиз - къулланыджы JavaScript'и шимдилик сакъланмады.'''",
'userinvalidcssjstitle' => "'''Ихтар:''' \"\$1\" адынен бир тема ёкътыр. тема-ады.css ве .js файлларынынъ адлары кичик афир иле язмакъ керек, яни {{ns:user}}:Темель/'''M'''onobook.css дегиль, {{ns:user}}:Темель/'''m'''onobook.css.",
'updated' => '(Янъарды)',
'note' => "'''Ихтар:'''",
'previewnote' => "'''Бу тек бакъып чыкъув, метин аля даа сакъланмагъан!'''",
'previewconflict' => 'Бу бакъып чыкъув юкъары тарир пенджересиндеки метиннинъ сакъланувдан сонъ оладжакъ корюнишини акс эте.',
'session_fail_preview' => "''' Сервер сиз япкъан денъиштирмелерни сессия идентификаторы джоюлгъаны себебинден сакълап оламады.
Бу вакътынджа проблемадыр. Лютфен, текрар сакълап бакъынъыз.
Бундан да сонъ олып чыкъмаса, малюмат локаль файлгъа сакъланъыз да браузеринъизни бир къапатып ачынъыз.'''",
'session_fail_preview_html' => "'''Афу этинъиз! HTML сессиянынъ малюматлары гъайып олгъаны себебинден сизинъ денъиштирмелеринъизни къабул этмеге имкян ёкътыр.'''",
'token_suffix_mismatch' => "'''Сизинъ программанъыз тарир пенджересинде пунктуация ишаретлерини догъру ишлемегени ичюн япкъан денъишиклигинъиз къабул олунмады. Денъишиклик саифенинъ метни корюнишининъ бозулмамасы ичюн лягъу этильди.
Бунынъ киби проблемалар анонимизирлеген хаталы web-проксилер къулланувдан чыкъып олалар.'''",
'editing' => '"$1" саифесини денъиштирмектесинъиз',
'editingsection' => '"$1" саифесинде болюк денъиштирмектесинъиз',
'editingcomment' => '$1 саифесини денъиштирмектесинъиз (янъы болюк)',
'editconflict' => 'Денъишиклик зыт кетюви: $1',
'explainconflict' => "Сиз саифени денъиштирген вакъытта башкъа бири де денъишиклик япты.
Юкъарыдаки язы саифенинъ шимдики алыны косьтере.
Сизинъ денъишикликлеринъиз алткъа косьтерильди.
Шимди япкъан денъишиклеринъизни ашагъы пенджереден юкъары пенджереге авуштырмакъ керек оладжакъсынъыз.
\"Саифени сакъла\"гъа баскъанда '''тек''' юкъарыдаки язы сакъланаджакъ.",
'yourtext' => 'Сизинъ метнинъиз',
'storedversion' => 'Сакълангъан метин',
'nonunicodebrowser' => "'''ТЕНБИ: Браузеринъизде Unicode кодламасы танылмаз. Саифелер денъиштиргенде бутюн ASCII олмагъан ишаретлернинъ ерине оларнынъ оналтылыкъ коду язылыр.'''",
'editingold' => "'''ДИКЪКЪАТ: Саифенинъ эски бир версиясында денъишиклик япмакътасынъыз.
Сакълагъанынъызда бу тарихлы версиядан кунюмизге къадар олгъан денъишикликлер ёкъ оладжакъ.'''",
'yourdiff' => 'Фаркълар',
'copyrightwarning' => "'''Лютфен, дикъкъат:''' {{SITENAME}} сайтына къошулгъан бутюн исселер <i>$2</i> мукъавелеси даиресиндедир (тафсилят ичюн $1 саифесине бакъынъыз).
Къошкъан иссенъизнинъ башкъа инсанлар тарафындан аджымасызджа денъиштирильмесини я да азат тарзда ве сынъырсызджа башкъа ерлерге дагъытылмасыны истемесенъиз, иссе къошманъыз.<br />
Айрыджа, мында иссе къошып, бу иссенинъ озюнъиз тарафындан язылгъанына, я да джемааткъа ачыкъ бир менбадан я да башкъа бир азат менбадан копиялангъанына гарантия берген оласынъыз.<br />
'''<center>МУЭЛЛИФЛИК АКЪКЪЫНЕН КЪОРЧАЛАНГЪАН ИЧ БИР МЕТИННИ МЫНДА РУХСЕТСИЗ КЪОШМАНЪЫЗ!</center>'''",
'copyrightwarning2' => "'''Лютфен, дикъкъат:''' {{SITENAME}} сайтына сиз къошкъан бутюн исселер башкъа бир къулланыджы тарафындан денъиштирилип я да ёкъ этилип олур. Къошкъан иссенъизнинъ башкъа инсанлар тарафындан аджымасызджа денъиштирильмесини я да азат тарзда ве сынъырсызджа башкъа ерлерге дагъытылмасыны истемесенъиз, иссе къошманъыз.<br />
Айрыджа, мында иссе къошып, бу иссенинъ озюнъиз тарафындан язылгъанына, я да джемааткъа ачыкъ бир менбадан я да башкъа бир азат менбадан копиялангъанына гарантия берген оласынъыз ($1 бакъынъыз).<br />
'''МУЭЛЛИФЛИК АКЪКЪЫНЕН КЪОРЧАЛАНГЪАН ИЧ БИР МЕТИННИ МЫНДА РУХСЕТСИЗ КЪОШМАНЪЫЗ!'''",
'longpagewarning' => "'''ТЕНБИ: Бу саифе $1 килобайт буюклигиндедир; базы браузерлер денъишиклик япкъан вакъытта 32 kb ве устю буюкликлерде проблемалар яшап олур. Саифени парчаларгъа айырмагъа тырышынъыз.'''",
'longpageerror' => "'''ТЕНБИ: Бу саифе $1 килобайт буюклигиндедир. Азамий (максималь) изинли буюклик исе $2 килобайт. Бу саифе сакъланып оламаз.'''",
'readonlywarning' => "'''ТЕНБИ: Бакъым себеби иле малюмат базасы шимди килитлидир. Бу себептен денъишикликлеринъиз шимди сакълап оламасынъыз. Язгъанларынъызны башкъа бир эдитор программасына алып сакълап олур ве даа сонъ текрар мында кетирип сакълап олурсынъыз'''
Малюмат базасыны килитлеген идареджи озь арекетини бойле анълатты: $1",
'protectedpagewarning' => "'''ТЕНБИ: Бу саифе къорчалангъан ве тек идареджилер тарафындан денъиштирилип олур.'''",
'semiprotectedpagewarning' => "'''Тенби''': Бу саифе тек къайдлы къулланыджылар тарафындан денъиштирилип олур.",
'cascadeprotectedwarning' => "'''Тенби:''' Бу саифени тек «Идареджилер» группасына кирген къулланыджылар денъиштирип олалар, чюнки о каскад къорчалав алтында булунгъан {{PLURAL:$1|саифеге|саифелерге}} менсюптир:",
'titleprotectedwarning' => "'''ТЕНБИ: Бу саифе къорчалав алтындадыр, тек [[Special:ListGroupRights|махсус акъларгъа]] саип къулланыджылар оны яратып олалар.'''",
'templatesused' => 'Бу саифеде къулланылгъан шаблонлар:',
'templatesusedpreview' => 'Сиз бакъып чыкъкъан саифенъизде къулланылгъан шаблонлар:',
'templatesusedsection' => 'Бу болюкте къулланылгъан шаблонлар:',
'template-protected' => '(къорчалав алтында)',
'template-semiprotected' => '(къысмен къорчалав алтында)',
'hiddencategories' => 'Бу саифе {{PLURAL:$1|1|$1}} гизли категориягъа менсюптир:',
'nocreatetitle' => 'Саифе яратув сынъырлыдыр',
'nocreatetext' => '{{SITENAME}} сайтында янъы саифе яратув сынъырлыдыр.
Кери къайтып мевджут олгъан саифени денъиштире, [[Special:UserLogin|отурым ача я да янъы бир эсап яратып оласынъыз]].',
'nocreate-loggedin' => 'Янъы саифелер яратмагъа изининъиз ёкътыр.',
'permissionserrors' => 'Иришим акъларынынъ хаталары',
'permissionserrorstext' => 'Буны япмагъа изининъиз ёкътыр. {{PLURAL:$1|Себеп|Себеплер}}:',
'permissionserrorstext-withaction' => 'Ашагъыдаки {{PLURAL:$1|себептен|себеплерден}} $2 рухсетинъиз ёкъ:',
'recreate-deleted-warn' => "'''Дикъкъат: эвельдже ёкъ этильген саифени янъыдан яратмагъа тырышасынъыз.'''
Бу саифени керчектен де янъыдан яратмагъа истейсинъизми? Ашагъыда ёкъ этилюв журналы булуна.",
'deleted-notice' => 'Бу саифе ёкъ этильди.
Ёкъ этюв журналындан къайдлары ашагъыда косьтериле.',
'edit-gone-missing' => 'Саифе янъартылып оламай.
Ола биле ки, о ёкъ этильгендир.',
'edit-conflict' => 'Денъишикликлер конфликти.',
'edit-no-change' => 'Япкъан денъишиклигинъиз сакъланмагъан, чюнки метинде бир тюрлю денъишиклик япылмады.',
'edit-already-exists' => 'Янъы саифени яратмакъ мумкюн дегиль.
О энди мевджут.',
# "Undo" feature
'undo-success' => 'Денъишиклик лягъу этилип ола. Лютфен, айны бу денъишикликлер мени меракъландыра деп эмин олмакъ ичюн версиялар тенъештирилювини козьден кечирип денъишикликлерни тамамен япмакъ ичюн «Саифени сакъла» дёгмесине басынъыз.',
'undo-failure' => 'Арадаки денъишикликлер бири-бирине келишикли олмагъаны ичюн денъишиклик лягъу этилип оламай.',
'undo-norev' => 'Денъишиклик лягъу этилип оламаз, чюнки о я да ёкъ, я да бар эди, амма ёкъ этильген.',
'undo-summary' => '[[Special:Contributions/$2|$2]] ([[User talk:$2|музакере]]) къулланыджысынынъ $1 номералы денъишиклигини лягъу этюв.',
# Account creation failure
'cantcreateaccounttitle' => 'Эсап яратмакънынъ ич чареси ёкъ.',
'cantcreateaccount-text' => "Бу IP адресинден ('''$1''') эсап яратув [[User:$3|$3]] тарафындан блок этильди.
$3 мына бу себепни бильдирди: ''$2''",
# History pages
'viewpagelogs' => 'Бу саифенинъ журналларыны косьтер',
'nohistory' => 'Бу саифенинъ кечмиш версиясы ёкъ.',
'currentrev' => 'Шимдики версия',
'currentrev-asof' => '$1 тарихында сонъки оларакъ денъиштирильген саифенинъ шимдики алы',
'revisionasof' => 'Саифенинъ $1 тарихындаки алы',
'revision-info' => 'Саифенинъ $2 тарафындан олуштырылгъан $1 тарихындаки алы', # Additionally available: $3: revision id
'previousrevision' => '← Эвельки алы',
'nextrevision' => 'Сонъраки алы →',
'currentrevisionlink' => 'энъ янъы алыны косьтер',
'cur' => 'фаркъ',
'next' => 'сонъраки',
'last' => 'сонъки',
'page_first' => 'ильк',
'page_last' => 'сонъки',
'histlegend' => "(фаркъ) = шимдики алнен арадаки фаркъ,
(сонъки) = эвельки алнен арадаки фаркъ, '''к''' = кичик денъишиклик",
'history-fieldset-title' => 'Кечмишке бакъув',
'deletedrev' => '[ёкъ этильди]',
'histfirst' => 'Энъ эски',
'histlast' => 'Энъ янъы',
'historysize' => '({{PLURAL:$1|1 байт|$1 байт}})',
'historyempty' => '(бош)',
# Revision feed
'history-feed-title' => 'Денъишикликлер тарихы',
'history-feed-description' => 'Викиде бу саифенинъ денъишикликлер тарихы',
'history-feed-item-nocomment' => '$2 устюнде $1', # user at time
'history-feed-empty' => 'Истенильген саифе мевджут дегиль.
О ёкъ эильген я да ады денъиштирильген ола биле.
Викиде бу саифеге ошагъан саифелерни [[Special:Search|тапып бакъынъыз]].',
# Revision deletion
'rev-deleted-comment' => '(тефсир ёкъ этильди)',
'rev-deleted-user' => '(къулланыджы ады ёкъ этильди)',
'rev-deleted-event' => '(къайд ёкъ этильди)',
'rev-delundel' => 'косьтер/гизле',
'revisiondelete' => 'Версияларны ёкъ эт/кери кетир',
'revdelete-hide-comment' => 'Къыскъа тарифни косьтерме',
'revdelete-hide-user' => 'Денъишикликни япкъан къулланыджы адыны/IP-ни гизле',
'revdelete-hide-restricted' => 'Малюматны адий къулланыджылардан киби идареджилерден де гизле',
'revdelete-submit' => 'Сайлангъан версиягъа ишлет',
'revdel-restore' => 'корюнювни денъиштир',
# Merge log
'revertmerge' => 'Айыр',
# Diffs
'history-title' => '$1 саифесининъ денъишиклик тарихы',
'difference' => '(Версиялар арасы фаркълар)',
'lineno' => '$1 сатыр:',
'compareselectedversions' => 'Сайлангъан версияларны тенъештир',
'editundo' => 'лягъу эт',
'diff-multi' => '({{PLURAL:$1|1 арадаки версия|$1 арадаки версия}} косьтерильмеди.)',
'diff-movedto' => '$1 саифесине авуштырылды',
# Search results
'searchresults' => 'Къыдырув нетиджелери',
'searchresults-title' => '«$1» ичюн къыдырув нетиджелери',
'searchresulttext' => '{{SITENAME}} ичинде къыдырув япмакъ хусусында малюмат алмакъ ичюн [[{{MediaWiki:Helppage}}|{{int:help}}]] саифесине бакъып оласынъыз.',
'searchsubtitle' => 'Къыдырылгъан: "[[:$1]]" ([[Special:Prefixindex/$1|"$1" иле башлангъан бутюн саифелер]]{{int:pipe-separator}}[[Special:WhatLinksHere/$1|"$1" саифесине багъланты олгъан бутюн саифелер]])',
'searchsubtitleinvalid' => "Сиз буны къыдырдынъыз '''$1'''",
'noexactmatch' => "'''\"\$1\" серлевалы бир саифе тапыламады.''' Бу саифени озюнъиз [[:\$1|яратып оласынъыз]].",
'noexactmatch-nocreate' => "'''«$1» адлы саифе ёкъ.'''",
'toomanymatches' => 'Пек чокъ эшлешме чыкъты, лютфен, башкъа бир соратма сайланъыз.',
'titlematches' => 'Макъале ады бир келе',
'notitlematches' => 'Ич бир серлевада тапыламады',
'textmatches' => 'Саифе метни бир келе',
'notextmatches' => 'Ич бир саифеде тапыламады',
'prevn' => 'эвельки $1',
'nextn' => 'сонъраки $1',
'viewprevnext' => '($1) ( $2) ($3).',
'searchhelp-url' => 'Help:Мундеридже',
'search-result-size' => '$1 ({{PLURAL:$2|1|$2}} сёз)',
'search-result-score' => 'Уйгъунлыкъ: $1 %',
'search-redirect' => '(ёллама $1)',
'search-section' => '(болюк $1)',
'search-suggest' => 'Бунымы демеге истединъиз: $1',
'search-interwiki-caption' => 'Къардаш проектлер',
'search-interwiki-default' => '$1 нетидже:',
'search-interwiki-more' => '(даа чокъ)',
'search-mwsuggest-enabled' => 'тевсиелернен',
'search-mwsuggest-disabled' => 'тевсие ёкъ',
'search-relatedarticle' => 'Багълы',
'mwsuggest-disable' => 'AJAX тевсиелерини ишлетме',
'searchrelated' => 'багълы',
'searchall' => 'эписи',
'showingresults' => "Ашагъыда № <strong>$2</strong>ден башлап {{PLURAL:$1|'''1''' нетидже|'''$1''' нетидже}} булуна.",
'showingresultsnum' => "Ашагъыда № '''$2'''ден башлап {{PLURAL:$3|'''1''' нетидже|'''$3''' нетидже}} булуна.",
'showingresultstotal' => "Ашагъыда {{PLURAL:$4|'''$3''' данеден '''$1''' нетидже косьтерильген|'''$3''' данеден '''$1 — $2''' нетидже косьтерильген}}",
'nonefound' => "'''Ихтар.''' Адийджесине къыдырув бутюн исим фезаларында япылмай. Бутюн исим фезаларында (бу джумледен къулланыджылар субетлери, шаблонлар ве иляхре) къыдырмакъ ичюн ''all:'' языны къулланынъыз, муайен бир исим фезасында къыдырмакъ ичюн исе ''ад:'' форматында онынъ адыны язынъыз.",
'search-nonefound' => 'Соратманен эшлешкен бир нетидже ёкъ.',
'powersearch' => 'Къыдыр',
'powersearch-legend' => 'Тафсилятлы къыдырув',
'powersearch-ns' => 'Бу исим фезаларында къыдыр:',
'powersearch-redir' => 'Ёллама саифелерини де косьтер',
'powersearch-field' => 'Къыдыр:',
'search-external' => 'Тыш къыдырув',
'searchdisabled' => '{{SITENAME}} сайтында къыдырув япма вакътынджа токътатылды. Бу арада Google къулланып {{SITENAME}} ичинде къыдырув япып оласынъыз. Къыдырув сайтларында индекслемелерининъ бираз эски къалгъан ола биледжегини козь огюне алынъыз.',
# Preferences page
'preferences' => 'Сазламалар',
'mypreferences' => 'Сазламаларым',
'prefs-edits' => 'Япкъан денъишиклик сайысы:',
'prefsnologin' => 'Отурым ачмадынъыз',
'prefsnologintext' => 'Шахсий сазламаларынъызны денъиштирмек ичюн <span class="plainlinks">[{{fullurl:Special:UserLogin|returnto=$1}} отурым ачмакъ]</span> керексинъиз.',
'prefsreset' => 'Сазламалар ильк алына кетирильди.',
'qbsettings' => 'Вызлы иришим сутун сазламалары',
'changepassword' => 'Пароль денъиштир',
'skin' => 'Ресимлеме',
'skin-preview' => 'Бакъып чыкъув',
'math' => 'Риязий (математик) ишаретлер',
'dateformat' => 'Тарих косьтерими',
'datedefault' => 'Стандарт',
'datetime' => 'Тарих ве саат',
'math_failure' => 'Айырыштырыламды',
'math_unknown_error' => 'билинмеген хата',
'math_unknown_function' => 'бельгисиз функция',
'math_lexing_error' => 'лексик хата',
'math_syntax_error' => 'синтаксис хатасы',
'prefs-personal' => 'Къулланыджы малюматы',
'prefs-rc' => 'Сонъки денъишикликлер',
'prefs-watchlist' => 'Козетюв джедвели',
'prefs-watchlist-days' => 'Козетюв джедвелинде косьтериледжек кунь сайысы:',
'prefs-watchlist-edits' => 'Кенишлетилген козетюв джедвелинде косьтериледжек денъишиклик сайысы:',
'prefs-misc' => 'Дигер сазламалар',
'prefs-resetpass' => 'Парольни денъиштир',
'saveprefs' => 'Денъишикликлерни сакъла',
'resetprefs' => 'Сакъланмагъан сазламаларны ильк алына кетир',
'restoreprefs' => 'Бутюн ог бельгиленген сазламаларны къайтар',
'textboxsize' => 'Саифе язув пенджереси',
'prefs-edit-boxsize' => 'Язув пенджересининъ ольчюлери.',
'rows' => 'Сатыр',
'columns' => 'Сутун',
'searchresultshead' => 'Къыдырув',
'resultsperpage' => 'Саифеде косьтериледжек тапылгъан саифе сайысы',
'contextlines' => 'Тапылгъан саифе ичюн айрылгъан сатыр сайысы',
'contextchars' => 'Сатырдаки ариф сайысы',
'recentchangesdays' => 'Сонъки денъишикликлер саифесинде косьтериледжек кунь сайысы:',
'recentchangescount' => 'Чешит-тюрлю джедвель ве журналларда косьтерильген денъишикликлер ог бельгиленген сайысы:',
'savedprefs' => 'Сазламаларынъыз сакъланды.',
'timezonelegend' => 'Саат къушагъы:',
'timezonetext' => 'Вики сервери (UTC/GMT) иле аранъыздаки саат фаркъы. (Украина ве Тюркие ичюн +02:00)',
'localtime' => 'Ерли вакъыт:',
'timezoneuseserverdefault' => 'Серверге коре олсун',
'timezoneuseoffset' => 'Башкъа (фракъны кирсетинъиз)',
'timezoneoffset' => 'Саат фаркъы¹:',
'servertime' => 'Сервернинъ сааты:',
'guesstimezone' => 'Браузеринъиз сизинъ еринъизге коре толдурсын',
'timezoneregion-africa' => 'Африка',
'timezoneregion-america' => 'Америка',
'timezoneregion-antarctica' => 'Антарктика',
'timezoneregion-arctic' => 'Арктика',
'timezoneregion-asia' => 'Асия',
'timezoneregion-atlantic' => 'Атлантик океан',
'timezoneregion-australia' => 'Австралия',
'timezoneregion-europe' => 'Авропа',
'timezoneregion-indian' => 'Инд океаны',
'timezoneregion-pacific' => 'Тынч океан',
'allowemail' => 'Дигер къулланыджылар манъа e-mail мектюплери ёллап олсун',
'prefs-searchoptions' => 'Къыдырув сазламалары',
'prefs-namespaces' => 'Исим фезалары',
'defaultns' => 'Къыдырувны ашагъыда сайлангъан исим фезаларында яп.',
'default' => 'оригинал',
'files' => 'Файллар',
# User rights
'userrights' => 'Къулланыджы акъларыны идаре этюв', # Not used as normal message but as header for the special page itself
'userrights-lookup-user' => 'Къулланыджы группаларныны идаре эт',
'userrights-user-editname' => 'Озь къулланыджы адынъызны язынъыз:',
'editusergroup' => 'Къулланыджы группалары низамла',
'editinguser' => "'''[[User:$1|$1]]''' къулланыджысынынъ ([[User talk:$1|{{int:talkpagelinktext}}]]{{int:pipe-separator}}[[Special:Contributions/$1|{{int:contribslink}}]]) изинлери денъиштирмектесинъиз",
'userrights-editusergroup' => 'Къулланыджы группалары низамла',
'userrights-groupsmember' => 'Азасы олгъан группаларынъыз:',
# Groups
'group' => 'Группа:',
'group-user' => 'Къулланыджылар',
'group-autoconfirmed' => 'Автоматик тасдыкълангъан къулланыджылар',
'group-bot' => 'Ботлар',
'group-sysop' => 'Идареджилер',
'group-bureaucrat' => 'Бюрократлар',
'group-suppress' => 'Тефтишчилер',
'group-all' => '(эписи)',
'group-user-member' => 'Къулланыджы',
'group-autoconfirmed-member' => 'Автоматик тасдыкълангъан къулланыджы',
'group-bot-member' => 'Бот',
'group-sysop-member' => 'Идареджи',
'group-bureaucrat-member' => 'Бюрократ',
'group-suppress-member' => 'Тефтишчи',
'grouppage-user' => '{{ns:project}}:Къулланыджылар',
'grouppage-autoconfirmed' => '{{ns:project}}:Автоматик тасдыкълангъан къулланыджылар',
'grouppage-bot' => '{{ns:project}}:Ботлар',
'grouppage-sysop' => '{{ns:project}}:Идареджилер',
'grouppage-bureaucrat' => '{{ns:project}}:Бюрократлар',
'grouppage-suppress' => '{{ns:project}}:Тефтишчилер',
# 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' => 'Сонъки денъишикликлер сазламалары',
'recentchangestext' => 'Япылгъан энъ сонъки денъишикликлерни бу саифеде корип оласынъыз.',
'recentchanges-feed-description' => 'Бу лента вастасынен викиде сонъки денъишикликлерни козет.',
'rcnote' => "$4 $5 тарихында сонъки {{PLURAL:$2|куньде|'''$2''' куньде}} япылгъан '''{{PLURAL:$1|1|$1}}''' денъишиклик:",
'rcnotefrom' => "'''$2''' тарихындан итибарен япылгъан денъишикликлер ашагъыдадыр (энъ чокъ '''$1''' дане саифе косьтериле).",
'rclistfrom' => '$1 тарихындан берли япылгъан денъишикликлерни косьтер',
'rcshowhideminor' => 'кичик денъишикликлерни $1',
'rcshowhidebots' => 'ботларны $1',
'rcshowhideliu' => 'къайдлы къулланыджыларны $1',
'rcshowhideanons' => 'аноним къулланыджыларны $1',
'rcshowhidepatr' => 'козетильген денъишикликлерни $1',
'rcshowhidemine' => 'меним денъишиклеримни $1',
'rclinks' => 'Сонъки $2 куньде япылгъан сонъки $1 денъишикликни косьтер;<br /> $3',
'diff' => 'фаркъ',
'hist' => 'кечмиш',
'hide' => 'гизле',
'show' => 'косьтер',
'minoreditletter' => 'к',
'newpageletter' => 'Я',
'boteditletter' => 'б',
'number_of_watching_users_pageview' => '[$1 {{PLURAL:$1|къулланыджы|къулланыджы}} козете]',
'rc_categories' => 'Тек категориялардан («|» иле айырыла)',
'rc_categories_any' => 'Эр анги',
'newsectionsummary' => '/* $1 */ янъы болюк',
'rc-enhanced-expand' => 'Тафсилятыны косьтер (JavaScript керек)',
'rc-enhanced-hide' => 'Тафсилятыны гизле',
# Recent changes linked
'recentchangeslinked' => 'Багълы денъишикликлер',
'recentchangeslinked-title' => '"$1" иле багълы денъишикликлер',
'recentchangeslinked-noresult' => 'Сайлангъан вакъытта багълы саифелерде ич денъишиклик ёкъ эди.',
'recentchangeslinked-summary' => "Бу махсус саифеде багълы саифелерде сонъки япкъан денъишикликлер джедвели мевджут. [[Special:Watchlist|Козетюв джедвелинъиз]]деки саифелер '''къалын''' оларакъ косьтериле.",
'recentchangeslinked-page' => 'Саифе ады:',
'recentchangeslinked-to' => 'Берильген саифе ерине берильген саифеге багъланты берген олгъан саифелерини косьтер',
# Upload
'upload' => 'Файл юкле',
'uploadbtn' => 'Файл юкле',
'reupload' => 'Янъыдан юкле',
'reuploaddesc' => 'Юклеме формасына кери къайт.',
'uploadnologin' => 'Отурым ачмадынъыз',
'uploadnologintext' => 'Файл юклеп олмакъ ичюн [[Special:UserLogin|отурым ачмакъ]] керексинъиз.',
'upload_directory_missing' => 'Юклемелер ичюн директория ($1) мевджут дегиль ве веб-сервер тарафындан япылып оламай.',
'upload_directory_read_only' => 'Web серверининъ ($1) джузьданына файллар сакъламагъа акълары ёкътыр.',
'uploaderror' => 'Юклеме хатасы',
'uploadtext' => "Файллар юклемек ичюн ашагъыдаки форманы къулланынъыз.
Эвельдже юкленген ресим тапмакъ я да бакъмакъ ичюн [[Special:FileList|юкленген файллар джедвелине]] кечинъиз, бундан гъайры файл юкленюв ве ёкъ этилюв къайдларыны [[Special:Log/upload|юкленюв журналында]] ве [[Special:Log/delete|ёкъ этилюв журналында]] тапып оласынъыз.
Саифеде ресим къулланмакъ ичюн бойле шекилли багълантылар къулланынъыз:
* '''<tt><nowiki>[[</nowiki>{{ns:file}}<nowiki>:File.jpg]]</nowiki></tt>''' файлнынъ там версиясыны къулланмакъ ичюн,
* '''<tt><nowiki>[[</nowiki>{{ns:file}}<nowiki>:File.png|200px|thumb|left|tarif]]</nowiki></tt>''' бир тариф иле 200 пиксель бир ресим къулланмакъ ичюн,
* '''<tt><nowiki>[[</nowiki>{{ns:media}}<nowiki>:File.ogg]]</nowiki></tt>''' файлгъа вастасыз багъланты ичюн.",
'upload-permitted' => 'Изинли файл чешитлери: $1.',
'upload-preferred' => 'Истенильген файл чешитлери: $1.',
'upload-prohibited' => 'Ясакълы файл чешитлери: $1.',
'uploadlog' => 'юклеме журналы',
'uploadlogpage' => 'Файл юклеме журналы',
'uploadlogpagetext' => 'Ашагъыда энъ сонъки къошулгъан файлларнынъ джедвели булуна.
Даа корьгезмели корюниш ичюн [[Special:NewFiles|янъы файллар галереясына]] бакъынъыз.',
'filename' => 'Файл',
'filedesc' => 'Файлгъа аит къыскъа тариф',
'fileuploadsummary' => 'Къыскъа тариф:',
'filereuploadsummary' => 'Файл денъишикликлери:',
'filestatus' => 'Таркъатув шартлары:',
'filesource' => 'Менба:',
'uploadedfiles' => 'Юкленген файллар',
'ignorewarning' => 'Тенбиге къулакъ асмайып файлны юкле.',
'ignorewarnings' => 'Тенбилерге къулакъ асма',
'minlength1' => 'Файлнынъ ады энъ аздан бир арифтен ибарет олмалы.',
'illegalfilename' => '"$1" файлынынъ адында серлева ичюн ясакълы ишаретлер бар. Лютфен, файл адыны денъиштирип янъыдан юклеп бакъынъыз.',
'badfilename' => 'Файл ады $1 оларакъ денъиштирильди.',
'filetype-badmime' => '"$1" MIME чешитиндеки файллар юклеме ясакълыдыр.',
'filetype-bad-ie-mime' => 'Бу файл юкленип оламаз, чюнки Internet Explorer оны "$1" яни рухсет берильмеген ве зарарлы ола бильген файл деп беллейджек.',
'filetype-unwanted-type' => "'''\".\$1\"''' — истенильмеген файл чешити.
Истенильген {{PLURAL:\$3|файл чешити|файл чешитлери}}: \$2.",
'filetype-banned-type' => "'''\".\$1\"''' — ясакълы файл чешити.
Истенильген {{PLURAL:\$3|файл чешити|файл чешитлери}}: \$2.",
'filetype-missing' => 'Файлнынъ ич бир узантысы ёкъ (меселя «.jpg», «.gif» ве илх.).',
'large-file' => 'Буюклиги $1 байттан зияде ибарет олмагъан ресимлер къулланув тевсие этиле (бу файлнынъ буюклиги $2 байт).',
'largefileserver' => 'Бу файлнынъ узунлыгъы серверде изин берильгенден буюкчедир.',
'emptyfile' => 'Ихтимал ки, юкленген файл бош.
Ихтималлы себеп - файл адландырув хатасыдыр.
Лютфен, тамам бу файлны юклемеге истейджек экенинъизни тешкеринъиз.',
'fileexists' => "Бу исимде бир файл энди бар.
Лютфен, эгер сиз денъиштирмектен эмин олмасанъыз башта '''<tt>[[:$1]]</tt>''' файлына козь ташланъыз.
[[$1|thumb]]",
'filepageexists' => "Бу файл ичюн тасвир саифеси энди япылгъан ('''<tt>[[:$1]]</tt>'''), лякин бу адда бир файл ёкътыр.
Язылгъан тасвиринъиз файл саифесинде косьтерильмейджек.
Тасвиринъиз анда косьтериледжеги ичюн, буны къолнен денъиштирмек керексинъиз.
[[$1|thumb]]",
'fileexists-extension' => "Бунъа ошагъан адда бир файл бар: [[$2|thumb]]
* Юкленген файлнынъ ады: '''<tt>[[:$1]]</tt>'''
* Мевджут олгъан файлнынъ ады: '''<tt>[[:$2]]</tt>'''
Лютфен, башкъа бир ад сайлап язынъыз.",
'fileexists-thumb' => "<center>'''Мевджут файл'''</center>",
'fileexists-thumbnail-yes' => "Бельки де бу файл бир уфакълаштырылгъан копиядыр (thumbnail). [[$1|thumb]]
Лютфен, '''<tt>[[:$1]]</tt>''' файлыны тешкеринъиз.
Эгер шу файл айны шу ресим олса, онынъ уфакълаштырылгъан копиясыны айры оларакъ юклемек аджети ёкътыр.",
'file-thumbnail-no' => "Файлнынъ ады '''<tt>$1</tt>'''нен башлана. Бельки де бу ресимнинъ уфакълаштырылгъан бир копиясыдыр ''(thumbnail)''.
Эгер сизде бу ресим там буюклигинде бар олса, лютфен, оны юкленъинъиз я да файлнынъ адыны денъиштиринъиз.",
'fileexists-forbidden' => 'Бу исимде бир файл энди бар, ве узерине языламай.
Файлынъызны янъыдан юклемеге истесенъиз, лютфен, кери къайтып янъы бир исим къулланынъыз.
[[File:$1|thumb|center|$1]]',
'fileexists-shared-forbidden' => 'Файллар умумий тутулгъан еринде бу исимде бир файл энди бар.
Эгер бу файлны эп бир юклемеге истесенъиз, кери къайтынъыз ве файл исмини денъиштирип янъыдан юкленъиз.
[[File:$1|thumb|center|$1]]',
'file-exists-duplicate' => 'Бу файл ашагъыдаки {{PLURAL:$1|файлнынъ|файлларнынъ}} дубликаты ола:',
'successfulupload' => 'Юкленюв беджерильди',
'uploadwarning' => 'Тенби',
'savefile' => 'Файлны сакъла',
'uploadedimage' => 'Юкленген: "[[$1]]"',
'overwroteimage' => '"[[$1]]" янъы версиясы юкленди',
'uploaddisabled' => 'Юклеме ясакълыдыр.',
'uploaddisabledtext' => 'Файл юклеме ясакълыдыр.',
'uploadscripted' => 'Бу файлда браузер тарафындан янълышнен ишленип олур HTML коду я да скрипт бар.',
'uploadcorrupt' => 'Бу файл я зарарланды, я да янълыш узантылы. Лютфен, файлны тешкерип янъыдан юклеп бакъынъыз.',
'uploadvirus' => 'Бу файл вируслыдыр! $1 бакъынъыз',
'sourcefilename' => 'Юклемеге истеген файлынъыз:',
'destfilename' => 'Файлнынъ истенильген ады:',
'upload-maxfilesize' => 'Азамий (максималь) файл буюклиги: $1',
'watchthisupload' => 'Бу файлны козет',
'filewasdeleted' => 'Бу исимде бир файл бар эди, амма ёкъ этильген эди. Лютфен, текрар юклемеден эвель $1 тешкеринъиз.',
'upload-wasdeleted' => "'''Дикъкъат: Эвельде ёкъ этильген файлны юклемектесинъиз.'''
Эр алда бу файлны юклемеге девам этмеге истейсинъизми?
Бу файл ичюн ёкъ этювнинъ журналыны мында бакъып оласынъыз:",
'filename-bad-prefix' => "Сиз юклеген файлнынъ ады '''\"\$1\"'''-нен башлана. Бу, адетиндже, ракъамлы фотоаппаратлардан файл адына язылгъан манасыз ишаретлердир. Лютфен, бу файл ичюн анълыджа бир ад сайлап язынъыз.",
'upload-proto-error' => 'Янълыш протокол',
'upload-proto-error-text' => 'Интернеттен бир ресим файлы юклемеге истесенъиз адрес <code>http://</code> я да <code>ftp://</code>нен башламалы.',
'upload-file-error' => 'Ички хата',
'upload-file-error-text' => 'Серверде мувакъкъат файл яратылгъан вакъытта ички хата чыкъты. Лютфен, [[Special:ListUsers/sysop|идареджиге]] мураджаат этинъиз.',
'upload-misc-error' => 'Бельгисиз юкленюв хатасы',
'upload-misc-error-text' => 'Бельгисиз юкленюв хатасы. Лютфен, адреснинъ догъру олгъаныны тешкерип текрарланъыз. Проблема девам этсе, [[Special:ListUsers/sysop|идареджиге]] мураджаат этинъиз.',
# Some likely curl errors. More could be added from <http://curl.haxx.se/libcurl/c/libcurl-errors.html>
'upload-curl-error6' => 'URL адресине иришилип оламады.',
'upload-curl-error6-text' => 'Бильдирильген URL адресине иришилип оламады. Лютфен, адреснинъ догъру олгъаны ве сайткъа иришмекнинъ чареси олгъаныны тешкеринъиз.',
'upload-curl-error28' => 'Юкленюв вакъты толды',
'upload-curl-error28-text' => 'Сайт чокътан джевап къайтармай. Лютфен, сайтнынъ догъру чалышкъаныны тешкерип бираздан сонъ текрарланъыз. Бельки де истеген арекетинъизни сонъ, сайт бошча олгъанда, этмек керектир.',
'license' => 'Лицензиялама:',
'nolicense' => 'Ёкъ',
'license-nopreview' => '(Бакъып чыкъув иришильмез)',
'upload_source_url' => ' (догъру, публик тарзда кирмеге мусаадели интернет адрес)',
'upload_source_file' => ' (компьютеринъиздеки файл)',
# Special:ListFiles
'listfiles-summary' => 'Бу махсус саифе бутюн юкленген файлларны косьтере.
Якъынларда юкленген файллар джедвельнинъ юкъарысында косьтериле.
Сутун серлевасына бир басув сортирлеменинъ тертибини денъиштирир.',
'listfiles_search_for' => 'Файл адыны къыдырув:',
'imgfile' => 'файл',
'listfiles' => 'Ресим джедвели',
'listfiles_date' => 'Тарих',
'listfiles_name' => 'Файл ады',
'listfiles_user' => 'Къулланыджы',
'listfiles_size' => 'Буюклик',
'listfiles_description' => 'Тасвир',
'listfiles_count' => 'Версиялар',
# File description page
'filehist' => 'Файлнынъ кечмиши',
'filehist-help' => 'Файлнынъ керекли аньки алыны корьмек ичюн тарихкъа/сааткъа басынъыз.',
'filehist-deleteall' => 'эписини ёкъ эт',
'filehist-deleteone' => 'ёкъ эт',
'filehist-revert' => 'кери ал',
'filehist-current' => 'шимдики',
'filehist-datetime' => 'Тарих ве саат',
'filehist-thumb' => 'Кичик ресим',
'filehist-nothumb' => 'Уфакълаштырылгъан ресим ёкъ',
'filehist-user' => 'Къулланыджы',
'filehist-dimensions' => 'Эн × бой',
'filehist-filesize' => 'Файл буюклиги',
'filehist-comment' => 'Изаат',
'imagelinks' => 'Файл багълантылары',
'linkstoimage' => 'Бу файлгъа багъланты олгъан {{PLURAL:$1|1|$1}} саифе:',
'nolinkstoimage' => 'Бу файлгъа багълангъан саифе ёкъ.',
'sharedupload' => 'Бу файл $1 сайтындан ве дигер лейхаларда да къулланылып ола.', # $1 is the repo name, $2 is shareduploadwiki(-desc)
'shareduploadwiki' => 'Тафсилятны $1 саифесинде тапмакъ мумкюн.',
'shareduploadwiki-linktext' => 'файл малюмат саифеси',
'noimage' => 'Бу исимде файл ёкъ, амма сиз $1.',
'noimage-linktext' => 'оны юклеп оласынъыз',
'uploadnewversion-linktext' => 'Файлнынъ янъысыны юкленъиз',
'shared-repo-from' => '$1нден', # $1 is the repository name
'shared-repo' => 'ортакъ тутулгъан ери', # used when shared-repo-NAME does not exist
# File reversion
'filerevert' => '$1 файлыны эски алына къайтар',
'filerevert-legend' => 'Файлны эски алына къайтар',
'filerevert-intro' => "'''[[Media:$1|$1]]''' файлынынъ [$4 $2, $3 тарихындаки версиясы]ны кери кетирмектесинъиз.",
'filerevert-comment' => 'Изаат:',
'filerevert-defaultcomment' => '$1, $2 тарихындаки версиягъа кери къайтарылды',
# MIME search
'mimesearch' => 'MIME къыдырувы',
'mimetype' => 'MIME чешити:',
'download' => 'юкле',
# Unwatched pages
'unwatchedpages' => 'Козетильмеген саифелер',
# List redirects
'listredirects' => 'Ёлламаларны джедвельге чек',
# Unused templates
'unusedtemplates' => 'Къулланылмагъан шаблонлар',
'unusedtemplatestext' => 'Бу саифе {{ns:template}} исим фезасында булунгъан ве дигер саифелерге кирсетильмеген шаблонларны косьтере. Шаблонларгъа олгъан дигер багълантыларны да тешкермеден ёкъ этменъиз.',
'unusedtemplateswlh' => 'дигер багълантылар',
# Random page
'randompage' => 'Тесадюфий саифе',
'randompage-nopages' => '"$1" исим фезасында ич бир саифе ёкъ.',
# Random redirect
'randomredirect' => 'Тесадюфий ёллама саифеси',
'randomredirect-nopages' => '"$1" исим фезасында ич бир ёллама саифеси ёкъ.',
# Statistics
'statistics' => 'Статистика',
'statistics-header-pages' => 'Саифе статистикасы',
'statistics-header-edits' => 'Денъиштирюв статистикасы',
'statistics-header-views' => 'Козьден кечирме статистикасы',
'statistics-header-users' => 'Къулланыджы статистикасы',
'statistics-mostpopular' => 'Энъ сыкъ бакъылгъан саифелер',
'disambiguations' => 'Чокъ маналы терминлер саифелери',
'disambiguationspage' => 'Template:disambig',
'disambiguations-text' => "Ашагъыдыки саифелер '''чокъ маналы саифелер'''ге багъланты ола.
Бельки де олар бир конкрет саифеге багъланты олмалы.<br />
Эгер саифеде, [[MediaWiki:Disambiguationspage]] саифесинде ады кечкен шаблон ерлештирильген олса, о саифе чокъ маналыдыр.",
'doubleredirects' => 'Ёлламагъа олгъан ёлламалар',
'doubleredirectstext' => 'Бу саифеде дигер ёллама саифелерине ёлланма олгъан саифелери косьтериле.
Эр сатырда биринджи ве экинджи ёлламагъа багълантылар да, экинджи ёлламанынъ макъсат саифеси (адетиндже о биринджи ёлламанынъ керекли макъсады ола) да бар.
<s>Устю сызылгъан</s> меселелер энди чезильген.',
'double-redirect-fixed-move' => '[[$1]] авуштырылды, шимди [[$2]] саифесине ёллап тура.',
'brokenredirects' => 'Бар олмагъан саифеге япылгъан ёлламалар',
'brokenredirectstext' => 'Ашагъыдаки ёлламалар бар олмагъан саифелерге багъланты берелер:',
'brokenredirects-edit' => '(денъиштир)',
'brokenredirects-delete' => '(ёкъ эт)',
'withoutinterwiki' => 'Дигер тиллердеки версияларгъа багълантылары олмагъан саифелер',
'withoutinterwiki-summary' => 'Бу саифелерде дигер тиллердеки версияларгъа багълантылар ёкъ:',
'withoutinterwiki-submit' => 'Косьтер',
'fewestrevisions' => 'Энъ аз денъиштирме япылгъан саифелер',
# Miscellaneous special pages
'nbytes' => '{{PLURAL:$1|1 байт|$1 байт}}',
'ncategories' => '{{PLURAL:$1|1 категория|$1 категория}}',
'nlinks' => '{{PLURAL:$1|1 багъланты|$1 багъланты}}',
'nmembers' => '{{PLURAL:$1|1 аза|$1 аза}}',
'nrevisions' => '{{PLURAL:$1|1 версия|$1 версия}}',
'nviews' => '{{PLURAL:$1|1 корюнюв|$1 корюнюв}}',
'specialpage-empty' => 'Бу соратма ичюн ич нетидже ёкъ.',
'lonelypages' => 'Озюне ич багъланты олмагъан саифелер',
'lonelypagestext' => 'Ашагъыдаки саифелерге {{SITENAME}} сайтындаки дигер саифелерден багъланты берильмеген, ондан да гъайры мезкюр саифелер дигер саиферлрге кирсетильмеген.',
'uncategorizedpages' => 'Эр анги бир категорияда олмагъан саифелер',
'uncategorizedcategories' => 'Эр анги бир категорияда олмагъан категориялар',
'uncategorizedimages' => 'Эр анги бир категорияда олмагъан ресимлер',
'uncategorizedtemplates' => 'Эр анги бир категорияда олмагъан шаблонлар',
'unusedcategories' => 'Къулланылмагъан категориялар',
'unusedimages' => 'Къулланылмагъан ресимлер',
'popularpages' => 'Популяр саифелер',
'wantedcategories' => 'Истенильген категориялар',
'wantedpages' => 'Истенильген саифелер',
'wantedfiles' => 'Истенильген файллар',
'wantedtemplates' => 'Истенильген шаблонлар',
'mostlinked' => 'Озюне энъ зияде багъланты берильген саифелер',
'mostlinkedcategories' => 'Энъ чокъ саифеге саип категориялар',
'mostlinkedtemplates' => 'Озюне энъ зияде багъланты берильген шаблонлар',
'mostcategories' => 'Энъ зияде категориягъа багълангъан саифелер',
'mostimages' => 'Энъ чокъ къулланылгъан ресимлер',
'mostrevisions' => 'Энъ чокъ денъишикликке огърагъан саифелер',
'prefixindex' => 'Префикснен бутюн саифелер',
'shortpages' => 'Къыскъа саифелер',
'longpages' => 'Узун саифелер',
'deadendpages' => 'Башкъа саифелерге багълантысы олмагъан саифелер',
'deadendpagestext' => 'Бу {{SITENAME}} башкъа саифелерине багълантысы олмагъан саифелердир.',
'protectedpages' => 'Къорчалангъан саифелер',
'protectedpagestext' => 'Бу саифелернинъ денъиштирювге къаршы къорчалавы бар',
'protectedtitles' => 'Ясакълангъан серлевалар',
'listusers' => 'Къулланыджылар джедвели',
'listusers-editsonly' => 'Тек денъишиклик япкъан къулланыджыларны косьтер',
'newpages' => 'Янъы саифелер',
'newpages-username' => 'Къулланыджы ады:',
'ancientpages' => 'Энъ эски саифелер',
'move' => 'Адыны денъиштир',
'movethispage' => 'Саифенинъ адыны денъиштир',
'pager-newer-n' => '{{PLURAL:$1|даа янъы 1|даа янъы $1}}',
'pager-older-n' => '{{PLURAL:$1|даа эски 1|даа эски $1}}',
# Book sources
'booksources' => 'Китаплар менбасы',
'booksources-search-legend' => 'Китаплар менбасыны къыдырув',
'booksources-go' => 'Къыдыр',
# Special:Log
'specialloguserlabel' => 'Къулланыджы:',
'speciallogtitlelabel' => 'Серлева:',
'log' => 'Журналлар',
'all-logs-page' => 'Бутюн умумий журналлар',
'logempty' => 'Журналда бир кельген малюмат ёкъ.',
'log-title-wildcard' => 'Бу ишаретлерден башлангъан серлеваларны къыдыр',
# Special:AllPages
'allpages' => 'Бутюн саифелер',
'alphaindexline' => '$1 саифесинден $2 саифесинедже',
'nextpage' => 'Сонъраки саифе ($1)',
'prevpage' => 'Эвельки саифе ($1)',
'allpagesfrom' => 'Джедвельге чекмеге башланыладжакъ арифлер:',
'allpagesto' => 'Шунынънен биткен саифелерни косьтер:',
'allarticles' => 'Бутюн саифелер',
'allinnamespace' => 'Бутюн саифелер ($1 саифелери)',
'allnotinnamespace' => 'Бутюн саифелер ($1 исим фезасында олмагъанлар)',
'allpagesprev' => 'Эвельки',
'allpagesnext' => 'Сонъраки',
'allpagessubmit' => 'Косьтер',
'allpagesprefix' => 'Язгъан арифлернен башлагъан саифелерни косьтер:',
'allpagesbadtitle' => 'Саифенинъ ады рухсетсиздир. Серлевада тиллер арасы префикси я да викилер арасы багъланты я да башкъа къулланылувы ясакъ олгъан ишаретлер бар.',
'allpages-bad-ns' => '{{SITENAME}} сайтында «$1» исим фезасы ёкътыр.',
# Special:Categories
'categories' => 'Саифе категориялары',
'categoriespagetext' => 'Ашагъыдаки категорияларда саифелер я да медиа-файллар бар.
Мында [[Special:UnusedCategories|къулланылмагъан категориялар]] косьтерильмеген.
[[Special:WantedCategories|Талап этильген категорияларнынъ джедвелини]] де бакъынъыз.',
'special-categories-sort-count' => 'сайыларына коре сырала',
'special-categories-sort-abc' => 'элифбе сырасынен сырала',
# Special:LinkSearch
'linksearch' => 'Тыш багълантылар',
# Special:ListUsers
'listusers-submit' => 'Косьтер',
'listusers-noresult' => 'Ич бир къулланыджы тапылмады.',
# Special:Log/newusers
'newuserlogpage' => 'Янъы къулланыджы журналы',
'newuserlogpagetext' => 'Энъ сонъки къайд олгъан къулланыджы журналы.',
'newuserlog-byemail' => 'пароль e-mail вастасынен йиберильген',
'newuserlog-create-entry' => 'Янъы къулланыджы',
'newuserlog-create2-entry' => 'янъы эсап яратты $1',
'newuserlog-autocreate-entry' => 'Эсап автоматик оларакъ яратылды',
# Special:ListGroupRights
'listgrouprights-members' => '(азалар джедвели)',
# E-mail user
'mailnologin' => 'Мектюп ёлланаджакъ адреси ёкътыр',
'mailnologintext' => 'Дигер къулланыджыларгъа электрон мектюплер ёллап олмакъ ичюн [[Special:UserLogin|отурым ачмалысынъыз]] ве [[Special:Preferences|сазламаларынъызда]] мевджут олгъан e-mail адресининъ саиби олмалысынъыз.',
'emailuser' => 'Къулланыджыгъа мектюп',
'emailpage' => 'Къулланыджыгъа электрон мектюп ёлла',
'emailpagetext' => 'Ашагъыдаки форманы толдурып бу къулланыджыгъа мектюп ёллап олурсынъыз.
[[Special:Preferences|Озь сазламаларынъызда]] язгъан электрон адресинъиз мектюпнинъ «Кимден» сатырында языладжакъ, бунынъ ичюн мектюп алыджы догърудан-догъру сизинъ адресинъизге джевап ёллап олур.',
'usermailererror' => 'E-mail беянаты ёллангъан вакъытта хата олып чыкъты',
'defemailsubject' => '{{SITENAME}} e-mail',
'noemailtitle' => 'E-mail адреси ёкътыр',
'noemailtext' => 'Бу къулланыджы уйгъун электрон почта адресини бильдирмеген.',
'emailfrom' => 'Кимден:',
'emailto' => 'Кимге:',
'emailsubject' => 'Мектюп мевзусы:',
'emailmessage' => 'Мектюп:',
'emailsend' => 'Ёлла',
'emailccme' => 'Мектюбимнинъ бир копиясыны манъа да ёлла.',
'emailccsubject' => '$1 къулланыджысына ёллангъан мектюбинъизнинъ копиясы: $2',
'emailsent' => 'Мектюп ёлланды',
'emailsenttext' => 'Сизинъ e-mail беянатынъыз ёлланды',
'emailuserfooter' => 'Бу мектюп $1 тарафындан $2 къулланыджысына, {{SITENAME}} сайтындаки "Къулланыджыгъа e-mail ёлла" функциясынен ёллангъан.',
# Watchlist
'watchlist' => 'Козетюв джедвели',
'mywatchlist' => 'Козетюв джедвелим',
'watchlistfor' => "('''$1''' ичюн)",
'nowatchlist' => 'Сизинъ козетюв джедвелинъиз боштыр.',
'watchlistanontext' => 'Козетюв джедвелини бакъмакъ я да денъиштирмек ичюн $1 борджлусынъыз.',
'watchnologin' => 'Отурым ачмакъ керек',
'watchnologintext' => 'Озь козетюв джедвелинъизни денъиштирмек ичюн [[Special:UserLogin|отурым ачынъыз]]',
'addedwatch' => 'Козетюв джедвелине кирсетмек',
'addedwatchtext' => '"[[:$1]]" саифеси [[Special:Watchlist|козетюв джевделинъизге]] кирсетильди.
Бу саифедеки ве онынънен багълы саифелердеки оладжакъ денъишикликлер бу джедвельде бельгиленеджек, эм де олар козьге чарпмасы ичюн [[Special:RecentChanges|янъы денъишиклик джедвели]] булунгъан саифеде къалын оларакъ косьтерилир.
Бираздан сонъ козетюв джедвелинъизден бир де бир саифени ёкъ этмеге истесенъиз де, саифенинъ юкъарысындаки сол тарафта "козетме" дёгмесине басынъыз.',
'removedwatch' => 'Козетюв джедвелинден ёкъ эт',
'removedwatchtext' => '"[[:$1]]" саифеси [[Special:Watchlist|козетюв джедвелинъизден]] ёкъ этильди.',
'watch' => 'Козет',
'watchthispage' => 'Бу саифени козет',
'unwatch' => 'Козетме',
'unwatchthispage' => 'Бу саифени козетме',
'notanarticle' => 'Малюмат саифеси дегиль',
'watchnochange' => 'Косьтерильген заман аралыгъында козетюв джедвелинъиздеки саифелернинъ ич бири денъиштирильмеген.',
'watchlist-details' => 'Музакере саифелерини эсапкъа алмайып, козетюв джедвелинъизде {{PLURAL:$1|1|$1}} саифе бар.',
'wlheader-enotif' => '* E-mail иле хабер берюв ачылды.',
'wlheader-showupdated' => "* Сонъки зияретинъизден сонъраки саифе денъишикликлери '''къалын''' оларакъ косьтерильди.",
'watchmethod-recent' => 'сонъки денъишикликлер арасында козеткен саифелеринъиз къыдырыла',
'watchmethod-list' => 'козетюв джедвелиндеки саифелер тешкериле',
'watchlistcontains' => 'Сизинъ козетюв джедвелинъизде {{PLURAL:$1|1|$1}} саифе бар.',
'iteminvalidname' => '"$1" саифеси мунасебетинен проблема олып чыкъты, эльверишли олмагъан исимдир…',
'wlnote' => "Ашагъыда сонъки {{PLURAL:$2|саат|'''$2''' саат}} ичинде япылгъан сонъки {{PLURAL:$1|денъишиклик|'''$1''' денъишиклик}} косьтериле.",
'wlshowlast' => 'Сонъки $1 саат ичюн, $2 кунь ичюн я да $3 косьтер',
'watchlist-options' => 'Козетюв джедвели сазламалары',
# Displayed when you click the "watch" button and it is in the process of watching
'watching' => 'Козетюв джедвелине кирсетильмекте...',
'unwatching' => 'Козетюв джедвелинден ёкъ этильмекте...',
'enotif_mailer' => '{{SITENAME}} почта вастасынен хабер берген хызмет',
'enotif_reset' => 'Джумле саифелерни бакъылгъан оларакъ ишаретле',
'enotif_newpagetext' => 'Бу янъы бир саифедир.',
'enotif_impersonal_salutation' => '{{SITENAME}} къулланыджысы',
'changed' => 'денъиштирильди',
'created' => 'яратылды',
'enotif_subject' => '«{{SITENAME}}» $PAGETITLE саифеси $PAGEEDITOR къулланыджы тарафындан $CHANGEDORCREATED',
'enotif_lastvisited' => 'Сонъки зияретинъизден берли япылгъан денъишикликлерни бильмек ичюн $1 бакъынъыз.',
'enotif_anon_editor' => 'адсыз (аноним) къулланыджы $1',
'enotif_body' => 'Сайгъылы $WATCHINGUSERNAME,
{{SITENAME}} сайтындаки $PAGETITLE серлевалы саифе $PAGEEDITDATE тарихында $PAGEEDITOR тарафындан $CHANGEDORCREATED. Шимдики версиягъа $PAGETITLE_URL адресинден етишип оласынъыз.
$NEWPAGE
Ачыкъламасы: $PAGESUMMARY $PAGEMINOREDIT
Саифени денъиштирген къулланыджынынъ иришим малюматы:
e-mail: $PAGEEDITOR_EMAIL
Вики: $PAGEEDITOR_WIKI
Бахсы кечкен саифени сиз зиярет этмеген муддет ичинде саифенен багълы башкъа денъишиклик тенбиси ёлланмайджакъ. Тенби сазламаларыны козетюв джедвелинъиздеки бутюн саифелер ичюн денъиштирип олурсынъыз.
{{SITENAME}} тенби системасы.
--
Сазламаларны денъиштирмек ичюн:
{{fullurl:Special:Watchlist/edit}}
Ярдым ве теклифлер ичюн:
{{fullurl:Help:Contents}}',
# Delete
'deletepage' => 'Саифени ёкъ эт',
'confirm' => 'Тасдыкъла',
'excontent' => "эски метин: '$1'",
'excontentauthor' => "эски метин: '$1' ('$2' иссе къошкъан тек бир къулланыджы)",
'exbeforeblank' => "Ёкъ этильмеген эвельки метин: '$1'",
'exblank' => 'саифе метини бош',
'delete-confirm' => '«$1» саифесини ёкъ этмектесинъиз',
'delete-legend' => 'Ёкъ этюв',
'historywarning' => 'Тенби: Сиз ёкъ этмек узьре олгъан саифенинъ кечмиши бардыр:',
'confirmdeletetext' => 'Бир саифени я да ресимни бутюн кечмиши иле бирликте малюмат базасындан къалыджы оларакъ ёкъ этмек узьресинъиз.
Лютфен, нетиджелерини анълагъанынъызны ве [[{{MediaWiki:Policy-url}}|ёкъ этюв политикасына]] уйгъунлыгъыны дикъкъаткъа алып, буны япмагъа истегенинъизни тасдыкъланъыз.',
'actioncomplete' => 'Арекет тамамланды.',
'deletedtext' => '"<nowiki>$1</nowiki>" ёкъ этильди.
якъын заманда ёкъ этильгенлерни корьмек ичюн: $2.',
'deletedarticle' => '"[[$1]]" ёкъ этильди',
'dellogpage' => 'Ёкъ этюв журналы',
'dellogpagetext' => 'Ашагъыдаки джедвель сонъки ёкъ этюв журналыдыр.',
'deletionlog' => 'ёкъ этюв журналы',
'reverted' => 'Эвельки версия кери кетирильди',
'deletecomment' => 'Ёкъ этюв себеби',
'deleteotherreason' => 'Дигер/илявели себеп:',
'deletereasonotherlist' => 'Дигер себеп',
# Rollback
'rollback' => 'денъишикликлерни кери ал',
'rollback_short' => 'кери ал',
'rollbacklink' => 'эски алына кетир',
'rollbackfailed' => 'кери алув мувафакъиетсиз',
'cantrollback' => 'Денъишикликлер кери алынамай, сонъки денъиштирген киши саифенинъ тек бир муэллифидир',
'editcomment' => "Денъиштирме изааты: \"''\$1''\" эди.", # only shown if there is an edit comment
'revertpage' => '[[Special:Contributions/$2|$2]] ([[User talk:$2|музакере]]) тарафындан япылгъан денъишикликлер кери алынып, [[User:$1|$1]] тарафындан денъиштирильген эвельки версия кери кетирильди.', # Additionally available: $3: revid of the revision reverted to, $4: timestamp of the revision reverted to, $5: revid of the revision reverted from, $6: timestamp of the revision reverted from
# Protect
'protectlogpage' => 'Къорчалав журналы',
'protectlogtext' => 'Къорчалавгъа алув/чыкъарув иле багълы денъишикликлер журналыны корьмектесинъиз.
Къорчалав алтына алынгъан саифелер там джедвели [[Special:ProtectedPages|бу саифеде]] корип оласынъыз.',
'protectedarticle' => '"[[$1]]" къорчалав алтына алынды',
'modifiedarticleprotection' => '«[[$1]]» ичюн къорчалав севиеси денъиштирильди',
'unprotectedarticle' => 'къорчалав чыкъарлыды: "[[$1]]"',
'prot_1movedto2' => '"[[$1]]" саифесининъ ады "[[$2]]" оларакъ денъиштирильди',
'protect-legend' => 'Къорчалавны тасдыкъла',
'protectcomment' => 'Себеп:',
'protectexpiry' => 'Битиш тарихы:',
'protect_expiry_invalid' => 'Битиш тарихы янълыш.',
'protect_expiry_old' => 'Битиш заманы кечмиштедир.',
'protect-unchain' => 'Саифе ады денъиштирюв килитини чыкъар',
'protect-text' => "'''[[<nowiki>$1</nowiki>]]''' саифесининъ къорчалав севиесини мындан корип олур ве денъиштирип оласынъыз.",
'protect-locked-access' => "Къулланыджы эсабынъыз саифенинъ къорчалав севиелерини денъиштирме еткисине саип дегиль. '''$1''' саифесининъ шимдики сазламалары шуларыдыр:",
'protect-cascadeon' => 'Бу саифе шимди къорчалав алтындадыр, чюнки ашагъыда джедвелленген ве каскадлы къорчалав алтындаки {{PLURAL:$1|1|$1}} саифеде къулланыла.
Бу саифенинъ къорчалав севиесини денъиштирип оласынъыз, амма каскадлы къорчалав тесир этильмейджек.',
'protect-default' => 'Бутюн къулланыджыларгъа рухсет бер',
'protect-fallback' => '«$1» изни керектир',
'protect-level-autoconfirmed' => 'Къайдсыз ве янъы къулланыджыларны блок эт',
'protect-level-sysop' => 'тек идареджилер',
'protect-summary-cascade' => 'каскадлы',
'protect-expiring' => 'бите: $1 (UTC)',
'protect-cascade' => 'Бу саифеде къулланылгъан бутюн саифелерни къорчалавгъа ал (каскадлы къорчалав)',
'protect-cantedit' => 'Бу саифенинъ къорчалав севиесини денъиштирип оламазсынъыз, чюнки буны япмагъа еткинъиз ёкъ.',
'protect-expiry-options' => '1 саат:1 hours,1 кунь:1 day,1 афта:1 week,2 афта:2 weeks,1 ай:1 month,3 ай:3 months,6 ай:6 months,1 йыл:1 year,муддетсиз:infinite', # display1:time1,display2:time2,...
'restriction-type' => 'Рухсети:',
'restriction-level' => 'Рухсет севиеси:',
'minimum-size' => 'Асгъарий (минималь) буюклик',
'maximum-size' => 'Азамий (максималь) буюклик:',
'pagesize' => '(байт)',
# Restrictions (nouns)
'restriction-edit' => 'Денъиштир',
'restriction-move' => 'Адыны денъиштир',
# Restriction levels
'restriction-level-sysop' => 'къорчалав алтында',
'restriction-level-autoconfirmed' => 'къысмен къорчалав алтында',
# Undelete
'undelete' => 'Ёкъ этильген саифелерни косьтер',
'undeletepage' => 'Саифенинъ ёкъ этильген версияларына козь ат ве кери кетир.',
'viewdeletedpage' => 'Ёкъ этильген саифелерге бакъ',
'undeletebtn' => 'Кери кетир!',
'undeletelink' => 'косьтер/кери кетир',
'undeletereset' => 'Вазгеч',
'undeletecomment' => 'Изаат:',
'undeletedarticle' => '"[[$1]]" кери кетирильди.',
'undeletedrevisions' => 'Топлам {{PLURAL:$1|1 къайд|$1 къайд}} кери кетирильди.',
'undelete-header' => 'Кеченлерде ёкъ этильген саифелерни корьмек ичюн [[Special:Log/delete|ёкъ этюв журналына]] бакъынъыз.',
# Namespace form on various pages
'namespace' => 'Исим фезасы:',
'invert' => 'Сайлангъан тышындакилерни сайла',
'blanknamespace' => '(Эсас)',
# Contributions
'contributions' => 'Къулланыджынынъ исселери',
'contributions-title' => '$1 къулланыджысынынъ исселери',
'mycontris' => 'Исселерим',
'contribsub2' => '$1 ($2)',
'nocontribs' => 'Бу критерийлерге уйгъан денъишиклик тапыламады', # Optional parameter: $1 is the user name
'uctop' => '(сонъки)',
'month' => 'Бу ай (ве ондан эрте):',
'year' => 'Бу сене (ве ондан эрте):',
'sp-contributions-newbies' => 'Тек янъы къулланыджыларнынъ исселерини косьтер',
'sp-contributions-newbies-sub' => 'Янъы къулланыджылар ичюн',
'sp-contributions-blocklog' => 'Блок этюв журналы',
'sp-contributions-search' => 'Исселерни къыдырув',
'sp-contributions-username' => 'IP адреси я да къулланыджы ады:',
'sp-contributions-submit' => 'Къыдыр',
# What links here
'whatlinkshere' => 'Бу саифеге багълантылар',
'whatlinkshere-title' => '$1 саифесине багъланты олгъан саифелер',
'whatlinkshere-page' => 'Саифе:',
'linkshere' => "Бу саифелер '''[[:$1]]''' саифесине багълантысы олгъан:",
'nolinkshere' => "'''[[:$1]]''' саифесине багълангъан саифе ёкъ.",
'nolinkshere-ns' => "Сайлангъан исим фезасында '''[[:$1]]''' саифесине багълангъан саифе ёкътыр.",
'isredirect' => 'Ёллама саифеси',
'istemplate' => 'кирсетильме',
'isimage' => 'ресим багълантысы',
'whatlinkshere-prev' => '{{PLURAL:$1|эвельки|эвельки $1}}',
'whatlinkshere-next' => '{{PLURAL:$1|сонъраки|сонъраки $1}}',
'whatlinkshere-links' => '← багълантылар',
'whatlinkshere-hideredirs' => 'ёлламаларны $1',
'whatlinkshere-hidetrans' => 'чапраз къошмаларны $1',
'whatlinkshere-hidelinks' => 'багълантыларны $1',
'whatlinkshere-filters' => 'Сюзгючлер',
# Block/unblock
'blockip' => 'Бу IP адресинден иришимни блок эт',
'blockip-legend' => 'Къулланыджыны блок эт',
'blockiptext' => 'Ашагъыдаки форманы къулланып белли бир IP адресининъ я да къулланыджынынъ иришимини блок этип оласынъыз. Бу тек вандализмни блок этмек ичюн ве [[{{MediaWiki:Policy-url}}|къаиделерге]] уйгъун оларакъ япылмалы. Ашагъыгъа мытлакъа блок этюв иле багълы бир изаат язынъыз. (меселя: Шу саифелерде вандализм япты).',
'ipaddress' => 'IP адреси',
'ipadressorusername' => 'IP адреси я да къулланыджы ады',
'ipbexpiry' => 'Битиш муддети',
'ipbreason' => 'Себеп',
'ipbsubmit' => 'Бу къулланыджыны блок эт',
'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', # display1:time1,display2:time2,...
'ipbotheroption' => 'фаркълы',
'ipbotherreason' => 'Дигер/илявели себеп:',
'badipaddress' => 'Янълыш IP адреси',
'blockipsuccesssub' => 'Блок этме мувафакъиетнен япылды',
'blockipsuccesstext' => '[[Special:Contributions/$1|$1]] блок этильди.<br />
Блок этмелерни козьден кечирмек ичюн [[Special:IPBlockList|IP адреси блок этильгенлер]] джедвелине бакъынъыз.',
'unblockip' => 'Къулланыджынынъ блок этмесини чыкъар',
'ipusubmit' => 'Бу блок этмени чыкъар',
'ipblocklist' => 'Блок этильген къулланыджылар ве IP адреслери',
'blocklistline' => '$1, $2 блок этти: $3 ($4)',
'infiniteblock' => 'муддетсиз',
'expiringblock' => '$1 тарихында битеджек',
'blocklink' => 'блок эт',
'unblocklink' => 'блок этмесини чыкъар',
'change-blocklink' => 'блок этювни денъиштир',
'contribslink' => 'Исселер',
'autoblocker' => 'Автоматик оларакъ блок этильдинъиз чюнки кеченлерде IP адресинъиз "[[User:$1|$1]]" къулланыджысы тарафындан къулланылды. $1 адлы къулланыджынынъ блок этилюви ичюн бильдирильген себеп: "\'\'\'$2\'\'\'"',
'blocklogpage' => 'Блок этюв журналы',
'blocklogentry' => '"[[$1]]" иришими $2 $3 токътатылды. Себеп',
'blocklogtext' => 'Мында къулланыджы иришимине ёнелик блок этюв ве блок чыкъарув къайдлары косьтериле. Автоматик IP адреси блок этювлери джедвельге кирсетильмеди. Шимди иришими токътатылгъан къулланыджыларны [[Special:IPBlockList|IP блок этюв джедвели]] саифесинден корип оласынъыз.',
'unblocklogentry' => '$1 къулланыджысынынъ блок этмеси чыкъарылды',
'block-log-flags-nocreate' => 'янъы эсап ачмакъ ясакъ этильди',
'block-log-flags-noemail' => 'e-mail блок этильди',
'ipb_expiry_invalid' => 'Янълыш битиш заманы.',
'ipb_already_blocked' => '"$1" энди блок этильди',
'ip_range_invalid' => 'Рухсетсиз IP аралыгъы.',
# Developer tools
'lockdb' => 'Малюмат базасы килитли',
'lockbtn' => 'Малюмат базасы килитли',
# Move page
'move-page' => '$1 саифесининъ адыны денъиштирмектесинъиз',
'move-page-legend' => 'Ад денъишиклиги',
'movepagetext' => "Ашагъыдаки форманы къулланып саифенинъ адыны денъиштирилир. Бунынънен берабер денъишиклик журналы да янъы адгъа авуштырылыр.
Эски ад янъы адгъа ёллама олур. Эски серлевагъа ёллама саифелерни автоматик оларакъ янъартып оласынъыз. Бу ишлеми автоматик япмагъа истемесенъиз, бутюн [[Special:DoubleRedirects|чифт]] ве [[Special:BrokenRedirects|йыртыкъ]] ёллама саифелерини озюнъиз тюзетмеге меджбур олурсынъыз. Багълантылар эндиден берли догъру чалышмасындан эмин олмалысынъыз.
Янъы адда бир ад энди бар олса, ад денъишиклиги '''япылмайджакъ''', анджакъ мевджут олгъан саифе ёллама я да бош олса ад денъишиклиги мумкюн оладжакъ. Бу демек ки, саифе адыны янълыштан денъиштирген олсанъыз деминки адыны кери къайтарып оласынъыз, амма мевджут олгъан саифени тесадюфен ёкъ эталмайсынъыз.
'''ТЕНБИ!'''
Ад денъиштирюв популяр саифелер ичюн буюк денъишмелерге себеп ола билир. Лютфен, денъишикликни япмадан эвель ола биледжеклерни козь огюне алынъыз.",
'movepagetalktext' => "Къошулгъан музакере саифесининъ де (бар олса)
ады автоматик тарзда денъиштириледжек. '''Мустесналар:'''
* Айны бу адда бош олмагъан бир музакере саифеси энди бар;
* Ашагъыдаки бошлукъкъа ишарет къоймадынъыз.
Бойле алларда, керек олса, саифелерни къолнен ташымагъа я да бирлештирмеге меджбур олурсынъыз.",
'movearticle' => 'Эски ад',
'movenologin' => 'Отурым ачмадынъыз',
'movenologintext' => 'Саифенинъ адыны денъиштирип олмакъ ичюн [[Special:UserLogin|отурым ачынъыз]].',
'movenotallowed' => 'Саифелер адларыны денъиштирмеге изининъиз ёкъ.',
'newtitle' => 'Янъы ад',
'move-watch' => 'Бу саифени козет',
'movepagebtn' => 'Адыны денъиштир',
'pagemovedsub' => 'Ад денъишиклиги тамамланды',
'movepage-moved' => "'''«$1» саифесининъ ады «$2» оларакъ денъиштирильди'''", # The two titles are passed in plain text as $3 and $4 to allow additional goodies in the message.
'movepage-moved-redirect' => 'Бир ёллама яратылды.',
'movepage-moved-noredirect' => 'Ёллама яратылувы бастырылды.',
'articleexists' => 'Бу адда бир саифе энди бар я да сиз язгъан ад ясакълы.
Лютфен, башкъа бир ад сайлап язынъыз.',
'cantmove-titleprotected' => 'Сиз язгъан янъы ад ясакълыдыр, бунынъ ичюн саифе адыны денъиштирмекнинъ чареси ёкъ.',
'talkexists' => "'''Саифенинъ ады денъиштирильди, амма музакере саифесининъ адыны денъиштирмеге мумкюнлик ёкътыр, чюнки айны бу адда бир саифе энди бар. Лютфен, буларны къолнен бирлештиринъиз.'''",
'movedto' => 'ады денъиштирильди:',
'movetalk' => 'Музакере саифесининъ адыны денъиштир.',
'move-subpages' => 'Алт саифелернинъ адларыны да денъиштир ($1 саифеге къадар)',
'move-talk-subpages' => 'Muzakere saifesi alt saifeleriniñ adlarını da deñiştir ($1 saifege qadar)',
'movepage-page-exists' => '$1 саифеси энди бар, ве автоматик оларакъ янъыдан язылып оламаз.',
'movepage-page-moved' => '$1 саифесининъ ады $2 оларакъ денъиштирильди.',
'movepage-page-unmoved' => '$1 саифесининъ ады $2 оларакъ денъиштирилип оламай.',
'1movedto2' => '"[[$1]]" саифесининъ ады "[[$2]]" оларакъ денъиштирильди',
'1movedto2_redir' => '[[$1]] серлевасы [[$2]] саифесине ёлланды',
'move-redirect-suppressed' => 'ёллама бастырылгъан',
'movelogpage' => 'Ад денъишиклиги журналы',
'movelogpagetext' => 'Ашагъыда булунгъан джедвель ады денъиштирильген саифелерни косьтере',
'movesubpage' => '{{PLURAL:$1|Алт саифе|Алт саифелер}}',
'movesubpagetext' => 'Бу саифенинъ ашагъыда косьтерильген $1 {{PLURAL:$1|алт саифеси|алт саифеси}} бар.',
'movenosubpage' => 'Бу саифенинъ алт саифеси ёкъ.',
'movereason' => 'Себеп',
'revertmove' => 'Кериге ал',
'delete_and_move' => 'Ёкъ эт ве адыны денъиштир',
'delete_and_move_text' => '==Ёкъ этмек лязимдир==
«[[:$1]]» саифеси энди бар. Адыны денъиштирип олмакъ ичюн оны ёкъ этмеге истейсинъизми?',
'delete_and_move_confirm' => 'Эбет, бу саифени ёкъ эт',
'delete_and_move_reason' => 'Исим денъиштирип олмакъ ичюн ёкъ этильди',
'selfmove' => 'Бу саифенинъ адыны денъиштирмеге имкян ёкътыр, чюнки асыл иле янъы адлары бир келе.',
'move-leave-redirect' => 'Аркъада бир ёллама ташла',
# Export
'export' => 'Саифелерни экспорт эт',
# Namespace 8 related
'allmessages' => 'Система беянатлары',
'allmessagesname' => 'Исим',
'allmessagesdefault' => 'Оригиналь метин',
'allmessagescurrent' => 'Шимди къулланылгъан метин',
'allmessagestext' => 'Ишбу джедвель MediaWiki-де мевджут олгъан бутюн система беянатларынынъ джедвелидир.
MediaWiki интерфейсининъ чешит тиллерге терджиме этювде иштирак этмеге истесенъиз [http://www.mediawiki.org/wiki/Localisation MediaWiki Localisation] ве [http://translatewiki.net translatewiki.net] саифелерине зиярет этинъиз.',
'allmessagesfilter' => 'Метин айрыштырыджы фильтры:',
'allmessagesmodified' => 'Тек денъиштирильгенлерни косьтер',
# Thumbnails
'thumbnail-more' => 'Буют',
'filemissing' => 'Файл тапылмады',
'thumbnail_error' => 'Кичик ресим (thumbnail) яратылгъанда бир хата чыкъты: $1',
'thumbnail_invalid_params' => 'Янълыш кичик ресим параметрлери',
'thumbnail_dest_directory' => 'Истенильген директорияны яратмакънынъ ич чареси ёкъ',
# Special:Import
'import-comment' => 'Изаат:',
# Import log
'importlogpage' => 'Импорт журналы',
# Tooltip help for the actions
'tooltip-pt-userpage' => 'Сизинъ къулланыджы саифенъиз',
'tooltip-pt-anonuserpage' => 'IP адресим ичюн къулланыджы саифеси',
'tooltip-pt-mytalk' => 'Сизинъ музакере саифенъиз',
'tooltip-pt-anontalk' => 'Бу IP адресинден япылгъан денъишикликлерни музакере этюв',
'tooltip-pt-preferences' => 'Сазламаларынъыз (настройкаларынъыз)',
'tooltip-pt-watchlist' => 'Козетювге алгъан саифелеринъиз',
'tooltip-pt-mycontris' => 'Къошкъан исселеринъизнинъ джедвели',
'tooltip-pt-login' => 'Отурым ачманъыз тевсие олуныр амма меджбур дегильсинъиз.',
'tooltip-pt-anonlogin' => 'Отурым ачманъыз тевсие олуныр амма меджбур дегильсинъиз.',
'tooltip-pt-logout' => 'Системадан чыкъув',
'tooltip-ca-talk' => 'Саифедеки малюматнен багълы музакере',
'tooltip-ca-edit' => 'Бу саифени денъиштирип оласынъыз. Сакъламаздан эвель бакъып чыкъмагъа унутманъыз.',
'tooltip-ca-addsection' => 'Янъы болюкни ачув',
'tooltip-ca-viewsource' => 'Бу саифе къорчалав алтында. Менба кодуны тек корип оласынъыз, денъиштирип оламайсынъыз.',
'tooltip-ca-history' => 'Бу саифенинъ кечмиш версиялары.',
'tooltip-ca-protect' => 'Бу саифени къорчалав',
'tooltip-ca-delete' => 'Бу саифени ёкъ этюв',
'tooltip-ca-undelete' => 'Саифени ёкъ этильмезден эвельки алына кери кетиринъиз',
'tooltip-ca-move' => 'Саифенинъ адыны денъиштирюв',
'tooltip-ca-watch' => 'Бу саифени козетюв джедвелине алув',
'tooltip-ca-unwatch' => 'Бу саифени козетювни ташлав',
'tooltip-search' => '{{SITENAME}} сайтында къыдырув',
'tooltip-search-go' => 'Бу адда саифе мевджут олса, онъа бар',
'tooltip-search-fulltext' => 'Бу метини олгъан саифелер къыдыр',
'tooltip-p-logo' => 'Баш саифе',
'tooltip-n-mainpage' => 'Баш саифеге барув',
'tooltip-n-portal' => 'Лейха узерине, не къайдадыр, нени япып оласынъыз',
'tooltip-n-currentevents' => 'Агъымдаки вакъиаларнен багълы сонъки малюмат',
'tooltip-n-recentchanges' => 'Викиде япылгъан сонъки денъишикликлернинъ джедвели.',
'tooltip-n-randompage' => 'Тесадюфий бир саифени косьтерюв',
'tooltip-n-help' => 'Ярдым болюги',
'tooltip-t-whatlinkshere' => 'Бу саифеге багъланты берген дигер вики саифелерининъ джедвели',
'tooltip-t-recentchangeslinked' => 'Бу саифеге багъланты берген саифелердеки сонъки денъишикликлер',
'tooltip-feed-rss' => 'Бу саифе ичюн RSS трансляциясы',
'tooltip-feed-atom' => 'Бу саифе ичюн atom трансляциясы',
'tooltip-t-contributions' => 'Къулланыджынынъ иссе джедвелине бакъув',
'tooltip-t-emailuser' => 'Къулланыджыгъа e-mail мектюбини ёлла',
'tooltip-t-upload' => 'Системагъа ресим я да медиа файлларны юкленъиз',
'tooltip-t-specialpages' => 'Бутюн махсус саифелернинъ джедвелини косьтер',
'tooltip-t-print' => 'Бу саифенинъ басылмагъа уйгъун корюниши',
'tooltip-t-permalink' => 'Бу саифенинъ версиясына даимий багъланты',
'tooltip-ca-nstab-main' => 'Саифени косьтер',
'tooltip-ca-nstab-user' => 'Къулланыджы саифесини косьтер',
'tooltip-ca-nstab-media' => 'Медиа саифесини косьтер',
'tooltip-ca-nstab-special' => 'Бу махсус саифе олгъаны ичюн денъишиклик япамазсынъыз.',
'tooltip-ca-nstab-project' => 'Лейха саифесини косьтер',
'tooltip-ca-nstab-image' => 'Ресим саифесини косьтер',
'tooltip-ca-nstab-mediawiki' => 'Система беянатыны косьтер',
'tooltip-ca-nstab-template' => 'Шаблонны косьтер',
'tooltip-ca-nstab-help' => 'Ярдым саифесини косьтер',
'tooltip-ca-nstab-category' => 'Категория саифесини косьтер',
'tooltip-minoredit' => 'Бу кичик бир денъишиклик деп бельгиле',
'tooltip-save' => 'Денъишикликлерни сакъла',
'tooltip-preview' => 'Бакъып чыкъув. Сакъламаздан эвель бу хусусиетни къулланып денъишикликлеринъизни бакъып чыкъынъыз!',
'tooltip-diff' => 'Метинге сиз япкъан денъишикликлерни косьтерир.',
'tooltip-compareselectedversions' => 'Сайлангъан эки версия арасындаки фаркъларны косьтер.',
'tooltip-watch' => 'Саифени козетюв джедвелине кирсет',
'tooltip-recreate' => 'Ёкъ этильген олмасына бакъмадан саифени янъыдан янъарт',
'tooltip-upload' => 'Юкленип башла',
'tooltip-rollback' => '"Кери къайтув" сычаннен бир басув вастасынен бу саифени сонъки денъиштиргеннинъ денъишикликлерини кери ала',
'tooltip-undo' => '"Кери ал" бу денъишикликни кери ала ве денъишиклик пенджересини бакъып чыкъув режиминде ача. Кери алувнынъ себебини бильдирмеге изин бере.',
# Stylesheets
'monobook.css' => '/* monobook темасынынъ аярларыны (настройкаларыны) денъиштирмек ичюн бу ерини денъиштиринъиз. Бутюн сайтта тесирли олур. */',
# Metadata
'nodublincore' => 'Dublin Core RDF мета малюматы бу сервер ичюн ясакълы.',
'nocreativecommons' => 'Creative Commons RDF мета малюматы бу сервер ичюн ясакълы.',
'notacceptable' => 'Вики-сервер браузеринъиз окъуп оладжакъ форматында малюмат бералмай.',
# Attribution
'anonymous' => '{{SITENAME}} сайтынынъ {{PLURAL:$1|1|$1}} къайдсыз (аноним) къулланыджысы',
'siteuser' => '{{SITENAME}} сайтынынъ къулланыджысы $1',
'lastmodifiedatby' => 'Саифе энъ сонъки $3 тарафындан $1, $2 тарихында денъиштирильди.', # $1 date, $2 time, $3 user
'othercontribs' => 'Бу саифени яраткъанда иштирак эткен: $1.',
'others' => 'дигерлери',
'siteusers' => '{{SITENAME}} сайтынынъ {{PLURAL:$2|1|$2}} къулланыджысы $1',
'creditspage' => 'Тешеккюрлер',
'nocredits' => 'Бу саифе ичюн къулланыджылар джедвели ёкъ.',
# Spam protection
'spamprotectiontitle' => 'Спам къаршы къорчалав сюзгючи',
'spamprotectiontext' => 'Сакъламагъа истеген саифенъиз спам сюзгючи тарафындан блок этильди. Буюк ихтималлы ки, саифеде къара джедвельдеки бир тыш сайткъа багъланты бар.',
'spamprotectionmatch' => 'Спам сюзгючинден бу беянат кельди: $1',
'spambot_username' => 'Спамдан темизлев',
'spam_reverting' => '$1 сайтына багълантысы олмагъан сонъки версиягъа кери кетирюв',
'spam_blanking' => 'Бар олгъан версияларда $1 сайтына багълантылар бар, темизлев',
# Info page
'infosubtitle' => 'Саифе акъкъында малюмат',
'numedits' => 'Денъишиклик сайысы (саифе): $1',
'numtalkedits' => 'Денъишиклик сайысы (музакере саифеси): $1',
'numwatchers' => 'Козетиджи сайысы: $1',
'numauthors' => 'Муэллиф сайысы (саифе): $1',
'numtalkauthors' => 'Муэллиф сайысы (музакере саифеси): $1',
# Skin names
'skinname-standard' => 'Стандарт',
'skinname-nostalgia' => 'Ностальгия',
'skinname-cologneblue' => 'Кёльн асретлиги',
'skinname-monobook' => 'MonoBook',
'skinname-myskin' => 'Озь ресимлеме',
'skinname-chick' => 'Чипче',
'skinname-simple' => 'Адий',
# Math options
'mw_math_png' => 'Даима PNG ресим форматына чевир',
'mw_math_simple' => 'Пек басит олса HTML, ёкъса PNG',
'mw_math_html' => 'Мумкюн олса HTML, ёкъса PNG',
'mw_math_source' => 'Денъиштирмеден TeX оларакъ ташла (метин темелли браузерлер ичюн)',
'mw_math_modern' => 'Земаневий браузерлер ичюн тевсие этильген',
'mw_math_mathml' => 'Мумкюн олса MathML (даа денъеме алында)',
# Patrol log
'patrol-log-page' => 'Тешкерюв журналы',
'log-show-hide-patrol' => 'Тешкерюв журналыны $1',
# Image deletion
'deletedrevision' => '$1 сайылы эски версия ёкъ этильди.',
'filedeleteerror-short' => 'Файл ёкъ эткенде хата чыкъты: $1',
'filedelete-missing' => '"$1" адлы файл ёкъ этилип оламай, чюнки ойле бир файл ёкъ.',
'filedelete-old-unregistered' => 'Малюмат базасында сайлангъан «$1» файл версиясы ёкъ.',
'filedelete-current-unregistered' => 'Малюмат базасында сайлангъан «$1» адлы файл ёкъ.',
# Browsing diffs
'previousdiff' => '← Эвельки денъишиклик',
'nextdiff' => 'Сонъраки денъишиклик →',
# Media information
'mediawarning' => "'''Ихтар''': Бу файл тюрюнинъ ичинде яман ниетли код ола биле.
Файлны ишлетип ишлетим системанъызгъа зарар кетирип олурсынъыз.<hr />",
'imagemaxsize' => 'Ресимлернинъ малюмат саифелериндеки ресимнинъ азамий (максималь) ольчюси:',
'thumbsize' => 'Кичик ольчю:',
'widthheightpage' => '$1 × $2, {{PLURAL:$3|1|$3}} саифе',
'file-info' => '(файл буюклиги: $1, MIME чешити: $2)',
'file-info-size' => '($1 × $2 пиксель, файл буюклиги: $3, MIME чешити: $4)',
'file-nohires' => '<small>Даа юксек чезинирликке саип версия ёкъ.</small>',
'svg-long-desc' => '(SVG файлы, номиналь $1 × $2 пиксель, файл буюклиги: $3)',
'show-big-image' => 'Там чезинирлик',
'show-big-image-thumb' => '<small>Бакъып чыкъувда ресим буюклиги: $1 × $2 пиксель</small>',
# Special:NewFiles
'newimages' => 'Янъы ресимлер',
'imagelisttext' => "Ашагъыдаки джедвельде $2 коре тизильген {{PLURAL:$1|'''1''' файлдыр|'''$1''' файлдыр}}.",
'newimages-summary' => 'Бу махсус саифе сонъки юкленген файлларны косьтере.',
'newimages-legend' => 'Сюзгюч',
'newimages-label' => 'Файл ады (я да онынъ бир парчасы):',
'showhidebots' => '(ботларны $1)',
'noimages' => 'Ресим ёкъ.',
'ilsubmit' => 'Къыдыр',
'bydate' => 'хронологик сыранен',
'sp-newimages-showfrom' => '$1, $2 тарихындан башлап янъы файллар косьтер',
# Video information, used by Language::formatTimePeriod() to format lengths in the above messages
'video-dims' => '$1, $2 × $3',
'seconds-abbrev' => 'сан.',
'minutes-abbrev' => 'дакъ.',
'hours-abbrev' => 'саат',
# Bad image list
'bad_image_list' => 'Формат бойле олмалы:
Эр сатыр * ишаретинен башламалы. Сатырнынъ биринджи багълантысы къошмагъа ясакълангъан файлгъа багъланмалы.
Шу сатырда илеридеки багълантылар истисна олурлар, яни шу саифелерде ишбу файл къулланмакъ мумкюн.',
# Metadata
'metadata' => 'Ресим деталлери',
'metadata-help' => 'Файлда (адетиндже ракъамлы камера ве сканерлернен къошулгъан) иляве малюматы бар. Эгер бу файл яратылгъандан сонъ денъиштирильсе эди, бельки де базы параметрлер эскирди.',
'metadata-expand' => 'Тафсилятны косьтер',
'metadata-collapse' => 'Тафсилятны косьтерме',
'metadata-fields' => 'Бу джедвельдеки EXIF мета малюматы ресим саифесинде косьтериледжек, башкъалары исе гизленеджек.
* make
* model
* datetimeoriginal
* exposuretime
* fnumber
* isospeedratings
* focallength', # Do not translate list items
# EXIF tags
'exif-make' => 'Камера маркасы',
'exif-model' => 'Камера модели',
'exif-artist' => 'Яратыджысы',
'exif-colorspace' => 'Ренк аралыгъы',
'exif-datetimeoriginal' => 'Оригиналь саат ве тарих',
'exif-exposuretime' => 'Экспозиция муддети',
'exif-exposuretime-format' => '$1 сание ($2)',
'exif-fnumber' => 'Диафрагма номерасы',
'exif-spectralsensitivity' => 'Спектраль дуйгъулылыкъ',
'exif-aperturevalue' => 'Диафрагма',
'exif-brightnessvalue' => 'парлакълыкъ',
'exif-lightsource' => 'Ярыкъ менбасы',
'exif-exposureindex' => 'Экспозиция индекси',
'exif-scenetype' => 'Сцена чешити',
'exif-digitalzoomratio' => 'Якъынлаштырув коэффициенти',
'exif-contrast' => 'Контрастлыкъ',
'exif-saturation' => 'Тойгъунлыкъ',
'exif-sharpness' => 'Ачыкълыкъ',
'exif-gpslatitude' => 'Энлик',
'exif-gpslongitude' => 'Бойлукъ',
'exif-gpsaltitude' => 'Юксеклик',
'exif-gpstimestamp' => 'GPS сааты (атом сааты)',
'exif-gpssatellites' => 'Ольчемек ичюн къуллангъаны спутниклер',
# EXIF attributes
'exif-compression-1' => 'Сыкъыштырылмагъан',
'exif-orientation-3' => '180° айландырылгъан', # 0th row: bottom; 0th column: right
'exif-exposureprogram-1' => 'Эльнен',
'exif-subjectdistance-value' => '$1 метр',
'exif-meteringmode-0' => 'Билинмей',
'exif-meteringmode-1' => 'Орта',
'exif-meteringmode-255' => 'Дигер',
'exif-lightsource-0' => 'Билинмей',
'exif-lightsource-2' => 'Флуоресцент',
'exif-lightsource-9' => 'Ачыкъ',
'exif-lightsource-10' => 'Къапалы',
'exif-lightsource-11' => 'Кольге',
'exif-lightsource-15' => 'Беяз флуоресцент (WW 3200 – 3700K)',
'exif-sensingmethod-1' => 'Танытувсыз',
'exif-scenecapturetype-0' => 'Стандарт',
'exif-scenecapturetype-2' => 'Портрет',
'exif-scenecapturetype-3' => 'Гедже съёмкасы',
'exif-subjectdistancerange-0' => 'Билинмей',
'exif-subjectdistancerange-1' => 'Макро',
# External editor support
'edit-externally' => 'Файл узеринде компьютеринъизде булунгъан программалар иле денъишикликлер япынъыз',
'edit-externally-help' => '(Даа зияде малюмат ичюн [http://www.mediawiki.org/wiki/Manual:External_editors бу саифеге] (Инглиздже) бакъып оласынъыз.)',
# 'all' in various places, this might be different for inflected languages
'recentchangesall' => 'эписини',
'imagelistall' => 'Джумлеси',
'watchlistall2' => 'эписини',
'namespacesall' => 'Эписи',
'monthsall' => 'Эписи',
# E-mail address confirmation
'confirmemail' => 'E-mail адресини тасдыкъла',
'confirmemail_noemail' => '[[Special:Preferences|Къулланыджы сазламаларынъызда]] догъру бир e-mail адресинъиз ёкъ.',
'confirmemail_text' => '{{SITENAME}} сайтынынъ e-mail функцияларыны къулланмаздан эвель e-mail адресинъизнинъ тасдыкъланмасы керек. Адресинъизге тасдыкъ e-mail мектюбини ёлламакъ ичюн ашагъыдаки дёгмени басынъыз. Ёлланаджакъ беянатта адресинъизни тасдыкъламакъ ичюн браузеринъизнен иришип оладжакъ, тасдыкъ коду олгъан бир багъланты оладжакъ.',
'confirmemail_pending' => 'Тасдыкъ коду энди сизге ёлланды.
Эгер эсабынъызны кеченлери ачса эдинъиз, бельки де янъны кодны бир даа сорагъанынъызда, бираз беклемек керек олур.',
'confirmemail_send' => 'Тасдыкъ кодуны ёлла',
'confirmemail_sent' => 'Тасдыкъ e-mail мектюбини ёлланды.',
'confirmemail_oncreate' => 'Бильдирген e-mail адресинъизге тасдыкъ кодунен мектюп ёлланды.
Шу код отурым ачмакъ ичюн лязим дегиль, амма бу сайтта электрон почтасынынъ чарелерини къулланмакъ ичюн рухсет берильмезден эвель оны кирсетмелисинъиз.',
'confirmemail_sendfailed' => '{{SITENAME}} тасдыкъ кодуны ёллап оламай. Лютфен, адресте рухсетсиз ариф я да ишарет олмагъаныны тешкеринъиз.
Сервернинъ джевабы: $1',
'confirmemail_invalid' => 'Янълыш тасдыкъ коду. Тасдыкъ кодунынъ сонъки къулланма тарихы кечкен ола билир.',
'confirmemail_needlogin' => '$1 япмакъ ичюн башта e-mail адресинъизни тасдыкъламалысынъыз.',
'confirmemail_success' => 'E-mail адресинъиз тасдыкъланды.',
'confirmemail_loggedin' => 'E-mail адресинъиз тасдыкъланды.',
'confirmemail_error' => 'Тасдыкъынъыз билинмеген бир хата себебинден къайд этильмеди.',
'confirmemail_subject' => '{{SITENAME}} e-mail адрес тасдыкъы.',
'confirmemail_body' => '$1 IP адресинден япылгъан иришим иле {{SITENAME}} сайтында
бу e-mail адресинен багълангъан $2 къулланыджы эсабы ачылды.
Бу e-mail адресининъ бахсы кечкен къулланыджы эсабына аит олгъаныны
тасдыкъламакъ ве {{SITENAME}} сайтындаки e-mail функцияларыны фааль алгъа
кетирмек ичюн ашагъыдаки багълантыны басынъыз.
$3
Бахсы кечкен къулланыджы эсабы сизге аит олмагъан олса бу багълантына басынъыз:
$5
Бу тасдыкъ коду $4 тарихына къадар къулланылып оладжакъ.',
'confirmemail_invalidated' => 'E-mail адресининъ тасдыкъы лягъу этильди',
'invalidateemail' => 'E-mail адресининъ тасдыкъы лягъу эт',
# Scary transclusion
'scarytranscludedisabled' => '[«Interwiki transcluding» ишлемей]',
'scarytranscludefailed' => '[$1 шаблонына иришилип оламады]',
'scarytranscludetoolong' => '[URL адреси чокъ узун]',
# Trackbacks
'trackbackbox' => 'Бу саифе ичюн trackback:<br />
$1',
'trackbackremove' => '([$1 ёкъ эт])',
'trackbacklink' => 'Trackback',
'trackbackdeleteok' => 'Trackback мувафакъиетнен ёкъ этильди.',
# Delete conflict
'deletedwhileediting' => "'''Тенби''': Бу саифе сиз денъишиклик япмагъа башлагъандан сонъ ёкъ этильди!",
'confirmrecreate' => "Сиз бу саифени денъиштирген вакъытта [[User:$1|$1]] ([[User talk:$1|музакере]]) къулланыджысы оны ёкъ эткендир, себеби:
:''$2''
Саифени янъыдан яратмагъа истесенъиз, лютфен, буны тасдыкъланъыз.",
'recreate' => 'Саифени янъыдан ярат',
# action=purge
'confirm_purge_button' => 'Ок',
'confirm-purge-top' => 'Саифе кэшини темизлесинми?',
# Multipage image navigation
'imgmultipageprev' => '← эвельки саифе',
'imgmultipagenext' => 'сонъраки саифе →',
'imgmultigo' => 'Бар',
'imgmultigoto' => '$1 саифесине бар',
# Table pager
'ascending_abbrev' => 'кичиктен буюкке',
'descending_abbrev' => 'буюктен кичикке',
'table_pager_next' => 'Сонъраки саифе',
'table_pager_prev' => 'Эвельки саифе',
'table_pager_first' => 'Ильк саифе',
'table_pager_last' => 'Сонъки саифе',
'table_pager_limit' => 'Саифе башына $1 дане косьтер',
'table_pager_limit_submit' => 'Бар',
'table_pager_empty' => 'Ич нетидже ёкъ',
# Auto-summaries
'autosumm-blank' => 'Саифе бошатылды',
'autosumm-replace' => "Саифедеки малюмат '$1' иле денъиштирильди",
'autoredircomment' => '[[$1]] саифесине ёлланды',
'autosumm-new' => "Янъы саифе яратылды. Мундериджеси: '$1'",
# Live preview
'livepreview-loading' => 'Юкленмекте…',
'livepreview-ready' => 'Юкленмекте… Азыр!',
'livepreview-failed' => 'Тез бакъып чыкъув ишлемей! Адий бакъып чыкъувны къулланып бакъынъыз.',
'livepreview-error' => 'Багъланамады: $1 «$2». Адий бакъып чыкъувны къулланып бакъынъыз.',
# Friendlier slave lag warnings
'lag-warn-normal' => '{{PLURAL:$1|1|$1}} саниеден эвель ве ондан сонъ япылгъан денъишикликлер бу джедвельде косьтерильмейип олалар.',
'lag-warn-high' => 'Малюмат базасындаки проблемалар себебинден {{PLURAL:$1|1|$1}} саниеден эвель ве ондан сонъ япылгъан денъишикликлер бу джедвельде косьтерильмейип олалар.',
# Watchlist editor
'watchlistedit-numitems' => 'Музакере саифесини эсапкъа алмайып, козетюв джедвелинъизде {{PLURAL:$1|1|$1}} саифе бар.',
'watchlistedit-noitems' => 'Козетюв джедвелинъизде ич бир саифе ёкъ.',
'watchlistedit-normal-title' => 'Козетюв джевелинъизни денъиштирмектесинъиз',
'watchlistedit-normal-legend' => 'Козетюв джедвелинден саифе ёкъ этилюви',
'watchlistedit-normal-explain' => 'Козетюв джедвелинъиздеки саифелер ашагъыда булуна. Саифе козетюв джедвелинден ёкъ этмек ичюн оны бельгилеп «Сайлангъан саифелерни козетюв джедвелинден ёкъ эт» язысына басынъыз. Козетюв джедвелинъизни [[Special:Watchlist/raw|метин оларакъ да денъиштирип]] оласынъыз.',
'watchlistedit-normal-submit' => 'Сайлангъан саифелерни козетюв джевелинден ёкъ эт',
'watchlistedit-normal-done' => '{{PLURAL:$1|1 саифе|$1 саифе}} козетюв джедвелинъизден ёкъ этильди:',
'watchlistedit-raw-title' => 'Козетюв джевелинъизни денъиштирмектесинъиз',
'watchlistedit-raw-legend' => 'Козетюв джедвелини денъиштирилюви',
'watchlistedit-raw-explain' => 'Козетюв джедвелинъиздеки саифелер ашагъыда булуна. Джедвельге саифе ады кирсетип я да ондан ёкъ этип (эр сатырда бирер ад) оны денъиштирип оласынъыз. Битирген сонъ «козетюв джедвелини янъарт» язысына басынъыз. [[Special:Watchlist/edit|Стандарт редакторны да къулланып олурсынъыз]].',
'watchlistedit-raw-titles' => 'Саифелер:',
'watchlistedit-raw-submit' => 'Козетюв джедвелини янъарт',
'watchlistedit-raw-done' => 'Козетюв джедвелинъиз янъарды.',
'watchlistedit-raw-added' => '{{PLURAL:$1|1 саифе|$1 саифе}} иляве олунды:',
'watchlistedit-raw-removed' => '{{PLURAL:$1|1 саифе|$1 саифе}} ёкъ этильди:',
# Watchlist editing tools
'watchlisttools-view' => 'Денъишикликлерни косьтер',
'watchlisttools-edit' => 'Козетюв джедвелини корь ве денъиштир',
'watchlisttools-raw' => 'Козетюв джедвелини адий метин оларакъ денъиштир',
# Special:Version
'version' => 'Версия', # Not used as normal message but as header for the special page itself
# Special:FileDuplicateSearch
'fileduplicatesearch-legend' => 'Дубликатны къыдыр',
'fileduplicatesearch-filename' => 'Файл ады:',
'fileduplicatesearch-submit' => 'Къыдыр',
'fileduplicatesearch-info' => '$1 × $2 пиксел<br />Файл буюклиги: $3<br />MIME чешити: $4',
'fileduplicatesearch-result-1' => '«$1» файлынынъ ич копиясы ёкъ.',
'fileduplicatesearch-result-n' => '«$1» файлынынъ {{PLURAL:$2|бир копиясы|$2 копиясы}} бар.',
# Special:SpecialPages
'specialpages' => 'Махсус саифелер',
'specialpages-group-maintenance' => 'Бакъым эсабатлары',
'specialpages-group-other' => 'Дигер махсус саифелер',
'specialpages-group-login' => 'Кириш / Къайд олув',
'specialpages-group-changes' => 'Сонъки денъишикликлер ве журналлар',
'specialpages-group-media' => 'Файл эсабатлары ве юклеме',
'specialpages-group-users' => 'Къулланыджылар ве акълары',
'specialpages-group-highuse' => 'Чокъ къулланылгъан саифелер',
'specialpages-group-pages' => 'Саифелер джедвели',
'specialpages-group-pagetools' => 'Саифе алетлери',
'specialpages-group-wiki' => 'Вики малюмат ве алетлер',
'specialpages-group-redirects' => 'Ёллама махсус саифелер',
'specialpages-group-spam' => 'Спамгъа къаршы алетлер',
# Special:BlankPage
'blankpage' => 'Бош саифе',
'intentionallyblankpage' => 'Бу саифе аселет бош къалдырылгъан',
);
|
gpl-2.0
|
simonchisnall-online/simonchisnall_online_website
|
modules/contrib/devel/webprofiler/src/Profiler/DatabaseProfilerStorage.php
|
3823
|
<?php
/**
* @file
* Contains \Drupal\webprofiler\Profiler\DatabaseProfilerStorage.
*/
namespace Drupal\webprofiler\Profiler;
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpKernel\Profiler\Profile;
use Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface;
/**
* Implements a profiler storage using the DBTNG query api.
*/
class DatabaseProfilerStorage implements ProfilerStorageInterface {
/**
* The database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Constructs a new DatabaseProfilerStorage instance.
*
* @param \Drupal\Core\Database\Connection $database
* The database connection.
*/
function __construct(Connection $database) {
$this->database = $database;
}
/**
* {@inheritdoc}
*/
public function find($ip, $url, $limit, $method, $start = NULL, $end = NULL) {
$select = $this->database->select('webprofiler', 'wp', ['fetch' => \PDO::FETCH_ASSOC]);
if (NULL === $start) {
$start = 0;
}
if (NULL === $end) {
$end = time();
}
if ($ip = preg_replace('/[^\d\.]/', '', $ip)) {
$select->condition('ip', '%' . $this->database->escapeLike($ip) . '%', 'LIKE');
}
if ($url) {
$select->condition('url', '%' . $this->database->escapeLike(addcslashes($url, '%_\\')) . '%', 'LIKE');
}
if ($method) {
$select->condition('method', $method);
}
if (!empty($start)) {
$select->condition('time', $start, '>=');
}
if (!empty($end)) {
$select->condition('time', $end, '<=');
}
$select->fields('wp', [
'token',
'ip',
'method',
'url',
'time',
'parent',
'status_code'
]);
$select->orderBy('time', 'DESC');
$select->range(0, $limit);
return $select->execute()
->fetchAllAssoc('token');
}
/**
* {@inheritdoc}
*/
public function read($token) {
$record = $this->database->select('webprofiler', 'w')
->fields('w')
->condition('token', $token)
->execute()
->fetch();
if (isset($record->data)) {
return $this->createProfileFromData($token, $record);
}
}
/**
* {@inheritdoc}
*/
public function write(Profile $profile) {
$args = [
'token' => $profile->getToken(),
'parent' => $profile->getParentToken(),
'data' => base64_encode(serialize($profile->getCollectors())),
'ip' => $profile->getIp(),
'method' => $profile->getMethod(),
'url' => $profile->getUrl(),
'time' => $profile->getTime(),
'created_at' => time(),
'status_code' => $profile->getStatusCode(),
];
try {
$query = $this->database->select('webprofiler', 'w')
->fields('w', ['token']);
$query->condition('token', $profile->getToken());
$count = $query->countQuery()->execute()->fetchAssoc();
if ($count['expression']) {
$this->database->update('webprofiler')
->fields($args)
->condition('token', $profile->getToken())
->execute();
}
else {
$this->database->insert('webprofiler')->fields($args)->execute();
}
$status = TRUE;
} catch (\Exception $e) {
$status = FALSE;
}
return $status;
}
/**
* {@inheritdoc}
*/
public function purge() {
$this->database->truncate('webprofiler')->execute();
}
/**
* @param string $token
* @param $data
*
* @return Profile
*/
private function createProfileFromData($token, $data) {
$profile = new Profile($token);
$profile->setIp($data->ip);
$profile->setMethod($data->method);
$profile->setUrl($data->url);
$profile->setTime($data->time);
$profile->setCollectors(unserialize(base64_decode($data->data)));
return $profile;
}
}
|
gpl-2.0
|
icebreaker/mm3d
|
src/commands/subdividecmd.cc
|
1540
|
/* Misfit Model 3D
*
* Copyright (c) 2004-2007 Kevin Worcester
*
* 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.
*
* See the COPYING file for full license text.
*/
#include "menuconf.h"
#include "subdividecmd.h"
#include "model.h"
#include "log.h"
#include "modelstatus.h"
#include <QtCore/QObject>
#include <QtGui/QApplication>
SubdivideCommand::SubdivideCommand()
{
}
SubdivideCommand::~SubdivideCommand()
{
}
bool SubdivideCommand::activated( int arg, Model * model )
{
model_status( model, StatusNormal, STATUSTIME_SHORT, qApp->translate( "Command", "Subdivide complete" ).toUtf8() );
model->subdivideSelectedTriangles();
return true;
}
const char * SubdivideCommand::getPath()
{
return GEOM_FACES_MENU;
}
const char * SubdivideCommand::getName( int arg )
{
return QT_TRANSLATE_NOOP( "Command", "Subdivide Faces" );
}
|
gpl-2.0
|
awesomerobot/discourse
|
lib/validators/email_validator.rb
|
1279
|
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless EmailValidator.allowed?(value)
record.errors.add(attribute, I18n.t(:'user.email.not_allowed'))
end
if record.errors[attribute].blank? && value && ScreenedEmail.should_block?(value)
record.errors.add(attribute, I18n.t(:'user.email.blocked'))
end
end
def self.allowed?(email)
if (setting = SiteSetting.email_domains_whitelist).present?
return email_in_restriction_setting?(setting, email) || is_developer?(email)
elsif (setting = SiteSetting.email_domains_blacklist).present?
return !(email_in_restriction_setting?(setting, email) && !is_developer?(email))
end
true
end
def self.email_in_restriction_setting?(setting, value)
domains = setting.gsub('.', '\.')
regexp = Regexp.new("@(.+\\.)?(#{domains})", true)
value =~ regexp
end
def self.is_developer?(value)
Rails.configuration.respond_to?(:developer_emails) && Rails.configuration.developer_emails.include?(value)
end
def self.email_regex
/\A[a-zA-Z0-9!#\$%&'*+\/=?\^_`{|}~\-]+(?:\.[a-zA-Z0-9!#\$%&'\*+\/=?\^_`{|}~\-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$\z/
end
end
|
gpl-2.0
|
spixi/wesnoth
|
src/serialization/string_utils.cpp
|
22365
|
/*
Copyright (C) 2003 by David White <dave@whitevine.net>
Copyright (C) 2005 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
Copyright (C) 2005 - 2018 by Philippe Plantier <ayin@anathas.org>
Part of the Battle for Wesnoth Project https://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.
*/
/**
* @file
* Various string-routines.
*/
#include "gettext.hpp"
#include "log.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/unicode.hpp"
#include "utils/general.hpp"
#include <cassert>
#include <array>
#include <limits>
#include <stdexcept>
#include <boost/algorithm/string.hpp>
static lg::log_domain log_engine("engine");
#define ERR_GENERAL LOG_STREAM(err, lg::general())
#define ERR_NG LOG_STREAM(err, log_engine)
namespace utils {
bool isnewline(const char c)
{
return c == '\r' || c == '\n';
}
// Make sure that we can use Mac, DOS, or Unix style text files on any system
// and they will work, by making sure the definition of whitespace is consistent
bool portable_isspace(const char c)
{
// returns true only on ASCII spaces
if (static_cast<unsigned char>(c) >= 128)
return false;
return isnewline(c) || isspace(static_cast<unsigned char>(c));
}
// Make sure we regard '\r' and '\n' as a space, since Mac, Unix, and DOS
// all consider these differently.
bool notspace(const char c)
{
return !portable_isspace(c);
}
/**
* Splits a (comma-)separated string into a vector of pieces.
* @param[in] val A (comma-)separated string.
* @param[in] c The separator character (usually a comma).
* @param[in] flags Flags controlling how the split is done.
* This is a bit field with two settings (both on by default):
* REMOVE_EMPTY causes empty pieces to be skipped/removed.
* STRIP_SPACES causes the leading and trailing spaces of each piece to be ignored/stripped.
*
* Basic method taken from http://stackoverflow.com/a/236803
*/
std::vector<std::string> split(const std::string& val, const char c, const int flags)
{
std::vector<std::string> res;
std::stringstream ss;
ss.str(val);
std::string item;
while(std::getline(ss, item, c)) {
if(flags & STRIP_SPACES) {
boost::trim(item);
}
if(!(flags & REMOVE_EMPTY) || !item.empty()) {
res.push_back(std::move(item));
}
}
return res;
}
std::vector<std::string> square_parenthetical_split(const std::string& val,
const char separator, const std::string& left,
const std::string& right,const int flags)
{
std::vector< std::string > res;
std::vector<char> part;
bool in_parenthesis = false;
std::vector<std::string::const_iterator> square_left;
std::vector<std::string::const_iterator> square_right;
std::vector< std::string > square_expansion;
std::string lp=left;
std::string rp=right;
std::string::const_iterator i1 = val.begin();
std::string::const_iterator i2;
std::string::const_iterator j1;
if (flags & STRIP_SPACES) {
while (i1 != val.end() && portable_isspace(*i1))
++i1;
}
i2=i1;
j1=i1;
if (i1 == val.end()) return res;
if (!separator) {
ERR_GENERAL << "Separator must be specified for square bracket split function." << std::endl;
return res;
}
if(left.size()!=right.size()){
ERR_GENERAL << "Left and Right Parenthesis lists not same length" << std::endl;
return res;
}
while (true) {
if(i2 == val.end() || (!in_parenthesis && *i2 == separator)) {
//push back square contents
std::size_t size_square_exp = 0;
for (std::size_t i=0; i < square_left.size(); i++) {
std::string tmp_val(square_left[i]+1,square_right[i]);
std::vector< std::string > tmp = split(tmp_val);
for(const std::string& piece : tmp) {
std::size_t found_tilde = piece.find_first_of('~');
if (found_tilde == std::string::npos) {
std::size_t found_asterisk = piece.find_first_of('*');
if (found_asterisk == std::string::npos) {
std::string tmp2(piece);
boost::trim(tmp2);
square_expansion.push_back(tmp2);
}
else { //'*' multiple expansion
std::string s_begin = piece.substr(0,found_asterisk);
boost::trim(s_begin);
std::string s_end = piece.substr(found_asterisk+1);
boost::trim(s_end);
for (int ast=std::stoi(s_end); ast>0; --ast)
square_expansion.push_back(s_begin);
}
}
else { //expand number range
std::string s_begin = piece.substr(0,found_tilde);
boost::trim(s_begin);
int begin = std::stoi(s_begin);
std::size_t padding = 0, padding_end = 0;
while (padding<s_begin.size() && s_begin[padding]=='0') {
padding++;
}
std::string s_end = piece.substr(found_tilde+1);
boost::trim(s_end);
int end = std::stoi(s_end);
while (padding_end<s_end.size() && s_end[padding_end]=='0') {
padding_end++;
}
if (padding*padding_end > 0 && s_begin.size() != s_end.size()) {
ERR_GENERAL << "Square bracket padding sizes not matching: "
<< s_begin << " and " << s_end <<".\n";
}
if (padding_end > padding) padding = padding_end;
int increment = (end >= begin ? 1 : -1);
end+=increment; //include end in expansion
for (int k=begin; k!=end; k+=increment) {
std::string pb = std::to_string(k);
for (std::size_t p=pb.size(); p<=padding; p++)
pb = std::string("0") + pb;
square_expansion.push_back(pb);
}
}
}
if (i*square_expansion.size() != (i+1)*size_square_exp ) {
std::string tmp2(i1, i2);
ERR_GENERAL << "Square bracket lengths do not match up: " << tmp2 << std::endl;
return res;
}
size_square_exp = square_expansion.size();
}
//combine square contents and rest of string for comma zone block
std::size_t j = 0;
std::size_t j_max = 0;
if (!square_left.empty())
j_max = square_expansion.size() / square_left.size();
do {
j1 = i1;
std::string new_val;
for (std::size_t i=0; i < square_left.size(); i++) {
std::string tmp_val(j1, square_left[i]);
new_val.append(tmp_val);
std::size_t k = j+i*j_max;
if (k < square_expansion.size())
new_val.append(square_expansion[k]);
j1 = square_right[i]+1;
}
std::string tmp_val(j1, i2);
new_val.append(tmp_val);
if (flags & STRIP_SPACES)
boost::trim_right(new_val);
if (!(flags & REMOVE_EMPTY) || !new_val.empty())
res.push_back(new_val);
j++;
} while (j<j_max);
if (i2 == val.end()) //escape loop
break;
++i2;
if (flags & STRIP_SPACES) { //strip leading spaces
while (i2 != val.end() && portable_isspace(*i2))
++i2;
}
i1=i2;
square_left.clear();
square_right.clear();
square_expansion.clear();
continue;
}
if(!part.empty() && *i2 == part.back()) {
part.pop_back();
if (*i2 == ']') square_right.push_back(i2);
if (part.empty())
in_parenthesis = false;
++i2;
continue;
}
bool found=false;
for(std::size_t i=0; i < lp.size(); i++) {
if (*i2 == lp[i]){
if (*i2 == '[')
square_left.push_back(i2);
++i2;
part.push_back(rp[i]);
found=true;
break;
}
}
if(!found){
++i2;
} else
in_parenthesis = true;
}
if(!part.empty()){
ERR_GENERAL << "Mismatched parenthesis:\n"<<val<< std::endl;
}
return res;
}
std::map<std::string, std::string> map_split(
const std::string& val
, char major
, char minor
, int flags
, const std::string& default_value)
{
//first split by major so that we get a vector with the key-value pairs
std::vector< std::string > v = split(val, major, flags);
//now split by minor to extract keys and values
std::map< std::string, std::string > res;
for( std::vector< std::string >::iterator i = v.begin(); i != v.end(); ++i) {
std::size_t pos = i->find_first_of(minor);
std::string key, value;
if(pos == std::string::npos) {
key = (*i);
value = default_value;
} else {
key = i->substr(0, pos);
value = i->substr(pos + 1);
}
res[key] = value;
}
return res;
}
std::vector<std::string> parenthetical_split(const std::string& val,
const char separator, const std::string& left,
const std::string& right,const int flags)
{
std::vector< std::string > res;
std::vector<char> part;
bool in_parenthesis = false;
std::string lp=left;
std::string rp=right;
std::string::const_iterator i1 = val.begin();
std::string::const_iterator i2;
if (flags & STRIP_SPACES) {
while (i1 != val.end() && portable_isspace(*i1))
++i1;
}
i2=i1;
if(left.size()!=right.size()){
ERR_GENERAL << "Left and Right Parenthesis lists not same length" << std::endl;
return res;
}
while (i2 != val.end()) {
if(!in_parenthesis && separator && *i2 == separator){
std::string new_val(i1, i2);
if (flags & STRIP_SPACES)
boost::trim_right(new_val);
if (!(flags & REMOVE_EMPTY) || !new_val.empty())
res.push_back(new_val);
++i2;
if (flags & STRIP_SPACES) {
while (i2 != val.end() && portable_isspace(*i2))
++i2;
}
i1=i2;
continue;
}
if(!part.empty() && *i2 == part.back()){
part.pop_back();
if(!separator && part.empty()){
std::string new_val(i1, i2);
if (flags & STRIP_SPACES)
boost::trim(new_val);
res.push_back(new_val);
++i2;
i1=i2;
}else{
if (part.empty())
in_parenthesis = false;
++i2;
}
continue;
}
bool found=false;
for(std::size_t i=0; i < lp.size(); i++){
if (*i2 == lp[i]){
if (!separator && part.empty()){
std::string new_val(i1, i2);
if (flags & STRIP_SPACES)
boost::trim(new_val);
res.push_back(new_val);
++i2;
i1=i2;
}else{
++i2;
}
part.push_back(rp[i]);
found=true;
break;
}
}
if(!found){
++i2;
} else
in_parenthesis = true;
}
std::string new_val(i1, i2);
if (flags & STRIP_SPACES)
boost::trim(new_val);
if (!(flags & REMOVE_EMPTY) || !new_val.empty())
res.push_back(std::move(new_val));
if(!part.empty()){
ERR_GENERAL << "Mismatched parenthesis:\n"<<val<< std::endl;
}
return res;
}
// Modify a number by string representing integer difference, or optionally %
int apply_modifier( const int number, const std::string &amount, const int minimum ) {
// wassert( amount.empty() == false );
int value = 0;
try {
value = std::stoi(amount);
} catch(const std::invalid_argument&) {}
if(amount[amount.size()-1] == '%') {
value = div100rounded(number * value);
}
value += number;
if (( minimum > 0 ) && ( value < minimum ))
value = minimum;
return value;
}
std::string escape(const std::string &str, const char *special_chars)
{
std::string::size_type pos = str.find_first_of(special_chars);
if (pos == std::string::npos) {
// Fast path, possibly involving only reference counting.
return str;
}
std::string res = str;
do {
res.insert(pos, 1, '\\');
pos = res.find_first_of(special_chars, pos + 2);
} while (pos != std::string::npos);
return res;
}
std::string unescape(const std::string &str)
{
std::string::size_type pos = str.find('\\');
if (pos == std::string::npos) {
// Fast path, possibly involving only reference counting.
return str;
}
std::string res = str;
do {
res.erase(pos, 1);
pos = res.find('\\', pos + 1);
} while (pos != std::string::npos);
return str;
}
std::string urlencode(const std::string &str)
{
static const std::string nonresv_str =
"-."
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"_"
"abcdefghijklmnopqrstuvwxyz"
"~";
static const std::set<char> nonresv(nonresv_str.begin(), nonresv_str.end());
std::ostringstream res;
res << std::hex;
res.fill('0');
for(char c : str) {
if(nonresv.count(c) != 0) {
res << c;
continue;
}
res << '%';
res.width(2);
res << static_cast<int>(c);
}
return res.str();
}
bool string_bool(const std::string& str, bool def) {
if (str.empty()) return def;
// yes/no is the standard, test it first
if (str == "yes") return true;
if (str == "no"|| str == "false" || str == "off" || str == "0" || str == "0.0")
return false;
// all other non-empty string are considered as true
return true;
}
std::string bool_string(const bool value)
{
std::ostringstream ss;
ss << std::boolalpha << value;
return ss.str();
}
std::string signed_value(int val)
{
std::ostringstream oss;
oss << (val >= 0 ? "+" : font::unicode_minus) << std::abs(val);
return oss.str();
}
std::string half_signed_value(int val)
{
std::ostringstream oss;
if (val < 0)
oss << font::unicode_minus;
oss << std::abs(val);
return oss.str();
}
static void si_string_impl_stream_write(std::stringstream &ss, double input) {
std::streamsize oldprec = ss.precision();
#ifdef _MSC_VER
// For MSVC, default mode misbehaves, so we use fixed instead.
ss.precision(1);
ss << std::fixed
<< input;
#else
// In default mode, precision sets the number of significant figures.
// 999.5 and above will render as 1000+, however, only numbers above 1000 will use 4 digits
// Rounding everything from 100 up (at which point we stop using decimals anyway) avoids this.
if (input >= 100) {
input = std::round(input);
}
// When in binary mode, numbers of up to 1023.9999 can be passed
// We should render those with 4 digits, instead of as 1e+3.
// Input should be an integer number now, but doubles can do strange things, so check the halfway point instead.
if (input >= 999.5) {
ss.precision(4);
} else {
ss.precision(3);
}
ss << input;
#endif
ss.precision(oldprec);
}
std::string si_string(double input, bool base2, const std::string& unit) {
const double multiplier = base2 ? 1024 : 1000;
typedef std::array<std::string, 9> strings9;
if(input < 0){
return font::unicode_minus + si_string(std::abs(input), base2, unit);
}
strings9 prefixes;
strings9::const_iterator prefix;
if (input == 0.0) {
strings9 tmp { { "","","","","","","","","" } };
prefixes = tmp;
prefix = prefixes.begin();
} else if (input < 1.0) {
strings9 tmp { {
"",
_("prefix_milli^m"),
_("prefix_micro^µ"),
_("prefix_nano^n"),
_("prefix_pico^p"),
_("prefix_femto^f"),
_("prefix_atto^a"),
_("prefix_zepto^z"),
_("prefix_yocto^y")
} };
prefixes = tmp;
prefix = prefixes.begin();
while (input < 1.0 && *prefix != prefixes.back()) {
input *= multiplier;
++prefix;
}
} else {
strings9 tmp { {
"",
(base2 ?
_("prefix_kibi^K") :
_("prefix_kilo^k")
),
_("prefix_mega^M"),
_("prefix_giga^G"),
_("prefix_tera^T"),
_("prefix_peta^P"),
_("prefix_exa^E"),
_("prefix_zetta^Z"),
_("prefix_yotta^Y")
} };
prefixes = tmp;
prefix = prefixes.begin();
while (input > multiplier && *prefix != prefixes.back()) {
input /= multiplier;
++prefix;
}
}
std::stringstream ss;
si_string_impl_stream_write(ss, input);
ss << ' '
<< *prefix
<< (base2 && (!(*prefix).empty()) ? _("infix_binary^i") : "")
<< unit;
return ss.str();
}
static bool is_username_char(char c) {
return ((c == '_') || (c == '-'));
}
static bool is_wildcard_char(char c) {
return ((c == '?') || (c == '*'));
}
bool isvalid_username(const std::string& username) {
const std::size_t alnum = std::count_if(username.begin(), username.end(), isalnum);
const std::size_t valid_char =
std::count_if(username.begin(), username.end(), is_username_char);
if ((alnum + valid_char != username.size())
|| valid_char == username.size() || username.empty() )
{
return false;
}
return true;
}
bool isvalid_wildcard(const std::string& username) {
const std::size_t alnum = std::count_if(username.begin(), username.end(), isalnum);
const std::size_t valid_char =
std::count_if(username.begin(), username.end(), is_username_char);
const std::size_t wild_char =
std::count_if(username.begin(), username.end(), is_wildcard_char);
if ((alnum + valid_char + wild_char != username.size())
|| valid_char == username.size() || username.empty() )
{
return false;
}
return true;
}
bool word_completion(std::string& text, std::vector<std::string>& wordlist) {
std::vector<std::string> matches;
const std::size_t last_space = text.rfind(" ");
// If last character is a space return.
if (last_space == text.size() -1) {
wordlist = matches;
return false;
}
bool text_start;
std::string semiword;
if (last_space == std::string::npos) {
text_start = true;
semiword = text;
} else {
text_start = false;
semiword.assign(text, last_space + 1, text.size());
}
std::string best_match = semiword;
for (std::vector<std::string>::const_iterator word = wordlist.begin();
word != wordlist.end(); ++word)
{
if (word->size() < semiword.size()
|| !std::equal(semiword.begin(), semiword.end(), word->begin(),
chars_equal_insensitive))
{
continue;
}
if (matches.empty()) {
best_match = *word;
} else {
int j = 0;
while (toupper(best_match[j]) == toupper((*word)[j])) j++;
if (best_match.begin() + j < best_match.end()) {
best_match.erase(best_match.begin() + j, best_match.end());
}
}
matches.push_back(*word);
}
if(!matches.empty()) {
text.replace(last_space + 1, best_match.size(), best_match);
}
wordlist = matches;
return text_start;
}
static bool is_word_boundary(char c) {
return (c == ' ' || c == ',' || c == ':' || c == '\'' || c == '"' || c == '-');
}
bool word_match(const std::string& message, const std::string& word) {
std::size_t first = message.find(word);
if (first == std::string::npos) return false;
if (first == 0 || is_word_boundary(message[first - 1])) {
std::size_t next = first + word.size();
if (next == message.size() || is_word_boundary(message[next])) {
return true;
}
}
return false;
}
bool wildcard_string_match(const std::string& str, const std::string& match) {
const bool wild_matching = (!match.empty() && (match[0] == '*' || match[0] == '+'));
const std::string::size_type solid_begin = match.find_first_not_of("*+");
const bool have_solids = (solid_begin != std::string::npos);
// Check the simple cases first
if(!have_solids) {
const std::string::size_type plus_count = std::count(match.begin(), match.end(), '+');
return match.empty() ? str.empty() : str.length() >= plus_count;
} else if(str.empty()) {
return false;
}
const std::string::size_type solid_end = match.find_first_of("*+", solid_begin);
const std::string::size_type solid_len = (solid_end == std::string::npos)
? match.length() - solid_begin : solid_end - solid_begin;
// Since + always consumes at least one character, increment current if the match
// begins with one
std::string::size_type current = match[0] == '+' ? 1 : 0;
bool matches;
do {
matches = true;
// Now try to place the str into the solid space
const std::string::size_type test_len = str.length() - current;
for(std::string::size_type i=0; i < solid_len && matches; ++i) {
char solid_c = match[solid_begin + i];
if(i > test_len || !(solid_c == '?' || solid_c == str[current+i])) {
matches = false;
}
}
if(matches) {
// The solid space matched, now consume it and attempt to find more
const std::string consumed_match = (solid_begin+solid_len < match.length())
? match.substr(solid_end) : "";
const std::string consumed_str = (solid_len < test_len)
? str.substr(current+solid_len) : "";
matches = wildcard_string_match(consumed_str, consumed_match);
}
} while(wild_matching && !matches && ++current < str.length());
return matches;
}
std::string indent(const std::string& string, std::size_t indent_size)
{
if(indent_size == 0) {
return string;
}
const std::string indent(indent_size, ' ');
if(string.empty()) {
return indent;
}
const std::vector<std::string>& lines = split(string, '\x0A', 0);
std::string res;
for(std::size_t lno = 0; lno < lines.size();) {
const std::string& line = lines[lno];
// Lines containing only a carriage return count as empty.
if(!line.empty() && line != "\x0D") {
res += indent;
}
res += line;
if(++lno < lines.size()) {
res += '\x0A';
}
}
return res;
}
std::vector<std::string> quoted_split(const std::string& val, char c, int flags, char quote)
{
std::vector<std::string> res;
std::string::const_iterator i1 = val.begin();
std::string::const_iterator i2 = val.begin();
while (i2 != val.end()) {
if (*i2 == quote) {
// Ignore quoted character
++i2;
if (i2 != val.end()) ++i2;
} else if (*i2 == c) {
std::string new_val(i1, i2);
if (flags & STRIP_SPACES)
boost::trim(new_val);
if (!(flags & REMOVE_EMPTY) || !new_val.empty())
res.push_back(std::move(new_val));
++i2;
if (flags & STRIP_SPACES) {
while(i2 != val.end() && *i2 == ' ')
++i2;
}
i1 = i2;
} else {
++i2;
}
}
std::string new_val(i1, i2);
if (flags & STRIP_SPACES)
boost::trim(new_val);
if (!(flags & REMOVE_EMPTY) || !new_val.empty())
res.push_back(new_val);
return res;
}
std::pair<int, int> parse_range(const std::string& str)
{
const std::string::const_iterator dash = std::find(str.begin(), str.end(), '-');
const std::string a(str.begin(), dash);
const std::string b = dash != str.end() ? std::string(dash + 1, str.end()) : a;
std::pair<int,int> res {0,0};
try {
if (b == "infinity") {
res = std::make_pair(std::stoi(a), std::numeric_limits<int>::max());
} else {
res = std::make_pair(std::stoi(a), std::stoi(b));
}
if (res.second < res.first) {
res.second = res.first;
}
} catch(const std::invalid_argument&) {
ERR_GENERAL << "Invalid range: "<< str << std::endl;
}
return res;
}
std::vector<std::pair<int, int>> parse_ranges(const std::string& str)
{
std::vector<std::pair<int, int>> to_return;
for(const std::string& r : utils::split(str)) {
to_return.push_back(parse_range(r));
}
return to_return;
}
void ellipsis_truncate(std::string& str, const std::size_t size)
{
const std::size_t prev_size = str.length();
utf8::truncate(str, size);
if(str.length() != prev_size) {
str += font::ellipsis;
}
}
} // end namespace utils
|
gpl-2.0
|
NathanW2/QGIS
|
src/gui/qgsoptionsdialoghighlightwidgetsimpl.cpp
|
9494
|
/***************************************************************************
qgsoptionsdialoghighlightwidgetsimpl.cpp
-------------------------------
Date : February 2018
Copyright : (C) 2018 Denis Rouzaud
Email : denis.rouzaud@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. *
* *
***************************************************************************/
#include <QCheckBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QEvent>
#include <QGroupBox>
#include <QLabel>
#include <QTreeView>
#include <QTreeWidget>
#include <QAbstractItemModel>
#include "qgsoptionsdialoghighlightwidget.h"
#include "qgsmessagebaritem.h"
#include "qgsoptionsdialoghighlightwidgetsimpl.h"
#include <functional>
const int HIGHLIGHT_BACKGROUND_RED = 255;
const int HIGHLIGHT_BACKGROUND_GREEN = 251;
const int HIGHLIGHT_BACKGROUND_BLUE = 190;
const int HIGHLIGHT_TEXT_RED = 0;
const int HIGHLIGHT_TEXT_GREEN = 0;
const int HIGHLIGHT_TEXT_BLUE = 0;
// ****************
// QLabel
QgsOptionsDialogHighlightLabel::QgsOptionsDialogHighlightLabel( QLabel *label )
: QgsOptionsDialogHighlightWidget( label )
, mLabel( label )
, mStyleSheet( QStringLiteral( /*!search!*/"QLabel { background-color: rgb(%1, %2, %3); color: rgb(%4, %5, %6 );}/*!search!*/" ).arg( HIGHLIGHT_BACKGROUND_RED )
.arg( HIGHLIGHT_BACKGROUND_GREEN )
.arg( HIGHLIGHT_BACKGROUND_BLUE )
.arg( HIGHLIGHT_TEXT_RED )
.arg( HIGHLIGHT_TEXT_GREEN )
.arg( HIGHLIGHT_TEXT_BLUE ) )
{}
bool QgsOptionsDialogHighlightLabel::searchText( const QString &text )
{
if ( !mLabel )
return false;
return mLabel->text().contains( text, Qt::CaseInsensitive );
}
bool QgsOptionsDialogHighlightLabel::highlightText( const QString &text )
{
if ( !mWidget )
return false;
Q_UNUSED( text );
mWidget->setStyleSheet( mWidget->styleSheet() + mStyleSheet );
return true;
}
void QgsOptionsDialogHighlightLabel::reset()
{
if ( !mWidget )
return;
QString ss = mWidget->styleSheet();
ss.remove( mStyleSheet );
mWidget->setStyleSheet( ss );
}
// ****************
// QCheckBox
QgsOptionsDialogHighlightCheckBox::QgsOptionsDialogHighlightCheckBox( QCheckBox *checkBox )
: QgsOptionsDialogHighlightWidget( checkBox )
, mCheckBox( checkBox )
, mStyleSheet( QStringLiteral( "/*!search!*/QCheckBox { background-color: rgb(%1, %2, %3); color: rgb( %4, %5, %6);}/*!search!*/" ).arg( HIGHLIGHT_BACKGROUND_RED )
.arg( HIGHLIGHT_BACKGROUND_GREEN )
.arg( HIGHLIGHT_BACKGROUND_BLUE )
.arg( HIGHLIGHT_TEXT_RED )
.arg( HIGHLIGHT_TEXT_GREEN )
.arg( HIGHLIGHT_TEXT_BLUE ) )
{
}
bool QgsOptionsDialogHighlightCheckBox::searchText( const QString &text )
{
if ( !mCheckBox )
return false;
return mCheckBox->text().contains( text, Qt::CaseInsensitive );
}
bool QgsOptionsDialogHighlightCheckBox::highlightText( const QString &text )
{
if ( !mWidget )
return false;
Q_UNUSED( text );
mWidget->setStyleSheet( mWidget->styleSheet() + mStyleSheet );
return true;
}
void QgsOptionsDialogHighlightCheckBox::reset()
{
if ( !mWidget )
return;
QString ss = mWidget->styleSheet();
ss.remove( mStyleSheet );
mWidget->setStyleSheet( ss );
}
// ****************
// QAbstractButton
QgsOptionsDialogHighlightButton::QgsOptionsDialogHighlightButton( QAbstractButton *button )
: QgsOptionsDialogHighlightWidget( button )
, mButton( button )
, mStyleSheet( QStringLiteral( "/*!search!*/QAbstractButton { background-color: rgb(%1, %2, %3); color: rgb(%4, %5, %6);}/*!search!*/" ).arg( HIGHLIGHT_BACKGROUND_RED )
.arg( HIGHLIGHT_BACKGROUND_GREEN )
.arg( HIGHLIGHT_BACKGROUND_BLUE )
.arg( HIGHLIGHT_TEXT_RED )
.arg( HIGHLIGHT_TEXT_GREEN )
.arg( HIGHLIGHT_TEXT_BLUE ) )
{
}
bool QgsOptionsDialogHighlightButton::searchText( const QString &text )
{
if ( !mButton )
return false;
return mButton->text().contains( text, Qt::CaseInsensitive );
}
bool QgsOptionsDialogHighlightButton::highlightText( const QString &text )
{
if ( !mWidget )
return false;
Q_UNUSED( text );
mWidget->setStyleSheet( mWidget->styleSheet() + mStyleSheet );
return true;
}
void QgsOptionsDialogHighlightButton::reset()
{
if ( !mWidget )
return;
QString ss = mWidget->styleSheet();
ss.remove( mStyleSheet );
mWidget->setStyleSheet( ss );
}
// ****************
// QGroupBox
QgsOptionsDialogHighlightGroupBox::QgsOptionsDialogHighlightGroupBox( QGroupBox *groupBox )
: QgsOptionsDialogHighlightWidget( groupBox )
, mGroupBox( groupBox )
, mStyleSheet( QStringLiteral( "/*!search!*/QGroupBox::title { background-color: rgb(%1, %2, %3); color: rgb(%4, %5, %6);}/*!search!*/" ).arg( HIGHLIGHT_BACKGROUND_RED )
.arg( HIGHLIGHT_BACKGROUND_GREEN )
.arg( HIGHLIGHT_BACKGROUND_BLUE )
.arg( HIGHLIGHT_TEXT_RED )
.arg( HIGHLIGHT_TEXT_GREEN )
.arg( HIGHLIGHT_TEXT_BLUE ) )
{
}
bool QgsOptionsDialogHighlightGroupBox::searchText( const QString &text )
{
if ( !mGroupBox )
return false;
return mGroupBox->title().contains( text, Qt::CaseInsensitive );
}
bool QgsOptionsDialogHighlightGroupBox::highlightText( const QString &text )
{
Q_UNUSED( text );
if ( !mWidget )
return false;
mWidget->setStyleSheet( mWidget->styleSheet() + mStyleSheet );
return true;
}
void QgsOptionsDialogHighlightGroupBox::reset()
{
if ( !mWidget )
return;
QString ss = mWidget->styleSheet();
ss.remove( mStyleSheet );
mWidget->setStyleSheet( ss );
}
// ****************
// QTreeView
QgsOptionsDialogHighlightTree::QgsOptionsDialogHighlightTree( QTreeView *treeView )
: QgsOptionsDialogHighlightWidget( treeView )
, mTreeView( treeView )
{
}
bool QgsOptionsDialogHighlightTree::searchText( const QString &text )
{
if ( !mTreeView )
return false;
QModelIndexList hits = mTreeView->model()->match( mTreeView->model()->index( 0, 0 ), Qt::DisplayRole, text, 1, Qt::MatchContains | Qt::MatchRecursive );
return !hits.isEmpty();
}
bool QgsOptionsDialogHighlightTree::highlightText( const QString &text )
{
bool success = false;
QTreeWidget *treeWidget = qobject_cast<QTreeWidget *>( mTreeView );
if ( treeWidget )
{
mTreeInitialVisible.clear();
// initially hide everything
std::function< void( QTreeWidgetItem *, bool ) > setChildrenVisible;
setChildrenVisible = [this, &setChildrenVisible]( QTreeWidgetItem * item, bool visible )
{
for ( int i = 0; i < item->childCount(); ++i )
setChildrenVisible( item->child( i ), visible );
mTreeInitialVisible.insert( item, !item->isHidden() );
item->setHidden( !visible );
};
setChildrenVisible( treeWidget->invisibleRootItem(), false );
QList<QTreeWidgetItem *> items = treeWidget->findItems( text, Qt::MatchContains | Qt::MatchRecursive, 0 );
success = items.count() ? true : false;
mTreeInitialStyle.clear();
mTreeInitialExpand.clear();
for ( QTreeWidgetItem *item : items )
{
mTreeInitialStyle.insert( item, qMakePair( item->background( 0 ), item->foreground( 0 ) ) );
item->setBackground( 0, QBrush( QColor( HIGHLIGHT_BACKGROUND_RED, HIGHLIGHT_BACKGROUND_GREEN, HIGHLIGHT_BACKGROUND_BLUE ) ) );
item->setForeground( 0, QBrush( QColor( HIGHLIGHT_TEXT_RED, HIGHLIGHT_TEXT_GREEN, HIGHLIGHT_TEXT_BLUE ) ) );
setChildrenVisible( item, true );
QTreeWidgetItem *parent = item;
while ( parent )
{
if ( mTreeInitialExpand.contains( parent ) )
break;
mTreeInitialExpand.insert( parent, parent->isExpanded() );
parent->setExpanded( true );
parent->setHidden( false );
parent = parent->parent();
}
}
}
return success;
}
void QgsOptionsDialogHighlightTree::reset()
{
if ( !mTreeView )
return;
QTreeWidget *treeWidget = qobject_cast<QTreeWidget *>( mTreeView );
if ( treeWidget )
{
// show everything
std::function< void( QTreeWidgetItem * ) > showChildren;
showChildren = [this, &showChildren]( QTreeWidgetItem * item )
{
for ( int i = 0; i < item->childCount(); ++i )
showChildren( item->child( i ) );
item->setHidden( !mTreeInitialVisible.value( item, true ) );
};
showChildren( treeWidget->invisibleRootItem() );
for ( QTreeWidgetItem *item : mTreeInitialExpand.keys() )
{
if ( item )
{
item->setExpanded( mTreeInitialExpand.value( item ) );
}
}
for ( QTreeWidgetItem *item : mTreeInitialStyle.keys() )
{
if ( item )
{
item->setBackground( 0, mTreeInitialStyle.value( item ).first );
item->setForeground( 0, mTreeInitialStyle.value( item ).second );
}
}
mTreeInitialStyle.clear();
mTreeInitialExpand.clear();
}
}
|
gpl-2.0
|
fahimc/mintcreations
|
wp-content/themes/mintcreations/lib/com/greensock/plugins/ScrollToPlugin.js
|
2659
|
/**
* VERSION: beta 1.30
* DATE: 2012-07-25
* JavaScript
* UPDATES AND DOCS AT: http://www.greensock.com
*
* Copyright (c) 2008-2012, GreenSock. All rights reserved.
* This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for
* corporate Club GreenSock members, the software agreement that was issued with the corporate
* membership.
*
* @author: Jack Doyle, jack@greensock.com
**/
(window._gsQueue || (window._gsQueue = [])).push( function() {
_gsDefine("plugins.ScrollToPlugin", ["plugins.TweenPlugin"], function(TweenPlugin) {
var ScrollToPlugin = function(props, priority) {
TweenPlugin.call(this, "scrollTo");
this._overwriteProps.pop();
},
p = ScrollToPlugin.prototype = new TweenPlugin("scrollTo"),
_getX = function() {
return (window.pageXOffset != null) ? window.pageXOffset : (document.documentElement.scrollLeft != null) ? document.documentElement.scrollLeft : document.body.scrollLeft;
},
_getY = function() {
return (window.pageYOffset != null) ? window.pageYOffset : (document.documentElement.scrollTop != null) ? document.documentElement.scrollTop : document.body.scrollTop;
},
_setRatio = TweenPlugin.prototype.setRatio; //speed optimization (quicker lookup)
p.constructor = ScrollToPlugin;
ScrollToPlugin.API = 2;
p._onInitTween = function(target, value, tween) {
this._wdw = (target == window);
this._target = target;
if (typeof(value) !== "object") {
value = {y:Number(value)}; //if we don't receive an object as the parameter, assume the user intends "y".
}
this.x = this._wdw ? _getX() : target.scrollLeft;
this.y = this._wdw ? _getY() : target.scrollTop;
if (value.x != null) {
this._addTween(this, "x", this.x, value.x, "scrollTo_x", true);
} else {
this.skipX = true;
}
if (value.y != null) {
this._addTween(this, "y", this.y, value.y, "scrollTo_y", true);
} else {
this.skipY = true;
}
return true;
};
p._kill = function(lookup) {
if (lookup.scrollTo_x) {
this.skipX = true;
}
if (lookup.scrollTo_x) {
this.skipY = true;
}
return TweenPlugin.prototype._kill.call(this, lookup);
}
p.setRatio = function(v) {
_setRatio.call(this, v);
if (this._wdw) {
window.scrollTo((!this.skipX) ? this.x : _getX(), (!this.skipY) ? this.y : _getY());
} else {
if (!this.skipY) {
this._target.scrollTop = this.y;
}
if (!this.skipX) {
this._target.scrollLeft = this.x;
}
}
};
TweenPlugin.activate([ScrollToPlugin]);
return ScrollToPlugin;
}, true);
}); if (window._gsDefine) { _gsQueue.pop()(); }
|
gpl-2.0
|
scztt/sc3-plugins
|
source/MCLDUGens/MCLDFilterUGens.cpp
|
10660
|
/*
This code (c) Dan Stowell, published under the GPL, v2 or later
*/
#include "SC_PlugIn.h"
#define TWOPI 6.28318530717952646f
static InterfaceTable *ft;
struct Friction : public Unit
{
float m_V, m_beltpos, m_x, m_dx;
};
struct Crest : public Unit
{
float *m_circbuf;
unsigned int m_circbufpos;
unsigned int m_length;
float m_result;
bool m_notfullyet;
int m_realNumSamples;
};
struct Goertzel : public Unit
{
unsigned int m_size, m_pos, m_realNumSamples;
// Constants
float m_w, m_cosine, m_sine;
float m_coeff;
unsigned int m_numParallel, m_whichNext, *m_checkpoints;
// State variables
float *m_q2, *m_q1;
// Output variables
float m_real, m_imag;
};
extern "C"
{
void load(InterfaceTable *inTable);
void Friction_Ctor(Friction* unit);
void Friction_next(Friction *unit, int inNumSamples);
void Crest_Ctor(Crest* unit);
void Crest_next(Crest *unit, int inNumSamples);
void Crest_Dtor(Crest* unit);
void Goertzel_Ctor(Goertzel* unit);
void Goertzel_next_1(Goertzel *unit, int inNumSamples);
void Goertzel_next_multi(Goertzel *unit, int inNumSamples);
void Goertzel_Dtor(Goertzel* unit);
};
//////////////////////////////////////////////////////////////////
void Friction_Ctor(Friction* unit)
{
SETCALC(Friction_next);
// initialize the unit generator state variables.
unit->m_V = 0.f;
unit->m_beltpos = 0.f;
unit->m_x = 0.f;
unit->m_dx = 0.f;
// calculate one sample of output.
Friction_next(unit, 1);
}
void Friction_next(Friction *unit, int inNumSamples)
{
float *out = OUT(0);
float *in = IN(0);
// Control-rate parameters
float friction = ZIN0(1);
float spring = ZIN0(2);
float damp = ZIN0(3);
float mass = ZIN0(4);
float beltmass = ZIN0(5);
// Retrive state
float beltpos = unit->m_beltpos;
float V = unit->m_V;
float x = unit->m_x;
float dx = unit->m_dx;
// vars used in the loop
float F_N, relspeed, F_f, drivingforce, F_s, F, ddx, oldbeltpos, oldV, beltaccn;
bool sticking;
// The normal force is just due to the weight of the object
F_N = mass * 9.81f;
float frictimesF_N = (friction * F_N);
for (int i=0; i < inNumSamples; ++i)
{
oldbeltpos = beltpos;
oldV = V;
beltpos = in[i];
V = beltpos - oldbeltpos;
beltaccn = V - oldV;
// Calc the kinetic friction force
relspeed = dx - V;
if(relspeed==0.f){
F_f = 0.f; // No kinetic friction when no relative motion
} else if (relspeed > 0.f){
F_f = frictimesF_N;
} else {
F_f = 0.f - frictimesF_N;
}
drivingforce = beltaccn * beltmass;
// Calc the nonfriction force that would occur if moving along with the belt
F_s = drivingforce - (damp * V) - (spring * x);
// Decide if we're sticking or not
sticking = sc_abs(F_s) < frictimesF_N;
// NOW TO UPDATE THE MASS'S POSITION.
// If sticking it's easy. Mass speed == belt speed
if(sticking){
dx = V;
} else {
// Based on eq (5)
F = F_s - F_f;
ddx = F / mass;
dx += ddx;
}
x += dx;
// write the output
out[i] = x;
}
// Store state
unit->m_beltpos = beltpos;
unit->m_V = V;
unit->m_x = x;
unit->m_dx = dx;
}
//////////////////////////////////////////////////////////////////
void Crest_Ctor(Crest* unit)
{
SETCALC(Crest_next);
unsigned int length = (unsigned int)ZIN0(1); // Fixed number of items to store in the ring buffer
if(length==0)
length=1; // ...because things would get painful in the stupid scenario of length 0
unit->m_circbuf = (float*)RTAlloc(unit->mWorld, length * sizeof(float));
unit->m_circbuf[0] = ZIN0(0); // Load first sample in...
unit->m_circbufpos = 0U;
unit->m_length = length;
unit->m_notfullyet = true; // Only after first filled do we scan the whole buffer. Otherwise we scan up to and including the current position.
if (INRATE(0) == calc_FullRate) {
unit->m_realNumSamples = unit->mWorld->mFullRate.mBufLength;
} else {
unit->m_realNumSamples = 1;
}
ZOUT0(0) = unit->m_result = 1.f; // Necessarily 1 at first since only 1 sample received. No need to run calc func
}
void Crest_next(Crest* unit, int inNumSamples)
{
float *in = ZIN(0);
float gate = ZIN0(1);
// Get state and instance variables from the struct
float* circbuf = unit->m_circbuf;
int circbufpos = unit->m_circbufpos;
int length = unit->m_length;
float result = unit->m_result;
bool notfullyet = unit->m_notfullyet;
int realNumSamples = unit->m_realNumSamples;
LOOP(realNumSamples,
// Always add to the ringbuf, even if we're not calculating
circbuf[circbufpos++] = std::fabs(ZXP(in));
if(circbufpos == length){
circbufpos = 0U;
if(notfullyet){
notfullyet = unit->m_notfullyet = false;
}
}
);
if(gate){
// crest = (samples.abs.max) / (samples.abs.mean).
// crest = N * (samples.abs.max) / (samples.abs.sum).
// Already performed abs when storing data.
float maxval=0.f, sum=0.f;
unsigned int limit = notfullyet ? circbufpos : length;
//Print("Crest calculating over %u samples (full length %u. mBufLength %u, realNumSamples %u)\n", limit, length, unit->mBufLength, realNumSamples);
for(unsigned int i=0U; i < limit; ++i){
sum += circbuf[i];
if(maxval < circbuf[i])
maxval = circbuf[i];
}
result = sum==0.f ? 1.f : (float)length * maxval / sum;
}
ZOUT0(0) = unit->m_result = result;
// Store state variables back
unit->m_circbufpos = circbufpos;
unit->m_result = result;
}
void Crest_Dtor(Crest* unit)
{
if(unit->m_circbuf)
RTFree(unit->mWorld, unit->m_circbuf);
}
//////////////////////////////////////////////////////////////////
// Goertzel Algorithm, following
// http://www.embedded.com/story/OEG20020819S0057
void Goertzel_Ctor(Goertzel* unit)
{
// initialize the unit generator state variables.
unsigned int size = (int)ZIN0(1);
float hopf = ZIN0(3); // a ratio, should be 0<hopf<=1
unsigned int hop = (unsigned int)std::ceil(hopf * (float)size); // in samples
double srate;
if (INRATE(0) == calc_FullRate) {
unit->m_realNumSamples = unit->mWorld->mFullRate.mBufLength;
srate = unit->mWorld->mFullRate.mSampleRate;
// Ensure size is a multiple of block size (if audio rate)
size = unit->m_realNumSamples * (unsigned int)std::ceil(size / (float)unit->m_realNumSamples);
hop = unit->m_realNumSamples * (unsigned int)std::ceil(hop / (float)unit->m_realNumSamples);
} else {
unit->m_realNumSamples = 1;
srate = unit->mWorld->mBufRate.mSampleRate;
}
unsigned int numParallel = size / hop;
//printf("Goertzel: size %u, hop %u; so %u in parallel\n", size, hop, numParallel);
if(numParallel == 1)
SETCALC(Goertzel_next_1);
else
SETCALC(Goertzel_next_multi);
float freq = ZIN0(2);
// Precomputed constants
float floatN = (float)size;
int k = (int)(0.5 + floatN * freq / srate);
double w = (TWOPI * k)/floatN;
double cosine = std::cos(w);
double sine = std::sin(w);
double coeff = 2. * cosine;
unit->m_size = size;
unit->m_cosine = cosine;
unit->m_sine = sine;
unit->m_coeff = coeff;
// Values re the round-robin approach to "overlap"
unit->m_numParallel = numParallel;
unit->m_whichNext = 0;
unit->m_q1 = (float*)RTAlloc(unit->mWorld, numParallel * sizeof(float));
unit->m_q2 = (float*)RTAlloc(unit->mWorld, numParallel * sizeof(float));
unit->m_checkpoints = (unsigned int*)RTAlloc(unit->mWorld, numParallel * sizeof(unsigned int));
for(unsigned int i=0; i<numParallel; ++i){
unit->m_q1[i] = 0.f;
unit->m_q2[i] = 0.f;
// The "checkpoints" are the points in the (theoretical) "buffer" at which we output-and-reset each goertzel stream
unit->m_checkpoints[i] = (i+1) * hop;
}
unit->m_real = 0.f;
unit->m_imag = 0.f;
unit->m_pos = 0;
// calculate one sample of output.
ZOUT0(0) = 0.f;
}
//////////////////////////////////////////////////////////////////
// Optimised version if no overlap (can avoid some looping, some array indexing, etc):
void Goertzel_next_1(Goertzel *unit, int wrongNumSamples)
{
unsigned int realNumSamples = unit->m_realNumSamples;
float* in = IN(0);
float cosine = unit->m_cosine;
float sine = unit->m_sine;
float coeff = unit->m_coeff;
unsigned int pos = unit->m_pos;
unsigned int size = unit->m_size;
float q1 = unit->m_q1[0];
float q2 = unit->m_q2[0];
float real = unit->m_real;
float imag = unit->m_imag;
float q0;
for(unsigned int i=0; i<realNumSamples; ++i){
q0 = coeff * q1 - q2 + in[i];
q2 = q1;
q1 = q0;
++pos;
}
if(pos == size){
// We've reached the end of a block, let's find values
real = (q1 - q2 * cosine);
imag = (q2 * sine);
//Print("Reached block boundary. cosine %g, sine %g, coeff %g, size %u, q0 %g, q1 %g, q2 %g\n", cosine, sine, coeff, size, q0, q1, q2);
// reset:
q1 = q2 = 0.f;
pos = 0;
}
// Output values
ZOUT0(0) = real;
ZOUT0(1) = imag;
// Store state
unit->m_q1[0] = q1;
unit->m_q2[0] = q2;
unit->m_pos = pos;
unit->m_real = real;
unit->m_imag = imag;
}
void Goertzel_next_multi(Goertzel *unit, int wrongNumSamples)
{
unsigned int realNumSamples = unit->m_realNumSamples;
float* in = IN(0);
float cosine = unit->m_cosine;
float sine = unit->m_sine;
float coeff = unit->m_coeff;
unsigned int pos = unit->m_pos;
unsigned int size = unit->m_size;
unsigned int whichNext = unit->m_whichNext;
unsigned int numParallel = unit->m_numParallel;
unsigned int checkpoint = unit->m_checkpoints[whichNext];
float *q1 = unit->m_q1;
float *q2 = unit->m_q2;
float real = unit->m_real;
float imag = unit->m_imag;
float q0;
for(unsigned int i=0; i<realNumSamples; ++i){
for(unsigned int j=0; j<numParallel; ++j){
q0 = coeff * q1[j] - q2[j] + in[i];
q2[j] = q1[j];
q1[j] = q0;
}
++pos;
}
if(pos == checkpoint){
// We've reached the end of a block for our currently-selected stream, let's find values
real = (q1[whichNext] - q2[whichNext] * cosine);
imag = (q2[whichNext] * sine);
//Print("Reached block boundary. cosine %g, sine %g, coeff %g, size %u, q0 %g, q1 %g, q2 %g\n", cosine, sine, coeff, size, q0, q1, q2);
// reset:
q1[whichNext] = q2[whichNext] = 0.;
if(pos==size){
pos = 0;
}
++whichNext;
if(whichNext == numParallel){
whichNext = 0;
}
unit->m_whichNext = whichNext;
}
// Output values
ZOUT0(0) = real;
ZOUT0(1) = imag;
// Store state
unit->m_pos = pos;
unit->m_real = real;
unit->m_imag = imag;
}
void Goertzel_Dtor(Goertzel* unit)
{
if(unit->m_q1){
RTFree(unit->mWorld, unit->m_q1);
RTFree(unit->mWorld, unit->m_q2);
RTFree(unit->mWorld, unit->m_checkpoints);
}
}
//////////////////////////////////////////////////////////////////
PluginLoad(MCLDFilter)
{
ft = inTable;
DefineSimpleUnit(Friction);
DefineDtorUnit(Crest);
DefineDtorUnit(Goertzel);
}
|
gpl-2.0
|
infoalex/huayra
|
saf/sigesp_saf_c_condicion.php
|
9050
|
<?php
require_once("../shared/class_folder/class_sql.php");
require_once("../shared/class_folder/class_datastore.php");
require_once("../shared/class_folder/class_mensajes.php");
require_once("../shared/class_folder/sigesp_include.php");
require_once("../shared/class_folder/sigesp_c_seguridad.php");
require_once("../shared/class_folder/class_funciones.php");
class sigesp_saf_c_condicion
{
var $obj="";
var $io_sql;
var $siginc;
var $con;
function sigesp_saf_c_condicion()
{
$this->io_msg=new class_mensajes();
$this->dat_emp=$_SESSION["la_empresa"];
$in=new sigesp_include();
$this->con=$in->uf_conectar();
$this->io_sql=new class_sql($this->con);
$this->seguridad= new sigesp_c_seguridad();
$this->io_funcion = new class_funciones();
}//fin de la function sigesp_saf_c_metodos()
function uf_saf_select_condicion($as_codigo)
{
//////////////////////////////////////////////////////////////////////////////
// Function: uf_saf_select_condicion
// Access: public
// Arguments:
// $as_codigo // codigo de condicion del bien
// Returns: $lb_valido-----> true: encontrado false: no encontrado
// Description: Esta funcion busca una condicion en la tabla de saf_conservacionbien
//
//////////////////////////////////////////////////////////////////////////////
global $fun;
global $msg;
$lb_valido=true;
$ls_cadena="";
$li_exec=-1;
$this->is_msg_error = "";
$ls_sql = "SELECT * FROM saf_conservacionbien ".
" WHERE codconbie='".$as_codigo."'" ;
$li_exec=$this->io_sql->select($ls_sql);
if($li_exec===false)
{
$this->io_msg->message("CLASE->condicion MÉTODO->uf_saf_select_condicion ERROR->".$this->io_funcion->uf_convertirmsg($this->io_sql->message));
$lb_valido=false;
}
else
{
if($row=$this->io_sql->fetch_row($li_exec))
{
$lb_valido=true;
}
else
{
$lb_valido=false;
}
}
$this->io_sql->free_result($li_exec);
return $lb_valido;
}//fin de la function uf_saf_select_condicion
function uf_generar_num_conbie()
{
$ls_gestor = $_SESSION["ls_gestor"];
if(strtoupper($ls_gestor)=="MYSQLT")
{
$ls_cadena = "MAX(CAST(codconbie as SIGNED)) ";
}
else
{
$ls_cadena = "MAX(CAST(codconbie as SMALLINT)) ";
}
$ls_sql = " SELECT ".$ls_cadena." as codconbie ".
" FROM saf_conservacionbien ".
" ORDER BY codconbie DESC";
$rs_funciondb=$this->io_sql->select($ls_sql);
if ($row=$this->io_sql->fetch_row($rs_funciondb))
{
$codigo=$row["codconbie"];
settype($codigo,'int'); // Asigna el tipo a la variable.
$codigo = $codigo + 1; // Le sumo uno al entero.
settype($codigo,'string'); // Lo convierto a varchar nuevamente.
$ls_codigo = str_pad($codigo,2,0,0);
}
else
{
$codigo="1";
$ls_codigo = str_pad($codigo,2,0,0);
}
return $ls_codigo;
}
function uf_saf_insert_condicion($as_codigo,$as_denominacion,$as_descripcion,$aa_seguridad)
{
//////////////////////////////////////////////////////////////////////////////
// Function: uf_saf_insert_condicion
// Access: public
// Arguments:
// $as_codigo // codigo de condicion del bien
// as_denominacion // denominacion de la condicion del bien
// as_descripcion // descricion de la condicion del bien
// aa_seguridad // arreglo de registro de seguridad
// Returns: $lb_valido-----> true: operacion exitosa false: operacion no exitosa
// Description: Esta funcion inserta una condicion del bien en la tabla de saf_conservacionbien
//
//////////////////////////////////////////////////////////////////////////////
global $fun;
global $msg;
$lb_valido=true;
$ls_sql="";
$li_exec=-1;
$this->is_msg_error = "";
$this->io_sql->begin_transaction();
$ls_sql = "INSERT INTO saf_conservacionbien (codconbie, denconbie, desconbie) ".
" VALUES('".$as_codigo."','".$as_denominacion."','".$as_descripcion."')" ;
$li_exec=$this->io_sql->execute($ls_sql);
if($li_exec===false)
{
$this->io_msg->message("CLASE->condicion MÉTODO->uf_saf_insert_condicion ERROR->".$this->io_funcion->uf_convertirmsg($this->io_sql->message));
$lb_valido=false;
$this->io_sql->rollback();
}
else
{
$lb_valido=true;
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="INSERT";
$ls_descripcion ="Insertó la Condición del bien ".$as_codigo;
$ls_variable= $this->seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
$this->io_sql->commit();
}
return $lb_valido;
}//fin de la uf_saf_insert_condicion
function uf_saf_update_condicion($as_codigo,$as_denominacion,$as_descripcion,$aa_seguridad)
{
//////////////////////////////////////////////////////////////////////////////
// Function: uf_saf_update_condicion
// Access: public
// Arguments:
// $as_codigo // codigo de condicion del bien
// as_denominacion // denominacion de la condicion del bien
// as_descripcion // descricion de la condicion del bien
// aa_seguridad // arreglo de registro de seguridad
// Returns: $lb_valido-----> true: operacion exitosa false: operacion no exitosa
// Description: Esta funcion modifica una condicion del bien en la tabla de saf_conservacionbien
//
//////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ls_cadena="";
$li_exce=-1;
$ls_sql = "UPDATE saf_conservacionbien SET denconbie='". $as_denominacion ."', desconbie='". $as_descripcion ."'".
"WHERE codconbie='" . $as_codigo ."' ";
$this->io_sql->begin_transaction();
$li_exec = $this->io_sql->execute($ls_sql);
if($li_exec===false)
{
$this->io_msg->message("CLASE->condicion MÉTODO->uf_saf_update_condicion ERROR->".$this->io_funcion->uf_convertirmsg($this->io_sql->message));
$lb_valido=false;
$this->io_sql->rollback();
}
else
{
$lb_valido=true;
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="UPDATE";
$ls_descripcion ="Modificó la Condición del bien ".$as_codigo;
$ls_variable= $this->seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
$this->io_sql->commit();
}
return $lb_valido;
}// fin de la function uf_sss_update_condicion
function uf_saf_delete_condicion($as_codigo,$aa_seguridad)
{
//////////////////////////////////////////////////////////////////////////////
// Function: uf_saf_delete_condicion
// Access: public
// Arguments:
// $as_codigo // codigo de condicion del bien
// aa_seguridad // arreglo de registro de seguridad
// Returns: $lb_valido-----> true: operacion exitosa false: operacion no exitosa
// Description: Esta funcion elimina una condicion en la tabla de saf_conservacionbien
//
//////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ls_sql="";
$li_exec=-1;
$ib_db_error = false;
$this->is_msg_error = "";
$msg=new class_mensajes();
$ls_sql = " DELETE FROM saf_conservacionbien".
" WHERE codconbie= '".$as_codigo. "'";
$this->io_sql->begin_transaction();
$li_exec=$this->io_sql->execute($ls_sql);
if($li_exec===false)
{
$this->io_msg->message("CLASE->condicion MÉTODO->uf_saf_delete_condicion ERROR->".$this->io_funcion->uf_convertirmsg($this->io_sql->message));
$lb_valido=false;
$this->io_sql->rollback();
}
else
{
$lb_valido=true;
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="DELETE";
$ls_descripcion ="Eliminó la Condición del bien ".$as_codigo;
$ls_variable= $this->seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
$this->io_sql->commit();
}
return $lb_valido;
} //fin de uf_saf_delete_condicion
}//fin de la class sigesp_saf_c_condicion
?>
|
gpl-2.0
|
fsg-ict/PARD-gem5
|
src/dev/cellx/I82094AX.py
|
2414
|
# Copyright (c) 2015 Institute of Computing Technology, CAS
# Copyright (c) 2008 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Gabe Black
# Jiuyue Ma
##@update
# majiuyue: add support for PARDg5-V CellX architecture
#
from m5.params import *
from m5.proxy import *
from Device import BasicPioDevice
from X86IntPin import X86IntSinkPin
class I82094AX(BasicPioDevice):
type = 'I82094AX'
cxx_class = 'X86ISA::I82094AX'
cxx_header = "dev/cellx/i82094ax.hh"
apic_id = Param.Int(1, 'APIC id for this IO APIC')
int_master = MasterPort("Port for sending interrupt messages")
int_latency = Param.Latency('1ns', \
"Latency for an interrupt to propagate through this device.")
external_int_pic = Param.SimObject(NULL, "External PIC, if any")
max_guests = Param.Int(8, "MAximum guests support")
def pin(self, line):
return X86IntSinkPin(device=self, number=line)
|
gpl-2.0
|
pgena/instance-portal
|
plugins/p_fckeditor/fckeditor/editor/lang/es.js
|
19102
|
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2010 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Spanish language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "Contraer Barra",
ToolbarExpand : "Expandir Barra",
// Toolbar Items and Context Menu
Save : "Guardar",
NewPage : "Nueva Página",
Preview : "Vista Previa",
Cut : "Cortar",
Copy : "Copiar",
Paste : "Pegar",
PasteText : "Pegar como texto plano",
PasteWord : "Pegar desde Word",
Print : "Imprimir",
SelectAll : "Seleccionar Todo",
RemoveFormat : "Eliminar Formato",
InsertLinkLbl : "Vínculo",
InsertLink : "Insertar/Editar Vínculo",
RemoveLink : "Eliminar Vínculo",
VisitLink : "Abrir enlace",
Anchor : "Referencia",
AnchorDelete : "Eliminar Referencia",
InsertImageLbl : "Imagen",
InsertImage : "Insertar/Editar Imagen",
InsertFlashLbl : "Flash",
InsertFlash : "Insertar/Editar Flash",
InsertTableLbl : "Tabla",
InsertTable : "Insertar/Editar Tabla",
InsertLineLbl : "Línea",
InsertLine : "Insertar Línea Horizontal",
InsertSpecialCharLbl: "Caracter Especial",
InsertSpecialChar : "Insertar Caracter Especial",
InsertSmileyLbl : "Emoticons",
InsertSmiley : "Insertar Emoticons",
About : "Acerca de FCKeditor",
Bold : "Negrita",
Italic : "Cursiva",
Underline : "Subrayado",
StrikeThrough : "Tachado",
Subscript : "Subíndice",
Superscript : "Superíndice",
LeftJustify : "Alinear a Izquierda",
CenterJustify : "Centrar",
RightJustify : "Alinear a Derecha",
BlockJustify : "Justificado",
DecreaseIndent : "Disminuir Sangría",
IncreaseIndent : "Aumentar Sangría",
Blockquote : "Cita",
CreateDiv : "Crear contenedor (div)",
EditDiv : "Editar contenedor (div)",
DeleteDiv : "Eliminar contenedor (div)",
Undo : "Deshacer",
Redo : "Rehacer",
NumberedListLbl : "Numeración",
NumberedList : "Insertar/Eliminar Numeración",
BulletedListLbl : "Viñetas",
BulletedList : "Insertar/Eliminar Viñetas",
ShowTableBorders : "Mostrar Bordes de Tablas",
ShowDetails : "Mostrar saltos de Párrafo",
Style : "Estilo",
FontFormat : "Formato",
Font : "Fuente",
FontSize : "Tamaño",
TextColor : "Color de Texto",
BGColor : "Color de Fondo",
Source : "Fuente HTML",
Find : "Buscar",
Replace : "Reemplazar",
SpellCheck : "Ortografía",
UniversalKeyboard : "Teclado Universal",
PageBreakLbl : "Salto de Página",
PageBreak : "Insertar Salto de Página",
Form : "Formulario",
Checkbox : "Casilla de Verificación",
RadioButton : "Botones de Radio",
TextField : "Campo de Texto",
Textarea : "Area de Texto",
HiddenField : "Campo Oculto",
Button : "Botón",
SelectionField : "Campo de Selección",
ImageButton : "Botón Imagen",
FitWindow : "Maximizar el tamaño del editor",
ShowBlocks : "Mostrar bloques",
// Context Menu
EditLink : "Editar Vínculo",
CellCM : "Celda",
RowCM : "Fila",
ColumnCM : "Columna",
InsertRowAfter : "Insertar fila en la parte inferior",
InsertRowBefore : "Insertar fila en la parte superior",
DeleteRows : "Eliminar Filas",
InsertColumnAfter : "Insertar columna a la derecha",
InsertColumnBefore : "Insertar columna a la izquierda",
DeleteColumns : "Eliminar Columnas",
InsertCellAfter : "Insertar celda a la derecha",
InsertCellBefore : "Insertar celda a la izquierda",
DeleteCells : "Eliminar Celdas",
MergeCells : "Combinar Celdas",
MergeRight : "Combinar a la derecha",
MergeDown : "Combinar hacia abajo",
HorizontalSplitCell : "Dividir la celda horizontalmente",
VerticalSplitCell : "Dividir la celda verticalmente",
TableDelete : "Eliminar Tabla",
CellProperties : "Propiedades de Celda",
TableProperties : "Propiedades de Tabla",
ImageProperties : "Propiedades de Imagen",
FlashProperties : "Propiedades de Flash",
AnchorProp : "Propiedades de Referencia",
ButtonProp : "Propiedades de Botón",
CheckboxProp : "Propiedades de Casilla",
HiddenFieldProp : "Propiedades de Campo Oculto",
RadioButtonProp : "Propiedades de Botón de Radio",
ImageButtonProp : "Propiedades de Botón de Imagen",
TextFieldProp : "Propiedades de Campo de Texto",
SelectionFieldProp : "Propiedades de Campo de Selección",
TextareaProp : "Propiedades de Area de Texto",
FormProp : "Propiedades de Formulario",
FontFormats : "Normal;Con formato;Dirección;Encabezado 1;Encabezado 2;Encabezado 3;Encabezado 4;Encabezado 5;Encabezado 6;Normal (DIV)",
// Alerts and Messages
ProcessingXHTML : "Procesando XHTML. Por favor, espere...",
Done : "Hecho",
PasteWordConfirm : "El texto que desea parece provenir de Word. Desea depurarlo antes de pegarlo?",
NotCompatiblePaste : "Este comando está disponible sólo para Internet Explorer version 5.5 or superior. Desea pegar sin depurar?",
UnknownToolbarItem : "Item de barra desconocido \"%1\"",
UnknownCommand : "Nombre de comando desconocido \"%1\"",
NotImplemented : "Comando no implementado",
UnknownToolbarSet : "Nombre de barra \"%1\" no definido",
NoActiveX : "La configuración de las opciones de seguridad de su navegador puede estar limitando algunas características del editor. Por favor active la opción \"Ejecutar controles y complementos de ActiveX \", de lo contrario puede experimentar errores o ausencia de funcionalidades.",
BrowseServerBlocked : "La ventana de visualización del servidor no pudo ser abierta. Verifique que su navegador no esté bloqueando las ventanas emergentes (pop up).",
DialogBlocked : "No se ha podido abrir la ventana de diálogo. Verifique que su navegador no esté bloqueando las ventanas emergentes (pop up).",
VisitLinkBlocked : "Nose ha podido abrir la ventana. Asegurese de que todos los bloqueadores de popups están deshabilitados.",
// Dialogs
DlgBtnOK : "OK",
DlgBtnCancel : "Cancelar",
DlgBtnClose : "Cerrar",
DlgBtnBrowseServer : "Ver Servidor",
DlgAdvancedTag : "Avanzado",
DlgOpOther : "<Otro>",
DlgInfoTab : "Información",
DlgAlertUrl : "Inserte el URL",
// General Dialogs Labels
DlgGenNotSet : "<No definido>",
DlgGenId : "Id",
DlgGenLangDir : "Orientación",
DlgGenLangDirLtr : "Izquierda a Derecha (LTR)",
DlgGenLangDirRtl : "Derecha a Izquierda (RTL)",
DlgGenLangCode : "Cód. de idioma",
DlgGenAccessKey : "Clave de Acceso",
DlgGenName : "Nombre",
DlgGenTabIndex : "Indice de tabulación",
DlgGenLongDescr : "Descripción larga URL",
DlgGenClass : "Clases de hojas de estilo",
DlgGenTitle : "Título",
DlgGenContType : "Tipo de Contenido",
DlgGenLinkCharset : "Fuente de caracteres vinculado",
DlgGenStyle : "Estilo",
// Image Dialog
DlgImgTitle : "Propiedades de Imagen",
DlgImgInfoTab : "Información de Imagen",
DlgImgBtnUpload : "Enviar al Servidor",
DlgImgURL : "URL",
DlgImgUpload : "Cargar",
DlgImgAlt : "Texto Alternativo",
DlgImgWidth : "Anchura",
DlgImgHeight : "Altura",
DlgImgLockRatio : "Proporcional",
DlgBtnResetSize : "Tamaño Original",
DlgImgBorder : "Borde",
DlgImgHSpace : "Esp.Horiz",
DlgImgVSpace : "Esp.Vert",
DlgImgAlign : "Alineación",
DlgImgAlignLeft : "Izquierda",
DlgImgAlignAbsBottom: "Abs inferior",
DlgImgAlignAbsMiddle: "Abs centro",
DlgImgAlignBaseline : "Línea de base",
DlgImgAlignBottom : "Pie",
DlgImgAlignMiddle : "Centro",
DlgImgAlignRight : "Derecha",
DlgImgAlignTextTop : "Tope del texto",
DlgImgAlignTop : "Tope",
DlgImgPreview : "Vista Previa",
DlgImgAlertUrl : "Por favor escriba la URL de la imagen",
DlgImgLinkTab : "Vínculo",
// Flash Dialog
DlgFlashTitle : "Propiedades de Flash",
DlgFlashChkPlay : "Autoejecución",
DlgFlashChkLoop : "Repetir",
DlgFlashChkMenu : "Activar Menú Flash",
DlgFlashScale : "Escala",
DlgFlashScaleAll : "Mostrar todo",
DlgFlashScaleNoBorder : "Sin Borde",
DlgFlashScaleFit : "Ajustado",
// Link Dialog
DlgLnkWindowTitle : "Vínculo",
DlgLnkInfoTab : "Información de Vínculo",
DlgLnkTargetTab : "Destino",
DlgLnkType : "Tipo de vínculo",
DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "Referencia en esta página",
DlgLnkTypeEMail : "E-Mail",
DlgLnkProto : "Protocolo",
DlgLnkProtoOther : "<otro>",
DlgLnkURL : "URL",
DlgLnkAnchorSel : "Seleccionar una referencia",
DlgLnkAnchorByName : "Por Nombre de Referencia",
DlgLnkAnchorById : "Por ID de elemento",
DlgLnkNoAnchors : "(No hay referencias disponibles en el documento)",
DlgLnkEMail : "Dirección de E-Mail",
DlgLnkEMailSubject : "Título del Mensaje",
DlgLnkEMailBody : "Cuerpo del Mensaje",
DlgLnkUpload : "Cargar",
DlgLnkBtnUpload : "Enviar al Servidor",
DlgLnkTarget : "Destino",
DlgLnkTargetFrame : "<marco>",
DlgLnkTargetPopup : "<ventana emergente>",
DlgLnkTargetBlank : "Nueva Ventana(_blank)",
DlgLnkTargetParent : "Ventana Padre (_parent)",
DlgLnkTargetSelf : "Misma Ventana (_self)",
DlgLnkTargetTop : "Ventana primaria (_top)",
DlgLnkTargetFrameName : "Nombre del Marco Destino",
DlgLnkPopWinName : "Nombre de Ventana Emergente",
DlgLnkPopWinFeat : "Características de Ventana Emergente",
DlgLnkPopResize : "Ajustable",
DlgLnkPopLocation : "Barra de ubicación",
DlgLnkPopMenu : "Barra de Menú",
DlgLnkPopScroll : "Barras de desplazamiento",
DlgLnkPopStatus : "Barra de Estado",
DlgLnkPopToolbar : "Barra de Herramientas",
DlgLnkPopFullScrn : "Pantalla Completa (IE)",
DlgLnkPopDependent : "Dependiente (Netscape)",
DlgLnkPopWidth : "Anchura",
DlgLnkPopHeight : "Altura",
DlgLnkPopLeft : "Posición Izquierda",
DlgLnkPopTop : "Posición Derecha",
DlnLnkMsgNoUrl : "Por favor tipee el vínculo URL",
DlnLnkMsgNoEMail : "Por favor tipee la dirección de e-mail",
DlnLnkMsgNoAnchor : "Por favor seleccione una referencia",
DlnLnkMsgInvPopName : "El nombre debe empezar con un caracter alfanumérico y no debe contener espacios",
// Color Dialog
DlgColorTitle : "Seleccionar Color",
DlgColorBtnClear : "Ninguno",
DlgColorHighlight : "Resaltado",
DlgColorSelected : "Seleccionado",
// Smiley Dialog
DlgSmileyTitle : "Insertar un Emoticon",
// Special Character Dialog
DlgSpecialCharTitle : "Seleccione un caracter especial",
// Table Dialog
DlgTableTitle : "Propiedades de Tabla",
DlgTableRows : "Filas",
DlgTableColumns : "Columnas",
DlgTableBorder : "Tamaño de Borde",
DlgTableAlign : "Alineación",
DlgTableAlignNotSet : "<No establecido>",
DlgTableAlignLeft : "Izquierda",
DlgTableAlignCenter : "Centrado",
DlgTableAlignRight : "Derecha",
DlgTableWidth : "Anchura",
DlgTableWidthPx : "pixeles",
DlgTableWidthPc : "porcentaje",
DlgTableHeight : "Altura",
DlgTableCellSpace : "Esp. e/celdas",
DlgTableCellPad : "Esp. interior",
DlgTableCaption : "Título",
DlgTableSummary : "Síntesis",
DlgTableHeaders : "Encabezados",
DlgTableHeadersNone : "Ninguno",
DlgTableHeadersColumn : "Primera columna",
DlgTableHeadersRow : "Primera fila",
DlgTableHeadersBoth : "Ambas",
// Table Cell Dialog
DlgCellTitle : "Propiedades de Celda",
DlgCellWidth : "Anchura",
DlgCellWidthPx : "pixeles",
DlgCellWidthPc : "porcentaje",
DlgCellHeight : "Altura",
DlgCellWordWrap : "Cortar Línea",
DlgCellWordWrapNotSet : "<No establecido>",
DlgCellWordWrapYes : "Si",
DlgCellWordWrapNo : "No",
DlgCellHorAlign : "Alineación Horizontal",
DlgCellHorAlignNotSet : "<No establecido>",
DlgCellHorAlignLeft : "Izquierda",
DlgCellHorAlignCenter : "Centrado",
DlgCellHorAlignRight: "Derecha",
DlgCellVerAlign : "Alineación Vertical",
DlgCellVerAlignNotSet : "<Not establecido>",
DlgCellVerAlignTop : "Tope",
DlgCellVerAlignMiddle : "Medio",
DlgCellVerAlignBottom : "ie",
DlgCellVerAlignBaseline : "Línea de Base",
DlgCellType : "Tipo de celda",
DlgCellTypeData : "Datos",
DlgCellTypeHeader : "Encabezado",
DlgCellRowSpan : "Abarcar Filas",
DlgCellCollSpan : "Abarcar Columnas",
DlgCellBackColor : "Color de Fondo",
DlgCellBorderColor : "Color de Borde",
DlgCellBtnSelect : "Seleccione...",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "Buscar y Reemplazar",
// Find Dialog
DlgFindTitle : "Buscar",
DlgFindFindBtn : "Buscar",
DlgFindNotFoundMsg : "El texto especificado no ha sido encontrado.",
// Replace Dialog
DlgReplaceTitle : "Reemplazar",
DlgReplaceFindLbl : "Texto a buscar:",
DlgReplaceReplaceLbl : "Reemplazar con:",
DlgReplaceCaseChk : "Coincidir may/min",
DlgReplaceReplaceBtn : "Reemplazar",
DlgReplaceReplAllBtn : "Reemplazar Todo",
DlgReplaceWordChk : "Coincidir toda la palabra",
// Paste Operations / Dialog
PasteErrorCut : "La configuración de seguridad de este navegador no permite la ejecución automática de operaciones de cortado. Por favor use el teclado (Ctrl+X).",
PasteErrorCopy : "La configuración de seguridad de este navegador no permite la ejecución automática de operaciones de copiado. Por favor use el teclado (Ctrl+C).",
PasteAsText : "Pegar como Texto Plano",
PasteFromWord : "Pegar desde Word",
DlgPasteMsg2 : "Por favor pegue dentro del cuadro utilizando el teclado (<STRONG>Ctrl+V</STRONG>); luego presione <STRONG>OK</STRONG>.",
DlgPasteSec : "Debido a la configuración de seguridad de su navegador, el editor no tiene acceso al portapapeles. Es necesario que lo pegue de nuevo en esta ventana.",
DlgPasteIgnoreFont : "Ignorar definiciones de fuentes",
DlgPasteRemoveStyles : "Remover definiciones de estilo",
// Color Picker
ColorAutomatic : "Automático",
ColorMoreColors : "Más Colores...",
// Document Properties
DocProps : "Propiedades del Documento",
// Anchor Dialog
DlgAnchorTitle : "Propiedades de la Referencia",
DlgAnchorName : "Nombre de la Referencia",
DlgAnchorErrorName : "Por favor, complete el nombre de la Referencia",
// Speller Pages Dialog
DlgSpellNotInDic : "No se encuentra en el Diccionario",
DlgSpellChangeTo : "Cambiar a",
DlgSpellBtnIgnore : "Ignorar",
DlgSpellBtnIgnoreAll : "Ignorar Todo",
DlgSpellBtnReplace : "Reemplazar",
DlgSpellBtnReplaceAll : "Reemplazar Todo",
DlgSpellBtnUndo : "Deshacer",
DlgSpellNoSuggestions : "- No hay sugerencias -",
DlgSpellProgress : "Control de Ortografía en progreso...",
DlgSpellNoMispell : "Control finalizado: no se encontraron errores",
DlgSpellNoChanges : "Control finalizado: no se ha cambiado ninguna palabra",
DlgSpellOneChange : "Control finalizado: se ha cambiado una palabra",
DlgSpellManyChanges : "Control finalizado: se ha cambiado %1 palabras",
IeSpellDownload : "Módulo de Control de Ortografía no instalado. ¿Desea descargarlo ahora?",
// Button Dialog
DlgButtonText : "Texto (Valor)",
DlgButtonType : "Tipo",
DlgButtonTypeBtn : "Boton",
DlgButtonTypeSbm : "Enviar",
DlgButtonTypeRst : "Reestablecer",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "Nombre",
DlgCheckboxValue : "Valor",
DlgCheckboxSelected : "Seleccionado",
// Form Dialog
DlgFormName : "Nombre",
DlgFormAction : "Acción",
DlgFormMethod : "Método",
// Select Field Dialog
DlgSelectName : "Nombre",
DlgSelectValue : "Valor",
DlgSelectSize : "Tamaño",
DlgSelectLines : "Lineas",
DlgSelectChkMulti : "Permitir múltiple selección",
DlgSelectOpAvail : "Opciones disponibles",
DlgSelectOpText : "Texto",
DlgSelectOpValue : "Valor",
DlgSelectBtnAdd : "Agregar",
DlgSelectBtnModify : "Modificar",
DlgSelectBtnUp : "Subir",
DlgSelectBtnDown : "Bajar",
DlgSelectBtnSetValue : "Establecer como predeterminado",
DlgSelectBtnDelete : "Eliminar",
// Textarea Dialog
DlgTextareaName : "Nombre",
DlgTextareaCols : "Columnas",
DlgTextareaRows : "Filas",
// Text Field Dialog
DlgTextName : "Nombre",
DlgTextValue : "Valor",
DlgTextCharWidth : "Caracteres de ancho",
DlgTextMaxChars : "Máximo caracteres",
DlgTextType : "Tipo",
DlgTextTypeText : "Texto",
DlgTextTypePass : "Contraseña",
// Hidden Field Dialog
DlgHiddenName : "Nombre",
DlgHiddenValue : "Valor",
// Bulleted List Dialog
BulletedListProp : "Propiedades de Viñetas",
NumberedListProp : "Propiedades de Numeraciones",
DlgLstStart : "Inicio",
DlgLstType : "Tipo",
DlgLstTypeCircle : "Círculo",
DlgLstTypeDisc : "Disco",
DlgLstTypeSquare : "Cuadrado",
DlgLstTypeNumbers : "Números (1, 2, 3)",
DlgLstTypeLCase : "letras en minúsculas (a, b, c)",
DlgLstTypeUCase : "letras en mayúsculas (A, B, C)",
DlgLstTypeSRoman : "Números Romanos (i, ii, iii)",
DlgLstTypeLRoman : "Números Romanos (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "General",
DlgDocBackTab : "Fondo",
DlgDocColorsTab : "Colores y Márgenes",
DlgDocMetaTab : "Meta Información",
DlgDocPageTitle : "Título de Página",
DlgDocLangDir : "Orientación de idioma",
DlgDocLangDirLTR : "Izq. a Derecha (LTR)",
DlgDocLangDirRTL : "Der. a Izquierda (RTL)",
DlgDocLangCode : "Código de Idioma",
DlgDocCharSet : "Codif. de Conjunto de Caracteres",
DlgDocCharSetCE : "Centro Europeo",
DlgDocCharSetCT : "Chino Tradicional (Big5)",
DlgDocCharSetCR : "Cirílico",
DlgDocCharSetGR : "Griego",
DlgDocCharSetJP : "Japonés",
DlgDocCharSetKR : "Coreano",
DlgDocCharSetTR : "Turco",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "Europeo occidental",
DlgDocCharSetOther : "Otra Codificación",
DlgDocDocType : "Encabezado de Tipo de Documento",
DlgDocDocTypeOther : "Otro Encabezado",
DlgDocIncXHTML : "Incluir Declaraciones XHTML",
DlgDocBgColor : "Color de Fondo",
DlgDocBgImage : "URL de Imagen de Fondo",
DlgDocBgNoScroll : "Fondo sin rolido",
DlgDocCText : "Texto",
DlgDocCLink : "Vínculo",
DlgDocCVisited : "Vínculo Visitado",
DlgDocCActive : "Vínculo Activo",
DlgDocMargins : "Márgenes de Página",
DlgDocMaTop : "Tope",
DlgDocMaLeft : "Izquierda",
DlgDocMaRight : "Derecha",
DlgDocMaBottom : "Pie",
DlgDocMeIndex : "Claves de indexación del Documento (separados por comas)",
DlgDocMeDescr : "Descripción del Documento",
DlgDocMeAuthor : "Autor",
DlgDocMeCopy : "Copyright",
DlgDocPreview : "Vista Previa",
// Templates Dialog
Templates : "Plantillas",
DlgTemplatesTitle : "Contenido de Plantillas",
DlgTemplatesSelMsg : "Por favor selecciona la plantilla a abrir en el editor<br>(el contenido actual se perderá):",
DlgTemplatesLoading : "Cargando lista de Plantillas. Por favor, aguarde...",
DlgTemplatesNoTpl : "(No hay plantillas definidas)",
DlgTemplatesReplace : "Reemplazar el contenido actual",
// About Dialog
DlgAboutAboutTab : "Acerca de",
DlgAboutBrowserInfoTab : "Información de Navegador",
DlgAboutLicenseTab : "Licencia",
DlgAboutVersion : "versión",
DlgAboutInfo : "Para mayor información por favor dirigirse a",
// Div Dialog
DlgDivGeneralTab : "General",
DlgDivAdvancedTab : "Avanzado",
DlgDivStyle : "Estilo",
DlgDivInlineStyle : "Estilos CSS",
ScaytTitle : "SCAYT", //MISSING
ScaytTitleOptions : "Options", //MISSING
ScaytTitleLangs : "Languages", //MISSING
ScaytTitleAbout : "About" //MISSING
};
|
gpl-2.0
|
Unofficial-Extend-Project-Mirror/openfoam-extend-Core-OpenFOAM-1.5-dev
|
src/sampling/graphField/makeGraph.C
|
2497
|
/*---------------------------------------------------------------------------*\
========= |
\\ / 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
Global
makeGraph
Description
Write a graph file for a field given the data point locations field,
the field of interest and the name of the field to be used for the
graph file name.
\*---------------------------------------------------------------------------*/
#include "makeGraph.H"
#include "volFields.H"
#include "fvMesh.H"
#include "graph.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
void makeGraph
(
const scalarField& x,
const volScalarField& vsf,
const word& graphFormat
)
{
makeGraph(x, vsf, vsf.name(), graphFormat);
}
void makeGraph
(
const scalarField& x,
const volScalarField& vsf,
const word& name,
const word& graphFormat
)
{
makeGraph(x, vsf.internalField(), name, vsf.path(), graphFormat);
}
void makeGraph
(
const scalarField& x,
const scalarField& sf,
const word& name,
const fileName& path,
const word& graphFormat
)
{
graph
(
name,
"x",
name,
x,
sf
).write(path/name, graphFormat);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
|
gpl-2.0
|
ConceptHaus/atra
|
wp-content/themes/Zephyr/404.php
|
463
|
<?php
define('IS_FULLWIDTH', TRUE);
get_header(); ?>
<div class="l-submain">
<div class="l-submain-h g-html i-cf">
<div class="l-content">
<div class="page-404">
<i class="mdfi_action_explore"></i>
<h1><?php esc_html_e('Error 404 - page not found', 'us') ?></h1>
<p><?php esc_html_e('Ohh... You have requested the page that is no longer there', 'us') ?>.<p>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
|
gpl-2.0
|
worldwideinterweb/joomla-173
|
components/com_joomgallery/views/upload/tmpl/default_java.php
|
8933
|
<?php defined('_JEXEC') or die('Direct Access to this location is not allowed.'); ?>
<!-- --------------------------------------------------------------------------------------------------- -->
<!-- -------- A DUMMY APPLET, THAT ALLOWS THE NAVIGATOR TO CHECK THAT JAVA IS INSTALLED ---------- -->
<!-- -------- If no Java: Java installation is prompted to the user. ---------- -->
<!-- --------------------------------------------------------------------------------------------------- -->
<!--"CONVERTED_APPLET"-->
<!-- HTML CONVERTER -->
<script language="JavaScript" type="text/javascript"><!--
var _info = navigator.userAgent;
var _ns = false;
var _ns6 = false;
var _ie = (_info.indexOf("MSIE") > 0 && _info.indexOf("Win") > 0 && _info.indexOf("Windows 3.1") < 0);
//--></script>
<comment>
<script language="JavaScript" type="text/javascript"><!--
var _ns = (navigator.appName.indexOf("Netscape") >= 0 && ((_info.indexOf("Win") > 0 && _info.indexOf("Win16") < 0 && java.lang.System.getProperty("os.version").indexOf("3.5") < 0) || (_info.indexOf("Sun") > 0) || (_info.indexOf("Linux") > 0) || (_info.indexOf("AIX") > 0) || (_info.indexOf("OS/2") > 0) || (_info.indexOf("IRIX") > 0)));
var _ns6 = ((_ns == true) && (_info.indexOf("Mozilla/5") >= 0));
//--></script>
</comment>
<script language="JavaScript" type="text/javascript"><!--
if (_ie == true) document.writeln('<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH = "0" HEIGHT = "0" NAME = "JUploadApplet" codebase="http://java.sun.com/update/1.5.0/jinstall-1_5-windows-i586.cab#Version=5,0,0,3"><noembed><xmp>');
else if (_ns == true && _ns6 == false) document.writeln('<embed ' +
'type="application/x-java-applet;version=1.5" \
CODE = "wjhk.jupload2.EmptyApplet" \
ARCHIVE = "<?php echo JURI::root(); ?>media/joomgallery/java/wjhk.jupload.jar" \
NAME = "JUploadApplet" \
WIDTH = "0" \
HEIGHT = "0" \
type ="application/x-java-applet;version=1.6" \
scriptable ="false" ' +
'scriptable=false ' +
'pluginspage="http://java.sun.com/products/plugin/index.html#download"><noembed><xmp>');
//--></script>
<applet code = "wjhk.jupload2.EmptyApplet" ARCHIVE = "<?php echo JURI::root(); ?>media/joomgallery/java/wjhk.jupload.jar" WIDTH = "0" HEIGHT = "0" NAME = "JUploadApplet"></xmp>
<param name = CODE VALUE = "wjhk.jupload2.EmptyApplet" >
<param name = ARCHIVE VALUE = "<?php echo JURI::root(); ?>media/joomgallery/java/wjhk.jupload.jar" >
<param name = NAME VALUE = "JUploadApplet" >
<param name = "type" value="application/x-java-applet;version=1.5">
<param name = "scriptable" value="false">
<param name = "type" VALUE="application/x-java-applet;version=1.6">
<param name = "scriptable" VALUE="false">
</xmp>
Java 1.5 or higher plugin required.
</applet>
</noembed>
</embed>
</object>
<form name="JavaUploadForm">
<table width="100%" border="0" cellpadding="4" cellspacing="2" class="adminlist">
<tr>
<td align="center" colspan="2">
<?php echo JText::_('COM_JOOMGALLERY_UPLOAD_JUPLOAD_NOTE'); ?>
</td>
</tr>
<tr>
<td align="right" width="50%">
<?php echo JText::_('COM_JOOMGALLERY_UPLOAD_IMAGE_ASSIGN_TO_CATEGORY'); ?>
</td>
<td align="left">
<?php echo $this->lists['cats']; ?>
</td>
</tr>
<?php if($this->_config->get('jg_delete_original_user') == 2)
{
$sup1 = '¹';
$sup2 = '²';
}
else
{
$sup2 = '¹';
}
if(!$this->_config->get('jg_useruseorigfilename')): ?>
<tr>
<td align="right">
<?php echo JText::_('COM_JOOMGALLERY_UPLOAD_GENERIC_TITLE'); ?>
</td>
<td align="left">
<input type="text" name="imgtitle" size="34" maxlength="256" value="" />
</td>
</tr>
<!--<tr>
<td align="right">
<?php echo JText::_('COM_JOOMGALLERY_COMMON_ALIAS'); ?>
</td>
<td align="left">
<input type="text" name="alias" size="34" maxlength="256" value="" />
</td>
</tr>-->
<?php endif; ?>
<tr>
<td align="right">
<?php echo JText::_('COM_JOOMGALLERY_UPLOAD_GENERIC_DESCRIPTION_OPTIONAL'); ?>
</td>
<td align="left">
<input type="text" name="imgtext" size="34" maxlength="1000" />
</td>
</tr>
<tr>
<td align="right">
<?php echo JText::_('COM_JOOMGALLERY_COMMON_AUTHOR_OWNER'); ?>
</td>
<td align="left">
<b><?php echo JHTML::_('joomgallery.displayname', $this->_user->get('id'), 'upload'); ?></b>
</td>
</tr>
<tr>
<td align="right">
<?php echo JText::_('COM_JOOMGALLERY_COMMON_PUBLISHED'); ?>
</td>
<td align="left">
<?php echo JHTML::_('select.booleanlist', 'published', 'class="inputbox"', 1); ?>
</td>
</tr>
<?php if($this->_config->get('jg_delete_original_user') == 2): ?>
<tr>
<td align="right">
<?php echo JText::_('COM_JOOMGALLERY_UPLOAD_DELETE_ORIGINAL_AFTER_UPLOAD'); ?> ¹
</td>
<td align="left">
<input type="checkbox" name="original_delete" value="1" />
</td>
</tr>
<?php endif;
if($this->_config->get('jg_special_gif_upload') == 1):?>
<tr>
<td align="right">
<?php echo JText::_('COM_JOOMGALLERY_UPLOAD_CREATE_SPECIAL_GIF'); ?> <?php echo $sup2; ?>
</td>
<td align="left">
<input type="checkbox" name="create_special_gif" value="1" />
</td>
</tr>
<?php endif;?>
<tr>
<td colspan="2" align="center">
<div align="center" class="smallgrey">
<?php if($this->_config->get('jg_delete_original_user') == 2): ?>
<?php echo $sup1; ?> <?php echo JText::_('COM_JOOMGALLERY_UPLOAD_DELETE_ORIGINAL_AFTER_UPLOAD_ASTERISK'); ?>
<?php endif;
if($this->_config->get('jg_special_gif_upload') == 1):?>
<br /><?php echo $sup2; ?> <?php echo JText::_('COM_JOOMGALLERY_UPLOAD_CREATE_SPECIAL_GIF_ASTERISK'); ?>
<?php endif;?>
</div>
</td>
</tr>
<tr>
<?php //If 'originals deleted' setted in backend AND the picture has to be resized
//this will be done local within in the applet, so only the detail picture
//will be uploaded
?>
<td colspan="2" align="center">
<applet name="JUpload" code="wjhk.jupload2.JUploadApplet" archive="<?php echo JURI::root(); ?>media/joomgallery/java/wjhk.jupload.jar" width="700" height="600" mayscript>
<param name="postURL" value="<?php echo JURI::root(); ?>index.php?option=<?php echo _JOOM_OPTION; ?>&task=upload&type=java">
<param name="lookAndFeel" value="system">
<param name="showLogWindow" value=false>
<param name="showStatusBar" value="true">
<param name="formdata" value="JavaUploadForm">
<param name="debugLevel" value="0">
<?php if($this->_config->get('jg_msg_upload_type') != 0):?>
<param name="afterUploadURL" value="<?php echo JURI::root(); ?>index.php?option=<?php echo _JOOM_OPTION; ?>&task=sendmessage&type=javaupload">
<param name="urlToSendErrorTo" value="<?php echo JURI::root(); ?>index.php?option=<?php echo _JOOM_OPTION; ?>&task=checkerror&type=javaupload">
<?php else: ?>
<param name="afterUploadURL" value="javascript:alert('<?php echo JText::_('COM_JOOMGALLERY_UPLOAD_OUTPUT_UPLOAD_COMPLETE', true); ?>');">
<?php endif;?>
<param name="nbFilesPerRequest" value="1">
<param name="stringUploadSuccess" value="JOOMGALLERYUPLOADSUCCESS">
<param name="stringUploadError" value="JOOMGALLERYUPLOADERROR (.*)">
<param name="uploadPolicy" value="PictureUploadPolicy">
<param name="pictureTransmitMetadata" value="true">
<param name="allowedFileExtensions" value="jpg/jpeg/jpe/png/gif">
<?php if($this->_config->get('jg_delete_original_user') == 1 && $this->_config->get('jg_resizetomaxwidth')): ?>
<param name="maxPicHeight" value="<?php echo $this->_config->get('jg_maxwidth'); ?>">
<param name="maxPicWidth" value="<?php echo $this->_config->get('jg_maxwidth'); ?>">
<param name="pictureCompressionQuality" value="<?php echo ($this->_config->get('jg_picturequality')/100); ?>">
<?php else: ?>
<param name="pictureCompressionQuality" value="0.8">
<?php endif; ?>
<param name="fileChooserImagePreview" value="false">
<param name="fileChooserIconFromFileContent" value="-1">
<?php if(!$this->cookieNavigator): ?>
<param name="readCookieFromNavigator" value="false">
<param name="specificHeaders" value="Cookie: <?php echo $this->sessionname.'='.$this->sessiontoken;?>">
<?php endif; ?>
Java 1.5 or higher plugin required.
</applet>
</td>
</tr>
</table>
</form>
|
gpl-2.0
|
peternixon/opennms-mirror
|
opennms-services/src/test/java/org/opennms/netmgt/eventd/EventUtilTest.java
|
8917
|
/*******************************************************************************
* 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.netmgt.eventd;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase;
import org.opennms.core.utils.Base64;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.eventd.datablock.EventUtil;
import org.opennms.netmgt.mock.MockEventUtil;
import org.opennms.netmgt.mock.MockNetwork;
import org.opennms.netmgt.mock.MockService;
import org.opennms.netmgt.model.OnmsSeverity;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Tticket;
import org.opennms.netmgt.xml.event.Value;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.springframework.test.context.ContextConfiguration;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:/META-INF/opennms/applicationContext-soa.xml",
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath*:/META-INF/opennms/component-dao.xml",
"classpath:/META-INF/opennms/applicationContext-daemon.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase(dirtiesContext=false)
public class EventUtilTest {
private final MockNetwork m_network = new MockNetwork();
private MockService m_svc;
private Event m_svcLostEvent;
private Event m_nodeDownEvent;
private Event m_bgpBkTnEvent;
@Before
public void setUp() throws Exception {
m_network.createStandardNetwork();
m_svc = m_network.getService(1, "192.168.1.1", "SMTP");
m_svcLostEvent = MockEventUtil.createNodeLostServiceEvent("Test", m_svc);
m_nodeDownEvent = MockEventUtil.createNodeDownEvent("Text", m_network.getNode(1));
m_bgpBkTnEvent = MockEventUtil.createBgpBkTnEvent("Test", m_network.getNode(1), "128.64.32.16", 2);
}
@After
public void tearDown() throws Exception {
}
/*
* Test method for 'org.opennms.netmgt.eventd.EventUtil.getValueAsString(Value)'
*/
@Test
public void testGetValueAsString() {
Value v = new Value();
v.setContent(String.valueOf(Base64.encodeBase64((new String("abcd")).getBytes())));
v.setEncoding("base64");
assertEquals("0x61626364", EventUtil.getValueAsString(v));
}
/*
* Test method for 'org.opennms.netmgt.eventd.EventUtil.escape(String, char)'
*/
@Test
public void testEscape() {
assertEquals("m%onkeys%47rock", EventUtil.escape("m%onkeys/rock", '/'));
}
/*
* Test method for 'org.opennms.netmgt.eventd.EventUtil.getValueOfParm(String, Event)'
*/
@Test
public void testGetValueOfParm() {
String testString = EventUtil.getValueOfParm(EventUtil.TAG_UEI, m_svcLostEvent);
assertEquals(EventConstants.NODE_LOST_SERVICE_EVENT_UEI, testString);
m_svcLostEvent.setSeverity(OnmsSeverity.MINOR.getLabel());
testString = EventUtil.getValueOfParm(EventUtil.TAG_SEVERITY, m_svcLostEvent);
assertEquals("Minor", testString);
Event event = MockEventUtil.createNodeLostServiceEvent("Test", m_svc, "noReasonAtAll");
assertEquals("noReasonAtAll", EventUtil.getNamedParmValue("parm["+EventConstants.PARM_LOSTSERVICE_REASON+"]", event));
}
/*
* Test method for 'org.opennms.netmgt.eventd.EventUtil.expandParms(String, Event)'
*/
@Test
public void testExpandParms() {
String testString = "%uei%:%dpname%:%nodeid%:%interface%:%service%";
String newString = EventUtil.expandParms(testString, m_svcLostEvent);
assertEquals(EventConstants.NODE_LOST_SERVICE_EVENT_UEI + "::1:192.168.1.1:SMTP", newString);
}
/**
* Test method for extracting parm names rather than parm values
*/
@Test
public void testExpandParmNames() {
String testString = "%uei%:%dpname%:%nodeid%:%parm[name-#1]%";
String newString = EventUtil.expandParms(testString, m_bgpBkTnEvent);
assertEquals("http://uei.opennms.org/standards/rfc1657/traps/bgpBackwardTransition::1:.1.3.6.1.2.1.15.3.1.7.128.64.32.16", newString);
}
/**
* Test method for split-and-extract functionality indexed from beginning of name
*/
@Test
public void testSplitAndExtractParmNamePositive() {
String testString = "%uei%:%dpname%:%nodeid%:%parm[name-#1.1]%.%parm[name-#1.3]%.%parm[name-#1.5]%.%parm[name-#1.7]%";
String newString = EventUtil.expandParms(testString, m_bgpBkTnEvent);
assertEquals("http://uei.opennms.org/standards/rfc1657/traps/bgpBackwardTransition::1:1.6.2.15", newString);
}
/**
* Additional test method for split-and-extract functionality indexed from end of name
*/
@Test
public void testSplitAndExtractParmNameNegative() {
String testString = "%uei%:%dpname%:%nodeid%:%parm[name-#1.-4]%.%parm[name-#1.-3]%.%parm[name-#1.-2]%.%parm[name-#1.-1]%";
String newString = EventUtil.expandParms(testString, m_bgpBkTnEvent);
assertEquals("http://uei.opennms.org/standards/rfc1657/traps/bgpBackwardTransition::1:128.64.32.16", newString);
}
/**
* Test method for split-and-extract-range functionality indexed from beginning of name
*/
@Test
public void testSplitAndExtractParmNameRangePositive() {
String testString = "%uei%:%dpname%:%nodeid%:%parm[name-#1.1:4]%";
String newString = EventUtil.expandParms(testString, m_bgpBkTnEvent);
assertEquals("http://uei.opennms.org/standards/rfc1657/traps/bgpBackwardTransition::1:1.3.6.1", newString);
}
/**
* Test method for split-and-extract-range functionality indexed from beginning of name and extending to end
*/
@Test
public void testSplitAndExtractParmNameRangePositiveToEnd() {
String testString = "%uei%:%dpname%:%nodeid%:%parm[name-#1.5:]%";
String newString = EventUtil.expandParms(testString, m_bgpBkTnEvent);
assertEquals("http://uei.opennms.org/standards/rfc1657/traps/bgpBackwardTransition::1:2.1.15.3.1.7.128.64.32.16", newString);
}
/**
* Test method for split-and-extract-range functionality indexed from end of name
*/
@Test
public void testSplitAndExtractParmNameRangeNegative() {
String testString = "%uei%:%dpname%:%nodeid%:%parm[name-#1.-4:2]%";
String newString = EventUtil.expandParms(testString, m_bgpBkTnEvent);
assertEquals("http://uei.opennms.org/standards/rfc1657/traps/bgpBackwardTransition::1:128.64", newString);
}
/**
* Test method for split-and-extract-range functionality indexed from end of name and extending to end
*/
@Test
public void testSplitAndExtractParmNameRangeNegativeToEnd() {
String testString = "%uei%:%dpname%:%nodeid%:%parm[name-#1.-5:]%";
String newString = EventUtil.expandParms(testString, m_bgpBkTnEvent);
assertEquals("http://uei.opennms.org/standards/rfc1657/traps/bgpBackwardTransition::1:7.128.64.32.16", newString);
}
@Test
public void testExpandTticketId() {
String testString = "%tticketid%";
String newString = EventUtil.expandParms(testString, m_nodeDownEvent);
assertEquals("", newString);
Tticket ticket = new Tticket();
ticket.setContent("777");
ticket.setState("1");
m_nodeDownEvent.setTticket(ticket);
newString = EventUtil.expandParms(testString, m_nodeDownEvent);
assertEquals("777", newString);
}
}
|
gpl-2.0
|
mariocontext/elcentro
|
ecp/plugins/gravity-forms-constant-contact/plugin-upgrade.php
|
5109
|
<?php
class RGConstantContactUpgrade{
public static function set_version_info($version_info){
if ( function_exists('set_site_transient') )
set_site_transient("gforms_constantcontact_version", $version_info, 60*60*12);
else
set_transient("gforms_constantcontact_version", $version_info, 60*60*12);
}
public static function check_update($plugin_path, $plugin_slug, $plugin_url, $offering, $key, $version, $option){
$version_info = function_exists('get_site_transient') ? get_site_transient("gforms_constantcontact_version") : get_transient("gforms_constantcontact_version");
//making the remote request for version information
if(!$version_info){
//Getting version number
$version_info = self::get_version_info($offering, $key, $version);
self::set_version_info($version_info);
}
if ($version_info == -1)
return $option;
if(empty($option->response[$plugin_path]))
$option->response[$plugin_path] = new stdClass();
//Empty response means that the key is invalid. Do not queue for upgrade
if(!$version_info["is_valid_key"] || version_compare($version, $version_info["version"], '>=')){
unset($option->response[$plugin_path]);
}
else{
$option->response[$plugin_path]->url = $plugin_url;
$option->response[$plugin_path]->slug = $plugin_slug;
$option->response[$plugin_path]->package = str_replace("{KEY}", $key, $version_info["url"]);
$option->response[$plugin_path]->new_version = $version_info["version"];
$option->response[$plugin_path]->id = "0";
}
return $option;
}
public static function display_plugin_message($message, $is_error = false){
$style = '';
if($is_error)
$style = 'style="background-color: #ffebe8;"';
echo '</tr><tr class="plugin-update-tr"><td colspan="5" class="plugin-update"><div class="update-message" ' . $style . '>' . $message . '</div></td>';
}
public static function display_upgrade_message($plugin_name, $plugin_title, $version, $message, $localization_namespace){
$upgrade_message = $message .' <a class="thickbox" title="'. $plugin_title .'" href="plugin-install.php?tab=plugin-information&plugin=' . $plugin_name . '&TB_iframe=true&width=640&height=808">'. sprintf(__('View version %s Details', $localization_namespace), $version) . '</a>. ';
self::display_plugin_message($upgrade_message);
}
//Displays current version details on Plugin's page
public static function display_changelog($offering, $key, $version){
$body = "key=$key";
$options = array('method' => 'POST', 'timeout' => 3, 'body' => $body);
$options['headers'] = array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset'),
'Content-Length' => strlen($body),
'User-Agent' => 'WordPress/' . get_bloginfo("version"),
'Referer' => get_bloginfo("url")
);
$raw_response = wp_remote_request(GRAVITY_MANAGER_URL . "/changelog.php?" . self::get_remote_request_params($offering, $key, $version), $options);
if ( is_wp_error( $raw_response ) || 200 != $raw_response['response']['code']){
$page_text = sprintf(__("Oops!! Something went wrong.%sPlease try again or %scontact us%s.", 'gravityformsconstantcontact'), "<br/>", "<a href='http://formplugin.com'>", "</a>");
}
else{
$page_text = $raw_response['body'];
if(substr($page_text, 0, 10) != "<!--GFM-->")
$page_text = "";
}
echo stripslashes($page_text);
exit;
}
public static function get_version_info($offering, $key, $version){
$body = "key=$key";
$options = array('method' => 'POST', 'timeout' => 3, 'body' => $body);
$options['headers'] = array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset'),
'Content-Length' => strlen($body),
'User-Agent' => 'WordPress/' . get_bloginfo("version"),
'Referer' => get_bloginfo("url")
);
$url = GRAVITY_MANAGER_URL . "/version.php?" . self::get_remote_request_params($offering, $key, $version);
$raw_response = wp_remote_request($url, $options);
if ( is_wp_error( $raw_response ) || 200 != $raw_response['response']['code'])
return -1;
else
{
$ary = explode("||", $raw_response['body']);
return array("is_valid_key" => $ary[0], "version" => $ary[1], "url" => $ary[2]);
}
}
public static function get_remote_request_params($offering, $key, $version){
global $wpdb;
return sprintf("of=%s&key=%s&v=%s&wp=%s&php=%s&mysql=%s", urlencode($offering), urlencode($key), urlencode($version), urlencode(get_bloginfo("version")), urlencode(phpversion()), urlencode($wpdb->db_version()));
}
}
?>
|
gpl-2.0
|
intelie/esper
|
esper/src/main/java/com/espertech/esper/epl/view/FilterExprView.java
|
4038
|
/**************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package com.espertech.esper.epl.view;
import com.espertech.esper.epl.expression.ExprEvaluator;
import com.espertech.esper.epl.expression.ExprEvaluatorContext;
import com.espertech.esper.client.EventType;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.view.ViewSupport;
import java.util.Iterator;
/**
* Simple filter view filtering events using a filter expression tree.
*/
public class FilterExprView extends ViewSupport
{
private ExprEvaluator exprEvaluator;
private ExprEvaluatorContext exprEvaluatorContext;
/**
* Ctor.
* @param exprEvaluator - Filter expression evaluation impl
* @param exprEvaluatorContext context for expression evalauation
*/
public FilterExprView(ExprEvaluator exprEvaluator, ExprEvaluatorContext exprEvaluatorContext)
{
this.exprEvaluator = exprEvaluator;
this.exprEvaluatorContext = exprEvaluatorContext;
}
public EventType getEventType()
{
return parent.getEventType();
}
public Iterator<EventBean> iterator()
{
return new FilterExprViewIterator(parent.iterator(), exprEvaluator, exprEvaluatorContext);
}
public void update(EventBean[] newData, EventBean[] oldData)
{
EventBean[] filteredNewData = filterEvents(exprEvaluator, newData, true, exprEvaluatorContext);
EventBean[] filteredOldData = filterEvents(exprEvaluator, oldData, false, exprEvaluatorContext);
if ((filteredNewData != null) || (filteredOldData != null))
{
this.updateChildren(filteredNewData, filteredOldData);
}
}
/**
* Filters events using the supplied evaluator.
* @param exprEvaluator - evaluator to use
* @param events - events to filter
* @param isNewData - true to indicate filter new data (istream) and not old data (rstream)
* @param exprEvaluatorContext context for expression evalauation
* @return filtered events, or null if no events got through the filter
*/
protected static EventBean[] filterEvents(ExprEvaluator exprEvaluator, EventBean[] events, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext)
{
if (events == null)
{
return null;
}
EventBean[] evalEventArr = new EventBean[1];
boolean passResult[] = new boolean[events.length];
int passCount = 0;
for (int i = 0; i < events.length; i++)
{
evalEventArr[0] = events[i];
Boolean pass = (Boolean) exprEvaluator.evaluate(evalEventArr, isNewData, exprEvaluatorContext);
if ((pass != null) && (pass))
{
passResult[i] = true;
passCount++;
}
}
if (passCount == 0)
{
return null;
}
if (passCount == events.length)
{
return events;
}
EventBean[] resultArray = new EventBean[passCount];
int count = 0;
for (int i = 0; i < passResult.length; i++)
{
if (passResult[i])
{
resultArray[count] = events[i];
count++;
}
}
return resultArray;
}
}
|
gpl-2.0
|
atodorov/anaconda
|
tests/nosetests/pyanaconda_tests/signal_test.py
|
5383
|
#
# Martin Kolman <mkolman@redhat.com>
#
# Copyright 2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties 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. Any Red Hat
# trademarks that are incorporated in the source code or documentation are not
# subject to the GNU General Public License and may only be used or replicated
# with the express permission of Red Hat, Inc.
#
# Test the Python-based signal and slot implementation.
#
import unittest
from pyanaconda.core.signal import Signal
class FooClass(object):
def __init__(self):
self._var = None
@property
def var(self):
return self._var
def set_var(self, value):
self._var = value
class SignalTestCase(unittest.TestCase):
def setUp(self):
self.var = None
def method_test(self):
"""Test if a method can be correctly connected to a signal."""
signal = Signal()
foo = FooClass()
self.assertIsNone(foo.var)
# connect the signal
signal.connect(foo.set_var)
# trigger the signal
signal.emit("bar")
# check if the callback triggered correctly
self.assertEqual(foo.var, "bar")
# try to trigger the signal again
signal.emit("baz")
self.assertEqual(foo.var, "baz")
# now try to disconnect the signal
signal.disconnect(foo.set_var)
# check that calling the signal again
# no longer triggers the callback
signal.emit("anaconda")
self.assertEqual(foo.var, "baz")
def function_test(self):
"""Test if a local function can be correctly connected to a signal."""
# create a local function
def set_var(value):
self.var = value
signal = Signal()
self.assertIsNone(self.var)
# connect the signal
signal.connect(set_var)
# trigger the signal
signal.emit("bar")
# check if the callback triggered correctly
self.assertEqual(self.var, "bar")
# try to trigger the signal again
signal.emit("baz")
self.assertEqual(self.var, "baz")
# now try to disconnect the signal
signal.disconnect(set_var)
# check that calling the signal again
# no longer triggers the callback
signal.emit("anaconda")
self.assertEqual(self.var, "baz")
def lambda_test(self):
"""Test if a lambda can be correctly connected to a signal."""
foo = FooClass()
signal = Signal()
self.assertIsNone(foo.var)
# connect the signal
# pylint: disable=unnecessary-lambda
lambda_instance = lambda x: foo.set_var(x)
signal.connect(lambda_instance)
# trigger the signal
signal.emit("bar")
# check if the callback triggered correctly
self.assertEqual(foo.var, "bar")
# try to trigger the signal again
signal.emit("baz")
self.assertEqual(foo.var, "baz")
# now try to disconnect the signal
signal.disconnect(lambda_instance)
# check that calling the signal again
# no longer triggers the callback
signal.emit("anaconda")
self.assertEqual(foo.var, "baz")
def clear_test(self):
"""Test if the clear() method correctly clears any connected callbacks."""
def set_var(value):
self.var = value
signal = Signal()
foo = FooClass()
lambda_foo = FooClass()
self.assertIsNone(foo.var)
self.assertIsNone(lambda_foo.var)
self.assertIsNone(self.var)
# connect the callbacks
signal.connect(set_var)
signal.connect(foo.set_var)
# pylint: disable=unnecessary-lambda
signal.connect(lambda x: lambda_foo.set_var(x))
# trigger the signal
signal.emit("bar")
# check that the callbacks were triggered
self.assertEqual(self.var, "bar")
self.assertEqual(foo.var, "bar")
self.assertEqual(lambda_foo.var, "bar")
# clear the callbacks
signal.clear()
# trigger the signal again
signal.emit("anaconda")
# check that the callbacks were not triggered
self.assertEqual(self.var, "bar")
self.assertEqual(foo.var, "bar")
self.assertEqual(lambda_foo.var, "bar")
def signal_chain_test(self):
"""Check if signals can be chained together."""
foo = FooClass()
self.assertIsNone(foo.var)
signal1 = Signal()
signal1.connect(foo.set_var)
signal2 = Signal()
signal2.connect(signal1.emit)
signal3 = Signal()
signal3.connect(signal2.emit)
# trigger the chain
signal3.emit("bar")
# check if the initial callback was triggered
self.assertEqual(foo.var, "bar")
|
gpl-2.0
|
Orphis/ppsspp
|
Qt/Debugger/debugger_memorytex.cpp
|
2606
|
#include "debugger_memorytex.h"
#include "gfx/GLStateCache.h"
#include "gfx/gl_common.h"
#include "gfx/gl_lost_manager.h"
#include "ui_debugger_memorytex.h"
#include "Core/MemMap.h"
#include <QImage>
#include <QTimer>
#include "Core/HLE/sceDisplay.h"
#include "GPU/GPUInterface.h"
#include "base/display.h"
Debugger_MemoryTex::Debugger_MemoryTex(QWidget *parent) :
QDialog(parent),
ui(new Ui::Debugger_MemoryTex)
{
ui->setupUi(this);
}
Debugger_MemoryTex::~Debugger_MemoryTex()
{
delete ui;
}
void Debugger_MemoryTex::ShowTex(const GPUgstate &state)
{
ui->texaddr->setText(QString("%1").arg(state.texaddr[0] & 0xFFFFFF,8,16,QChar('0')));
ui->texbufwidth0->setText(QString("%1").arg(state.texbufwidth[0] & 0xFFFFFF,8,16,QChar('0')));
ui->texformat->setText(QString("%1").arg(state.texformat & 0xFFFFFF,8,16,QChar('0')));
ui->texsize->setText(QString("%1").arg(state.texsize[0] & 0xFFFFFF,8,16,QChar('0')));
ui->texmode->setText(QString("%1").arg(state.texmode & 0xFFFFFF,8,16,QChar('0')));
ui->clutformat->setText(QString("%1").arg(state.clutformat & 0xFFFFFF,8,16,QChar('0')));
ui->clutaddr->setText(QString("%1").arg(state.clutaddr & 0xFFFFFF,8,16,QChar('0')));
ui->clutaddrupper->setText(QString("%1").arg(state.clutaddrupper & 0xFFFFFF,8,16,QChar('0')));
ui->loadclut->setText(QString("%1").arg(state.loadclut & 0xFFFFFF,8,16,QChar('0')));
on_readBtn_clicked();
show();
}
void Debugger_MemoryTex::on_readBtn_clicked()
{
GPUgstate state;
state.texaddr[0] = ui->texaddr->text().toUInt(0,16);
state.texbufwidth[0] = ui->texbufwidth0->text().toUInt(0,16);
state.texformat = ui->texformat->text().toUInt(0,16);
state.texsize[0] = ui->texsize->text().toUInt(0,16);
state.texmode = ui->texmode->text().toUInt(0,16);
state.clutformat = ui->clutformat->text().toUInt(0,16);
state.clutaddr = ui->clutaddr->text().toUInt(0,16);
state.clutaddrupper = ui->clutaddrupper->text().toUInt(0,16);
state.loadclut = ui->loadclut->text().toUInt(0,16);
int bufW = state.texbufwidth[0] & 0x3ff;
int w = 1 << (state.texsize[0] & 0xf);
int h = 1 << ((state.texsize[0]>>8) & 0xf);
w = std::max(bufW,w);
uchar* newData = new uchar[w*h*4];
if(gpu->DecodeTexture(newData, state))
{
QImage img = QImage(newData, w, h, w*4, QImage::Format_ARGB32); // EmuThread_GrabBackBuffer();
QPixmap pixmap = QPixmap::fromImage(img);
ui->textureImg->setPixmap(pixmap);
ui->textureImg->setMinimumWidth(pixmap.width());
ui->textureImg->setMinimumHeight(pixmap.height());
ui->textureImg->setMaximumWidth(pixmap.width());
ui->textureImg->setMaximumHeight(pixmap.height());
}
delete[] newData;
}
|
gpl-2.0
|
mxkmp29/joomla-cms
|
libraries/cms/html/html.php
|
33535
|
<?php
/**
* @package Joomla.Libraries
* @subpackage HTML
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
use Joomla\Utilities\ArrayHelper;
jimport('joomla.environment.browser');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.path');
/**
* Utility class for all HTML drawing classes
*
* @since 1.5
*/
abstract class JHtml
{
/**
* Option values related to the generation of HTML output. Recognized
* options are:
* fmtDepth, integer. The current indent depth.
* fmtEol, string. The end of line string, default is linefeed.
* fmtIndent, string. The string to use for indentation, default is
* tab.
*
* @var array
* @since 1.5
*/
public static $formatOptions = array('format.depth' => 0, 'format.eol' => "\n", 'format.indent' => "\t");
/**
* An array to hold included paths
*
* @var string[]
* @since 1.5
*/
protected static $includePaths = array();
/**
* An array to hold method references
*
* @var callable[]
* @since 1.6
*/
protected static $registry = array();
/**
* Method to extract a key
*
* @param string $key The name of helper method to load, (prefix).(class).function
* prefix and class are optional and can be used to load custom html helpers.
*
* @return array Contains lowercase key, prefix, file, function.
*
* @since 1.6
*/
protected static function extract($key)
{
$key = preg_replace('#[^A-Z0-9_\.]#i', '', $key);
// Check to see whether we need to load a helper file
$parts = explode('.', $key);
$prefix = (count($parts) == 3 ? array_shift($parts) : 'JHtml');
$file = (count($parts) == 2 ? array_shift($parts) : '');
$func = array_shift($parts);
return array(strtolower($prefix . '.' . $file . '.' . $func), $prefix, $file, $func);
}
/**
* Class loader method
*
* Additional arguments may be supplied and are passed to the sub-class.
* Additional include paths are also able to be specified for third-party use
*
* @param string $key The name of helper method to load, (prefix).(class).function
* prefix and class are optional and can be used to load custom
* html helpers.
*
* @return mixed Result of JHtml::call($function, $args)
*
* @since 1.5
* @throws InvalidArgumentException
*/
public static function _($key)
{
list($key, $prefix, $file, $func) = static::extract($key);
if (array_key_exists($key, static::$registry))
{
$function = static::$registry[$key];
$args = func_get_args();
// Remove function name from arguments
array_shift($args);
return static::call($function, $args);
}
$className = $prefix . ucfirst($file);
if (!class_exists($className))
{
$path = JPath::find(static::$includePaths, strtolower($file) . '.php');
if (!$path)
{
throw new InvalidArgumentException(sprintf('%s %s not found.', $prefix, $file), 500);
}
JLoader::register($className, $path);
if (!class_exists($className))
{
throw new InvalidArgumentException(sprintf('%s not found.', $className), 500);
}
}
$toCall = array($className, $func);
if (!is_callable($toCall))
{
throw new InvalidArgumentException(sprintf('%s::%s not found.', $className, $func), 500);
}
static::register($key, $toCall);
$args = func_get_args();
// Remove function name from arguments
array_shift($args);
return static::call($toCall, $args);
}
/**
* Registers a function to be called with a specific key
*
* @param string $key The name of the key
* @param string $function Function or method
*
* @return boolean True if the function is callable
*
* @since 1.6
*/
public static function register($key, $function)
{
list($key) = static::extract($key);
if (is_callable($function))
{
static::$registry[$key] = $function;
return true;
}
return false;
}
/**
* Removes a key for a method from registry.
*
* @param string $key The name of the key
*
* @return boolean True if a set key is unset
*
* @since 1.6
*/
public static function unregister($key)
{
list($key) = static::extract($key);
if (isset(static::$registry[$key]))
{
unset(static::$registry[$key]);
return true;
}
return false;
}
/**
* Test if the key is registered.
*
* @param string $key The name of the key
*
* @return boolean True if the key is registered.
*
* @since 1.6
*/
public static function isRegistered($key)
{
list($key) = static::extract($key);
return isset(static::$registry[$key]);
}
/**
* Function caller method
*
* @param callable $function Function or method to call
* @param array $args Arguments to be passed to function
*
* @return mixed Function result or false on error.
*
* @see https://secure.php.net/manual/en/function.call-user-func-array.php
* @since 1.6
* @throws InvalidArgumentException
*/
protected static function call($function, $args)
{
if (!is_callable($function))
{
throw new InvalidArgumentException('Function not supported', 500);
}
// PHP 5.3 workaround
$temp = array();
foreach ($args as &$arg)
{
$temp[] = &$arg;
}
return call_user_func_array($function, $temp);
}
/**
* Write a `<a>` element
*
* @param string $url The relative URL to use for the href attribute
* @param string $text The target attribute to use
* @param array|string $attribs Attributes to be added to the `<a>` element
*
* @return string
*
* @since 1.5
*/
public static function link($url, $text, $attribs = null)
{
if (is_array($attribs))
{
$attribs = ArrayHelper::toString($attribs);
}
return '<a href="' . $url . '" ' . $attribs . '>' . $text . '</a>';
}
/**
* Write a `<iframe>` element
*
* @param string $url The relative URL to use for the src attribute.
* @param string $name The target attribute to use.
* @param array|string $attribs Attributes to be added to the `<iframe>` element
* @param string $noFrames The message to display if the iframe tag is not supported.
*
* @return string
*
* @since 1.5
*/
public static function iframe($url, $name, $attribs = null, $noFrames = '')
{
if (is_array($attribs))
{
$attribs = ArrayHelper::toString($attribs);
}
return '<iframe src="' . $url . '" ' . $attribs . ' name="' . $name . '">' . $noFrames . '</iframe>';
}
/**
* Include version with MD5SUM file in path.
*
* @param string $path Folder name to search into (images, css, js, ...).
*
* @return string Query string to add.
*
* @since __DEPLOY_VERSION__
*
* @deprecated 4.0 Usage of MD5SUM files is deprecated, use version instead.
*/
protected static function getMd5Version($path)
{
$md5 = dirname($path) . '/MD5SUM';
if (file_exists($md5))
{
JLog::add('Usage of MD5SUM files is deprecated, use version instead.', JLog::WARNING, 'deprecated');
return '?' . file_get_contents($md5);
}
return '';
}
/**
* Compute the files to be included
*
* @param string $folder Folder name to search in (i.e. images, css, js).
* @param string $file Path to file.
* @param boolean $relative Flag if the path to the file is relative to the /media folder (and searches in template).
* @param boolean $detect_browser Flag if the browser should be detected to include specific browser files.
* @param boolean $detect_debug Flag if debug mode is enabled to include uncompressed files if debug is on.
*
* @return array files to be included.
*
* @see JBrowser
* @since 1.6
*/
protected static function includeRelativeFiles($folder, $file, $relative, $detect_browser, $detect_debug)
{
// If http is present in filename just return it as an array
if (strpos($file, 'http') === 0 || strpos($file, '//') === 0)
{
return array($file);
}
// Extract extension and strip the file
$strip = JFile::stripExt($file);
$ext = JFile::getExt($file);
// Prepare array of files
$includes = array();
// Detect browser and compute potential files
if ($detect_browser)
{
$navigator = JBrowser::getInstance();
$browser = $navigator->getBrowser();
$major = $navigator->getMajor();
$minor = $navigator->getMinor();
// Try to include files named filename.ext, filename_browser.ext, filename_browser_major.ext, filename_browser_major_minor.ext
// where major and minor are the browser version names
$potential = array(
$strip,
$strip . '_' . $browser,
$strip . '_' . $browser . '_' . $major,
$strip . '_' . $browser . '_' . $major . '_' . $minor,
);
}
else
{
$potential = array($strip);
}
// If relative search in template directory or media directory
if ($relative)
{
// Get the template
$template = JFactory::getApplication()->getTemplate();
// For each potential files
foreach ($potential as $strip)
{
$files = array();
// Detect debug mode
if ($detect_debug && JFactory::getConfig()->get('debug'))
{
/*
* Detect if we received a file in the format name.min.ext
* If so, strip the .min part out, otherwise append -uncompressed
*/
if (strrpos($strip, '.min', '-4'))
{
$position = strrpos($strip, '.min', '-4');
$filename = str_replace('.min', '.', $strip, $position);
$files[] = $filename . $ext;
}
else
{
$files[] = $strip . '-uncompressed.' . $ext;
}
}
$files[] = $strip . '.' . $ext;
/*
* Loop on 1 or 2 files and break on first found.
* Add the content of the MD5SUM file located in the same folder to url to ensure cache browser refresh
* This MD5SUM file must represent the signature of the folder content
*/
foreach ($files as $file)
{
// If the file is in the template folder
$path = JPATH_THEMES . "/$template/$folder/$file";
if (file_exists($path))
{
$includes[] = JUri::base(true) . "/templates/$template/$folder/$file" . static::getMd5Version($path);
break;
}
else
{
// If the file contains any /: it can be in an media extension subfolder
if (strpos($file, '/'))
{
// Divide the file extracting the extension as the first part before /
list($extension, $file) = explode('/', $file, 2);
// If the file yet contains any /: it can be a plugin
if (strpos($file, '/'))
{
// Divide the file extracting the element as the first part before /
list($element, $file) = explode('/', $file, 2);
// Try to deal with plugins group in the media folder
$path = JPATH_ROOT . "/media/$extension/$element/$folder/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/media/$extension/$element/$folder/$file" . static::getMd5Version($path);
break;
}
// Try to deal with classical file in a media subfolder called element
$path = JPATH_ROOT . "/media/$extension/$folder/$element/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/media/$extension/$folder/$element/$file" . static::getMd5Version($path);
break;
}
// Try to deal with system files in the template folder
$path = JPATH_THEMES . "/$template/$folder/system/$element/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/templates/$template/$folder/system/$element/$file" . static::getMd5Version($path);
break;
}
// Try to deal with system files in the media folder
$path = JPATH_ROOT . "/media/system/$folder/$element/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/media/system/$folder/$element/$file" . static::getMd5Version($path);
break;
}
}
else
{
// Try to deals in the extension media folder
$path = JPATH_ROOT . "/media/$extension/$folder/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/media/$extension/$folder/$file" . static::getMd5Version($path);
break;
}
// Try to deal with system files in the template folder
$path = JPATH_THEMES . "/$template/$folder/system/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/templates/$template/$folder/system/$file" . static::getMd5Version($path);
break;
}
// Try to deal with system files in the media folder
$path = JPATH_ROOT . "/media/system/$folder/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/media/system/$folder/$file" . static::getMd5Version($path);
break;
}
}
}
// Try to deal with system files in the media folder
else
{
$path = JPATH_ROOT . "/media/system/$folder/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/media/system/$folder/$file" . static::getMd5Version($path);
break;
}
}
}
}
}
}
// If not relative and http is not present in filename
else
{
foreach ($potential as $strip)
{
$files = array();
// Detect debug mode
if ($detect_debug && JFactory::getConfig()->get('debug'))
{
/*
* Detect if we received a file in the format name.min.ext
* If so, strip the .min part out, otherwise append -uncompressed
*/
if (strrpos($strip, '.min', '-4'))
{
$position = strrpos($strip, '.min', '-4');
$filename = str_replace('.min', '.', $strip, $position);
$files[] = $filename . $ext;
}
else
{
$files[] = $strip . '-uncompressed.' . $ext;
}
}
$files[] = $strip . '.' . $ext;
/*
* Loop on 1 or 2 files and break on first found.
* Add the content of the MD5SUM file located in the same folder to url to ensure cache browser refresh
* This MD5SUM file must represent the signature of the folder content
*/
foreach ($files as $file)
{
$path = JPATH_ROOT . "/$file";
if (file_exists($path))
{
$includes[] = JUri::root(true) . "/$file" . static::getMd5Version($path);
break;
}
}
}
}
return $includes;
}
/**
* Write a `<img>` element
*
* @param string $file The relative or absolute URL to use for the src attribute.
* @param string $alt The alt text.
* @param array|string $attribs Attributes to be added to the `<img>` element
* @param boolean $relative Flag if the path to the file is relative to the /media folder (and searches in template).
* @param integer $returnPath Defines the return value for the method:
* -1: Returns a `<img>` tag without looking for relative files
* 0: Returns a `<img>` tag while searching for relative files
* 1: Returns the file path to the image while searching for relative files
*
* @return string
*
* @since 1.5
*/
public static function image($file, $alt, $attribs = null, $relative = false, $returnPath = 0)
{
$returnPath = (int) $returnPath;
if ($returnPath !== -1)
{
$includes = static::includeRelativeFiles('images', $file, $relative, false, false);
$file = count($includes) ? $includes[0] : null;
}
// If only path is required
if ($returnPath)
{
return $file;
}
return '<img src="' . $file . '" alt="' . $alt . '" ' . trim((is_array($attribs) ? ArrayHelper::toString($attribs) : $attribs) . ' /') . '>';
}
/**
* Write a `<link>` element to load a CSS file
*
* @param string $file Path to file
* @param array $attribs Attributes to be added to the `<link>` element
* @param boolean $relative Flag if the path to the file is relative to the /media folder (and searches in template).
* @param boolean $returnPath Flag if the file path should be returned or if the file should be included in the global JDocument instance
* @param boolean $detect_browser Flag if the browser should be detected to include specific browser files.
* This will try to include file, `file_*browser*`, `file_*browser*_*major*`, `file_*browser*_*major*_*minor*`
* <table>
* <tr><th>Navigator</th> <th>browser</th> <th>major.minor</th></tr>
*
* <tr><td>Safari 3.0.x</td> <td>konqueror</td> <td>522.x</td></tr>
* <tr><td>Safari 3.1.x and 3.2.x</td> <td>konqueror</td> <td>525.x</td></tr>
* <tr><td>Safari 4.0 to 4.0.2</td> <td>konqueror</td> <td>530.x</td></tr>
* <tr><td>Safari 4.0.3 to 4.0.4</td> <td>konqueror</td> <td>531.x</td></tr>
* <tr><td>iOS 4.0 Safari</td> <td>konqueror</td> <td>532.x</td></tr>
* <tr><td>Safari 5.0</td> <td>konqueror</td> <td>533.x</td></tr>
*
* <tr><td>Google Chrome 1.0</td> <td>konqueror</td> <td>528.x</td></tr>
* <tr><td>Google Chrome 2.0</td> <td>konqueror</td> <td>530.x</td></tr>
* <tr><td>Google Chrome 3.0 and 4.x</td> <td>konqueror</td> <td>532.x</td></tr>
* <tr><td>Google Chrome 5.0</td> <td>konqueror</td> <td>533.x</td></tr>
*
* <tr><td>Internet Explorer 5.5</td> <td>msie</td> <td>5.5</td></tr>
* <tr><td>Internet Explorer 6.x</td> <td>msie</td> <td>6.x</td></tr>
* <tr><td>Internet Explorer 7.x</td> <td>msie</td> <td>7.x</td></tr>
* <tr><td>Internet Explorer 8.x</td> <td>msie</td> <td>8.x</td></tr>
*
* <tr><td>Firefox</td> <td>mozilla</td> <td>5.0</td></tr>
* </table>
* @param boolean $detect_debug Flag if debug mode is enabled to include uncompressed files if debug is on.
*
* @return array|string|null nothing if $returnPath is false, null, path or array of path if specific CSS browser files were detected
*
* @see JBrowser
* @since 1.5
*/
public static function stylesheet($file, $attribs = array(), $relative = false, $returnPath = false, $detect_browser = true, $detect_debug = true)
{
$includes = static::includeRelativeFiles('css', $file, $relative, $detect_browser, $detect_debug);
// If only path is required
if ($returnPath)
{
if (count($includes) == 0)
{
return;
}
if (count($includes) == 1)
{
return $includes[0];
}
return $includes;
}
// If inclusion is required
$document = JFactory::getDocument();
foreach ($includes as $include)
{
$document->addStyleSheet($include, 'text/css', null, $attribs);
}
}
/**
* Write a `<script>` element to load a JavaScript file
*
* @param string $file Path to file.
* @param array $options Array of options. Example: array('version' => 'auto', 'conditional' => 'lt IE 9')
* @param array $attribs Array of attributes. Example: array('id' => 'scriptid', 'async' => 'async', 'data-test' => 1)
*
* @return array|string|null Nothing if $returnPath is false, null, path or array of path if specific JavaScript browser files were detected
*
* @see JHtml::stylesheet()
* @since 1.5
* @deprecated 4.0 The (file, framework, relative, pathOnly, detectBrowser, detectDebug) method signature is deprecated,
* use (file, options, attributes) instead.
*/
public static function script($file, $options = array(), $attribs = array())
{
// B/C before __DEPLOY_VERSION__
if (!is_array($options) && !is_array($attribs))
{
JLog::add('The script method signature used has changed, use (file, options, attributes) instead.', JLog::WARNING, 'deprecated');
$argList = func_get_args();
$options = array();
$attribs = array();
// Old parameters.
$options['framework'] = isset($argList[1]) ? $argList[1] : false;
$options['relative'] = isset($argList[2]) ? $argList[2] : false;
$options['pathOnly'] = isset($argList[3]) ? $argList[3] : false;
$options['detectBrowser'] = isset($argList[4]) ? $argList[4] : true;
$options['detectDebug'] = isset($argList[5]) ? $argList[5] : true;
}
else
{
$options['framework'] = isset($options['framework']) ? $options['framework'] : false;
$options['relative'] = isset($options['relative']) ? $options['relative'] : false;
$options['pathOnly'] = isset($options['pathOnly']) ? $options['pathOnly'] : false;
$options['detectBrowser'] = isset($options['detectBrowser']) ? $options['detectBrowser'] : true;
$options['detectDebug'] = isset($options['detectDebug']) ? $options['detectDebug'] : true;
}
// Include MooTools framework
if ($options['framework'])
{
static::_('behavior.framework');
}
$includes = static::includeRelativeFiles('js', $file, $options['relative'], $options['detectBrowser'], $options['detectDebug']);
// If only path is required
if ($options['pathOnly'])
{
if (count($includes) === 0)
{
return;
}
if (count($includes) === 1)
{
return $includes[0];
}
return $includes;
}
// If inclusion is required
$document = JFactory::getDocument();
foreach ($includes as $include)
{
// If there is already a version hash in the script reference (by using deprecated MD5SUM).
if ($pos = strpos($include, '?') !== false)
{
$options['version'] = substr($include, $pos + 1);
}
$document->addScript($include, $options, $attribs);
}
}
/**
* Set format related options.
*
* Updates the formatOptions array with all valid values in the passed array.
*
* @param array $options Option key/value pairs.
*
* @return void
*
* @see JHtml::$formatOptions
* @since 1.5
*/
public static function setFormatOptions($options)
{
foreach ($options as $key => $val)
{
if (isset(static::$formatOptions[$key]))
{
static::$formatOptions[$key] = $val;
}
}
}
/**
* Returns formated date according to a given format and time zone.
*
* @param string $input String in a format accepted by date(), defaults to "now".
* @param string $format The date format specification string (see {@link PHP_MANUAL#date}).
* @param mixed $tz Time zone to be used for the date. Special cases: boolean true for user
* setting, boolean false for server setting.
* @param boolean $gregorian True to use Gregorian calendar.
*
* @return string A date translated by the given format and time zone.
*
* @see strftime
* @since 1.5
*/
public static function date($input = 'now', $format = null, $tz = true, $gregorian = false)
{
// Get some system objects.
$config = JFactory::getConfig();
$user = JFactory::getUser();
// UTC date converted to user time zone.
if ($tz === true)
{
// Get a date object based on UTC.
$date = JFactory::getDate($input, 'UTC');
// Set the correct time zone based on the user configuration.
$date->setTimezone(new DateTimeZone($user->getParam('timezone', $config->get('offset'))));
}
// UTC date converted to server time zone.
elseif ($tz === false)
{
// Get a date object based on UTC.
$date = JFactory::getDate($input, 'UTC');
// Set the correct time zone based on the server configuration.
$date->setTimezone(new DateTimeZone($config->get('offset')));
}
// No date conversion.
elseif ($tz === null)
{
$date = JFactory::getDate($input);
}
// UTC date converted to given time zone.
else
{
// Get a date object based on UTC.
$date = JFactory::getDate($input, 'UTC');
// Set the correct time zone based on the server configuration.
$date->setTimezone(new DateTimeZone($tz));
}
// If no format is given use the default locale based format.
if (!$format)
{
$format = JText::_('DATE_FORMAT_LC1');
}
// $format is an existing language key
elseif (JFactory::getLanguage()->hasKey($format))
{
$format = JText::_($format);
}
if ($gregorian)
{
return $date->format($format, true);
}
return $date->calendar($format, true);
}
/**
* Creates a tooltip with an image as button
*
* @param string $tooltip The tip string.
* @param mixed $title The title of the tooltip or an associative array with keys contained in
* {'title','image','text','href','alt'} and values corresponding to parameters of the same name.
* @param string $image The image for the tip, if no text is provided.
* @param string $text The text for the tip.
* @param string $href A URL that will be used to create the link.
* @param string $alt The alt attribute for img tag.
* @param string $class CSS class for the tool tip.
*
* @return string
*
* @since 1.5
*/
public static function tooltip($tooltip, $title = '', $image = 'tooltip.png', $text = '', $href = '', $alt = 'Tooltip', $class = 'hasTooltip')
{
if (is_array($title))
{
foreach (array('image', 'text', 'href', 'alt', 'class') as $param)
{
if (isset($title[$param]))
{
$$param = $title[$param];
}
}
if (isset($title['title']))
{
$title = $title['title'];
}
else
{
$title = '';
}
}
if (!$text)
{
$alt = htmlspecialchars($alt, ENT_COMPAT, 'UTF-8');
$text = static::image($image, $alt, null, true);
}
if ($href)
{
$tip = '<a href="' . $href . '">' . $text . '</a>';
}
else
{
$tip = $text;
}
if ($class == 'hasTip')
{
// Still using MooTools tooltips!
$tooltip = htmlspecialchars($tooltip, ENT_COMPAT, 'UTF-8');
if ($title)
{
$title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
$tooltip = $title . '::' . $tooltip;
}
}
else
{
$tooltip = self::tooltipText($title, $tooltip, 0);
}
return '<span class="' . $class . '" title="' . $tooltip . '">' . $tip . '</span>';
}
/**
* Converts a double colon separated string or 2 separate strings to a string ready for bootstrap tooltips
*
* @param string $title The title of the tooltip (or combined '::' separated string).
* @param string $content The content to tooltip.
* @param boolean $translate If true will pass texts through JText.
* @param boolean $escape If true will pass texts through htmlspecialchars.
*
* @return string The tooltip string
*
* @since 3.1.2
*/
public static function tooltipText($title = '', $content = '', $translate = true, $escape = true)
{
// Initialise return value.
$result = '';
// Don't process empty strings
if ($content != '' || $title != '')
{
// Split title into title and content if the title contains '::' (old Mootools format).
if ($content == '' && !(strpos($title, '::') === false))
{
list($title, $content) = explode('::', $title, 2);
}
// Pass texts through JText if required.
if ($translate)
{
$title = JText::_($title);
$content = JText::_($content);
}
// Use only the content if no title is given.
if ($title == '')
{
$result = $content;
}
// Use only the title, if title and text are the same.
elseif ($title == $content)
{
$result = '<strong>' . $title . '</strong>';
}
// Use a formatted string combining the title and content.
elseif ($content != '')
{
$result = '<strong>' . $title . '</strong><br />' . $content;
}
else
{
$result = $title;
}
// Escape everything, if required.
if ($escape)
{
$result = htmlspecialchars($result);
}
}
return $result;
}
/**
* Displays a calendar control field
*
* @param string $value The date value
* @param string $name The name of the text field
* @param string $id The id of the text field
* @param string $format The date format
* @param mixed $attribs Additional HTML attributes
*
* @return string HTML markup for a calendar field
*
* @since 1.5
*/
public static function calendar($value, $name, $id, $format = '%Y-%m-%d', $attribs = null)
{
static $done;
if ($done === null)
{
$done = array();
}
$readonly = isset($attribs['readonly']) && $attribs['readonly'] == 'readonly';
$disabled = isset($attribs['disabled']) && $attribs['disabled'] == 'disabled';
if (is_array($attribs))
{
$attribs['class'] = isset($attribs['class']) ? $attribs['class'] : 'input-medium';
$attribs['class'] = trim($attribs['class'] . ' hasTooltip');
$attribs = ArrayHelper::toString($attribs);
}
static::_('bootstrap.tooltip');
// Format value when not nulldate ('0000-00-00 00:00:00'), otherwise blank it as it would result in 1970-01-01.
if ($value && $value != JFactory::getDbo()->getNullDate() && strtotime($value) !== false)
{
$tz = date_default_timezone_get();
date_default_timezone_set('UTC');
$inputvalue = strftime($format, strtotime($value));
date_default_timezone_set($tz);
}
else
{
$inputvalue = '';
}
// Load the calendar behavior
static::_('behavior.calendar');
// Only display the triggers once for each control.
if (!in_array($id, $done))
{
JFactory::getDocument()->addScriptDeclaration(
'jQuery(document).ready(function($) {Calendar.setup({
// Id of the input field
inputField: "' . $id . '",
// Format of the input field
ifFormat: "' . $format . '",
// Trigger for the calendar (button ID)
button: "' . $id . '_img",
// Alignment (defaults to "Bl")
align: "Tl",
singleClick: true,
firstDay: ' . JFactory::getLanguage()->getFirstDay() . '
});});'
);
$done[] = $id;
}
// Hide button using inline styles for readonly/disabled fields
$btn_style = ($readonly || $disabled) ? ' style="display:none;"' : '';
$div_class = (!$readonly && !$disabled) ? ' class="input-append"' : '';
return '<div' . $div_class . '>'
. '<input type="text" title="' . ($inputvalue ? static::_('date', $value, null, null) : '')
. '" name="' . $name . '" id="' . $id . '" value="' . htmlspecialchars($inputvalue, ENT_COMPAT, 'UTF-8') . '" ' . $attribs . ' />'
. '<button type="button" class="btn" id="' . $id . '_img"' . $btn_style . '><span class="icon-calendar"></span></button>'
. '</div>';
}
/**
* Add a directory where JHtml should search for helpers. You may
* either pass a string or an array of directories.
*
* @param string $path A path to search.
*
* @return array An array with directory elements
*
* @since 1.5
*/
public static function addIncludePath($path = '')
{
// Force path to array
settype($path, 'array');
// Loop through the path directories
foreach ($path as $dir)
{
if (!empty($dir) && !in_array($dir, static::$includePaths))
{
array_unshift(static::$includePaths, JPath::clean($dir));
}
}
return static::$includePaths;
}
/**
* Internal method to get a JavaScript object notation string from an array
*
* @param array $array The array to convert to JavaScript object notation
*
* @return string JavaScript object notation representation of the array
*
* @since 3.0
* @deprecated 4.0 Use `json_encode()` or `Joomla\Registry\Registry::toString('json')` instead
*/
public static function getJSObject(array $array = array())
{
JLog::add(
__METHOD__ . " is deprecated. Use json_encode() or \\Joomla\\Registry\\Registry::toString('json') instead.",
JLog::WARNING,
'deprecated'
);
$elements = array();
foreach ($array as $k => $v)
{
// Don't encode either of these types
if (is_null($v) || is_resource($v))
{
continue;
}
// Safely encode as a Javascript string
$key = json_encode((string) $k);
if (is_bool($v))
{
$elements[] = $key . ': ' . ($v ? 'true' : 'false');
}
elseif (is_numeric($v))
{
$elements[] = $key . ': ' . ($v + 0);
}
elseif (is_string($v))
{
if (strpos($v, '\\') === 0)
{
// Items such as functions and JSON objects are prefixed with \, strip the prefix and don't encode them
$elements[] = $key . ': ' . substr($v, 1);
}
else
{
// The safest way to insert a string
$elements[] = $key . ': ' . json_encode((string) $v);
}
}
else
{
$elements[] = $key . ': ' . static::getJSObject(is_object($v) ? get_object_vars($v) : $v);
}
}
return '{' . implode(',', $elements) . '}';
}
}
|
gpl-2.0
|
zookeepr/zookeepr
|
zk/model/travel.py
|
1388
|
"""The application's model objects"""
import sqlalchemy as sa
from meta import Base
from person import Person
from pylons.controllers.util import abort
from beaker.cache import CacheManager
from meta import Session
import datetime
import random
class Travel(Base):
"""Stores the details of an individuals travel to and from the conference
"""
__tablename__ = 'travel'
id = sa.Column(sa.types.Integer, primary_key=True)
person_id = sa.Column(sa.types.Integer, sa.ForeignKey('person.id'), unique=True, nullable=False)
origin_airport = sa.Column(sa.types.Text, nullable=False)
destination_airport = sa.Column(sa.types.Text, nullable=False)
flight_details = sa.Column(sa.types.Text, nullable=False)
# relations
#person = sa.orm.relation(Person, backref=sa.orm.backref('travel', cascade="all, delete-orphan", uselist=False))
person = sa.orm.relation(lambda: Person, backref='travel', lazy='subquery')
def __init__(self, **kwargs):
super(Travel, self).__init__(**kwargs)
def __repr__(self):
return '<Travel id=%r person=%s origin_airport=%s destination_airport=%s' % (self.id, self.person, self.origin_airport, self.destination_airport)
@classmethod
def find_all(self):
return Session.query(Travel).all()
@classmethod
def find_by_id(self, id):
return Session.query(Travel).get(id)
|
gpl-2.0
|
hariomkumarmth/champaranexpress
|
wp-content/plugins/dojo/dojox/grid/enhanced/plugins/Pagination.js.uncompressed.js
|
34461
|
require({cache:{
'url:dojox/grid/enhanced/templates/Pagination.html':"<div dojoAttachPoint=\"paginatorBar\"\n\t><table cellpadding=\"0\" cellspacing=\"0\" class=\"dojoxGridPaginator\"\n\t\t><tr\n\t\t\t><td dojoAttachPoint=\"descriptionTd\" class=\"dojoxGridDescriptionTd\"\n\t\t\t\t><div dojoAttachPoint=\"descriptionDiv\" class=\"dojoxGridDescription\"></div\n\t\t\t></div></td\n\t\t\t><td dojoAttachPoint=\"sizeSwitchTd\"></td\n\t\t\t><td dojoAttachPoint=\"pageStepperTd\" class=\"dojoxGridPaginatorFastStep\"\n\t\t\t\t><div dojoAttachPoint=\"pageStepperDiv\" class=\"dojoxGridPaginatorStep\"></div\n\t\t\t></td\n\t\t\t><td dojoAttachPoint=\"gotoPageTd\" class=\"dojoxGridPaginatorGotoTd\"\n\t\t\t\t><div dojoAttachPoint=\"gotoPageDiv\" class=\"dojoxGridPaginatorGotoDiv\" dojoAttachEvent=\"onclick:_openGotopageDialog, onkeydown:_openGotopageDialog\"\n\t\t\t\t\t><span class=\"dojoxGridWardButtonInner\">⊥</span\n\t\t\t\t></div\n\t\t\t></td\n\t\t></tr\n\t></table\n></div>\n"}});
define("dojox/grid/enhanced/plugins/Pagination", [
"dojo/_base/kernel",
"dojo/_base/declare",
"dojo/_base/array",
"dojo/_base/connect",
"dojo/_base/lang",
"dojo/_base/html",
"dojo/_base/event",
"dojo/query",
"dojo/string",
"dojo/keys",
"dojo/text!../templates/Pagination.html",
"./Dialog",
"./_StoreLayer",
"../_Plugin",
"../../EnhancedGrid",
"dijit/form/Button",
"dijit/form/NumberTextBox",
"dijit/focus",
"dijit/_Widget",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin",
"dojox/html/metrics",
"dojo/i18n!../nls/Pagination"
], function(kernel, declare, array, connect, lang, html, event, query,
string, keys, template, Dialog, layers, _Plugin, EnhancedGrid,
Button, NumberTextBox, dijitFocus, _Widget, _TemplatedMixin, _WidgetsInTemplateMixin, metrics, nls){
var _GotoPagePane = declare("dojox.grid.enhanced.plugins.pagination._GotoPagePane", [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: "<div>" +
"<div class='dojoxGridDialogMargin' dojoAttachPoint='_mainMsgNode'></div>" +
"<div class='dojoxGridDialogMargin'>" +
"<input dojoType='dijit.form.NumberTextBox' style='width: 50px;' dojoAttachPoint='_pageInputBox' dojoAttachEvent='onKeyUp: _onKey'></input>" +
"<label dojoAttachPoint='_pageLabelNode'></label>" +
"</div>" +
"<div class='dojoxGridDialogButton'>" +
"<button dojoType='dijit.form.Button' dojoAttachPoint='_confirmBtn' dojoAttachEvent='onClick: _onConfirm'></button>" +
"<button dojoType='dijit.form.Button' dojoAttachPoint='_cancelBtn' dojoAttachEvent='onClick: _onCancel'></button>" +
"</div>" +
"</div>",
widgetsInTemplate: true,
dlg: null,
postMixInProperties: function(){
this.plugin = this.dlg.plugin;
},
postCreate: function(){
this.inherited(arguments);
this._mainMsgNode.innerHTML = this.plugin._nls[12];
this._confirmBtn.set("label", this.plugin._nls[14]);
this._confirmBtn.set("disabled", true);
this._cancelBtn.set("label", this.plugin._nls[15]);
},
_onConfirm: function(evt){
if(this._pageInputBox.isValid() && this._pageInputBox.getDisplayedValue() !== ""){
this.plugin.currentPage(this._pageInputBox.parse(this._pageInputBox.getDisplayedValue()));
this.dlg._gotoPageDialog.hide();
this._pageInputBox.reset();
}
stopEvent(evt);
},
_onCancel: function(evt){
this._pageInputBox.reset();
this.dlg._gotoPageDialog.hide();
stopEvent(evt);
},
_onKey: function(evt){
this._confirmBtn.set("disabled", !this._pageInputBox.isValid() || this._pageInputBox.getDisplayedValue() == "");
if(!evt.altKey && !evt.metaKey && evt.keyCode === keys.ENTER){
this._onConfirm(evt);
}
}
});
var _GotoPageDialog = declare("dojox.grid.enhanced.plugins.pagination._GotoPageDialog", null, {
pageCount: 0,
dlgPane: null,
constructor: function(plugin){
this.plugin = plugin;
this.dlgPane = new _GotoPagePane({"dlg": this});
this.dlgPane.startup();
this._gotoPageDialog = new Dialog({
"refNode": plugin.grid.domNode,
"title": this.plugin._nls[11],
"content": this.dlgPane
});
this._gotoPageDialog.startup();
},
_updatePageCount: function(){
this.pageCount = this.plugin.getTotalPageNum();
this.dlgPane._pageInputBox.constraints = {fractional:false, min:1, max:this.pageCount};
this.dlgPane._pageLabelNode.innerHTML = string.substitute(this.plugin._nls[13], [this.pageCount]);
},
showDialog: function(){
this._updatePageCount();
this._gotoPageDialog.show();
},
destroy: function(){
this._gotoPageDialog.destroy();
}
});
var _ForcedPageStoreLayer = declare("dojox.grid.enhanced.plugins._ForcedPageStoreLayer", layers._StoreLayer, {
tags: ["presentation"],
constructor: function(plugin){
this._plugin = plugin;
},
_fetch: function(request){
var _this = this,
plugin = _this._plugin,
grid = plugin.grid,
scope = request.scope || kernel.global,
onBegin = request.onBegin;
request.start = (plugin._currentPage - 1) * plugin._currentPageSize + request.start;
_this.startIdx = request.start;
_this.endIdx = request.start + plugin._currentPageSize - 1;
var p = plugin._paginator;
if(!plugin._showAll){
plugin._showAll = !p.sizeSwitch && !p.pageStepper && !p.gotoButton;
}
if(onBegin && plugin._showAll){
request.onBegin = function(size, req){
plugin._maxSize = plugin._currentPageSize = size;
_this.startIdx = 0;
_this.endIdx = size - 1;
plugin._paginator._update();
req.onBegin = onBegin;
req.onBegin.call(scope, size, req);
};
}else if(onBegin){
request.onBegin = function(size, req){
req.start = 0;
req.count = plugin._currentPageSize;
plugin._maxSize = size;
_this.endIdx = _this.endIdx >= size ? (size - 1) : _this.endIdx;
if(_this.startIdx > size && size !== 0){
grid._pending_requests[req.start] = false;
plugin.firstPage();
}
plugin._paginator._update();
req.onBegin = onBegin;
req.onBegin.call(scope, Math.min(plugin._currentPageSize, (size - _this.startIdx)), req);
};
}
return lang.hitch(this._store, this._originFetch)(request);
}
});
var stopEvent = function(evt){
try{
if(evt){
event.stop(evt);
}
}catch(e){}
};
var _Focus = declare("dojox.grid.enhanced.plugins.pagination._Focus", null, {
_focusedNode: null,
_isFocused: false,
constructor: function(paginator){
this._pager = paginator;
var focusMgr = paginator.plugin.grid.focus;
paginator.plugin.connect(paginator, 'onSwitchPageSize', lang.hitch(this, '_onActive'));
paginator.plugin.connect(paginator, 'onPageStep', lang.hitch(this, '_onActive'));
paginator.plugin.connect(paginator, 'onShowGotoPageDialog', lang.hitch(this, '_onActive'));
paginator.plugin.connect(paginator, '_update', lang.hitch(this, '_moveFocus'));
},
_onFocus: function(evt, step){
var node, nodes;
if(!this._isFocused){
node = this._focusedNode || query('[tabindex]', this._pager.domNode)[0];
}else if(step && this._focusedNode){
var dir = step > 0 ? -1 : 1,
tabindex = parseInt(this._focusedNode.getAttribute('tabindex'), 10) + dir;
while(tabindex >= -3 && tabindex < 0){
node = query('[tabindex=' + tabindex + ']', this._pager.domNode)[0];
if(node){
break;
}else{
tabindex += dir;
}
}
}
return this._focus(node, evt);
},
_onBlur: function(evt, step){
if(!step || !this._focusedNode){
this._isFocused = false;
if(this._focusedNode && html.hasClass(this._focusedNode, 'dojoxGridButtonFocus')){
html.removeClass(this._focusedNode, 'dojoxGridButtonFocus');
}
return true;
}
var node, dir = step > 0 ? -1 : 1,
tabindex = parseInt(this._focusedNode.getAttribute('tabindex'), 10) + dir;
while(tabindex >= -3 && tabindex < 0){
node = query('[tabindex=' + tabindex + ']', this._pager.domNode)[0];
if(node){
break;
}else{
tabindex += dir;
}
}
if(!node){
this._isFocused = false;
if(html.hasClass(this._focusedNode, 'dojoxGridButtonFocus')){
html.removeClass(this._focusedNode, 'dojoxGridButtonFocus');
}
}
return node ? false : true;
},
_onMove: function(rowDelta, colDelta, evt){
if(this._focusedNode){
var tabindex = this._focusedNode.getAttribute('tabindex'),
delta = colDelta == 1 ? "nextSibling" : "previousSibling",
node = this._focusedNode[delta];
while(node){
if(node.getAttribute('tabindex') == tabindex){
this._focus(node);
break;
}
node = node[delta];
}
}
},
_focus: function(node, evt){
if(node){
this._isFocused = true;
if(kernel.isIE && this._focusedNode){
html.removeClass(this._focusedNode, 'dojoxGridButtonFocus');
}
this._focusedNode = node;
node.focus();
if(kernel.isIE){
html.addClass(node, 'dojoxGridButtonFocus');
}
stopEvent(evt);
return true;
}
return false;
},
_onActive: function(e){
this._focusedNode = e.target;
if(!this._isFocused){
this._pager.plugin.grid.focus.focusArea('pagination' + this._pager.position);
}
},
_moveFocus: function(){
if(this._focusedNode && !this._focusedNode.getAttribute('tabindex')){
var next = this._focusedNode.nextSibling;
while(next){
if(next.getAttribute('tabindex')){
this._focus(next);
return;
}
next = next.nextSibling;
}
var prev = this._focusedNode.previousSibling;
while(prev){
if(prev.getAttribute('tabindex')){
this._focus(prev);
return;
}
prev = prev.previousSibling;
}
this._focusedNode = null;
this._onBlur();
}else if(kernel.isIE && this._focusedNode){
html.addClass(this._focusedNode, 'dojoxGridButtonFocus');
}
}
});
var _Paginator = declare("dojox.grid.enhanced.plugins._Paginator", [_Widget, _TemplatedMixin], {
templateString: template,
constructor: function(params){
lang.mixin(this, params);
this.grid = this.plugin.grid;
},
postCreate: function(){
this.inherited(arguments);
var _this = this, g = this.grid;
this.plugin.connect(g, "_resize", lang.hitch(this, "_resetGridHeight"));
this._originalResize = g.resize;
g.resize = function(changeSize, resultSize){
_this._changeSize = changeSize;
_this._resultSize = resultSize;
_this._originalResize.apply(g, arguments);
};
this.focus = _Focus(this);
this._placeSelf();
},
destroy: function(){
this.inherited(arguments);
this.grid.focus.removeArea("pagination" + this.position);
if(this._gotoPageDialog){
this._gotoPageDialog.destroy();
}
this.grid.resize = this._originalResize;
},
onSwitchPageSize: function(/*Event*/evt){
},
onPageStep: function(/*Event*/evt){
},
onShowGotoPageDialog: function(/*Event*/evt){
},
_update: function(){
// summary:
// Function to update paging information and update
// pagination bar display.
this._updateDescription();
this._updatePageStepper();
this._updateSizeSwitch();
this._updateGotoButton();
},
_registerFocus: function(isTop){
// summary:
// Function to register pagination bar to focus manager.
var focusMgr = this.grid.focus,
name = "pagination" + this.position,
f = this.focus;
focusMgr.addArea({
name: name,
onFocus: lang.hitch(this.focus, "_onFocus"),
onBlur: lang.hitch(this.focus, "_onBlur"),
onMove: lang.hitch(this.focus, "_onMove")
});
focusMgr.placeArea(name, isTop ? "before" : "after", isTop ? "header" : "content");
},
_placeSelf: function(){
// summary:
// Place pagination bar to a position.
// There are two options, top of the grid, bottom of the grid.
var g = this.grid,
isTop = this.position == "top";
this.placeAt(isTop ? g.viewsHeaderNode : g.viewsNode, isTop ? "before" : "after");
this._registerFocus(isTop);
},
_resetGridHeight: function(changeSize, resultSize){
// summary:
// Function of resize grid height to place this pagination bar.
// Since the grid would be able to add other element in its domNode, we have
// change the grid view size to place the pagination bar.
// This function will resize the grid viewsNode height, scorllboxNode height
var g = this.grid;
changeSize = changeSize || this._changeSize;
resultSize = resultSize || this._resultSize;
delete this._changeSize;
delete this._resultSize;
if(g._autoHeight){
return;
}
var padBorder = g._getPadBorder().h;
if(!this.plugin.gh){
this.plugin.gh = (g.domNode.clientHeight || html.style(g.domNode, 'height')) + 2 * padBorder;
}
if(resultSize){
changeSize = resultSize;
}
if(changeSize){
this.plugin.gh = html.contentBox(g.domNode).h + 2 * padBorder;
}
var gh = this.plugin.gh,
hh = g._getHeaderHeight(),
ph = html.marginBox(this.domNode).h;
// ph = this.plugin._paginator.position == "bottom" ? ph * 2 : ph;
if(typeof g.autoHeight === "number"){
var cgh = gh + ph - padBorder;
html.style(g.domNode, "height", cgh + "px");
html.style(g.viewsNode, "height", (cgh - ph - hh) + "px");
this._styleMsgNode(hh, html.marginBox(g.viewsNode).w, cgh - ph - hh);
}else{
var h = gh - ph - hh - padBorder;
html.style(g.viewsNode, "height", h + "px");
var hasHScroller = array.some(g.views.views, function(v){
return v.hasHScrollbar();
});
array.forEach(g.viewsNode.childNodes, function(c){
html.style(c, "height", h + "px");
});
array.forEach(g.views.views, function(v){
if(v.scrollboxNode){
if(!v.hasHScrollbar() && hasHScroller){
html.style(v.scrollboxNode, "height", (h - metrics.getScrollbar().h) + "px");
}else{
html.style(v.scrollboxNode, "height", h + "px");
}
}
});
this._styleMsgNode(hh, html.marginBox(g.viewsNode).w, h);
}
},
_styleMsgNode: function(top, width, height){
var messagesNode = this.grid.messagesNode;
html.style(messagesNode, {"position": "absolute", "top": top + "px", "width": width + "px", "height": height + "px", "z-Index": "100"});
},
_updateDescription: function(){
// summary:
// Update size information.
var s = this.plugin.forcePageStoreLayer,
maxSize = this.plugin._maxSize,
nls = this.plugin._nls,
getItemTitle = function(){
return maxSize <= 0 || maxSize == 1 ? nls[5] : nls[4];
};
if(this.description && this.descriptionDiv){
this.descriptionDiv.innerHTML = maxSize > 0 ? string.substitute(nls[0], [getItemTitle(), maxSize, s.startIdx + 1, s.endIdx + 1]) : "0 " + getItemTitle();
}
},
_updateSizeSwitch: function(){
// summary:
// Update "items per page" information.
html.style(this.sizeSwitchTd, "display", this.sizeSwitch ? "" : "none");
if(!this.sizeSwitch){
return;
}
if(this.sizeSwitchTd.childNodes.length < 1){
this._createSizeSwitchNodes();
}
this._updateSwitchNodesStyle();
},
_createSizeSwitchNodes: function(){
// summary:
// The function to create the size switch nodes
var node = null,
nls = this.plugin._nls,
connect = lang.hitch(this.plugin, 'connect');
array.forEach(this.pageSizes, function(size){
// create page size switch node
var labelValue = isFinite(size) ? string.substitute(nls[2], [size]) : nls[1],
value = isFinite(size) ? size : nls[16];
node = html.create("span", {innerHTML: value, title: labelValue, value: size, tabindex: "-1"}, this.sizeSwitchTd, "last");
// for accessibility
node.setAttribute("aria-label", labelValue);
// connect event
connect(node, "onclick", lang.hitch(this, "_onSwitchPageSize"));
connect(node, "onkeydown", lang.hitch(this, "_onSwitchPageSize"));
connect(node, "onmouseover", function(e){
html.addClass(e.target, "dojoxGridPageTextHover");
});
connect(node, "onmouseout", function(e){
html.removeClass(e.target, "dojoxGridPageTextHover");
});
// create a separation node
node = html.create("span", {innerHTML: "|"}, this.sizeSwitchTd, "last");
html.addClass(node, "dojoxGridSeparator");
}, this);
// delete last separation node
html.destroy(node);
},
_updateSwitchNodesStyle: function(){
// summary:
// Update the switch nodes style
var size = null;
var styleNode = function(node, status){
if(status){
html.addClass(node, "dojoxGridActivedSwitch");
html.removeAttr(node, "tabindex");
}else{
html.addClass(node, "dojoxGridInactiveSwitch");
node.setAttribute("tabindex", "-1");
}
};
array.forEach(this.sizeSwitchTd.childNodes, function(node){
if(node.value){
html.removeClass(node);
size = node.value;
if(this.plugin._showAll){
styleNode(node, isNaN(parseInt(size, 10)));
}else{
styleNode(node, this.plugin._currentPageSize == size);
}
}
}, this);
},
_updatePageStepper: function(){
// summary:
// Update the page step nodes
html.style(this.pageStepperTd, "display", this.pageStepper ? "" : "none");
if(!this.pageStepper){
return;
}
if(this.pageStepperDiv.childNodes.length < 1){
this._createPageStepNodes();
this._createWardBtns();
}else{
this._resetPageStepNodes();
}
this._updatePageStepNodesStyle();
},
_createPageStepNodes: function(){
// summary:
// Create the page step nodes if they do not exist
var startPage = this._getStartPage(),
stepSize = this._getStepPageSize(),
label = "", node = null, i = startPage,
connect = lang.hitch(this.plugin, 'connect');
for(; i < startPage + this.maxPageStep + 1; i++){
label = string.substitute(this.plugin._nls[3], [i]);
node = html.create("div", {innerHTML: i, value: i, title: label}, this.pageStepperDiv, "last");
node.setAttribute("aria-label", label);
// connect event
connect(node, "onclick", lang.hitch(this, "_onPageStep"));
connect(node, "onkeydown", lang.hitch(this, "_onPageStep"));
connect(node, "onmouseover", function(e){
html.addClass(e.target, "dojoxGridPageTextHover");
});
connect(node, "onmouseout", function(e){
html.removeClass(e.target, "dojoxGridPageTextHover");
});
html.style(node, "display", i < startPage + stepSize ? "" : "none");
}
},
_createWardBtns: function(){
// summary:
// Create the previous/next/first/last button
var _this = this, nls = this.plugin._nls;
var highContrastLabel = {prevPage: "<", firstPage: "«", nextPage: ">", lastPage: "»"};
var createWardBtn = function(value, label, position){
var node = html.create("div", {value: value, title: label, tabindex: "-2"}, _this.pageStepperDiv, position);
_this.plugin.connect(node, "onclick", lang.hitch(_this, "_onPageStep"));
_this.plugin.connect(node, "onkeydown", lang.hitch(_this, "_onPageStep"));
node.setAttribute("aria-label", label);
// for high contrast
var highConrastNode = html.create("span", {value: value, title: label, innerHTML: highContrastLabel[value]}, node, position);
html.addClass(highConrastNode, "dojoxGridWardButtonInner");
};
createWardBtn("prevPage", nls[6], "first");
createWardBtn("firstPage", nls[7], "first");
createWardBtn("nextPage", nls[8], "last");
createWardBtn("lastPage", nls[9], "last");
},
_resetPageStepNodes: function(){
// summary:
// The page step nodes might be changed when fetch data, we need to
// update/reset them
var startPage = this._getStartPage(),
stepSize = this._getStepPageSize(),
stepNodes = this.pageStepperDiv.childNodes,
node = null, i = startPage, j = 2, tip;
for(; j < stepNodes.length - 2; j++, i++){
node = stepNodes[j];
if(i < startPage + stepSize){
tip = string.substitute(this.plugin._nls[3], [i]);
html.attr(node, {
"innerHTML": i,
"title": tip,
"value": i
});
html.style(node, "display", "");
node.setAttribute("aria-label", tip);
}else{
html.style(node, "display", "none");
}
}
},
_updatePageStepNodesStyle: function(){
// summary:
// Update the style of the page step nodes
var value = null,
curPage = this.plugin.currentPage(),
pageCount = this.plugin.getTotalPageNum();
var updateClass = function(node, isWardBtn, status){
var value = node.value,
enableClass = isWardBtn ? "dojoxGrid" + value + "Btn" : "dojoxGridInactived",
disableClass = isWardBtn ? "dojoxGrid" + value + "BtnDisable" : "dojoxGridActived";
if(status){
html.addClass(node, disableClass);
html.removeAttr(node, "tabindex");
}else{
html.addClass(node, enableClass);
node.setAttribute("tabindex", "-2");
}
};
array.forEach(this.pageStepperDiv.childNodes, function(node){
html.removeClass(node);
if(isNaN(parseInt(node.value, 10))){
html.addClass(node, "dojoxGridWardButton");
var disablePageNum = node.value == "prevPage" || node.value == "firstPage" ? 1 : pageCount;
updateClass(node, true, (curPage === disablePageNum));
}else{
value = parseInt(node.value, 10);
updateClass(node, false, (value === curPage || html.style(node, "display") === "none"));
}
}, this);
},
_showGotoButton: function(flag){
this.gotoButton = flag;
this._updateGotoButton();
},
_updateGotoButton: function(){
// summary:
// Create/destroy the goto page button
if(!this.gotoButton){
if(this._gotoPageDialog){
this._gotoPageDialog.destroy();
}
html.removeAttr(this.gotoPageDiv, "tabindex");
html.style(this.gotoPageTd, 'display', 'none');
return;
}
if(html.style(this.gotoPageTd, 'display') == 'none'){
html.style(this.gotoPageTd, 'display', '');
}
this.gotoPageDiv.setAttribute('title', this.plugin._nls[10]);
html.toggleClass(this.gotoPageDiv, "dojoxGridPaginatorGotoDivDisabled", this.plugin.getTotalPageNum() <= 1);
if(this.plugin.getTotalPageNum() <= 1){
html.removeAttr(this.gotoPageDiv, "tabindex");
}else{
this.gotoPageDiv.setAttribute("tabindex", "-3");
}
},
_openGotopageDialog: function(e){
// summary:
// Show the goto page dialog
if(this.plugin.getTotalPageNum() <= 1){
return;
}
if(e.type === "keydown" && e.keyCode !== keys.ENTER && e.keyCode !== keys.SPACE){
return;
}
if(!this._gotoPageDialog){
this._gotoPageDialog = new _GotoPageDialog(this.plugin);
}
this._gotoPageDialog.showDialog();
this.onShowGotoPageDialog(e);
},
_onSwitchPageSize: function(/*Event*/e){
// summary:
// The handler of switch the page size
if(e.type === "keydown" && e.keyCode !== keys.ENTER && e.keyCode !== keys.SPACE){
return;
}
this.onSwitchPageSize(e);
this.plugin.currentPageSize(e.target.value);
},
_onPageStep: function(/*Event*/e){
// summary:
// The handler jump page event
if(e.type === "keydown" && e.keyCode !== keys.ENTER && e.keyCode !== keys.SPACE){
return;
}
var p = this.plugin,
value = e.target.value;
this.onPageStep(e);
if(!isNaN(parseInt(value, 10))){
p.currentPage(parseInt(value, 10));
}else{
p[value]();
}
},
_getStartPage: function(){
var cp = this.plugin.currentPage(),
ms = this.maxPageStep,
hs = parseInt(ms / 2, 10),
tp = this.plugin.getTotalPageNum();
if(cp < hs || (cp - hs) < 1 || tp <= ms){
return 1;
}else{
return tp - cp < hs && cp - ms >= 0 ? tp - ms + 1 : cp - hs;
}
},
_getStepPageSize: function(){
var sp = this._getStartPage(),
tp = this.plugin.getTotalPageNum(),
ms = this.maxPageStep;
return sp + ms > tp ? tp - sp + 1 : ms;
}
});
var Pagination = declare("dojox.grid.enhanced.plugins.Pagination", _Plugin, {
// summary:
// The typical pagination way to deal with huge dataset
// an alternative for the default virtual scrolling manner.
name: "pagination",
// defaultPageSize: Integer
// Number of rows in a page, 25 by default.
defaultPageSize: 25,
// defaultPage: Integer
// Which page will be displayed initially, 1st page by default.
defaultPage: 1,
// description: boolean
// Whether the description information will be displayed, true by default.
description: true,
// sizeSwitch: boolean
// Whether the page size switch options will be displayed, true by default.
sizeSwitch: true,
// pageStepper: boolean
// Whether the page switch options will be displayed, true by default.
pageStepper: true,
// gotoButton: boolean
// Whether the goto page button will be displayed, false by default.
gotoButton: false,
// pageSizes: Array
// Array of page sizes for switching, e.g. [10, 25, 50, 100, Infinity] by default,
// Infinity or any NaN value will be treated as "all".
pageSizes: [10, 25, 50, 100, Infinity],
// maxPageStep: Integer
// The max number of page sizes to be displayed, 7 by default.
maxPageStep: 7,
// position: string
// The position of the pagination bar - "top"|"bottom", "bottom" by default.
position: 'bottom',
init: function(){
var g = this.grid;
g.usingPagination = true;
this._initOptions();
this._currentPage = this.defaultPage;
this._currentPageSize = this.grid.rowsPerPage = this.defaultPageSize;
// wrap store layer
this._store = g.store;
this.forcePageStoreLayer = new _ForcedPageStoreLayer(this);
layers.wrap(g, "_storeLayerFetch", this.forcePageStoreLayer);
// create pagination bar
this._paginator = this.option.position != "top" ?
new _Paginator(lang.mixin(this.option, {position: "bottom", plugin: this})) :
new _Paginator(lang.mixin(this.option, {position: "top", plugin: this}));
this._regApis();
},
destroy: function(){
this.inherited(arguments);
this._paginator.destroy();
var g = this.grid;
g.unwrap(this.forcePageStoreLayer.name());
g.scrollToRow = this._gridOriginalfuncs[0];
g._onNew = this._gridOriginalfuncs[1];
g.removeSelectedRows = this._gridOriginalfuncs[2];
this._paginator = null;
this._nls = null;
},
currentPage: function(page){
// summary:
// Shift to the given page, return current page number. If there
// is no valid page was passed in, just return current page num.
// page: Integer
// The page to go to, starting at 1.
// returns:
// Current page number
if(page <= this.getTotalPageNum() && page > 0 && this._currentPage !== page){
this._currentPage = page;
this.grid._refresh(true);
this.grid.resize();
}
return this._currentPage;
},
nextPage: function(){
// summary:
// Go to the next page.
this.currentPage(this._currentPage + 1);
},
prevPage: function(){
// summary:
// Go to the previous page.
this.currentPage(this._currentPage - 1);
},
firstPage: function(){
// summary:
// Go to the first page
this.currentPage(1);
},
lastPage: function(){
// summary:
// Go to the last page
this.currentPage(this.getTotalPageNum());
},
currentPageSize: function(size){
// summary:
// Change the size of current page or return the current page size.
// size: Integer|null
// An integer identifying the number of rows per page. If the size
// is an Infinity, all rows will be displayed; if an invalid value passed
// in, the current page size will be returned.
// returns:
// Current size of items per page.
if(!isNaN(size)){
var g = this.grid,
startIndex = this._currentPageSize * (this._currentPage - 1), endIndex;
this._showAll = !isFinite(size);
this.grid.usingPagination = !this._showAll;
this._currentPageSize = this._showAll ? this._maxSize : size;
g.rowsPerPage = this._showAll ? this._defaultRowsPerPage : size;
endIndex = startIndex + Math.min(this._currentPageSize, this._maxSize);
if(endIndex > this._maxSize){
this.lastPage();
}else{
var cp = Math.ceil(startIndex / this._currentPageSize) + 1;
if(cp !== this._currentPage){
this.currentPage(cp);
}else{
this.grid._refresh(true);
}
}
this.grid.resize();
}
return this._currentPageSize;
},
getTotalPageNum: function(){
// summary:
// Get total page number
return Math.ceil(this._maxSize / this._currentPageSize);
},
getTotalRowCount: function(){
// summary:
// Function for get total row count
return this._maxSize;
},
scrollToRow: function(inRowIndex){
// summary:
// Override the grid.scrollToRow(), could jump to the right page
// and scroll to the specific row
// inRowIndex: integer
// The row index
var page = parseInt(inRowIndex / this._currentPageSize, 10) + 1;
if(page > this.getTotalPageNum()){
return;
}
this.currentPage(page);
var rowIdx = inRowIndex % this._currentPageSize;
return this._gridOriginalfuncs[0](rowIdx);
},
removeSelectedRows: function(){
this._multiRemoving = true;
this._gridOriginalfuncs[2].apply();
this._multiRemoving = false;
if(this.grid.store.save){
this.grid.store.save();
}
this.grid.resize();
this.grid._refresh();
},
showGotoPageButton: function(flag){
// summary:
// For show/hide the go to page button dynamically
// flag: boolean
// Show the go to page button when flag is true, otherwise hide it
this._paginator.gotoButton = flag;
this._paginator._updateGotoButton();
},
// [DEPRECATED] ============
gotoPage: function(page){
kernel.deprecated("dojox.grid.enhanced.EnhancedGrid.gotoPage(page)", "use dojox.grid.enhanced.EnhancedGrid.currentPage(page) instead", "1.8");
this.currentPage(page);
},
gotoFirstPage: function(){
kernel.deprecated("dojox.grid.enhanced.EnhancedGrid.gotoFirstPage()", "use dojox.grid.enhanced.EnhancedGrid.firstPage() instead", "1.8");
this.firstPage();
},
gotoLastPage: function(){
kernel.deprecated("dojox.grid.enhanced.EnhancedGrid.gotoLastPage()", "use dojox.grid.enhanced.EnhancedGrid.lastPage() instead", "1.8");
this.lastPage();
},
changePageSize: function(size){
kernel.deprecated("dojox.grid.enhanced.EnhancedGrid.changePageSize(size)", "use dojox.grid.enhanced.EnhancedGrid.currentPageSize(size) instead", "1.8");
this.currentPageSize(size);
},
// =============== Protected ================
_nls: null,
_showAll: false,
_maxSize: 0,
// =============== Private ===============
_defaultRowsPerPage: 25,
_currentPage: 1,
_currentPageSize: 25,
_initOptions: function(){
this._defaultRowsPerPage = this.grid.rowsPerPage || 25;
this.defaultPage = this.option.defaultPage >= 1 ? parseInt(this.option.defaultPage, 10) : 1;
this.option.description = this.option.description !== undefined ? !!this.option.description : this.description;
this.option.sizeSwitch = this.option.sizeSwitch !== undefined ? !!this.option.sizeSwitch : this.sizeSwitch;
this.option.pageStepper = this.option.pageStepper !== undefined ? !!this.option.pageStepper : this.pageStepper;
this.option.gotoButton = this.option.gotoButton !== undefined ? !!this.option.gotoButton : this.gotoButton;
if(lang.isArray(this.option.pageSizes)){
var pageSizes = [];
array.forEach(this.option.pageSizes, function(size){
size = typeof size == 'number' ? size : parseInt(size, 10);
if(!isNaN(size) && size > 0){
pageSizes.push(size);
}else if(array.indexOf(pageSizes, Infinity) < 0){
pageSizes.push(Infinity);
}
}, this);
this.option.pageSizes = pageSizes.sort(function(a, b){return a - b;});
}else{
this.option.pageSizes = this.pageSizes;
}
this.defaultPageSize = this.option.defaultPageSize >= 1 ? parseInt(this.option.defaultPageSize, 10) : this.pageSizes[0];
this.option.maxPageStep = this.option.maxPageStep > 0 ? this.option.maxPageStep : this.maxPageStep;
this.option.position = lang.isString(this.option.position) ? this.option.position.toLowerCase() : this.position;
this._nls = [
nls.descTemplate,
nls.allItemsLabelTemplate,
nls.pageSizeLabelTemplate,
nls.pageStepLabelTemplate,
nls.itemTitle,
nls.singularItemTitle,
nls.prevTip,
nls.firstTip,
nls.nextTip,
nls.lastTip,
nls.gotoButtonTitle,
nls.dialogTitle,
nls.dialogIndication,
nls.pageCountIndication,
nls.dialogConfirm,
nls.dialogCancel,
nls.all
];
},
_regApis: function(){
var g = this.grid;
// New added APIs
g.currentPage = lang.hitch(this, this.currentPage);
g.nextPage = lang.hitch(this, this.nextPage);
g.prevPage = lang.hitch(this, this.prevPage);
g.firstPage = lang.hitch(this, this.firstPage);
g.lastPage = lang.hitch(this, this.lastPage);
g.currentPageSize = lang.hitch(this, this.currentPageSize);
g.showGotoPageButton = lang.hitch(this, this.showGotoPageButton);
g.getTotalRowCount = lang.hitch(this, this.getTotalRowCount);
g.getTotalPageNum = lang.hitch(this, this.getTotalPageNum);
g.gotoPage = lang.hitch(this, this.gotoPage);
g.gotoFirstPage = lang.hitch(this, this.gotoFirstPage);
g.gotoLastPage = lang.hitch(this, this.gotoLastPage);
g.changePageSize = lang.hitch(this, this.changePageSize);
// Changed APIs
this._gridOriginalfuncs = [
lang.hitch(g, g.scrollToRow),
lang.hitch(g, g._onNew),
lang.hitch(g, g.removeSelectedRows)
];
g.scrollToRow = lang.hitch(this, this.scrollToRow);
g.removeSelectedRows = lang.hitch(this, this.removeSelectedRows);
g._onNew = lang.hitch(this, this._onNew);
this.connect(g, "_onDelete", lang.hitch(this, this._onDelete));
},
_onNew: function(item, parentInfo){
var totalPages = this.getTotalPageNum();
if(((this._currentPage === totalPages || totalPages === 0) && this.grid.get('rowCount') < this._currentPageSize) || this._showAll){
lang.hitch(this.grid, this._gridOriginalfuncs[1])(item, parentInfo);
this.forcePageStoreLayer.endIdx++;
}
this._maxSize++;
if(this._showAll){
this._currentPageSize++;
}
if(this._showAll && this.grid.autoHeight){
this.grid._refresh();
}else{
this._paginator._update();
}
},
_onDelete: function(){
if(!this._multiRemoving){
this.grid.resize();
if(this._showAll){
this.grid._refresh();
}
}
if(this.grid.get('rowCount') === 0){
this.prevPage();
}
}
});
EnhancedGrid.registerPlugin(Pagination/*name:'pagination'*/);
return Pagination;
});
|
gpl-2.0
|
hariomkumarmth/champaranexpress
|
wp-content/plugins/dojo/dojox/editor/plugins/nls/zh/SafePaste.js
|
305
|
//>>built
define("dojox/editor/plugins/nls/zh/SafePaste",({"instructions":"禁用了直接粘贴。请使用标准浏览器键盘或菜单粘贴控件在此对话框中粘贴内容。一旦您满意要插入的内容,请按“粘贴”按钮。要中止插入内容,请按“取消”按钮。"}));
|
gpl-2.0
|
trasher/glpi
|
front/cluster.php
|
1391
|
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2021 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
include ('../inc/includes.php');
Session::checkRight("cluster", READ);
Html::header(Cluster::getTypeName(Session::getPluralNumber()), $_SERVER['PHP_SELF'], "management", "cluster");
Search::show('Cluster');
Html::footer();
|
gpl-2.0
|
jacenkow/inspire-next
|
tests/unit/workflows/test_proxies.py
|
993
|
# -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2016 CERN.
#
# INSPIRE 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.
#
# INSPIRE 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 INSPIRE; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Unit tests for the workflows proxies."""
from inspirehep.modules.workflows.proxies import antihep_keywords
def test_load_antihep():
"""Test that keyword loading works."""
assert "ATLAS" in antihep_keywords
|
gpl-2.0
|
DavidSalzer/nadlan-city
|
wp-content/themes/Tyler/event-framework/lib/style-switcher/style-switcher.php
|
2536
|
<?php
if ( ! is_admin() ) {
add_action( 'wp_head' , 'style_switcher_enqueue_scripts' );
add_action( 'init' , 'style_switcher_display' );
}
function style_switcher_enqueue_scripts() {
wp_enqueue_style( 'css-style-switcher', EF_LIB_URL . '/style-switcher/style-switcher.css' );
wp_enqueue_script( 'js-style-switcher', EF_LIB_URL . '/style-switcher/style-switcher.js', array( 'jquery' ) );
}
function style_switcher_display() {
$ef_options = EF_Event_Options::get_theme_options();
$color_scheme = empty( $ef_options['ef_color_palette'] ) ? 'basic' : $ef_options['ef_color_palette'];
$tyler_session_expired = 5;
if ( isset( $_SESSION['dxef_last_skin_activity'] ) && ( ( time() - $_SESSION['dxef_last_skin_activity'] ) > $tyler_session_expired ) ) {
unset( $_SESSION['dxef_last_skin_activity'] );
unset( $_SESSION['dxef_selected_skin'] );
} else {
$_SESSION['dxef_last_skin_activity'] = time();
if ( ! empty( $_POST['selected-skin'] ) ) {
$_SESSION['dxef_selected_skin'] = $_POST['selected-skin'];
}
if ( ! empty( $_SESSION['dxef_selected_skin'] ) ) {
$color_scheme = $_SESSION['dxef_selected_skin'];
}
if ( isset( $color_scheme ) && $color_scheme != 'basic' ) {
wp_enqueue_style( $color_scheme . '-scheme', get_template_directory_uri() . '/css/schemes/' . $color_scheme . '/layout.css', true );
?>
<script>
var poi_marker = '<?php echo get_stylesheet_directory_uri(); ?>/images/schemes/<?php echo $color_scheme; ?>/icon-map-pointer.png';
</script>
<?php
}
}
?>
<div id="dxef-style-switcher">
<div id="dxef-style-switcher-close"></div>
<h3><?php _e( 'Select Skin', 'tyler' ); ?></h3>
<form id="selected-skin-form" method="post">
<select id="selected-skin" name="selected-skin">
<option>Select Skin</option>
<option value="basic">Basic</option>
<option value="bangkok">Bangkok</option>
<option value="barcelona">Barcelona</option>
<option value="helsinki">Helsinki</option>
<option value="istanbul">Istanbul</option>
<option value="london">London</option>
<option value="melbourne">Melbourne</option>
<option value="mexico-city">Mmexico City</option>
<option value="new-orleans">New Orleans</option>
<option value="oslo">Oslo</option>
<option value="paris">Paris</option>
<option value="san-diego">San Diego</option>
<option value="santa-monica">Santa Monica</option>
<option value="shangai">Shangai</option>
<option value="tokyo">Tokyo</option>
</select>
</form>
</div>
<?php
}
|
gpl-2.0
|
tvcnet/pharmtest
|
sandbox/Sandbox1/wp-content/plugins/iwp-client/backup.class.php
|
104543
|
<?php
/************************************************************
* This plugin was modified by Revmakx *
* Copyright (c) 2012 Revmakx *
* www.revmakx.com *
* *
************************************************************/
/*************************************************************
*
* backup.class.php
*
* Manage Backups
*
*
* Copyright (c) 2011 Prelovac Media
* www.prelovac.com
**************************************************************/
define('IWP_BACKUP_DIR', WP_CONTENT_DIR . '/infinitewp/backups');
define('IWP_DB_DIR', IWP_BACKUP_DIR . '/iwp_db');
$zip_errors = array(
'No error',
'No error',
'Unexpected end of zip file',
'A generic error in the zipfile format was detected',
'zip was unable to allocate itself memory',
'A severe error in the zipfile format was detected',
'Entry too large to be split with zipsplit',
'Invalid comment format',
'zip -T failed or out of memory',
'The user aborted zip prematurely',
'zip encountered an error while using a temp file. Please check if this domain\'s account has enough disk space.',
'Read or seek error',
'zip has nothing to do',
'Missing or empty zip file',
'Error writing to a file. Please check if this domain\'s account has enough disk space.',
'zip was unable to create a file to write to',
'bad command line parameters',
'no error',
'zip could not open a specified file to read'
);
$unzip_errors = array(
'No error',
'One or more warning errors were encountered, but processing completed successfully anyway',
'A generic error in the zipfile format was detected',
'A severe error in the zipfile format was detected.',
'unzip was unable to allocate itself memory.',
'unzip was unable to allocate memory, or encountered an encryption error',
'unzip was unable to allocate memory during decompression to disk',
'unzip was unable allocate memory during in-memory decompression',
'unused',
'The specified zipfiles were not found',
'Bad command line parameters',
'No matching files were found',
50 => 'The disk is (or was) full during extraction',
51 => 'The end of the ZIP archive was encountered prematurely.',
80 => 'The user aborted unzip prematurely.',
81 => 'Testing or extraction of one or more files failed due to unsupported compression methods or unsupported decryption.',
82 => 'No files were found due to bad decryption password(s)'
);
class IWP_MMB_Backup extends IWP_MMB_Core
{
var $site_name;
var $statuses;
var $tasks;
var $s3;
var $ftp;
var $dropbox;
function __construct()
{
parent::__construct();
$this->site_name = str_replace(array(
"_",
"/",
"~"
), array(
"",
"-",
"-"
), rtrim($this->remove_http(get_bloginfo('url')), "/"));
$this->statuses = array(
'db_dump' => 1,
'db_zip' => 2,
'files_zip' => 3,
'finished' => 100
);
$this->tasks = get_option('iwp_client_backup_tasks');
}
function set_memory()
{
$changed = array('execution_time' => 0, 'memory_limit' => 0);
@ignore_user_abort(true);
$memory_limit = trim(ini_get('memory_limit'));
$last = strtolower(substr($memory_limit, -1));
if($last == 'g')
$memory_limit = ((int) $memory_limit)*1024;
else if($last == 'm')
$memory_limit = (int) $memory_limit;
if($last == 'k')
$memory_limit = ((int) $memory_limit)/1024;
if ( $memory_limit < 384 ) {
@ini_set('memory_limit', '384M');
$changed['memory_limit'] = 1;
}
if ( (int) @ini_get('max_execution_time') < 1200 ) {
@ini_set('max_execution_time', 1200);//twenty minutes
@set_time_limit(1200);
$changed['execution_time'] = 1;
}
return $changed;
}
function get_backup_settings()
{
$backup_settings = get_option('iwp_client_backup_tasks');
if (!empty($backup_settings))
return $backup_settings;
else
return false;
}
function set_backup_task($params)
{
//$params => [$task_name, $args, $error]
if (!empty($params)) {
//Make sure backup cron job is set
if (!wp_next_scheduled('iwp_client_backup_tasks')) {
wp_schedule_event( time(), 'tenminutes', 'iwp_client_backup_tasks' );
}
extract($params);
//$before = $this->get_backup_settings();
$before = $this->tasks;
if (!$before || empty($before))
$before = array();
if (isset($args['remove'])) {
unset($before[$task_name]);
$return = array(
'removed' => true
);
} else {
if (is_array($params['account_info'])) { //only if sends from IWP Admin Panel first time(secure data)
$args['account_info'] = $account_info;
}
$before[$task_name]['task_args'] = $args;
//$before[$task_name]['task_args'] = $task_name;
/*if (strlen($args['schedule']))
$before[$task_name]['task_args']['next'] = $this->schedule_next($args['type'], $args['schedule']);*///to WP cron
$before[$task_name]['task_args']['task_name'] = $task_name;
$return = $before[$task_name];
}
//Update with error
if (isset($error)) {
if (is_array($error)) {
$before[$task_name]['task_results'][count($before[$task_name]['task_results']) - 1]['error'] = $error['error'];
} else {
$before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['error'] = $error;
}
}
// if (isset($time) && $time) { //set next result time before backup
if (is_array($before[$task_name]['task_results'])) {
$before[$task_name]['task_results'] = array_values($before[$task_name]['task_results']);
}
//$before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['time'] = (isset($time) && $time) ? $time : time();
//}
if (isset($time) && $time) { //This will occur for schedule runtask.
$before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['time'] = $time;
}else{
if($task_name == 'Backup Now')
$before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['time'] = time();
}
$this->update_tasks($before);
//update_option('iwp_client_backup_tasks', $before);
if ($task_name == 'Backup Now') {
$result = $this->backup($args, $task_name);
$backup_settings = $this->tasks;
if (is_array($result) && array_key_exists('error', $result)) {
$return = $result;
} else {
$return = $backup_settings[$task_name];
}
}
return $return;
}
return false;
}
//Cron check
function check_backup_tasks()
{
$this->check_cron_remove();
$settings = $this->tasks;
if (is_array($settings) && !empty($settings)) {
foreach ($settings as $task_name => $setting) {
if ($setting['task_args']['next'] && $setting['task_args']['next'] < time()) {
//if ($setting['task_args']['next'] && $_GET['force_backup']) {
if ($setting['task_args']['url'] && $setting['task_args']['task_id'] && $setting['task_args']['site_key']) {
//Check orphan task
$check_data = array(
'task_name' => $task_name,
'task_id' => $setting['task_args']['task_id'],
'site_key' => $setting['task_args']['site_key']
);
$check = $this->validate_task($check_data, $setting['task_args']['url']);
}
$update = array(
'task_name' => $task_name,
'args' => $settings[$task_name]['task_args']
);
if($check != 'paused'){
$update['time'] = time();
}
//Update task with next schedule
$this->set_backup_task($update);
if($check == 'paused'){
continue;
}
$result = $this->backup($setting['task_args'], $task_name);
$error = '';
if (is_array($result) && array_key_exists('error', $result)) {
$error = $result;
$this->set_backup_task(array(
'task_name' => $task_name,
'args' => $settings[$task_name]['task_args'],
'error' => $error
));
} else {
$error = '';
}
break; //Only one backup per cron
}
}
}
}
function task_now($task_name){
$settings = $this->tasks;
if(!array_key_exists($task_name,$settings)){
return array('error' => $task_name." does not exist.");
} else {
$setting = $settings[$task_name];
}
$this->set_backup_task(array(
'task_name' => $task_name,
'args' => $settings[$task_name]['task_args'],
'time' => time()
));
//Run backup
$result = $this->backup($setting['task_args'], $task_name);
//Check for error
if (is_array($result) && array_key_exists('error', $result)) {
$this->set_backup_task(array(
'task_name' => $task_name,
'args' => $settings[$task_name]['task_args'],
'error' => $result['error']
));
return $result;
} else {
return $this->get_backup_stats();
}
}
function delete_task_now($task_name){
$tasks = $this->tasks;
unset($tasks[$task_name]);
$this->update_tasks($tasks);
$this->cleanup();
return $task_name;
}
/*
* If Task Name not set then it's manual backup
* Backup args:
* type -> db, full
* what -> daily, weekly, monthly
* account_info -> ftp, amazons3, dropbox
* exclude-> array of paths to exclude from backup
*/
function backup($args, $task_name = false)
{
if (!$args || empty($args))
return false;
extract($args); //extract settings
//$adminHistoryID - admin panel history ID for backup task.
//Try increase memory limit and execution time
$this->set_memory();
//Remove old backup(s)
$removed = $this->remove_old_backups($task_name);
if (is_array($removed) && isset($removed['error'])) {
//$error_message = $removed['error'];
return $removed;
}
$new_file_path = IWP_BACKUP_DIR;
if (!file_exists($new_file_path)) {
if (!mkdir($new_file_path, 0755, true))
return array(
'error' => 'Permission denied, make sure you have write permission to wp-content folder.'
);
}
@file_put_contents($new_file_path . '/index.php', ''); //safe
//Prepare .zip file name
$hash = md5(time());
$label = $type ? $type : 'manual';
$backup_file = $new_file_path . '/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
$backup_url = WP_CONTENT_URL . '/infinitewp/backups/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
//Optimize tables?
if (isset($optimize_tables) && !empty($optimize_tables)) {
$this->optimize_tables();
}
//What to backup - db or full?
if (trim($what) == 'db') {
//Take database backup
$this->update_status($task_name, 'db_dump');
$GLOBALS['fail_safe_db'] = $this->tasks[$task_name]['task_args']['fail_safe_db'];
$db_result = $this->backup_db();
if ($db_result == false) {
return array(
'error' => 'Failed to backup database.'
);
} else if (is_array($db_result) && isset($db_result['error'])) {
return array(
'error' => $db_result['error']
);
} else {
$this->update_status($task_name, 'db_dump', true);
$this->update_status($task_name, 'db_zip');
/*zip_backup_db*/
$fail_safe_files = $this->tasks[$task_name]['task_args']['fail_safe_files'];
$disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
if($fail_safe_files){
$this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
}
else{
$comp_level = $disable_comp ? '-0' : '-1';
chdir(IWP_BACKUP_DIR);
$zip = $this->get_zip();
$command = "$zip -q -r $comp_level $backup_file 'iwp_db'";
iwp_mmb_print_flush('DB ZIP CMD: Start');
ob_start();
$result = $this->iwp_mmb_exec($command);
ob_get_clean();
iwp_mmb_print_flush('DB ZIP CMD: End');
/*zip_backup_db */
if(!$result){
$zip_archive_db_result = false;
if (class_exists("ZipArchive")) {
$this->_log("DB zip, fallback to ZipArchive");
iwp_mmb_print_flush('DB ZIP Archive: Start');
$zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
iwp_mmb_print_flush('DB ZIP Archive: End');
}
if (!$zip_archive_db_result) {
$this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
}
}
}
@unlink($db_result);
@unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
@rmdir(IWP_DB_DIR);
/*if (!$result) {
return array(
'error' => 'Failed to zip database.'
);
}*///commented because of zipArchive
$this->update_status($task_name, 'db_zip', true);
}
} elseif (trim($what) == 'full') {
$content_backup = $this->backup_full($task_name, $backup_file, $exclude, $include);
if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
return array(
'error' => $content_backup['error']
);
}
}
//Update backup info
if ($task_name) {
//backup task (scheduled)
$backup_settings = $this->tasks;
$paths = array();
$size = round(filesize($backup_file) / 1024, 2);
if ($size > 1000) {
$paths['size'] = round($size / 1024, 2) . " MB";//Modified by IWP //Mb => MB
} else {
$paths['size'] = $size . 'KB';//Modified by IWP //Kb => KB
}
$paths['backup_name'] = $backup_settings[$task_name]['task_args']['backup_name'];
if ($task_name != 'Backup Now') {
if (!$backup_settings[$task_name]['task_args']['del_host_file']) {
$paths['server'] = array(
'file_path' => $backup_file,
'file_url' => $backup_url
);
}
} else {
$paths['server'] = array(
'file_path' => $backup_file,
'file_url' => $backup_url
);
}
if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_ftp'])) {
$paths['ftp'] = basename($backup_url);
}
if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_amazon_s3'])) {
$paths['amazons3'] = basename($backup_url);
}
if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_dropbox'])) {
$paths['dropbox'] = basename($backup_url);
}
if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_email'])) {
$paths['email'] = basename($backup_url);
}
$temp = $backup_settings[$task_name]['task_results'];
$temp = @array_values($temp);
$paths['time'] = time();
//if ($task_name != 'Backup Now') {
$paths['backhack_status'] = $temp[count($temp) - 1]['backhack_status'];
//$paths['status'] = $temp[count($temp) - 1]['status'];
$temp[count($temp) - 1] = $paths;
/*
} else {
$temp[count($temp)] = $paths;
}
*/
$backup_settings[$task_name]['task_results'] = $temp;
$this->update_tasks($backup_settings);
//update_option('iwp_client_backup_tasks', $backup_settings);
}
if ($task_name != 'Backup Now') {
if (isset($account_info['iwp_ftp']) && !empty($account_info['iwp_ftp'])) {
$this->update_status($task_name, 'ftp');
$account_info['iwp_ftp']['backup_file'] = $backup_file;
iwp_mmb_print_flush('FTP upload: Start');
$ftp_result = $this->ftp_backup($account_info['iwp_ftp']);
iwp_mmb_print_flush('FTP upload: End');
if ($ftp_result !== true && $del_host_file) {
@unlink($backup_file);
}
if (is_array($ftp_result) && isset($ftp_result['error'])) {
return $ftp_result;
}
$this->wpdb_reconnect();
$this->update_status($task_name, 'ftp', true);
}
if (isset($account_info['iwp_amazon_s3']) && !empty($account_info['iwp_amazon_s3'])) {
$this->update_status($task_name, 's3');
$account_info['iwp_amazon_s3']['backup_file'] = $backup_file;
iwp_mmb_print_flush('Amazon S3 upload: Start');
$amazons3_result = $this->amazons3_backup($account_info['iwp_amazon_s3']);
iwp_mmb_print_flush('Amazon S3 upload: End');
if ($amazons3_result !== true && $del_host_file) {
@unlink($backup_file);
}
if (is_array($amazons3_result) && isset($amazons3_result['error'])) {
return $amazons3_result;
}
$this->wpdb_reconnect();
$this->update_status($task_name, 's3', true);
}
if (isset($account_info['iwp_dropbox']) && !empty($account_info['iwp_dropbox'])) {
$this->update_status($task_name, 'dropbox');
$account_info['iwp_dropbox']['backup_file'] = $backup_file;
iwp_mmb_print_flush('Dropbox upload: Start');
$dropbox_result = $this->dropbox_backup($account_info['iwp_dropbox']);
iwp_mmb_print_flush('Dropbox upload: End');
if ($dropbox_result !== true && $del_host_file) {
@unlink($backup_file);
}
if (is_array($dropbox_result) && isset($dropbox_result['error'])) {
return $dropbox_result;
}
$this->wpdb_reconnect();
$this->update_status($task_name, 'dropbox', true);
}
if ($del_host_file) {
@unlink($backup_file);
}
} //end additional
$this->update_status($task_name,'finished',true);
return $backup_url; //Return url to backup file
}
function backup_full($task_name, $backup_file, $exclude = array(), $include = array())
{
global $zip_errors;
$sys = substr(PHP_OS, 0, 3);
$this->update_status($task_name, 'db_dump');
$GLOBALS['fail_safe_db'] = $this->tasks[$task_name]['task_args']['fail_safe_db'];
$db_result = $this->backup_db();
if ($db_result == false) {
return array(
'error' => 'Failed to backup database.'
);
} else if (is_array($db_result) && isset($db_result['error'])) {
return array(
'error' => $db_result['error']
);
}
$this->update_status($task_name, 'db_dump', true);
$this->update_status($task_name, 'db_zip');
/*zip_backup_db*/
$fail_safe_files = $this->tasks[$task_name]['task_args']['fail_safe_files'];
$disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
if($fail_safe_files){
$this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
}
else{
$comp_level = $disable_comp ? '-0' : '-1';
$zip = $this->get_zip();
iwp_mmb_print_flush('DB ZIP CMD: Start');
//Add database file
chdir(IWP_BACKUP_DIR);
$command = "$zip -q -r $comp_level $backup_file 'iwp_db'";
ob_start();
$result = $this->iwp_mmb_exec($command);
ob_get_clean();
iwp_mmb_print_flush('DB ZIP CMD: End');
/*zip_backup_db*/
if(!$result){
$zip_archive_db_result = false;
if (class_exists("ZipArchive")) {
iwp_mmb_print_flush('DB ZIP Archive: Start');
$this->_log("DB zip, fallback to ZipArchive");
$zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
iwp_mmb_print_flush('DB ZIP Archive: End');
}
if (!$zip_archive_db_result) {
$this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
}
}
}
@unlink($db_result);
@unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
@rmdir(IWP_DB_DIR);
$this->update_status($task_name, 'db_zip', true);
//Always remove backup folders
$remove = array(
trim(basename(WP_CONTENT_DIR)) . "/infinitewp/backups",
trim(basename(WP_CONTENT_DIR)) . "/" . md5('iwp_mmb-client') . "/iwp_backups",
trim(basename(WP_CONTENT_DIR)) . "/cache",
trim(basename(WP_CONTENT_DIR)) . "/w3tc"
);
$exclude = array_merge($exclude, $remove);
//Exclude paths
$exclude_data = "-x";
$exclude_file_data = '';
if (!empty($exclude) && is_array($exclude)) {
foreach ($exclude as $data) {
if(empty($data))
continue;
if (is_dir(ABSPATH . $data)) {
if ($sys == 'WIN')
$exclude_data .= " $data/*.*";
else
$exclude_data .= " '$data/*'";
}else {
if ($sys == 'WIN'){
if(file_exists(ABSPATH . $data)){
$exclude_data .= " $data";
$exclude_file_data .= " $data";
}
}else {
if(file_exists(ABSPATH . $data)){
$exclude_data .= " '$data'";
$exclude_file_data .= " '$data'";
}
}
}
}
}
if($exclude_file_data){
$exclude_file_data = "-x".$exclude_file_data;
}
/* foreach ($remove as $data) {
if(empty($data))
continue;
if ($sys == 'WIN')
$exclude_data .= " $data/*.*";
else
$exclude_data .= " '$data/*'";
}*/ //commented for pclzip modifications
//Include paths by default
$add = array(
trim(WPINC),
trim(basename(WP_CONTENT_DIR)),
"wp-admin"
);
$include_data = ". -i";
foreach ($add as $data) {
if ($sys == 'WIN')
$include_data .= " $data/*.*";
else
$include_data .= " '$data/*'";
}
//Additional includes?
if (!empty($include) && is_array($include)) {
foreach ($include as $data) {
if(empty($data))
continue;
if ($data) {
if ($sys == 'WIN')
$include_data .= " $data/*.*";
else
$include_data .= " '$data/*'";
}
}
}
$this->update_status($task_name, 'files_zip');
chdir(ABSPATH);
if($fail_safe_files){
$this->fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove);
}
else{
$do_cmd_zip_alternative = false;
@copy($backup_file, $backup_file.'_2');
iwp_mmb_print_flush('Files ZIP CMD: Start');
$command = "$zip -q -j $comp_level $backup_file .* * $exclude_file_data";
ob_start();
$result_f = $this->iwp_mmb_exec($command, false, true);
ob_get_clean();
iwp_mmb_print_flush('Files ZIP CMD: 1/2 over');
if (!$result_f || $result_f == 18) { // disregard permissions error, file can't be accessed
$command = "$zip -q -r $comp_level $backup_file $include_data $exclude_data";
ob_start();
$result_d = $this->iwp_mmb_exec($command, false, true);
ob_get_clean();
if ($result_d && $result_d != 18) {
@unlink($backup_file);
$do_cmd_zip_alternative = true;
if($result_d > 0 && $result_d < 18){
//return array(
// 'error' => 'Failed to archive files (' . $zip_errors[$result_d] . ') .'
// );
iwp_mmb_print_flush('Files ZIP CMD: Failed to archive files (' . $zip_errors[$result_d] . ') .');
}
else{
//return array(
// 'error' => 'Failed to archive files.'
//);
iwp_mmb_print_flush('Files ZIP CMD: Failed to archive files.');
}
}
}
if(!$do_cmd_zip_alternative){//if FILE ZIP CMD successful
@unlink($backup_file.'_2');
}
iwp_mmb_print_flush('Files ZIP CMD: End');
if (($result_f && $result_f != 18) || ($do_cmd_zip_alternative)) {
if($do_cmd_zip_alternative){
@copy($backup_file.'_2', $backup_file);
@unlink($backup_file.'_2');
}
$zip_archive_result = false;
if (class_exists("ZipArchive")) {
iwp_mmb_print_flush('Files ZIP Archive: Start');
$this->_log("Files zip fallback to ZipArchive");
$zip_archive_result = $this->zip_archive_backup($task_name, $backup_file, $exclude, $include);
iwp_mmb_print_flush('Files ZIP Archive: End');
}
if (!$zip_archive_result) {
$this->fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove);
}
}
}
//Reconnect
$this->wpdb_reconnect();
$this->update_status($task_name, 'files_zip', true);
return true;
}
function fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove){ //Try pclZip
//$this->back_hack($task_name, 'Files ZIP PCL: Start');
iwp_mmb_print_flush('Files ZIP PCL: Start');
if (!isset($archive)) {
define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
//require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
$archive = new IWPPclZip($backup_file);
}
//Include paths
$include_data = array();
if (!empty($include) && is_array($include)) {
foreach ($include as $data) {
if ($data && file_exists(ABSPATH . $data))
$include_data[] = ABSPATH . $data . '/';
}
}
foreach ($add as $data) {
if (file_exists(ABSPATH . $data))
$include_data[] = ABSPATH . $data . '/';
}
//Include root files
if ($handle = opendir(ABSPATH)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && !is_dir($file) && file_exists(ABSPATH . $file)) {
$include_data[] = ABSPATH . $file;
}
}
closedir($handle);
}
//exclude paths
$exclude_data = array();
if (!empty($exclude) && is_array($exclude)) {
foreach ($exclude as $data) {
if (is_dir(ABSPATH . $data))
$exclude_data[] = $data . '/';
else
$exclude_data[] = $data;
}
}
foreach ($remove as $rem) {
$exclude_data[] = $rem . '/';
}
if($fail_safe_files && $disable_comp){
$result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
}
elseif(!$fail_safe_files && $disable_comp){
$result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_NO_COMPRESSION);
}
elseif($fail_safe_files && !$disable_comp){
$result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
}
else{
$result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data);
}
iwp_mmb_print_flush('Files ZIP PCL: End');
if (!$result) {
@unlink($backup_file);
return array(
'error' => 'Failed to zip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
);
}
//}
}
//Reconnect
function fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp){
//$this->back_hack($task_name, 'DB ZIP PCL: Start');
iwp_mmb_print_flush('DB ZIP PCL: Start');
define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
$archive = new IWPPclZip($backup_file);
if($fail_safe_files && $disable_comp){
$result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
}
elseif(!$fail_safe_files && $disable_comp){
$result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION);
}
elseif($fail_safe_files && !$disable_comp){
$result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
}
else{
$result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR);
}
//$this->back_hack($task_name, 'DB ZIP PCL: End');
iwp_mmb_print_flush('DB ZIP PCL: End');
@unlink($db_result);
@unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
@rmdir(IWP_DB_DIR);
if (!$result_db) {
return array(
'error' => 'Failed to zip database. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
);
}
}
/**
* Zipping database dump and index.php in folder iwp_db by ZipArchive class, requires php zip extension.
*
* @param string $task_name the name of backup task
* @param string $db_result relative path to database dump file
* @param string $backup_file absolute path to zip file
* @return bool is compress successful or not
*/
function zip_archive_backup_db($task_name, $db_result, $backup_file) {
$disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
if (!$disable_comp) {
$this->_log("Compression is not supported by ZipArchive");
}
$zip = new ZipArchive();
$result = $zip->open($backup_file, ZIPARCHIVE::OVERWRITE); // Tries to open $backup_file for acrhiving
if ($result === true) {
$result = $result && $zip->addFile(IWP_BACKUP_DIR.'/iwp_db/index.php', "iwp_db/index.php"); // Tries to add iwp_db/index.php to $backup_file
$result = $result && $zip->addFile($db_result, "iwp_db/" . basename($db_result)); // Tries to add db dump form iwp_db dir to $backup_file
$result = $result && $zip->close(); // Tries to close $backup_file
} else {
$result = false;
}
return $result; // true if $backup_file iz zipped successfully, false if error is occured in zip process
}
/**
* Zipping whole site root folder and append to backup file with database dump
* by ZipArchive class, requires php zip extension.
*
* @param string $task_name the name of backup task
* @param string $backup_file absolute path to zip file
* @param array $exclude array of files of folders to exclude, relative to site's root
* @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
* @return array|bool true if successful or an array with error message if not
*/
function zip_archive_backup($task_name, $backup_file, $exclude, $include, $overwrite = false) {
$filelist = $this->get_backup_files($exclude, $include);
$disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
if (!$disable_comp) {
$this->_log("Compression is not supported by ZipArchive");
}
$zip = new ZipArchive();
if ($overwrite) {
$result = $zip->open($backup_file, ZipArchive::OVERWRITE); // Tries to open $backup_file for acrhiving
} else {
$result = $zip->open($backup_file); // Tries to open $backup_file for acrhiving
}
if ($result === true) {
foreach ($filelist as $file) {
iwp_mmb_auto_print('zip_archive_backup');
$result = $result && $zip->addFile($file, sprintf("%s", str_replace(ABSPATH, '', $file))); // Tries to add a new file to $backup_file
}
$result = $result && $zip->close(); // Tries to close $backup_file
} else {
$result = false;
}
return $result; // true if $backup_file iz zipped successfully, false if error is occured in zip process
}
/**
* Gets an array of relative paths of all files in site root recursively.
* By default, there are all files from root folder, all files from folders wp-admin, wp-content, wp-includes recursively.
* Parameter $include adds other folders from site root, and excludes any file or folder by relative path to site's root.
*
* @param array $exclude array of files of folders to exclude, relative to site's root
* @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
* @return array array with all files in site root dir
*/
function get_backup_files($exclude, $include) {
$add = array(
trim(WPINC),
trim(basename(WP_CONTENT_DIR)),
"wp-admin"
);
$include = array_merge($add, $include);
$filelist = array();
if ($handle = opendir(ABSPATH)) {
while (false !== ($file = readdir($handle))) {
if (is_dir($file) && file_exists(ABSPATH . $file) && !(in_array($file, $include))) {
$exclude[] = $file;
}
}
closedir($handle);
}
$filelist = get_all_files_from_dir(ABSPATH, $exclude);
return $filelist;
}
function backup_db()
{
$db_folder = IWP_DB_DIR . '/';
if (!file_exists($db_folder)) {
if (!mkdir($db_folder, 0755, true))
return array(
'error' => 'Error creating database backup folder (' . $db_folder . '). Make sure you have corrrect write permissions.'
);
$db_index_file = '<?php
global $old_url, $old_file_path;
$old_url = \''.get_option('siteurl').'\';
$old_file_path = \''.ABSPATH.'\';
';
@file_put_contents(IWP_BACKUP_DIR.'/iwp_db/index.php', $db_index_file);
}
$file = $db_folder . DB_NAME . '.sql';
if($GLOBALS['fail_safe_db']){
$result = $this->backup_db_php($file);
return $result;
}
$result = $this->backup_db_dump($file); // try mysqldump always then fallback to php dump
return $result;
}
function backup_db_dump($file)
{
global $wpdb;
$paths = $this->check_mysql_paths();
$brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
$command = $brace . $paths['mysqldump'] . $brace . ' --force --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --add-drop-table --skip-lock-tables "' . DB_NAME . '" > ' . $brace . $file . $brace;
iwp_mmb_print_flush('DB DUMP CMD: Start');
ob_start();
$result = $this->iwp_mmb_exec($command);
ob_get_clean();
iwp_mmb_print_flush('DB DUMP CMD: End');
if (!$result) { // Fallback to php
$result = $this->backup_db_php($file);
return $result;
}
if (filesize($file) == 0 || !is_file($file) || !$result) {
@unlink($file);
return false;
} else {
return $file;
}
}
function backup_db_php($file)
{
global $wpdb;
if(empty($GLOBALS['fail_safe_db'])){
iwp_mmb_print_flush('DB DUMP PHP Normal: Start');
$fp = fopen( $file, 'w' );
if ( !mysql_ping( $wpdb->dbh ) ) {
mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
mysql_select_db( DB_NAME );
}
$_count = 0;
$insert_sql = '';
$result = mysql_query( 'SHOW TABLES' );
if(!$result)
{
return array(
'error' => 'MySQL '.mysql_error()." "
);
}
while( $row = mysql_fetch_row( $result ) ) {
$tables[]=$row[0];
//array_push( $tables, $row[0] );
}
//$tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
foreach ($tables as $table) {
iwp_mmb_auto_print('backup_db_php_normal');
$insert_sql .= "DROP TABLE IF EXISTS $table;";
//create table
$table_descr_query = mysql_query("SHOW CREATE TABLE `$table`");
$fetch_table_descr_row = mysql_fetch_array( $table_descr_query );
$insert_sql .= "\n\n" . $fetch_table_descr_row[1] . ";\n\n";
fwrite( $fp, $insert_sql );
$insert_sql = '';
$table_query = mysql_query("SELECT * FROM `$table`");
$num_fields = mysql_num_fields($table_query);
while ( $fetch_row = mysql_fetch_array( $table_query ) ) {
$insert_sql .= "INSERT INTO $table VALUES(";
for ( $n=1; $n<=$num_fields; $n++ ) {
$m = $n - 1;
if ( $fetch_row[$m] === NULL ) {
$insert_sql .= "NULL, ";
} else {
$insert_sql .= "'" . mysql_real_escape_string( $fetch_row[$m] ) . "', ";
}
}
$insert_sql = substr( $insert_sql, 0, -2 );
$insert_sql .= ");\n";
fwrite( $fp, $insert_sql );
$insert_sql = '';
// Help keep HTTP alive.
$_count++;
if ($_count >= 400) {
echo ' ';
flush();
$_count = 0;
}
} // End foreach $tables.
$insert_sql .= "\n\n\n";
// testing: mysql_close( $wpdb->dbh );
// Verify database is still connected and working properly. Sometimes mysql runs out of memory and dies in the above foreach.
// No point in reconnecting as we can NOT trust that our dump was succesful anymore (it most likely was not).
if ( @mysql_ping( $wpdb->dbh ) ) { // Still connected to database.
mysql_free_result( $table_query ); // Free memory.
} /*else { // Database not connected.
return false;
}*/
// Help keep HTTP alive.
echo ' ';
flush();
//unset( $tables[$table_key] );
}
fclose( $fp );
unset ($fp);
iwp_mmb_print_flush('DB DUMP PHP Normal: End');
}
else{
iwp_mmb_print_flush('DB DUMP PHP Fail-safe: Start');
file_put_contents($file, '');//safe to reset any old data
$tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
foreach ($tables as $table) {
//drop existing table
$dump_data = "DROP TABLE IF EXISTS $table[0];";
file_put_contents($file, $dump_data, FILE_APPEND);
//create table
$create_table = $wpdb->get_row("SHOW CREATE TABLE $table[0]", ARRAY_N);
$dump_data = "\n\n" . $create_table[1] . ";\n\n";
file_put_contents($file, $dump_data, FILE_APPEND);
$count = $wpdb->get_var("SELECT count(*) FROM $table[0]");
if ($count > 100)
$count = ceil($count / 100);
else if ($count > 0)
$count = 1;
for ($i = 0; $i < $count; $i++) {
iwp_mmb_auto_print('backup_db_php_fail_safe');
$low_limit = $i * 100;
$qry = "SELECT * FROM $table[0] LIMIT $low_limit, 100";
$rows = $wpdb->get_results($qry, ARRAY_A);
if (is_array($rows)) {
foreach ($rows as $row) {
//insert single row
$dump_data = "INSERT INTO $table[0] VALUES(";
$num_values = count($row);
$j = 1;
foreach ($row as $value) {
$value = addslashes($value);
$value = preg_replace("/\n/Ui", "\\n", $value);
$num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
$j++;
unset($value);
}
$dump_data .= ");\n";
file_put_contents($file, $dump_data, FILE_APPEND);
}
}
}
$dump_data = "\n\n\n";
file_put_contents($file, $dump_data, FILE_APPEND);
unset($rows);
unset($dump_data);
}
iwp_mmb_print_flush('DB DUMP PHP Fail-safe: End');
}
if (filesize($file) == 0 || !is_file($file)) {
@unlink($file);
return array(
'error' => 'Database backup failed. Try to enable MySQL dump on your server.'
);
}
return $file;
}
/**
* Copies a directory from one location to another via the WordPress Filesystem Abstraction.
* Assumes that WP_Filesystem() has already been called and setup.
*
* @since 2.5.0
*
* @param string $from source directory
* @param string $to destination directory
* @param array $skip_list a list of files/folders to skip copying
* @return mixed WP_Error on failure, True on success.
*/
function iwp_mmb_direct_to_any_copy_dir($from, $to, $skip_list = array() ) {//$from => direct file system, $to => automatic filesystem
global $wp_filesystem;
$wp_temp_direct = new WP_Filesystem_Direct('');
$dirlist = $wp_temp_direct->dirlist($from);
$from = trailingslashit($from);
$to = trailingslashit($to);
$skip_regex = '';
foreach ( (array)$skip_list as $key => $skip_file )
$skip_regex .= preg_quote($skip_file, '!') . '|';
if ( !empty($skip_regex) )
$skip_regex = '!(' . rtrim($skip_regex, '|') . ')$!i';
foreach ( (array) $dirlist as $filename => $fileinfo ) {
if ( !empty($skip_regex) )
if ( preg_match($skip_regex, $from . $filename) )
continue;
if ( 'f' == $fileinfo['type'] ) {
if ( ! $this->iwp_mmb_direct_to_any_copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
// If copy failed, chmod file to 0644 and try again.
$wp_filesystem->chmod($to . $filename, 0644);
if ( ! $this->iwp_mmb_direct_to_any_copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
return new WP_Error('copy_failed', __('Could not copy file.'), $to . $filename);
}
} elseif ( 'd' == $fileinfo['type'] ) {
if ( !$wp_filesystem->is_dir($to . $filename) ) {
if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
return new WP_Error('mkdir_failed', __('Could not create directory.'), $to . $filename);
}
$result = $this->iwp_mmb_direct_to_any_copy_dir($from . $filename, $to . $filename, $skip_list);
if ( is_wp_error($result) )
return $result;
}
}
return true;
}
function iwp_mmb_direct_to_any_copy($source, $destination, $overwrite = false, $mode = false){
global $wp_filesystem;
if($wp_filesystem->method == 'direct'){
return $wp_filesystem->copy($source, $destination, $overwrite, $mode);
}
elseif($wp_filesystem->method == 'ftpext' || $wp_filesystem->method == 'ftpsockets'){
if ( ! $overwrite && $wp_filesystem->exists($destination) )
return false;
//$content = $this->get_contents($source);
// if ( false === $content)
// return false;
//put content
//$tempfile = wp_tempnam($file);
$source_handle = fopen($source, 'r');
if ( ! $source_handle )
return false;
//fwrite($temp, $contents);
//fseek($temp, 0); //Skip back to the start of the file being written to
$sample_content = fread($source_handle, (1024 * 1024 * 2));//1024 * 1024 * 2 => 2MB
fseek($source_handle, 0); //Skip back to the start of the file being written to
$type = $wp_filesystem->is_binary($sample_content) ? FTP_BINARY : FTP_ASCII;
unset($sample_content);
if($wp_filesystem->method == 'ftpext'){
$ret = @ftp_fput($wp_filesystem->link, $destination, $source_handle, $type);
}
elseif($wp_filesystem->method == 'ftpsockets'){
$wp_filesystem->ftp->SetType($type);
$ret = $wp_filesystem->ftp->fput($destination, $source_handle);
}
fclose($source_handle);
unlink($source);//to immediately save system space
//unlink($tempfile);
$wp_filesystem->chmod($destination, $mode);
return $ret;
//return $this->put_contents($destination, $content, $mode);
}
}
function restore($args)
{
global $wpdb, $wp_filesystem;
if (empty($args)) {
return false;
}
extract($args);
$this->set_memory();
$unlink_file = true; //Delete file after restore
include_once ABSPATH . 'wp-admin/includes/file.php';
//Detect source
if ($backup_url) {
//This is for clone (overwrite)
$backup_file = download_url($backup_url);
if (is_wp_error($backup_file)) {
return array(
'error' => 'Unable to download backup file ('.$backup_file->get_error_message().')'
);
}
$what = 'full';
} else {
$tasks = $this->tasks;
$task = $tasks[$task_name];
if (isset($task['task_results'][$result_id]['server'])) {
$backup_file = $task['task_results'][$result_id]['server']['file_path'];
$unlink_file = false; //Don't delete file if stored on server
} elseif (isset($task['task_results'][$result_id]['ftp'])) {
$ftp_file = $task['task_results'][$result_id]['ftp'];
$args = $task['task_args']['account_info']['iwp_ftp'];
$args['backup_file'] = $ftp_file;
iwp_mmb_print_flush('FTP download: Start');
$backup_file = $this->get_ftp_backup($args);
iwp_mmb_print_flush('FTP download: End');
if ($backup_file == false) {
return array(
'error' => 'Failed to download file from FTP.'
);
}
} elseif (isset($task['task_results'][$result_id]['amazons3'])) {
$amazons3_file = $task['task_results'][$result_id]['amazons3'];
$args = $task['task_args']['account_info']['iwp_amazon_s3'];
$args['backup_file'] = $amazons3_file;
iwp_mmb_print_flush('Amazon S3 download: Start');
$backup_file = $this->get_amazons3_backup($args);
iwp_mmb_print_flush('Amazon S3 download: End');
if ($backup_file == false) {
return array(
'error' => 'Failed to download file from Amazon S3.'
);
}
} elseif(isset($task['task_results'][$result_id]['dropbox'])){
$dropbox_file = $task['task_results'][$result_id]['dropbox'];
$args = $task['task_args']['account_info']['iwp_dropbox'];
$args['backup_file'] = $dropbox_file;
iwp_mmb_print_flush('Dropbox download: Start');
$backup_file = $this->get_dropbox_backup($args);
iwp_mmb_print_flush('Dropbox download: End');
if ($backup_file == false) {
return array(
'error' => 'Failed to download file from Dropbox.'
);
}
}
$what = $tasks[$task_name]['task_args']['what'];
}
$this->wpdb_reconnect();
/////////////////// dev ////////////////////////
if (!$this->is_server_writable()) {
return array(
'error' => 'Failed, please add FTP details'
);
}
$url = wp_nonce_url('index.php?page=iwp_no_page','iwp_fs_cred');
ob_start();
if (false === ($creds = request_filesystem_credentials($url, '', false, ABSPATH, null) ) ) {
return array(
'error' => 'Unable to get file system credentials'
); // stop processing here
}
ob_end_clean();
if ( ! WP_Filesystem($creds, ABSPATH) ) {
//request_filesystem_credentials($url, '', true, false, null);
return array(
'error' => 'Unable to initiate file system. Please check you have entered valid FTP credentials.'
); // stop processing here
//return;
}
require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php');//will be used to copy from temp directory
// do process
$temp_dir = get_temp_dir();
$new_temp_folder = untrailingslashit($temp_dir);
$temp_uniq = md5(microtime(1));//should be random
while (is_dir($new_temp_folder .'/'. $temp_uniq )) {
$temp_uniq = md5(microtime(1));
}
$new_temp_folder = trailingslashit($new_temp_folder .'/'. $temp_uniq);
$is_dir_created = mkdir($new_temp_folder);// new folder should be empty
if(!$is_dir_created){
return array(
'error' => 'Unable to create a temporary directory.'
);
}
//echo '<pre>$new_temp_folder:'; var_dump($new_temp_folder); echo '</pre>';
$remote_abspath = $wp_filesystem->abspath();
if(!empty($remote_abspath)){
$remote_abspath = trailingslashit($remote_abspath);
}else{
return array(
'error' => 'Unable to locate WP root directory using file system.'
);
}
//global $wp_filesystem;
// $wp_filesystem->put_contents(
// '/tmp/example.txt',
// 'Example contents of a file',
// FS_CHMOD_FILE // predefined mode settings for WP files
// );
/////////////////// dev ////////////////////////
if ($backup_file && file_exists($backup_file)) {
if ($overwrite) {//clone only fresh or existing to existing
//Keep old db credentials before overwrite
if (!$wp_filesystem->copy($remote_abspath . 'wp-config.php', $remote_abspath . 'iwp-temp-wp-config.php', true)) {
if($unlink_file) @unlink($backup_file);
return array(
'error' => 'Error creating wp-config. Please check your write permissions.'
);
}
$db_host = DB_HOST;
$db_user = DB_USER;
$db_password = DB_PASSWORD;
$home = rtrim(get_option('home'), "/");
$site_url = get_option('site_url');
$clone_options = array();
if (trim($clone_from_url) || trim($iwp_clone) || trim($maintain_old_key)) {
$clone_options['iwp_client_nossl_key'] = get_option('iwp_client_nossl_key');
$clone_options['iwp_client_public_key'] = get_option('iwp_client_public_key');
$clone_options['iwp_client_action_message_id'] = get_option('iwp_client_action_message_id');
}
$clone_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_backup_tasks'));
$clone_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
$clone_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
} else {
$restore_options = array();
$restore_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
$restore_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
$restore_options['iwp_client_user_hit_count'] = serialize(get_option('iwp_client_user_hit_count'));
$restore_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_backup_tasks'));
}
//Backup file will be extracted to a temporary path
//chdir(ABSPATH);
$unzip = $this->get_unzip();
$command = "$unzip -o $backup_file -d $new_temp_folder";
iwp_mmb_print_flush('ZIP Extract CMD: Start');
ob_start();
$result = $this->iwp_mmb_exec($command);
ob_get_clean();
iwp_mmb_print_flush('ZIP Extract CMD: End');
if (!$result) { //fallback to pclzip
define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
//require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
iwp_mmb_print_flush('ZIP Extract PCL: Start');
$archive = new IWPPclZip($backup_file);
$result = $archive->extract(PCLZIP_OPT_PATH, $new_temp_folder, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
iwp_mmb_print_flush('ZIP Extract PCL: End');
}
$this->wpdb_reconnect();
if ($unlink_file) {
@unlink($backup_file);
}
if (!$result) {
return array(
'error' => 'Failed to unzip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
);
}
$db_result = $this->restore_db($new_temp_folder);
if (!$db_result) {
return array(
'error' => 'Error restoring database.'
);
} else if(is_array($db_result) && isset($db_result['error'])){
return array(
'error' => $db_result['error']
);
}
} else {
return array(
'error' => 'Backup file not found.'
);
}
//copy files from temp to ABSPATH
$copy_result = $this->iwp_mmb_direct_to_any_copy_dir($new_temp_folder, $remote_abspath);
if ( is_wp_error($copy_result) ){
$wp_temp_direct2 = new WP_Filesystem_Direct('');
$wp_temp_direct2->delete($new_temp_folder, true);
return $copy_result;
}
$this->wpdb_reconnect();
//Replace options and content urls
if ($overwrite) {//fresh WP package or existing to existing site
//Get New Table prefix
$new_table_prefix = trim($this->get_table_prefix());
//Retrieve old wp_config
//@unlink(ABSPATH . 'wp-config.php');
$wp_filesystem->delete($remote_abspath . 'wp-config.php', false, 'f');
//Replace table prefix
//$lines = file(ABSPATH . 'iwp-temp-wp-config.php');
$lines = $wp_filesystem->get_contents_array($remote_abspath . 'iwp-temp-wp-config.php');
$new_lines = '';
foreach ($lines as $line) {
if (strstr($line, '$table_prefix')) {
$line = '$table_prefix = "' . $new_table_prefix . '";' . PHP_EOL;
}
$new_lines .= $line;
//file_put_contents(ABSPATH . 'wp-config.php', $line, FILE_APPEND);
}
$wp_filesystem->put_contents($remote_abspath . 'wp-config.php', $new_lines);
//@unlink(ABSPATH . 'iwp-temp-wp-config.php');
$wp_filesystem->delete($remote_abspath . 'iwp-temp-wp-config.php', false, 'f');
//Replace options
$query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
$old = $wpdb->get_var($query);
$old = rtrim($old, "/");
$query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'home'";
$wpdb->query($wpdb->prepare($query, $home));
$query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'siteurl'";
$wpdb->query($wpdb->prepare($query, $home));
//Replace content urls
$regexp1 = 'src="(.*)'.$old.'(.*)"';
$regexp2 = 'href="(.*)'.$old.'(.*)"';
$query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, %s,%s) WHERE post_content REGEXP %s OR post_content REGEXP %s";
$wpdb->query($wpdb->prepare($query, $old, $home, $regexp1, $regexp2));
if (trim($new_password)) {
$new_password = wp_hash_password($new_password);
}
if (!trim($clone_from_url) && !trim($iwp_clone)) {
if ($new_user && $new_password) {
$query = "UPDATE " . $new_table_prefix . "users SET user_login = %s, user_pass = %s WHERE user_login = %s";
$wpdb->query($wpdb->prepare($query, $new_user, $new_password, $old_user));
}
} else {
// if ($iwp_clone) {
if ($admin_email) {
//Clean Install
$query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'admin_email'";
$wpdb->query($wpdb->prepare($query, $admin_email));
$query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
$temp_user = $wpdb->get_row($query);
if (!empty($temp_user)) {
$query = "UPDATE " . $new_table_prefix . "users SET user_email=%s, user_login = %s, user_pass = %s WHERE user_login = %s";
$wpdb->query($wpdb->prepare($query, $admin_email, $new_user, $new_password, $temp_user->user_login));
}
}
// }
//if ($clone_from_url) {
if ($new_user && $new_password) {
$query = "UPDATE " . $new_table_prefix . "users SET user_pass = %s WHERE user_login = %s";
$wpdb->query($wpdb->prepare($query, $new_password, $new_user));
}
// }
}
if (is_array($clone_options) && !empty($clone_options)) {
foreach ($clone_options as $key => $option) {
if (!empty($key)) {
$query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = %s";
$res = $wpdb->get_var($wpdb->prepare($query, $key));
if ($res == false) {
$query = "INSERT INTO " . $new_table_prefix . "options (option_value,option_name) VALUES(%s,%s)";
$wpdb->query($wpdb->prepare($query, $option, $key));
} else {
$query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = %s";
$wpdb->query($wpdb->prepare($query, $option, $key));
}
}
}
}
//Remove hit count
$query = "DELETE FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_user_hit_count'";
$wpdb->query($query);
//Check for .htaccess permalinks update
$this->replace_htaccess($home, $remote_abspath);
} else {
//restore client options
if (is_array($restore_options) && !empty($restore_options)) {
foreach ($restore_options as $key => $option) {
if (!empty($key)) {
$query = "SELECT option_value FROM " . $wpdb->base_prefix . "options WHERE option_name = %s";
$res = $wpdb->get_var($wpdb->prepare($query, $key));
if ($res == false) {
$query = "INSERT INTO " . $wpdb->base_prefix . "options (option_value,option_name) VALUES(%s,%s)";
$wpdb->query($wpdb->prepare($query, $option, $key));
} else {
$query = "UPDATE " . $wpdb->base_prefix . "options SET option_value = %s WHERE option_name = %s";
$wpdb->query($wpdb->prepare($query, $option, $key));
}
}
/*$test = update_option($key,$option);*/
}
}
}
//clear the temp directory
$wp_temp_direct2 = new WP_Filesystem_Direct('');
$wp_temp_direct2->delete($new_temp_folder, true);
return !empty($new_user) ? $new_user : true ;
}
function restore_db($new_temp_folder)
{
global $wpdb;
$paths = $this->check_mysql_paths();
$file_path = $new_temp_folder . '/iwp_db';
@chmod($file_path,0755);
$file_name = glob($file_path . '/*.sql');
$file_name = $file_name[0];
if(!$file_name){
return array('error' => 'Cannot access database file.');
}
$brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
$command = $brace . $paths['mysql'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --default-character-set="utf8" ' . DB_NAME . ' < ' . $brace . $file_name . $brace;
iwp_mmb_print_flush('DB Restore CMD: Start');
ob_start();
$result = $this->iwp_mmb_exec($command);
ob_get_clean();
iwp_mmb_print_flush('DB Restore CMD: End');
if (!$result) {
//try php
$this->restore_db_php($file_name);
}
@unlink($file_name);
@unlink(dirname($file_name).'/index.php');
@rmdir(dirname($file_name));//remove its folder
return true;
}
function restore_db_php($file_name)
{
$this->wpdb_reconnect();
global $wpdb;
$wpdb->query("SET NAMES 'utf8'");
$current_query = '';
// Read in entire file
$lines = file($file_name);
// Loop through each line
if(!empty($lines)){
foreach ($lines as $line) {
iwp_mmb_auto_print('restore_db_php');
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current query
$current_query .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
// Perform the query
$result = $wpdb->query($current_query);
if ($result === false)
return false;
// Reset temp variable to empty
$current_query = '';
}
}
}
return true;
}
function get_table_prefix()
{
$lines = file(ABSPATH . 'wp-config.php');
foreach ($lines as $line) {
if (strstr($line, '$table_prefix')) {
$pattern = "/(\'|\")[^(\'|\")]*/";
preg_match($pattern, $line, $matches);
$prefix = substr($matches[0], 1);
return $prefix;
break;
}
}
return 'wp_'; //default
}
function optimize_tables()
{
global $wpdb;
$query = 'SHOW TABLE STATUS';
$tables = $wpdb->get_results($query, ARRAY_A);
foreach ($tables as $table) {
if (in_array($table['Engine'], array(
'MyISAM',
'ISAM',
'HEAP',
'MEMORY',
'ARCHIVE'
)))
$table_string .= $table['Name'] . ",";
elseif ($table['Engine'] == 'InnoDB') {
$optimize = $wpdb->query("ALTER TABLE {$table['Name']} ENGINE=InnoDB");
}
}
if(!empty($table_string)){
$table_string = rtrim($table_string, ',');
$optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
}
return $optimize ? true : false;
}
### Function: Auto Detect MYSQL and MYSQL Dump Paths
function check_mysql_paths()
{
global $wpdb;
$paths = array(
'mysql' => '',
'mysqldump' => ''
);
if (substr(PHP_OS, 0, 3) == 'WIN') {
$mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
if ($mysql_install) {
$install_path = str_replace('\\', '/', $mysql_install->Value);
$paths['mysql'] = $install_path . 'bin/mysql.exe';
$paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
} else {
$paths['mysql'] = 'mysql.exe';
$paths['mysqldump'] = 'mysqldump.exe';
}
} else {
$paths['mysql'] = $this->iwp_mmb_exec('which mysql', true);
if (empty($paths['mysql']))
$paths['mysql'] = 'mysql'; // try anyway
$paths['mysqldump'] = $this->iwp_mmb_exec('which mysqldump', true);
if (empty($paths['mysqldump']))
$paths['mysqldump'] = 'mysqldump'; // try anyway
}
return $paths;
}
//Check if exec, system, passthru functions exist
function check_sys()
{
if ($this->iwp_mmb_function_exists('exec'))
return 'exec';
if ($this->iwp_mmb_function_exists('system'))
return 'system';
if ($this->iwp_mmb_function_exists('passhtru'))
return 'passthru';
return false;
}
function iwp_mmb_exec($command, $string = false, $rawreturn = false)
{
if ($command == '')
return false;
if ($this->iwp_mmb_function_exists('exec')) {
$log = @exec($command, $output, $return);
if ($string)
return $log;
if ($rawreturn)
return $return;
return $return ? false : true;
} elseif ($this->iwp_mmb_function_exists('system')) {
$log = @system($command, $return);
if ($string)
return $log;
if ($rawreturn)
return $return;
return $return ? false : true;
} elseif ($this->iwp_mmb_function_exists('passthru') && !$string) {
$log = passthru($command, $return);
if ($rawreturn)
return $return;
return $return ? false : true;
}
if ($rawreturn)
return -1;
return false;
}
function get_zip()
{
$zip = $this->iwp_mmb_exec('which zip', true);
if (!$zip)
$zip = "zip";
return $zip;
}
function get_unzip()
{
$unzip = $this->iwp_mmb_exec('which unzip', true);
if (!$unzip)
$unzip = "unzip";
return $unzip;
}
function check_backup_compat()
{
$reqs = array();
if (strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0) {
$reqs['Server OS']['status'] = 'Linux (or compatible)';
$reqs['Server OS']['pass'] = true;
} else {
$reqs['Server OS']['status'] = 'Windows';
$reqs['Server OS']['pass'] = true;
$pass = false;
}
$reqs['PHP Version']['status'] = phpversion();
if ((float) phpversion() >= 5.1) {
$reqs['PHP Version']['pass'] = true;
} else {
$reqs['PHP Version']['pass'] = false;
$pass = false;
}
if (is_writable(WP_CONTENT_DIR)) {
$reqs['Backup Folder']['status'] = "writable";
$reqs['Backup Folder']['pass'] = true;
} else {
$reqs['Backup Folder']['status'] = "not writable";
$reqs['Backup Folder']['pass'] = false;
}
$file_path = IWP_BACKUP_DIR;
$reqs['Backup Folder']['status'] .= ' (' . $file_path . ')';
if ($func = $this->check_sys()) {
$reqs['Execute Function']['status'] = $func;
$reqs['Execute Function']['pass'] = true;
} else {
$reqs['Execute Function']['status'] = "not found";
$reqs['Execute Function']['info'] = "(will try PHP replacement)";
$reqs['Execute Function']['pass'] = false;
}
$reqs['Zip']['status'] = $this->get_zip();
$reqs['Zip']['pass'] = true;
$reqs['Unzip']['status'] = $this->get_unzip();
$reqs['Unzip']['pass'] = true;
$paths = $this->check_mysql_paths();
if (!empty($paths['mysqldump'])) {
$reqs['MySQL Dump']['status'] = $paths['mysqldump'];
$reqs['MySQL Dump']['pass'] = true;
} else {
$reqs['MySQL Dump']['status'] = "not found";
$reqs['MySQL Dump']['info'] = "(will try PHP replacement)";
$reqs['MySQL Dump']['pass'] = false;
}
$exec_time = ini_get('max_execution_time');
$reqs['Execution time']['status'] = $exec_time ? $exec_time . "s" : 'unknown';
$reqs['Execution time']['pass'] = true;
$mem_limit = ini_get('memory_limit');
$reqs['Memory limit']['status'] = $mem_limit ? $mem_limit : 'unknown';
$reqs['Memory limit']['pass'] = true;
return $reqs;
}
function ftp_backup($args)
{
extract($args);
//Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder, $ftp_site_folder
$port = $ftp_port ? $ftp_port : 21; //default port is 21
if ($ftp_ssl) {
if (function_exists('ftp_ssl_connect')) {
$conn_id = ftp_ssl_connect($ftp_hostname,$port);
if ($conn_id === false) {
return array(
'error' => 'Failed to connect to ' . $ftp_hostname,
'partial' => 1
);
}
} else {
return array(
'error' => 'Your server doesn\'t support FTP SSL',
'partial' => 1
);
}
} else {
if (function_exists('ftp_connect')) {
$conn_id = ftp_connect($ftp_hostname,$port);
if ($conn_id === false) {
return array(
'error' => 'Failed to connect to ' . $ftp_hostname,
'partial' => 1
);
}
} else {
return array(
'error' => 'Your server doesn\'t support FTP',
'partial' => 1
);
}
}
$login = @ftp_login($conn_id, $ftp_username, $ftp_password);
if ($login === false) {
return array(
'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
'partial' => 1
);
}
if($ftp_passive){
@ftp_pasv($conn_id,true);
}
@ftp_mkdir($conn_id, $ftp_remote_folder);
if ($ftp_site_folder) {
$ftp_remote_folder .= '/' . $this->site_name;
}
@ftp_mkdir($conn_id, $ftp_remote_folder);
$upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
if ($upload === false) { //Try ascii
$upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_ASCII);
}
@ftp_close($conn_id);
if ($upload === false) {
return array(
'error' => 'Failed to upload file to FTP. Please check your specified path.',
'partial' => 1
);
}
return true;
}
function remove_ftp_backup($args)
{
extract($args);
//Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
$port = $ftp_port ? $ftp_port : 21; //default port is 21
if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
$conn_id = ftp_ssl_connect($ftp_hostname,$port);
} else if (function_exists('ftp_connect')) {
$conn_id = ftp_connect($ftp_hostname,$port);
}
if ($conn_id) {
$login = @ftp_login($conn_id, $ftp_username, $ftp_password);
if ($ftp_site_folder)
$ftp_remote_folder .= '/' . $this->site_name;
if($ftp_passive){
@ftp_pasv($conn_id,true);
}
$delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $backup_file);
ftp_close($conn_id);
}
}
function get_ftp_backup($args)
{
extract($args);
//Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
$port = $ftp_port ? $ftp_port : 21; //default port is 21
if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
$conn_id = ftp_ssl_connect($ftp_hostname,$port);
} else if (function_exists('ftp_connect')) {
$conn_id = ftp_connect($ftp_hostname,$port);
if ($conn_id === false) {
return false;
}
}
$login = @ftp_login($conn_id, $ftp_username, $ftp_password);
if ($login === false) {
return false;
}
if ($ftp_site_folder)
$ftp_remote_folder .= '/' . $this->site_name;
if($ftp_passive){
@ftp_pasv($conn_id,true);
}
//$temp = ABSPATH . 'iwp_temp_backup.zip';
$temp = wp_tempnam('iwp_temp_backup.zip');
$get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
if ($get === false) {
return false;
} else {
}
ftp_close($conn_id);
return $temp;
}
function dropbox_backup($args){
extract($args);
if(isset($consumer_secret) && !empty($consumer_secret)){
require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
$dropbox = new IWP_Dropbox($consumer_key, $consumer_secret);
$dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
if ($dropbox_site_folder == true)
$dropbox_destination .= '/' . $this->site_name . '/' . basename($backup_file);
else
$dropbox_destination .= '/' . basename($backup_file);
try {
$dropbox->upload($backup_file, $dropbox_destination, true);
} catch (Exception $e) {
$this->_log($e->getMessage());
return array(
'error' => $e->getMessage(),
'partial' => 1
);
}
return true;
} else {
return array(
'error' => 'Please connect your InfiniteWP panel with your Dropbox account.'
);
}
}
function remove_dropbox_backup($args) {
extract($args);
require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
$dropbox = new IWP_Dropbox($consumer_key, $consumer_secret);
$dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
if ($dropbox_site_folder == true)
$dropbox_destination .= '/' . $this->site_name;
try {
$dropbox->fileopsDelete($dropbox_destination . '/' . $backup_file);
} catch (Exception $e) {
$this->_log($e->getMessage());
/*return array(
'error' => $e->getMessage(),
'partial' => 1
);*/
}
//return true;
}
function get_dropbox_backup($args) {
extract($args);
require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
$dropbox = new IWP_Dropbox($consumer_key, $consumer_secret);
$dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
if ($dropbox_site_folder == true)
$dropbox_destination .= '/' . $this->site_name;
//$temp = ABSPATH . 'iwp_temp_backup.zip';
$temp = wp_tempnam('iwp_temp_backup.zip');
try {
$file = $dropbox->download($dropbox_destination.'/'.$backup_file);
$handle = @fopen($temp, 'w');
$result = fwrite($handle, $file);
fclose($handle);
if($result)
return $temp;
else
return false;
} catch (Exception $e) {
$this->_log($e->getMessage());
return array(
'error' => $e->getMessage(),
'partial' => 1
);
}
}
function amazons3_backup($args)
{
if ($this->iwp_mmb_function_exists('curl_init')) {
require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
extract($args);
if ($as3_site_folder == true)
$as3_directory .= '/' . $this->site_name;
try{
CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true, 'use_ssl'=>false, 'ssl_verification'=>false), '@default' => 'development'));
$s3 = new AmazonS3();
$response = $s3->create_object($as3_bucket, $as3_directory . '/' . basename($backup_file), array('fileUpload' => $backup_file));
$upload = $response->isOk();
if($upload) {
return true;
} else {
return array(
'error' => 'Failed to upload to Amazon S3. Please check your details and set upload/delete permissions on your bucket.',
'partial' => 1
);
}
}catch (Exception $e){
$err = $e->getMessage();
if($err){
return array(
'error' => 'Failed to upload to AmazonS3 ('.$err.').'
);
} else {
return array(
'error' => 'Failed to upload to Amazon S3.'
);
}
}
} else {
return array(
'error' => 'You cannot use Amazon S3 on your server. Please enable curl first.',
'partial' => 1
);
}
}
function remove_amazons3_backup($args)
{
if ($this->iwp_mmb_function_exists('curl_init')) {
require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
extract($args);
if ($as3_site_folder == true)
$as3_directory .= '/' . $this->site_name;
try{
CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true), '@default' => 'development'));
$s3 = new AmazonS3();
$s3->delete_object($as3_bucket, $as3_directory . '/' . $backup_file);
} catch (Exception $e){
}
}
}
function get_amazons3_backup($args)
{
require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
extract($args);
$temp = '';
try{
CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true), '@default' => 'development'));
$s3 = new AmazonS3();
if ($as3_site_folder == true)
$as3_directory .= '/' . $this->site_name;
//$temp = ABSPATH . 'iwp_temp_backup.zip';
$temp = wp_tempnam('iwp_temp_backup.zip');
$s3->get_object($as3_bucket, $as3_directory . '/' . $backup_file, array("fileDownload" => $temp));
} catch (Exception $e){
return $temp;
}
return $temp;
}
//IWP Remove ends here
function schedule_next($type, $schedule)
{
$schedule = explode("|", $schedule);
if (empty($schedule))
return false;
switch ($type) {
case 'daily':
if (isset($schedule[1]) && $schedule[1]) {
$delay_time = $schedule[1] * 60;
}
$current_hour = date("H");
$schedule_hour = $schedule[0];
if ($current_hour >= $schedule_hour){
$time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 1, date("Y"));
//$time ='0001#'.$current_hour.'|'.$schedule_hour;
}
else{
$time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
//$time ='0000#'.$current_hour.'|'.$schedule_hour;
}
$time = time() + 30;
break;
case 'weekly':
if (isset($schedule[2]) && $schedule[2]) {
$delay_time = $schedule[2] * 60;
}
$current_weekday = date('w');
$schedule_weekday = $schedule[1];
$current_hour = date("H");
$schedule_hour = $schedule[0];
if ($current_weekday > $schedule_weekday)
$weekday_offset = 7 - ($week_day - $task_schedule[1]);
else
$weekday_offset = $schedule_weekday - $current_weekday;
if (!$weekday_offset) { //today is scheduled weekday
if ($current_hour >= $schedule_hour)
$time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 7, date("Y"));
else
$time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
} else {
$time = mktime($schedule_hour, 0, 0, date("m"), date("d") + $weekday_offset, date("Y"));
}
break;
case 'monthly':
if (isset($schedule[2]) && $schedule[2]) {
$delay_time = $schedule[2] * 60;
}
$current_monthday = date('j');
$schedule_monthday = $schedule[1];
$current_hour = date("H");
$schedule_hour = $schedule[0];
if ($current_monthday > $schedule_monthday) {
$time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
} else if ($current_monthday < $schedule_monthday) {
$time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
} else if ($current_monthday == $schedule_monthday) {
if ($current_hour >= $schedule_hour)
$time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
else
$time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
break;
}
break;
default:
break;
}
if (isset($delay_time) && $delay_time) {
$time += $delay_time;
}
return $time;
}
//Parse task arguments for info on IWP Admin Panel
function get_backup_stats()
{
$stats = array();
$tasks = $this->tasks;
if (is_array($tasks) && !empty($tasks)) {
foreach ($tasks as $task_name => $info) {
if (is_array($info['task_results']) && !empty($info['task_results'])) {
foreach ($info['task_results'] as $key => $result) {
if (isset($result['server']) && !isset($result['error'])) {
if (!file_exists($result['server']['file_path'])) {
$info['task_results'][$key]['error'] = 'Backup created but manually removed from server.';
}
}
}
}
if (is_array($info['task_results']))
$stats[$task_name] = $info['task_results'];
}
}
return $stats;
}
function get_next_schedules()
{
$stats = array();
$tasks = $this->tasks;
if (is_array($tasks) && !empty($tasks)) {
foreach ($tasks as $task_name => $info) {
$stats[$task_name] = isset($info['task_args']['next']) ? $info['task_args']['next'] : array();
}
}
return $stats;
}
function remove_old_backups($task_name)
{
//Check for previous failed backups first
$this->cleanup();
//Remove by limit
$backups = $this->tasks;
if ($task_name == 'Backup Now') {
$num = 0;
} else {
$num = 1;
}
if ((count($backups[$task_name]['task_results']) - $num) >= $backups[$task_name]['task_args']['limit']) {
//how many to remove ?
$remove_num = (count($backups[$task_name]['task_results']) - $num - $backups[$task_name]['task_args']['limit']) + 1;
for ($i = 0; $i < $remove_num; $i++) {
//Remove from the server
if (isset($backups[$task_name]['task_results'][$i]['server'])) {
@unlink($backups[$task_name]['task_results'][$i]['server']['file_path']);
}
if (isset($backups[$task_name]['task_results'][$i]['ftp'])) {
$ftp_file = $backups[$task_name]['task_results'][$i]['ftp'];
$args = $backups[$task_name]['task_args']['account_info']['iwp_ftp'];
$args['backup_file'] = $ftp_file;
$this->remove_ftp_backup($args);
}
if (isset($backups[$task_name]['task_results'][$i]['amazons3'])) {
$amazons3_file = $backups[$task_name]['task_results'][$i]['amazons3'];
$args = $backups[$task_name]['task_args']['account_info']['iwp_amazon_s3'];
$args['backup_file'] = $amazons3_file;
$this->remove_amazons3_backup($args);
}
if (isset($backups[$task_name]['task_results'][$i]['dropbox']) && isset($backups[$task_name]['task_args']['account_info']['iwp_dropbox'])) {
//To do: dropbox remove
$dropbox_file = $backups[$task_name]['task_results'][$i]['dropbox'];
$args = $backups[$task_name]['task_args']['account_info']['iwp_dropbox'];
$args['backup_file'] = $dropbox_file;
$this->remove_dropbox_backup($args);
}
//Remove database backup info
unset($backups[$task_name]['task_results'][$i]);
} //end foreach
if (is_array($backups[$task_name]['task_results']))
$backups[$task_name]['task_results'] = array_values($backups[$task_name]['task_results']);
else
$backups[$task_name]['task_results']=array();
$this->update_tasks($backups);
return true;
}
}
/**
* Delete specified backup
* Args: $task_name, $result_id
*/
function delete_backup($args)
{
if (empty($args))
return false;
extract($args);
$tasks = $this->tasks;
$task = $tasks[$task_name];
$backups = $task['task_results'];
$backup = $backups[$result_id];
if (isset($backup['server'])) {
@unlink($backup['server']['file_path']);
}
/*
//IWP Remove starts here//IWP Remove ends here
*/
//Remove from ftp
if (isset($backup['ftp'])) {
$ftp_file = $backup['ftp'];
$args = $tasks[$task_name]['task_args']['account_info']['iwp_ftp'];
$args['backup_file'] = $ftp_file;
$this->remove_ftp_backup($args);
}
if (isset($backup['amazons3'])) {
$amazons3_file = $backup['amazons3'];
$args = $tasks[$task_name]['task_args']['account_info']['iwp_amazon_s3'];
$args['backup_file'] = $amazons3_file;
$this->remove_amazons3_backup($args);
}
if (isset($backup['dropbox'])) {
$dropbox_file = $backup['dropbox'];
$args = $tasks[$task_name]['task_args']['account_info']['iwp_dropbox'];
$args['backup_file'] = $dropbox_file;
$this->remove_dropbox_backup($args);
}
unset($backups[$result_id]);
if (count($backups)) {
$tasks[$task_name]['task_results'] = $backups;
} else {
unset($tasks[$task_name]['task_results']);
}
$this->update_tasks($tasks);
//update_option('iwp_client_backup_tasks', $tasks);
return true;
}
function cleanup()
{
$tasks = $this->tasks;
$backup_folder = WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups/';
$backup_folder_new = IWP_BACKUP_DIR . '/';
$files = glob($backup_folder . "*");
$new = glob($backup_folder_new . "*");
//Failed db files first
$db_folder = IWP_DB_DIR . '/';
$db_files = glob($db_folder . "*");
if (is_array($db_files) && !empty($db_files)) {
foreach ($db_files as $file) {
@unlink($file);
}
@unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
@rmdir(IWP_DB_DIR);
}
//clean_old folder?
if ((basename($files[0]) == 'index.php' && count($files) == 1) || (!empty($files))) { //USE (!empty($files)
foreach ($files as $file) {
@unlink($file);
}
@rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups');
@rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client'));
}
if (!empty($new)) {
foreach ($new as $b) {
$files[] = $b;
}
}
$deleted = array();
if (is_array($files) && count($files)) {
$results = array();
if (!empty($tasks)) {
foreach ((array) $tasks as $task) {
if (isset($task['task_results']) && count($task['task_results'])) {
foreach ($task['task_results'] as $backup) {
if (isset($backup['server'])) {
$results[] = $backup['server']['file_path'];
}
}
}
}
}
$num_deleted = 0;
foreach ($files as $file) {
if (!in_array($file, $results) && basename($file) != 'index.php') {
@unlink($file);
$deleted[] = basename($file);
$num_deleted++;
}
}
}
return $deleted;
}
/*
*/
function validate_task($args, $url)
{
if (!class_exists('WP_Http')) {
include_once(ABSPATH . WPINC . '/class-http.php');
}
$params = array();
$params['body'] = $args;
$result = wp_remote_post($url, $params);
if (is_array($result) && $result['body'] == 'iwp_delete_task') {
//$tasks = $this->get_backup_settings();
$tasks = $this->tasks;
unset($tasks[$args['task_name']]);
$this->update_tasks($tasks);
$this->cleanup();
exit;
} elseif(is_array($result) && $result['body'] == 'iwp_pause_task'){
return 'paused';
}
return 'ok';
}
function update_status($task_name, $status, $completed = false)
{
/* Statuses:
0 - Backup started
1 - DB dump
2 - DB ZIP
3 - Files ZIP
4 - Amazon S3
5 - Dropbox
6 - FTP
7 - Email
100 - Finished
*/
//if ($task_name != 'Backup Now') {
$tasks = $this->tasks;
$index = count($tasks[$task_name]['task_results']) - 1;
//!is_array($tasks[$task_name]['task_results'][$index]['status']) &&
if (!is_array($tasks[$task_name]['task_results'][$index]['backhack_status'])) {
//$tasks[$task_name]['task_results'][$index]['status'] = array();
$tasks[$task_name]['task_results'][$index]['backhack_status'] = array();
}
$tasks[$task_name]['task_results'][$index]['backhack_status']['adminHistoryID'] = $GLOBALS['IWP_CLIENT_HISTORY_ID'];
if (!$completed) {
//$tasks[$task_name]['task_results'][$index]['status'][] = (int) $status * (-1);
$tasks[$task_name]['task_results'][$index]['backhack_status'][$status]['start'] = microtime(true);
} else {
$status_index = count($tasks[$task_name]['task_results'][$index]['status']) - 1;
//$tasks[$task_name]['task_results'][$index]['status'][$status_index] = abs($tasks[$task_name]['task_results'][$index]['status'][$status_index]);
$tasks[$task_name]['task_results'][$index]['backhack_status'][$status]['end'] = microtime(true);
}
$this->update_tasks($tasks);
//update_option('iwp_client_backup_tasks',$tasks);
//}
}
function update_tasks($tasks)
{
$this->tasks = $tasks;
update_option('iwp_client_backup_tasks', $tasks);
}
function wpdb_reconnect(){
global $wpdb;
$old_wpdb = $wpdb;
//Reconnect to avoid timeout problem after ZIP files
if(class_exists('wpdb') && function_exists('wp_set_wpdb_vars')){
@mysql_close($wpdb->dbh);
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
wp_set_wpdb_vars();
$wpdb->options = $old_wpdb->options;//fix for multi site full backup
}
}
function replace_htaccess($url, $remote_abspath)
{
global $wp_filesystem;
//$file = @file_get_contents(ABSPATH.'.htaccess');
$file = $wp_filesystem->get_contents($remote_abspath.'.htaccess');
if ($file && strlen($file)) {
$args = parse_url($url);
$string = rtrim($args['path'], "/");
$regex = "/BEGIN WordPress(.*?)RewriteBase(.*?)\n(.*?)RewriteRule \.(.*?)index\.php(.*?)END WordPress/sm";
$replace = "BEGIN WordPress$1RewriteBase " . $string . "/ \n$3RewriteRule . " . $string . "/index.php$5END WordPress";
$file = preg_replace($regex, $replace, $file);
//@file_put_contents(ABSPATH.'.htaccess', $file);
$wp_filesystem->put_contents($remote_abspath.'.htaccess', $file);
}
}
function check_cron_remove(){
if(empty($this->tasks) || (count($this->tasks) == 1 && isset($this->tasks['Backup Now'])) ){
wp_clear_scheduled_hook('iwp_client_backup_tasks');
exit;
}
}
public function readd_tasks( $params = array() ){
global $iwp_mmb_core;
if( empty($params) || !isset($params['backups']) )
return $params;
$before = array();
$tasks = $params['backups'];
if( !empty($tasks) ){
$iwp_mmb_backup = new IWP_MMB_Backup();
if( function_exists( 'wp_next_scheduled' ) ){
if ( !wp_next_scheduled('iwp_client_backup_tasks') ) {
wp_schedule_event( time(), 'tenminutes', 'iwp_client_backup_tasks' );
}
}
foreach( $tasks as $task ){
$before[$task['task_name']] = array();
if(isset($task['secure'])){
if($decrypted = $iwp_mmb_core->_secure_data($task['secure'])){
$decrypted = maybe_unserialize($decrypted);
if(is_array($decrypted)){
foreach($decrypted as $key => $val){
if(!is_numeric($key))
$task[$key] = $val;
}
unset($task['secure']);
} else
$task['secure'] = $decrypted;
}
}
if (isset($task['account_info']) && is_array($task['account_info'])) { //only if sends from panel first time(secure data)
$task['args']['account_info'] = $task['account_info'];
}
$before[$task['task_name']]['task_args'] = $task['args'];
$before[$task['task_name']]['task_args']['next'] = $iwp_mmb_backup->schedule_next($task['args']['type'], $task['args']['schedule']);
}
}
update_option('iwp_client_backup_tasks', $before);
unset($params['backups']);
return $params;
}
function is_server_writable(){
if((!defined('FTP_HOST') || !defined('FTP_USER') || !defined('FTP_PASS')) && (get_filesystem_method(array(), ABSPATH) != 'direct'))
return false;
else
return true;
}
}
/*if( function_exists('add_filter') ){
add_filter( 'iwp_website_add', 'IWP_MMB_Backup::readd_tasks' );
}*/
if(!function_exists('get_all_files_from_dir')) {
/**
* Get all files in directory
*
* @param string $path Relative or absolute path to folder
* @param array $exclude List of excluded files or folders, relative to $path
* @return array List of all files in folder $path, exclude all files in $exclude array
*/
function get_all_files_from_dir($path, $exclude = array()) {
if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
global $directory_tree, $ignore_array;
$directory_tree = array();
foreach ($exclude as $file) {
if (!in_array($file, array('.', '..'))) {
if ($file[0] === "/") $path = substr($file, 1);
$ignore_array[] = "$path/$file";
}
}
get_all_files_from_dir_recursive($path);
return $directory_tree;
}
}
if (!function_exists('get_all_files_from_dir_recursive')) {
/**
* Get all files in directory,
* wrapped function which writes in global variable
* and exclued files or folders are read from global variable
*
* @param string $path Relative or absolute path to folder
* @return void
*/
function get_all_files_from_dir_recursive($path) {
if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
global $directory_tree, $ignore_array;
$directory_tree_temp = array();
$dh = @opendir($path);
while (false !== ($file = @readdir($dh))) {
if (!in_array($file, array('.', '..'))) {
if (!in_array("$path/$file", $ignore_array)) {
if (!is_dir("$path/$file")) {
$directory_tree[] = "$path/$file";
} else {
get_all_files_from_dir_recursive("$path/$file");
}
}
}
}
@closedir($dh);
}
}
?>
|
gpl-2.0
|
edmundgentle/schoolscript
|
SchoolScript/bin/Debug/pythonlib/Lib/test/ssl_servers.py
|
6561
|
import os
import sys
import ssl
import pprint
import socket
import urllib.parse
# Rename HTTPServer to _HTTPServer so as to avoid confusion with HTTPSServer.
from http.server import (HTTPServer as _HTTPServer,
SimpleHTTPRequestHandler, BaseHTTPRequestHandler)
from test import support
threading = support.import_module("threading")
here = os.path.dirname(__file__)
HOST = support.HOST
CERTFILE = os.path.join(here, 'keycert.pem')
# This one's based on HTTPServer, which is based on SocketServer
class HTTPSServer(_HTTPServer):
def __init__(self, server_address, handler_class, context):
_HTTPServer.__init__(self, server_address, handler_class)
self.context = context
def __str__(self):
return ('<%s %s:%s>' %
(self.__class__.__name__,
self.server_name,
self.server_port))
def get_request(self):
# override this to wrap socket with SSL
try:
sock, addr = self.socket.accept()
sslconn = self.context.wrap_socket(sock, server_side=True)
except socket.error as e:
# socket errors are silenced by the caller, print them here
if support.verbose:
sys.stderr.write("Got an error:\n%s\n" % e)
raise
return sslconn, addr
class RootedHTTPRequestHandler(SimpleHTTPRequestHandler):
# need to override translate_path to get a known root,
# instead of using os.curdir, since the test could be
# run from anywhere
server_version = "TestHTTPS/1.0"
root = here
# Avoid hanging when a request gets interrupted by the client
timeout = 5
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = urllib.parse.urlparse(path)[2]
path = os.path.normpath(urllib.parse.unquote(path))
words = path.split('/')
words = filter(None, words)
path = self.root
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
path = os.path.join(path, word)
return path
def log_message(self, format, *args):
# we override this to suppress logging unless "verbose"
if support.verbose:
sys.stdout.write(" server (%s:%d %s):\n [%s] %s\n" %
(self.server.server_address,
self.server.server_port,
self.request.cipher(),
self.log_date_time_string(),
format%args))
class StatsRequestHandler(BaseHTTPRequestHandler):
"""Example HTTP request handler which returns SSL statistics on GET
requests.
"""
server_version = "StatsHTTPS/1.0"
def do_GET(self, send_body=True):
"""Serve a GET request."""
sock = self.rfile.raw._sock
context = sock.context
body = pprint.pformat(context.session_stats())
body = body.encode('utf-8')
self.send_response(200)
self.send_header("Content-type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if send_body:
self.wfile.write(body)
def do_HEAD(self):
"""Serve a HEAD request."""
self.do_GET(send_body=False)
def log_request(self, format, *args):
if support.verbose:
BaseHTTPRequestHandler.log_request(self, format, *args)
class HTTPSServerThread(threading.Thread):
def __init__(self, context, host=HOST, handler_class=None):
self.flag = None
self.server = HTTPSServer((host, 0),
handler_class or RootedHTTPRequestHandler,
context)
self.port = self.server.server_port
threading.Thread.__init__(self)
self.daemon = True
def __str__(self):
return "<%s %s>" % (self.__class__.__name__, self.server)
def start(self, flag=None):
self.flag = flag
threading.Thread.start(self)
def run(self):
if self.flag:
self.flag.set()
try:
self.server.serve_forever(0.05)
finally:
self.server.server_close()
def stop(self):
self.server.shutdown()
def make_https_server(case, certfile=CERTFILE, host=HOST, handler_class=None):
# we assume the certfile contains both private key and certificate
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain(certfile)
server = HTTPSServerThread(context, host, handler_class)
flag = threading.Event()
server.start(flag)
flag.wait()
def cleanup():
if support.verbose:
sys.stdout.write('stopping HTTPS server\n')
server.stop()
if support.verbose:
sys.stdout.write('joining HTTPS thread\n')
server.join()
case.addCleanup(cleanup)
return server
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description='Run a test HTTPS server. '
'By default, the current directory is served.')
parser.add_argument('-p', '--port', type=int, default=4433,
help='port to listen on (default: %(default)s)')
parser.add_argument('-q', '--quiet', dest='verbose', default=True,
action='store_false', help='be less verbose')
parser.add_argument('-s', '--stats', dest='use_stats_handler', default=False,
action='store_true', help='always return stats page')
args = parser.parse_args()
support.verbose = args.verbose
if args.use_stats_handler:
handler_class = StatsRequestHandler
else:
handler_class = RootedHTTPRequestHandler
handler_class.root = os.getcwd()
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.load_cert_chain(CERTFILE)
server = HTTPSServer(("", args.port), handler_class, context)
if args.verbose:
print("Listening on https://localhost:{0.port}".format(args))
server.serve_forever(0.1)
|
gpl-2.0
|
gtessier/OPTZ
|
wp-content/themes/simple/framework/widgets/most-read.php
|
8884
|
<?php
/**
* Most_Read_Posts Widget Class
*/
class Wt_Widget_Most_Read_Posts extends WP_Widget {
function Wt_Widget_Most_Read_Posts() {
$widget_ops = array('classname' => 'widget_most_read_posts', 'description' => esc_html__( "The most read posts on your site", 'wt_admin') );
$this->WP_Widget('most_read_posts', THEME_SLUG.' - '.esc_html__('Most Read Posts', 'wt_admin'), $widget_ops);
$this->alt_option_name = 'widget_most_read_posts';
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 widget($args, $instance) {
$cache = wp_cache_get('theme_widget_most_read_posts', 'widget');
if ( !is_array($cache) )
$cache = array();
if ( isset($cache[$args['widget_id']]) ) {
echo balanceTags( $cache[$args['widget_id']] );
return;
}
ob_start();
extract($args);
$title = apply_filters('widget_title', empty($instance['title']) ? esc_html__('Most Read Posts', 'wt_front') : $instance['title'], $instance, $this->id_base);
if ( !$number = (int) $instance['number'] )
$number = 10;
else if ( $number < 1 )
$number = 1;
else if ( $number > 15 )
$number = 15;
if ( !$desc_length = (int) $instance['desc_length'] )
$desc_length = 80;
else if ( $desc_length < 1 )
$desc_length = 1;
$disable_thumbnail = $instance['disable_thumbnail'] ? '1' : '0';
$display_extra_type = $instance['display_extra_type'] ? $instance['display_extra_type'] :'time';
$query = array('showposts' => $number, 'nopaging' => 0, 'meta_key' => 'post_views_count', 'orderby'=> 'meta_value_num' , 'order'=> 'DESC', 'post_status' => 'publish', 'ignore_sticky_posts' => 1);
if(!empty($instance['cat'])){
$query['cat'] = implode(',', $instance['cat']);
}
$r = new WP_Query($query);
if ($r->have_posts()) :
?>
<section class="wt_widgetPosts widget">
<h4 class="widgettitle"><span><?php echo esc_attr( $title ); ?></span></h4>
<?php if($display_extra_type != 'none'):?>
<ul class="wt_postList">
<?php else: // end thumbsOnly ?>
<div class="postThumbs">
<?php endif;?>
<?php while ($r->have_posts()) : $r->the_post();
?>
<?php if($display_extra_type != 'none'):?><li><?php endif;?>
<?php if(!$disable_thumbnail):?>
<a class="thumb" href="<?php echo get_permalink() ?>" title="<?php the_title();?>">
<?php if (has_post_thumbnail() ): ?>
<?php the_post_thumbnail('thumb', array(55,55),array('title'=>get_the_title(),'alt'=>get_the_title())); ?>
<?php else:?>
<img src="<?php echo THEME_IMAGES;?>/widget_posts_thumbnail.png" width="55" height="55" title="<?php the_title();?>" alt="<?php the_title();?>"/>
<?php endif;//end has_post_thumbnail ?>
</a>
<?php endif;//disable_thumbnail ?>
<?php if($display_extra_type != 'none'):?>
<div class="wt_postInfo">
<a href="<?php the_permalink() ?>" class="postInfoTitle" rel="bookmark" title="<?php echo esc_attr(get_the_title() ? get_the_title() : get_the_ID()); ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?></a>
<?php if($display_extra_type == 'time'):?>
<span class="date"><?php echo get_the_date(); ?></span>
<?php elseif($display_extra_type == 'description'):?>
<p><?php echo wp_html_excerpt(get_the_excerpt(),$desc_length);?></p>
<?php elseif($display_extra_type == 'comments'):?>
<span class="comments"><?php echo comments_popup_link(esc_html__('No response ','wt_front'), esc_html__('1 Comment','wt_front'), esc_html__('% Comments','wt_front'),''); ?></span>
<?php endif;//end display extra type ?>
</div>
<div class="wt_clearboth"></div>
<?php endif; //end display post information ?>
<?php if($display_extra_type != 'none'):?></li><?php endif;?>
<?php endwhile; ?>
<?php if($display_extra_type != 'none'):?>
</ul>
<?php else: // end postThumbs ?>
</div>
<div class="wt_clearboth"></div>
<?php endif;?>
</section>
<?php
// Reset the global $the_post as this query will have stomped on it
wp_reset_query();
endif;
$cache[$args['widget_id']] = ob_get_flush();
wp_cache_set('theme_widget_most_read_posts', $cache, 'widget');
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['number'] = (int) $new_instance['number'];
$instance['desc_length'] = (int) $new_instance['desc_length'];
$instance['disable_thumbnail'] = !empty($new_instance['disable_thumbnail']) ? 1 : 0;
$instance['display_extra_type'] = $new_instance['display_extra_type'];
$instance['cat'] = $new_instance['cat'];
$this->flush_widget_cache();
$alloptions = wp_cache_get( 'alloptions', 'options' );
if ( isset($alloptions['theme_widget_most_read_posts']) )
delete_option('theme_widget_most_read_posts');
return $instance;
}
function flush_widget_cache() {
wp_cache_delete('theme_widget_most_read_posts', 'widget');
}
function form( $instance ) {
$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
$disable_thumbnail = isset( $instance['disable_thumbnail'] ) ? (bool) $instance['disable_thumbnail'] : false;
$display_extra_type = isset( $instance['display_extra_type'] ) ? $instance['display_extra_type'] : 'time';
$cat = isset($instance['cat']) ? $instance['cat'] : array();
if ( !isset($instance['number']) || !$number = (int) $instance['number'] )
$number = 5;
if ( !isset($instance['desc_length']) || !$desc_length = (int) $instance['desc_length'] )
$desc_length = 80;
$categories = get_categories('orderby=name&hide_empty=0');
?>
<p><label for="<?php echo esc_attr( $this->get_field_id('title') ); ?>"><?php esc_html_e('Title:','wt_admin'); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id('title') ); ?>" name="<?php echo esc_attr( $this->get_field_name('title') ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /></p>
<p><label for="<?php echo esc_attr( $this->get_field_id('number') ); ?>"><?php esc_html_e('Number of posts to show:', 'wt_admin'); ?></label>
<input id="<?php echo esc_attr( $this->get_field_id('number') ); ?>" name="<?php echo esc_attr( $this->get_field_name('number') ); ?>" type="text" value="<?php echo esc_attr( $number ); ?>" size="3" /></p>
<p><input type="checkbox" class="checkbox" id="<?php echo esc_attr( $this->get_field_id('disable_thumbnail') ); ?>" name="<?php echo esc_attr( $this->get_field_name('disable_thumbnail') ); ?>"<?php checked( $disable_thumbnail ); ?> />
<label for="<?php echo esc_attr( $this->get_field_id('disable_thumbnail') ); ?>"><?php esc_html_e( 'Disable Post Thumbnail?' , 'wt_admin'); ?></label></p>
<p>
<label for="<?php echo esc_attr( $this->get_field_id('display_extra_type') ); ?>"><?php esc_html_e( 'Display Extra infomation type:', 'wt_admin' ); ?></label>
<select name="<?php echo esc_attr( $this->get_field_name('display_extra_type') ); ?>" id="<?php echo esc_attr( $this->get_field_id('display_extra_type') ); ?>" class="widefat">
<option value="time"<?php selected($display_extra_type,'time');?>><?php esc_html_e( 'Time', 'wt_admin' ); ?></option>
<option value="description"<?php selected($display_extra_type,'description');?>><?php esc_html_e( 'Description', 'wt_admin' ); ?></option>
<option value="comments"<?php selected($display_extra_type,'comments');?>><?php esc_html_e( 'Comments', 'wt_admin' ); ?></option>
<option value="none"<?php selected($display_extra_type,'none');?>><?php esc_html_e( 'None', 'wt_admin' ); ?></option>
</select>
</p>
<p><label for="<?php echo esc_attr( $this->get_field_id('desc_length') ); ?>"><?php esc_html_e('Length of Description to show:', 'wt_admin'); ?></label>
<input id="<?php echo esc_attr( $this->get_field_id('desc_length') ); ?>" name="<?php echo esc_attr( $this->get_field_name('desc_length') ); ?>" type="text" value="<?php echo esc_attr( $desc_length ); ?>" size="3" /></p>
<p>
<label for="<?php echo esc_attr( $this->get_field_id('cat') ); ?>"><?php esc_html_e( 'Categorys:' , 'wt_admin'); ?></label>
<select style="height:5.5em" name="<?php echo esc_attr( $this->get_field_name('cat') ); ?>[]" id="<?php echo esc_attr( $this->get_field_id('cat') ); ?>" class="widefat" multiple="multiple">
<?php foreach($categories as $category):?>
<option value="<?php echo esc_attr( $category->term_id );?>"<?php echo in_array($category->term_id, $cat)? ' selected="selected"':'';?>><?php echo esc_attr( $category->name );?></option>
<?php endforeach;?>
</select>
</p>
<?php
}
}
|
gpl-2.0
|
joomla-projects/GSoC17_publishing_workflow
|
libraries/src/MVC/Controller/AdminController.php
|
10388
|
<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\MVC\Controller;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\Utilities\ArrayHelper;
/**
* Base class for a Joomla Administrator Controller
*
* Controller (controllers are where you put all the actual code) Provides basic
* functionality, such as rendering views (aka displaying templates).
*
* @since 1.6
*/
class AdminController extends BaseController
{
/**
* The URL option for the component.
*
* @var string
* @since 1.6
*/
protected $option;
/**
* The prefix to use with controller messages.
*
* @var string
* @since 1.6
*/
protected $text_prefix;
/**
* The URL view list variable.
*
* @var string
* @since 1.6
*/
protected $view_list;
/**
* Constructor.
*
* @param array $config An optional associative array of configuration settings.
* Recognized key values include 'name', 'default_task', 'model_path', and
* 'view_path' (this list is not meant to be comprehensive).
* @param MVCFactoryInterface $factory The factory.
* @param CmsApplication $app The JApplication for the dispatcher
* @param \JInput $input Input
*
* @since 3.0
*/
public function __construct($config = array(), MVCFactoryInterface $factory = null, $app = null, $input = null)
{
parent::__construct($config, $factory, $app, $input);
// Define standard task mappings.
// Value = 0
$this->registerTask('unpublish', 'publish');
// Value = 2
$this->registerTask('archive', 'publish');
// Value = -2
$this->registerTask('trash', 'publish');
// Value = -3
$this->registerTask('report', 'publish');
$this->registerTask('orderup', 'reorder');
$this->registerTask('orderdown', 'reorder');
// Guess the option as com_NameOfController.
if (empty($this->option))
{
$this->option = \JComponentHelper::getComponentName($this, $this->getName());
}
// Guess the \JText message prefix. Defaults to the option.
if (empty($this->text_prefix))
{
$this->text_prefix = strtoupper($this->option);
}
// Guess the list view as the suffix, eg: OptionControllerSuffix.
if (empty($this->view_list))
{
$reflect = new \ReflectionClass($this);
$r = array(0 => '', 1 => '', 2 => $reflect->getShortName());
if ($reflect->getNamespaceName())
{
$r[2] = str_replace('Controller', '', $r[2]);
}
elseif (!preg_match('/(.*)Controller(.*)/i', $reflect->getShortName(), $r))
{
throw new \Exception(\JText::_('JLIB_APPLICATION_ERROR_CONTROLLER_GET_NAME'), 500);
}
$this->view_list = strtolower($r[2]);
}
}
/**
* Removes an item.
*
* @return void
*
* @since 1.6
*/
public function delete()
{
// Check for request forgeries
\JSession::checkToken() or die(\JText::_('JINVALID_TOKEN'));
// Get items to remove from the request.
$cid = $this->input->get('cid', array(), 'array');
if (!is_array($cid) || count($cid) < 1)
{
$this->app->getLogger()->warning(\JText::_($this->text_prefix . '_NO_ITEM_SELECTED'), array('category' => 'jerror'));
}
else
{
// Get the model.
$model = $this->getModel();
// Make sure the item ids are integers
$cid = ArrayHelper::toInteger($cid);
// Remove the items.
if ($model->delete($cid))
{
$this->setMessage(\JText::plural($this->text_prefix . '_N_ITEMS_DELETED', count($cid)));
}
else
{
$this->setMessage($model->getError(), 'error');
}
// Invoke the postDelete method to allow for the child class to access the model.
$this->postDeleteHook($model, $cid);
}
$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false));
}
/**
* Function that allows child controller access to model data
* after the item has been deleted.
*
* @param \JModelLegacy $model The data model object.
* @param integer $id The validated data.
*
* @return void
*
* @since 3.1
*/
protected function postDeleteHook(\JModelLegacy $model, $id = null)
{
}
/**
* Display is not supported by this controller.
*
* @param boolean $cachable If true, the view output will be cached
* @param array $urlparams An array of safe URL parameters and their variable types, for valid values see {@link \JFilterInput::clean()}.
*
* @return \JControllerLegacy A \JControllerLegacy object to support chaining.
*
* @since 1.6
*/
public function display($cachable = false, $urlparams = array())
{
return $this;
}
/**
* Method to publish a list of items
*
* @return void
*
* @since 1.6
*/
public function publish()
{
// Check for request forgeries
\JSession::checkToken() or die(\JText::_('JINVALID_TOKEN'));
// Get items to publish from the request.
$cid = $this->input->get('cid', array(), 'array');
$data = array('publish' => 1, 'unpublish' => 0, 'archive' => 2, 'trash' => -2, 'report' => -3);
$task = $this->getTask();
$value = ArrayHelper::getValue($data, $task, 0, 'int');
if (empty($cid))
{
$this->app->getLogger()->warning(\JText::_($this->text_prefix . '_NO_ITEM_SELECTED'), array('category' => 'jerror'));
}
else
{
// Get the model.
$model = $this->getModel();
// Make sure the item ids are integers
$cid = ArrayHelper::toInteger($cid);
// Publish the items.
try
{
$model->publish($cid, $value);
$errors = $model->getErrors();
$ntext = null;
if ($value === 1)
{
if ($errors)
{
\JFactory::getApplication()->enqueueMessage(\JText::plural($this->text_prefix . '_N_ITEMS_FAILED_PUBLISHING', count($cid)), 'error');
}
else
{
$ntext = $this->text_prefix . '_N_ITEMS_PUBLISHED';
}
}
elseif ($value === 0)
{
$ntext = $this->text_prefix . '_N_ITEMS_UNPUBLISHED';
}
elseif ($value === 2)
{
$ntext = $this->text_prefix . '_N_ITEMS_ARCHIVED';
}
else
{
$ntext = $this->text_prefix . '_N_ITEMS_TRASHED';
}
if ($ntext !== null)
{
$this->setMessage(\JText::plural($ntext, count($cid)));
}
}
catch (\Exception $e)
{
$this->setMessage($e->getMessage(), 'error');
}
}
$extension = $this->input->get('extension');
$extensionURL = $extension ? '&extension=' . $extension : '';
$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $extensionURL, false));
}
/**
* Changes the order of one or more records.
*
* @return boolean True on success
*
* @since 1.6
*/
public function reorder()
{
// Check for request forgeries.
\JSession::checkToken() or jexit(\JText::_('JINVALID_TOKEN'));
$ids = $this->input->post->get('cid', array(), 'array');
$inc = $this->getTask() === 'orderup' ? -1 : 1;
$model = $this->getModel();
$return = $model->reorder($ids, $inc);
if ($return === false)
{
// Reorder failed.
$message = \JText::sprintf('JLIB_APPLICATION_ERROR_REORDER_FAILED', $model->getError());
$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false), $message, 'error');
return false;
}
else
{
// Reorder succeeded.
$message = \JText::_('JLIB_APPLICATION_SUCCESS_ITEM_REORDERED');
$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false), $message);
return true;
}
}
/**
* Method to save the submitted ordering values for records.
*
* @return boolean True on success
*
* @since 1.6
*/
public function saveorder()
{
// Check for request forgeries.
\JSession::checkToken() or jexit(\JText::_('JINVALID_TOKEN'));
// Get the input
$pks = $this->input->post->get('cid', array(), 'array');
$order = $this->input->post->get('order', array(), 'array');
// Sanitize the input
$pks = ArrayHelper::toInteger($pks);
$order = ArrayHelper::toInteger($order);
// Get the model
$model = $this->getModel();
// Save the ordering
$return = $model->saveorder($pks, $order);
if ($return === false)
{
// Reorder failed
$message = \JText::sprintf('JLIB_APPLICATION_ERROR_REORDER_FAILED', $model->getError());
$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false), $message, 'error');
return false;
}
else
{
// Reorder succeeded.
$this->setMessage(\JText::_('JLIB_APPLICATION_SUCCESS_ORDERING_SAVED'));
$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false));
return true;
}
}
/**
* Check in of one or more records.
*
* @return boolean True on success
*
* @since 1.6
*/
public function checkin()
{
// Check for request forgeries.
\JSession::checkToken() or jexit(\JText::_('JINVALID_TOKEN'));
$ids = $this->input->post->get('cid', array(), 'array');
$model = $this->getModel();
$return = $model->checkin($ids);
if ($return === false)
{
// Checkin failed.
$message = \JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError());
$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false), $message, 'error');
return false;
}
else
{
// Checkin succeeded.
$message = \JText::plural($this->text_prefix . '_N_ITEMS_CHECKED_IN', count($ids));
$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false), $message);
return true;
}
}
/**
* Method to save the submitted ordering values for records via AJAX.
*
* @return void
*
* @since 3.0
*/
public function saveOrderAjax()
{
// Get the input
$pks = $this->input->post->get('cid', array(), 'array');
$order = $this->input->post->get('order', array(), 'array');
// Sanitize the input
$pks = ArrayHelper::toInteger($pks);
$order = ArrayHelper::toInteger($order);
// Get the model
$model = $this->getModel();
// Save the ordering
$return = $model->saveorder($pks, $order);
if ($return)
{
echo '1';
}
// Close the application
$this->app->close();
}
}
|
gpl-2.0
|
TakingInitiative/wesnoth
|
src/units/unit.hpp
|
21711
|
/*
Copyright (C) 2003 - 2016 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.
*/
/** @file */
#ifndef UNIT_H_INCLUDED
#define UNIT_H_INCLUDED
#include <boost/dynamic_bitset_fwd.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/variant.hpp>
#include <bitset>
#include "units/types.hpp"
#include "units/ptr.hpp"
#include "units/id.hpp"
class display;
class display_context;
class gamemap;
struct color_t;
class team;
class unit_animation_component;
class unit_formula_manager;
class vconfig;
/// The things contained within a unit_ability_list.
typedef std::pair<const config *, map_location> unit_ability;
namespace unit_detail {
template<typename T> const T& get_or_default(const std::unique_ptr<T>& v)
{
if(v) {
return *v;
}
else {
static const T def;
return def;
}
}
}
class unit_ability_list
{
public:
unit_ability_list() :
cfgs_()
{
}
// Implemented in unit_abilities.cpp:
std::pair<int,map_location> highest(const std::string& key, int def=0) const;
std::pair<int,map_location> lowest(const std::string& key, int def=0) const;
// The following make this class usable with standard library algorithms and such:
typedef std::vector<unit_ability>::iterator iterator;
typedef std::vector<unit_ability>::const_iterator const_iterator;
iterator begin() { return cfgs_.begin(); }
const_iterator begin() const { return cfgs_.begin(); }
iterator end() { return cfgs_.end(); }
const_iterator end() const { return cfgs_.end(); }
// Vector access:
bool empty() const { return cfgs_.empty(); }
unit_ability & front() { return cfgs_.front(); }
const unit_ability & front() const { return cfgs_.front(); }
unit_ability & back() { return cfgs_.back(); }
const unit_ability & back() const { return cfgs_.back(); }
iterator erase(const iterator & erase_it) { return cfgs_.erase(erase_it); }
void push_back(const unit_ability & ability) { cfgs_.push_back(ability); }
private:
// Data:
std::vector<unit_ability> cfgs_;
};
class unit
{
public:
/**
* Clear the unit status cache for all units. Currently only the hidden
* status of units is cached this way.
*/
static void clear_status_caches();
/** The path to the leader crown overlay. */
static const std::string& leader_crown();
// Copy constructor
unit(const unit& u);
/** Initializes a unit from a config */
explicit unit(const config& cfg, bool use_traits = false, const vconfig* vcfg = nullptr);
/**
* Initializes a unit from a unit type
* only real_unit may have random traits, name and gender
* (to prevent OOS caused by RNG calls)
*/
unit(const unit_type& t, int side, bool real_unit,
unit_race::GENDER gender = unit_race::NUM_GENDERS);
virtual ~unit();
void swap (unit &);
unit& operator=(unit);
/** Advances this unit to another type */
void advance_to(const unit_type &t, bool use_traits = false);
const std::vector<std::string>& advances_to() const { return advances_to_; }
const std::vector<std::string> advances_to_translated() const;
void set_advances_to(const std::vector<std::string>& advances_to);
/**
* The id of the type of the unit.
* If you are dealing with creating units (e.g. recruitment), this is not what
* you want, as a variation can change this; use type().base_id() instead.
*/
const std::string& type_id() const { return type_->id(); }
/** The type of the unit (accounting for gender and variation). */
const unit_type& type() const { return *type_; }
/** id assigned by wml */
void set_id(const std::string& id) { id_ = id; }
const std::string& id() const { if (id_.empty()) return type_name(); else return id_; }
/** The unique internal ID of the unit */
size_t underlying_id() const { return underlying_id_.value; }
/** The unit type name */
const t_string& type_name() const {return type_name_;}
const std::string& undead_variation() const {return undead_variation_;}
const std::string& variation() const {return variation_; }
/** The unit name for display */
const t_string &name() const { return name_; }
void set_name(const t_string &name) { name_ = name; }
void rename(const std::string& name) {if (!unrenamable_) name_= name;}
/** The unit's profile */
std::string small_profile() const;
std::string big_profile() const;
/** Information about the unit -- a detailed description of it */
t_string unit_description() const { return description_; }
int hitpoints() const { return hit_points_; }
int max_hitpoints() const { return max_hit_points_; }
void set_hitpoints(int hp) { hit_points_ = hp; }
int experience() const { return experience_; }
int max_experience() const { return max_experience_; }
void set_experience(int xp) { experience_ = xp; }
void set_recall_cost(int recall_cost) { recall_cost_ = recall_cost; }
int level() const { return level_; }
void set_level(int level) { level_ = level; }
int recall_cost() const { return recall_cost_; }
void remove_movement_ai();
void remove_attacks_ai();
/** Colors for the unit's *current* hitpoints.
* @returns a color between green and red representing
* how wounded the unit is.
* The maximum_hitpoints are considered as base.
*/
color_t hp_color() const;
/** Colors for the unit's hitpoints.
* @param hitpoints the amount of hitpoints the color represents.
* @returns the color considering the current hitpoints as base.
*/
color_t hp_color(int hitpoints) const;
/** Colors for the unit's XP. */
color_t xp_color() const;
double hp_bar_scaling() const { return hp_bar_scaling_; }
double xp_bar_scaling() const { return xp_bar_scaling_; }
/** Set to true for some scenario-specific units which should not be renamed */
bool unrenamable() const { return unrenamable_; }
void set_unrenamable(bool unrenamable) { unrenamable_ = unrenamable; }
int side() const { return side_; }
const std::string& team_color() const;
unit_race::GENDER gender() const { return gender_; }
void set_side(unsigned int new_side) { side_ = new_side; }
fixed_t alpha() const { return alpha_; }
bool can_recruit() const { return canrecruit_; }
void set_can_recruit(bool canrecruit) { canrecruit_ = canrecruit; }
const std::vector<std::string>& recruits() const
{ return recruit_list_; }
void set_recruits(const std::vector<std::string>& recruits);
const config& recall_filter() const { return filter_recall_; }
bool poisoned() const { return get_state(STATE_POISONED); }
bool incapacitated() const { return get_state(STATE_PETRIFIED); }
bool slowed() const { return get_state(STATE_SLOWED); }
int total_movement() const { return max_movement_; }
/// Returns how far a unit can move this turn (zero if incapacitated).
int movement_left() const { return (movement_ == 0 || incapacitated()) ? 0 : movement_; }
/// Providing a true parameter to movement_left() causes it to ignore incapacitation.
int movement_left(bool base_value) const { return base_value ? movement_ : movement_left(); }
int vision() const { return vision_ < 0 ? max_movement_ : vision_; }
int jamming() const { return jamming_; }
void toggle_hold_position() { hold_position_ = !hold_position_; if ( hold_position_ ) end_turn_ = true; }
bool hold_position() const { return hold_position_; }
void set_user_end_turn(bool value=true) { end_turn_ = value; }
void toggle_user_end_turn() { end_turn_ = !end_turn_; if ( !end_turn_ ) hold_position_ = false; }
bool user_end_turn() const { return end_turn_; }
int attacks_left() const { return (attacks_left_ == 0 || incapacitated()) ? 0 : attacks_left_; }
int max_attacks() const { return max_attacks_; }
void set_movement(int moves, bool unit_action=false);
void set_attacks(int left) { attacks_left_ = std::max<int>(0, left); }
void new_turn();
void end_turn();
void new_scenario();
/** Called on every draw */
bool take_hit(int damage) { hit_points_ -= damage; return hit_points_ <= 0; }
void heal(int amount);
void heal_all() { hit_points_ = max_hitpoints(); }
bool resting() const { return resting_; }
void set_resting(bool rest) { resting_ = rest; }
const std::set<std::string> get_states() const;
bool get_state(const std::string& state) const;
void set_state(const std::string &state, bool value);
enum state_t { STATE_SLOWED = 0, STATE_POISONED, STATE_PETRIFIED,
STATE_UNCOVERED, STATE_NOT_MOVED, STATE_UNHEALABLE, STATE_GUARDIAN, STATE_UNKNOWN = -1 };
void set_state(state_t state, bool value);
bool get_state(state_t state) const;
static state_t get_known_boolean_state_id(const std::string &state);
bool has_moved() const { return movement_left() != total_movement(); }
bool has_goto() const { return get_goto().valid(); }
bool emits_zoc() const { return emit_zoc_ && !incapacitated();}
bool matches_id(const std::string& unit_id) const;
/* cfg: standard unit filter */
const std::vector<std::string>& overlays() const { return overlays_; }
void write(config& cfg) const;
void set_role(const std::string& role) { role_ = role; }
const std::string &get_role() const { return role_; }
void set_emit_zoc(bool val) { emit_zoc_ = val; }
bool get_emit_zoc() const { return emit_zoc_; }
const_attack_itors attacks() const { return make_attack_itors(attacks_); }
attack_itors attacks() { return make_attack_itors(attacks_); }
bool remove_attack(attack_ptr atk);
template<typename... Args>
attack_ptr add_attack(attack_itors::iterator position, Args... args) {
return *attacks_.emplace(position.base(), new attack_type(args...));
}
int damage_from(const attack_type& attack,bool attacker,const map_location& loc) const { return resistance_against(attack,attacker,loc); }
unit_animation_component & anim_comp() const { return *anim_comp_; }
void set_facing(map_location::DIRECTION dir) const;
map_location::DIRECTION facing() const { return facing_; }
const std::vector<t_string>& trait_names() const { return trait_names_; }
const std::vector<t_string>& trait_descriptions() const { return trait_descriptions_; }
std::vector<std::string> get_traits_list() const;
int cost () const { return unit_value_; }
const map_location &get_location() const { return loc_; }
/** To be called by unit_map or for temporary units only. */
void set_location(const map_location &loc) { loc_ = loc; }
const map_location& get_goto() const { return goto_; }
void set_goto(const map_location& new_goto) { goto_ = new_goto; }
int upkeep() const;
struct upkeep_full {};
struct upkeep_loyal {};
typedef boost::variant<upkeep_full, upkeep_loyal, int> upkeep_t;
upkeep_t upkeep_raw() const { return upkeep_; }
void set_upkeep(upkeep_t v) { upkeep_ = v; }
bool loyal() const;
void set_hidden(bool state) const;
bool get_hidden() const { return hidden_; }
bool is_flying() const { return movement_type_.is_flying(); }
bool is_fearless() const { return is_fearless_; }
bool is_healthy() const { return is_healthy_; }
int movement_cost(const t_translation::terrain_code & terrain) const
{ return movement_type_.movement_cost(terrain, get_state(STATE_SLOWED)); }
int vision_cost(const t_translation::terrain_code & terrain) const
{ return movement_type_.vision_cost(terrain, get_state(STATE_SLOWED)); }
int jamming_cost(const t_translation::terrain_code & terrain) const
{ return movement_type_.jamming_cost(terrain, get_state(STATE_SLOWED)); }
int defense_modifier(const t_translation::terrain_code & terrain) const;
int resistance_against(const std::string& damage_name,bool attacker,const map_location& loc) const;
int resistance_against(const attack_type& damage_type,bool attacker,const map_location& loc) const
{ return resistance_against(damage_type.type(), attacker, loc); }
//return resistances without any abilities applied
utils::string_map get_base_resistances() const { return movement_type_.damage_table(); }
const movetype & movement_type() const { return movement_type_; }
bool can_advance() const { return advances_to_.empty()==false || get_modification_advances().empty() == false; }
bool advances() const { return experience_ >= max_experience() && can_advance(); }
std::map<std::string,std::string> advancement_icons() const;
std::vector<std::pair<std::string,std::string> > amla_icons() const;
std::vector<config> get_modification_advances() const;
config& get_modifications() { return modifications_; }
const config& get_modifications() const { return modifications_; }
typedef boost::ptr_vector<config> advancements_list;
void set_advancements(std::vector<config> advancements);
const advancements_list& modification_advancements() const
{ return advancements_; }
size_t modification_count(const std::string& type, const std::string& id) const;
void add_modification(const std::string& type, const config& modification,
bool no_add=false);
void expire_modifications(const std::string & duration);
static const std::set<std::string> builtin_effects;
void apply_builtin_effect(std::string type, const config& effect);
std::string describe_builtin_effect(std::string type, const config& effect);
bool move_interrupted() const { return movement_left() > 0 && interrupted_move_.x >= 0 && interrupted_move_.y >= 0; }
const map_location& get_interrupted_move() const { return interrupted_move_; }
void set_interrupted_move(const map_location& interrupted_move) { interrupted_move_ = interrupted_move; }
/** The name of the file to game_display (used in menus). */
std::string absolute_image() const;
/** The default image to use for animation frames with no defined image. */
std::string default_anim_image() const;
std::string image_halo() const { return unit_detail::get_or_default(halo_); }
std::string image_ellipse() const { return unit_detail::get_or_default(ellipse_); }
std::string usage() const { return unit_detail::get_or_default(usage_); }
void set_image_halo(const std::string& halo);
void set_image_ellipse(const std::string& ellipse) { ellipse_.reset(new std::string(ellipse)); }
void set_usage(const std::string& usage) { usage_.reset(new std::string(usage)); }
config &variables() { return variables_; }
const config &variables() const { return variables_; }
unit_type::ALIGNMENT alignment() const { return alignment_; }
void set_alignment(unit_type::ALIGNMENT alignment) { alignment_ = alignment; }
/// Never returns nullptr, but may point to the null race.
const unit_race* race() const { return race_; }
/**
* Returns true if the unit is currently under effect by an ability with this given TAG NAME.
* This means that the ability could be owned by the unit itself, or by an adjacent unit.
*/
bool get_ability_bool(const std::string& tag_name, const map_location& loc, const display_context& dc) const;
/**
* Returns true if the unit is currently under effect by an ability with this given TAG NAME.
* This means that the ability could be owned by the unit itself, or by an adjacent unit.
*/
bool get_ability_bool(const std::string &tag_name, const display_context& dc) const
{ return get_ability_bool(tag_name, loc_, dc); }
unit_ability_list get_abilities(const std::string &tag_name, const map_location& loc) const;
unit_ability_list get_abilities(const std::string &tag_name) const
{ return get_abilities(tag_name, loc_); }
/** Tuple of: neutral ability name, gendered ability name, description */
std::vector<std::tuple<t_string, t_string, t_string> > ability_tooltips(boost::dynamic_bitset<>* active_list = nullptr) const;
std::vector<std::string> get_ability_list() const;
bool has_ability_type(const std::string& ability) const;
unit_formula_manager & formula_manager() const { return *formula_man_; }
void backup_state();
void apply_modifications();
void generate_traits(bool musthaveonly=false);
void generate_name();
// Only see_all=true use caching
bool invisible(const map_location& loc, const display_context& dc, bool see_all = true) const;
bool is_visible_to_team(team const& team, display_context const& dc, bool const see_all = true) const;
/** Mark this unit as clone so it can be inserted to unit_map
* @returns self (for convenience)
**/
unit& clone(bool is_temporary=true);
std::string TC_image_mods() const;
const std::string& effect_image_mods() const;
std::string image_mods() const;
long ref_count() const { return ref_count_; }
friend void intrusive_ptr_add_ref(const unit *);
friend void intrusive_ptr_release(const unit *);
protected:
mutable long ref_count_; //used by intrusive_ptr
private:
/*
* cfg: an ability WML structure
*/
bool ability_active(const std::string& ability,const config& cfg,const map_location& loc) const;
bool ability_affects_adjacent(const std::string& ability,const config& cfg,int dir,const map_location& loc,const unit& from) const;
bool ability_affects_self(const std::string& ability,const config& cfg,const map_location& loc) const;
bool resistance_filter_matches(const config& cfg,bool attacker,const std::string& damage_name, int res) const;
public:
bool has_ability_by_id(const std::string& ability) const;
// ^ Needed for unit_filter
private:
void remove_ability_by_id(const std::string& ability);
/** register a trait's name and its description for UI's use*/
void add_trait_description(const config& trait, const t_string& description);
void set_underlying_id(n_unit::id_manager& id_manager);
private:
map_location loc_;
std::vector<std::string> advances_to_;
const unit_type * type_;/// Never nullptr. Adjusted for gender and variation.
t_string type_name_; /// The displayed name of the unit type.
const unit_race* race_; /// Never nullptr, but may point to the null race.
std::string id_;
t_string name_;
n_unit::unit_id underlying_id_;
std::string undead_variation_;
std::string variation_;
int hit_points_;
int max_hit_points_;
int experience_;
int max_experience_;
int level_;
int recall_cost_;
bool canrecruit_;
std::vector<std::string> recruit_list_;
unit_type::ALIGNMENT alignment_;
std::string flag_rgb_;
std::string image_mods_;
bool unrenamable_;
int side_;
unit_race::GENDER gender_;
fixed_t alpha_;
std::unique_ptr<unit_formula_manager> formula_man_;
int movement_;
int max_movement_;
int vision_;
int jamming_;
movetype movement_type_;
bool hold_position_;
bool end_turn_;
bool resting_;
int attacks_left_;
int max_attacks_;
std::set<std::string> states_;
// TODO: Somehow make a static const var for the 7 so that it can auto-update if new boolean states are ever added
std::bitset<7> known_boolean_states_;
static std::map<std::string, state_t> known_boolean_state_names_;
config variables_;
config events_;
config filter_recall_;
bool emit_zoc_;
std::vector<std::string> overlays_;
std::string role_;
attack_list attacks_;
protected:
mutable map_location::DIRECTION facing_; //TODO: I think we actually consider this to be part of the gamestate, so it might be better if it's not mutable
//But it's not easy to separate this guy from the animation code right now.
private:
std::vector<t_string> trait_names_;
std::vector<t_string> trait_descriptions_;
int unit_value_;
map_location goto_, interrupted_move_;
bool is_fearless_, is_healthy_;
utils::string_map modification_descriptions_;
// Animations:
friend class unit_animation_component;
private:
std::unique_ptr<unit_animation_component> anim_comp_;
bool getsHit_;
mutable bool hidden_;
double hp_bar_scaling_, xp_bar_scaling_;
config modifications_;
config abilities_;
advancements_list advancements_;
t_string description_;
std::unique_ptr<std::string> usage_;
std::unique_ptr<std::string> halo_;
std::unique_ptr<std::string> ellipse_;
bool random_traits_;
bool generate_name_;
upkeep_t upkeep_;
std::string profile_;
std::string small_profile_;
//TODO add a to initializer list.
void parse_upkeep(const config::attribute_value& upkeep);
void write_upkeep(config::attribute_value& upkeep) const;
/**
* Hold the visibility status cache for a unit, when not uncovered.
* This is mutable since it is a cache.
*/
mutable std::map<map_location, bool> invisibility_cache_;
/**
* Clears the cache.
*
* Since we don't change the state of the object we're marked const (also
* required since the objects in the cache need to be marked const).
*/
void clear_visibility_cache() const { invisibility_cache_.clear(); }
};
/**
* Object which temporarily resets a unit's movement.
*
* @warning
* The unit whose movement is reset may not be deleted while a
* @ref unit_movement_resetter object 'holds'. So best use it only in a small
* scope.
*/
struct unit_movement_resetter
{
unit_movement_resetter(const unit_movement_resetter&) = delete;
unit_movement_resetter& operator=(const unit_movement_resetter&) = delete;
unit_movement_resetter(const unit& u, bool operate=true);
~unit_movement_resetter();
private:
unit& u_;
int moves_;
};
/**
* Gets a checksum for a unit.
*
* In MP games the descriptions are locally generated and might differ, so it
* should be possible to discard them. Not sure whether replays suffer the
* same problem.
*
* @param u the unit
*
* @returns the checksum for a unit
*/
std::string get_checksum(const unit& u);
#endif
|
gpl-2.0
|
ARudik/feelpp.ginac
|
check/check_lsolve.cpp
|
6165
|
/** @file check_lsolve.cpp
*
* These test routines do some simple checks on solving linear systems of
* symbolic equations. They are a well-tried resource for cross-checking
* the underlying symbolic manipulations. */
/*
* GiNaC Copyright (C) 1999-2011 Johannes Gutenberg University Mainz, Germany
*
* 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 "ginac.h"
using namespace GiNaC;
#include <cstdlib> // for rand()
#include <iostream>
#include <sstream>
using namespace std;
extern const ex
dense_univariate_poly(const symbol & x, unsigned degree);
static unsigned check_matrix_solve(unsigned m, unsigned n, unsigned p,
unsigned degree)
{
const symbol a("a");
matrix A(m,n);
matrix B(m,p);
// set the first min(m,n) rows of A and B
for (unsigned ro=0; (ro<m)&&(ro<n); ++ro) {
for (unsigned co=0; co<n; ++co)
A.set(ro,co,dense_univariate_poly(a,degree));
for (unsigned co=0; co<p; ++co)
B.set(ro,co,dense_univariate_poly(a,degree));
}
// repeat excessive rows of A and B to avoid excessive construction of
// overdetermined linear systems
for (unsigned ro=n; ro<m; ++ro) {
for (unsigned co=0; co<n; ++co)
A.set(ro,co,A(ro-1,co));
for (unsigned co=0; co<p; ++co)
B.set(ro,co,B(ro-1,co));
}
// create a vector of n*p symbols all named "xrc" where r and c are ints
vector<symbol> x;
matrix X(n,p);
for (unsigned i=0; i<n; ++i) {
for (unsigned j=0; j<p; ++j) {
ostringstream buf;
buf << "x" << i << j << ends;
x.push_back(symbol(buf.str()));
X.set(i,j,x[p*i+j]);
}
}
matrix sol(n,p);
// Solve the system A*X==B:
try {
sol = A.solve(X, B);
} catch (const exception & err) { // catch runtime_error
// Presumably, the coefficient matrix A was degenerate
string errwhat = err.what();
if (errwhat == "matrix::solve(): inconsistent linear system")
return 0;
else
clog << "caught exception: " << errwhat << endl;
throw;
}
// check the result with our original matrix:
bool errorflag = false;
for (unsigned ro=0; ro<m; ++ro) {
for (unsigned pco=0; pco<p; ++pco) {
ex e = 0;
for (unsigned co=0; co<n; ++co)
e += A(ro,co)*sol(co,pco);
if (!(e-B(ro,pco)).normal().is_zero())
errorflag = true;
}
}
if (errorflag) {
clog << "Our solve method claims that A*X==B, with matrices" << endl
<< "A == " << A << endl
<< "X == " << sol << endl
<< "B == " << B << endl;
return 1;
}
return 0;
}
static unsigned check_inifcns_lsolve(unsigned n)
{
unsigned result = 0;
for (int repetition=0; repetition<200; ++repetition) {
// create two size n vectors of symbols, one for the coefficients
// a[0],..,a[n], one for indeterminates x[0]..x[n]:
vector<symbol> a;
vector<symbol> x;
for (unsigned i=0; i<n; ++i) {
ostringstream buf;
buf << i << ends;
a.push_back(symbol(string("a")+buf.str()));
x.push_back(symbol(string("x")+buf.str()));
}
lst eqns; // equation list
lst vars; // variable list
ex sol; // solution
// Create a random linear system...
for (unsigned i=0; i<n; ++i) {
ex lhs = rand()%201-100;
ex rhs = rand()%201-100;
for (unsigned j=0; j<n; ++j) {
// ...with small coefficients to give degeneracy a chance...
lhs += a[j]*(rand()%21-10);
rhs += x[j]*(rand()%21-10);
}
eqns.append(lhs==rhs);
vars.append(x[i]);
}
// ...solve it...
sol = lsolve(eqns, vars);
// ...and check the solution:
if (sol.nops() == 0) {
// no solution was found
// is the coefficient matrix really, really, really degenerate?
matrix coeffmat(n,n);
for (unsigned ro=0; ro<n; ++ro)
for (unsigned co=0; co<n; ++co)
coeffmat.set(ro,co,eqns.op(co).rhs().coeff(a[co],1));
if (!coeffmat.determinant().is_zero()) {
++result;
clog << "solution of the system " << eqns << " for " << vars
<< " was not found" << endl;
}
} else {
// insert the solution into rhs of out equations
bool errorflag = false;
for (unsigned i=0; i<n; ++i)
if (eqns.op(i).rhs().subs(sol) != eqns.op(i).lhs())
errorflag = true;
if (errorflag) {
++result;
clog << "solution of the system " << eqns << " for " << vars
<< " erroneously returned " << sol << endl;
}
}
}
return result;
}
unsigned check_lsolve()
{
unsigned result = 0;
cout << "checking linear solve" << flush;
// solve some numeric linear systems
for (unsigned n=1; n<14; ++n)
result += check_matrix_solve(n, n, 1, 0);
cout << '.' << flush;
// solve some underdetermined numeric systems
for (unsigned n=1; n<14; ++n)
result += check_matrix_solve(n+1, n, 1, 0);
cout << '.' << flush;
// solve some overdetermined numeric systems
for (unsigned n=1; n<14; ++n)
result += check_matrix_solve(n, n+1, 1, 0);
cout << '.' << flush;
// solve some multiple numeric systems
for (unsigned n=1; n<14; ++n)
result += check_matrix_solve(n, n, n/3+1, 0);
cout << '.' << flush;
// solve some symbolic linear systems
for (unsigned n=1; n<8; ++n)
result += check_matrix_solve(n, n, 1, 2);
cout << '.' << flush;
// check lsolve, the wrapper function around matrix::solve()
result += check_inifcns_lsolve(2); cout << '.' << flush;
result += check_inifcns_lsolve(3); cout << '.' << flush;
result += check_inifcns_lsolve(4); cout << '.' << flush;
result += check_inifcns_lsolve(5); cout << '.' << flush;
result += check_inifcns_lsolve(6); cout << '.' << flush;
return result;
}
int main(int argc, char** argv)
{
return check_lsolve();
}
|
gpl-2.0
|
ylahav/joomla-cms
|
libraries/joomla/http/response.php
|
460
|
<?php
/**
* @package Joomla.Platform
* @subpackage HTTP
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
use Joomla\Http\Response;
/**
* HTTP response data object class.
*
* @since 11.3
* @deprecated 5.0 Use Joomla\Http\Response instead
*/
class JHttpResponse extends Response
{
}
|
gpl-2.0
|
tom-fallon/free-commerce
|
modules/contrib/commerce/modules/price/src/Event/PriceEvents.php
|
632
|
<?php
/**
* @file
* Contains \Drupal\commerce_price\Event\PriceEvents.
*/
namespace Drupal\commerce_price\Event;
/**
* Defines events for the price module.
*/
final class PriceEvents {
/**
* Name of the event fired when loading a number format.
*
* This event allows modules to alter the loaded number format before it's
* returned and used by the system. The event listener method receives a
* \Drupal\commerce_price\Event\NumberFormatEvent instance.
*
* @Event
*
* @see \Drupal\commerce_price\Event\NumberFormatEvent
*/
const NUMBER_FORMAT_LOAD = 'commerce_price.number_format.load';
}
|
gpl-2.0
|
cyberalpha/GarbageSocial
|
modules/mod_roknavmenu/lib/includes.php
|
594
|
<?php
/**
* @version 1.13 July 2, 2012
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2012 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
require_once(dirname(__FILE__) . '/common/includes.php');
require_once(dirname(__FILE__) . '/librokmenu/includes.php');
require_once(dirname(__FILE__) . '/providers/includes.php');
require_once(dirname(__FILE__) . '/renderers/includes.php');
require_once(dirname(__FILE__) . '/RokNavMenu.php');
require_once(dirname(__FILE__) . '/AbstractJoomlaRokMenuFormatter.php');
|
gpl-2.0
|
mauriciofauth/phpmyadmin
|
libraries/classes/Dbal/DbalInterface.php
|
21915
|
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Dbal;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\SystemDatabase;
use PhpMyAdmin\Table;
/**
* Main interface for database interactions
*/
interface DbalInterface
{
public const FETCH_NUM = 'NUM';
public const FETCH_ASSOC = 'ASSOC';
/**
* runs a query
*
* @param string $query SQL query to execute
* @param mixed $link optional database link to use
* @param int $options optional query options
* @param bool $cache_affected_rows whether to cache affected rows
*/
public function query(
string $query,
$link = DatabaseInterface::CONNECT_USER,
int $options = 0,
bool $cache_affected_rows = true
): ResultInterface;
/**
* runs a query and returns the result
*
* @param string $query query to run
* @param mixed $link link type
* @param int $options query options
* @param bool $cache_affected_rows whether to cache affected row
*
* @return mixed
*/
public function tryQuery(
string $query,
$link = DatabaseInterface::CONNECT_USER,
int $options = 0,
bool $cache_affected_rows = true
);
/**
* Send multiple SQL queries to the database server and execute the first one
*
* @param string $multiQuery multi query statement to execute
* @param int $linkIndex index of the opened database link
*/
public function tryMultiQuery(
string $multiQuery = '',
$linkIndex = DatabaseInterface::CONNECT_USER
): bool;
/**
* returns array with table names for given db
*
* @param string $database name of database
* @param mixed $link mysql link resource|object
*
* @return array tables names
*/
public function getTables(string $database, $link = DatabaseInterface::CONNECT_USER): array;
/**
* returns array of all tables in given db or dbs
* this function expects unquoted names:
* RIGHT: my_database
* WRONG: `my_database`
* WRONG: my\_database
* if $tbl_is_group is true, $table is used as filter for table names
*
* <code>
* $dbi->getTablesFull('my_database');
* $dbi->getTablesFull('my_database', 'my_table'));
* $dbi->getTablesFull('my_database', 'my_tables_', true));
* </code>
*
* @param string $database database
* @param string|array $table table name(s)
* @param bool $tbl_is_group $table is a table group
* @param int $limit_offset zero-based offset for the count
* @param bool|int $limit_count number of tables to return
* @param string $sort_by table attribute to sort by
* @param string $sort_order direction to sort (ASC or DESC)
* @param string|null $table_type whether table or view
* @param mixed $link link type
*
* @return array list of tables in given db(s)
*
* @todo move into Table
*/
public function getTablesFull(
string $database,
$table = '',
bool $tbl_is_group = false,
int $limit_offset = 0,
$limit_count = false,
string $sort_by = 'Name',
string $sort_order = 'ASC',
?string $table_type = null,
$link = DatabaseInterface::CONNECT_USER
): array;
/**
* Get VIEWs in a particular database
*
* @param string $db Database name to look in
*
* @return Table[] Set of VIEWs inside the database
*/
public function getVirtualTables(string $db): array;
/**
* returns array with databases containing extended infos about them
*
* @param string|null $database database
* @param bool $force_stats retrieve stats also for MySQL < 5
* @param int $link link type
* @param string $sort_by column to order by
* @param string $sort_order ASC or DESC
* @param int $limit_offset starting offset for LIMIT
* @param bool|int $limit_count row count for LIMIT or true
* for $GLOBALS['cfg']['MaxDbList']
*
* @return array
*
* @todo move into ListDatabase?
*/
public function getDatabasesFull(
?string $database = null,
bool $force_stats = false,
$link = DatabaseInterface::CONNECT_USER,
string $sort_by = 'SCHEMA_NAME',
string $sort_order = 'ASC',
int $limit_offset = 0,
$limit_count = false
): array;
/**
* returns detailed array with all columns for sql
*
* @param string $sql_query target SQL query to get columns
* @param array $view_columns alias for columns
*
* @return array
*/
public function getColumnMapFromSql(string $sql_query, array $view_columns = []): array;
/**
* returns detailed array with all columns for given table in database,
* or all tables/databases
*
* @param string|null $database name of database
* @param string|null $table name of table to retrieve columns from
* @param string|null $column name of specific column
* @param mixed $link mysql link resource
*
* @return array
*/
public function getColumnsFull(
?string $database = null,
?string $table = null,
?string $column = null,
$link = DatabaseInterface::CONNECT_USER
): array;
/**
* Returns description of a $column in given table
*
* @param string $database name of database
* @param string $table name of table to retrieve columns from
* @param string $column name of column
* @param bool $full whether to return full info or only column names
* @param int $link link type
*
* @return array flat array description
*/
public function getColumn(
string $database,
string $table,
string $column,
bool $full = false,
$link = DatabaseInterface::CONNECT_USER
): array;
/**
* Returns descriptions of columns in given table
*
* @param string $database name of database
* @param string $table name of table to retrieve columns from
* @param bool $full whether to return full info or only column names
* @param int $link link type
*
* @return array<string, array> array indexed by column names
*/
public function getColumns(
string $database,
string $table,
bool $full = false,
$link = DatabaseInterface::CONNECT_USER
): array;
/**
* Returns all column names in given table
*
* @param string $database name of database
* @param string $table name of table to retrieve columns from
* @param mixed $link mysql link resource
*
* @return string[]
*/
public function getColumnNames(
string $database,
string $table,
$link = DatabaseInterface::CONNECT_USER
): array;
/**
* Returns indexes of a table
*
* @param string $database name of database
* @param string $table name of the table whose indexes are to be retrieved
* @param mixed $link mysql link resource
*
* @return array
*/
public function getTableIndexes(
string $database,
string $table,
$link = DatabaseInterface::CONNECT_USER
): array;
/**
* returns value of given mysql server variable
*
* @param string $var mysql server variable name
* @param int $type DatabaseInterface::GETVAR_SESSION |
* DatabaseInterface::GETVAR_GLOBAL
* @param int $link mysql link resource|object
*
* @return false|string|null value for mysql server variable
*/
public function getVariable(
string $var,
int $type = DatabaseInterface::GETVAR_SESSION,
$link = DatabaseInterface::CONNECT_USER
);
/**
* Sets new value for a variable if it is different from the current value
*
* @param string $var variable name
* @param string $value value to set
* @param int $link mysql link resource|object
*/
public function setVariable(string $var, string $value, $link = DatabaseInterface::CONNECT_USER): bool;
/**
* Function called just after a connection to the MySQL database server has
* been established. It sets the connection collation, and determines the
* version of MySQL which is running.
*/
public function postConnect(): void;
/**
* Sets collation connection for user link
*
* @param string $collation collation to set
*/
public function setCollation(string $collation): void;
/**
* Function called just after a connection to the MySQL database server has
* been established. It sets the connection collation, and determines the
* version of MySQL which is running.
*/
public function postConnectControl(Relation $relation): void;
/**
* returns a single value from the given result or query,
* if the query or the result has more than one row or field
* the first field of the first row is returned
*
* <code>
* $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
* $user_name = $dbi->fetchValue($sql);
* // produces
* // $user_name = 'John Doe'
* </code>
*
* @param string $query The query to execute
* @param int|string $field field to fetch the value from,
* starting at 0, with 0 being
* default
* @param int $link link type
*
* @return string|false|null value of first field in first row from result
* or false if not found
*/
public function fetchValue(
string $query,
$field = 0,
$link = DatabaseInterface::CONNECT_USER
);
/**
* Returns only the first row from the result or null if result is empty.
*
* <code>
* $sql = 'SELECT * FROM `user` WHERE `id` = 123';
* $user = $dbi->fetchSingleRow($sql);
* // produces
* // $user = array('id' => 123, 'name' => 'John Doe')
* </code>
*
* @param string $query The query to execute
* @param string $type NUM|ASSOC returned array should either numeric
* associative or both
* @param int $link link type
* @psalm-param self::FETCH_NUM|self::FETCH_ASSOC $type
*/
public function fetchSingleRow(
string $query,
string $type = DbalInterface::FETCH_ASSOC,
$link = DatabaseInterface::CONNECT_USER
): ?array;
/**
* returns all rows in the resultset in one array
*
* <code>
* $sql = 'SELECT * FROM `user`';
* $users = $dbi->fetchResult($sql);
* // produces
* // $users[] = array('id' => 123, 'name' => 'John Doe')
*
* $sql = 'SELECT `id`, `name` FROM `user`';
* $users = $dbi->fetchResult($sql, 'id');
* // produces
* // $users['123'] = array('id' => 123, 'name' => 'John Doe')
*
* $sql = 'SELECT `id`, `name` FROM `user`';
* $users = $dbi->fetchResult($sql, 0);
* // produces
* // $users['123'] = array(0 => 123, 1 => 'John Doe')
*
* $sql = 'SELECT `id`, `name` FROM `user`';
* $users = $dbi->fetchResult($sql, 'id', 'name');
* // or
* $users = $dbi->fetchResult($sql, 0, 1);
* // produces
* // $users['123'] = 'John Doe'
*
* $sql = 'SELECT `name` FROM `user`';
* $users = $dbi->fetchResult($sql);
* // produces
* // $users[] = 'John Doe'
*
* $sql = 'SELECT `group`, `name` FROM `user`'
* $users = $dbi->fetchResult($sql, array('group', null), 'name');
* // produces
* // $users['admin'][] = 'John Doe'
*
* $sql = 'SELECT `group`, `name` FROM `user`'
* $users = $dbi->fetchResult($sql, array('group', 'name'), 'id');
* // produces
* // $users['admin']['John Doe'] = '123'
* </code>
*
* @param string $query query to execute
* @param string|int|array $key field-name or offset
* used as key for
* array or array of
* those
* @param string|int $value value-name or offset
* used as value for
* array
* @param int $link link type
*
* @return array resultrows or values indexed by $key
*/
public function fetchResult(
string $query,
$key = null,
$value = null,
$link = DatabaseInterface::CONNECT_USER
): array;
/**
* Get supported SQL compatibility modes
*
* @return array supported SQL compatibility modes
*/
public function getCompatibilities(): array;
/**
* returns warnings for last query
*
* @param int $link link type
*
* @return array warnings
*/
public function getWarnings($link = DatabaseInterface::CONNECT_USER): array;
/**
* returns an array of PROCEDURE or FUNCTION names for a db
*
* @param string $db db name
* @param string $which PROCEDURE | FUNCTION
* @param int $link link type
*
* @return array the procedure names or function names
*/
public function getProceduresOrFunctions(
string $db,
string $which,
$link = DatabaseInterface::CONNECT_USER
): array;
/**
* returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
*
* @param string $db db name
* @param string $which PROCEDURE | FUNCTION | EVENT | VIEW
* @param string $name the procedure|function|event|view name
* @param int $link link type
*
* @return string|null the definition
*/
public function getDefinition(
string $db,
string $which,
string $name,
$link = DatabaseInterface::CONNECT_USER
): ?string;
/**
* returns details about the PROCEDUREs or FUNCTIONs for a specific database
* or details about a specific routine
*
* @param string $db db name
* @param string|null $which PROCEDURE | FUNCTION or null for both
* @param string $name name of the routine (to fetch a specific routine)
*
* @return array information about ROCEDUREs or FUNCTIONs
*/
public function getRoutines(string $db, ?string $which = null, string $name = ''): array;
/**
* returns details about the EVENTs for a specific database
*
* @param string $db db name
* @param string $name event name
*
* @return array information about EVENTs
*/
public function getEvents(string $db, string $name = ''): array;
/**
* returns details about the TRIGGERs for a specific table or database
*
* @param string $db db name
* @param string $table table name
* @param string $delimiter the delimiter to use (may be empty)
*
* @return array information about triggers (may be empty)
*/
public function getTriggers(string $db, string $table = '', string $delimiter = '//'): array;
/**
* gets the current user with host
*
* @return string the current user i.e. user@host
*/
public function getCurrentUser(): string;
/**
* Checks if current user is superuser
*/
public function isSuperUser(): bool;
public function isGrantUser(): bool;
public function isCreateUser(): bool;
public function isConnected(): bool;
/**
* Get the current user and host
*
* @return array array of username and hostname
*/
public function getCurrentUserAndHost(): array;
/**
* Returns value for lower_case_table_names variable
*
* @return string
*/
public function getLowerCaseNames();
/**
* connects to the database server
*
* @param int $mode Connection mode on of CONNECT_USER, CONNECT_CONTROL
* or CONNECT_AUXILIARY.
* @param array|null $server Server information like host/port/socket/persistent
* @param int|null $target How to store connection link, defaults to $mode
*
* @return mixed false on error or a connection object on success
*/
public function connect(int $mode, ?array $server = null, ?int $target = null);
/**
* selects given database
*
* @param string|DatabaseName $dbname database name to select
* @param int $link link type
*/
public function selectDb($dbname, $link = DatabaseInterface::CONNECT_USER): bool;
/**
* Check if there are any more query results from a multi query
*
* @param int $link link type
*/
public function moreResults($link = DatabaseInterface::CONNECT_USER): bool;
/**
* Prepare next result from multi_query
*
* @param int $link link type
*/
public function nextResult($link = DatabaseInterface::CONNECT_USER): bool;
/**
* Store the result returned from multi query
*
* @param int $link link type
*
* @return mixed false when empty results / result set when not empty
*/
public function storeResult($link = DatabaseInterface::CONNECT_USER);
/**
* Returns a string representing the type of connection used
*
* @param int $link link type
*
* @return string|bool type of connection used
*/
public function getHostInfo($link = DatabaseInterface::CONNECT_USER);
/**
* Returns the version of the MySQL protocol used
*
* @param int $link link type
*
* @return int|bool version of the MySQL protocol used
*/
public function getProtoInfo($link = DatabaseInterface::CONNECT_USER);
/**
* returns a string that represents the client library version
*
* @return string MySQL client library version
*/
public function getClientInfo(): string;
/**
* Returns last error message or an empty string if no errors occurred.
*
* @param int $link link type
*/
public function getError($link = DatabaseInterface::CONNECT_USER): string;
/**
* returns the number of rows returned by last query
* used with tryQuery as it accepts false
*
* @param string $query query to run
*
* @return string|int
* @psalm-return int|numeric-string
*/
public function queryAndGetNumRows(string $query);
/**
* returns last inserted auto_increment id for given $link
* or $GLOBALS['userlink']
*
* @param int $link link type
*
* @return int
*/
public function insertId($link = DatabaseInterface::CONNECT_USER);
/**
* returns the number of rows affected by last query
*
* @param int $link link type
* @param bool $get_from_cache whether to retrieve from cache
*
* @return int|string
* @psalm-return int|numeric-string
*/
public function affectedRows($link = DatabaseInterface::CONNECT_USER, bool $get_from_cache = true);
/**
* returns metainfo for fields in $result
*
* @param ResultInterface $result result set identifier
*
* @return FieldMetadata[] meta info for fields in $result
*/
public function getFieldsMeta(ResultInterface $result): array;
/**
* returns properly escaped string for use in MySQL queries
*
* @param string $str string to be escaped
* @param mixed $link optional database link to use
*
* @return string a MySQL escaped string
*/
public function escapeString(string $str, $link = DatabaseInterface::CONNECT_USER);
/**
* Checks if this database server is running on Amazon RDS.
*/
public function isAmazonRds(): bool;
/**
* Gets SQL for killing a process.
*
* @param int $process Process ID
*/
public function getKillQuery(int $process): string;
/**
* Get the phpmyadmin database manager
*/
public function getSystemDatabase(): SystemDatabase;
/**
* Get a table with database name and table name
*
* @param string $db_name DB name
* @param string $table_name Table name
*/
public function getTable(string $db_name, string $table_name): Table;
/**
* returns collation of given db
*
* @param string $db name of db
*
* @return string collation of $db
*/
public function getDbCollation(string $db): string;
/**
* returns default server collation from show variables
*/
public function getServerCollation(): string;
/**
* Server version as number
*/
public function getVersion(): int;
/**
* Server version
*/
public function getVersionString(): string;
/**
* Server version comment
*/
public function getVersionComment(): string;
/**
* Whether connection is MariaDB
*/
public function isMariaDB(): bool;
/**
* Whether connection is Percona
*/
public function isPercona(): bool;
/**
* Prepare an SQL statement for execution.
*
* @param string $query The query, as a string.
* @param int $link Link type.
*
* @return object|false A statement object or false.
*/
public function prepare(string $query, $link = DatabaseInterface::CONNECT_USER);
}
|
gpl-2.0
|
ForcerKing/ShaoqunXu-mysql5.7
|
storage/ndb/nodejs/Adapter/impl/common/src/async_common.cpp
|
1949
|
/*
Copyright (c) 2012, Oracle and/or its affiliates. All rights
reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include <stdio.h>
#include "adapter_global.h"
#include "AsyncMethodCall.h"
using namespace v8;
void report_error(TryCatch * err) {
HandleScope scope;
String::Utf8Value exception(err->Exception());
String::Utf8Value stack(err->StackTrace());
Handle<Message> message = err->Message();
fprintf(stderr, "%s\n", *exception);
if(! message.IsEmpty()) {
String::Utf8Value file(message->GetScriptResourceName());
int line = message->GetLineNumber();
fprintf(stderr, "%s:%d\n", *file, line);
}
if(stack.length() > 0)
fprintf(stderr, "%s\n", *stack);
}
void work_thd_run(uv_work_t *req) {
AsyncCall *m = (AsyncCall *) req->data;
m->run();
m->handleErrors();
}
void main_thd_complete_async_call(AsyncCall *m) {
v8::HandleScope scope;
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
m->doAsyncCallback(v8::Context::GetCurrent()->Global());
/* exceptions */
if(try_catch.HasCaught()) {
report_error(& try_catch);
}
/* cleanup */
delete m;
}
void main_thd_complete(uv_work_t *req) {
AsyncCall *m = (AsyncCall *) req->data;
main_thd_complete_async_call(m);
delete req;
}
void main_thd_complete_newapi(uv_work_t *req, int) {
main_thd_complete(req);
}
|
gpl-2.0
|
monsdar/BoostSymLinkError
|
thirdparty/Boost/boost/context/detail/config.hpp
|
1155
|
// Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_CONTEXT_DETAIL_CONFIG_H
#define BOOST_CONTEXT_DETAIL_CONFIG_H
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#ifdef BOOST_CONTEXT_DECL
# undef BOOST_CONTEXT_DECL
#endif
#if (defined(BOOST_ALL_DYN_LINK) || defined(BOOST_CONTEXT_DYN_LINK) ) && ! defined(BOOST_CONTEXT_STATIC_LINK)
# if defined(BOOST_CONTEXT_SOURCE)
# define BOOST_CONTEXT_DECL BOOST_SYMBOL_EXPORT
# define BOOST_CONTEXT_BUILD_DLL
# else
# define BOOST_CONTEXT_DECL BOOST_SYMBOL_IMPORT
# endif
#endif
#if ! defined(BOOST_CONTEXT_DECL)
# define BOOST_CONTEXT_DECL
#endif
#if ! defined(BOOST_CONTEXT_SOURCE) && ! defined(BOOST_ALL_NO_LIB) && ! defined(BOOST_CONTEXT_NO_LIB)
# define BOOST_LIB_NAME boost_context
# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_CONTEXT_DYN_LINK)
# define BOOST_DYN_LINK
# endif
# include <boost/config/auto_link.hpp>
#endif
#endif // BOOST_CONTEXT_DETAIL_CONFIG_H
|
gpl-2.0
|
kaji-project/pynag
|
examples/Parsers/get_timeperiod.py
|
494
|
#!/usr/bin/python
import sys
if len(sys.argv) != 2:
sys.stderr.write("Usage: %s 'Timeperiod Name'\n" % (sys.argv[0]))
sys.exit(2)
## This is for the custom nagios module
sys.path.insert(1, '../')
from pynag.Parsers import config
target_item = sys.argv[1]
## Create the plugin option
nc = config('/etc/nagios/nagios.cfg')
nc.parse()
item = nc.get_timeperiod(target_item)
if not item:
sys.stderr.write("Item not found: %s\n" % item)
sys.exit(2)
print nc.print_conf(item)
|
gpl-2.0
|
seem-sky/fceuxd
|
output/luaScripts/Galaxian.lua
|
5609
|
--Galaxian
--Written by XKeeper
--Accesses the Music Player Easter Egg and displays the songs & information
require "x_functions";
require "x_interface";
if not x_requires then
-- Sanity check. If they require a newer version, let them know.
timer = 1;
while (true) do
timer = timer + 1;
for i = 0, 32 do
gui.drawbox( 6, 28 + i, 250, 92 - i, "#000000");
end;
gui.text( 10, 32, string.format("This Lua script requires the x_functions library."));
gui.text( 53, 42, string.format("It appears you do not have it."));
gui.text( 39, 58, "Please get the x_functions library at");
gui.text( 14, 69, "http://xkeeper.shacknet.nu:5/");
gui.text(114, 78, "emu/nes/lua/x_functions.lua");
warningboxcolor = string.format("%02X", math.floor(math.abs(30 - math.fmod(timer, 60)) / 30 * 0xFF));
gui.drawbox(7, 29, 249, 91, "#ff" .. warningboxcolor .. warningboxcolor);
FCEU.frameadvance();
end;
else
x_requires(6);
end;
function musicplayer()
resets = memory.readbyte(0x0115);
song = memory.readbyte(0x0002);
songlua = math.max(1, math.floor(resets / 45));
speed = memory.readbyte(0x0004);
speedde = memory.readbyte(0x0104); -- it's really an AND. But the only two values used are 0F and 07, so this modulous works.
pos = memory.readbyte(0x0000);
note = memory.readbyte(0x0001);
offsetb = song * 0x0100 + 0x4010 - 1;
offset = song * 0x0100 + pos - 1 + 0x4010;
note1 = 0x10 - math.floor(note / 0x10);
note2 = math.fmod(note, 0x10);
if note1 == 0x10 then note1 = 0 end;
text( 35, 42, string.format("Song Position: %02X%02X", song, pos));
text( 40, 50, string.format("ROM Offset: %04X", offset));
text( 43, 58, string.format("Song Speed: %02X", speed));
text(105, 66, string.format(" %02X", math.fmod(speedde, speed)));
lifebar(186, 21, 64, 4, note1, 15, "#8888ff", "#000066", false, "#ffffff");
lifebar(186, 29, 64, 4, note2, 15, "#8888ff", "#000066", false, "#ffffff");
text(178, 20, string.format("%X\n%X", note1, note2));
lifebar( 44, 67, 64, 4, math.fmod(speedde, speed), speed, "#8888ff", "#000066", false, "#ffffff");
if control.button(75, 90, 84, 1, "Toggle hex viewer") then
hexmap = not hexmap;
end;
if hexmap then
songdata = {};
songdata2 = {};
for i = 0x00, 0xFF do
if i >= songs[songlua]['st'] and i <= songs[songlua]['en'] or true then
o = string.format("%02X", rom.readbyte(offsetb + i));
else
o = "";
end;
x = math.fmod(i, 0x10);
y = math.floor(i / 0x70);
if not songdata2[x] then
songdata2[x] = {};
end;
if not songdata2[x][y] then
songdata2[x][y] = o;
-- songdata2[x][y] = string.format("%02X", y);
else
songdata2[x][y] = songdata2[x][y] .."\n".. o;
end;
end;
for x = 0, 0x0F do
text(29 + x * 14, 100 + 8 * 0, songdata2[x][0]);
text(29 + x * 14, 100 + 8 * 7, songdata2[x][1]);
text(29 + x * 14, 100 + 8 * 14, songdata2[x][2]);
end;
oboxx = 29 + math.fmod(pos, 0x10) * 14;
oboxy = 100 + 8 * math.floor(pos / 0x10);
c = "#ff0000";
if math.fmod(timer, 4) < 2 then
c = "#FFFFFF";
end;
box(oboxx, oboxy + 0, oboxx + 14, oboxy + 10, c);
end;
if pos >= songs[songlua]['en'] then --and pos == 0xFE then
if not songs[songlua]['xx'] then
memory.writebyte(0x0104, 0xFF);
-- text(50, 50, "LOCK");
else
memory.writebyte(0x0115, songs[songs[songlua]['xx']]['rv']);
memory.writebyte(0x0002, songs[songs[songlua]['xx']]['sv']);
memory.writebyte(0x0004, songs[songs[songlua]['xx']]['sp']);
memory.writebyte(0x0000, songs[songs[songlua]['xx']]['st']);
end;
end;
for id, val in pairs(songs) do
if id == songlua then
c = "#8888ff";
if math.fmod(timer, 4) < 2 then
c = "#FFFFFF";
end;
else
c = nil;
end;
if control.button(195, 33 + 11 * id, 57, 1, string.format("Play song %d", id), c, true) then
-- resetrequired = true;
-- memory.register(0x0104, nil);
memory.writebyte(0x0115, val['rv']);
memory.writebyte(0x0002, val['sv']);
memory.writebyte(0x0004, val['sp']);
memory.writebyte(0x0000, val['st']);
end;
end;
if resetrequired then
text(50, 85, "Please soft-reset game.");
if movie.framecount() == 0 then
resetrequired = false;
end;
end;
end;
songs = {
-- resets song `id` speed start end
{ rv = 0x2E, sv = 0x1B, sp = 0x0F, st = 0x00, en = 0xC6 },
{ rv = 0x5A, sv = 0x18, sp = 0x07, st = 0x00, en = 0xC2 },
{ rv = 0x87, sv = 0x06, sp = 0x0F, st = 0x00, en = 0x7F },
{ rv = 0xB4, sv = 0x16, sp = 0x0F, st = 0x50, en = 0xAF },
{ rv = 0xE1, sv = 0x1A, sp = 0x0F, st = 0x80, en = 0xF8, xx = 0x01 },
};
timer = 0;
hexmap = true;
while true do
timer = timer + 1;
input.update();
if memory.readbyte(0x0101) == 1 then
musicplayer();
else
filledbox(23, 49, 233, 130, "#000000");
text( 25, 50, "Normally you'd have to do something insane");
text( 52, 58, "like push RESET 45 times and");
text( 56, 66, "hold A+B on P2's controller.");
text( 28, 82, "Lucky for you, though, we borrowed this.");
text( 73, 90, "Feel free to use it.");
text( 73, 119, "(Yeah, we've got that)");
timer2 = math.fmod(timer, 60);
if timer2 >= 30 then timer2 = 60 - timer2; end;
timer2 = math.floor((timer2 / 30) * 255);
c = string.format("#%02X%02XFF", timer2, timer2);
if control.button(110, 106, 37, 1, " EASY ", c, "#ffffff") then
memory.writebyte(0x0101, 0x01);
memory.writebyte(0x0115, songs[2]['rv']);
memory.writebyte(0x0002, songs[2]['sv']);
memory.writebyte(0x0004, songs[2]['sp']);
memory.writebyte(0x0000, songs[2]['st']);
FCEU.softreset();
-- text(1, 1, 'woohoo');
end;
end;
FCEU.frameadvance();
end;
|
gpl-2.0
|
gxwangdi/practice
|
grpc-java/examples/src/test/java/io/grpc/examples/helloworld/HelloWorldClientTest.java
|
3906
|
/*
* Copyright 2015, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.grpc.examples.helloworld;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.StreamObserver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
/**
* Unit tests for {@link HelloWorldClient}.
* For demonstrating how to write gRPC unit test only.
* Not intended to provide a high code coverage or to test every major usecase.
*
* <p>For more unit test examples see {@link io.grpc.examples.routeguide.RouteGuideClientTest} and
* {@link io.grpc.examples.routeguide.RouteGuideServerTest}.
*/
@RunWith(JUnit4.class)
public class HelloWorldClientTest {
private final GreeterGrpc.GreeterImplBase serviceImpl = spy(new GreeterGrpc.GreeterImplBase() {});
private Server fakeServer;
private HelloWorldClient client;
/**
* Creates and starts a fake in-process server, and creates a client with an in-process channel.
*/
@Before
public void setUp() throws Exception {
String uniqueServerName = "fake server for " + getClass();
fakeServer = InProcessServerBuilder
.forName(uniqueServerName).directExecutor().addService(serviceImpl).build().start();
InProcessChannelBuilder channelBuilder =
InProcessChannelBuilder.forName(uniqueServerName).directExecutor();
client = new HelloWorldClient(channelBuilder);
}
/**
* Shuts down the client and server.
*/
@After
public void tearDown() throws Exception {
client.shutdown();
fakeServer.shutdownNow();
}
/**
* To test the client, call from the client against the fake server, and verify behaviors or state
* changes from the server side.
*/
@Test
public void greet_messageDeliveredToServer() {
ArgumentCaptor<HelloRequest> requestCaptor = ArgumentCaptor.forClass(HelloRequest.class);
String testName = "test name";
client.greet(testName);
verify(serviceImpl)
.sayHello(requestCaptor.capture(), Matchers.<StreamObserver<HelloReply>>any());
assertEquals(testName, requestCaptor.getValue().getName());
}
}
|
gpl-2.0
|
rorist/maps-lib-nutiteq
|
src/com/nutiteq/location/cellid/OpenCellIdDataFeeder.java
|
1930
|
package com.nutiteq.location.cellid;
import com.nutiteq.cache.Cache;
import com.nutiteq.components.Cell;
import com.nutiteq.components.WgsPoint;
import com.nutiteq.core.MappingCore;
import com.nutiteq.io.ResourceRequestor;
import com.nutiteq.location.LocationListener;
import com.nutiteq.log.Log;
public class OpenCellIdDataFeeder implements LocationListener {
private WgsPoint lastLocation;
private final CellIdDataReader cellIdDataReader;
private final String developerKey;
private final CellIdDataFeederListener feederListener;
public OpenCellIdDataFeeder(final String developerKey,
final CellIdDataFeederListener feederListener) {
this.developerKey = developerKey;
this.feederListener = feederListener;
cellIdDataReader = new SonyEricssonCellIdDataReader();
}
public void setLocation(final WgsPoint location) {
try {
if (location == null
|| (lastLocation != null && WgsPoint.distanceInMeters(lastLocation, location) < 300)) {
Log.debug(location + " not pushed");
return;
}
final String cellId = cellIdDataReader.getCellId();
final String lac = cellIdDataReader.getLac();
final String mcc = cellIdDataReader.getMcc();
final String mnc = cellIdDataReader.getMnc();
if (cellId == null || lac == null || mcc == null || mnc == null) {
Log.error("Could not push " + cellId + " : " + lac + " : " + mcc + " : " + mnc);
return;
}
final WgsPoint pushedLocation = location.toInternalWgs().toWgsPoint();
lastLocation = pushedLocation;
final ResourceRequestor pushTask = new OpenCellIdMeasurePushTask(developerKey,
pushedLocation, new Cell(cellId, lac, mcc, mnc), feederListener);
MappingCore.getInstance().getTasksRunner().enqueueDownload(pushTask, Cache.CACHE_LEVEL_NONE);
} catch (final Exception e) {
Log.error("Push error " + e.getMessage());
}
}
}
|
gpl-2.0
|
WholeFoodsCoop/Scannie
|
ScannieV2/common/lib/javascript/javascript/CoreChart.js
|
2643
|
/**
Wrapper for Chart.js so commonly used
chart formats can be repeated easily
*/
var CoreChart = (function () {
var mod = {};
var colors = [
"#3366cc",
"#dc3912",
"#ff9900",
"#109618",
"#990099",
"#0099c6",
"#dd4477",
"#66aa00",
"#b82e2e",
"#316395",
"#994499",
"#22aa99",
"#aaaa11",
"#6633cc",
"#e67300",
"#8b0707",
"#651067",
"#329262",
"#5574a6",
"#3b3eac"
];
var getColorIndex = 0;
mod.getColor = function() {
var ret = colors[getColorIndex];
getColorIndex = (getColorIndex + 1) % colors.length;
return ret;
};
var lineDataSets = function(lineData, lineLabels) {
var datasets = [];
for (var i=0; i<lineData.length; i++) {
var set = {
data: lineData[i],
fill: false,
label: lineLabels[i],
backgroundColor: colors[i],
pointBackgroundColor: colors[i],
pointBorderColor: colors[i],
borderColor: colors[i]
};
datasets.push(set);
}
return datasets;
};
mod.lineChart = function(elementID, xLabels, lineData, lineLabels) {
var ctx = document.getElementById(elementID);
var line = new Chart(ctx, {
type: 'line',
data: {
labels: xLabels,
datasets: lineDataSets(lineData, lineLabels)
}
});
};
mod.pieChart = function(elementID, pieLabels, pieData) {
var ctx = document.getElementById(elementID);
var line = new Chart(ctx, {
type: 'pie',
data: {
labels: pieLabels,
datasets: [{
data: pieData,
backgroundColor: colors
}]
}
});
};
mod.barChart = function(elementID, labels, dataSets) {
var ctx = document.getElementById(elementID);
dataSets = dataSets.map(function(obj, i) {
if (!('backgroundColor' in obj)) {
obj['backgroundColor'] = colors[i];
}
if (!('borderColor' in obj)) {
obj['borderColor'] = colors[i];
}
return obj;
});
console.log(dataSets);
var line = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: dataSets
}
});
};
return mod;
}());
|
gpl-2.0
|
certik/ginac
|
check/time_lw_H.cpp
|
2352
|
/** @file time_lw_H.cpp
*
* Test H from the paper "Comparison of Polynomial-Oriented CAS" by Robert H.
* Lewis and Michael Wester. */
/*
* GiNaC Copyright (C) 1999-2011 Johannes Gutenberg University Mainz, Germany
*
* 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 "ginac.h"
#include "timer.h"
using namespace GiNaC;
#include <iostream>
#include <vector>
using namespace std;
static unsigned test(unsigned n)
{
matrix hilbert(n,n);
for (unsigned r=0; r<n; ++r)
for (unsigned c=0; c<n; ++c)
hilbert.set(r,c,numeric(1,r+c+1));
ex det = hilbert.determinant();
/*
The closed form of the determinant of n x n Hilbert matrices is:
n-1 / \
----- | pow(factorial(r),3) |
| | | ------------------- |
| | | factorial(r+n) |
r = 0 \ /
*/
ex hilbdet = 1;
for (unsigned r=0; r<n; ++r)
hilbdet *= pow(factorial(r),3)/(factorial(r+n));
if (det != hilbdet) {
clog << "determinant of " << n << "x" << n << " erroneously returned " << det << endl;
return 1;
}
return 0;
}
unsigned time_lw_H()
{
unsigned result = 0;
unsigned count = 0;
timer rolex;
double time = .0;
cout << "timing Lewis-Wester test H (det of 80x80 Hilbert)" << flush;
rolex.start();
// correct for very small times:
do {
result = test(80);
++count;
} while ((time=rolex.read())<0.1 && !result);
cout << '.' << flush;
cout << time/count << 's' << endl;
return result;
}
extern void randomify_symbol_serials();
int main(int argc, char** argv)
{
randomify_symbol_serials();
cout << setprecision(2) << showpoint;
return time_lw_H();
}
|
gpl-2.0
|
CZ-NIC/dionaea
|
modules/python/dionaea/smb/include/asn1/mib.py
|
5664
|
#*************************************************************************
#* Dionaea
#* - catches bugs -
#*
#*
#*
#* Copyright (C) 2010 Markus Koetter
#*
#* 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.
#*
#*
#* contact nepenthesdev@gmail.com
#*
#*******************************************************************************/
#* This file was part of Scapy
#* See http://www.secdev.org/projects/scapy for more informations
#* Copyright (C) Philippe Biondi <phil@secdev.org>
#* This program is published under a GPLv2 license
#*************************************************************************
import re
from glob import glob
from scapy.dadict import DADict,fixname
from scapy.config import conf
from scapy.utils import do_graph
#################
## MIB parsing ##
#################
_mib_re_integer = re.compile("^[0-9]+$")
_mib_re_both = re.compile("^([a-zA-Z_][a-zA-Z0-9_-]*)\(([0-9]+)\)$")
_mib_re_oiddecl = re.compile(
"$\s*([a-zA-Z0-9_-]+)\s+OBJECT([^:\{\}]|\{[^:]+\})+::=\s*\{([^\}]+)\}",re.M)
_mib_re_strings = re.compile('"[^"]*"')
_mib_re_comments = re.compile('--.*(\r|\n)')
class MIBDict(DADict):
def _findroot(self, x):
if x.startswith("."):
x = x[1:]
if not x.endswith("."):
x += "."
max_value = 0
root="."
for k in list(self.keys()):
if x.startswith(self[k]+"."):
if max_value < len(self[k]):
max_value = len(self[k])
root = k
return root, x[max_value:-1]
def _oidname(self, x):
root,remainder = self._findroot(x)
return root+remainder
def _oid(self, x):
xl = x.strip(".").split(".")
p = len(xl)-1
while p >= 0 and _mib_re_integer.match(xl[p]):
p -= 1
if p != 0 or xl[p] not in self:
return x
xl[p] = self[xl[p]]
return ".".join(xl[p:])
def _make_graph(self, other_keys=None, **kargs):
if other_keys is None:
other_keys = []
nodes = [(k,self[k]) for k in list(self.keys())]
oids = [self[k] for k in list(self.keys())]
for k in other_keys:
if k not in oids:
nodes.append(self.oidname(k),k)
s = 'digraph "mib" {\n\trankdir=LR;\n\n'
for k,o in nodes:
s += '\t"%s" [ label="%s" ];\n' % (o,k)
s += "\n"
for k,o in nodes:
parent,remainder = self._findroot(o[:-1])
remainder = remainder[1:]+o[-1]
if parent != ".":
parent = self[parent]
s += '\t"%s" -> "%s" [label="%s"];\n' % (parent, o,remainder)
s += "}\n"
do_graph(s, **kargs)
def __len__(self):
return len(list(self.keys()))
def mib_register(ident, value, the_mib, unresolved):
if ident in the_mib or ident in unresolved:
return ident in the_mib
resval = []
not_resolved = 0
for v in value:
if _mib_re_integer.match(v):
resval.append(v)
else:
v = fixname(v)
if v not in the_mib:
not_resolved = 1
if v in the_mib:
v = the_mib[v]
elif v in unresolved:
v = unresolved[v]
if type(v) is list:
resval += v
else:
resval.append(v)
if not_resolved:
unresolved[ident] = resval
return False
else:
the_mib[ident] = resval
keys = list(unresolved.keys())
i = 0
while i < len(keys):
k = keys[i]
if mib_register(k,unresolved[k], the_mib, {}):
del(unresolved[k])
del(keys[i])
i = 0
else:
i += 1
return True
def load_mib(filenames):
the_mib = {'iso': ['1']}
unresolved = {}
for k in list(conf.mib.keys()):
mib_register(k, conf.mib[k].split("."), the_mib, unresolved)
if type(filenames) is str:
filenames = [filenames]
for fnames in filenames:
for fname in glob(fnames):
f = open(fname)
text = f.read()
cleantext = " ".join(
_mib_re_strings.split(" ".join(_mib_re_comments.split(text))))
for m in _mib_re_oiddecl.finditer(cleantext):
gr = m.groups()
ident,oid = gr[0],gr[-1]
ident=fixname(ident)
oid = oid.split()
for i in range(len(oid)):
m = _mib_re_both.match(oid[i])
if m:
oid[i] = m.groups()[1]
mib_register(ident, oid, the_mib, unresolved)
newmib = MIBDict(_name="MIB")
for k,o in the_mib.items():
newmib[k]=".".join(o)
for k,o in unresolved.items():
newmib[k]=".".join(o)
conf.mib=newmib
conf.mib = MIBDict(_name="MIB")
|
gpl-2.0
|
blitztech/rev4
|
src/server/scripts/EasternKingdoms/ThroneOfTheTides/instance_throne_of_the_tides.cpp
|
10464
|
/*
* Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.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 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/>.
*/
#include "ScriptMgr.h"
#include "throne_of_the_tides.h"
enum Factions
{
FACTION_FRIENDLY = 35
};
class instance_throne_of_the_tides : public InstanceMapScript
{
public:
instance_throne_of_the_tides() : InstanceMapScript("instance_throne_of_the_tides", 643) {}
InstanceScript* GetInstanceScript(InstanceMap* map) const
{
return new instance_throne_of_the_tides_InstanceMapScript(map);
}
struct instance_throne_of_the_tides_InstanceMapScript : public InstanceScript
{
instance_throne_of_the_tides_InstanceMapScript(Map* map) : InstanceScript(map)
{
SetBossNumber(MAX_ENCOUNTER);
}
uint64 LadyNazjar;
uint64 JellyFishElevator;
uint64 CommanderUlthok;
uint64 ErunakStonespeaker;
uint64 MindbenderGhursha;
uint64 Ozumat;
uint64 Neptulon;
uint64 LadyNazjarDoor;
uint64 CommanderUlthokDoor;
uint64 ErunakStonespeakerDoor;
uint64 OzumatDoor;
uint32 encounter[MAX_ENCOUNTER];
std::string str_data;
void Initialize()
{
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
encounter[i] = NOT_STARTED;
LadyNazjar = 0;
JellyFishElevator = 0;
CommanderUlthok = 0;
ErunakStonespeaker = 0;
MindbenderGhursha = 0;
Ozumat = 0;
Neptulon = 0;
LadyNazjarDoor = 0;
CommanderUlthokDoor = 0;
ErunakStonespeakerDoor = 0;
OzumatDoor = 0;
}
bool IsEncounterInProgress() const
{
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
if (encounter[i] == IN_PROGRESS) return true;
return false;
}
void OnCreatureCreate(Creature* creature)
{
Map::PlayerList const &players = instance->GetPlayers();
uint32 TeamInInstance = 0;
if (!players.isEmpty())
{
if (Player* player = players.begin()->GetSource())
TeamInInstance = player->GetTeam();
}
switch (creature->GetEntry())
{
case BOSS_LADY_NAZJAR:
LadyNazjar = creature->GetGUID();
break;
case BOSS_COMMANDER_ULTHOK:
CommanderUlthok = creature->GetGUID();
break;
case BOSS_ERUNAK_STONESPEAKER:
ErunakStonespeaker = creature->GetGUID();
break;
case BOSS_MINDBENDER_GHURSHA:
MindbenderGhursha = creature->GetGUID();
break;
case BOSS_OZUMAT:
Ozumat = creature->GetGUID();
break;
case BOSS_NEPTULON:
Neptulon = creature->GetGUID();
break;
case 50272:
{
if (ServerAllowsTwoSideGroups())
creature->setFaction(FACTION_FRIENDLY);
if (TeamInInstance == ALLIANCE)
creature->UpdateEntry(50270, ALLIANCE);
break;
}
}
}
void OnGameObjectCreate(GameObject* go)
{
switch(go->GetEntry())
{
case GO_LADY_NAZJAR_DOOR:
LadyNazjarDoor = go->GetGUID();
if (encounter[0] == DONE)
HandleGameObject(0, true, go);
if (encounter[0] == IN_PROGRESS)
HandleGameObject(0, false, go);
break;
case GO_JELLYFISH_ELEVATOR:
JellyFishElevator = go->GetGUID();
if (encounter[0] == DONE)
HandleGameObject(0, true, go);
if (encounter[0] == IN_PROGRESS)
HandleGameObject(0, false, go);
break;
case GO_COMMANDER_ULTHOK_DOOR:
CommanderUlthokDoor = go->GetGUID();
if (encounter[0] == DONE)
HandleGameObject(0, false, go);
if (encounter[1] == DONE)
HandleGameObject(0, true, go);
break;
case GO_ERUNAK_STONESPEAKER_DOOR:
OzumatDoor = go->GetGUID();
if (encounter[1] == DONE)
HandleGameObject(0, true, go);
if (encounter[2] == IN_PROGRESS)
HandleGameObject(0, false, go);
if (encounter[2] == DONE)
HandleGameObject(0, true, go);
break;
case GO_OZUMAT_DOOR:
ErunakStonespeakerDoor = go->GetGUID();
if (encounter[2] == DONE)
HandleGameObject(0, true, go);
if (encounter[3] == IN_PROGRESS)
HandleGameObject(0, false, go);
if (encounter[3] == DONE)
HandleGameObject(0, true, go);
break;
}
}
void SetData(uint32 type, uint32 data)
{
switch(type)
{
case DATA_LADY_NAZJAR_EVENT:
encounter[0] = data;
break;
case DATA_COMMANDER_ULTHOK_EVENT:
encounter[1] = data;
break;
case DATA_ERUNAK_STONESPEAKER_EVENT:
encounter[2] = data;
break;
case DATA_OZUMAT_EVENT:
encounter[3] = data;
break;
}
if (data == DONE)
SaveToDB();
}
uint32 GetData(uint32 type) const
{
switch(type)
{
case DATA_LADY_NAZJAR_EVENT: return encounter[0];
case DATA_COMMANDER_ULTHOK_EVENT: return encounter[1];
case DATA_ERUNAK_STONESPEAKER_EVENT: return encounter[2];
case DATA_OZUMAT_EVENT: return encounter[3];
}
return 0;
}
uint64 GetData64(uint32 identifier) const
{
switch(identifier)
{
case DATA_LADY_NAZJAR: return LadyNazjar;
case DATA_COMMANDER_ULTHOK: return CommanderUlthok;
case DATA_ERUNAK_STONESPEAKER: return ErunakStonespeaker;
case BOSS_MINDBENDER_GHURSHA: return MindbenderGhursha;
case DATA_OZUMAT: return Ozumat;
case DATA_NEPTULON: return Neptulon;
}
return 0;
}
std::string GetSaveData()
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << "T o t T " << encounter[0] << " " << encounter[1] << " "
<< encounter[2] << " " << encounter[3];
str_data = saveStream.str();
OUT_SAVE_INST_DATA_COMPLETE;
return str_data;
}
void Load(const char* in)
{
if (!in)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(in);
char dataHead1, dataHead2, dataHead3, dataHead4;
uint16 data0, data1, data2, data3;
std::istringstream loadStream(in);
loadStream >> dataHead1 >> dataHead2 >> dataHead3 >> dataHead4 >> data0 >> data1 >> data2 >> data3;
if (dataHead1 == 'T' && dataHead2 == 'o' && dataHead3 == 't' && dataHead4 == 'T')
{
encounter[0] = data0;
encounter[1] = data1;
encounter[2] = data2;
encounter[3] = data3;
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
if (encounter[i] == IN_PROGRESS)
encounter[i] = NOT_STARTED;
if(encounter[0] == DONE && encounter[1] == NOT_STARTED)
{
if(Creature* summoner = instance->GetCreature(Neptulon))
summoner->SummonCreature(BOSS_COMMANDER_ULTHOK, 59.185f, 802.251f, 805.730f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 60480000);
}
} else OUT_LOAD_INST_DATA_FAIL;
OUT_LOAD_INST_DATA_COMPLETE;
}
};
};
void AddSC_instance_throne_of_the_tides()
{
new instance_throne_of_the_tides();
}
|
gpl-2.0
|
artur-kink/7kaa
|
src/file/ODIR.cpp
|
5227
|
/*
* Seven Kingdoms: Ancient Adversaries
*
* Copyright 1997,1998 Enlight Software Ltd.
*
* 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/>.
*
*/
//Filename : ODIR.CPP
//Description : Object Directory
#include <stdlib.h>
#include <string.h>
#include <ODIR.h>
#ifdef NO_WINDOWS
#include <dirent.h>
#include <ctype.h>
#include <sys/stat.h>
#endif
#include <dbglog.h>
DBGLOG_DEFAULT_CHANNEL(Directory);
//----------- Define static function ------------//
static int sort_file_function( const void *a, const void *b );
//------- Begin of function Directory::Directory -------//
Directory::Directory() : DynArray( sizeof(FileInfo), 20 )
{
}
//-------- End of function Directory::Directory -------//
//------- Begin of function Directory::read -------//
//
// Read in the file list of the specified file spec.
//
// <char*> fileSpec = the file spec of the directory
// [int] sortName = sort the file list by file name
// (default : 0)
//
// return : <int> the no. of files matched the file spec.
//
int Directory::read(const char *fileSpec, int sortName)
{
FileInfo fileInfo;
#ifndef NO_WINDOWS
WIN32_FIND_DATA findData;
//----------- get the file list -------------//
HANDLE findHandle = FindFirstFile( fileSpec, &findData );
while(findHandle!=INVALID_HANDLE_VALUE)
{
misc.extract_file_name( fileInfo.name, findData.cFileName ); // get the file name only from a full path string
fileInfo.size = findData.nFileSizeLow;
fileInfo.time = findData.ftLastWriteTime;
linkin( &fileInfo );
if( !FindNextFile( findHandle, &findData ) )
break;
}
FindClose(findHandle);
//------ the file list by file name ---------//
if( sortName )
quick_sort( sort_file_function );
#else
MSG("Listing Directory %s sortName=%d\n", fileSpec, sortName);
char dirname[MAX_PATH];
char search[MAX_PATH];
struct dirent **namelist;
int n;
char *slash = strrchr((char*)fileSpec, '/');
if (slash)
{
char *s = (char*)fileSpec;
char *d = dirname;
int i = 0;
while (s != slash && i < MAX_PATH - 1)
{
if (*s == '\\')
*d = '/';
else if (isalpha(*s))
*d = tolower(*s);
else
*d = *s;
d++;
s++;
i++;
}
*d = 0;
i = 0;
d = search;
s++;
while (*s && i < MAX_PATH - 1)
{
if (*s == '*')
{
s++;
i++;
continue;
}
else if (isalpha(*s))
{
*d = tolower(*s);
}
else
{
*d = *s;
}
d++;
s++;
i++;
}
*d = 0;
} else {
char *s = (char*)fileSpec;
char *d = search;
int i = 0;
while (*s && i < MAX_PATH - 1)
{
if (*s == '*')
{
s++;
i++;
continue;
}
else if (isalpha(*s))
{
*d = tolower(*s);
}
else
{
*d = *s;
}
d++;
s++;
i++;
}
*d = 0;
dirname[0] = '.';
dirname[1] = 0;
}
MSG("directory=%s search=%s\n", dirname, search);
n = scandir(dirname, &namelist, 0, alphasort);
for (int i = 0; i < n; i++)
{
char filename[MAX_PATH];
char *s = namelist[i]->d_name;
char *d = filename;
int j = 0;
while (*s && j < MAX_PATH - 1)
{
if (isalpha(*s))
*d = tolower(*s);
else
*d = *s;
d++;
s++;
j++;
}
*d = 0;
if (strstr(filename, search))
{
char full_path[MAX_PATH];
struct stat file_stat;
full_path[0] = 0;
strcat(full_path, dirname);
strcat(full_path, "/");
strcat(full_path, namelist[i]->d_name);
stat(full_path, &file_stat);
strncpy(fileInfo.name, namelist[i]->d_name, MAX_PATH - 2);
fileInfo.size = file_stat.st_size;
fileInfo.time.dwLowDateTime = 0;
fileInfo.time.dwHighDateTime = 0;
linkin( &fileInfo );
}
free(namelist[i]);
}
if (n > -1)
free(namelist);
#endif
return size(); // DynArray::size()
}
//-------- End of function Directory::read -------//
//------ Begin of function sort_file_function ------//
//
static int sort_file_function( const void *a, const void *b )
{
return strcmpi( ((FileInfo*)a)->name, ((FileInfo*)b)->name );
}
//------- End of function sort_file_function ------//
|
gpl-2.0
|
nekrozar/ygopro-scripts
|
c33656832.lua
|
2258
|
--曲芸の魔術師
function c33656832.initial_effect(c)
--pendulum summon
aux.EnablePendulumAttribute(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_PZONE)
e1:SetCode(EVENT_DESTROYED)
e1:SetCountLimit(1,33656832)
e1:SetCondition(c33656832.spcon)
e1:SetTarget(c33656832.sptg)
e1:SetOperation(c33656832.spop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_CHAIN_NEGATED)
e2:SetRange(LOCATION_HAND)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCondition(c33656832.spcon2)
e2:SetTarget(c33656832.sptg)
e2:SetOperation(c33656832.spop)
c:RegisterEffect(e2)
--pendulum set
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_BATTLE_DESTROYED)
e3:SetTarget(c33656832.pentg)
e3:SetOperation(c33656832.penop)
c:RegisterEffect(e3)
end
function c33656832.cfilter(c,tp)
return c:IsPreviousLocation(LOCATION_MZONE) and c:GetPreviousControler()==tp and c:IsReason(REASON_EFFECT)
end
function c33656832.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c33656832.cfilter,1,nil,tp)
end
function c33656832.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c33656832.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
function c33656832.spcon2(e,tp,eg,ep,ev,re,r,rp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE)
end
function c33656832.pentg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLocation(tp,LOCATION_PZONE,0) or Duel.CheckLocation(tp,LOCATION_PZONE,1) end
end
function c33656832.penop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e)
and (Duel.CheckLocation(tp,LOCATION_PZONE,0) or Duel.CheckLocation(tp,LOCATION_PZONE,1)) then
Duel.MoveToField(e:GetHandler(),tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
|
gpl-2.0
|
eq0rip/Hamroreview.com
|
wp-content/themes/hueman/header.php
|
2433
|
<!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="wrapper">
<header id="header">
<?php if ( has_nav_menu('topbar') ): ?>
<nav class="nav-container group" id="nav-topbar">
<div class="nav-toggle"><i class="fa fa-bars"></i></div>
<div class="nav-text"><!-- put your mobile menu text here --></div>
<div class="nav-wrap container"><?php wp_nav_menu(array('theme_location'=>'topbar','menu_class'=>'nav container-inner group','container'=>'','menu_id' => '','fallback_cb'=> false)); ?></div>
<div class="container">
<div class="container-inner">
<div class="toggle-search"><i class="fa fa-search"></i></div>
<div class="search-expand">
<div class="search-expand-inner">
<?php get_search_form(); ?>
</div>
</div>
</div><!--/.container-inner-->
</div><!--/.container-->
</nav><!--/#nav-topbar-->
<?php endif; ?>
<div class="container group">
<div class="container-inner">
<div class="group pad">
<?php echo alx_site_title(); ?>
<?php if ( ot_get_option('site-description') != 'off' ): ?><p class="site-description"><?php bloginfo( 'description' ); ?></p><?php endif; ?>
<?php if ( ot_get_option('header-ads') == 'on' ): ?>
<div id="header-ads">
<?php dynamic_sidebar( 'header-ads' ); ?>
</div><!--/#header-ads-->
<?php endif; ?>
</div>
<?php if ( has_nav_menu('header') ): ?>
<nav class="nav-container group" id="nav-header">
<div class="nav-toggle"><i class="fa fa-bars"></i></div>
<div class="nav-text"><!-- put your mobile menu text here --></div>
<div class="nav-wrap container"><?php wp_nav_menu(array('theme_location'=>'header','menu_class'=>'nav container-inner group','container'=>'','menu_id' => '','fallback_cb'=> false)); ?></div>
</nav><!--/#nav-header-->
<?php endif; ?>
</div><!--/.container-inner-->
</div><!--/.container-->
</header><!--/#header-->
<div class="container" id="page">
<div class="container-inner">
<div class="main">
<div class="main-inner group">
|
gpl-2.0
|
Lasanha/Gambiarra
|
libs/olpcgames/textsprite.py
|
1641
|
"""Simple Sprite sub-class that renders via a PangoFont"""
from pygame import sprite
from olpcgames import pangofont
class TextSprite( sprite.Sprite ):
"""Sprite with a simple text renderer"""
image = rect = text = color = background = None
def __init__( self, text=None, family=None, size=None, bold=False, italic=False, color=None, background=None ):
super( TextSprite, self ).__init__( )
self.font = pangofont.PangoFont( family=family, size=size, bold=bold, italic=italic )
self.set_color( color )
self.set_background( background )
self.set_text( text )
def set_text( self, text ):
"""Set our text string and render to a graphic"""
self.text = text
self.render( )
def set_color( self, color =None):
"""Set our rendering colour (default white)"""
self.color = color or (255,255,255)
self.render()
def set_background( self, color=None ):
"""Set our background color, default transparent"""
self.background = color
self.render()
def render( self ):
"""Render our image and rect (or None,None)
After a render you will need to move the rect member to the
correct location on the screen.
"""
if self.text:
self.image = self.font.render( self.text, color = self.color, background = self.background )
currentRect = self.rect
self.rect = self.image.get_rect()
if currentRect:
self.rect.center = currentRect.center
else:
self.rect = None
self.image = None
|
gpl-2.0
|
Froxlor/Froxlor
|
lib/tables.inc.php
|
2393
|
<?php
/**
* This file is part of the Froxlor project.
* Copyright (c) 2003-2009 the SysCP Team (see authors).
* Copyright (c) 2010 the Froxlor Team (see authors).
*
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code. You can also view the
* COPYING file online at http://files.froxlor.org/misc/COPYING.txt
*
* @copyright (c) the authors
* @author Florian Lippert <flo@syscp.org> (2003-2009)
* @author Froxlor team <team@froxlor.org> (2010-)
* @license GPLv2 http://files.froxlor.org/misc/COPYING.txt
* @package System
*
*/
define('TABLE_FTP_GROUPS', 'ftp_groups');
define('TABLE_FTP_USERS', 'ftp_users');
define('TABLE_FTP_QUOTALIMITS', 'ftp_quotalimits');
define('TABLE_FTP_QUOTATALLIES', 'ftp_quotatallies');
define('TABLE_MAIL_AUTORESPONDER', 'mail_autoresponder');
define('TABLE_MAIL_USERS', 'mail_users');
define('TABLE_MAIL_VIRTUAL', 'mail_virtual');
define('TABLE_PANEL_ACTIVATION', 'panel_activation');
define('TABLE_PANEL_ADMINS', 'panel_admins');
define('TABLE_PANEL_CUSTOMERS', 'panel_customers');
define('TABLE_PANEL_DATABASES', 'panel_databases');
define('TABLE_PANEL_DOMAINS', 'panel_domains');
define('TABLE_PANEL_HTACCESS', 'panel_htaccess');
define('TABLE_PANEL_HTPASSWDS', 'panel_htpasswds');
define('TABLE_PANEL_SESSIONS', 'panel_sessions');
define('TABLE_PANEL_SETTINGS', 'panel_settings');
define('TABLE_PANEL_TASKS', 'panel_tasks');
define('TABLE_PANEL_TEMPLATES', 'panel_templates');
define('TABLE_PANEL_TRAFFIC', 'panel_traffic');
define('TABLE_PANEL_TRAFFIC_ADMINS', 'panel_traffic_admins');
define('TABLE_PANEL_DISKSPACE', 'panel_diskspace');
define('TABLE_PANEL_LANGUAGE', 'panel_languages');
define('TABLE_PANEL_IPSANDPORTS', 'panel_ipsandports');
define('TABLE_PANEL_LOG', 'panel_syslog');
define('TABLE_PANEL_PHPCONFIGS', 'panel_phpconfigs');
define('TABLE_PANEL_CRONRUNS', 'cronjobs_run');
define('TABLE_PANEL_REDIRECTCODES', 'redirect_codes');
define('TABLE_PANEL_DOMAINREDIRECTS', 'domain_redirect_codes');
define('TABLE_PANEL_DOMAIN_SSL_SETTINGS', 'domain_ssl_settings');
define('TABLE_DOMAINTOIP', 'panel_domaintoip');
define('TABLE_DOMAIN_DNS', 'domain_dns_entries');
define('TABLE_PANEL_FPMDAEMONS', 'panel_fpmdaemons');
define('TABLE_PANEL_PLANS', 'panel_plans');
define('TABLE_API_KEYS', 'api_keys');
require dirname(__FILE__) . '/version.inc.php';
|
gpl-2.0
|
yad/mangos-d3
|
src/scriptdev2/scripts/kalimdor/azuremyst_isle.cpp
|
8647
|
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Azuremyst_Isle
SD%Complete: 75
SDComment: Quest support: 9283, 9528, Injured Draenei cosmetic only
SDCategory: Azuremyst Isle
EndScriptData */
/* ContentData
npc_draenei_survivor
npc_injured_draenei
npc_magwin
EndContentData */
#include "precompiled.h"
#include "escort_ai.h"
/*######
## npc_draenei_survivor
######*/
enum
{
SAY_HEAL1 = -1000176,
SAY_HEAL2 = -1000177,
SAY_HEAL3 = -1000178,
SAY_HEAL4 = -1000179,
SAY_HELP1 = -1000180,
SAY_HELP2 = -1000181,
SAY_HELP3 = -1000182,
SAY_HELP4 = -1000183,
SPELL_IRRIDATION = 35046,
SPELL_STUNNED = 28630
};
struct npc_draenei_survivorAI : public ScriptedAI
{
npc_draenei_survivorAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();}
ObjectGuid m_casterGuid;
uint32 m_uiSayThanksTimer;
uint32 m_uiRunAwayTimer;
uint32 m_uiSayHelpTimer;
bool m_bCanSayHelp;
void Reset() override
{
m_casterGuid.Clear();
m_uiSayThanksTimer = 0;
m_uiRunAwayTimer = 0;
m_uiSayHelpTimer = 10000;
m_bCanSayHelp = true;
m_creature->CastSpell(m_creature, SPELL_IRRIDATION, true);
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
m_creature->SetHealth(int(m_creature->GetMaxHealth()*.1));
m_creature->SetStandState(UNIT_STAND_STATE_SLEEP);
}
void MoveInLineOfSight(Unit* pWho) override
{
if (m_bCanSayHelp && pWho->GetTypeId() == TYPEID_PLAYER && m_creature->IsFriendlyTo(pWho) &&
m_creature->IsWithinDistInMap(pWho, 25.0f))
{
// Random switch between 4 texts
switch (urand(0, 3))
{
case 0: DoScriptText(SAY_HELP1, m_creature, pWho); break;
case 1: DoScriptText(SAY_HELP2, m_creature, pWho); break;
case 2: DoScriptText(SAY_HELP3, m_creature, pWho); break;
case 3: DoScriptText(SAY_HELP4, m_creature, pWho); break;
}
m_uiSayHelpTimer = 20000;
m_bCanSayHelp = false;
}
}
void SpellHit(Unit* pCaster, const SpellEntry* pSpell) override
{
if (pSpell->IsFitToFamilyMask(UI64LIT(0x0000000000000000), 0x080000000))
{
m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
m_creature->SetStandState(UNIT_STAND_STATE_STAND);
m_creature->CastSpell(m_creature, SPELL_STUNNED, true);
m_casterGuid = pCaster->GetObjectGuid();
m_uiSayThanksTimer = 5000;
}
}
void UpdateAI(const uint32 uiDiff) override
{
if (m_uiSayThanksTimer)
{
if (m_uiSayThanksTimer <= uiDiff)
{
m_creature->RemoveAurasDueToSpell(SPELL_IRRIDATION);
if (Player* pPlayer = m_creature->GetMap()->GetPlayer(m_casterGuid))
{
if (pPlayer->GetTypeId() != TYPEID_PLAYER)
return;
switch (urand(0, 3))
{
case 0: DoScriptText(SAY_HEAL1, m_creature, pPlayer); break;
case 1: DoScriptText(SAY_HEAL2, m_creature, pPlayer); break;
case 2: DoScriptText(SAY_HEAL3, m_creature, pPlayer); break;
case 3: DoScriptText(SAY_HEAL4, m_creature, pPlayer); break;
}
pPlayer->TalkedToCreature(m_creature->GetEntry(), m_creature->GetObjectGuid());
}
m_creature->GetMotionMaster()->Clear();
m_creature->GetMotionMaster()->MovePoint(0, -4115.053711f, -13754.831055f, 73.508949f);
m_uiRunAwayTimer = 10000;
m_uiSayThanksTimer = 0;
}
else m_uiSayThanksTimer -= uiDiff;
return;
}
if (m_uiRunAwayTimer)
{
if (m_uiRunAwayTimer <= uiDiff)
m_creature->ForcedDespawn();
else
m_uiRunAwayTimer -= uiDiff;
return;
}
if (m_uiSayHelpTimer < uiDiff)
{
m_bCanSayHelp = true;
m_uiSayHelpTimer = 20000;
}
else m_uiSayHelpTimer -= uiDiff;
}
};
CreatureAI* GetAI_npc_draenei_survivor(Creature* pCreature)
{
return new npc_draenei_survivorAI(pCreature);
}
/*######
## npc_injured_draenei
######*/
struct npc_injured_draeneiAI : public ScriptedAI
{
npc_injured_draeneiAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();}
void Reset() override
{
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
m_creature->SetHealth(int(m_creature->GetMaxHealth()*.15));
switch (urand(0, 1))
{
case 0: m_creature->SetStandState(UNIT_STAND_STATE_SIT); break;
case 1: m_creature->SetStandState(UNIT_STAND_STATE_SLEEP); break;
}
}
void MoveInLineOfSight(Unit* /*pWho*/) override {} // ignore everyone around them (won't aggro anything)
void UpdateAI(const uint32 /*uiDiff*/) override {}
};
CreatureAI* GetAI_npc_injured_draenei(Creature* pCreature)
{
return new npc_injured_draeneiAI(pCreature);
}
/*######
## npc_magwin
######*/
enum
{
SAY_START = -1000111,
SAY_AGGRO = -1000112,
SAY_PROGRESS = -1000113,
SAY_END1 = -1000114,
SAY_END2 = -1000115,
EMOTE_HUG = -1000116,
QUEST_A_CRY_FOR_HELP = 9528
};
struct npc_magwinAI : public npc_escortAI
{
npc_magwinAI(Creature* pCreature) : npc_escortAI(pCreature) { Reset(); }
void WaypointReached(uint32 uiPointId) override
{
Player* pPlayer = GetPlayerForEscort();
if (!pPlayer)
return;
switch (uiPointId)
{
case 0:
DoScriptText(SAY_START, m_creature, pPlayer);
break;
case 17:
DoScriptText(SAY_PROGRESS, m_creature, pPlayer);
break;
case 28:
DoScriptText(SAY_END1, m_creature, pPlayer);
break;
case 29:
DoScriptText(EMOTE_HUG, m_creature, pPlayer);
DoScriptText(SAY_END2, m_creature, pPlayer);
pPlayer->GroupEventHappens(QUEST_A_CRY_FOR_HELP, m_creature);
break;
}
}
void Aggro(Unit* pWho) override
{
DoScriptText(SAY_AGGRO, m_creature, pWho);
}
void Reset() override { }
};
bool QuestAccept_npc_magwin(Player* pPlayer, Creature* pCreature, const Quest* pQuest)
{
if (pQuest->GetQuestId() == QUEST_A_CRY_FOR_HELP)
{
pCreature->SetFactionTemporary(FACTION_ESCORT_A_NEUTRAL_PASSIVE, TEMPFACTION_RESTORE_RESPAWN);
if (npc_magwinAI* pEscortAI = dynamic_cast<npc_magwinAI*>(pCreature->AI()))
pEscortAI->Start(false, pPlayer, pQuest);
}
return true;
}
CreatureAI* GetAI_npc_magwinAI(Creature* pCreature)
{
return new npc_magwinAI(pCreature);
}
void AddSC_azuremyst_isle()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "npc_draenei_survivor";
pNewScript->GetAI = &GetAI_npc_draenei_survivor;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "npc_injured_draenei";
pNewScript->GetAI = &GetAI_npc_injured_draenei;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "npc_magwin";
pNewScript->GetAI = &GetAI_npc_magwinAI;
pNewScript->pQuestAcceptNPC = &QuestAccept_npc_magwin;
pNewScript->RegisterSelf();
}
|
gpl-2.0
|
dtiguarulhos/suporteguarulhos
|
front/notificationmailsetting.form.php
|
1671
|
<?php
/*
* @version $Id: notificationmailsetting.form.php 23305 2015-01-21 15:06:28Z moyo $
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2014 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org
-------------------------------------------------------------------------
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
*/
include ('../inc/includes.php');
Session::checkRight("config", UPDATE);
$notificationmail = new NotificationMailSetting();
if (!empty($_POST["test_smtp_send"])) {
NotificationMail::testNotification();
Html::back();
} else if (!empty($_POST["update"])) {
$config = new Config();
$config->update($_POST);
Html::back();
}
Html::header(Notification::getTypeName(Session::getPluralNumber()), $_SERVER['PHP_SELF'], "config", "notification", "config");
$notificationmail->display(array('id' => 1));
Html::footer();
?>
|
gpl-2.0
|
onkelhotte/XCSoar
|
src/Form/TabDisplay.hpp
|
3935
|
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2013 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.
}
*/
#ifndef XCSOAR_FORM_TAB_DISPLAY_HPP
#define XCSOAR_FORM_TAB_DISPLAY_HPP
#include "Screen/PaintWindow.hpp"
#include "Util/StaticArray.hpp"
#include "Util/StaticString.hpp"
#include <tchar.h>
struct DialogLook;
class Bitmap;
class ContainerWindow;
class TabBarControl;
/**
* TabButton class holds display and callbacks data for a single tab
*/
class TabButton {
public:
StaticString<32> caption;
const Bitmap *bitmap;
PixelRect rc;
public:
TabButton(const TCHAR* _caption, const Bitmap *_bitmap)
:bitmap(_bitmap)
{
caption = _caption;
rc.left = 0;
rc.top = 0;
rc.right = 0;
rc.bottom = 0;
};
};
/**
* TabDisplay class handles onPaint callback for TabBar UI
* and handles Mouse and key events
* TabDisplay uses a pointer to TabBarControl
* to show/hide the appropriate pages in the Container Class
*/
class TabDisplay: public PaintWindow
{
protected:
TabBarControl& tab_bar;
const DialogLook &look;
StaticArray<TabButton *, 32> buttons;
const bool vertical;
bool dragging; // tracks that mouse is down and captured
bool drag_off_button; // set by mouse_move
unsigned down_index; // index of tab where mouse down occurred
const UPixelScalar tab_line_height;
public:
/**
*
* @param parent
* @param _theTabBar. An existing TabBar object
*/
TabDisplay(TabBarControl& _theTabBar, const DialogLook &look,
ContainerWindow &parent, PixelRect rc,
bool vertical);
virtual ~TabDisplay();
const DialogLook &GetLook() const {
return look;
}
bool IsVertical() const {
return vertical;
}
/**
* Paints one button
*/
static void PaintButton(Canvas &canvas, const unsigned CaptionStyle,
const TCHAR *caption, const PixelRect &rc,
const Bitmap *bmp, const bool isDown, bool inverse);
unsigned GetSize() const {
return buttons.size();
}
void Add(const TCHAR *caption, const Bitmap *bmp = NULL);
gcc_pure
const TCHAR *GetCaption(unsigned i) const {
return buttons[i]->caption.c_str();
}
/**
* @return -1 if there is no button at the specified position
*/
gcc_pure
int GetButtonIndexAt(RasterPoint p) const;
private:
/**
* calculates the size and position of ith button
* works in landscape or portrait mode
* @param i index of button
* @return Rectangle of button coordinates
*/
gcc_pure
const PixelRect &GetButtonSize(unsigned i) const;
protected:
virtual void OnPaint(Canvas &canvas) override;
virtual void OnKillFocus() override;
virtual void OnSetFocus() override;
virtual void OnCancelMode() override;
virtual bool OnKeyCheck(unsigned key_code) const override;
virtual bool OnKeyDown(unsigned key_code) override;
virtual bool OnMouseDown(PixelScalar x, PixelScalar y) override;
virtual bool OnMouseUp(PixelScalar x, PixelScalar y) override;
virtual bool OnMouseMove(PixelScalar x, PixelScalar y,
unsigned keys) override;
void EndDrag();
};
#endif
|
gpl-2.0
|
dubrousky/preon
|
preon-samples/preon-sample-bmp/src/main/java/org/codehaus/preon/sample/bmp/BitmapInformation.java
|
2794
|
/**
* Copyright (C) 2009-2010 Wilfred Springer
*
* This file is part of Preon.
*
* Preon 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.
*
* Preon 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
* Preon; see the file COPYING. If not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is making a
* combined work based on this library. Thus, the terms and conditions of the
* GNU General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and
* to copy and distribute the resulting executable under terms of your choice,
* provided that you also meet, for each linked independent module, the terms
* and conditions of the license of that module. An independent module is a
* module which is not derived from or based on this library. If you modify this
* library, you may extend this exception to your version of the library, but
* you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package org.codehaus.preon.sample.bmp;
import org.codehaus.preon.annotation.BoundNumber;
import org.codehaus.preon.annotation.Purpose;
@Purpose("Bitmap information.")
public class BitmapInformation {
@BoundNumber(size = "32")
private long headerSize;
@BoundNumber(size = "32")
private long bitmapWidth;
@BoundNumber(size = "32")
private long bitmapHeight;
@BoundNumber(size = "16")
private int numberOfColorPlanes;
@BoundNumber(size = "16")
private int colorDepth;
@BoundNumber(size = "32")
private long compressionMethod;
@BoundNumber(size = "32")
private long imageSize;
@BoundNumber(size = "32")
private long horizontalResolution;
@BoundNumber(size = "32")
private long verticalResolution;
@BoundNumber(size = "32")
private long numberOfColors;
@BoundNumber(size = "32")
private long numberOfImportantColors;
public long getHeight() {
return bitmapHeight;
}
public long getWidth() {
return bitmapWidth;
}
}
|
gpl-2.0
|
rompe/digikam-core-yolo
|
project/scripts/cleanup_headers/cleanup_headers.py
|
8065
|
#!/usr/bin/env python
# ============================================================
#
# This file is a part of digiKam project
# http://www.digikam.org
#
# Date : 2009-10-12
# Description : a helper script for formatting the digiKam source code
#
# Copyright (C) 2009-2012 by Andi Clemens <andi dot clemens 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, 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.
#
# ============================================================ */
import os
import sys
import re
# --------------------------------------------------
# VARIABLES
sourcedir = ""
patternsdir = os.path.dirname(os.path.realpath(__file__))
patternsurl = os.path.join(patternsdir, "known_patterns.txt")
filelist = list()
# PATTERNS
pfile = re.compile("^.*\.(cpp)$") # filename pattern
pic = re.compile("^\s*\/\/\s*.*includes?\.*\s*$") # old include comments
pch = re.compile(".*={10,}.*") # copyright header boundries
plocal = re.compile("\"[a-zA-Z].*\.h\"") # local includes
pqt = re.compile("<[Qq].*(.h)?>") # Qt includes
pkde = re.compile("<k.*\.h>") # KDE includes
pcpp = re.compile("<c.*(.h)?>") # C++ includes
pkdcraw = re.compile("<libkdcraw\/.*(.h)?>") # libkdcraw includes
pkexiv2 = re.compile("<libkexiv2\/.*(.h)?>") # libkexiv2 includes
pkipi = re.compile("<libkipi\/.*(.h)?>") # libkipi includes
pinclude = "#include" # include statement
pknown = dict() # will hold known patterns
# FIXME: maybe it is better to generate all valid header files from filesystem
# paths instead of those regex patterns
# --------------------------------------------------
def intro(dir, pattern):
print()
print("digiKam code cleaner")
print()
print("SOURCEDIR:\t%s" % os.path.realpath(dir))
print("PATTERNS FILE:\t%s" % pattern)
print()
# --------------------------------------------------
def legend():
print()
print("-" * 50)
print()
print("Legend:")
print()
print("PARSE ERROR")
print("\tThe sourcecode is malformed, the shown lines need to be checked manually")
print()
print("MISSING / WRONG REGEX")
print("\tThe pattern for an include statement was not recognized.")
print("\tAdd it to the patterns file or create an regex for it.")
print("\tFor now, the patterns can be found under '// OTHERS includes.'")
print("\tin the sourceode.")
print()
# --------------------------------------------------
# generate known patterns map
def generate_known_patterns(file):
patterns = dict()
try:
f = open(file, 'r')
for line in f:
k, v = line.strip().split()
if not k in patterns:
patterns[k] = list()
patterns[k].append(v)
except:
patterns = dict()
finally:
f.close()
return patterns
# --------------------------------------------------
# generate a sorted includes list
def generate_includes(fp, includes, comment, bstart=None, bend=None):
tmp = list()
if (includes):
includes.sort()
if (comment):
fp.write("\n// %s includes\n\n" % comment)
else:
fp.write("\n")
if bstart: fp.write(bstart+"\n")
for inc in includes: fp.write("#include " + inc)
if bend: fp.write(bend+"\n")
# --------------------------------------------------
# strip the whitespace / empty lines from the sourcecode block
def strip_content(content):
return "".join(str(c) for c in content).strip()
# --------------------------------------------------
# parse the files in filelist and generate a new sourcefile
def parse_files(filelist):
errors = False
print("parsing %s files... " % len(filelist))
print()
for file in filelist:
inheader = False
i = 0
nameonly = '%s' % file.split(".")[-2].split("/")[-1]
pow = re.compile("\"%s\.(h|moc)\"" % nameonly)
header = list()
includes = list()
owninc = list()
localinc = list()
qtinc = list()
kdeinc = list()
cppinc = list()
cinc = list()
kdcrawinc = list()
kexiv2inc = list()
kipiinc = list()
sourcecode = list()
f = open(file, 'r')
for line in f:
i += 1
if pinclude in line:
try:
command, include = line.split(" ", 1)
except:
errors = True
print("PARSE ERROR: %s (%s)" % (line.strip(), file))
continue
if pow.match(include): owninc.append(include)
elif (include.strip() in pknown['kde']): kdeinc.append(include)
elif (include.strip() in pknown['cpp']): cppinc.append(include)
elif (include.strip() in pknown['c']): cinc.append(include)
elif plocal.match(include): localinc.append(include)
elif pqt.match(include): qtinc.append(include)
elif pkde.match(include): kdeinc.append(include)
elif pcpp.match(include): cppinc.append(include)
elif pkdcraw.match(include): kdcrawinc.append(include)
elif pkexiv2.match(include): kexiv2inc.append(include)
elif pkipi.match(include): kipiinc.append(include)
else:
includes.append(include)
errors = True
print("MISSING / WRONG REGEX: %s (%s)" % (line.strip(), file))
elif pic.match(line): continue
elif pch.match(line):
if i < 5 and not inheader:
inheader = True
header.append(line)
elif inheader:
inheader = False
header.append(line)
elif inheader:
header.append(line)
else: sourcecode.append(line)
f.close()
#output
fw = open(file, 'w')
for h in header: fw.write(h)
# order is important!!
generate_includes(fw, owninc, "")
generate_includes(fw, includes, "OTHERS")
generate_includes(fw, cinc, "C ANSI", 'extern "C"\n{', '}')
generate_includes(fw, cppinc, "C++")
generate_includes(fw, qtinc, "Qt")
generate_includes(fw, kdeinc, "KDE")
generate_includes(fw, kdcrawinc, "LibKDcraw")
generate_includes(fw, kexiv2inc, "LibKExiv2")
generate_includes(fw, kipiinc, "Libkipi")
generate_includes(fw, localinc, "Local")
fw.write("\n"+strip_content(sourcecode)+"\n");
fw.close()
return errors
# --------------------------------------------------
# MAIN
if __name__ == '__main__':
# check for valid arguments first
if (len(sys.argv) != 2):
print("usage: cleanup_headers.py <sourcedir>")
sys.exit(1)
sourcedir = sys.argv[1]
intro(sourcedir, patternsurl)
# scan given source dir
filelist = [os.path.join(root, file) for root, dirs, files in os.walk(sourcedir) for file in files if pfile.match(file)]
# read known patterns
pknown = generate_known_patterns(patternsurl)
# parse files
error = parse_files(filelist)
if error: legend()
|
gpl-2.0
|
Regis85/gepi
|
mod_ooo/extractions/extrait_AID_1_fichier.php
|
2015
|
<?php
/*
*
* Copyright 2015 Régis Bouguin
*
* This file is part of GEPI.
*
* GEPI 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.
*
* GEPI 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 GEPI; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
[eleves.nom]
[eleves.prenom]
[eleves.sexe]
[eleves.date_nais]
[eleves.lieu_nais]
[eleves.classe]
[eleves.ine]
[eleves.elenoet]
[eleves.ele_id]
[eleves.login]
*/
/*
echo 'AID dans 1 fichier<br />';
print_r($id_AID);
echo '<br />';
print_r($num_fich);
echo '<br />';
*/
$i = 0;
$filtre = "";
foreach ($id_AID as $id) {
if ($i) {
$filtre .= "OR ";
}
$filtre .= "a.`id_aid` LIKE '".$id."' ";
$i++;
}
$sqlElv = "SELECT DISTINCT a.`login` , e.`nom` , e.`prenom` , "
. "e.`sexe` , e.`naissance` , e.`lieu_naissance` , "
. "c.`classe` , e.`no_gep` , e.`elenoet`, e.`ele_id` "
. "FROM `j_aid_eleves` AS a "
. "INNER JOIN `eleves` AS e ON e.`login` = a.`login`"
. "INNER JOIN `j_eleves_classes` AS jec ON jec.`login` = e.`login` "
. "INNER JOIN `classes` AS c ON c.`id` = jec.`id_classe` "
. "WHERE ".$filtre." "
. "ORDER BY e.nom, e.prenom ";
// echo $sqlElv.'<br />';
$resElv = mysqli_query($mysqli, $sqlElv);
if(mysqli_num_rows($resElv)>0) {
$tab_eleves_OOo=array();
$nb_eleve=0;
while($lig=mysqli_fetch_object($resElv)) {
$nb_eleve_actuel=$nb_eleve;
include 'lib/charge_tableau.php';
$tab_eleves_OOo[$nb_eleve_actuel]['classe']=$lig->classe;
}
}
|
gpl-2.0
|
sanjanjetan/lba-website
|
library/core/class.email.php
|
15503
|
<?php
/**
* @copyright 2009-2016 Vanilla Forums Inc.
* @license http://www.opensource.org/licenses/gpl-2.0.php GNU GPL v2
*/
/**
* Email layer abstraction
*
* This class implements fluid method chaining.
*
* @author Mark O'Sullivan <markm@vanillaforums.com>
* @author Todd Burry <todd@vanillaforums.com>
* @package Core
* @since 2.0
*/
class Gdn_Email extends Gdn_Pluggable {
/** @var PHPMailer */
public $PhpMailer;
/** @var boolean */
private $_IsToSet;
/** @var array Recipients that were skipped because they lack permission. */
public $Skipped = array();
/** @var EmailTemplate The email body renderer. Use this to edit the email body. */
protected $emailTemplate;
/** @var string The format of the email. */
protected $format;
/** @var string The supported email formats. */
public static $supportedFormats = array('html', 'text');
/**
* Constructor.
*/
function __construct() {
$this->PhpMailer = new PHPMailer();
$this->PhpMailer->CharSet = c('Garden.Charset', 'utf-8');
$this->PhpMailer->SingleTo = c('Garden.Email.SingleTo', false);
$this->PhpMailer->PluginDir = combinePaths(array(PATH_LIBRARY, 'vendors/phpmailer/'));
$this->PhpMailer->Hostname = c('Garden.Email.Hostname', '');
$this->PhpMailer->Encoding = 'quoted-printable';
$this->clear();
$this->addHeader('Precedence', 'list');
$this->addHeader('X-Auto-Response-Suppress', 'All');
$this->setEmailTemplate(new EmailTemplate());
$this->resolveFormat();
parent::__construct();
}
/**
* Sets the format property based on the config, and defaults to html.
*/
protected function resolveFormat() {
$configFormat = c('Garden.Email.Format', 'text');
if (in_array(strtolower($configFormat), self::$supportedFormats)) {
$this->setFormat($configFormat);
} else {
$this->setFormat('text');
}
}
/**
* Sets the format property, the email mime type and the email template format property.
*
* @param string $format The format of the email. Must be in the $supportedFormats array.
* @return Gdn_Email
*/
public function setFormat($format) {
if (strtolower($format) === 'html') {
$this->format = 'html';
$this->mimeType('text/html');
$this->emailTemplate->setPlaintext(false);
} else {
$this->format = 'text';
$this->mimeType('text/plain');
$this->emailTemplate->setPlaintext(true);
}
return $this;
}
/**
* Get email format
*
* Returns 'text' or 'html'.
*
* @return string
*/
public function getFormat() {
return $this->format;
}
/**
* Add a custom header to the outgoing email.
*
* @param string $Name
* @param string $Value
* @since 2.1
* @return Gdn_Email
*/
public function addHeader($Name, $Value) {
$this->PhpMailer->addCustomHeader("$Name:$Value");
return $this;
}
/**
* Adds to the "Bcc" recipient collection.
*
* @param mixed $RecipientEmail An email (or array of emails) to add to the "Bcc" recipient collection.
* @param string $RecipientName The recipient name associated with $RecipientEmail. If $RecipientEmail is
* an array of email addresses, this value will be ignored.
* @return Gdn_Email
*/
public function bcc($RecipientEmail, $RecipientName = '') {
if ($RecipientName != '' && c('Garden.Email.OmitToName', false)) {
$RecipientName = '';
}
ob_start();
$this->PhpMailer->addBCC($RecipientEmail, $RecipientName);
ob_end_clean();
return $this;
}
/**
* Adds to the "Cc" recipient collection.
*
* @param mixed $RecipientEmail An email (or array of emails) to add to the "Cc" recipient collection.
* @param string $RecipientName The recipient name associated with $RecipientEmail. If $RecipientEmail is
* an array of email addresses, this value will be ignored.
* @return Gdn_Email
*/
public function cc($RecipientEmail, $RecipientName = '') {
if ($RecipientName != '' && c('Garden.Email.OmitToName', false)) {
$RecipientName = '';
}
ob_start();
$this->PhpMailer->addCC($RecipientEmail, $RecipientName);
ob_end_clean();
return $this;
}
/**
* Clears out all previously specified values for this object and restores
* it to the state it was in when it was instantiated.
*
* @return Gdn_Email
*/
public function clear() {
$this->PhpMailer->clearAllRecipients();
$this->PhpMailer->Body = '';
$this->PhpMailer->AltBody = '';
$this->from();
$this->_IsToSet = false;
$this->mimeType(c('Garden.Email.MimeType', 'text/plain'));
$this->_MasterView = 'email.master';
$this->Skipped = array();
return $this;
}
/**
* Allows the explicit definition of the email's sender address & name.
* Defaults to the applications Configuration 'SupportEmail' & 'SupportName' settings respectively.
*
* @param string $SenderEmail
* @param string $SenderName
* @param boolean $bOverrideSender optional. default false.
* @return Gdn_Email
*/
public function from($SenderEmail = '', $SenderName = '', $bOverrideSender = false) {
if ($SenderEmail == '') {
$SenderEmail = c('Garden.Email.SupportAddress', '');
if (!$SenderEmail) {
$SenderEmail = 'noreply@'.Gdn::request()->host();
}
}
if ($SenderName == '') {
$SenderName = c('Garden.Email.SupportName', c('Garden.Title', ''));
}
if ($this->PhpMailer->Sender == '' || $bOverrideSender) {
$this->PhpMailer->Sender = $SenderEmail;
}
ob_start();
$this->PhpMailer->setFrom($SenderEmail, $SenderName, false);
ob_end_clean();
return $this;
}
/**
* Allows the definition of a masterview other than the default: "email.master".
*
* @deprecated since version 2.2
* @param string $MasterView
* @return Gdn_Email
*/
public function masterView($MasterView) {
deprecated(__METHOD__);
return $this;
}
/**
* The message to be sent.
*
* @param string $message The body of the message to be sent.
* @param boolean $convertNewlines Optional. Convert newlines to br tags
* @return Gdn_Email
*/
public function message($message, $convertNewlines = true) {
$this->emailTemplate->setMessage($message, $convertNewlines);
return $this;
}
public function formatMessage($message) {
// htmlspecialchars_decode is being used here to revert any specialchar escaping done by Gdn_Format::Text()
// which, untreated, would result in ' in the message in place of single quotes.
if ($this->PhpMailer->ContentType == 'text/html') {
$TextVersion = false;
if (stristr($message, '<!-- //TEXT VERSION FOLLOWS//')) {
$EmailParts = explode('<!-- //TEXT VERSION FOLLOWS//', $message);
$TextVersion = array_pop($EmailParts);
$message = array_shift($EmailParts);
$TextVersion = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $TextVersion)));
$message = trim($message);
}
$this->PhpMailer->msgHTML(htmlspecialchars_decode($message, ENT_QUOTES));
if ($TextVersion !== false && !empty($TextVersion)) {
$TextVersion = html_entity_decode($TextVersion);
$this->PhpMailer->AltBody = $TextVersion;
}
} else {
$this->PhpMailer->Body = htmlspecialchars_decode($message, ENT_QUOTES);
}
return $this;
}
/**
* @return EmailTemplate The email body renderer.
*/
public function getEmailTemplate() {
return $this->emailTemplate;
}
/**
* @param EmailTemplate $emailTemplate The email body renderer.
* @return Gdn_Email
*/
public function setEmailTemplate($emailTemplate) {
$this->emailTemplate = $emailTemplate;
// if we change email templates after construct, inform it of the current format
if ($this->format) {
$this->setFormat($this->format);
}
return $this;
}
/**
*
*
* @param $template
* @return bool|mixed|string
*/
public static function getTextVersion($template) {
if (stristr($template, '<!-- //TEXT VERSION FOLLOWS//')) {
$emailParts = explode('<!-- //TEXT VERSION FOLLOWS//', $template);
$textVersion = array_pop($emailParts);
$textVersion = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $textVersion)));
return $textVersion;
}
return false;
}
/**
*
*
* @param $template
* @return mixed|string
*/
public static function getHTMLVersion($template) {
if (stristr($template, '<!-- //TEXT VERSION FOLLOWS//')) {
$emailParts = explode('<!-- //TEXT VERSION FOLLOWS//', $template);
array_pop($emailParts);
$message = array_shift($emailParts);
$message = trim($message);
return $message;
}
return $template;
}
/**
* Sets the mime-type of the email.
*
* Only accept text/plain or text/html.
*
* @param string $MimeType The mime-type of the email.
* @return Gdn_Email
*/
public function mimeType($MimeType) {
$this->PhpMailer->isHTML($MimeType === 'text/html');
return $this;
}
/**
* @param string $EventName
* @todo add port settings
* @return boolean
*/
public function send($EventName = '') {
$this->formatMessage($this->emailTemplate->toString());
$this->fireEvent('BeforeSendMail');
if (c('Garden.Email.Disabled')) {
return;
}
if (c('Garden.Email.UseSmtp')) {
$this->PhpMailer->isSMTP();
$SmtpHost = c('Garden.Email.SmtpHost', '');
$SmtpPort = c('Garden.Email.SmtpPort', 25);
if (strpos($SmtpHost, ':') !== false) {
list($SmtpHost, $SmtpPort) = explode(':', $SmtpHost);
}
$this->PhpMailer->Host = $SmtpHost;
$this->PhpMailer->Port = $SmtpPort;
$this->PhpMailer->SMTPSecure = c('Garden.Email.SmtpSecurity', '');
$this->PhpMailer->Username = $Username = c('Garden.Email.SmtpUser', '');
$this->PhpMailer->Password = $Password = c('Garden.Email.SmtpPassword', '');
if (!empty($Username)) {
$this->PhpMailer->SMTPAuth = true;
}
} else {
$this->PhpMailer->isMail();
}
if ($EventName != '') {
$this->EventArguments['EventName'] = $EventName;
$this->fireEvent('SendMail');
}
if (!empty($this->Skipped) && $this->PhpMailer->countRecipients() == 0) {
// We've skipped all recipients.
return true;
}
$this->PhpMailer->throwExceptions(true);
if (!$this->PhpMailer->send()) {
throw new Exception($this->PhpMailer->ErrorInfo);
}
return true;
}
/**
* Adds subject of the message to the email.
*
* @param string $Subject The subject of the message.
* @return Gdn_Email
*/
public function subject($Subject) {
$this->PhpMailer->Subject = $Subject;
return $this;
}
public function addTo($RecipientEmail, $RecipientName = '') {
if ($RecipientName != '' && c('Garden.Email.OmitToName', false)) {
$RecipientName = '';
}
ob_start();
$this->PhpMailer->addAddress($RecipientEmail, $RecipientName);
ob_end_clean();
return $this;
}
/**
* Adds to the "To" recipient collection.
*
* @param mixed $RecipientEmail An email (or array of emails) to add to the "To" recipient collection.
* @param string $RecipientName The recipient name associated with $RecipientEmail. If $RecipientEmail is
* an array of email addresses, this value will be ignored.
* @return Gdn_Email
*/
public function to($RecipientEmail, $RecipientName = '') {
if ($RecipientName != '' && c('Garden.Email.OmitToName', false)) {
$RecipientName = '';
}
if (is_string($RecipientEmail)) {
if (strpos($RecipientEmail, ',') > 0) {
$RecipientEmail = explode(',', $RecipientEmail);
// trim no need, PhpMailer::AddAnAddress() will do it
return $this->to($RecipientEmail, $RecipientName);
}
if ($this->PhpMailer->SingleTo) {
return $this->addTo($RecipientEmail, $RecipientName);
}
if (!$this->_IsToSet) {
$this->_IsToSet = true;
$this->addTo($RecipientEmail, $RecipientName);
} else {
$this->cc($RecipientEmail, $RecipientName);
}
return $this;
} elseif ((is_object($RecipientEmail) && property_exists($RecipientEmail, 'Email'))
|| (is_array($RecipientEmail) && isset($RecipientEmail['Email']))
) {
$User = $RecipientEmail;
$RecipientName = val('Name', $User);
$RecipientEmail = val('Email', $User);
$UserID = val('UserID', $User, false);
if ($UserID !== false) {
// Check to make sure the user can receive email.
if (!Gdn::userModel()->checkPermission($UserID, 'Garden.Email.View')) {
$this->Skipped[] = $User;
return $this;
}
}
return $this->to($RecipientEmail, $RecipientName);
} elseif ($RecipientEmail instanceof Gdn_DataSet) {
foreach ($RecipientEmail->resultObject() as $Object) {
$this->to($Object);
}
return $this;
} elseif (is_array($RecipientEmail)) {
$Count = count($RecipientEmail);
if (!is_array($RecipientName)) {
$RecipientName = array_fill(0, $Count, '');
}
if ($Count == count($RecipientName)) {
$RecipientEmail = array_combine($RecipientEmail, $RecipientName);
foreach ($RecipientEmail as $Email => $Name) {
$this->to($Email, $Name);
}
} else {
trigger_error(errorMessage('Size of arrays do not match', 'Email', 'To'), E_USER_ERROR);
}
return $this;
}
trigger_error(errorMessage('Incorrect first parameter ('.getType($RecipientEmail).') passed to function.', 'Email', 'To'), E_USER_ERROR);
}
public function charset($Use = '') {
if ($Use != '') {
$this->PhpMailer->CharSet = $Use;
return $this;
}
return $this->PhpMailer->CharSet;
}
}
|
gpl-2.0
|
secatoriuris/vista-theme
|
modules/contrib/webform/src/Plugin/WebformSourceEntity/RouteParametersWebformSourceEntity.php
|
2348
|
<?php
namespace Drupal\webform\Plugin\WebformSourceEntity;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\webform\Plugin\WebformSourceEntityInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Detect source entity by examining route parameters.
*
* @WebformSourceEntity(
* id = "route_parameters",
* label = @Translation("Route parameters"),
* weight = 100
* )
*/
class RouteParametersWebformSourceEntity extends PluginBase implements WebformSourceEntityInterface, ContainerFactoryPluginInterface {
/**
* Current route match service.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_route_match')
);
}
/**
* RouteParametersWebformSourceEntity constructor.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The "current_route_match" service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteMatchInterface $route_match) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public function getSourceEntity(array $ignored_types) {
// Get the most specific source entity available in the current route's
// parameters.
$parameters = $this->routeMatch->getParameters()->all();
$parameters = array_reverse($parameters);
if (!empty($ignored_types)) {
$parameters = array_diff_key($parameters, array_flip($ignored_types));
}
foreach ($parameters as $value) {
if ($value instanceof EntityInterface) {
return $value;
}
}
return NULL;
}
}
|
gpl-2.0
|
DRIZO/xcsoar
|
src/Audio/Sound.cpp
|
1694
|
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2013 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 "Audio/Sound.hpp"
#ifdef ANDROID
#include "Android/Main.hpp"
#include "Android/SoundUtil.hpp"
#include "Android/Context.hpp"
#endif
#if defined(WIN32) && !defined(GNAV)
#include "ResourceLoader.hpp"
#include <windows.h>
#include <mmsystem.h>
#endif
bool
PlayResource(const TCHAR *resource_name)
{
#ifdef ANDROID
return SoundUtil::Play(Java::GetEnv(), context->Get(), resource_name);
#elif defined(WIN32) && !defined(GNAV)
if (_tcsstr(resource_name, TEXT(".wav")))
return sndPlaySound(resource_name, SND_ASYNC | SND_NODEFAULT);
ResourceLoader::Data data = ResourceLoader::Load(resource_name, _T("WAVE"));
return !data.IsNull() &&
sndPlaySound((LPCTSTR)data.data,
SND_MEMORY | SND_ASYNC | SND_NODEFAULT);
#else
return false;
#endif
}
|
gpl-2.0
|
KDE/calligra-history
|
kformula/flake/elements/AnnotationElement.cpp
|
1071
|
/* This file is part of the KDE project
Copyright (C) 2010 Inge Wallin <inge@lysator.liu.se>
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 "AnnotationElement.h"
AnnotationElement::AnnotationElement( BasicElement* parent ) : BasicElement( parent )
{
}
ElementType AnnotationElement::elementType() const
{
return Annotation;
}
|
gpl-2.0
|
austinv11/PeripheralsPlusPlus
|
src/api/resources/reference/miscperipherals/tile/TileSignalController.java
|
11414
|
package miscperipherals.tile;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import miscperipherals.core.TickHandler;
import miscperipherals.util.Util;
import mods.railcraft.api.core.WorldCoordinate;
import mods.railcraft.api.signals.IControllerTile;
import mods.railcraft.api.signals.IReceiverTile;
import mods.railcraft.api.signals.SignalAspect;
import mods.railcraft.api.signals.SignalController;
import mods.railcraft.api.signals.SignalReceiver;
import mods.railcraft.api.signals.SignalTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import dan200.computer.api.IComputerAccess;
import dan200.computer.api.IPeripheral;
public class TileSignalController extends Tile implements IControllerTile, IReceiverTile, IPeripheral {
private static final String NAME = "Electronic Signal Controller";
private static final SignalAspect[] ASPECTS = SignalAspect.values();
private MultiSignalReceiver receiver = new MultiSignalReceiver(NAME, this, 256);
private MultiSignalController controller = new MultiSignalController(NAME, this, 256);
private final Map<IComputerAccess, Boolean> computers = new WeakHashMap<IComputerAccess, Boolean>();
@Override
public World getWorld() {
return worldObj;
}
@Override
public SignalReceiver getReceiver() {
return receiver;
}
@Override
public void onControllerAspectChange(SignalController con, SignalAspect aspect) {
for (IComputerAccess computer : computers.keySet()) {
WorldCoordinate coords = con.getCoords();
computer.queueEvent("signal", new Object[] {coords.dimension, coords.x, coords.y, coords.z, aspectToString(aspect)});
}
}
@Override
public SignalController getController() {
return controller;
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
receiver.readFromNBT(compound);
controller.readFromNBT(compound);
}
@Override
public void writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
receiver.writeToNBT(compound);
controller.writeToNBT(compound);
}
@Override
public String getType() {
return "signalController";
}
@Override
public String[] getMethodNames() {
return new String[] {"get", "set"};
}
@Override
public Object[] callMethod(IComputerAccess computer, int method, final Object[] arguments) throws Exception {
switch (method) {
case 0: {
if (arguments.length > 0 && arguments.length < 3) throw new Exception("too few arguments");
else if (!(arguments[0] instanceof Double)) throw new Exception("bad argument #1 (expected number)");
else if (arguments.length > 1 && !(arguments[1] instanceof Double)) throw new Exception("bad argument #2 (expected number)");
else if (arguments.length > 2 && !(arguments[2] instanceof Double)) throw new Exception("bad argument #3 (expected number)");
else if (arguments.length > 3 && !(arguments[3] instanceof Double)) throw new Exception("bad argument #4 (expected number)");
Future<SignalAspect> callback = TickHandler.addTickCallback(worldObj, new Callable<SignalAspect>() {
@Override
public SignalAspect call() {
if (arguments.length > 1) {
int x = (int)Math.floor((Double)arguments[0]);
int y = (int)Math.floor((Double)arguments[1]);
int z = (int)Math.floor((Double)arguments[2]);
int dim = arguments.length > 3 ? (int)Math.floor((Double)arguments[3]) : worldObj.provider.dimensionId;
return receiver.getAspectFor(new WorldCoordinate(dim, x, y, z));
} else {
return receiver.getDefaultAspect();
}
}
});
SignalAspect aspect = callback.get();
return new Object[] {aspect == null ? null : aspectToString(aspect)};
}
case 1: {
if (arguments.length < 1 || (arguments.length > 1 && arguments.length < 4)) throw new Exception("too few arguments");
else if (!(arguments[0] instanceof String)) throw new Exception("bad argument #1 (expected string)");
else if (arguments.length > 1 && !(arguments[1] instanceof Double)) throw new Exception("bad argument #2 (expected number)");
else if (arguments.length > 2 && !(arguments[2] instanceof Double)) throw new Exception("bad argument #3 (expected number)");
else if (arguments.length > 3 && !(arguments[3] instanceof Double)) throw new Exception("bad argument #4 (expected number)");
else if (arguments.length > 4 && !(arguments[4] instanceof Double)) throw new Exception("bad argument #5 (expected number)");
Future<String> callback = TickHandler.addTickCallback(worldObj, new Callable<String>() {
@Override
public String call() {
String aspectName = (String)arguments[0];
SignalAspect aspect = getAspect(aspectName);
if (arguments.length > 1) {
int x = (int)Math.floor((Double)arguments[1]);
int y = (int)Math.floor((Double)arguments[2]);
int z = (int)Math.floor((Double)arguments[3]);
int dim = arguments.length > 4 ? (int)Math.floor((Double)arguments[4]) : worldObj.provider.dimensionId;
if (!controller.setAspectFor(new WorldCoordinate(dim, x, y, z), aspect)) return null;
} else {
controller.setDefaultAspect(aspect);
}
return aspectToString(aspect);
}
});
return new Object[] {callback.get()};
}
}
return new Object[0];
}
@Override
public boolean canAttachToSide(int side) {
return true;
}
@Override
public void attach(IComputerAccess computer) {
computers.put(computer, true);
}
@Override
public void detach(IComputerAccess computer) {
computers.remove(computer);
}
@Override
public boolean canUpdate() {
return true;
}
@Override
public void updateEntity() {
super.updateEntity();
Side side = FMLCommonHandler.instance().getEffectiveSide();
if (side.isServer()) {
receiver.tickServer();
controller.tickServer();
} else if (side.isClient()) {
receiver.tickClient();
controller.tickClient();
}
}
private SignalAspect getAspect(String name) {
for (SignalAspect aspect : ASPECTS) {
if (name.equalsIgnoreCase(aspectToString(aspect))) return aspect;
}
return SignalAspect.BLINK_RED;
}
private String aspectToString(SignalAspect aspect) {
return Util.camelCase(aspect.name().replaceAll("_", " "));
}
private WorldCoordinate getWorldCoordinate() {
return new WorldCoordinate(worldObj.provider.dimensionId, xCoord, yCoord, zCoord);
}
private class MultiSignalController extends SignalController {
private Map<WorldCoordinate, SignalAspect> aspects = new HashMap<WorldCoordinate, SignalAspect>();
public MultiSignalController(String name, TileEntity tile, int maxPairings) {
super(name, tile, maxPairings);
}
@Override
public void loadNBT(NBTTagCompound compound) {
NBTTagList aspects = compound.getTagList("aspects");
for (int i = 0; i < aspects.tagCount(); i++) {
NBTTagCompound aspect = (NBTTagCompound)aspects.tagAt(i);
int[] coords = aspect.getIntArray("coords");
this.aspects.put(new WorldCoordinate(coords[0], coords[1], coords[2], coords[3]), SignalAspect.values()[aspect.getByte("aspect")]);
}
}
@Override
public void saveNBT(NBTTagCompound compound) {
NBTTagList aspects = new NBTTagList();
for (Entry<WorldCoordinate, SignalAspect> entry : this.aspects.entrySet()) {
NBTTagCompound aspect = new NBTTagCompound();
WorldCoordinate coords = entry.getKey();
aspect.setIntArray("coords", new int[] {coords.dimension, coords.x, coords.y, coords.z});
aspect.setByte("aspect", (byte)entry.getValue().ordinal());
aspects.appendTag(aspect);
}
compound.setTag("aspects", aspects);
}
@Override
public SignalAspect getAspectFor(WorldCoordinate receiver) {
return aspects.get(receiver);
}
@Override
public void clearPairing(WorldCoordinate other) {
super.clearPairing(other);
aspects.remove(other);
for (IComputerAccess computer : computers.keySet()) {
computer.queueEvent("signal_receiver_remove", new Object[] {other.dimension, other.x, other.y, other.z});
}
}
@Override
public void addPairing(WorldCoordinate other) {
// modified super code
pairings.add(other);
while (pairings.size() > getMaxPairings()) {
WorldCoordinate coord = pairings.remove();
for (IComputerAccess computer : computers.keySet()) {
computer.queueEvent("signal_receiver_remove", new Object[] {coord.dimension, coord.x, coord.y, coord.z});
}
}
SignalTools.packetBuilder.sendPairPacketUpdate(this);
aspects.put(other, SignalAspect.BLINK_RED);
for (IComputerAccess computer : computers.keySet()) {
computer.queueEvent("signal_receiver_add", new Object[] {other.dimension, other.x, other.y, other.z});
}
}
public boolean setAspectFor(WorldCoordinate receiver, SignalAspect aspect) {
if (!pairings.contains(receiver)) return false;
if (sendAspectTo(receiver, aspect)) {
aspects.put(receiver, aspect);
return true;
} else return false;
}
public void setDefaultAspect(SignalAspect aspect) {
for (WorldCoordinate coord : getPairs()) {
setAspectFor(coord, aspect);
}
}
}
private class MultiSignalReceiver extends SignalReceiver {
private Map<WorldCoordinate, SignalAspect> aspects = new HashMap<WorldCoordinate, SignalAspect>();
public MultiSignalReceiver(String name, TileEntity tile, int maxPairings) {
super(name, tile, maxPairings);
}
@Override
public void loadNBT(NBTTagCompound compound) {
super.loadNBT(compound);
NBTTagList aspects = compound.getTagList("aspects");
for (int i = 0; i < aspects.tagCount(); i++) {
NBTTagCompound aspect = (NBTTagCompound)aspects.tagAt(i);
int[] coords = aspect.getIntArray("coords");
this.aspects.put(new WorldCoordinate(coords[0], coords[1], coords[2], coords[3]), SignalAspect.values()[aspect.getByte("aspect")]);
}
}
@Override
public void saveNBT(NBTTagCompound compound) {
super.saveNBT(compound);
NBTTagList aspects = new NBTTagList();
for (Entry<WorldCoordinate, SignalAspect> entry : this.aspects.entrySet()) {
NBTTagCompound aspect = new NBTTagCompound();
WorldCoordinate coords = entry.getKey();
aspect.setIntArray("coords", new int[] {coords.dimension, coords.x, coords.y, coords.z});
aspect.setByte("aspect", (byte)entry.getValue().ordinal());
aspects.appendTag(aspect);
}
compound.setTag("aspects", aspects);
}
@Override
public void onControllerAspectChange(SignalController con, SignalAspect aspect) {
super.onControllerAspectChange(con, aspect);
aspects.put(con.getCoords(), aspect);
}
public SignalAspect getAspectFor(WorldCoordinate coord) {
SignalController controller = getControllerAt(coord);
if (controller == null) return SignalAspect.BLINK_RED;
return controller.getAspectFor(getCoords());
}
public SignalAspect getDefaultAspect() {
SignalAspect ret = null;
for (WorldCoordinate coord : getPairs()) {
ret = SignalAspect.mostRestrictive(ret, getAspectFor(coord));
}
return ret;
}
}
}
|
gpl-2.0
|
uhef/fs-uae-gles
|
src/jit/compemu_support_codegen.cpp
|
156384
|
/*
* compiler/compemu_support.cpp - Core dynamic translation engine
*
* Original 68040 JIT compiler for UAE, copyright 2000-2002 Bernd Meyer
*
* Adaptation for Basilisk II and improvements, copyright 2000-2005
* Gwenole Beauchesne
*
* Basilisk II (C) 1997-2008 Christian Bauer
*
* 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
*/
#if 0
#if !REAL_ADDRESSING && !DIRECT_ADDRESSING
#error "Only Real or Direct Addressing is supported with the JIT Compiler"
#endif
#if X86_ASSEMBLY && !SAHF_SETO_PROFITABLE
#error "Only [LS]AHF scheme to [gs]et flags is supported with the JIT Compiler"
#endif
#endif
/* NOTE: support for AMD64 assumes translation cache and other code
* buffers are allocated into a 32-bit address space because (i) B2/JIT
* code is not 64-bit clean and (ii) it's faster to resolve branches
* that way.
*/
#if 0
#if !defined(__i386__) && !defined(__x86_64__)
#error "Only IA-32 and X86-64 targets are supported with the JIT Compiler"
#endif
#endif
#define USE_MATCH 0
/* kludge for Brian, so he can compile under MSVC++ */
#define USE_NORMAL_CALLING_CONVENTION 0
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#endif
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include "sysconfig.h"
#include "sysdeps.h"
#if 0
#include "cpu_emulation.h"
#include "main.h"
#include "prefs.h"
#include "user_strings.h"
#include "vm_alloc.h"
#endif
//#include "machdep/m68k.h"
#include "custom.h"
#include "uae/memory.h"
//#include "readcpu.h"
#include "newcpu.h"
#include "comptbl.h"
#include "jit/compemu_codegen.h"
#include "fpu/fpu.h"
#include "fpu/flags.h"
#define DEBUG 1
#include "debug.h"
#ifdef ENABLE_MON
#include "mon.h"
#endif
#ifndef WIN32
#define PROFILE_COMPILE_TIME 1
#define PROFILE_UNTRANSLATED_INSNS 1
#endif
#if defined(__x86_64__) && 0
#define RECORD_REGISTER_USAGE 1
#endif
#ifdef WIN32
#undef write_log
#define write_log dummy_write_log
static void dummy_write_log(const char *, ...) { }
#endif
#if JIT_DEBUG
#undef abort
#define abort() do { \
fprintf(stderr, "Abort in file %s at line %d\n", __FILE__, __LINE__); \
exit(EXIT_FAILURE); \
} while (0)
#endif
#if RECORD_REGISTER_USAGE
static uint64 reg_count[16];
static int reg_count_local[16];
static int reg_count_compare(const void *ap, const void *bp)
{
const int a = *((int *)ap);
const int b = *((int *)bp);
return reg_count[b] - reg_count[a];
}
#endif
#if PROFILE_COMPILE_TIME
#include <time.h>
static uae_u32 compile_count = 0;
static clock_t compile_time = 0;
static clock_t emul_start_time = 0;
static clock_t emul_end_time = 0;
#endif
#if PROFILE_UNTRANSLATED_INSNS
const int untranslated_top_ten = 20;
static uae_u32 raw_cputbl_count[65536] = { 0, };
static uae_u16 opcode_nums[65536];
static int untranslated_compfn(const void *e1, const void *e2)
{
return raw_cputbl_count[*(const uae_u16 *)e1] < raw_cputbl_count[*(const uae_u16 *)e2];
}
#endif
static compop_func *compfunctbl[65536];
static compop_func *nfcompfunctbl[65536];
static cpuop_func *nfcpufunctbl[65536];
uae_u8* comp_pc_p;
// From newcpu.cpp
extern bool quit_program;
// gb-- Extra data for Basilisk II/JIT
#if JIT_DEBUG
static bool JITDebug = false; // Enable runtime disassemblers through mon?
#else
const bool JITDebug = false; // Don't use JIT debug mode at all
#endif
#if USE_INLINING
static bool follow_const_jumps = true; // Flag: translation through constant jumps
#else
const bool follow_const_jumps = false;
#endif
const uae_u32 MIN_CACHE_SIZE = 1024; // Minimal translation cache size (1 MB)
static uae_u32 cache_size = 0; // Size of total cache allocated for compiled blocks
static uae_u32 current_cache_size = 0; // Cache grows upwards: how much has been consumed already
static bool lazy_flush = true; // Flag: lazy translation cache invalidation
static bool avoid_fpu = true; // Flag: compile FPU instructions ?
static bool have_cmov = false; // target has CMOV instructions ?
static bool have_lahf_lm = true; // target has LAHF supported in long mode ?
static bool have_rat_stall = true; // target has partial register stalls ?
const bool tune_alignment = true; // Tune code alignments for running CPU ?
const bool tune_nop_fillers = true; // Tune no-op fillers for architecture
static bool setzflg_uses_bsf = false; // setzflg virtual instruction can use native BSF instruction correctly?
static int align_loops = 32; // Align the start of loops
static int align_jumps = 32; // Align the start of jumps
static int optcount[10] = {
10, // How often a block has to be executed before it is translated
0, // How often to use naive translation
0, 0, 0, 0,
-1, -1, -1, -1
};
struct op_properties {
uae_u8 use_flags;
uae_u8 set_flags;
uae_u8 is_addx;
uae_u8 cflow;
};
static op_properties prop[65536];
static inline int end_block(uae_u32 opcode)
{
return (prop[opcode].cflow & fl_end_block);
}
static inline bool is_const_jump(uae_u32 opcode)
{
return (prop[opcode].cflow == fl_const_jump);
}
static inline bool may_trap(uae_u32 opcode)
{
return (prop[opcode].cflow & fl_trap);
}
static inline unsigned int cft_map (unsigned int f)
{
#ifndef HAVE_GET_WORD_UNSWAPPED
return f;
#else
return ((f >> 8) & 255) | ((f & 255) << 8);
#endif
}
uae_u8* start_pc_p;
uae_u32 start_pc;
uae_u32 current_block_pc_p;
static uintptr current_block_start_target;
uae_u32 needed_flags;
static uintptr next_pc_p;
static uintptr taken_pc_p;
static int branch_cc;
static int redo_current_block;
int segvcount=0;
int soft_flush_count=0;
int hard_flush_count=0;
int checksum_count=0;
static uae_u8* current_compile_p=NULL;
static uae_u8* max_compile_start;
static uae_u8* compiled_code=NULL;
static uae_s32 reg_alloc_run;
const int POPALLSPACE_SIZE = 1024; /* That should be enough space */
static uae_u8* popallspace=NULL;
void* pushall_call_handler=NULL;
static void* popall_do_nothing=NULL;
static void* popall_exec_nostats=NULL;
static void* popall_execute_normal=NULL;
static void* popall_cache_miss=NULL;
static void* popall_recompile_block=NULL;
static void* popall_check_checksum=NULL;
/* The 68k only ever executes from even addresses. So right now, we
* waste half the entries in this array
* UPDATE: We now use those entries to store the start of the linked
* lists that we maintain for each hash result.
*/
cacheline cache_tags[TAGSIZE];
int letit=0;
blockinfo* hold_bi[MAX_HOLD_BI];
blockinfo* active;
blockinfo* dormant;
/* 68040 */
extern struct cputbl op_smalltbl_0_nf[];
extern struct comptbl op_smalltbl_0_comp_nf[];
extern struct comptbl op_smalltbl_0_comp_ff[];
/* 68020 + 68881 */
extern struct cputbl op_smalltbl_1_nf[];
/* 68020 */
extern struct cputbl op_smalltbl_2_nf[];
/* 68010 */
extern struct cputbl op_smalltbl_3_nf[];
/* 68000 */
extern struct cputbl op_smalltbl_4_nf[];
/* 68000 slow but compatible. */
extern struct cputbl op_smalltbl_5_nf[];
static void flush_icache_hard(int n);
static void flush_icache_lazy(int n);
static void flush_icache_none(int n);
void (*flush_icache)(int n) = flush_icache_none;
bigstate live;
smallstate empty_ss;
smallstate default_ss;
static int optlev;
static int writereg(int r, int size);
static void unlock2(int r);
static void setlock(int r);
static int readreg_specific(int r, int size, int spec);
static int writereg_specific(int r, int size, int spec);
static void prepare_for_call_1(void);
static void prepare_for_call_2(void);
static void align_target(uae_u32 a);
static uae_s32 nextused[VREGS];
uae_u32 m68k_pc_offset;
/* Some arithmetic ooperations can be optimized away if the operands
* are known to be constant. But that's only a good idea when the
* side effects they would have on the flags are not important. This
* variable indicates whether we need the side effects or not
*/
uae_u32 needflags=0;
/* Flag handling is complicated.
*
* x86 instructions create flags, which quite often are exactly what we
* want. So at times, the "68k" flags are actually in the x86 flags.
*
* Then again, sometimes we do x86 instructions that clobber the x86
* flags, but don't represent a corresponding m68k instruction. In that
* case, we have to save them.
*
* We used to save them to the stack, but now store them back directly
* into the regflags.cznv of the traditional emulation. Thus some odd
* names.
*
* So flags can be in either of two places (used to be three; boy were
* things complicated back then!); And either place can contain either
* valid flags or invalid trash (and on the stack, there was also the
* option of "nothing at all", now gone). A couple of variables keep
* track of the respective states.
*
* To make things worse, we might or might not be interested in the flags.
* by default, we are, but a call to dont_care_flags can change that
* until the next call to live_flags. If we are not, pretty much whatever
* is in the register and/or the native flags is seen as valid.
*/
static __inline__ blockinfo* get_blockinfo(uae_u32 cl)
{
return cache_tags[cl+1].bi;
}
static __inline__ blockinfo* get_blockinfo_addr(void* addr)
{
blockinfo* bi=get_blockinfo(cacheline(addr));
while (bi) {
if (bi->pc_p==addr)
return bi;
bi=bi->next_same_cl;
}
return NULL;
}
/*******************************************************************
* All sorts of list related functions for all of the lists *
*******************************************************************/
static __inline__ void remove_from_cl_list(blockinfo* bi)
{
uae_u32 cl=cacheline(bi->pc_p);
if (bi->prev_same_cl_p)
*(bi->prev_same_cl_p)=bi->next_same_cl;
if (bi->next_same_cl)
bi->next_same_cl->prev_same_cl_p=bi->prev_same_cl_p;
if (cache_tags[cl+1].bi)
cache_tags[cl].handler=cache_tags[cl+1].bi->handler_to_use;
else
cache_tags[cl].handler=(cpuop_func *)popall_execute_normal;
}
static __inline__ void remove_from_list(blockinfo* bi)
{
if (bi->prev_p)
*(bi->prev_p)=bi->next;
if (bi->next)
bi->next->prev_p=bi->prev_p;
}
static __inline__ void remove_from_lists(blockinfo* bi)
{
remove_from_list(bi);
remove_from_cl_list(bi);
}
static __inline__ void add_to_cl_list(blockinfo* bi)
{
uae_u32 cl=cacheline(bi->pc_p);
if (cache_tags[cl+1].bi)
cache_tags[cl+1].bi->prev_same_cl_p=&(bi->next_same_cl);
bi->next_same_cl=cache_tags[cl+1].bi;
cache_tags[cl+1].bi=bi;
bi->prev_same_cl_p=&(cache_tags[cl+1].bi);
cache_tags[cl].handler=bi->handler_to_use;
}
static __inline__ void raise_in_cl_list(blockinfo* bi)
{
remove_from_cl_list(bi);
add_to_cl_list(bi);
}
static __inline__ void add_to_active(blockinfo* bi)
{
if (active)
active->prev_p=&(bi->next);
bi->next=active;
active=bi;
bi->prev_p=&active;
}
static __inline__ void add_to_dormant(blockinfo* bi)
{
if (dormant)
dormant->prev_p=&(bi->next);
bi->next=dormant;
dormant=bi;
bi->prev_p=&dormant;
}
static __inline__ void remove_dep(dependency* d)
{
if (d->prev_p)
*(d->prev_p)=d->next;
if (d->next)
d->next->prev_p=d->prev_p;
d->prev_p=NULL;
d->next=NULL;
}
/* This block's code is about to be thrown away, so it no longer
depends on anything else */
static __inline__ void remove_deps(blockinfo* bi)
{
remove_dep(&(bi->dep[0]));
remove_dep(&(bi->dep[1]));
}
static __inline__ void adjust_jmpdep(dependency* d, cpuop_func* a)
{
*(d->jmp_off)=(uintptr)a-((uintptr)d->jmp_off+4);
}
/********************************************************************
* Soft flush handling support functions *
********************************************************************/
static __inline__ void set_dhtu(blockinfo* bi, cpuop_func* dh)
{
//write_log("bi is %p\n",bi);
if (dh!=bi->direct_handler_to_use) {
dependency* x=bi->deplist;
//write_log("bi->deplist=%p\n",bi->deplist);
while (x) {
//write_log("x is %p\n",x);
//write_log("x->next is %p\n",x->next);
//write_log("x->prev_p is %p\n",x->prev_p);
if (x->jmp_off) {
adjust_jmpdep(x,dh);
}
x=x->next;
}
bi->direct_handler_to_use=dh;
}
}
static __inline__ void invalidate_block(blockinfo* bi)
{
int i;
bi->optlevel=0;
bi->count=optcount[0]-1;
bi->handler=NULL;
bi->handler_to_use=(cpuop_func *)popall_execute_normal;
bi->direct_handler=NULL;
set_dhtu(bi,bi->direct_pen);
bi->needed_flags=0xff;
bi->status=BI_INVALID;
for (i=0;i<2;i++) {
bi->dep[i].jmp_off=NULL;
bi->dep[i].target=NULL;
}
remove_deps(bi);
}
static __inline__ void create_jmpdep(blockinfo* bi, int i, uae_u32* jmpaddr, uae_u32 target)
{
blockinfo* tbi=get_blockinfo_addr((void*)(uintptr)target);
Dif(!tbi) {
write_log("Could not create jmpdep!\n");
abort();
}
bi->dep[i].jmp_off=jmpaddr;
bi->dep[i].source=bi;
bi->dep[i].target=tbi;
bi->dep[i].next=tbi->deplist;
if (bi->dep[i].next)
bi->dep[i].next->prev_p=&(bi->dep[i].next);
bi->dep[i].prev_p=&(tbi->deplist);
tbi->deplist=&(bi->dep[i]);
}
static __inline__ void block_need_recompile(blockinfo * bi)
{
uae_u32 cl = cacheline(bi->pc_p);
set_dhtu(bi, bi->direct_pen);
bi->direct_handler = bi->direct_pen;
bi->handler_to_use = (cpuop_func *)popall_execute_normal;
bi->handler = (cpuop_func *)popall_execute_normal;
if (bi == cache_tags[cl + 1].bi)
cache_tags[cl].handler = (cpuop_func *)popall_execute_normal;
bi->status = BI_NEED_RECOMP;
}
static __inline__ void mark_callers_recompile(blockinfo * bi)
{
dependency *x = bi->deplist;
while (x) {
dependency *next = x->next; /* This disappears when we mark for
* recompilation and thus remove the
* blocks from the lists */
if (x->jmp_off) {
blockinfo *cbi = x->source;
Dif(cbi->status == BI_INVALID) {
// write_log("invalid block in dependency list\n"); // FIXME?
// abort();
}
if (cbi->status == BI_ACTIVE || cbi->status == BI_NEED_CHECK) {
block_need_recompile(cbi);
mark_callers_recompile(cbi);
}
else if (cbi->status == BI_COMPILING) {
redo_current_block = 1;
}
else if (cbi->status == BI_NEED_RECOMP) {
/* nothing */
}
else {
//write_log("Status %d in mark_callers\n",cbi->status); // FIXME?
}
}
x = next;
}
}
static __inline__ blockinfo* get_blockinfo_addr_new(void* addr, int setstate)
{
blockinfo* bi=get_blockinfo_addr(addr);
int i;
if (!bi) {
for (i=0;i<MAX_HOLD_BI && !bi;i++) {
if (hold_bi[i]) {
uae_u32 cl=cacheline(addr);
bi=hold_bi[i];
hold_bi[i]=NULL;
bi->pc_p=(uae_u8 *)addr;
invalidate_block(bi);
add_to_active(bi);
add_to_cl_list(bi);
}
}
}
if (!bi) {
write_log("Looking for blockinfo, can't find free one\n");
abort();
}
return bi;
}
static void prepare_block(blockinfo* bi);
/* Managment of blockinfos.
A blockinfo struct is allocated whenever a new block has to be
compiled. If the list of free blockinfos is empty, we allocate a new
pool of blockinfos and link the newly created blockinfos altogether
into the list of free blockinfos. Otherwise, we simply pop a structure
off the free list.
Blockinfo are lazily deallocated, i.e. chained altogether in the
list of free blockinfos whenvever a translation cache flush (hard or
soft) request occurs.
*/
template< class T >
class LazyBlockAllocator
{
enum {
kPoolSize = 1 + 4096 / sizeof(T)
};
struct Pool {
T chunk[kPoolSize];
Pool * next;
};
Pool * mPools;
T * mChunks;
public:
LazyBlockAllocator() : mPools(0), mChunks(0) { }
~LazyBlockAllocator();
T * acquire();
void release(T * const);
};
template< class T >
LazyBlockAllocator<T>::~LazyBlockAllocator()
{
Pool * currentPool = mPools;
while (currentPool) {
Pool * deadPool = currentPool;
currentPool = currentPool->next;
free(deadPool);
}
}
template< class T >
T * LazyBlockAllocator<T>::acquire()
{
if (!mChunks) {
// There is no chunk left, allocate a new pool and link the
// chunks into the free list
Pool * newPool = (Pool *)malloc(sizeof(Pool));
for (T * chunk = &newPool->chunk[0]; chunk < &newPool->chunk[kPoolSize]; chunk++) {
chunk->next = mChunks;
mChunks = chunk;
}
newPool->next = mPools;
mPools = newPool;
}
T * chunk = mChunks;
mChunks = chunk->next;
return chunk;
}
template< class T >
void LazyBlockAllocator<T>::release(T * const chunk)
{
chunk->next = mChunks;
mChunks = chunk;
}
template< class T >
class HardBlockAllocator
{
public:
T * acquire() {
T * data = (T *)current_compile_p;
current_compile_p += sizeof(T);
return data;
}
void release(T * const chunk) {
// Deallocated on invalidation
}
};
#if USE_SEPARATE_BIA
static LazyBlockAllocator<blockinfo> BlockInfoAllocator;
static LazyBlockAllocator<checksum_info> ChecksumInfoAllocator;
#else
static HardBlockAllocator<blockinfo> BlockInfoAllocator;
static HardBlockAllocator<checksum_info> ChecksumInfoAllocator;
#endif
static __inline__ checksum_info *alloc_checksum_info(void)
{
checksum_info *csi = ChecksumInfoAllocator.acquire();
csi->next = NULL;
return csi;
}
static __inline__ void free_checksum_info(checksum_info *csi)
{
csi->next = NULL;
ChecksumInfoAllocator.release(csi);
}
static __inline__ void free_checksum_info_chain(checksum_info *csi)
{
while (csi != NULL) {
checksum_info *csi2 = csi->next;
free_checksum_info(csi);
csi = csi2;
}
}
static __inline__ blockinfo *alloc_blockinfo(void)
{
blockinfo *bi = BlockInfoAllocator.acquire();
#if USE_CHECKSUM_INFO
bi->csi = NULL;
#endif
return bi;
}
static __inline__ void free_blockinfo(blockinfo *bi)
{
#if USE_CHECKSUM_INFO
free_checksum_info_chain(bi->csi);
bi->csi = NULL;
#endif
BlockInfoAllocator.release(bi);
}
static __inline__ void alloc_blockinfos(void)
{
int i;
blockinfo* bi;
for (i=0;i<MAX_HOLD_BI;i++) {
if (hold_bi[i])
return;
bi=hold_bi[i]=alloc_blockinfo();
prepare_block(bi);
}
}
/********************************************************************
* Functions to emit data into memory, and other general support *
********************************************************************/
static uae_u8* target;
static void emit_init(void)
{
}
static __inline__ void emit_byte(uae_u8 x)
{
*target++=x;
}
static __inline__ void emit_word(uae_u16 x)
{
*((uae_u16*)target)=x;
target+=2;
}
static __inline__ void emit_long(uae_u32 x)
{
*((uae_u32*)target)=x;
target+=4;
}
static __inline__ void emit_quad(uae_u64 x)
{
*((uae_u64*)target)=x;
target+=8;
}
static __inline__ void emit_block(const uae_u8 *block, uae_u32 blocklen)
{
memcpy((uae_u8 *)target,block,blocklen);
target+=blocklen;
}
static __inline__ uae_u32 reverse32(uae_u32 v)
{
#if 1
// gb-- We have specialized byteswapping functions, just use them
return do_byteswap_32(v);
#else
return ((v>>24)&0xff) | ((v>>8)&0xff00) | ((v<<8)&0xff0000) | ((v<<24)&0xff000000);
#endif
}
/********************************************************************
* Getting the information about the target CPU *
********************************************************************/
#include "codegen_x86.cpp"
void set_target(uae_u8* t)
{
target=t;
}
static __inline__ uae_u8* get_target_noopt(void)
{
return target;
}
__inline__ uae_u8* get_target(void)
{
return get_target_noopt();
}
/********************************************************************
* Flags status handling. EMIT TIME! *
********************************************************************/
static void bt_l_ri_noclobber(R4 r, IMM i);
static void make_flags_live_internal(void)
{
if (live.flags_in_flags==VALID)
return;
Dif (live.flags_on_stack==TRASH) {
write_log("Want flags, got something on stack, but it is TRASH\n");
abort();
}
if (live.flags_on_stack==VALID) {
int tmp;
tmp=readreg_specific(FLAGTMP,4,FLAG_NREG2);
raw_reg_to_flags(tmp);
unlock2(tmp);
live.flags_in_flags=VALID;
return;
}
write_log("Huh? live.flags_in_flags=%d, live.flags_on_stack=%d, but need to make live\n",
live.flags_in_flags,live.flags_on_stack);
abort();
}
static void flags_to_stack(void)
{
if (live.flags_on_stack==VALID)
return;
if (!live.flags_are_important) {
live.flags_on_stack=VALID;
return;
}
Dif (live.flags_in_flags!=VALID)
abort();
else {
int tmp;
tmp=writereg_specific(FLAGTMP,4,FLAG_NREG1);
raw_flags_to_reg(tmp);
unlock2(tmp);
}
live.flags_on_stack=VALID;
}
static __inline__ void clobber_flags(void)
{
if (live.flags_in_flags==VALID && live.flags_on_stack!=VALID)
flags_to_stack();
live.flags_in_flags=TRASH;
}
/* Prepare for leaving the compiled stuff */
static __inline__ void flush_flags(void)
{
flags_to_stack();
return;
}
int touchcnt;
/********************************************************************
* Partial register flushing for optimized calls *
********************************************************************/
struct regusage {
uae_u16 rmask;
uae_u16 wmask;
};
static inline void ru_set(uae_u16 *mask, int reg)
{
#if USE_OPTIMIZED_CALLS
*mask |= 1 << reg;
#endif
}
static inline bool ru_get(const uae_u16 *mask, int reg)
{
#if USE_OPTIMIZED_CALLS
return (*mask & (1 << reg));
#else
/* Default: instruction reads & write to register */
return true;
#endif
}
static inline void ru_set_read(regusage *ru, int reg)
{
ru_set(&ru->rmask, reg);
}
static inline void ru_set_write(regusage *ru, int reg)
{
ru_set(&ru->wmask, reg);
}
static inline bool ru_read_p(const regusage *ru, int reg)
{
return ru_get(&ru->rmask, reg);
}
static inline bool ru_write_p(const regusage *ru, int reg)
{
return ru_get(&ru->wmask, reg);
}
static void ru_fill_ea(regusage *ru, int reg, amodes mode,
wordsizes size, int write_mode)
{
switch (mode) {
case Areg:
reg += 8;
/* fall through */
case Dreg:
ru_set(write_mode ? &ru->wmask : &ru->rmask, reg);
break;
case Ad16:
/* skip displacment */
m68k_pc_offset += 2;
case Aind:
case Aipi:
case Apdi:
ru_set_read(ru, reg+8);
break;
case Ad8r:
ru_set_read(ru, reg+8);
/* fall through */
case PC8r: {
uae_u16 dp = comp_get_iword((m68k_pc_offset+=2)-2);
reg = (dp >> 12) & 15;
ru_set_read(ru, reg);
if (dp & 0x100)
m68k_pc_offset += (((dp & 0x30) >> 3) & 7) + ((dp & 3) * 2);
break;
}
case PC16:
case absw:
case imm0:
case imm1:
m68k_pc_offset += 2;
break;
case absl:
case imm2:
m68k_pc_offset += 4;
break;
case immi:
m68k_pc_offset += (size == sz_long) ? 4 : 2;
break;
}
}
/* TODO: split into a static initialization part and a dynamic one
(instructions depending on extension words) */
static void ru_fill(regusage *ru, uae_u32 opcode)
{
m68k_pc_offset += 2;
/* Default: no register is used or written to */
ru->rmask = 0;
ru->wmask = 0;
uae_u32 real_opcode = cft_map(opcode);
struct instr *dp = &table68k[real_opcode];
bool rw_dest = true;
bool handled = false;
/* Handle some instructions specifically */
uae_u16 reg, ext;
switch (dp->mnemo) {
case i_BFCHG:
case i_BFCLR:
case i_BFEXTS:
case i_BFEXTU:
case i_BFFFO:
case i_BFINS:
case i_BFSET:
case i_BFTST:
ext = comp_get_iword((m68k_pc_offset+=2)-2);
if (ext & 0x800) ru_set_read(ru, (ext >> 6) & 7);
if (ext & 0x020) ru_set_read(ru, ext & 7);
ru_fill_ea(ru, dp->dreg, (amodes)dp->dmode, (wordsizes)dp->size, 1);
if (dp->dmode == Dreg)
ru_set_read(ru, dp->dreg);
switch (dp->mnemo) {
case i_BFEXTS:
case i_BFEXTU:
case i_BFFFO:
ru_set_write(ru, (ext >> 12) & 7);
break;
case i_BFINS:
ru_set_read(ru, (ext >> 12) & 7);
/* fall through */
case i_BFCHG:
case i_BFCLR:
case i_BSET:
if (dp->dmode == Dreg)
ru_set_write(ru, dp->dreg);
break;
}
handled = true;
rw_dest = false;
break;
case i_BTST:
rw_dest = false;
break;
case i_CAS:
{
ext = comp_get_iword((m68k_pc_offset+=2)-2);
int Du = ext & 7;
ru_set_read(ru, Du);
int Dc = (ext >> 6) & 7;
ru_set_read(ru, Dc);
ru_set_write(ru, Dc);
break;
}
case i_CAS2:
{
int Dc1, Dc2, Du1, Du2, Rn1, Rn2;
ext = comp_get_iword((m68k_pc_offset+=2)-2);
Rn1 = (ext >> 12) & 15;
Du1 = (ext >> 6) & 7;
Dc1 = ext & 7;
ru_set_read(ru, Rn1);
ru_set_read(ru, Du1);
ru_set_read(ru, Dc1);
ru_set_write(ru, Dc1);
ext = comp_get_iword((m68k_pc_offset+=2)-2);
Rn2 = (ext >> 12) & 15;
Du2 = (ext >> 6) & 7;
Dc2 = ext & 7;
ru_set_read(ru, Rn2);
ru_set_read(ru, Du2);
ru_set_write(ru, Dc2);
break;
}
case i_DIVL: case i_MULL:
m68k_pc_offset += 2;
break;
case i_LEA:
case i_MOVE: case i_MOVEA: case i_MOVE16:
rw_dest = false;
break;
case i_PACK: case i_UNPK:
rw_dest = false;
m68k_pc_offset += 2;
break;
case i_TRAPcc:
m68k_pc_offset += (dp->size == sz_long) ? 4 : 2;
break;
case i_RTR:
/* do nothing, just for coverage debugging */
break;
/* TODO: handle EXG instruction */
}
/* Handle A-Traps better */
if ((real_opcode & 0xf000) == 0xa000) {
handled = true;
}
/* Handle EmulOps better */
if ((real_opcode & 0xff00) == 0x7100) {
handled = true;
ru->rmask = 0xffff;
ru->wmask = 0;
}
if (dp->suse && !handled)
ru_fill_ea(ru, dp->sreg, (amodes)dp->smode, (wordsizes)dp->size, 0);
if (dp->duse && !handled)
ru_fill_ea(ru, dp->dreg, (amodes)dp->dmode, (wordsizes)dp->size, 1);
if (rw_dest)
ru->rmask |= ru->wmask;
handled = handled || dp->suse || dp->duse;
/* Mark all registers as used/written if the instruction may trap */
if (may_trap(opcode)) {
handled = true;
ru->rmask = 0xffff;
ru->wmask = 0xffff;
}
if (!handled) {
write_log("ru_fill: %04x = { %04x, %04x }\n",
real_opcode, ru->rmask, ru->wmask);
abort();
}
}
/********************************************************************
* register allocation per block logging *
********************************************************************/
static uae_s8 vstate[VREGS];
static uae_s8 vwritten[VREGS];
static uae_s8 nstate[N_REGS];
#define L_UNKNOWN -127
#define L_UNAVAIL -1
#define L_NEEDED -2
#define L_UNNEEDED -3
static __inline__ void big_to_small_state(bigstate * b, smallstate * s)
{
int i;
for (i = 0; i < VREGS; i++)
s->virt[i] = vstate[i];
for (i = 0; i < N_REGS; i++)
s->nat[i] = nstate[i];
}
static __inline__ int callers_need_recompile(bigstate * b, smallstate * s)
{
int i;
int reverse = 0;
for (i = 0; i < VREGS; i++) {
if (vstate[i] != L_UNNEEDED && s->virt[i] == L_UNNEEDED)
return 1;
if (vstate[i] == L_UNNEEDED && s->virt[i] != L_UNNEEDED)
reverse++;
}
for (i = 0; i < N_REGS; i++) {
if (nstate[i] >= 0 && nstate[i] != s->nat[i])
return 1;
if (nstate[i] < 0 && s->nat[i] >= 0)
reverse++;
}
if (reverse >= 2 && USE_MATCH)
return 1; /* In this case, it might be worth recompiling the
* callers */
return 0;
}
static __inline__ void log_startblock(void)
{
int i;
for (i = 0; i < VREGS; i++) {
vstate[i] = L_UNKNOWN;
vwritten[i] = 0;
}
for (i = 0; i < N_REGS; i++)
nstate[i] = L_UNKNOWN;
}
/* Using an n-reg for a temp variable */
static __inline__ void log_isused(int n)
{
if (nstate[n] == L_UNKNOWN)
nstate[n] = L_UNAVAIL;
}
static __inline__ void log_visused(int r)
{
if (vstate[r] == L_UNKNOWN)
vstate[r] = L_NEEDED;
}
static __inline__ void do_load_reg(int n, int r)
{
if (r == FLAGTMP)
raw_load_flagreg(n, r);
else if (r == FLAGX)
raw_load_flagx(n, r);
else
raw_mov_l_rm(n, (uintptr) live.state[r].mem);
}
static __inline__ void check_load_reg(int n, int r)
{
raw_mov_l_rm(n, (uintptr) live.state[r].mem);
}
static __inline__ void log_vwrite(int r)
{
vwritten[r] = 1;
}
/* Using an n-reg to hold a v-reg */
static __inline__ void log_isreg(int n, int r)
{
static int count = 0;
if (nstate[n] == L_UNKNOWN && r < 16 && !vwritten[r] && USE_MATCH)
nstate[n] = r;
else {
do_load_reg(n, r);
if (nstate[n] == L_UNKNOWN)
nstate[n] = L_UNAVAIL;
}
if (vstate[r] == L_UNKNOWN)
vstate[r] = L_NEEDED;
}
static __inline__ void log_clobberreg(int r)
{
if (vstate[r] == L_UNKNOWN)
vstate[r] = L_UNNEEDED;
}
/* This ends all possibility of clever register allocation */
static __inline__ void log_flush(void)
{
int i;
for (i = 0; i < VREGS; i++)
if (vstate[i] == L_UNKNOWN)
vstate[i] = L_NEEDED;
for (i = 0; i < N_REGS; i++)
if (nstate[i] == L_UNKNOWN)
nstate[i] = L_UNAVAIL;
}
static __inline__ void log_dump(void)
{
int i;
return;
write_log("----------------------\n");
for (i = 0; i < N_REGS; i++) {
switch (nstate[i]) {
case L_UNKNOWN:
write_log("Nat %d : UNKNOWN\n", i);
break;
case L_UNAVAIL:
write_log("Nat %d : UNAVAIL\n", i);
break;
default:
write_log("Nat %d : %d\n", i, nstate[i]);
break;
}
}
for (i = 0; i < VREGS; i++) {
if (vstate[i] == L_UNNEEDED)
write_log("Virt %d: UNNEEDED\n", i);
}
}
/********************************************************************
* register status handling. EMIT TIME! *
********************************************************************/
static __inline__ void set_status(int r, int status)
{
if (status == ISCONST)
log_clobberreg(r);
live.state[r].status=status;
}
static __inline__ int isinreg(int r)
{
return live.state[r].status==CLEAN || live.state[r].status==DIRTY;
}
static __inline__ void adjust_nreg(int r, uae_u32 val)
{
if (!val)
return;
raw_lea_l_brr(r,r,val);
}
static void tomem(int r)
{
int rr=live.state[r].realreg;
if (isinreg(r)) {
if (live.state[r].val && live.nat[rr].nholds==1
&& !live.nat[rr].locked) {
// write_log("RemovingA offset %x from reg %d (%d) at %p\n",
// live.state[r].val,r,rr,target);
adjust_nreg(rr,live.state[r].val);
live.state[r].val=0;
live.state[r].dirtysize=4;
set_status(r,DIRTY);
}
}
if (live.state[r].status==DIRTY) {
switch (live.state[r].dirtysize) {
case 1: raw_mov_b_mr((uintptr)live.state[r].mem,rr); break;
case 2: raw_mov_w_mr((uintptr)live.state[r].mem,rr); break;
case 4: raw_mov_l_mr((uintptr)live.state[r].mem,rr); break;
default: abort();
}
log_vwrite(r);
set_status(r,CLEAN);
live.state[r].dirtysize=0;
}
}
static __inline__ int isconst(int r)
{
return live.state[r].status==ISCONST;
}
int is_const(int r)
{
return isconst(r);
}
static __inline__ void writeback_const(int r)
{
if (!isconst(r))
return;
Dif (live.state[r].needflush==NF_HANDLER) {
write_log("Trying to write back constant NF_HANDLER!\n");
abort();
}
raw_mov_l_mi((uintptr)live.state[r].mem,live.state[r].val);
log_vwrite(r);
live.state[r].val=0;
set_status(r,INMEM);
}
static __inline__ void tomem_c(int r)
{
if (isconst(r)) {
writeback_const(r);
}
else
tomem(r);
}
static void evict(int r)
{
int rr;
if (!isinreg(r))
return;
tomem(r);
rr=live.state[r].realreg;
Dif (live.nat[rr].locked &&
live.nat[rr].nholds==1) {
write_log("register %d in nreg %d is locked!\n",r,live.state[r].realreg);
abort();
}
live.nat[rr].nholds--;
if (live.nat[rr].nholds!=live.state[r].realind) { /* Was not last */
int topreg=live.nat[rr].holds[live.nat[rr].nholds];
int thisind=live.state[r].realind;
live.nat[rr].holds[thisind]=topreg;
live.state[topreg].realind=thisind;
}
live.state[r].realreg=-1;
set_status(r,INMEM);
}
static __inline__ void free_nreg(int r)
{
int i=live.nat[r].nholds;
while (i) {
int vr;
--i;
vr=live.nat[r].holds[i];
evict(vr);
}
Dif (live.nat[r].nholds!=0) {
write_log("Failed to free nreg %d, nholds is %d\n",r,live.nat[r].nholds);
abort();
}
}
/* Use with care! */
static __inline__ void isclean(int r)
{
if (!isinreg(r))
return;
live.state[r].validsize=4;
live.state[r].dirtysize=0;
live.state[r].val=0;
set_status(r,CLEAN);
}
static __inline__ void disassociate(int r)
{
isclean(r);
evict(r);
}
static __inline__ void set_const(int r, uae_u32 val)
{
disassociate(r);
live.state[r].val=val;
set_status(r,ISCONST);
}
static __inline__ uae_u32 get_offset(int r)
{
return live.state[r].val;
}
static int alloc_reg_hinted(int r, int size, int willclobber, int hint)
{
int bestreg;
uae_s32 when;
int i;
uae_s32 badness=0; /* to shut up gcc */
bestreg=-1;
when=2000000000;
/* XXX use a regalloc_order table? */
for (i=0;i<N_REGS;i++) {
badness=live.nat[i].touched;
if (live.nat[i].nholds==0)
badness=0;
if (i==hint)
badness-=200000000;
if (!live.nat[i].locked && badness<when) {
if ((size==1 && live.nat[i].canbyte) ||
(size==2 && live.nat[i].canword) ||
(size==4)) {
bestreg=i;
when=badness;
if (live.nat[i].nholds==0 && hint<0)
break;
if (i==hint)
break;
}
}
}
Dif (bestreg==-1)
abort();
if (live.nat[bestreg].nholds>0) {
free_nreg(bestreg);
}
if (isinreg(r)) {
int rr=live.state[r].realreg;
/* This will happen if we read a partially dirty register at a
bigger size */
Dif (willclobber || live.state[r].validsize>=size)
abort();
Dif (live.nat[rr].nholds!=1)
abort();
if (size==4 && live.state[r].validsize==2) {
log_isused(bestreg);
log_visused(r);
raw_mov_l_rm(bestreg,(uintptr)live.state[r].mem);
raw_bswap_32(bestreg);
raw_zero_extend_16_rr(rr,rr);
raw_zero_extend_16_rr(bestreg,bestreg);
raw_bswap_32(bestreg);
raw_lea_l_brr_indexed(rr,rr,bestreg,1,0);
live.state[r].validsize=4;
live.nat[rr].touched=touchcnt++;
return rr;
}
if (live.state[r].validsize==1) {
/* Nothing yet */
}
evict(r);
}
if (!willclobber) {
if (live.state[r].status!=UNDEF) {
if (isconst(r)) {
raw_mov_l_ri(bestreg,live.state[r].val);
live.state[r].val=0;
live.state[r].dirtysize=4;
set_status(r,DIRTY);
log_isused(bestreg);
}
else {
log_isreg(bestreg, r); /* This will also load it! */
live.state[r].dirtysize=0;
set_status(r,CLEAN);
}
}
else {
live.state[r].val=0;
live.state[r].dirtysize=0;
set_status(r,CLEAN);
log_isused(bestreg);
}
live.state[r].validsize=4;
}
else { /* this is the easiest way, but not optimal. FIXME! */
/* Now it's trickier, but hopefully still OK */
if (!isconst(r) || size==4) {
live.state[r].validsize=size;
live.state[r].dirtysize=size;
live.state[r].val=0;
set_status(r,DIRTY);
if (size == 4) {
log_clobberreg(r);
log_isused(bestreg);
}
else {
log_visused(r);
log_isused(bestreg);
}
}
else {
if (live.state[r].status!=UNDEF)
raw_mov_l_ri(bestreg,live.state[r].val);
live.state[r].val=0;
live.state[r].validsize=4;
live.state[r].dirtysize=4;
set_status(r,DIRTY);
log_isused(bestreg);
}
}
live.state[r].realreg=bestreg;
live.state[r].realind=live.nat[bestreg].nholds;
live.nat[bestreg].touched=touchcnt++;
live.nat[bestreg].holds[live.nat[bestreg].nholds]=r;
live.nat[bestreg].nholds++;
return bestreg;
}
static int alloc_reg(int r, int size, int willclobber)
{
return alloc_reg_hinted(r,size,willclobber,-1);
}
static void unlock2(int r)
{
Dif (!live.nat[r].locked)
abort();
live.nat[r].locked--;
}
static void setlock(int r)
{
live.nat[r].locked++;
}
static void mov_nregs(int d, int s)
{
int ns=live.nat[s].nholds;
int nd=live.nat[d].nholds;
int i;
if (s==d)
return;
if (nd>0)
free_nreg(d);
log_isused(d);
raw_mov_l_rr(d,s);
for (i=0;i<live.nat[s].nholds;i++) {
int vs=live.nat[s].holds[i];
live.state[vs].realreg=d;
live.state[vs].realind=i;
live.nat[d].holds[i]=vs;
}
live.nat[d].nholds=live.nat[s].nholds;
live.nat[s].nholds=0;
}
static __inline__ void make_exclusive(int r, int size, int spec)
{
int clobber;
reg_status oldstate;
int rr=live.state[r].realreg;
int nr;
int nind;
int ndirt=0;
int i;
if (!isinreg(r))
return;
if (live.nat[rr].nholds==1)
return;
for (i=0;i<live.nat[rr].nholds;i++) {
int vr=live.nat[rr].holds[i];
if (vr!=r &&
(live.state[vr].status==DIRTY || live.state[vr].val))
ndirt++;
}
if (!ndirt && size<live.state[r].validsize && !live.nat[rr].locked) {
/* Everything else is clean, so let's keep this register */
for (i=0;i<live.nat[rr].nholds;i++) {
int vr=live.nat[rr].holds[i];
if (vr!=r) {
evict(vr);
i--; /* Try that index again! */
}
}
Dif (live.nat[rr].nholds!=1) {
write_log("natreg %d holds %d vregs, %d not exclusive\n",
rr,live.nat[rr].nholds,r);
abort();
}
return;
}
/* We have to split the register */
oldstate=live.state[r];
setlock(rr); /* Make sure this doesn't go away */
/* Forget about r being in the register rr */
disassociate(r);
/* Get a new register, that we will clobber completely */
if (oldstate.status==DIRTY) {
/* If dirtysize is <4, we need a register that can handle the
eventual smaller memory store! Thanks to Quake68k for exposing
this detail ;-) */
nr=alloc_reg_hinted(r,oldstate.dirtysize,1,spec);
}
else {
nr=alloc_reg_hinted(r,4,1,spec);
}
nind=live.state[r].realind;
live.state[r]=oldstate; /* Keep all the old state info */
live.state[r].realreg=nr;
live.state[r].realind=nind;
if (size<live.state[r].validsize) {
if (live.state[r].val) {
/* Might as well compensate for the offset now */
raw_lea_l_brr(nr,rr,oldstate.val);
live.state[r].val=0;
live.state[r].dirtysize=4;
set_status(r,DIRTY);
}
else
raw_mov_l_rr(nr,rr); /* Make another copy */
}
unlock2(rr);
}
static __inline__ void add_offset(int r, uae_u32 off)
{
live.state[r].val+=off;
}
static __inline__ void remove_offset(int r, int spec)
{
reg_status oldstate;
int rr;
if (isconst(r))
return;
if (live.state[r].val==0)
return;
if (isinreg(r) && live.state[r].validsize<4)
evict(r);
if (!isinreg(r))
alloc_reg_hinted(r,4,0,spec);
Dif (live.state[r].validsize!=4) {
write_log("Validsize=%d in remove_offset\n",live.state[r].validsize);
abort();
}
make_exclusive(r,0,-1);
/* make_exclusive might have done the job already */
if (live.state[r].val==0)
return;
rr=live.state[r].realreg;
if (live.nat[rr].nholds==1) {
//write_log("RemovingB offset %x from reg %d (%d) at %p\n",
// live.state[r].val,r,rr,target);
adjust_nreg(rr,live.state[r].val);
live.state[r].dirtysize=4;
live.state[r].val=0;
set_status(r,DIRTY);
return;
}
write_log("Failed in remove_offset\n");
abort();
}
static __inline__ void remove_all_offsets(void)
{
int i;
for (i=0;i<VREGS;i++)
remove_offset(i,-1);
}
static inline void flush_reg_count(void)
{
#if RECORD_REGISTER_USAGE
for (int r = 0; r < 16; r++)
if (reg_count_local[r])
ADDQim(reg_count_local[r], ((uintptr)reg_count) + (8 * r), X86_NOREG, X86_NOREG, 1);
#endif
}
static inline void record_register(int r)
{
#if RECORD_REGISTER_USAGE
if (r < 16)
reg_count_local[r]++;
#endif
}
static __inline__ int readreg_general(int r, int size, int spec, int can_offset)
{
int n;
int answer=-1;
record_register(r);
if (live.state[r].status==UNDEF) {
write_log("WARNING: Unexpected read of undefined register %d\n",r);
}
if (!can_offset)
remove_offset(r,spec);
if (isinreg(r) && live.state[r].validsize>=size) {
n=live.state[r].realreg;
switch(size) {
case 1:
if (live.nat[n].canbyte || spec>=0) {
answer=n;
}
break;
case 2:
if (live.nat[n].canword || spec>=0) {
answer=n;
}
break;
case 4:
answer=n;
break;
default: abort();
}
if (answer<0)
evict(r);
}
/* either the value was in memory to start with, or it was evicted and
is in memory now */
if (answer<0) {
answer=alloc_reg_hinted(r,spec>=0?4:size,0,spec);
}
if (spec>=0 && spec!=answer) {
/* Too bad */
mov_nregs(spec,answer);
answer=spec;
}
live.nat[answer].locked++;
live.nat[answer].touched=touchcnt++;
return answer;
}
static int readreg(int r, int size)
{
return readreg_general(r,size,-1,0);
}
static int readreg_specific(int r, int size, int spec)
{
return readreg_general(r,size,spec,0);
}
static int readreg_offset(int r, int size)
{
return readreg_general(r,size,-1,1);
}
/* writereg_general(r, size, spec)
*
* INPUT
* - r : mid-layer register
* - size : requested size (1/2/4)
* - spec : -1 if find or make a register free, otherwise specifies
* the physical register to use in any case
*
* OUTPUT
* - hard (physical, x86 here) register allocated to virtual register r
*/
static __inline__ int writereg_general(int r, int size, int spec)
{
int n;
int answer=-1;
record_register(r);
if (size<4) {
remove_offset(r,spec);
}
make_exclusive(r,size,spec);
if (isinreg(r)) {
int nvsize=size>live.state[r].validsize?size:live.state[r].validsize;
int ndsize=size>live.state[r].dirtysize?size:live.state[r].dirtysize;
n=live.state[r].realreg;
Dif (live.nat[n].nholds!=1)
abort();
switch(size) {
case 1:
if (live.nat[n].canbyte || spec>=0) {
live.state[r].dirtysize=ndsize;
live.state[r].validsize=nvsize;
answer=n;
}
break;
case 2:
if (live.nat[n].canword || spec>=0) {
live.state[r].dirtysize=ndsize;
live.state[r].validsize=nvsize;
answer=n;
}
break;
case 4:
live.state[r].dirtysize=ndsize;
live.state[r].validsize=nvsize;
answer=n;
break;
default: abort();
}
if (answer<0)
evict(r);
}
/* either the value was in memory to start with, or it was evicted and
is in memory now */
if (answer<0) {
answer=alloc_reg_hinted(r,size,1,spec);
}
if (spec>=0 && spec!=answer) {
mov_nregs(spec,answer);
answer=spec;
}
if (live.state[r].status==UNDEF)
live.state[r].validsize=4;
live.state[r].dirtysize=size>live.state[r].dirtysize?size:live.state[r].dirtysize;
live.state[r].validsize=size>live.state[r].validsize?size:live.state[r].validsize;
live.nat[answer].locked++;
live.nat[answer].touched=touchcnt++;
if (size==4) {
live.state[r].val=0;
}
else {
Dif (live.state[r].val) {
write_log("Problem with val\n");
abort();
}
}
set_status(r,DIRTY);
return answer;
}
static int writereg(int r, int size)
{
return writereg_general(r,size,-1);
}
static int writereg_specific(int r, int size, int spec)
{
return writereg_general(r,size,spec);
}
static __inline__ int rmw_general(int r, int wsize, int rsize, int spec)
{
int n;
int answer=-1;
record_register(r);
if (live.state[r].status==UNDEF) {
write_log("WARNING: Unexpected read of undefined register %d\n",r);
}
remove_offset(r,spec);
make_exclusive(r,0,spec);
Dif (wsize<rsize) {
write_log("Cannot handle wsize<rsize in rmw_general()\n");
abort();
}
if (isinreg(r) && live.state[r].validsize>=rsize) {
n=live.state[r].realreg;
Dif (live.nat[n].nholds!=1)
abort();
switch(rsize) {
case 1:
if (live.nat[n].canbyte || spec>=0) {
answer=n;
}
break;
case 2:
if (live.nat[n].canword || spec>=0) {
answer=n;
}
break;
case 4:
answer=n;
break;
default: abort();
}
if (answer<0)
evict(r);
}
/* either the value was in memory to start with, or it was evicted and
is in memory now */
if (answer<0) {
answer=alloc_reg_hinted(r,spec>=0?4:rsize,0,spec);
}
if (spec>=0 && spec!=answer) {
/* Too bad */
mov_nregs(spec,answer);
answer=spec;
}
if (wsize>live.state[r].dirtysize)
live.state[r].dirtysize=wsize;
if (wsize>live.state[r].validsize)
live.state[r].validsize=wsize;
set_status(r,DIRTY);
live.nat[answer].locked++;
live.nat[answer].touched=touchcnt++;
Dif (live.state[r].val) {
write_log("Problem with val(rmw)\n");
abort();
}
return answer;
}
static int rmw(int r, int wsize, int rsize)
{
return rmw_general(r,wsize,rsize,-1);
}
static int rmw_specific(int r, int wsize, int rsize, int spec)
{
return rmw_general(r,wsize,rsize,spec);
}
/* needed for restoring the carry flag on non-P6 cores */
static void bt_l_ri_noclobber(R4 r, IMM i)
{
int size=4;
if (i<16)
size=2;
r=readreg(r,size);
raw_bt_l_ri(r,i);
unlock2(r);
}
/********************************************************************
* FPU register status handling. EMIT TIME! *
********************************************************************/
static void f_tomem(int r)
{
if (live.fate[r].status==DIRTY) {
#if USE_LONG_DOUBLE
raw_fmov_ext_mr((uintptr)live.fate[r].mem,live.fate[r].realreg);
#else
raw_fmov_mr((uintptr)live.fate[r].mem,live.fate[r].realreg);
#endif
live.fate[r].status=CLEAN;
}
}
static void f_tomem_drop(int r)
{
if (live.fate[r].status==DIRTY) {
#if USE_LONG_DOUBLE
raw_fmov_ext_mr_drop((uintptr)live.fate[r].mem,live.fate[r].realreg);
#else
raw_fmov_mr_drop((uintptr)live.fate[r].mem,live.fate[r].realreg);
#endif
live.fate[r].status=INMEM;
}
}
static __inline__ int f_isinreg(int r)
{
return live.fate[r].status==CLEAN || live.fate[r].status==DIRTY;
}
static void f_evict(int r)
{
int rr;
if (!f_isinreg(r))
return;
rr=live.fate[r].realreg;
if (live.fat[rr].nholds==1)
f_tomem_drop(r);
else
f_tomem(r);
Dif (live.fat[rr].locked &&
live.fat[rr].nholds==1) {
write_log("FPU register %d in nreg %d is locked!\n",r,live.fate[r].realreg);
abort();
}
live.fat[rr].nholds--;
if (live.fat[rr].nholds!=live.fate[r].realind) { /* Was not last */
int topreg=live.fat[rr].holds[live.fat[rr].nholds];
int thisind=live.fate[r].realind;
live.fat[rr].holds[thisind]=topreg;
live.fate[topreg].realind=thisind;
}
live.fate[r].status=INMEM;
live.fate[r].realreg=-1;
}
static __inline__ void f_free_nreg(int r)
{
int i=live.fat[r].nholds;
while (i) {
int vr;
--i;
vr=live.fat[r].holds[i];
f_evict(vr);
}
Dif (live.fat[r].nholds!=0) {
write_log("Failed to free nreg %d, nholds is %d\n",r,live.fat[r].nholds);
abort();
}
}
/* Use with care! */
static __inline__ void f_isclean(int r)
{
if (!f_isinreg(r))
return;
live.fate[r].status=CLEAN;
}
static __inline__ void f_disassociate(int r)
{
f_isclean(r);
f_evict(r);
}
static int f_alloc_reg(int r, int willclobber)
{
int bestreg;
uae_s32 when;
int i;
uae_s32 badness;
bestreg=-1;
when=2000000000;
for (i=N_FREGS;i--;) {
badness=live.fat[i].touched;
if (live.fat[i].nholds==0)
badness=0;
if (!live.fat[i].locked && badness<when) {
bestreg=i;
when=badness;
if (live.fat[i].nholds==0)
break;
}
}
Dif (bestreg==-1)
abort();
if (live.fat[bestreg].nholds>0) {
f_free_nreg(bestreg);
}
if (f_isinreg(r)) {
f_evict(r);
}
if (!willclobber) {
if (live.fate[r].status!=UNDEF) {
#if USE_LONG_DOUBLE
raw_fmov_ext_rm(bestreg,(uintptr)live.fate[r].mem);
#else
raw_fmov_rm(bestreg,(uintptr)live.fate[r].mem);
#endif
}
live.fate[r].status=CLEAN;
}
else {
live.fate[r].status=DIRTY;
}
live.fate[r].realreg=bestreg;
live.fate[r].realind=live.fat[bestreg].nholds;
live.fat[bestreg].touched=touchcnt++;
live.fat[bestreg].holds[live.fat[bestreg].nholds]=r;
live.fat[bestreg].nholds++;
return bestreg;
}
static void f_unlock(int r)
{
Dif (!live.fat[r].locked)
abort();
live.fat[r].locked--;
}
static void f_setlock(int r)
{
live.fat[r].locked++;
}
static __inline__ int f_readreg(int r)
{
int n;
int answer=-1;
if (f_isinreg(r)) {
n=live.fate[r].realreg;
answer=n;
}
/* either the value was in memory to start with, or it was evicted and
is in memory now */
if (answer<0)
answer=f_alloc_reg(r,0);
live.fat[answer].locked++;
live.fat[answer].touched=touchcnt++;
return answer;
}
static __inline__ void f_make_exclusive(int r, int clobber)
{
freg_status oldstate;
int rr=live.fate[r].realreg;
int nr;
int nind;
int ndirt=0;
int i;
if (!f_isinreg(r))
return;
if (live.fat[rr].nholds==1)
return;
for (i=0;i<live.fat[rr].nholds;i++) {
int vr=live.fat[rr].holds[i];
if (vr!=r && live.fate[vr].status==DIRTY)
ndirt++;
}
if (!ndirt && !live.fat[rr].locked) {
/* Everything else is clean, so let's keep this register */
for (i=0;i<live.fat[rr].nholds;i++) {
int vr=live.fat[rr].holds[i];
if (vr!=r) {
f_evict(vr);
i--; /* Try that index again! */
}
}
Dif (live.fat[rr].nholds!=1) {
write_log("realreg %d holds %d (",rr,live.fat[rr].nholds);
for (i=0;i<live.fat[rr].nholds;i++) {
write_log(" %d(%d,%d)",live.fat[rr].holds[i],
live.fate[live.fat[rr].holds[i]].realreg,
live.fate[live.fat[rr].holds[i]].realind);
}
write_log("\n");
abort();
}
return;
}
/* We have to split the register */
oldstate=live.fate[r];
f_setlock(rr); /* Make sure this doesn't go away */
/* Forget about r being in the register rr */
f_disassociate(r);
/* Get a new register, that we will clobber completely */
nr=f_alloc_reg(r,1);
nind=live.fate[r].realind;
if (!clobber)
raw_fmov_rr(nr,rr); /* Make another copy */
live.fate[r]=oldstate; /* Keep all the old state info */
live.fate[r].realreg=nr;
live.fate[r].realind=nind;
f_unlock(rr);
}
static __inline__ int f_writereg(int r)
{
int n;
int answer=-1;
f_make_exclusive(r,1);
if (f_isinreg(r)) {
n=live.fate[r].realreg;
answer=n;
}
if (answer<0) {
answer=f_alloc_reg(r,1);
}
live.fate[r].status=DIRTY;
live.fat[answer].locked++;
live.fat[answer].touched=touchcnt++;
return answer;
}
static int f_rmw(int r)
{
int n;
f_make_exclusive(r,0);
if (f_isinreg(r)) {
n=live.fate[r].realreg;
}
else
n=f_alloc_reg(r,0);
live.fate[r].status=DIRTY;
live.fat[n].locked++;
live.fat[n].touched=touchcnt++;
return n;
}
static void fflags_into_flags_internal(uae_u32 tmp)
{
int r;
clobber_flags();
r=f_readreg(FP_RESULT);
if (FFLAG_NREG_CLOBBER_CONDITION) {
int tmp2=tmp;
tmp=writereg_specific(tmp,4,FFLAG_NREG);
raw_fflags_into_flags(r);
unlock2(tmp);
forget_about(tmp2);
}
else
raw_fflags_into_flags(r);
f_unlock(r);
live_flags();
}
/********************************************************************
* CPU functions exposed to gencomp. Both CREATE and EMIT time *
********************************************************************/
/*
* RULES FOR HANDLING REGISTERS:
*
* * In the function headers, order the parameters
* - 1st registers written to
* - 2nd read/modify/write registers
* - 3rd registers read from
* * Before calling raw_*, you must call readreg, writereg or rmw for
* each register
* * The order for this is
* - 1st call remove_offset for all registers written to with size<4
* - 2nd call readreg for all registers read without offset
* - 3rd call rmw for all rmw registers
* - 4th call readreg_offset for all registers that can handle offsets
* - 5th call get_offset for all the registers from the previous step
* - 6th call writereg for all written-to registers
* - 7th call raw_*
* - 8th unlock2 all registers that were locked
*/
MIDFUNC(0,live_flags,(void))
{
live.flags_on_stack=TRASH;
live.flags_in_flags=VALID;
live.flags_are_important=1;
}
MENDFUNC(0,live_flags,(void))
MIDFUNC(0,dont_care_flags,(void))
{
live.flags_are_important=0;
}
MENDFUNC(0,dont_care_flags,(void))
MIDFUNC(0,duplicate_carry,(void))
{
evict(FLAGX);
make_flags_live_internal();
COMPCALL(setcc_m)((uintptr)live.state[FLAGX].mem,2);
log_vwrite(FLAGX);
}
MENDFUNC(0,duplicate_carry,(void))
MIDFUNC(0,restore_carry,(void))
{
if (!have_rat_stall) { /* Not a P6 core, i.e. no partial stalls */
bt_l_ri_noclobber(FLAGX,0);
}
else { /* Avoid the stall the above creates.
This is slow on non-P6, though.
*/
COMPCALL(rol_b_ri(FLAGX,8));
isclean(FLAGX);
}
}
MENDFUNC(0,restore_carry,(void))
MIDFUNC(0,start_needflags,(void))
{
needflags=1;
}
MENDFUNC(0,start_needflags,(void))
MIDFUNC(0,end_needflags,(void))
{
needflags=0;
}
MENDFUNC(0,end_needflags,(void))
MIDFUNC(0,make_flags_live,(void))
{
make_flags_live_internal();
}
MENDFUNC(0,make_flags_live,(void))
MIDFUNC(1,fflags_into_flags,(W2 tmp))
{
clobber_flags();
fflags_into_flags_internal(tmp);
}
MENDFUNC(1,fflags_into_flags,(W2 tmp))
MIDFUNC(2,bt_l_ri,(R4 r, IMM i)) /* This is defined as only affecting C */
{
int size=4;
if (i<16)
size=2;
CLOBBER_BT;
r=readreg(r,size);
raw_bt_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,bt_l_ri,(R4 r, IMM i)) /* This is defined as only affecting C */
MIDFUNC(2,bt_l_rr,(R4 r, R4 b)) /* This is defined as only affecting C */
{
CLOBBER_BT;
r=readreg(r,4);
b=readreg(b,4);
raw_bt_l_rr(r,b);
unlock2(r);
unlock2(b);
}
MENDFUNC(2,bt_l_rr,(R4 r, R4 b)) /* This is defined as only affecting C */
MIDFUNC(2,btc_l_ri,(RW4 r, IMM i))
{
int size=4;
if (i<16)
size=2;
CLOBBER_BT;
r=rmw(r,size,size);
raw_btc_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,btc_l_ri,(RW4 r, IMM i))
MIDFUNC(2,btc_l_rr,(RW4 r, R4 b))
{
CLOBBER_BT;
b=readreg(b,4);
r=rmw(r,4,4);
raw_btc_l_rr(r,b);
unlock2(r);
unlock2(b);
}
MENDFUNC(2,btc_l_rr,(RW4 r, R4 b))
MIDFUNC(2,btr_l_ri,(RW4 r, IMM i))
{
int size=4;
if (i<16)
size=2;
CLOBBER_BT;
r=rmw(r,size,size);
raw_btr_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,btr_l_ri,(RW4 r, IMM i))
MIDFUNC(2,btr_l_rr,(RW4 r, R4 b))
{
CLOBBER_BT;
b=readreg(b,4);
r=rmw(r,4,4);
raw_btr_l_rr(r,b);
unlock2(r);
unlock2(b);
}
MENDFUNC(2,btr_l_rr,(RW4 r, R4 b))
MIDFUNC(2,bts_l_ri,(RW4 r, IMM i))
{
int size=4;
if (i<16)
size=2;
CLOBBER_BT;
r=rmw(r,size,size);
raw_bts_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,bts_l_ri,(RW4 r, IMM i))
MIDFUNC(2,bts_l_rr,(RW4 r, R4 b))
{
CLOBBER_BT;
b=readreg(b,4);
r=rmw(r,4,4);
raw_bts_l_rr(r,b);
unlock2(r);
unlock2(b);
}
MENDFUNC(2,bts_l_rr,(RW4 r, R4 b))
MIDFUNC(2,mov_l_rm,(W4 d, IMM s))
{
CLOBBER_MOV;
d=writereg(d,4);
raw_mov_l_rm(d,s);
unlock2(d);
}
MENDFUNC(2,mov_l_rm,(W4 d, IMM s))
MIDFUNC(1,call_r,(R4 r)) /* Clobbering is implicit */
{
r=readreg(r,4);
raw_call_r(r);
unlock2(r);
}
MENDFUNC(1,call_r,(R4 r)) /* Clobbering is implicit */
MIDFUNC(2,sub_l_mi,(IMM d, IMM s))
{
CLOBBER_SUB;
raw_sub_l_mi(d,s) ;
}
MENDFUNC(2,sub_l_mi,(IMM d, IMM s))
MIDFUNC(2,mov_l_mi,(IMM d, IMM s))
{
CLOBBER_MOV;
raw_mov_l_mi(d,s) ;
}
MENDFUNC(2,mov_l_mi,(IMM d, IMM s))
MIDFUNC(2,mov_w_mi,(IMM d, IMM s))
{
CLOBBER_MOV;
raw_mov_w_mi(d,s) ;
}
MENDFUNC(2,mov_w_mi,(IMM d, IMM s))
MIDFUNC(2,mov_b_mi,(IMM d, IMM s))
{
CLOBBER_MOV;
raw_mov_b_mi(d,s) ;
}
MENDFUNC(2,mov_b_mi,(IMM d, IMM s))
MIDFUNC(2,rol_b_ri,(RW1 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_ROL;
r=rmw(r,1,1);
raw_rol_b_ri(r,i);
unlock2(r);
}
MENDFUNC(2,rol_b_ri,(RW1 r, IMM i))
MIDFUNC(2,rol_w_ri,(RW2 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_ROL;
r=rmw(r,2,2);
raw_rol_w_ri(r,i);
unlock2(r);
}
MENDFUNC(2,rol_w_ri,(RW2 r, IMM i))
MIDFUNC(2,rol_l_ri,(RW4 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_ROL;
r=rmw(r,4,4);
raw_rol_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,rol_l_ri,(RW4 r, IMM i))
MIDFUNC(2,rol_l_rr,(RW4 d, R1 r))
{
if (isconst(r)) {
COMPCALL(rol_l_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_ROL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,4,4);
Dif (r!=1) {
write_log("Illegal register %d in raw_rol_b\n",r);
abort();
}
raw_rol_l_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,rol_l_rr,(RW4 d, R1 r))
MIDFUNC(2,rol_w_rr,(RW2 d, R1 r))
{ /* Can only do this with r==1, i.e. cl */
if (isconst(r)) {
COMPCALL(rol_w_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_ROL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,2,2);
Dif (r!=1) {
write_log("Illegal register %d in raw_rol_b\n",r);
abort();
}
raw_rol_w_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,rol_w_rr,(RW2 d, R1 r))
MIDFUNC(2,rol_b_rr,(RW1 d, R1 r))
{ /* Can only do this with r==1, i.e. cl */
if (isconst(r)) {
COMPCALL(rol_b_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_ROL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,1,1);
Dif (r!=1) {
write_log("Illegal register %d in raw_rol_b\n",r);
abort();
}
raw_rol_b_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,rol_b_rr,(RW1 d, R1 r))
MIDFUNC(2,shll_l_rr,(RW4 d, R1 r))
{
if (isconst(r)) {
COMPCALL(shll_l_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHLL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,4,4);
Dif (r!=1) {
write_log("Illegal register %d in raw_rol_b\n",r);
abort();
}
raw_shll_l_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shll_l_rr,(RW4 d, R1 r))
MIDFUNC(2,shll_w_rr,(RW2 d, R1 r))
{ /* Can only do this with r==1, i.e. cl */
if (isconst(r)) {
COMPCALL(shll_w_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHLL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,2,2);
Dif (r!=1) {
write_log("Illegal register %d in raw_shll_b\n",r);
abort();
}
raw_shll_w_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shll_w_rr,(RW2 d, R1 r))
MIDFUNC(2,shll_b_rr,(RW1 d, R1 r))
{ /* Can only do this with r==1, i.e. cl */
if (isconst(r)) {
COMPCALL(shll_b_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHLL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,1,1);
Dif (r!=1) {
write_log("Illegal register %d in raw_shll_b\n",r);
abort();
}
raw_shll_b_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shll_b_rr,(RW1 d, R1 r))
MIDFUNC(2,ror_b_ri,(R1 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_ROR;
r=rmw(r,1,1);
raw_ror_b_ri(r,i);
unlock2(r);
}
MENDFUNC(2,ror_b_ri,(R1 r, IMM i))
MIDFUNC(2,ror_w_ri,(R2 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_ROR;
r=rmw(r,2,2);
raw_ror_w_ri(r,i);
unlock2(r);
}
MENDFUNC(2,ror_w_ri,(R2 r, IMM i))
MIDFUNC(2,ror_l_ri,(R4 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_ROR;
r=rmw(r,4,4);
raw_ror_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,ror_l_ri,(R4 r, IMM i))
MIDFUNC(2,ror_l_rr,(R4 d, R1 r))
{
if (isconst(r)) {
COMPCALL(ror_l_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_ROR;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,4,4);
raw_ror_l_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,ror_l_rr,(R4 d, R1 r))
MIDFUNC(2,ror_w_rr,(R2 d, R1 r))
{
if (isconst(r)) {
COMPCALL(ror_w_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_ROR;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,2,2);
raw_ror_w_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,ror_w_rr,(R2 d, R1 r))
MIDFUNC(2,ror_b_rr,(R1 d, R1 r))
{
if (isconst(r)) {
COMPCALL(ror_b_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_ROR;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,1,1);
raw_ror_b_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,ror_b_rr,(R1 d, R1 r))
MIDFUNC(2,shrl_l_rr,(RW4 d, R1 r))
{
if (isconst(r)) {
COMPCALL(shrl_l_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHRL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,4,4);
Dif (r!=1) {
write_log("Illegal register %d in raw_rol_b\n",r);
abort();
}
raw_shrl_l_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shrl_l_rr,(RW4 d, R1 r))
MIDFUNC(2,shrl_w_rr,(RW2 d, R1 r))
{ /* Can only do this with r==1, i.e. cl */
if (isconst(r)) {
COMPCALL(shrl_w_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHRL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,2,2);
Dif (r!=1) {
write_log("Illegal register %d in raw_shrl_b\n",r);
abort();
}
raw_shrl_w_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shrl_w_rr,(RW2 d, R1 r))
MIDFUNC(2,shrl_b_rr,(RW1 d, R1 r))
{ /* Can only do this with r==1, i.e. cl */
if (isconst(r)) {
COMPCALL(shrl_b_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHRL;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,1,1);
Dif (r!=1) {
write_log("Illegal register %d in raw_shrl_b\n",r);
abort();
}
raw_shrl_b_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shrl_b_rr,(RW1 d, R1 r))
MIDFUNC(2,shll_l_ri,(RW4 r, IMM i))
{
if (!i && !needflags)
return;
if (isconst(r) && !needflags) {
live.state[r].val<<=i;
return;
}
CLOBBER_SHLL;
r=rmw(r,4,4);
raw_shll_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shll_l_ri,(RW4 r, IMM i))
MIDFUNC(2,shll_w_ri,(RW2 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SHLL;
r=rmw(r,2,2);
raw_shll_w_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shll_w_ri,(RW2 r, IMM i))
MIDFUNC(2,shll_b_ri,(RW1 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SHLL;
r=rmw(r,1,1);
raw_shll_b_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shll_b_ri,(RW1 r, IMM i))
MIDFUNC(2,shrl_l_ri,(RW4 r, IMM i))
{
if (!i && !needflags)
return;
if (isconst(r) && !needflags) {
live.state[r].val>>=i;
return;
}
CLOBBER_SHRL;
r=rmw(r,4,4);
raw_shrl_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shrl_l_ri,(RW4 r, IMM i))
MIDFUNC(2,shrl_w_ri,(RW2 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SHRL;
r=rmw(r,2,2);
raw_shrl_w_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shrl_w_ri,(RW2 r, IMM i))
MIDFUNC(2,shrl_b_ri,(RW1 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SHRL;
r=rmw(r,1,1);
raw_shrl_b_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shrl_b_ri,(RW1 r, IMM i))
MIDFUNC(2,shra_l_ri,(RW4 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SHRA;
r=rmw(r,4,4);
raw_shra_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shra_l_ri,(RW4 r, IMM i))
MIDFUNC(2,shra_w_ri,(RW2 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SHRA;
r=rmw(r,2,2);
raw_shra_w_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shra_w_ri,(RW2 r, IMM i))
MIDFUNC(2,shra_b_ri,(RW1 r, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SHRA;
r=rmw(r,1,1);
raw_shra_b_ri(r,i);
unlock2(r);
}
MENDFUNC(2,shra_b_ri,(RW1 r, IMM i))
MIDFUNC(2,shra_l_rr,(RW4 d, R1 r))
{
if (isconst(r)) {
COMPCALL(shra_l_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHRA;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,4,4);
Dif (r!=1) {
write_log("Illegal register %d in raw_rol_b\n",r);
abort();
}
raw_shra_l_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shra_l_rr,(RW4 d, R1 r))
MIDFUNC(2,shra_w_rr,(RW2 d, R1 r))
{ /* Can only do this with r==1, i.e. cl */
if (isconst(r)) {
COMPCALL(shra_w_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHRA;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,2,2);
Dif (r!=1) {
write_log("Illegal register %d in raw_shra_b\n",r);
abort();
}
raw_shra_w_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shra_w_rr,(RW2 d, R1 r))
MIDFUNC(2,shra_b_rr,(RW1 d, R1 r))
{ /* Can only do this with r==1, i.e. cl */
if (isconst(r)) {
COMPCALL(shra_b_ri)(d,(uae_u8)live.state[r].val);
return;
}
CLOBBER_SHRA;
r=readreg_specific(r,1,SHIFTCOUNT_NREG);
d=rmw(d,1,1);
Dif (r!=1) {
write_log("Illegal register %d in raw_shra_b\n",r);
abort();
}
raw_shra_b_rr(d,r) ;
unlock2(r);
unlock2(d);
}
MENDFUNC(2,shra_b_rr,(RW1 d, R1 r))
MIDFUNC(2,setcc,(W1 d, IMM cc))
{
CLOBBER_SETCC;
d=writereg(d,1);
raw_setcc(d,cc);
unlock2(d);
}
MENDFUNC(2,setcc,(W1 d, IMM cc))
MIDFUNC(2,setcc_m,(IMM d, IMM cc))
{
CLOBBER_SETCC;
raw_setcc_m(d,cc);
}
MENDFUNC(2,setcc_m,(IMM d, IMM cc))
MIDFUNC(3,cmov_b_rr,(RW1 d, R1 s, IMM cc))
{
if (d==s)
return;
CLOBBER_CMOV;
s=readreg(s,1);
d=rmw(d,1,1);
raw_cmov_b_rr(d,s,cc);
unlock2(s);
unlock2(d);
}
MENDFUNC(3,cmov_b_rr,(RW1 d, R1 s, IMM cc))
MIDFUNC(3,cmov_w_rr,(RW2 d, R2 s, IMM cc))
{
if (d==s)
return;
CLOBBER_CMOV;
s=readreg(s,2);
d=rmw(d,2,2);
raw_cmov_w_rr(d,s,cc);
unlock2(s);
unlock2(d);
}
MENDFUNC(3,cmov_w_rr,(RW2 d, R2 s, IMM cc))
MIDFUNC(3,cmov_l_rr,(RW4 d, R4 s, IMM cc))
{
if (d==s)
return;
CLOBBER_CMOV;
s=readreg(s,4);
d=rmw(d,4,4);
raw_cmov_l_rr(d,s,cc);
unlock2(s);
unlock2(d);
}
MENDFUNC(3,cmov_l_rr,(RW4 d, R4 s, IMM cc))
MIDFUNC(3,cmov_l_rm,(RW4 d, IMM s, IMM cc))
{
CLOBBER_CMOV;
d=rmw(d,4,4);
raw_cmov_l_rm(d,s,cc);
unlock2(d);
}
MENDFUNC(3,cmov_l_rm,(RW4 d, IMM s, IMM cc))
MIDFUNC(2,bsf_l_rr,(W4 d, W4 s))
{
CLOBBER_BSF;
s = readreg(s, 4);
d = writereg(d, 4);
raw_bsf_l_rr(d, s);
unlock2(s);
unlock2(d);
}
MENDFUNC(2,bsf_l_rr,(W4 d, W4 s))
/* Set the Z flag depending on the value in s. Note that the
value has to be 0 or -1 (or, more precisely, for non-zero
values, bit 14 must be set)! */
MIDFUNC(2,simulate_bsf,(W4 tmp, RW4 s))
{
CLOBBER_BSF;
s=rmw_specific(s,4,4,FLAG_NREG3);
tmp=writereg(tmp,4);
raw_flags_set_zero(s, tmp);
unlock2(tmp);
unlock2(s);
}
MENDFUNC(2,simulate_bsf,(W4 tmp, RW4 s))
MIDFUNC(2,imul_32_32,(RW4 d, R4 s))
{
CLOBBER_MUL;
s=readreg(s,4);
d=rmw(d,4,4);
raw_imul_32_32(d,s);
unlock2(s);
unlock2(d);
}
MENDFUNC(2,imul_32_32,(RW4 d, R4 s))
MIDFUNC(2,imul_64_32,(RW4 d, RW4 s))
{
CLOBBER_MUL;
s=rmw_specific(s,4,4,MUL_NREG2);
d=rmw_specific(d,4,4,MUL_NREG1);
raw_imul_64_32(d,s);
unlock2(s);
unlock2(d);
}
MENDFUNC(2,imul_64_32,(RW4 d, RW4 s))
MIDFUNC(2,mul_64_32,(RW4 d, RW4 s))
{
CLOBBER_MUL;
s=rmw_specific(s,4,4,MUL_NREG2);
d=rmw_specific(d,4,4,MUL_NREG1);
raw_mul_64_32(d,s);
unlock2(s);
unlock2(d);
}
MENDFUNC(2,mul_64_32,(RW4 d, RW4 s))
MIDFUNC(2,mul_32_32,(RW4 d, R4 s))
{
CLOBBER_MUL;
s=readreg(s,4);
d=rmw(d,4,4);
raw_mul_32_32(d,s);
unlock2(s);
unlock2(d);
}
MENDFUNC(2,mul_32_32,(RW4 d, R4 s))
#if SIZEOF_VOID_P == 8
MIDFUNC(2,sign_extend_32_rr,(W4 d, R2 s))
{
int isrmw;
if (isconst(s)) {
set_const(d,(uae_s32)live.state[s].val);
return;
}
CLOBBER_SE32;
isrmw=(s==d);
if (!isrmw) {
s=readreg(s,4);
d=writereg(d,4);
}
else { /* If we try to lock this twice, with different sizes, we
are int trouble! */
s=d=rmw(s,4,4);
}
raw_sign_extend_32_rr(d,s);
if (!isrmw) {
unlock2(d);
unlock2(s);
}
else {
unlock2(s);
}
}
MENDFUNC(2,sign_extend_32_rr,(W4 d, R2 s))
#endif
MIDFUNC(2,sign_extend_16_rr,(W4 d, R2 s))
{
int isrmw;
if (isconst(s)) {
set_const(d,(uae_s32)(uae_s16)live.state[s].val);
return;
}
CLOBBER_SE16;
isrmw=(s==d);
if (!isrmw) {
s=readreg(s,2);
d=writereg(d,4);
}
else { /* If we try to lock this twice, with different sizes, we
are int trouble! */
s=d=rmw(s,4,2);
}
raw_sign_extend_16_rr(d,s);
if (!isrmw) {
unlock2(d);
unlock2(s);
}
else {
unlock2(s);
}
}
MENDFUNC(2,sign_extend_16_rr,(W4 d, R2 s))
MIDFUNC(2,sign_extend_8_rr,(W4 d, R1 s))
{
int isrmw;
if (isconst(s)) {
set_const(d,(uae_s32)(uae_s8)live.state[s].val);
return;
}
isrmw=(s==d);
CLOBBER_SE8;
if (!isrmw) {
s=readreg(s,1);
d=writereg(d,4);
}
else { /* If we try to lock this twice, with different sizes, we
are int trouble! */
s=d=rmw(s,4,1);
}
raw_sign_extend_8_rr(d,s);
if (!isrmw) {
unlock2(d);
unlock2(s);
}
else {
unlock2(s);
}
}
MENDFUNC(2,sign_extend_8_rr,(W4 d, R1 s))
MIDFUNC(2,zero_extend_16_rr,(W4 d, R2 s))
{
int isrmw;
if (isconst(s)) {
set_const(d,(uae_u32)(uae_u16)live.state[s].val);
return;
}
isrmw=(s==d);
CLOBBER_ZE16;
if (!isrmw) {
s=readreg(s,2);
d=writereg(d,4);
}
else { /* If we try to lock this twice, with different sizes, we
are int trouble! */
s=d=rmw(s,4,2);
}
raw_zero_extend_16_rr(d,s);
if (!isrmw) {
unlock2(d);
unlock2(s);
}
else {
unlock2(s);
}
}
MENDFUNC(2,zero_extend_16_rr,(W4 d, R2 s))
MIDFUNC(2,zero_extend_8_rr,(W4 d, R1 s))
{
int isrmw;
if (isconst(s)) {
set_const(d,(uae_u32)(uae_u8)live.state[s].val);
return;
}
isrmw=(s==d);
CLOBBER_ZE8;
if (!isrmw) {
s=readreg(s,1);
d=writereg(d,4);
}
else { /* If we try to lock this twice, with different sizes, we
are int trouble! */
s=d=rmw(s,4,1);
}
raw_zero_extend_8_rr(d,s);
if (!isrmw) {
unlock2(d);
unlock2(s);
}
else {
unlock2(s);
}
}
MENDFUNC(2,zero_extend_8_rr,(W4 d, R1 s))
MIDFUNC(2,mov_b_rr,(W1 d, R1 s))
{
if (d==s)
return;
if (isconst(s)) {
COMPCALL(mov_b_ri)(d,(uae_u8)live.state[s].val);
return;
}
CLOBBER_MOV;
s=readreg(s,1);
d=writereg(d,1);
raw_mov_b_rr(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,mov_b_rr,(W1 d, R1 s))
MIDFUNC(2,mov_w_rr,(W2 d, R2 s))
{
if (d==s)
return;
if (isconst(s)) {
COMPCALL(mov_w_ri)(d,(uae_u16)live.state[s].val);
return;
}
CLOBBER_MOV;
s=readreg(s,2);
d=writereg(d,2);
raw_mov_w_rr(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,mov_w_rr,(W2 d, R2 s))
MIDFUNC(4,mov_l_rrm_indexed,(W4 d,R4 baser, R4 index, IMM factor))
{
CLOBBER_MOV;
baser=readreg(baser,4);
index=readreg(index,4);
d=writereg(d,4);
raw_mov_l_rrm_indexed(d,baser,index,factor);
unlock2(d);
unlock2(baser);
unlock2(index);
}
MENDFUNC(4,mov_l_rrm_indexed,(W4 d,R4 baser, R4 index, IMM factor))
MIDFUNC(4,mov_w_rrm_indexed,(W2 d, R4 baser, R4 index, IMM factor))
{
CLOBBER_MOV;
baser=readreg(baser,4);
index=readreg(index,4);
d=writereg(d,2);
raw_mov_w_rrm_indexed(d,baser,index,factor);
unlock2(d);
unlock2(baser);
unlock2(index);
}
MENDFUNC(4,mov_w_rrm_indexed,(W2 d, R4 baser, R4 index, IMM factor))
MIDFUNC(4,mov_b_rrm_indexed,(W1 d, R4 baser, R4 index, IMM factor))
{
CLOBBER_MOV;
baser=readreg(baser,4);
index=readreg(index,4);
d=writereg(d,1);
raw_mov_b_rrm_indexed(d,baser,index,factor);
unlock2(d);
unlock2(baser);
unlock2(index);
}
MENDFUNC(4,mov_b_rrm_indexed,(W1 d, R4 baser, R4 index, IMM factor))
MIDFUNC(4,mov_l_mrr_indexed,(R4 baser, R4 index, IMM factor, R4 s))
{
CLOBBER_MOV;
baser=readreg(baser,4);
index=readreg(index,4);
s=readreg(s,4);
Dif (baser==s || index==s)
abort();
raw_mov_l_mrr_indexed(baser,index,factor,s);
unlock2(s);
unlock2(baser);
unlock2(index);
}
MENDFUNC(4,mov_l_mrr_indexed,(R4 baser, R4 index, IMM factor, R4 s))
MIDFUNC(4,mov_w_mrr_indexed,(R4 baser, R4 index, IMM factor, R2 s))
{
CLOBBER_MOV;
baser=readreg(baser,4);
index=readreg(index,4);
s=readreg(s,2);
raw_mov_w_mrr_indexed(baser,index,factor,s);
unlock2(s);
unlock2(baser);
unlock2(index);
}
MENDFUNC(4,mov_w_mrr_indexed,(R4 baser, R4 index, IMM factor, R2 s))
MIDFUNC(4,mov_b_mrr_indexed,(R4 baser, R4 index, IMM factor, R1 s))
{
CLOBBER_MOV;
s=readreg(s,1);
baser=readreg(baser,4);
index=readreg(index,4);
raw_mov_b_mrr_indexed(baser,index,factor,s);
unlock2(s);
unlock2(baser);
unlock2(index);
}
MENDFUNC(4,mov_b_mrr_indexed,(R4 baser, R4 index, IMM factor, R1 s))
MIDFUNC(5,mov_l_bmrr_indexed,(IMM base, R4 baser, R4 index, IMM factor, R4 s))
{
int basereg=baser;
int indexreg=index;
CLOBBER_MOV;
s=readreg(s,4);
baser=readreg_offset(baser,4);
index=readreg_offset(index,4);
base+=get_offset(basereg);
base+=factor*get_offset(indexreg);
raw_mov_l_bmrr_indexed(base,baser,index,factor,s);
unlock2(s);
unlock2(baser);
unlock2(index);
}
MENDFUNC(5,mov_l_bmrr_indexed,(IMM base, R4 baser, R4 index, IMM factor, R4 s))
MIDFUNC(5,mov_w_bmrr_indexed,(IMM base, R4 baser, R4 index, IMM factor, R2 s))
{
int basereg=baser;
int indexreg=index;
CLOBBER_MOV;
s=readreg(s,2);
baser=readreg_offset(baser,4);
index=readreg_offset(index,4);
base+=get_offset(basereg);
base+=factor*get_offset(indexreg);
raw_mov_w_bmrr_indexed(base,baser,index,factor,s);
unlock2(s);
unlock2(baser);
unlock2(index);
}
MENDFUNC(5,mov_w_bmrr_indexed,(IMM base, R4 baser, R4 index, IMM factor, R2 s))
MIDFUNC(5,mov_b_bmrr_indexed,(IMM base, R4 baser, R4 index, IMM factor, R1 s))
{
int basereg=baser;
int indexreg=index;
CLOBBER_MOV;
s=readreg(s,1);
baser=readreg_offset(baser,4);
index=readreg_offset(index,4);
base+=get_offset(basereg);
base+=factor*get_offset(indexreg);
raw_mov_b_bmrr_indexed(base,baser,index,factor,s);
unlock2(s);
unlock2(baser);
unlock2(index);
}
MENDFUNC(5,mov_b_bmrr_indexed,(IMM base, R4 baser, R4 index, IMM factor, R1 s))
/* Read a long from base+baser+factor*index */
MIDFUNC(5,mov_l_brrm_indexed,(W4 d, IMM base, R4 baser, R4 index, IMM factor))
{
int basereg=baser;
int indexreg=index;
CLOBBER_MOV;
baser=readreg_offset(baser,4);
index=readreg_offset(index,4);
base+=get_offset(basereg);
base+=factor*get_offset(indexreg);
d=writereg(d,4);
raw_mov_l_brrm_indexed(d,base,baser,index,factor);
unlock2(d);
unlock2(baser);
unlock2(index);
}
MENDFUNC(5,mov_l_brrm_indexed,(W4 d, IMM base, R4 baser, R4 index, IMM factor))
MIDFUNC(5,mov_w_brrm_indexed,(W2 d, IMM base, R4 baser, R4 index, IMM factor))
{
int basereg=baser;
int indexreg=index;
CLOBBER_MOV;
remove_offset(d,-1);
baser=readreg_offset(baser,4);
index=readreg_offset(index,4);
base+=get_offset(basereg);
base+=factor*get_offset(indexreg);
d=writereg(d,2);
raw_mov_w_brrm_indexed(d,base,baser,index,factor);
unlock2(d);
unlock2(baser);
unlock2(index);
}
MENDFUNC(5,mov_w_brrm_indexed,(W2 d, IMM base, R4 baser, R4 index, IMM factor))
MIDFUNC(5,mov_b_brrm_indexed,(W1 d, IMM base, R4 baser, R4 index, IMM factor))
{
int basereg=baser;
int indexreg=index;
CLOBBER_MOV;
remove_offset(d,-1);
baser=readreg_offset(baser,4);
index=readreg_offset(index,4);
base+=get_offset(basereg);
base+=factor*get_offset(indexreg);
d=writereg(d,1);
raw_mov_b_brrm_indexed(d,base,baser,index,factor);
unlock2(d);
unlock2(baser);
unlock2(index);
}
MENDFUNC(5,mov_b_brrm_indexed,(W1 d, IMM base, R4 baser, R4 index, IMM factor))
/* Read a long from base+factor*index */
MIDFUNC(4,mov_l_rm_indexed,(W4 d, IMM base, R4 index, IMM factor))
{
int indexreg=index;
if (isconst(index)) {
COMPCALL(mov_l_rm)(d,base+factor*live.state[index].val);
return;
}
CLOBBER_MOV;
index=readreg_offset(index,4);
base+=get_offset(indexreg)*factor;
d=writereg(d,4);
raw_mov_l_rm_indexed(d,base,index,factor);
unlock2(index);
unlock2(d);
}
MENDFUNC(4,mov_l_rm_indexed,(W4 d, IMM base, R4 index, IMM factor))
/* read the long at the address contained in s+offset and store in d */
MIDFUNC(3,mov_l_rR,(W4 d, R4 s, IMM offset))
{
if (isconst(s)) {
COMPCALL(mov_l_rm)(d,live.state[s].val+offset);
return;
}
CLOBBER_MOV;
s=readreg(s,4);
d=writereg(d,4);
raw_mov_l_rR(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_l_rR,(W4 d, R4 s, IMM offset))
/* read the word at the address contained in s+offset and store in d */
MIDFUNC(3,mov_w_rR,(W2 d, R4 s, IMM offset))
{
if (isconst(s)) {
COMPCALL(mov_w_rm)(d,live.state[s].val+offset);
return;
}
CLOBBER_MOV;
s=readreg(s,4);
d=writereg(d,2);
raw_mov_w_rR(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_w_rR,(W2 d, R4 s, IMM offset))
/* read the word at the address contained in s+offset and store in d */
MIDFUNC(3,mov_b_rR,(W1 d, R4 s, IMM offset))
{
if (isconst(s)) {
COMPCALL(mov_b_rm)(d,live.state[s].val+offset);
return;
}
CLOBBER_MOV;
s=readreg(s,4);
d=writereg(d,1);
raw_mov_b_rR(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_b_rR,(W1 d, R4 s, IMM offset))
/* read the long at the address contained in s+offset and store in d */
MIDFUNC(3,mov_l_brR,(W4 d, R4 s, IMM offset))
{
int sreg=s;
if (isconst(s)) {
COMPCALL(mov_l_rm)(d,live.state[s].val+offset);
return;
}
CLOBBER_MOV;
s=readreg_offset(s,4);
offset+=get_offset(sreg);
d=writereg(d,4);
raw_mov_l_brR(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_l_brR,(W4 d, R4 s, IMM offset))
/* read the word at the address contained in s+offset and store in d */
MIDFUNC(3,mov_w_brR,(W2 d, R4 s, IMM offset))
{
int sreg=s;
if (isconst(s)) {
COMPCALL(mov_w_rm)(d,live.state[s].val+offset);
return;
}
CLOBBER_MOV;
remove_offset(d,-1);
s=readreg_offset(s,4);
offset+=get_offset(sreg);
d=writereg(d,2);
raw_mov_w_brR(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_w_brR,(W2 d, R4 s, IMM offset))
/* read the word at the address contained in s+offset and store in d */
MIDFUNC(3,mov_b_brR,(W1 d, R4 s, IMM offset))
{
int sreg=s;
if (isconst(s)) {
COMPCALL(mov_b_rm)(d,live.state[s].val+offset);
return;
}
CLOBBER_MOV;
remove_offset(d,-1);
s=readreg_offset(s,4);
offset+=get_offset(sreg);
d=writereg(d,1);
raw_mov_b_brR(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_b_brR,(W1 d, R4 s, IMM offset))
MIDFUNC(3,mov_l_Ri,(R4 d, IMM i, IMM offset))
{
int dreg=d;
if (isconst(d)) {
COMPCALL(mov_l_mi)(live.state[d].val+offset,i);
return;
}
CLOBBER_MOV;
d=readreg_offset(d,4);
offset+=get_offset(dreg);
raw_mov_l_Ri(d,i,offset);
unlock2(d);
}
MENDFUNC(3,mov_l_Ri,(R4 d, IMM i, IMM offset))
MIDFUNC(3,mov_w_Ri,(R4 d, IMM i, IMM offset))
{
int dreg=d;
if (isconst(d)) {
COMPCALL(mov_w_mi)(live.state[d].val+offset,i);
return;
}
CLOBBER_MOV;
d=readreg_offset(d,4);
offset+=get_offset(dreg);
raw_mov_w_Ri(d,i,offset);
unlock2(d);
}
MENDFUNC(3,mov_w_Ri,(R4 d, IMM i, IMM offset))
MIDFUNC(3,mov_b_Ri,(R4 d, IMM i, IMM offset))
{
int dreg=d;
if (isconst(d)) {
COMPCALL(mov_b_mi)(live.state[d].val+offset,i);
return;
}
CLOBBER_MOV;
d=readreg_offset(d,4);
offset+=get_offset(dreg);
raw_mov_b_Ri(d,i,offset);
unlock2(d);
}
MENDFUNC(3,mov_b_Ri,(R4 d, IMM i, IMM offset))
/* Warning! OFFSET is byte sized only! */
MIDFUNC(3,mov_l_Rr,(R4 d, R4 s, IMM offset))
{
if (isconst(d)) {
COMPCALL(mov_l_mr)(live.state[d].val+offset,s);
return;
}
if (isconst(s)) {
COMPCALL(mov_l_Ri)(d,live.state[s].val,offset);
return;
}
CLOBBER_MOV;
s=readreg(s,4);
d=readreg(d,4);
raw_mov_l_Rr(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_l_Rr,(R4 d, R4 s, IMM offset))
MIDFUNC(3,mov_w_Rr,(R4 d, R2 s, IMM offset))
{
if (isconst(d)) {
COMPCALL(mov_w_mr)(live.state[d].val+offset,s);
return;
}
if (isconst(s)) {
COMPCALL(mov_w_Ri)(d,(uae_u16)live.state[s].val,offset);
return;
}
CLOBBER_MOV;
s=readreg(s,2);
d=readreg(d,4);
raw_mov_w_Rr(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_w_Rr,(R4 d, R2 s, IMM offset))
MIDFUNC(3,mov_b_Rr,(R4 d, R1 s, IMM offset))
{
if (isconst(d)) {
COMPCALL(mov_b_mr)(live.state[d].val+offset,s);
return;
}
if (isconst(s)) {
COMPCALL(mov_b_Ri)(d,(uae_u8)live.state[s].val,offset);
return;
}
CLOBBER_MOV;
s=readreg(s,1);
d=readreg(d,4);
raw_mov_b_Rr(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_b_Rr,(R4 d, R1 s, IMM offset))
MIDFUNC(3,lea_l_brr,(W4 d, R4 s, IMM offset))
{
if (isconst(s)) {
COMPCALL(mov_l_ri)(d,live.state[s].val+offset);
return;
}
#if USE_OFFSET
if (d==s) {
add_offset(d,offset);
return;
}
#endif
CLOBBER_LEA;
s=readreg(s,4);
d=writereg(d,4);
raw_lea_l_brr(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,lea_l_brr,(W4 d, R4 s, IMM offset))
MIDFUNC(5,lea_l_brr_indexed,(W4 d, R4 s, R4 index, IMM factor, IMM offset))
{
if (!offset) {
COMPCALL(lea_l_rr_indexed)(d,s,index,factor);
return;
}
CLOBBER_LEA;
s=readreg(s,4);
index=readreg(index,4);
d=writereg(d,4);
raw_lea_l_brr_indexed(d,s,index,factor,offset);
unlock2(d);
unlock2(index);
unlock2(s);
}
MENDFUNC(5,lea_l_brr_indexed,(W4 d, R4 s, R4 index, IMM factor, IMM offset))
MIDFUNC(4,lea_l_rr_indexed,(W4 d, R4 s, R4 index, IMM factor))
{
CLOBBER_LEA;
s=readreg(s,4);
index=readreg(index,4);
d=writereg(d,4);
raw_lea_l_rr_indexed(d,s,index,factor);
unlock2(d);
unlock2(index);
unlock2(s);
}
MENDFUNC(4,lea_l_rr_indexed,(W4 d, R4 s, R4 index, IMM factor))
/* write d to the long at the address contained in s+offset */
MIDFUNC(3,mov_l_bRr,(R4 d, R4 s, IMM offset))
{
int dreg=d;
if (isconst(d)) {
COMPCALL(mov_l_mr)(live.state[d].val+offset,s);
return;
}
CLOBBER_MOV;
s=readreg(s,4);
d=readreg_offset(d,4);
offset+=get_offset(dreg);
raw_mov_l_bRr(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_l_bRr,(R4 d, R4 s, IMM offset))
/* write the word at the address contained in s+offset and store in d */
MIDFUNC(3,mov_w_bRr,(R4 d, R2 s, IMM offset))
{
int dreg=d;
if (isconst(d)) {
COMPCALL(mov_w_mr)(live.state[d].val+offset,s);
return;
}
CLOBBER_MOV;
s=readreg(s,2);
d=readreg_offset(d,4);
offset+=get_offset(dreg);
raw_mov_w_bRr(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_w_bRr,(R4 d, R2 s, IMM offset))
MIDFUNC(3,mov_b_bRr,(R4 d, R1 s, IMM offset))
{
int dreg=d;
if (isconst(d)) {
COMPCALL(mov_b_mr)(live.state[d].val+offset,s);
return;
}
CLOBBER_MOV;
s=readreg(s,1);
d=readreg_offset(d,4);
offset+=get_offset(dreg);
raw_mov_b_bRr(d,s,offset);
unlock2(d);
unlock2(s);
}
MENDFUNC(3,mov_b_bRr,(R4 d, R1 s, IMM offset))
MIDFUNC(1,bswap_32,(RW4 r))
{
int reg=r;
if (isconst(r)) {
uae_u32 oldv=live.state[r].val;
live.state[r].val=reverse32(oldv);
return;
}
CLOBBER_SW32;
r=rmw(r,4,4);
raw_bswap_32(r);
unlock2(r);
}
MENDFUNC(1,bswap_32,(RW4 r))
MIDFUNC(1,bswap_16,(RW2 r))
{
if (isconst(r)) {
uae_u32 oldv=live.state[r].val;
live.state[r].val=((oldv>>8)&0xff) | ((oldv<<8)&0xff00) |
(oldv&0xffff0000);
return;
}
CLOBBER_SW16;
r=rmw(r,2,2);
raw_bswap_16(r);
unlock2(r);
}
MENDFUNC(1,bswap_16,(RW2 r))
MIDFUNC(2,mov_l_rr,(W4 d, R4 s))
{
int olds;
if (d==s) { /* How pointless! */
return;
}
if (isconst(s)) {
COMPCALL(mov_l_ri)(d,live.state[s].val);
return;
}
olds=s;
disassociate(d);
s=readreg_offset(s,4);
live.state[d].realreg=s;
live.state[d].realind=live.nat[s].nholds;
live.state[d].val=live.state[olds].val;
live.state[d].validsize=4;
live.state[d].dirtysize=4;
set_status(d,DIRTY);
live.nat[s].holds[live.nat[s].nholds]=d;
live.nat[s].nholds++;
log_clobberreg(d);
/* write_log("Added %d to nreg %d(%d), now holds %d regs\n",
d,s,live.state[d].realind,live.nat[s].nholds); */
unlock2(s);
}
MENDFUNC(2,mov_l_rr,(W4 d, R4 s))
MIDFUNC(2,mov_l_mr,(IMM d, R4 s))
{
if (isconst(s)) {
COMPCALL(mov_l_mi)(d,live.state[s].val);
return;
}
CLOBBER_MOV;
s=readreg(s,4);
raw_mov_l_mr(d,s);
unlock2(s);
}
MENDFUNC(2,mov_l_mr,(IMM d, R4 s))
MIDFUNC(2,mov_w_mr,(IMM d, R2 s))
{
if (isconst(s)) {
COMPCALL(mov_w_mi)(d,(uae_u16)live.state[s].val);
return;
}
CLOBBER_MOV;
s=readreg(s,2);
raw_mov_w_mr(d,s);
unlock2(s);
}
MENDFUNC(2,mov_w_mr,(IMM d, R2 s))
MIDFUNC(2,mov_w_rm,(W2 d, IMM s))
{
CLOBBER_MOV;
d=writereg(d,2);
raw_mov_w_rm(d,s);
unlock2(d);
}
MENDFUNC(2,mov_w_rm,(W2 d, IMM s))
MIDFUNC(2,mov_b_mr,(IMM d, R1 s))
{
if (isconst(s)) {
COMPCALL(mov_b_mi)(d,(uae_u8)live.state[s].val);
return;
}
CLOBBER_MOV;
s=readreg(s,1);
raw_mov_b_mr(d,s);
unlock2(s);
}
MENDFUNC(2,mov_b_mr,(IMM d, R1 s))
MIDFUNC(2,mov_b_rm,(W1 d, IMM s))
{
CLOBBER_MOV;
d=writereg(d,1);
raw_mov_b_rm(d,s);
unlock2(d);
}
MENDFUNC(2,mov_b_rm,(W1 d, IMM s))
MIDFUNC(2,mov_l_ri,(W4 d, IMM s))
{
set_const(d,s);
return;
}
MENDFUNC(2,mov_l_ri,(W4 d, IMM s))
MIDFUNC(2,mov_w_ri,(W2 d, IMM s))
{
CLOBBER_MOV;
d=writereg(d,2);
raw_mov_w_ri(d,s);
unlock2(d);
}
MENDFUNC(2,mov_w_ri,(W2 d, IMM s))
MIDFUNC(2,mov_b_ri,(W1 d, IMM s))
{
CLOBBER_MOV;
d=writereg(d,1);
raw_mov_b_ri(d,s);
unlock2(d);
}
MENDFUNC(2,mov_b_ri,(W1 d, IMM s))
MIDFUNC(2,add_l_mi,(IMM d, IMM s))
{
CLOBBER_ADD;
raw_add_l_mi(d,s) ;
}
MENDFUNC(2,add_l_mi,(IMM d, IMM s))
MIDFUNC(2,add_w_mi,(IMM d, IMM s))
{
CLOBBER_ADD;
raw_add_w_mi(d,s) ;
}
MENDFUNC(2,add_w_mi,(IMM d, IMM s))
MIDFUNC(2,add_b_mi,(IMM d, IMM s))
{
CLOBBER_ADD;
raw_add_b_mi(d,s) ;
}
MENDFUNC(2,add_b_mi,(IMM d, IMM s))
MIDFUNC(2,test_l_ri,(R4 d, IMM i))
{
CLOBBER_TEST;
d=readreg(d,4);
raw_test_l_ri(d,i);
unlock2(d);
}
MENDFUNC(2,test_l_ri,(R4 d, IMM i))
MIDFUNC(2,test_l_rr,(R4 d, R4 s))
{
CLOBBER_TEST;
d=readreg(d,4);
s=readreg(s,4);
raw_test_l_rr(d,s);;
unlock2(d);
unlock2(s);
}
MENDFUNC(2,test_l_rr,(R4 d, R4 s))
MIDFUNC(2,test_w_rr,(R2 d, R2 s))
{
CLOBBER_TEST;
d=readreg(d,2);
s=readreg(s,2);
raw_test_w_rr(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,test_w_rr,(R2 d, R2 s))
MIDFUNC(2,test_b_rr,(R1 d, R1 s))
{
CLOBBER_TEST;
d=readreg(d,1);
s=readreg(s,1);
raw_test_b_rr(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,test_b_rr,(R1 d, R1 s))
MIDFUNC(2,and_l_ri,(RW4 d, IMM i))
{
if (isconst(d) && !needflags) {
live.state[d].val &= i;
return;
}
CLOBBER_AND;
d=rmw(d,4,4);
raw_and_l_ri(d,i);
unlock2(d);
}
MENDFUNC(2,and_l_ri,(RW4 d, IMM i))
MIDFUNC(2,and_l,(RW4 d, R4 s))
{
CLOBBER_AND;
s=readreg(s,4);
d=rmw(d,4,4);
raw_and_l(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,and_l,(RW4 d, R4 s))
MIDFUNC(2,and_w,(RW2 d, R2 s))
{
CLOBBER_AND;
s=readreg(s,2);
d=rmw(d,2,2);
raw_and_w(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,and_w,(RW2 d, R2 s))
MIDFUNC(2,and_b,(RW1 d, R1 s))
{
CLOBBER_AND;
s=readreg(s,1);
d=rmw(d,1,1);
raw_and_b(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,and_b,(RW1 d, R1 s))
// gb-- used for making an fpcr value in compemu_fpp.cpp
MIDFUNC(2,or_l_rm,(RW4 d, IMM s))
{
CLOBBER_OR;
d=rmw(d,4,4);
raw_or_l_rm(d,s);
unlock2(d);
}
MENDFUNC(2,or_l_rm,(RW4 d, IMM s))
MIDFUNC(2,or_l_ri,(RW4 d, IMM i))
{
if (isconst(d) && !needflags) {
live.state[d].val|=i;
return;
}
CLOBBER_OR;
d=rmw(d,4,4);
raw_or_l_ri(d,i);
unlock2(d);
}
MENDFUNC(2,or_l_ri,(RW4 d, IMM i))
MIDFUNC(2,or_l,(RW4 d, R4 s))
{
if (isconst(d) && isconst(s) && !needflags) {
live.state[d].val|=live.state[s].val;
return;
}
CLOBBER_OR;
s=readreg(s,4);
d=rmw(d,4,4);
raw_or_l(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,or_l,(RW4 d, R4 s))
MIDFUNC(2,or_w,(RW2 d, R2 s))
{
CLOBBER_OR;
s=readreg(s,2);
d=rmw(d,2,2);
raw_or_w(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,or_w,(RW2 d, R2 s))
MIDFUNC(2,or_b,(RW1 d, R1 s))
{
CLOBBER_OR;
s=readreg(s,1);
d=rmw(d,1,1);
raw_or_b(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,or_b,(RW1 d, R1 s))
MIDFUNC(2,adc_l,(RW4 d, R4 s))
{
CLOBBER_ADC;
s=readreg(s,4);
d=rmw(d,4,4);
raw_adc_l(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,adc_l,(RW4 d, R4 s))
MIDFUNC(2,adc_w,(RW2 d, R2 s))
{
CLOBBER_ADC;
s=readreg(s,2);
d=rmw(d,2,2);
raw_adc_w(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,adc_w,(RW2 d, R2 s))
MIDFUNC(2,adc_b,(RW1 d, R1 s))
{
CLOBBER_ADC;
s=readreg(s,1);
d=rmw(d,1,1);
raw_adc_b(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,adc_b,(RW1 d, R1 s))
MIDFUNC(2,add_l,(RW4 d, R4 s))
{
if (isconst(s)) {
COMPCALL(add_l_ri)(d,live.state[s].val);
return;
}
CLOBBER_ADD;
s=readreg(s,4);
d=rmw(d,4,4);
raw_add_l(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,add_l,(RW4 d, R4 s))
MIDFUNC(2,add_w,(RW2 d, R2 s))
{
if (isconst(s)) {
COMPCALL(add_w_ri)(d,(uae_u16)live.state[s].val);
return;
}
CLOBBER_ADD;
s=readreg(s,2);
d=rmw(d,2,2);
raw_add_w(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,add_w,(RW2 d, R2 s))
MIDFUNC(2,add_b,(RW1 d, R1 s))
{
if (isconst(s)) {
COMPCALL(add_b_ri)(d,(uae_u8)live.state[s].val);
return;
}
CLOBBER_ADD;
s=readreg(s,1);
d=rmw(d,1,1);
raw_add_b(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,add_b,(RW1 d, R1 s))
MIDFUNC(2,sub_l_ri,(RW4 d, IMM i))
{
if (!i && !needflags)
return;
if (isconst(d) && !needflags) {
live.state[d].val-=i;
return;
}
#if USE_OFFSET
if (!needflags) {
add_offset(d,-i);
return;
}
#endif
CLOBBER_SUB;
d=rmw(d,4,4);
raw_sub_l_ri(d,i);
unlock2(d);
}
MENDFUNC(2,sub_l_ri,(RW4 d, IMM i))
MIDFUNC(2,sub_w_ri,(RW2 d, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SUB;
d=rmw(d,2,2);
raw_sub_w_ri(d,i);
unlock2(d);
}
MENDFUNC(2,sub_w_ri,(RW2 d, IMM i))
MIDFUNC(2,sub_b_ri,(RW1 d, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_SUB;
d=rmw(d,1,1);
raw_sub_b_ri(d,i);
unlock2(d);
}
MENDFUNC(2,sub_b_ri,(RW1 d, IMM i))
MIDFUNC(2,add_l_ri,(RW4 d, IMM i))
{
if (!i && !needflags)
return;
if (isconst(d) && !needflags) {
live.state[d].val+=i;
return;
}
#if USE_OFFSET
if (!needflags) {
add_offset(d,i);
return;
}
#endif
CLOBBER_ADD;
d=rmw(d,4,4);
raw_add_l_ri(d,i);
unlock2(d);
}
MENDFUNC(2,add_l_ri,(RW4 d, IMM i))
MIDFUNC(2,add_w_ri,(RW2 d, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_ADD;
d=rmw(d,2,2);
raw_add_w_ri(d,i);
unlock2(d);
}
MENDFUNC(2,add_w_ri,(RW2 d, IMM i))
MIDFUNC(2,add_b_ri,(RW1 d, IMM i))
{
if (!i && !needflags)
return;
CLOBBER_ADD;
d=rmw(d,1,1);
raw_add_b_ri(d,i);
unlock2(d);
}
MENDFUNC(2,add_b_ri,(RW1 d, IMM i))
MIDFUNC(2,sbb_l,(RW4 d, R4 s))
{
CLOBBER_SBB;
s=readreg(s,4);
d=rmw(d,4,4);
raw_sbb_l(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,sbb_l,(RW4 d, R4 s))
MIDFUNC(2,sbb_w,(RW2 d, R2 s))
{
CLOBBER_SBB;
s=readreg(s,2);
d=rmw(d,2,2);
raw_sbb_w(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,sbb_w,(RW2 d, R2 s))
MIDFUNC(2,sbb_b,(RW1 d, R1 s))
{
CLOBBER_SBB;
s=readreg(s,1);
d=rmw(d,1,1);
raw_sbb_b(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,sbb_b,(RW1 d, R1 s))
MIDFUNC(2,sub_l,(RW4 d, R4 s))
{
if (isconst(s)) {
COMPCALL(sub_l_ri)(d,live.state[s].val);
return;
}
CLOBBER_SUB;
s=readreg(s,4);
d=rmw(d,4,4);
raw_sub_l(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,sub_l,(RW4 d, R4 s))
MIDFUNC(2,sub_w,(RW2 d, R2 s))
{
if (isconst(s)) {
COMPCALL(sub_w_ri)(d,(uae_u16)live.state[s].val);
return;
}
CLOBBER_SUB;
s=readreg(s,2);
d=rmw(d,2,2);
raw_sub_w(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,sub_w,(RW2 d, R2 s))
MIDFUNC(2,sub_b,(RW1 d, R1 s))
{
if (isconst(s)) {
COMPCALL(sub_b_ri)(d,(uae_u8)live.state[s].val);
return;
}
CLOBBER_SUB;
s=readreg(s,1);
d=rmw(d,1,1);
raw_sub_b(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,sub_b,(RW1 d, R1 s))
MIDFUNC(2,cmp_l,(R4 d, R4 s))
{
CLOBBER_CMP;
s=readreg(s,4);
d=readreg(d,4);
raw_cmp_l(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,cmp_l,(R4 d, R4 s))
MIDFUNC(2,cmp_l_ri,(R4 r, IMM i))
{
CLOBBER_CMP;
r=readreg(r,4);
raw_cmp_l_ri(r,i);
unlock2(r);
}
MENDFUNC(2,cmp_l_ri,(R4 r, IMM i))
MIDFUNC(2,cmp_w,(R2 d, R2 s))
{
CLOBBER_CMP;
s=readreg(s,2);
d=readreg(d,2);
raw_cmp_w(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,cmp_w,(R2 d, R2 s))
MIDFUNC(2,cmp_b,(R1 d, R1 s))
{
CLOBBER_CMP;
s=readreg(s,1);
d=readreg(d,1);
raw_cmp_b(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,cmp_b,(R1 d, R1 s))
MIDFUNC(2,xor_l,(RW4 d, R4 s))
{
CLOBBER_XOR;
s=readreg(s,4);
d=rmw(d,4,4);
raw_xor_l(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,xor_l,(RW4 d, R4 s))
MIDFUNC(2,xor_w,(RW2 d, R2 s))
{
CLOBBER_XOR;
s=readreg(s,2);
d=rmw(d,2,2);
raw_xor_w(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,xor_w,(RW2 d, R2 s))
MIDFUNC(2,xor_b,(RW1 d, R1 s))
{
CLOBBER_XOR;
s=readreg(s,1);
d=rmw(d,1,1);
raw_xor_b(d,s);
unlock2(d);
unlock2(s);
}
MENDFUNC(2,xor_b,(RW1 d, R1 s))
MIDFUNC(5,call_r_11,(W4 out1, R4 r, R4 in1, IMM osize, IMM isize))
{
clobber_flags();
remove_all_offsets();
if (osize==4) {
if (out1!=in1 && out1!=r) {
COMPCALL(forget_about)(out1);
}
}
else {
tomem_c(out1);
}
in1=readreg_specific(in1,isize,REG_PAR1);
r=readreg(r,4);
prepare_for_call_1(); /* This should ensure that there won't be
any need for swapping nregs in prepare_for_call_2
*/
#if USE_NORMAL_CALLING_CONVENTION
raw_push_l_r(in1);
#endif
unlock2(in1);
unlock2(r);
prepare_for_call_2();
raw_call_r(r);
#if USE_NORMAL_CALLING_CONVENTION
raw_inc_sp(4);
#endif
live.nat[REG_RESULT].holds[0]=out1;
live.nat[REG_RESULT].nholds=1;
live.nat[REG_RESULT].touched=touchcnt++;
live.state[out1].realreg=REG_RESULT;
live.state[out1].realind=0;
live.state[out1].val=0;
live.state[out1].validsize=osize;
live.state[out1].dirtysize=osize;
set_status(out1,DIRTY);
}
MENDFUNC(5,call_r_11,(W4 out1, R4 r, R4 in1, IMM osize, IMM isize))
MIDFUNC(5,call_r_02,(R4 r, R4 in1, R4 in2, IMM isize1, IMM isize2))
{
clobber_flags();
remove_all_offsets();
in1=readreg_specific(in1,isize1,REG_PAR1);
in2=readreg_specific(in2,isize2,REG_PAR2);
r=readreg(r,4);
prepare_for_call_1(); /* This should ensure that there won't be
any need for swapping nregs in prepare_for_call_2
*/
#if USE_NORMAL_CALLING_CONVENTION
raw_push_l_r(in2);
raw_push_l_r(in1);
#endif
unlock2(r);
unlock2(in1);
unlock2(in2);
prepare_for_call_2();
raw_call_r(r);
#if USE_NORMAL_CALLING_CONVENTION
raw_inc_sp(8);
#endif
}
MENDFUNC(5,call_r_02,(R4 r, R4 in1, R4 in2, IMM isize1, IMM isize2))
/* forget_about() takes a mid-layer register */
MIDFUNC(1,forget_about,(W4 r))
{
if (isinreg(r))
disassociate(r);
live.state[r].val=0;
set_status(r,UNDEF);
}
MENDFUNC(1,forget_about,(W4 r))
MIDFUNC(0,nop,(void))
{
raw_nop();
}
MENDFUNC(0,nop,(void))
MIDFUNC(1,f_forget_about,(FW r))
{
if (f_isinreg(r))
f_disassociate(r);
live.fate[r].status=UNDEF;
}
MENDFUNC(1,f_forget_about,(FW r))
MIDFUNC(1,fmov_pi,(FW r))
{
r=f_writereg(r);
raw_fmov_pi(r);
f_unlock(r);
}
MENDFUNC(1,fmov_pi,(FW r))
MIDFUNC(1,fmov_log10_2,(FW r))
{
r=f_writereg(r);
raw_fmov_log10_2(r);
f_unlock(r);
}
MENDFUNC(1,fmov_log10_2,(FW r))
MIDFUNC(1,fmov_log2_e,(FW r))
{
r=f_writereg(r);
raw_fmov_log2_e(r);
f_unlock(r);
}
MENDFUNC(1,fmov_log2_e,(FW r))
MIDFUNC(1,fmov_loge_2,(FW r))
{
r=f_writereg(r);
raw_fmov_loge_2(r);
f_unlock(r);
}
MENDFUNC(1,fmov_loge_2,(FW r))
MIDFUNC(1,fmov_1,(FW r))
{
r=f_writereg(r);
raw_fmov_1(r);
f_unlock(r);
}
MENDFUNC(1,fmov_1,(FW r))
MIDFUNC(1,fmov_0,(FW r))
{
r=f_writereg(r);
raw_fmov_0(r);
f_unlock(r);
}
MENDFUNC(1,fmov_0,(FW r))
MIDFUNC(2,fmov_rm,(FW r, MEMR m))
{
r=f_writereg(r);
raw_fmov_rm(r,m);
f_unlock(r);
}
MENDFUNC(2,fmov_rm,(FW r, MEMR m))
MIDFUNC(2,fmovi_rm,(FW r, MEMR m))
{
r=f_writereg(r);
raw_fmovi_rm(r,m);
f_unlock(r);
}
MENDFUNC(2,fmovi_rm,(FW r, MEMR m))
MIDFUNC(2,fmovi_mr,(MEMW m, FR r))
{
r=f_readreg(r);
raw_fmovi_mr(m,r);
f_unlock(r);
}
MENDFUNC(2,fmovi_mr,(MEMW m, FR r))
MIDFUNC(2,fmovs_rm,(FW r, MEMR m))
{
r=f_writereg(r);
raw_fmovs_rm(r,m);
f_unlock(r);
}
MENDFUNC(2,fmovs_rm,(FW r, MEMR m))
MIDFUNC(2,fmovs_mr,(MEMW m, FR r))
{
r=f_readreg(r);
raw_fmovs_mr(m,r);
f_unlock(r);
}
MENDFUNC(2,fmovs_mr,(MEMW m, FR r))
MIDFUNC(2,fmov_ext_mr,(MEMW m, FR r))
{
r=f_readreg(r);
raw_fmov_ext_mr(m,r);
f_unlock(r);
}
MENDFUNC(2,fmov_ext_mr,(MEMW m, FR r))
MIDFUNC(2,fmov_mr,(MEMW m, FR r))
{
r=f_readreg(r);
raw_fmov_mr(m,r);
f_unlock(r);
}
MENDFUNC(2,fmov_mr,(MEMW m, FR r))
MIDFUNC(2,fmov_ext_rm,(FW r, MEMR m))
{
r=f_writereg(r);
raw_fmov_ext_rm(r,m);
f_unlock(r);
}
MENDFUNC(2,fmov_ext_rm,(FW r, MEMR m))
MIDFUNC(2,fmov_rr,(FW d, FR s))
{
if (d==s) { /* How pointless! */
return;
}
#if USE_F_ALIAS
f_disassociate(d);
s=f_readreg(s);
live.fate[d].realreg=s;
live.fate[d].realind=live.fat[s].nholds;
live.fate[d].status=DIRTY;
live.fat[s].holds[live.fat[s].nholds]=d;
live.fat[s].nholds++;
f_unlock(s);
#else
s=f_readreg(s);
d=f_writereg(d);
raw_fmov_rr(d,s);
f_unlock(s);
f_unlock(d);
#endif
}
MENDFUNC(2,fmov_rr,(FW d, FR s))
MIDFUNC(2,fldcw_m_indexed,(R4 index, IMM base))
{
index=readreg(index,4);
raw_fldcw_m_indexed(index,base);
unlock2(index);
}
MENDFUNC(2,fldcw_m_indexed,(R4 index, IMM base))
MIDFUNC(1,ftst_r,(FR r))
{
r=f_readreg(r);
raw_ftst_r(r);
f_unlock(r);
}
MENDFUNC(1,ftst_r,(FR r))
MIDFUNC(0,dont_care_fflags,(void))
{
f_disassociate(FP_RESULT);
}
MENDFUNC(0,dont_care_fflags,(void))
MIDFUNC(2,fsqrt_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_fsqrt_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fsqrt_rr,(FW d, FR s))
MIDFUNC(2,fabs_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_fabs_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fabs_rr,(FW d, FR s))
MIDFUNC(2,fsin_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_fsin_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fsin_rr,(FW d, FR s))
MIDFUNC(2,fcos_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_fcos_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fcos_rr,(FW d, FR s))
MIDFUNC(2,ftwotox_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_ftwotox_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,ftwotox_rr,(FW d, FR s))
MIDFUNC(2,fetox_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_fetox_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fetox_rr,(FW d, FR s))
MIDFUNC(2,frndint_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_frndint_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,frndint_rr,(FW d, FR s))
MIDFUNC(2,flog2_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_flog2_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,flog2_rr,(FW d, FR s))
MIDFUNC(2,fneg_rr,(FW d, FR s))
{
s=f_readreg(s);
d=f_writereg(d);
raw_fneg_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fneg_rr,(FW d, FR s))
MIDFUNC(2,fadd_rr,(FRW d, FR s))
{
s=f_readreg(s);
d=f_rmw(d);
raw_fadd_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fadd_rr,(FRW d, FR s))
MIDFUNC(2,fsub_rr,(FRW d, FR s))
{
s=f_readreg(s);
d=f_rmw(d);
raw_fsub_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fsub_rr,(FRW d, FR s))
MIDFUNC(2,fcmp_rr,(FR d, FR s))
{
d=f_readreg(d);
s=f_readreg(s);
raw_fcmp_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fcmp_rr,(FR d, FR s))
MIDFUNC(2,fdiv_rr,(FRW d, FR s))
{
s=f_readreg(s);
d=f_rmw(d);
raw_fdiv_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fdiv_rr,(FRW d, FR s))
MIDFUNC(2,frem_rr,(FRW d, FR s))
{
s=f_readreg(s);
d=f_rmw(d);
raw_frem_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,frem_rr,(FRW d, FR s))
MIDFUNC(2,frem1_rr,(FRW d, FR s))
{
s=f_readreg(s);
d=f_rmw(d);
raw_frem1_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,frem1_rr,(FRW d, FR s))
MIDFUNC(2,fmul_rr,(FRW d, FR s))
{
s=f_readreg(s);
d=f_rmw(d);
raw_fmul_rr(d,s);
f_unlock(s);
f_unlock(d);
}
MENDFUNC(2,fmul_rr,(FRW d, FR s))
/********************************************************************
* Support functions exposed to gencomp. CREATE time *
********************************************************************/
void set_zero(int r, int tmp)
{
if (setzflg_uses_bsf)
bsf_l_rr(r,r);
else
simulate_bsf(tmp,r);
}
int kill_rodent(int r)
{
return KILLTHERAT &&
have_rat_stall &&
(live.state[r].status==INMEM ||
live.state[r].status==CLEAN ||
live.state[r].status==ISCONST ||
live.state[r].dirtysize==4);
}
uae_u32 get_const(int r)
{
Dif (!isconst(r)) {
write_log("Register %d should be constant, but isn't\n",r);
abort();
}
return live.state[r].val;
}
void sync_m68k_pc(void)
{
if (m68k_pc_offset) {
add_l_ri(PC_P,m68k_pc_offset);
comp_pc_p+=m68k_pc_offset;
m68k_pc_offset=0;
}
}
/********************************************************************
* Scratch registers management *
********************************************************************/
struct scratch_t {
uae_u32 regs[VREGS];
fpu_register fregs[VFREGS];
};
static scratch_t scratch;
/********************************************************************
* Support functions exposed to newcpu *
********************************************************************/
static inline const char *str_on_off(bool b)
{
return b ? "on" : "off";
}
void compiler_init(void)
{
static bool initialized = false;
if (initialized)
return;
#if JIT_DEBUG
// JIT debug mode ?
JITDebug = PrefsFindBool("jitdebug");
#endif
write_log("<JIT compiler> : enable runtime disassemblers : %s\n", JITDebug ? "yes" : "no");
#ifdef USE_JIT_FPU
// Use JIT compiler for FPU instructions ?
avoid_fpu = !PrefsFindBool("jitfpu");
#else
// JIT FPU is always disabled
avoid_fpu = true;
#endif
write_log("<JIT compiler> : compile FPU instructions : %s\n", !avoid_fpu ? "yes" : "no");
// Get size of the translation cache (in KB)
cache_size = PrefsFindInt32("jitcachesize");
write_log("<JIT compiler> : requested translation cache size : %d KB\n", cache_size);
// Initialize target CPU (check for features, e.g. CMOV, rat stalls)
raw_init_cpu();
setzflg_uses_bsf = target_check_bsf();
write_log("<JIT compiler> : target processor has CMOV instructions : %s\n", have_cmov ? "yes" : "no");
write_log("<JIT compiler> : target processor can suffer from partial register stalls : %s\n", have_rat_stall ? "yes" : "no");
write_log("<JIT compiler> : alignment for loops, jumps are %d, %d\n", align_loops, align_jumps);
// Translation cache flush mechanism
lazy_flush = PrefsFindBool("jitlazyflush");
write_log("<JIT compiler> : lazy translation cache invalidation : %s\n", str_on_off(lazy_flush));
flush_icache = lazy_flush ? flush_icache_lazy : flush_icache_hard;
// Compiler features
write_log("<JIT compiler> : register aliasing : %s\n", str_on_off(1));
write_log("<JIT compiler> : FP register aliasing : %s\n", str_on_off(USE_F_ALIAS));
write_log("<JIT compiler> : lazy constant offsetting : %s\n", str_on_off(USE_OFFSET));
#if USE_INLINING
follow_const_jumps = PrefsFindBool("jitinline");
#endif
write_log("<JIT compiler> : translate through constant jumps : %s\n", str_on_off(follow_const_jumps));
write_log("<JIT compiler> : separate blockinfo allocation : %s\n", str_on_off(USE_SEPARATE_BIA));
// Build compiler tables
build_comp();
initialized = true;
#if PROFILE_UNTRANSLATED_INSNS
write_log("<JIT compiler> : gather statistics on untranslated insns count\n");
#endif
#if PROFILE_COMPILE_TIME
write_log("<JIT compiler> : gather statistics on translation time\n");
emul_start_time = clock();
#endif
}
void compiler_exit(void)
{
#if PROFILE_COMPILE_TIME
emul_end_time = clock();
#endif
// Deallocate translation cache
if (compiled_code) {
vm_release(compiled_code, cache_size * 1024);
compiled_code = 0;
}
// Deallocate popallspace
if (popallspace) {
vm_release(popallspace, POPALLSPACE_SIZE);
popallspace = 0;
}
#if PROFILE_COMPILE_TIME
write_log("### Compile Block statistics\n");
write_log("Number of calls to compile_block : %d\n", compile_count);
uae_u32 emul_time = emul_end_time - emul_start_time;
write_log("Total emulation time : %.1f sec\n", double(emul_time)/double(CLOCKS_PER_SEC));
write_log("Total compilation time : %.1f sec (%.1f%%)\n", double(compile_time)/double(CLOCKS_PER_SEC),
100.0*double(compile_time)/double(emul_time));
write_log("\n");
#endif
#if PROFILE_UNTRANSLATED_INSNS
uae_u64 untranslated_count = 0;
for (int i = 0; i < 65536; i++) {
opcode_nums[i] = i;
untranslated_count += raw_cputbl_count[i];
}
write_log("Sorting out untranslated instructions count...\n");
qsort(opcode_nums, 65536, sizeof(uae_u16), untranslated_compfn);
write_log("\nRank Opc Count Name\n");
for (int i = 0; i < untranslated_top_ten; i++) {
uae_u32 count = raw_cputbl_count[opcode_nums[i]];
struct instr *dp;
struct mnemolookup *lookup;
if (!count)
break;
dp = table68k + opcode_nums[i];
for (lookup = lookuptab; lookup->mnemo != dp->mnemo; lookup++)
;
write_log("%03d: %04x %10lu %s\n", i, opcode_nums[i], count, lookup->name);
}
#endif
#if RECORD_REGISTER_USAGE
int reg_count_ids[16];
uint64 tot_reg_count = 0;
for (int i = 0; i < 16; i++) {
reg_count_ids[i] = i;
tot_reg_count += reg_count[i];
}
qsort(reg_count_ids, 16, sizeof(int), reg_count_compare);
uint64 cum_reg_count = 0;
for (int i = 0; i < 16; i++) {
int r = reg_count_ids[i];
cum_reg_count += reg_count[r];
printf("%c%d : %16ld %2.1f%% [%2.1f]\n", r < 8 ? 'D' : 'A', r % 8,
reg_count[r],
100.0*double(reg_count[r])/double(tot_reg_count),
100.0*double(cum_reg_count)/double(tot_reg_count));
}
#endif
}
bool compiler_use_jit(void)
{
// Check for the "jit" prefs item
if (!PrefsFindBool("jit"))
return false;
// Don't use JIT if translation cache size is less then MIN_CACHE_SIZE KB
if (PrefsFindInt32("jitcachesize") < MIN_CACHE_SIZE) {
write_log("<JIT compiler> : translation cache size is less than %d KB. Disabling JIT.\n", MIN_CACHE_SIZE);
return false;
}
// Enable JIT for 68020+ emulation only
if (CPUType < 2) {
write_log("<JIT compiler> : JIT is not supported in 680%d0 emulation mode, disabling.\n", CPUType);
return false;
}
return true;
}
void init_comp(void)
{
int i;
uae_s8* cb=can_byte;
uae_s8* cw=can_word;
uae_s8* au=always_used;
#if RECORD_REGISTER_USAGE
for (i=0;i<16;i++)
reg_count_local[i] = 0;
#endif
for (i=0;i<VREGS;i++) {
live.state[i].realreg=-1;
live.state[i].needflush=NF_SCRATCH;
live.state[i].val=0;
set_status(i,UNDEF);
}
for (i=0;i<VFREGS;i++) {
live.fate[i].status=UNDEF;
live.fate[i].realreg=-1;
live.fate[i].needflush=NF_SCRATCH;
}
for (i=0;i<VREGS;i++) {
if (i<16) { /* First 16 registers map to 68k registers */
live.state[i].mem=((uae_u32*)®s)+i;
live.state[i].needflush=NF_TOMEM;
set_status(i,INMEM);
}
else
live.state[i].mem=scratch.regs+i;
}
live.state[PC_P].mem=(uae_u32*)&(regs.pc_p);
live.state[PC_P].needflush=NF_TOMEM;
set_const(PC_P,(uintptr)comp_pc_p);
live.state[FLAGX].mem=(uae_u32*)&(regflags.x);
live.state[FLAGX].needflush=NF_TOMEM;
set_status(FLAGX,INMEM);
live.state[FLAGTMP].mem=(uae_u32*)&(regflags.cznv);
live.state[FLAGTMP].needflush=NF_TOMEM;
set_status(FLAGTMP,INMEM);
live.state[NEXT_HANDLER].needflush=NF_HANDLER;
set_status(NEXT_HANDLER,UNDEF);
for (i=0;i<VFREGS;i++) {
if (i<8) { /* First 8 registers map to 68k FPU registers */
live.fate[i].mem=(uae_u32*)fpu_register_address(i);
live.fate[i].needflush=NF_TOMEM;
live.fate[i].status=INMEM;
}
else if (i==FP_RESULT) {
live.fate[i].mem=(uae_u32*)(&fpu.result);
live.fate[i].needflush=NF_TOMEM;
live.fate[i].status=INMEM;
}
else
live.fate[i].mem=(uae_u32*)(&scratch.fregs[i]);
}
for (i=0;i<N_REGS;i++) {
live.nat[i].touched=0;
live.nat[i].nholds=0;
live.nat[i].locked=0;
if (*cb==i) {
live.nat[i].canbyte=1; cb++;
} else live.nat[i].canbyte=0;
if (*cw==i) {
live.nat[i].canword=1; cw++;
} else live.nat[i].canword=0;
if (*au==i) {
live.nat[i].locked=1; au++;
}
}
for (i=0;i<N_FREGS;i++) {
live.fat[i].touched=0;
live.fat[i].nholds=0;
live.fat[i].locked=0;
}
touchcnt=1;
m68k_pc_offset=0;
live.flags_in_flags=TRASH;
live.flags_on_stack=VALID;
live.flags_are_important=1;
raw_fp_init();
}
/* Only do this if you really mean it! The next call should be to init!*/
void flush(int save_regs)
{
int fi,i;
log_flush();
flush_flags(); /* low level */
sync_m68k_pc(); /* mid level */
if (save_regs) {
for (i=0;i<VFREGS;i++) {
if (live.fate[i].needflush==NF_SCRATCH ||
live.fate[i].status==CLEAN) {
f_disassociate(i);
}
}
for (i=0;i<VREGS;i++) {
if (live.state[i].needflush==NF_TOMEM) {
switch(live.state[i].status) {
case INMEM:
if (live.state[i].val) {
raw_add_l_mi((uintptr)live.state[i].mem,live.state[i].val);
log_vwrite(i);
live.state[i].val=0;
}
break;
case CLEAN:
case DIRTY:
remove_offset(i,-1); tomem(i); break;
case ISCONST:
if (i!=PC_P)
writeback_const(i);
break;
default: break;
}
Dif (live.state[i].val && i!=PC_P) {
write_log("Register %d still has val %x\n",
i,live.state[i].val);
}
}
}
for (i=0;i<VFREGS;i++) {
if (live.fate[i].needflush==NF_TOMEM &&
live.fate[i].status==DIRTY) {
f_evict(i);
}
}
raw_fp_cleanup_drop();
}
if (needflags) {
write_log("Warning! flush with needflags=1!\n");
}
}
static void flush_keepflags(void)
{
int fi,i;
for (i=0;i<VFREGS;i++) {
if (live.fate[i].needflush==NF_SCRATCH ||
live.fate[i].status==CLEAN) {
f_disassociate(i);
}
}
for (i=0;i<VREGS;i++) {
if (live.state[i].needflush==NF_TOMEM) {
switch(live.state[i].status) {
case INMEM:
/* Can't adjust the offset here --- that needs "add" */
break;
case CLEAN:
case DIRTY:
remove_offset(i,-1); tomem(i); break;
case ISCONST:
if (i!=PC_P)
writeback_const(i);
break;
default: break;
}
}
}
for (i=0;i<VFREGS;i++) {
if (live.fate[i].needflush==NF_TOMEM &&
live.fate[i].status==DIRTY) {
f_evict(i);
}
}
raw_fp_cleanup_drop();
}
void freescratch(void)
{
int i;
for (i=0;i<N_REGS;i++)
if (live.nat[i].locked && i!=4)
write_log("Warning! %d is locked\n",i);
for (i=0;i<VREGS;i++)
if (live.state[i].needflush==NF_SCRATCH) {
forget_about(i);
}
for (i=0;i<VFREGS;i++)
if (live.fate[i].needflush==NF_SCRATCH) {
f_forget_about(i);
}
}
/********************************************************************
* Support functions, internal *
********************************************************************/
static void align_target(uae_u32 a)
{
if (!a)
return;
if (tune_nop_fillers)
raw_emit_nop_filler(a - (((uintptr)target) & (a - 1)));
else {
/* Fill with NOPs --- makes debugging with gdb easier */
while ((uintptr)target&(a-1))
*target++=0x90;
}
}
static __inline__ int isinrom(uintptr addr)
{
return ((addr >= (uintptr)ROMBaseHost) && (addr < (uintptr)ROMBaseHost + ROMSize));
}
static void flush_all(void)
{
int i;
log_flush();
for (i=0;i<VREGS;i++)
if (live.state[i].status==DIRTY) {
if (!call_saved[live.state[i].realreg]) {
tomem(i);
}
}
for (i=0;i<VFREGS;i++)
if (f_isinreg(i))
f_evict(i);
raw_fp_cleanup_drop();
}
/* Make sure all registers that will get clobbered by a call are
save and sound in memory */
static void prepare_for_call_1(void)
{
flush_all(); /* If there are registers that don't get clobbered,
* we should be a bit more selective here */
}
/* We will call a C routine in a moment. That will clobber all registers,
so we need to disassociate everything */
static void prepare_for_call_2(void)
{
int i;
for (i=0;i<N_REGS;i++)
if (!call_saved[i] && live.nat[i].nholds>0)
free_nreg(i);
for (i=0;i<N_FREGS;i++)
if (live.fat[i].nholds>0)
f_free_nreg(i);
live.flags_in_flags=TRASH; /* Note: We assume we already rescued the
flags at the very start of the call_r
functions! */
}
/********************************************************************
* Memory access and related functions, CREATE time *
********************************************************************/
void register_branch(uae_u32 not_taken, uae_u32 taken, uae_u8 cond)
{
next_pc_p=not_taken;
taken_pc_p=taken;
branch_cc=cond;
}
static uae_u32 get_handler_address(uae_u32 addr)
{
uae_u32 cl=cacheline(addr);
blockinfo* bi=get_blockinfo_addr_new((void*)(uintptr)addr,0);
return (uintptr)&(bi->direct_handler_to_use);
}
static uae_u32 get_handler(uae_u32 addr)
{
uae_u32 cl=cacheline(addr);
blockinfo* bi=get_blockinfo_addr_new((void*)(uintptr)addr,0);
return (uintptr)bi->direct_handler_to_use;
}
static void load_handler(int reg, uae_u32 addr)
{
mov_l_rm(reg,get_handler_address(addr));
}
/* This version assumes that it is writing *real* memory, and *will* fail
* if that assumption is wrong! No branches, no second chances, just
* straight go-for-it attitude */
static void writemem_real(int address, int source, int size, int tmp, int clobber)
{
int f=tmp;
if (clobber)
f=source;
switch(size) {
case 1: mov_b_bRr(address,source,MEMBaseDiff); break;
case 2: mov_w_rr(f,source); bswap_16(f); mov_w_bRr(address,f,MEMBaseDiff); break;
case 4: mov_l_rr(f,source); bswap_32(f); mov_l_bRr(address,f,MEMBaseDiff); break;
}
forget_about(tmp);
forget_about(f);
}
void writebyte(int address, int source, int tmp)
{
writemem_real(address,source,1,tmp,0);
}
static __inline__ void writeword_general(int address, int source, int tmp,
int clobber)
{
writemem_real(address,source,2,tmp,clobber);
}
void writeword_clobber(int address, int source, int tmp)
{
writeword_general(address,source,tmp,1);
}
void writeword(int address, int source, int tmp)
{
writeword_general(address,source,tmp,0);
}
static __inline__ void writelong_general(int address, int source, int tmp,
int clobber)
{
writemem_real(address,source,4,tmp,clobber);
}
void writelong_clobber(int address, int source, int tmp)
{
writelong_general(address,source,tmp,1);
}
void writelong(int address, int source, int tmp)
{
writelong_general(address,source,tmp,0);
}
/* This version assumes that it is reading *real* memory, and *will* fail
* if that assumption is wrong! No branches, no second chances, just
* straight go-for-it attitude */
static void readmem_real(int address, int dest, int size, int tmp)
{
int f=tmp;
if (size==4 && address!=dest)
f=dest;
switch(size) {
case 1: mov_b_brR(dest,address,MEMBaseDiff); break;
case 2: mov_w_brR(dest,address,MEMBaseDiff); bswap_16(dest); break;
case 4: mov_l_brR(dest,address,MEMBaseDiff); bswap_32(dest); break;
}
forget_about(tmp);
}
void readbyte(int address, int dest, int tmp)
{
readmem_real(address,dest,1,tmp);
}
void readword(int address, int dest, int tmp)
{
readmem_real(address,dest,2,tmp);
}
void readlong(int address, int dest, int tmp)
{
readmem_real(address,dest,4,tmp);
}
void get_n_addr(int address, int dest, int tmp)
{
// a is the register containing the virtual address
// after the offset had been fetched
int a=tmp;
// f is the register that will contain the offset
int f=tmp;
// a == f == tmp if (address == dest)
if (address!=dest) {
a=address;
f=dest;
}
#if REAL_ADDRESSING
mov_l_rr(dest, address);
#elif DIRECT_ADDRESSING
lea_l_brr(dest,address,MEMBaseDiff);
#endif
forget_about(tmp);
}
void get_n_addr_jmp(int address, int dest, int tmp)
{
/* For this, we need to get the same address as the rest of UAE
would --- otherwise we end up translating everything twice */
get_n_addr(address,dest,tmp);
}
/* base is a register, but dp is an actual value.
target is a register, as is tmp */
void calc_disp_ea_020(int base, uae_u32 dp, int target, int tmp)
{
int reg = (dp >> 12) & 15;
int regd_shift=(dp >> 9) & 3;
if (dp & 0x100) {
int ignorebase=(dp&0x80);
int ignorereg=(dp&0x40);
int addbase=0;
int outer=0;
if ((dp & 0x30) == 0x20) addbase = (uae_s32)(uae_s16)comp_get_iword((m68k_pc_offset+=2)-2);
if ((dp & 0x30) == 0x30) addbase = comp_get_ilong((m68k_pc_offset+=4)-4);
if ((dp & 0x3) == 0x2) outer = (uae_s32)(uae_s16)comp_get_iword((m68k_pc_offset+=2)-2);
if ((dp & 0x3) == 0x3) outer = comp_get_ilong((m68k_pc_offset+=4)-4);
if ((dp & 0x4) == 0) { /* add regd *before* the get_long */
if (!ignorereg) {
if ((dp & 0x800) == 0)
sign_extend_16_rr(target,reg);
else
mov_l_rr(target,reg);
shll_l_ri(target,regd_shift);
}
else
mov_l_ri(target,0);
/* target is now regd */
if (!ignorebase)
add_l(target,base);
add_l_ri(target,addbase);
if (dp&0x03) readlong(target,target,tmp);
} else { /* do the getlong first, then add regd */
if (!ignorebase) {
mov_l_rr(target,base);
add_l_ri(target,addbase);
}
else
mov_l_ri(target,addbase);
if (dp&0x03) readlong(target,target,tmp);
if (!ignorereg) {
if ((dp & 0x800) == 0)
sign_extend_16_rr(tmp,reg);
else
mov_l_rr(tmp,reg);
shll_l_ri(tmp,regd_shift);
/* tmp is now regd */
add_l(target,tmp);
}
}
add_l_ri(target,outer);
}
else { /* 68000 version */
if ((dp & 0x800) == 0) { /* Sign extend */
sign_extend_16_rr(target,reg);
lea_l_brr_indexed(target,base,target,1<<regd_shift,(uae_s32)((uae_s8)dp));
}
else {
lea_l_brr_indexed(target,base,reg,1<<regd_shift,(uae_s32)((uae_s8)dp));
}
}
forget_about(tmp);
}
void set_cache_state(int enabled)
{
if (enabled!=letit)
flush_icache_hard(77);
letit=enabled;
}
int get_cache_state(void)
{
return letit;
}
uae_u32 get_jitted_size(void)
{
if (compiled_code)
return current_compile_p-compiled_code;
return 0;
}
const int CODE_ALLOC_MAX_ATTEMPTS = 10;
const int CODE_ALLOC_BOUNDARIES = 128 * 1024; // 128 KB
static uint8 *do_alloc_code(uint32 size, int depth)
{
#if defined(__linux__) && 0
/*
This is a really awful hack that is known to work on Linux at
least.
The trick here is to make sure the allocated cache is nearby
code segment, and more precisely in the positive half of a
32-bit address space. i.e. addr < 0x80000000. Actually, it
turned out that a 32-bit binary run on AMD64 yields a cache
allocated around 0xa0000000, thus causing some troubles when
translating addresses from m68k to x86.
*/
static uint8 * code_base = NULL;
if (code_base == NULL) {
uintptr page_size = getpagesize();
uintptr boundaries = CODE_ALLOC_BOUNDARIES;
if (boundaries < page_size)
boundaries = page_size;
code_base = (uint8 *)sbrk(0);
for (int attempts = 0; attempts < CODE_ALLOC_MAX_ATTEMPTS; attempts++) {
if (vm_acquire_fixed(code_base, size) == 0) {
uint8 *code = code_base;
code_base += size;
return code;
}
code_base += boundaries;
}
return NULL;
}
if (vm_acquire_fixed(code_base, size) == 0) {
uint8 *code = code_base;
code_base += size;
return code;
}
if (depth >= CODE_ALLOC_MAX_ATTEMPTS)
return NULL;
return do_alloc_code(size, depth + 1);
#else
uint8 *code = (uint8 *)vm_acquire(size);
return code == VM_MAP_FAILED ? NULL : code;
#endif
}
static inline uint8 *alloc_code(uint32 size)
{
uint8 *ptr = do_alloc_code(size, 0);
/* allocated code must fit in 32-bit boundaries */
assert((uintptr)ptr <= 0xffffffff);
return ptr;
}
void alloc_cache(void)
{
if (compiled_code) {
flush_icache_hard(6);
vm_release(compiled_code, cache_size * 1024);
compiled_code = 0;
}
if (cache_size == 0)
return;
while (!compiled_code && cache_size) {
if ((compiled_code = alloc_code(cache_size * 1024)) == NULL) {
compiled_code = 0;
cache_size /= 2;
}
}
vm_protect(compiled_code, cache_size * 1024, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE);
if (compiled_code) {
write_log("<JIT compiler> : actual translation cache size : %d KB at 0x%08X\n", cache_size, compiled_code);
max_compile_start = compiled_code + cache_size*1024 - BYTES_PER_INST;
current_compile_p = compiled_code;
current_cache_size = 0;
}
}
extern void op_illg_1 (uae_u32 opcode) REGPARAM;
static void calc_checksum(blockinfo* bi, uae_u32* c1, uae_u32* c2)
{
uae_u32 k1 = 0;
uae_u32 k2 = 0;
#if USE_CHECKSUM_INFO
checksum_info *csi = bi->csi;
Dif(!csi) abort();
while (csi) {
uae_s32 len = csi->length;
uintptr tmp = (uintptr)csi->start_p;
#else
uae_s32 len = bi->len;
uintptr tmp = (uintptr)bi->min_pcp;
#endif
uae_u32*pos;
len += (tmp & 3);
tmp &= ~((uintptr)3);
pos = (uae_u32 *)tmp;
if (len >= 0 && len <= MAX_CHECKSUM_LEN) {
while (len > 0) {
k1 += *pos;
k2 ^= *pos;
pos++;
len -= 4;
}
}
#if USE_CHECKSUM_INFO
csi = csi->next;
}
#endif
*c1 = k1;
*c2 = k2;
}
#if 0
static void show_checksum(CSI_TYPE* csi)
{
uae_u32 k1=0;
uae_u32 k2=0;
uae_s32 len=CSI_LENGTH(csi);
uae_u32 tmp=(uintptr)CSI_START_P(csi);
uae_u32* pos;
len+=(tmp&3);
tmp&=(~3);
pos=(uae_u32*)tmp;
if (len<0 || len>MAX_CHECKSUM_LEN) {
return;
}
else {
while (len>0) {
write_log("%08x ",*pos);
pos++;
len-=4;
}
write_log(" bla\n");
}
}
#endif
int check_for_cache_miss(void)
{
blockinfo* bi=get_blockinfo_addr(regs.pc_p);
if (bi) {
int cl=cacheline(regs.pc_p);
if (bi!=cache_tags[cl+1].bi) {
raise_in_cl_list(bi);
return 1;
}
}
return 0;
}
static void recompile_block(void)
{
/* An existing block's countdown code has expired. We need to make
sure that execute_normal doesn't refuse to recompile due to a
perceived cache miss... */
blockinfo* bi=get_blockinfo_addr(regs.pc_p);
Dif (!bi)
abort();
raise_in_cl_list(bi);
execute_normal();
return;
}
static void cache_miss(void)
{
blockinfo* bi=get_blockinfo_addr(regs.pc_p);
uae_u32 cl=cacheline(regs.pc_p);
blockinfo* bi2=get_blockinfo(cl);
if (!bi) {
execute_normal(); /* Compile this block now */
return;
}
Dif (!bi2 || bi==bi2) {
write_log("Unexplained cache miss %p %p\n",bi,bi2);
abort();
}
raise_in_cl_list(bi);
return;
}
static int called_check_checksum(blockinfo* bi);
static inline int block_check_checksum(blockinfo* bi)
{
uae_u32 c1,c2;
bool isgood;
if (bi->status!=BI_NEED_CHECK)
return 1; /* This block is in a checked state */
checksum_count++;
if (bi->c1 || bi->c2)
calc_checksum(bi,&c1,&c2);
else {
c1=c2=1; /* Make sure it doesn't match */
}
isgood=(c1==bi->c1 && c2==bi->c2);
if (isgood) {
/* This block is still OK. So we reactivate. Of course, that
means we have to move it into the needs-to-be-flushed list */
bi->handler_to_use=bi->handler;
set_dhtu(bi,bi->direct_handler);
bi->status=BI_CHECKING;
isgood=called_check_checksum(bi);
}
if (isgood) {
/* write_log("reactivate %p/%p (%x %x/%x %x)\n",bi,bi->pc_p,
c1,c2,bi->c1,bi->c2);*/
remove_from_list(bi);
add_to_active(bi);
raise_in_cl_list(bi);
bi->status=BI_ACTIVE;
}
else {
/* This block actually changed. We need to invalidate it,
and set it up to be recompiled */
/* write_log("discard %p/%p (%x %x/%x %x)\n",bi,bi->pc_p,
c1,c2,bi->c1,bi->c2); */
invalidate_block(bi);
raise_in_cl_list(bi);
}
return isgood;
}
static int called_check_checksum(blockinfo* bi)
{
dependency* x=bi->deplist;
int isgood=1;
int i;
for (i=0;i<2 && isgood;i++) {
if (bi->dep[i].jmp_off) {
isgood=block_check_checksum(bi->dep[i].target);
}
}
return isgood;
}
static void check_checksum(void)
{
blockinfo* bi=get_blockinfo_addr(regs.pc_p);
uae_u32 cl=cacheline(regs.pc_p);
blockinfo* bi2=get_blockinfo(cl);
/* These are not the droids you are looking for... */
if (!bi) {
/* Whoever is the primary target is in a dormant state, but
calling it was accidental, and we should just compile this
new block */
execute_normal();
return;
}
if (bi!=bi2) {
/* The block was hit accidentally, but it does exist. Cache miss */
cache_miss();
return;
}
if (!block_check_checksum(bi))
execute_normal();
}
static __inline__ void match_states(blockinfo* bi)
{
int i;
smallstate* s=&(bi->env);
if (bi->status==BI_NEED_CHECK) {
block_check_checksum(bi);
}
if (bi->status==BI_ACTIVE ||
bi->status==BI_FINALIZING) { /* Deal with the *promises* the
block makes (about not using
certain vregs) */
for (i=0;i<16;i++) {
if (s->virt[i]==L_UNNEEDED) {
// write_log("unneeded reg %d at %p\n",i,target);
COMPCALL(forget_about)(i); // FIXME
}
}
}
flush(1);
/* And now deal with the *demands* the block makes */
for (i=0;i<N_REGS;i++) {
int v=s->nat[i];
if (v>=0) {
// printf("Loading reg %d into %d at %p\n",v,i,target);
readreg_specific(v,4,i);
// do_load_reg(i,v);
// setlock(i);
}
}
for (i=0;i<N_REGS;i++) {
int v=s->nat[i];
if (v>=0) {
unlock2(i);
}
}
}
static __inline__ void create_popalls(void)
{
int i,r;
if ((popallspace = alloc_code(POPALLSPACE_SIZE)) == NULL) {
write_log("FATAL: Could not allocate popallspace!\n");
abort();
}
vm_protect(popallspace, POPALLSPACE_SIZE, VM_PAGE_READ | VM_PAGE_WRITE);
int stack_space = STACK_OFFSET;
for (i=0;i<N_REGS;i++) {
if (need_to_preserve[i])
stack_space += sizeof(void *);
}
stack_space %= STACK_ALIGN;
if (stack_space)
stack_space = STACK_ALIGN - stack_space;
current_compile_p=popallspace;
set_target(current_compile_p);
/* We need to guarantee 16-byte stack alignment on x86 at any point
within the JIT generated code. We have multiple exit points
possible but a single entry. A "jmp" is used so that we don't
have to generate stack alignment in generated code that has to
call external functions (e.g. a generic instruction handler).
In summary, JIT generated code is not leaf so we have to deal
with it here to maintain correct stack alignment. */
align_target(align_jumps);
current_compile_p=get_target();
pushall_call_handler=get_target();
for (i=N_REGS;i--;) {
if (need_to_preserve[i])
raw_push_l_r(i);
}
raw_dec_sp(stack_space);
r=REG_PC_TMP;
raw_mov_l_rm(r,(uintptr)®s.pc_p);
raw_and_l_ri(r,TAGMASK);
raw_jmp_m_indexed((uintptr)cache_tags,r,SIZEOF_VOID_P);
/* now the exit points */
align_target(align_jumps);
popall_do_nothing=get_target();
raw_inc_sp(stack_space);
for (i=0;i<N_REGS;i++) {
if (need_to_preserve[i])
raw_pop_l_r(i);
}
raw_jmp((uintptr)do_nothing);
align_target(align_jumps);
popall_execute_normal=get_target();
raw_inc_sp(stack_space);
for (i=0;i<N_REGS;i++) {
if (need_to_preserve[i])
raw_pop_l_r(i);
}
raw_jmp((uintptr)execute_normal);
align_target(align_jumps);
popall_cache_miss=get_target();
raw_inc_sp(stack_space);
for (i=0;i<N_REGS;i++) {
if (need_to_preserve[i])
raw_pop_l_r(i);
}
raw_jmp((uintptr)cache_miss);
align_target(align_jumps);
popall_recompile_block=get_target();
raw_inc_sp(stack_space);
for (i=0;i<N_REGS;i++) {
if (need_to_preserve[i])
raw_pop_l_r(i);
}
raw_jmp((uintptr)recompile_block);
align_target(align_jumps);
popall_exec_nostats=get_target();
raw_inc_sp(stack_space);
for (i=0;i<N_REGS;i++) {
if (need_to_preserve[i])
raw_pop_l_r(i);
}
raw_jmp((uintptr)exec_nostats);
align_target(align_jumps);
popall_check_checksum=get_target();
raw_inc_sp(stack_space);
for (i=0;i<N_REGS;i++) {
if (need_to_preserve[i])
raw_pop_l_r(i);
}
raw_jmp((uintptr)check_checksum);
// no need to further write into popallspace
vm_protect(popallspace, POPALLSPACE_SIZE, VM_PAGE_READ | VM_PAGE_EXECUTE);
}
static __inline__ void reset_lists(void)
{
int i;
for (i=0;i<MAX_HOLD_BI;i++)
hold_bi[i]=NULL;
active=NULL;
dormant=NULL;
}
static void prepare_block(blockinfo* bi)
{
int i;
set_target(current_compile_p);
align_target(align_jumps);
bi->direct_pen=(cpuop_func *)get_target();
raw_mov_l_rm(0,(uintptr)&(bi->pc_p));
raw_mov_l_mr((uintptr)®s.pc_p,0);
raw_jmp((uintptr)popall_execute_normal);
align_target(align_jumps);
bi->direct_pcc=(cpuop_func *)get_target();
raw_mov_l_rm(0,(uintptr)&(bi->pc_p));
raw_mov_l_mr((uintptr)®s.pc_p,0);
raw_jmp((uintptr)popall_check_checksum);
current_compile_p=get_target();
bi->deplist=NULL;
for (i=0;i<2;i++) {
bi->dep[i].prev_p=NULL;
bi->dep[i].next=NULL;
}
bi->env=default_ss;
bi->status=BI_INVALID;
bi->havestate=0;
//bi->env=empty_ss;
}
// OPCODE is in big endian format, use cft_map() beforehand, if needed.
static inline void reset_compop(int opcode)
{
compfunctbl[opcode] = NULL;
nfcompfunctbl[opcode] = NULL;
}
static int read_opcode(const char *p)
{
int opcode = 0;
for (int i = 0; i < 4; i++) {
int op = p[i];
switch (op) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
opcode = (opcode << 4) | (op - '0');
break;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
opcode = (opcode << 4) | ((op - 'a') + 10);
break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
opcode = (opcode << 4) | ((op - 'A') + 10);
break;
default:
return -1;
}
}
return opcode;
}
static bool merge_blacklist()
{
const char *blacklist = PrefsFindString("jitblacklist");
if (blacklist) {
const char *p = blacklist;
for (;;) {
if (*p == 0)
return true;
int opcode1 = read_opcode(p);
if (opcode1 < 0)
return false;
p += 4;
int opcode2 = opcode1;
if (*p == '-') {
p++;
opcode2 = read_opcode(p);
if (opcode2 < 0)
return false;
p += 4;
}
if (*p == 0 || *p == ',' || *p == ';') {
write_log("<JIT compiler> : blacklist opcodes : %04x-%04x\n", opcode1, opcode2);
for (int opcode = opcode1; opcode <= opcode2; opcode++)
reset_compop(cft_map(opcode));
if (*p == ',' || *p++ == ';')
continue;
return true;
}
return false;
}
}
return true;
}
void build_comp(void)
{
int i;
int jumpcount=0;
unsigned long opcode;
struct comptbl* tbl=op_smalltbl_0_comp_ff;
struct comptbl* nftbl=op_smalltbl_0_comp_nf;
int count;
int cpu_level = 0; // 68000 (default)
if (CPUType == 4)
cpu_level = 4; // 68040 with FPU
else {
if (FPUType)
cpu_level = 3; // 68020 with FPU
else if (CPUType >= 2)
cpu_level = 2; // 68020
else if (CPUType == 1)
cpu_level = 1;
}
struct cputbl *nfctbl = (
cpu_level == 4 ? op_smalltbl_0_nf
: cpu_level == 3 ? op_smalltbl_1_nf
: cpu_level == 2 ? op_smalltbl_2_nf
: cpu_level == 1 ? op_smalltbl_3_nf
: op_smalltbl_4_nf);
write_log ("<JIT compiler> : building compiler function tables\n");
for (opcode = 0; opcode < 65536; opcode++) {
reset_compop(opcode);
nfcpufunctbl[opcode] = op_illg_1;
prop[opcode].use_flags = 0x1f;
prop[opcode].set_flags = 0x1f;
prop[opcode].cflow = fl_trap; // ILLEGAL instructions do trap
}
for (i = 0; tbl[i].opcode < 65536; i++) {
int cflow = table68k[tbl[i].opcode].cflow;
if (follow_const_jumps && (tbl[i].specific & 16))
cflow = fl_const_jump;
else
cflow &= ~fl_const_jump;
prop[cft_map(tbl[i].opcode)].cflow = cflow;
int uses_fpu = tbl[i].specific & 32;
if (uses_fpu && avoid_fpu)
compfunctbl[cft_map(tbl[i].opcode)] = NULL;
else
compfunctbl[cft_map(tbl[i].opcode)] = tbl[i].handler;
}
for (i = 0; nftbl[i].opcode < 65536; i++) {
int uses_fpu = tbl[i].specific & 32;
if (uses_fpu && avoid_fpu)
nfcompfunctbl[cft_map(nftbl[i].opcode)] = NULL;
else
nfcompfunctbl[cft_map(nftbl[i].opcode)] = nftbl[i].handler;
nfcpufunctbl[cft_map(nftbl[i].opcode)] = nfctbl[i].handler;
}
for (i = 0; nfctbl[i].handler; i++) {
nfcpufunctbl[cft_map(nfctbl[i].opcode)] = nfctbl[i].handler;
}
for (opcode = 0; opcode < 65536; opcode++) {
compop_func *f;
compop_func *nff;
cpuop_func *nfcf;
int isaddx,cflow;
if (table68k[opcode].mnemo == i_ILLG || table68k[opcode].clev > cpu_level)
continue;
if (table68k[opcode].handler != -1) {
f = compfunctbl[cft_map(table68k[opcode].handler)];
nff = nfcompfunctbl[cft_map(table68k[opcode].handler)];
nfcf = nfcpufunctbl[cft_map(table68k[opcode].handler)];
cflow = prop[cft_map(table68k[opcode].handler)].cflow;
isaddx = prop[cft_map(table68k[opcode].handler)].is_addx;
prop[cft_map(opcode)].cflow = cflow;
prop[cft_map(opcode)].is_addx = isaddx;
compfunctbl[cft_map(opcode)] = f;
nfcompfunctbl[cft_map(opcode)] = nff;
Dif (nfcf == op_illg_1)
abort();
nfcpufunctbl[cft_map(opcode)] = nfcf;
}
prop[cft_map(opcode)].set_flags = table68k[opcode].flagdead;
prop[cft_map(opcode)].use_flags = table68k[opcode].flaglive;
/* Unconditional jumps don't evaluate condition codes, so they
* don't actually use any flags themselves */
if (prop[cft_map(opcode)].cflow & fl_const_jump)
prop[cft_map(opcode)].use_flags = 0;
}
for (i = 0; nfctbl[i].handler != NULL; i++) {
if (nfctbl[i].specific)
nfcpufunctbl[cft_map(tbl[i].opcode)] = nfctbl[i].handler;
}
/* Merge in blacklist */
if (!merge_blacklist())
write_log("<JIT compiler> : blacklist merge failure!\n");
count=0;
for (opcode = 0; opcode < 65536; opcode++) {
if (compfunctbl[cft_map(opcode)])
count++;
}
write_log("<JIT compiler> : supposedly %d compileable opcodes!\n",count);
/* Initialise state */
create_popalls();
alloc_cache();
reset_lists();
for (i=0;i<TAGSIZE;i+=2) {
cache_tags[i].handler=(cpuop_func *)popall_execute_normal;
cache_tags[i+1].bi=NULL;
}
#if 0
for (i=0;i<N_REGS;i++) {
empty_ss.nat[i].holds=-1;
empty_ss.nat[i].validsize=0;
empty_ss.nat[i].dirtysize=0;
}
#endif
for (i=0;i<VREGS;i++) {
empty_ss.virt[i]=L_NEEDED;
}
for (i=0;i<N_REGS;i++) {
empty_ss.nat[i]=L_UNKNOWN;
}
default_ss=empty_ss;
}
static void flush_icache_none(int n)
{
/* Nothing to do. */
}
static void flush_icache_hard(int n)
{
uae_u32 i;
blockinfo* bi, *dbi;
hard_flush_count++;
#if 0
write_log("Flush Icache_hard(%d/%x/%p), %u KB\n",
n,regs.pc,regs.pc_p,current_cache_size/1024);
current_cache_size = 0;
#endif
bi=active;
while(bi) {
cache_tags[cacheline(bi->pc_p)].handler=(cpuop_func *)popall_execute_normal;
cache_tags[cacheline(bi->pc_p)+1].bi=NULL;
dbi=bi; bi=bi->next;
free_blockinfo(dbi);
}
bi=dormant;
while(bi) {
cache_tags[cacheline(bi->pc_p)].handler=(cpuop_func *)popall_execute_normal;
cache_tags[cacheline(bi->pc_p)+1].bi=NULL;
dbi=bi; bi=bi->next;
free_blockinfo(dbi);
}
reset_lists();
if (!compiled_code)
return;
current_compile_p=compiled_code;
SPCFLAGS_SET( SPCFLAG_JIT_EXEC_RETURN ); /* To get out of compiled code */
}
/* "Soft flushing" --- instead of actually throwing everything away,
we simply mark everything as "needs to be checked".
*/
static inline void flush_icache_lazy(int n)
{
uae_u32 i;
blockinfo* bi;
blockinfo* bi2;
soft_flush_count++;
if (!active)
return;
bi=active;
while (bi) {
uae_u32 cl=cacheline(bi->pc_p);
if (bi->status==BI_INVALID ||
bi->status==BI_NEED_RECOMP) {
if (bi==cache_tags[cl+1].bi)
cache_tags[cl].handler=(cpuop_func *)popall_execute_normal;
bi->handler_to_use=(cpuop_func *)popall_execute_normal;
set_dhtu(bi,bi->direct_pen);
bi->status=BI_INVALID;
}
else {
if (bi==cache_tags[cl+1].bi)
cache_tags[cl].handler=(cpuop_func *)popall_check_checksum;
bi->handler_to_use=(cpuop_func *)popall_check_checksum;
set_dhtu(bi,bi->direct_pcc);
bi->status=BI_NEED_CHECK;
}
bi2=bi;
bi=bi->next;
}
/* bi2 is now the last entry in the active list */
bi2->next=dormant;
if (dormant)
dormant->prev_p=&(bi2->next);
dormant=active;
active->prev_p=&dormant;
active=NULL;
}
void flush_icache_range(uae_u8 *start_p, uae_u32 length)
{
if (!active)
return;
#if LAZY_FLUSH_ICACHE_RANGE
blockinfo *bi = active;
while (bi) {
#if USE_CHECKSUM_INFO
bool candidate = false;
for (checksum_info *csi = bi->csi; csi; csi = csi->next) {
if (((start_p - csi->start_p) < csi->length) ||
((csi->start_p - start_p) < length)) {
candidate = true;
break;
}
}
#else
// Assume system is consistent and would invalidate the right range
const bool candidate = (bi->pc_p - start_p) < length;
#endif
blockinfo *dbi = bi;
bi = bi->next;
if (candidate) {
uae_u32 cl = cacheline(dbi->pc_p);
if (dbi->status == BI_INVALID || dbi->status == BI_NEED_RECOMP) {
if (dbi == cache_tags[cl+1].bi)
cache_tags[cl].handler = (cpuop_func *)popall_execute_normal;
dbi->handler_to_use = (cpuop_func *)popall_execute_normal;
set_dhtu(dbi, dbi->direct_pen);
dbi->status = BI_INVALID;
}
else {
if (dbi == cache_tags[cl+1].bi)
cache_tags[cl].handler = (cpuop_func *)popall_check_checksum;
dbi->handler_to_use = (cpuop_func *)popall_check_checksum;
set_dhtu(dbi, dbi->direct_pcc);
dbi->status = BI_NEED_CHECK;
}
remove_from_list(dbi);
add_to_dormant(dbi);
}
}
return;
#endif
flush_icache(-1);
}
static void catastrophe(void)
{
abort();
}
int failure;
#define TARGET_M68K 0
#define TARGET_POWERPC 1
#define TARGET_X86 2
#define TARGET_X86_64 3
#if defined(i386) || defined(__i386__)
#define TARGET_NATIVE TARGET_X86
#endif
#if defined(powerpc) || defined(__powerpc__)
#define TARGET_NATIVE TARGET_POWERPC
#endif
#if defined(x86_64) || defined(__x86_64__)
#define TARGET_NATIVE TARGET_X86_64
#endif
#ifdef ENABLE_MON
static uae_u32 mon_read_byte_jit(uintptr addr)
{
uae_u8 *m = (uae_u8 *)addr;
return (uintptr)(*m);
}
static void mon_write_byte_jit(uintptr addr, uae_u32 b)
{
uae_u8 *m = (uae_u8 *)addr;
*m = b;
}
#endif
void disasm_block(int target, uint8 * start, size_t length)
{
if (!JITDebug)
return;
#if defined(JIT_DEBUG) && defined(ENABLE_MON)
char disasm_str[200];
sprintf(disasm_str, "%s $%x $%x",
target == TARGET_M68K ? "d68" :
target == TARGET_X86 ? "d86" :
target == TARGET_X86_64 ? "d8664" :
target == TARGET_POWERPC ? "d" : "x",
start, start + length - 1);
uae_u32 (*old_mon_read_byte)(uintptr) = mon_read_byte;
void (*old_mon_write_byte)(uintptr, uae_u32) = mon_write_byte;
mon_read_byte = mon_read_byte_jit;
mon_write_byte = mon_write_byte_jit;
char *arg[5] = {"mon", "-m", "-r", disasm_str, NULL};
mon(4, arg);
mon_read_byte = old_mon_read_byte;
mon_write_byte = old_mon_write_byte;
#endif
}
static void disasm_native_block(uint8 *start, size_t length)
{
disasm_block(TARGET_NATIVE, start, length);
}
static void disasm_m68k_block(uint8 *start, size_t length)
{
disasm_block(TARGET_M68K, start, length);
}
#ifdef HAVE_GET_WORD_UNSWAPPED
# define DO_GET_OPCODE(a) (do_get_mem_word_unswapped((uae_u16 *)(a)))
#else
# define DO_GET_OPCODE(a) (do_get_mem_word((uae_u16 *)(a)))
#endif
#if JIT_DEBUG
static uae_u8 *last_regs_pc_p = 0;
static uae_u8 *last_compiled_block_addr = 0;
void compiler_dumpstate(void)
{
if (!JITDebug)
return;
write_log("### Host addresses\n");
write_log("MEM_BASE : %x\n", MEMBaseDiff);
write_log("PC_P : %p\n", ®s.pc_p);
write_log("SPCFLAGS : %p\n", ®s.spcflags);
write_log("D0-D7 : %p-%p\n", ®s.regs[0], ®s.regs[7]);
write_log("A0-A7 : %p-%p\n", ®s.regs[8], ®s.regs[15]);
write_log("\n");
write_log("### M68k processor state\n");
m68k_dumpstate(0);
write_log("\n");
write_log("### Block in Mac address space\n");
write_log("M68K block : %p\n",
(void *)(uintptr)get_virtual_address(last_regs_pc_p));
write_log("Native block : %p (%d bytes)\n",
(void *)(uintptr)get_virtual_address(last_compiled_block_addr),
get_blockinfo_addr(last_regs_pc_p)->direct_handler_size);
write_log("\n");
}
#endif
static void compile_block(cpu_history* pc_hist, int blocklen)
{
if (letit && compiled_code) {
#if PROFILE_COMPILE_TIME
compile_count++;
clock_t start_time = clock();
#endif
#if JIT_DEBUG
bool disasm_block = false;
#endif
/* OK, here we need to 'compile' a block */
int i;
int r;
int was_comp=0;
uae_u8 liveflags[MAXRUN+1];
#if USE_CHECKSUM_INFO
bool trace_in_rom = isinrom((uintptr)pc_hist[0].location);
uintptr max_pcp=(uintptr)pc_hist[blocklen - 1].location;
uintptr min_pcp=max_pcp;
#else
uintptr max_pcp=(uintptr)pc_hist[0].location;
uintptr min_pcp=max_pcp;
#endif
uae_u32 cl=cacheline(pc_hist[0].location);
void* specflags=(void*)®s.spcflags;
blockinfo* bi=NULL;
blockinfo* bi2;
int extra_len=0;
redo_current_block=0;
if (current_compile_p>=max_compile_start)
flush_icache_hard(7);
alloc_blockinfos();
bi=get_blockinfo_addr_new(pc_hist[0].location,0);
bi2=get_blockinfo(cl);
optlev=bi->optlevel;
if (bi->status!=BI_INVALID) {
Dif (bi!=bi2) {
/* I don't think it can happen anymore. Shouldn't, in
any case. So let's make sure... */
write_log("WOOOWOO count=%d, ol=%d %p %p\n",
bi->count,bi->optlevel,bi->handler_to_use,
cache_tags[cl].handler);
abort();
}
Dif (bi->count!=-1 && bi->status!=BI_NEED_RECOMP) {
write_log("bi->count=%d, bi->status=%d\n",bi->count,bi->status);
/* What the heck? We are not supposed to be here! */
abort();
}
}
if (bi->count==-1) {
optlev++;
while (!optcount[optlev])
optlev++;
bi->count=optcount[optlev]-1;
}
current_block_pc_p=(uintptr)pc_hist[0].location;
remove_deps(bi); /* We are about to create new code */
bi->optlevel=optlev;
bi->pc_p=(uae_u8*)pc_hist[0].location;
#if USE_CHECKSUM_INFO
free_checksum_info_chain(bi->csi);
bi->csi = NULL;
#endif
liveflags[blocklen]=0x1f; /* All flags needed afterwards */
i=blocklen;
while (i--) {
uae_u16* currpcp=pc_hist[i].location;
uae_u32 op=DO_GET_OPCODE(currpcp);
#if USE_CHECKSUM_INFO
trace_in_rom = trace_in_rom && isinrom((uintptr)currpcp);
if (follow_const_jumps && is_const_jump(op)) {
checksum_info *csi = alloc_checksum_info();
csi->start_p = (uae_u8 *)min_pcp;
csi->length = max_pcp - min_pcp + LONGEST_68K_INST;
csi->next = bi->csi;
bi->csi = csi;
max_pcp = (uintptr)currpcp;
}
min_pcp = (uintptr)currpcp;
#else
if ((uintptr)currpcp<min_pcp)
min_pcp=(uintptr)currpcp;
if ((uintptr)currpcp>max_pcp)
max_pcp=(uintptr)currpcp;
#endif
liveflags[i]=((liveflags[i+1]&
(~prop[op].set_flags))|
prop[op].use_flags);
if (prop[op].is_addx && (liveflags[i+1]&FLAG_Z)==0)
liveflags[i]&= ~FLAG_Z;
}
#if USE_CHECKSUM_INFO
checksum_info *csi = alloc_checksum_info();
csi->start_p = (uae_u8 *)min_pcp;
csi->length = max_pcp - min_pcp + LONGEST_68K_INST;
csi->next = bi->csi;
bi->csi = csi;
#endif
bi->needed_flags=liveflags[0];
align_target(align_loops);
was_comp=0;
bi->direct_handler=(cpuop_func *)get_target();
set_dhtu(bi,bi->direct_handler);
bi->status=BI_COMPILING;
current_block_start_target=(uintptr)get_target();
log_startblock();
if (bi->count>=0) { /* Need to generate countdown code */
raw_mov_l_mi((uintptr)®s.pc_p,(uintptr)pc_hist[0].location);
raw_sub_l_mi((uintptr)&(bi->count),1);
raw_jl((uintptr)popall_recompile_block);
}
if (optlev==0) { /* No need to actually translate */
/* Execute normally without keeping stats */
raw_mov_l_mi((uintptr)®s.pc_p,(uintptr)pc_hist[0].location);
raw_jmp((uintptr)popall_exec_nostats);
}
else {
reg_alloc_run=0;
next_pc_p=0;
taken_pc_p=0;
branch_cc=0;
comp_pc_p=(uae_u8*)pc_hist[0].location;
init_comp();
was_comp=1;
#ifdef USE_CPU_EMUL_SERVICES
raw_sub_l_mi((uintptr)&emulated_ticks,blocklen);
raw_jcc_b_oponly(NATIVE_CC_GT);
uae_s8 *branchadd=(uae_s8*)get_target();
emit_byte(0);
raw_call((uintptr)cpu_do_check_ticks);
*branchadd=(uintptr)get_target()-((uintptr)branchadd+1);
#endif
#if JIT_DEBUG
if (JITDebug) {
raw_mov_l_mi((uintptr)&last_regs_pc_p,(uintptr)pc_hist[0].location);
raw_mov_l_mi((uintptr)&last_compiled_block_addr,current_block_start_target);
}
#endif
for (i=0;i<blocklen &&
get_target_noopt()<max_compile_start;i++) {
cpuop_func **cputbl;
compop_func **comptbl;
uae_u32 opcode=DO_GET_OPCODE(pc_hist[i].location);
needed_flags=(liveflags[i+1] & prop[opcode].set_flags);
if (!needed_flags) {
cputbl=nfcpufunctbl;
comptbl=nfcompfunctbl;
}
else {
cputbl=cpufunctbl;
comptbl=compfunctbl;
}
#if FLIGHT_RECORDER
{
mov_l_ri(S1, get_virtual_address((uae_u8 *)(pc_hist[i].location)) | 1);
clobber_flags();
remove_all_offsets();
int arg = readreg_specific(S1,4,REG_PAR1);
prepare_for_call_1();
unlock2(arg);
prepare_for_call_2();
raw_call((uintptr)m68k_record_step);
}
#endif
failure = 1; // gb-- defaults to failure state
if (comptbl[opcode] && optlev>1) {
failure=0;
if (!was_comp) {
comp_pc_p=(uae_u8*)pc_hist[i].location;
init_comp();
}
was_comp=1;
comptbl[opcode](opcode);
freescratch();
if (!(liveflags[i+1] & FLAG_CZNV)) {
/* We can forget about flags */
dont_care_flags();
}
#if INDIVIDUAL_INST
flush(1);
nop();
flush(1);
was_comp=0;
#endif
}
if (failure) {
if (was_comp) {
flush(1);
was_comp=0;
}
raw_mov_l_ri(REG_PAR1,(uae_u32)opcode);
#if USE_NORMAL_CALLING_CONVENTION
raw_push_l_r(REG_PAR1);
#endif
raw_mov_l_mi((uintptr)®s.pc_p,
(uintptr)pc_hist[i].location);
raw_call((uintptr)cputbl[opcode]);
#if PROFILE_UNTRANSLATED_INSNS
// raw_cputbl_count[] is indexed with plain opcode (in m68k order)
raw_add_l_mi((uintptr)&raw_cputbl_count[cft_map(opcode)],1);
#endif
#if USE_NORMAL_CALLING_CONVENTION
raw_inc_sp(4);
#endif
if (i < blocklen - 1) {
uae_s8* branchadd;
raw_mov_l_rm(0,(uintptr)specflags);
raw_test_l_rr(0,0);
raw_jz_b_oponly();
branchadd=(uae_s8 *)get_target();
emit_byte(0);
raw_jmp((uintptr)popall_do_nothing);
*branchadd=(uintptr)get_target()-(uintptr)branchadd-1;
}
}
}
#if 1 /* This isn't completely kosher yet; It really needs to be
be integrated into a general inter-block-dependency scheme */
if (next_pc_p && taken_pc_p &&
was_comp && taken_pc_p==current_block_pc_p) {
blockinfo* bi1=get_blockinfo_addr_new((void*)next_pc_p,0);
blockinfo* bi2=get_blockinfo_addr_new((void*)taken_pc_p,0);
uae_u8 x=bi1->needed_flags;
if (x==0xff || 1) { /* To be on the safe side */
uae_u16* next=(uae_u16*)next_pc_p;
uae_u32 op=DO_GET_OPCODE(next);
x=0x1f;
x&=(~prop[op].set_flags);
x|=prop[op].use_flags;
}
x|=bi2->needed_flags;
if (!(x & FLAG_CZNV)) {
/* We can forget about flags */
dont_care_flags();
extra_len+=2; /* The next instruction now is part of this
block */
}
}
#endif
log_flush();
if (next_pc_p) { /* A branch was registered */
uintptr t1=next_pc_p;
uintptr t2=taken_pc_p;
int cc=branch_cc;
uae_u32* branchadd;
uae_u32* tba;
bigstate tmp;
blockinfo* tbi;
if (taken_pc_p<next_pc_p) {
/* backward branch. Optimize for the "taken" case ---
which means the raw_jcc should fall through when
the 68k branch is taken. */
t1=taken_pc_p;
t2=next_pc_p;
cc=branch_cc^1;
}
tmp=live; /* ouch! This is big... */
raw_jcc_l_oponly(cc);
branchadd=(uae_u32*)get_target();
emit_long(0);
/* predicted outcome */
tbi=get_blockinfo_addr_new((void*)t1,1);
match_states(tbi);
raw_cmp_l_mi((uintptr)specflags,0);
raw_jcc_l_oponly(4);
tba=(uae_u32*)get_target();
emit_long(get_handler(t1)-((uintptr)tba+4));
raw_mov_l_mi((uintptr)®s.pc_p,t1);
flush_reg_count();
raw_jmp((uintptr)popall_do_nothing);
create_jmpdep(bi,0,tba,t1);
align_target(align_jumps);
/* not-predicted outcome */
*branchadd=(uintptr)get_target()-((uintptr)branchadd+4);
live=tmp; /* Ouch again */
tbi=get_blockinfo_addr_new((void*)t2,1);
match_states(tbi);
//flush(1); /* Can only get here if was_comp==1 */
raw_cmp_l_mi((uintptr)specflags,0);
raw_jcc_l_oponly(4);
tba=(uae_u32*)get_target();
emit_long(get_handler(t2)-((uintptr)tba+4));
raw_mov_l_mi((uintptr)®s.pc_p,t2);
flush_reg_count();
raw_jmp((uintptr)popall_do_nothing);
create_jmpdep(bi,1,tba,t2);
}
else
{
if (was_comp) {
flush(1);
}
flush_reg_count();
/* Let's find out where next_handler is... */
if (was_comp && isinreg(PC_P)) {
r=live.state[PC_P].realreg;
raw_and_l_ri(r,TAGMASK);
int r2 = (r==0) ? 1 : 0;
raw_mov_l_ri(r2,(uintptr)popall_do_nothing);
raw_cmp_l_mi((uintptr)specflags,0);
raw_cmov_l_rm_indexed(r2,(uintptr)cache_tags,r,SIZEOF_VOID_P,NATIVE_CC_EQ);
raw_jmp_r(r2);
}
else if (was_comp && isconst(PC_P)) {
uae_u32 v=live.state[PC_P].val;
uae_u32* tba;
blockinfo* tbi;
tbi=get_blockinfo_addr_new((void*)(uintptr)v,1);
match_states(tbi);
raw_cmp_l_mi((uintptr)specflags,0);
raw_jcc_l_oponly(4);
tba=(uae_u32*)get_target();
emit_long(get_handler(v)-((uintptr)tba+4));
raw_mov_l_mi((uintptr)®s.pc_p,v);
raw_jmp((uintptr)popall_do_nothing);
create_jmpdep(bi,0,tba,v);
}
else {
r=REG_PC_TMP;
raw_mov_l_rm(r,(uintptr)®s.pc_p);
raw_and_l_ri(r,TAGMASK);
int r2 = (r==0) ? 1 : 0;
raw_mov_l_ri(r2,(uintptr)popall_do_nothing);
raw_cmp_l_mi((uintptr)specflags,0);
raw_cmov_l_rm_indexed(r2,(uintptr)cache_tags,r,SIZEOF_VOID_P,NATIVE_CC_EQ);
raw_jmp_r(r2);
}
}
}
#if USE_MATCH
if (callers_need_recompile(&live,&(bi->env))) {
mark_callers_recompile(bi);
}
big_to_small_state(&live,&(bi->env));
#endif
#if USE_CHECKSUM_INFO
remove_from_list(bi);
if (trace_in_rom) {
// No need to checksum that block trace on cache invalidation
free_checksum_info_chain(bi->csi);
bi->csi = NULL;
add_to_dormant(bi);
}
else {
calc_checksum(bi,&(bi->c1),&(bi->c2));
add_to_active(bi);
}
#else
if (next_pc_p+extra_len>=max_pcp &&
next_pc_p+extra_len<max_pcp+LONGEST_68K_INST)
max_pcp=next_pc_p+extra_len; /* extra_len covers flags magic */
else
max_pcp+=LONGEST_68K_INST;
bi->len=max_pcp-min_pcp;
bi->min_pcp=min_pcp;
remove_from_list(bi);
if (isinrom(min_pcp) && isinrom(max_pcp)) {
add_to_dormant(bi); /* No need to checksum it on cache flush.
Please don't start changing ROMs in
flight! */
}
else {
calc_checksum(bi,&(bi->c1),&(bi->c2));
add_to_active(bi);
}
#endif
current_cache_size += get_target() - (uae_u8 *)current_compile_p;
#if JIT_DEBUG
if (JITDebug)
bi->direct_handler_size = get_target() - (uae_u8 *)current_block_start_target;
if (JITDebug && disasm_block) {
uaecptr block_addr = start_pc + ((char *)pc_hist[0].location - (char *)start_pc_p);
D(bug("M68K block @ 0x%08x (%d insns)\n", block_addr, blocklen));
uae_u32 block_size = ((uae_u8 *)pc_hist[blocklen - 1].location - (uae_u8 *)pc_hist[0].location) + 1;
disasm_m68k_block((uae_u8 *)pc_hist[0].location, block_size);
D(bug("Compiled block @ 0x%08x\n", pc_hist[0].location));
disasm_native_block((uae_u8 *)current_block_start_target, bi->direct_handler_size);
getchar();
}
#endif
log_dump();
align_target(align_jumps);
/* This is the non-direct handler */
bi->handler=
bi->handler_to_use=(cpuop_func *)get_target();
raw_cmp_l_mi((uintptr)®s.pc_p,(uintptr)pc_hist[0].location);
raw_jnz((uintptr)popall_cache_miss);
comp_pc_p=(uae_u8*)pc_hist[0].location;
bi->status=BI_FINALIZING;
init_comp();
match_states(bi);
flush(1);
raw_jmp((uintptr)bi->direct_handler);
current_compile_p=get_target();
raise_in_cl_list(bi);
/* We will flush soon, anyway, so let's do it now */
if (current_compile_p>=max_compile_start)
flush_icache_hard(7);
bi->status=BI_ACTIVE;
if (redo_current_block)
block_need_recompile(bi);
#if PROFILE_COMPILE_TIME
compile_time += (clock() - start_time);
#endif
}
/* Account for compilation time */
cpu_do_check_ticks();
}
void do_nothing(void)
{
/* What did you expect this to do? */
}
void exec_nostats(void)
{
for (;;) {
uae_u32 opcode = GET_OPCODE;
#if FLIGHT_RECORDER
m68k_record_step(m68k_getpc());
#endif
(*cpufunctbl[opcode])(opcode);
cpu_check_ticks();
if (end_block(opcode) || SPCFLAGS_TEST(SPCFLAG_ALL)) {
return; /* We will deal with the spcflags in the caller */
}
}
}
void execute_normal(void)
{
if (!check_for_cache_miss()) {
cpu_history pc_hist[MAXRUN];
int blocklen = 0;
#if REAL_ADDRESSING || DIRECT_ADDRESSING
start_pc_p = regs.pc_p;
start_pc = get_virtual_address(regs.pc_p);
#else
start_pc_p = regs.pc_oldp;
start_pc = regs.pc;
#endif
for (;;) { /* Take note: This is the do-it-normal loop */
pc_hist[blocklen++].location = (uae_u16 *)regs.pc_p;
uae_u32 opcode = GET_OPCODE;
#if FLIGHT_RECORDER
m68k_record_step(m68k_getpc());
#endif
(*cpufunctbl[opcode])(opcode);
cpu_check_ticks();
if (end_block(opcode) || SPCFLAGS_TEST(SPCFLAG_ALL) || blocklen>=MAXRUN) {
compile_block(pc_hist, blocklen);
return; /* We will deal with the spcflags in the caller */
}
/* No need to check regs.spcflags, because if they were set,
we'd have ended up inside that "if" */
}
}
}
typedef void (*compiled_handler)(void);
static void m68k_do_compile_execute(void)
{
for (;;) {
((compiled_handler)(pushall_call_handler))();
/* Whenever we return from that, we should check spcflags */
if (SPCFLAGS_TEST(SPCFLAG_ALL)) {
if (m68k_do_specialties ())
return;
}
}
}
void m68k_compile_execute (void)
{
for (;;) {
if (quit_program)
break;
m68k_do_compile_execute();
}
}
|
gpl-2.0
|
teamfx/openjfx-9-dev-rt
|
modules/javafx.web/src/main/native/Source/JavaScriptCore/jit/JITSubGenerator.cpp
|
3391
|
/*
* Copyright (C) 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JITSubGenerator.h"
#if ENABLE(JIT)
namespace JSC {
void JITSubGenerator::generateFastPath(CCallHelpers& jit)
{
ASSERT(m_scratchGPR != InvalidGPRReg);
ASSERT(m_scratchGPR != m_left.payloadGPR());
ASSERT(m_scratchGPR != m_right.payloadGPR());
#if USE(JSVALUE32_64)
ASSERT(m_scratchGPR != m_left.tagGPR());
ASSERT(m_scratchGPR != m_right.tagGPR());
ASSERT(m_scratchFPR != InvalidFPRReg);
#endif
m_didEmitFastPath = true;
CCallHelpers::Jump leftNotInt = jit.branchIfNotInt32(m_left);
CCallHelpers::Jump rightNotInt = jit.branchIfNotInt32(m_right);
jit.move(m_left.payloadGPR(), m_scratchGPR);
m_slowPathJumpList.append(jit.branchSub32(CCallHelpers::Overflow, m_right.payloadGPR(), m_scratchGPR));
jit.boxInt32(m_scratchGPR, m_result);
m_endJumpList.append(jit.jump());
if (!jit.supportsFloatingPoint()) {
m_slowPathJumpList.append(leftNotInt);
m_slowPathJumpList.append(rightNotInt);
return;
}
leftNotInt.link(&jit);
if (!m_leftOperand.definitelyIsNumber())
m_slowPathJumpList.append(jit.branchIfNotNumber(m_left, m_scratchGPR));
if (!m_rightOperand.definitelyIsNumber())
m_slowPathJumpList.append(jit.branchIfNotNumber(m_right, m_scratchGPR));
jit.unboxDoubleNonDestructive(m_left, m_leftFPR, m_scratchGPR, m_scratchFPR);
CCallHelpers::Jump rightIsDouble = jit.branchIfNotInt32(m_right);
jit.convertInt32ToDouble(m_right.payloadGPR(), m_rightFPR);
CCallHelpers::Jump rightWasInteger = jit.jump();
rightNotInt.link(&jit);
if (!m_rightOperand.definitelyIsNumber())
m_slowPathJumpList.append(jit.branchIfNotNumber(m_right, m_scratchGPR));
jit.convertInt32ToDouble(m_left.payloadGPR(), m_leftFPR);
rightIsDouble.link(&jit);
jit.unboxDoubleNonDestructive(m_right, m_rightFPR, m_scratchGPR, m_scratchFPR);
rightWasInteger.link(&jit);
jit.subDouble(m_rightFPR, m_leftFPR);
jit.boxDouble(m_leftFPR, m_result);
}
} // namespace JSC
#endif // ENABLE(JIT)
|
gpl-2.0
|
dieterv/gobject-introspection
|
giscanner/message.py
|
6152
|
#!/usr/bin/env python
# -*- Mode: Python -*-
# GObject-Introspection - a framework for introspecting GObject libraries
# Copyright (C) 2010 Red Hat, Inc.
# Copyright (C) 2010 Johan Dahlin
#
# 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.
#
import os
import sys
from . import utils
(WARNING,
ERROR,
FATAL) = range(3)
class Position(object):
"""Represents a position in the source file which we
want to inform about.
"""
def __init__(self, filename=None, line=None, column=None):
self.filename = filename
self.line = line
self.column = column
def __cmp__(self, other):
return cmp((self.filename, self.line, self.column),
(other.filename, other.line, other.column))
def __repr__(self):
return '<Position %s:%d:%d>' % (
os.path.basename(self.filename),
self.line or -1,
self.column or -1)
def format(self, cwd):
filename = self.filename
if filename.startswith(cwd):
filename = filename[len(cwd):]
if self.column is not None:
return '%s:%d:%d' % (filename, self.line, self.column)
elif self.line is not None:
return '%s:%d' % (filename, self.line, )
else:
return '%s:' % (filename, )
def offset(self, offset):
return Position(self.filename, self.line+offset, self.column)
class MessageLogger(object):
_instance = None
def __init__(self, namespace, output=None):
if output is None:
output = sys.stderr
self._cwd = os.getcwd() + os.sep
self._output = output
self._namespace = namespace
self._enable_warnings = False
self._warning_count = 0
@classmethod
def get(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = cls(*args, **kwargs)
return cls._instance
def enable_warnings(self, enable):
self._enable_warnings = enable
def get_warning_count(self):
return self._warning_count
def log(self, log_type, text, positions=None, prefix=None):
"""Log a warning, using optional file positioning information.
If the warning is related to a ast.Node type, see log_node()."""
utils.break_on_debug_flag('warning')
self._warning_count += 1
if not self._enable_warnings and log_type != FATAL:
return
# Always drop through on fatal
if type(positions) == set:
positions = list(positions)
if isinstance(positions, Position):
positions = [positions]
if not positions:
positions = [Position('<unknown>')]
for position in positions[:-1]:
self._output.write("%s:\n" % (position.format(cwd=self._cwd), ))
last_position = positions[-1].format(cwd=self._cwd)
if log_type == WARNING:
error_type = "Warning"
elif log_type == ERROR:
error_type = "Error"
elif log_type == FATAL:
error_type = "Fatal"
if prefix:
text = (
'''%s: %s: %s: %s: %s\n''' % (last_position, error_type, self._namespace.name,
prefix, text))
else:
if self._namespace:
text = (
'''%s: %s: %s: %s\n''' % (last_position, error_type, self._namespace.name, text))
else:
text = (
'''%s: %s: %s\n''' % (last_position, error_type, text))
self._output.write(text)
if log_type == FATAL:
utils.break_on_debug_flag('fatal')
raise SystemExit(text)
def log_node(self, log_type, node, text, context=None, positions=None):
"""Log a warning, using information about file positions from
the given node. The optional context argument, if given, should be
another ast.Node type which will also be displayed. If no file position
information is available from the node, the position data from the
context will be used."""
if positions:
pass
elif getattr(node, 'file_positions', None):
positions = node.file_positions
elif context and context.file_positions:
positions = context.file_positions
else:
positions = []
if not context:
text = "context=%r %s" % (node, text)
if context:
text = "%s: %s" % (getattr(context, 'symbol', context.name), text)
elif not positions and hasattr(node, 'name'):
text = "(%s)%s: %s" % (node.__class__.__name__, node.name, text)
self.log(log_type, text, positions)
def log_symbol(self, log_type, symbol, text):
"""Log a warning in the context of the given symbol."""
self.log(log_type, text, symbol.position,
prefix="symbol=%r" % (symbol.ident, ))
def log_node(log_type, node, text, context=None, positions=None):
ml = MessageLogger.get()
ml.log_node(log_type, node, text, context=context, positions=positions)
def warn(text, positions=None, prefix=None):
ml = MessageLogger.get()
ml.log(WARNING, text, positions, prefix)
def warn_node(node, text, context=None, positions=None):
log_node(WARNING, node, text, context=context, positions=positions)
def warn_symbol(symbol, text):
ml = MessageLogger.get()
ml.log_symbol(WARNING, symbol, text)
def fatal(text, positions=None, prefix=None):
ml = MessageLogger.get()
ml.log(FATAL, text, positions, prefix)
|
gpl-2.0
|
redpois0n/yontma
|
yontma/WiredEthernetMonitor.cpp
|
3825
|
#include "stdafx.h"
HRESULT GetInternetAdapterAddresses(__inout PIP_ADAPTER_ADDRESSES* ppAdapterAddresses,__inout PULONG pAdapterAddressesSize);
HRESULT GetInternetAdapterAddresses(__inout PIP_ADAPTER_ADDRESSES* ppAdapterAddresses,__inout PULONG pAdapterAddressesSize)
{
HRESULT hr;
ULONG rc = 0;
rc = GetAdaptersAddresses(AF_UNSPEC,
GAA_FLAG_INCLUDE_PREFIX,
NULL,
*ppAdapterAddresses,
pAdapterAddressesSize);
if(rc == ERROR_SUCCESS) {
//
// Our original buffer was large enough to store the result, so we're done.
//
hr = S_OK;
goto cleanexit;
}
else if(rc != ERROR_BUFFER_OVERFLOW) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto cleanexit;
}
//
// Our original buffer couldn't store the result, so we need to allocate a larger buffer.
//
HB_SAFE_FREE(*ppAdapterAddresses);
*ppAdapterAddresses = (PIP_ADAPTER_ADDRESSES)malloc(*pAdapterAddressesSize);
if(*ppAdapterAddresses == NULL) {
hr = E_OUTOFMEMORY;
goto cleanexit;
}
rc = GetAdaptersAddresses(AF_UNSPEC,
GAA_FLAG_INCLUDE_PREFIX,
NULL,
*ppAdapterAddresses,
pAdapterAddressesSize);
if(rc != ERROR_SUCCESS) {
hr = HRESULT_FROM_WIN32(rc);
goto cleanexit;
}
hr = S_OK;
cleanexit:
return hr;
}
DWORD WINAPI WiredEthernetMonitorThread(LPVOID lpParams)
{
HRESULT hr;
PMONITOR_THREAD_PARAMS pMonitorThreadParams = (PMONITOR_THREAD_PARAMS)lpParams;
PIP_ADAPTER_ADDRESSES pOriginalAddresses = NULL;
ULONG originalAddressesSize = 0;
PIP_ADAPTER_ADDRESSES pNewAddresses = NULL;
ULONG newAddressesSize = 0;
PIP_ADAPTER_ADDRESSES pCurrOriginalAddress = NULL;
PIP_ADAPTER_ADDRESSES pCurrNewAddress = NULL;
WriteLineToLog("WiredEtherMonitorThread: Started");
hr = GetInternetAdapterAddresses(&pOriginalAddresses, &originalAddressesSize);
if(HB_FAILED(hr)) {
WriteLineToLog("WiredEtherMonitorThread: Failed to get original adapter addresses");
goto cleanexit;
}
while(1) {
hr = GetInternetAdapterAddresses(&pNewAddresses, &newAddressesSize);
if(HB_FAILED(hr)) {
WriteLineToLog("WiredEtherMonitorThread: Failed to get new adapter addresses");
goto cleanexit;
}
pCurrOriginalAddress = pOriginalAddresses;
pCurrNewAddress = pNewAddresses;
while(pCurrOriginalAddress && pCurrNewAddress) {
if(pCurrNewAddress->IfType == IF_TYPE_ETHERNET_CSMACD) {
if((pCurrNewAddress->OperStatus == IfOperStatusDown) && (pCurrOriginalAddress->OperStatus == IfOperStatusUp)) {
WriteLineToLog("WiredEtherMonitorThread: Firing monitor event");
SetEvent(pMonitorThreadParams->hMonitorEvent);
goto cleanexit;
}
else {
ResetEvent(pMonitorThreadParams->hMonitorEvent);
}
}
pCurrOriginalAddress = pCurrOriginalAddress->Next;
pCurrNewAddress = pCurrNewAddress->Next;
}
switch (WaitForSingleObject(pMonitorThreadParams->hMonitorStopEvent, DEFAULT_SLEEP_TIME)) {
case WAIT_OBJECT_0:
goto cleanexit;
case WAIT_TIMEOUT:
continue;
}
}
cleanexit:
WriteLineToLog("WiredEtherMonitorThread: Exiting");
InterlockedIncrement(pMonitorThreadParams->pMonitorsCompleted);
HB_SAFE_FREE(pOriginalAddresses);
HB_SAFE_FREE(pNewAddresses);
HB_SAFE_FREE(pMonitorThreadParams);
return 0;
}
|
gpl-2.0
|
SCADA-LTS/Scada-LTS
|
src/com/serotonin/mango/rt/dataSource/virtual/VirtualDataSourceRT.java
|
2454
|
/*
Mango - Open Source M2M - http://mango.serotoninsoftware.com
Copyright (C) 2006-2011 Serotonin Software Technologies Inc.
@author Matthew Lohbihler
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/>.
*/
package com.serotonin.mango.rt.dataSource.virtual;
import com.serotonin.mango.rt.dataImage.DataPointRT;
import com.serotonin.mango.rt.dataImage.PointValueTime;
import com.serotonin.mango.rt.dataImage.SetPointSource;
import com.serotonin.mango.rt.dataSource.PollingDataSource;
import com.serotonin.mango.vo.dataSource.virtual.VirtualDataSourceVO;
public class VirtualDataSourceRT extends PollingDataSource {
public VirtualDataSourceRT(VirtualDataSourceVO vo) {
super(vo);
setPollingPeriod(vo.getUpdatePeriodType(), vo.getUpdatePeriods(), false);
}
@Override
public void doPoll(long time) {
for (DataPointRT dataPoint : dataPoints) {
VirtualPointLocatorRT locator = dataPoint.getPointLocator();
// Change the point values according to their definitions.
locator.change();
// Update the data image with the new value.
dataPoint.updatePointValue(new PointValueTime(locator.getCurrentValue(), time));
}
}
@Override
public void setPointValue(DataPointRT dataPoint, PointValueTime valueTime, SetPointSource source) {
VirtualPointLocatorRT l = dataPoint.getPointLocator();
l.setCurrentValue(valueTime.getValue());
dataPoint.setPointValue(valueTime, source);
}
@Override
public void addDataPoint(DataPointRT dataPoint) {
if (dataPoint.getPointValue() != null) {
VirtualPointLocatorRT locator = dataPoint.getPointLocator();
locator.setCurrentValue(dataPoint.getPointValue().getValue());
}
super.addDataPoint(dataPoint);
}
}
|
gpl-2.0
|
AppleWin/AppleWin
|
source/Configuration/PageConfigTfe.cpp
|
7361
|
/*
AppleWin : An Apple //e emulator for Windows
Copyright (C) 1994-1996, Michael O'Brien
Copyright (C) 1999-2001, Oliver Schmidt
Copyright (C) 2002-2005, Tom Charlesworth
Copyright (C) 2006-2014, Tom Charlesworth, Michael Pohoreski, Nick Westgate
AppleWin 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.
AppleWin 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 AppleWin; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "StdAfx.h"
#include "PageConfigTfe.h"
#include "../Common.h"
#include "../Registry.h"
#include "../resource/resource.h"
#include "../Tfe/tfe.h"
#include "../Tfe/tfesupp.h"
CPageConfigTfe* CPageConfigTfe::ms_this = 0; // reinit'd in ctor
uilib_localize_dialog_param CPageConfigTfe::ms_dialog[] =
{
{0, IDS_TFE_CAPTION, -1},
{IDC_TFE_SETTINGS_ENABLE_T, IDS_TFE_ETHERNET, 0},
{IDC_TFE_SETTINGS_INTERFACE_T, IDS_TFE_INTERFACE, 0},
{IDOK, IDS_OK, 0},
{IDCANCEL, IDS_CANCEL, 0},
{0, 0, 0}
};
uilib_dialog_group CPageConfigTfe::ms_leftgroup[] =
{
{IDC_TFE_SETTINGS_ENABLE_T, 0},
{IDC_TFE_SETTINGS_INTERFACE_T, 0},
{0, 0}
};
uilib_dialog_group CPageConfigTfe::ms_rightgroup[] =
{
{IDC_TFE_SETTINGS_ENABLE, 0},
{IDC_TFE_SETTINGS_INTERFACE, 0},
{0, 0}
};
INT_PTR CALLBACK CPageConfigTfe::DlgProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
// Switch from static func to our instance
return CPageConfigTfe::ms_this->DlgProcInternal(hwnd, msg, wparam, lparam);
}
INT_PTR CPageConfigTfe::DlgProcInternal(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_COMMAND:
switch (LOWORD(wparam))
{
case IDOK:
DlgOK(hwnd);
/* FALL THROUGH */
case IDCANCEL:
DlgCANCEL(hwnd);
return TRUE;
case IDC_TFE_SETTINGS_INTERFACE:
/* FALL THROUGH */
case IDC_TFE_SETTINGS_ENABLE:
gray_ungray_items(hwnd);
break;
}
return FALSE;
case WM_CLOSE:
EndDialog(hwnd,0);
return TRUE;
case WM_INITDIALOG:
init_tfe_dialog(hwnd);
return TRUE;
}
return FALSE;
}
void CPageConfigTfe::DlgOK(HWND window)
{
save_tfe_dialog(window);
}
void CPageConfigTfe::DlgCANCEL(HWND window)
{
EndDialog(window, 0);
}
BOOL CPageConfigTfe::get_tfename(int number, char **ppname, char **ppdescription)
{
if (tfe_enumadapter_open())
{
char *pname = NULL;
char *pdescription = NULL;
while (number--)
{
if (!tfe_enumadapter(&pname, &pdescription))
break;
lib_free(pname);
lib_free(pdescription);
}
if (tfe_enumadapter(&pname, &pdescription))
{
*ppname = pname;
*ppdescription = pdescription;
tfe_enumadapter_close();
return TRUE;
}
tfe_enumadapter_close();
}
return FALSE;
}
int CPageConfigTfe::gray_ungray_items(HWND hwnd)
{
int enable;
int number;
int disabled = 0;
get_disabled_state(&disabled);
if (disabled)
{
EnableWindow(GetDlgItem(hwnd, IDC_TFE_SETTINGS_ENABLE_T), 0);
EnableWindow(GetDlgItem(hwnd, IDC_TFE_SETTINGS_ENABLE), 0);
EnableWindow(GetDlgItem(hwnd, IDOK), 0);
SetWindowText(GetDlgItem(hwnd,IDC_TFE_SETTINGS_INTERFACE_NAME), "");
SetWindowText(GetDlgItem(hwnd,IDC_TFE_SETTINGS_INTERFACE_DESC), "");
enable = 0;
}
else
{
enable = SendMessage(GetDlgItem(hwnd, IDC_TFE_SETTINGS_ENABLE), CB_GETCURSEL, 0, 0) ? 1 : 0;
}
EnableWindow(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE_T), enable);
EnableWindow(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE), enable);
if (enable)
{
char *pname = NULL;
char *pdescription = NULL;
number = SendMessage(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE), CB_GETCURSEL, 0, 0);
if (get_tfename(number, &pname, &pdescription))
{
SetWindowText(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE_NAME), pname);
SetWindowText(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE_DESC), pdescription);
lib_free(pname);
lib_free(pdescription);
}
}
else
{
SetWindowText(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE_NAME), "");
SetWindowText(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE_DESC), "");
}
return disabled ? 1 : 0;
}
void CPageConfigTfe::init_tfe_dialog(HWND hwnd)
{
HWND temp_hwnd;
int active_value;
int xsize, ysize;
uilib_get_group_extent(hwnd, ms_leftgroup, &xsize, &ysize);
uilib_adjust_group_width(hwnd, ms_leftgroup);
uilib_move_group(hwnd, ms_rightgroup, xsize + 30);
active_value = (m_tfe_enabled > 0 ? 1 : 0);
temp_hwnd=GetDlgItem(hwnd,IDC_TFE_SETTINGS_ENABLE);
SendMessage(temp_hwnd, CB_ADDSTRING, 0, (LPARAM)"Disabled");
SendMessage(temp_hwnd, CB_ADDSTRING, 0, (LPARAM)"Uthernet");
SendMessage(temp_hwnd, CB_SETCURSEL, (WPARAM)active_value, 0);
if (tfe_enumadapter_open())
{
int cnt = 0;
char *pname;
char *pdescription;
temp_hwnd=GetDlgItem(hwnd,IDC_TFE_SETTINGS_INTERFACE);
for (cnt = 0; tfe_enumadapter(&pname, &pdescription); cnt++)
{
BOOL this_entry = FALSE;
if (strcmp(pname, m_tfe_interface_name.c_str()) == 0)
{
this_entry = TRUE;
}
SetWindowText(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE_NAME), pname);
SetWindowText(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE_DESC), pdescription);
SendMessage(temp_hwnd, CB_ADDSTRING, 0, (LPARAM)pname);
lib_free(pname);
lib_free(pdescription);
if (this_entry)
{
SendMessage(GetDlgItem(hwnd, IDC_TFE_SETTINGS_INTERFACE),
CB_SETCURSEL, (WPARAM)cnt, 0);
}
}
tfe_enumadapter_close();
}
if (gray_ungray_items(hwnd))
{
/* we have a problem: TFE is disabled. Give a message to the user */
// TC (18 Dec 2017) this vicekb URL is a broken link now, so I copied it to the AppleWin repo, here:
// . https://github.com/AppleWin/AppleWin/blob/master/docs/VICE%20Knowledge%20Base%20-%20Article%2013-005.htm
MessageBox( hwnd,
"TFE support is not available on your system,\n"
"there is some important part missing. Please have a\n"
"look at the VICE knowledge base support page\n"
"\n http://vicekb.trikaliotis.net/13-005\n\n"
"for possible reasons and to activate networking with VICE.",
"TFE support", MB_ICONINFORMATION|MB_OK);
/* just quit the dialog before it is open */
SendMessage( hwnd, WM_COMMAND, IDCANCEL, 0);
}
}
void CPageConfigTfe::save_tfe_dialog(HWND hwnd)
{
int active_value;
char buffer[256];
buffer[255] = 0;
GetDlgItemText(hwnd, IDC_TFE_SETTINGS_INTERFACE, buffer, sizeof(buffer)-1);
// RGJ - Added check for NULL interface so we don't set it active without a valid interface selected
if (strlen(buffer) > 0)
{
m_tfe_interface_name = buffer;
active_value = SendMessage(GetDlgItem(hwnd, IDC_TFE_SETTINGS_ENABLE), CB_GETCURSEL, 0, 0);
m_tfe_enabled = active_value > 0 ? 1 : 0;
}
else
{
m_tfe_enabled = 0;
m_tfe_interface_name.clear();
}
}
|
gpl-2.0
|
penberg/classpath
|
tools/gnu/classpath/tools/gjdoc/Main.java
|
58258
|
/* gnu.classpath.tools.gjdoc.Main
Copyright (C) 2001, 2012 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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 Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.classpath.tools.gjdoc;
import com.sun.javadoc.*;
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import java.text.Collator;
import gnu.classpath.tools.FileSystemClassLoader;
/**
* Class that will launch the gjdoc tool.
*/
public final class Main
{
/**
* Do we load classes that are referenced as base class?
*/
static final boolean DESCEND_SUPERCLASS = true;
/**
* Do we load classes that are referenced as interface?
*/
static final boolean DESCEND_INTERFACES = false;
/**
* Do we load classes that are imported in a source file?
*/
static final boolean DESCEND_IMPORTED = true;
/**
* Document only public members.
*/
static final int COVERAGE_PUBLIC = 0;
/**
* Document only public and protected members.
*/
static final int COVERAGE_PROTECTED = 1;
/**
* Document public, protected and package private members.
*/
static final int COVERAGE_PACKAGE = 2;
/**
* Document all members.
*/
static final int COVERAGE_PRIVATE = 3;
/*
* FIXME: This should come from a ResourceBundle
*/
private static final String STRING_TRY_GJDOC_HELP =
"Try `gjdoc --help' for more information.";
/**
* Grid for looking up whether a particular access level is included in the
* documentation.
*/
static final boolean[][] coverageTemplates = new boolean[][]
{ new boolean[]
{ true, false, false, false }, // public
new boolean[]
{ true, true, false, false }, // protected
new boolean[]
{ true, true, true, false }, // package
new boolean[]
{ true, true, true, true }, // private
};
/**
* Holds the Singleton instance of this class.
*/
private static Main instance = new Main();
/**
* Avoid re-instantiation of this class.
*/
private Main()
{
}
private static RootDocImpl rootDoc;
private ErrorReporter reporter;
/**
* Cache for version string from resource /version.properties
*/
private String gjdocVersion;
/**
* <code>false</code> during Phase I: preparation of the documentation data.
* <code>true</code> during Phase II: documentation output by doclet.
*/
boolean docletRunning = false;
//---- Command line options
/**
* Option "-doclet": name of the Doclet class to use.
*/
private String option_doclet = "gnu.classpath.tools.doclets.htmldoclet.HtmlDoclet";
/**
* Option "-coverage": which members to include in generated documentation.
*/
private int option_coverage = COVERAGE_PROTECTED;
/**
* Option "-help": display command line usage.
*/
private boolean option_help;
/**
* Option "-docletpath": path to doclet classes.
*/
private String option_docletpath;
/**
* Option "-sourcepath": path to the Java source files to be documented.
* FIXME: this should be a list of paths
*/
private List<File> option_sourcepath = new ArrayList<File>();
/**
* Option "-locale:" Specify the locale charset of Java source files.
*/
private Locale option_locale = new Locale("en", "us");
/**
* Option "-encoding": Specify character encoding of Java source files.
*/
private String option_encoding;
/**
* Option "-source:" should be 1.4 to handle assertions, 1.1 is no
* longer supported.
*/
private String option_source = "1.2";
/**
* Option "-subpackages": list of subpackages to be recursively
* added.
*/
private List<String> option_subpackages = new ArrayList<String>();
/**
* Option "-exclude": list of subpackages to exclude.
*/
private List<String> option_exclude = new ArrayList<String>();
/**
* Option "-breakiterator" - whether to use BreakIterator for
* detecting the end of the first sentence.
*/
private boolean option_breakiterator;
/**
* Option "-licensetext" - whether to copy license text.
*/
private boolean option_licensetext;
/**
* The locale-dependent collator used for sorting.
*/
private Collator collator;
/**
* true when --version has been specified on the command line.
*/
private boolean option_showVersion;
/**
* true when -bootclasspath has been specified on the command line.
*/
private boolean option_bootclasspath_specified;
/**
* true when -all has been specified on the command line.
*/
private boolean option_all;
/**
* true when -reflection has been specified on the command line.
*/
private boolean option_reflection;
// TODO: add the rest of the options as instance variables
/**
* Parse all source files/packages and subsequentially start the Doclet given
* on the command line.
*
* @param allOptions List of all command line tokens
*/
private boolean startDoclet(List<String> allOptions)
{
try
{
//--- Fetch the Class object for the Doclet.
Debug.log(1, "loading doclet class...");
Class<?> docletClass;
if (null != option_docletpath) {
try {
FileSystemClassLoader docletPathClassLoader
= new FileSystemClassLoader(option_docletpath);
System.err.println("trying to load class " + option_doclet + " from path " + option_docletpath);
docletClass = docletPathClassLoader.findClass(option_doclet);
}
catch (Exception e) {
docletClass = Class.forName(option_doclet);
}
}
else {
docletClass = Class.forName(option_doclet);
}
//Object docletInstance = docletClass.newInstance();
Debug.log(1, "doclet class loaded...");
Method startTempMethod = null;
Method startMethod = null;
Method optionLenMethod = null;
Method validOptionsMethod = null;
//--- Try to find the optionLength method in the Doclet class.
try
{
optionLenMethod = docletClass.getMethod("optionLength", new Class[]
{ String.class });
}
catch (NoSuchMethodException e)
{
// Ignore if not found; it's OK it the Doclet class doesn't define
// this method.
}
//--- Try to find the validOptions method in the Doclet class.
try
{
validOptionsMethod = docletClass.getMethod("validOptions", new Class[]
{ String[][].class, DocErrorReporter.class });
}
catch (NoSuchMethodException e)
{
// Ignore if not found; it's OK it the Doclet class doesn't define
// this method.
}
//--- Find the start method in the Doclet class; complain if not found
try
{
startTempMethod = docletClass.getMethod("start", new Class[]
{ TemporaryStore.class });
}
catch (Exception e)
{
// ignore
}
startMethod = docletClass.getMethod("start", new Class[]
{ RootDoc.class });
//--- Feed the custom command line tokens to the Doclet
// stores all recognized options
List<String[]> options = new LinkedList<String[]>();
// stores packages and classes defined on the command line
List<String> packageAndClasses = new LinkedList<String>();
for (Iterator<String> it = allOptions.iterator(); it.hasNext();)
{
String option = it.next();
Debug.log(9, "parsing option '" + option + "'");
if (option.startsWith("-"))
{
//--- Parse option
int optlen = optionLength(option);
//--- Try to get option length from Doclet class
if (optlen <= 0 && optionLenMethod != null)
{
optionLenMethod.invoke(null, new Object[]
{ option });
Debug.log(3, "invoking optionLen method");
optlen = ((Integer) optionLenMethod.invoke(null, new Object[]
{ option })).intValue();
Debug.log(3, "done");
}
if (optlen <= 0) {
if (option.startsWith("-JD")) {
// Simulate VM option -D
String propertyValue = option.substring(3);
int ndx = propertyValue.indexOf('=');
if (ndx <= 0) {
reporter.printError("Illegal format in option " + option + ": use -JDproperty=value");
return false;
}
else {
String property = propertyValue.substring(0, ndx);
String value = propertyValue.substring(ndx + 1);
System.setProperty(property, value);
}
}
else if (option.startsWith("-J")) {
//--- Warn if VM option is encountered
reporter.printWarning("Ignored option " + option + ". Pass this option to the VM if required.");
}
else {
//--- Complain if not found
reporter.printError("Unknown option " + option);
reporter.printNotice(STRING_TRY_GJDOC_HELP);
return false;
}
}
else
{
//--- Read option values
String[] optionAndValues = new String[optlen];
optionAndValues[0] = option;
for (int i = 1; i < optlen; ++i)
{
if (!it.hasNext())
{
reporter.printError("Missing value for option " + option);
return false;
}
else
{
optionAndValues[i] = (String) it.next();
}
}
//--- Store option for processing later
options.add(optionAndValues);
}
}
else if (option.length() > 0)
{
//--- Add to list of packages/classes if not option or option
// value
packageAndClasses.add(option);
}
}
Debug.log(9, "options parsed...");
//--- For each package specified with the -subpackages option on
// the command line, recursively find all valid java files
// beneath it.
//--- For each class or package specified on the command line,
// check that it exists and find out whether it is a class
// or a package
for (Iterator<String> it = option_subpackages.iterator(); it.hasNext();)
{
String subpackage = it.next();
Set<String> foundPackages = new LinkedHashSet<String>();
for (Iterator<File> pit = option_sourcepath.iterator(); pit.hasNext(); ) {
File sourceDir = pit.next();
File packageDir = new File(sourceDir, subpackage.replace('.', File.separatorChar));
findPackages(subpackage, packageDir, foundPackages);
}
addFoundPackages(subpackage, foundPackages);
}
if (option_all) {
Set<String> foundPackages = new LinkedHashSet<String>();
for (Iterator<File> pit = option_sourcepath.iterator(); pit.hasNext(); ) {
File sourceDir = pit.next();
findPackages("", sourceDir, foundPackages);
}
addFoundPackages(null, foundPackages);
for (Iterator<String> packageIt = foundPackages.iterator(); packageIt.hasNext(); ) {
String packageName = packageIt.next();
if (null == packageName) {
packageName = "";
}
rootDoc.addSpecifiedPackageName(packageName);
}
}
for (Iterator<String> it = packageAndClasses.iterator(); it.hasNext();)
{
String classOrPackage = it.next();
boolean foundSourceFile = false;
if (classOrPackage.endsWith(".java")) {
for (Iterator<File> pit = option_sourcepath.iterator(); pit.hasNext() && !foundSourceFile; ) {
File sourceDir = pit.next();
File sourceFile = new File(sourceDir, classOrPackage);
if (sourceFile.exists() && !sourceFile.isDirectory()) {
rootDoc.addSpecifiedSourceFile(sourceFile);
foundSourceFile = true;
break;
}
}
if (!foundSourceFile) {
File sourceFile = new File(classOrPackage);
if (sourceFile.exists() && !sourceFile.isDirectory()) {
rootDoc.addSpecifiedSourceFile(sourceFile);
foundSourceFile = true;
}
}
}
if (!foundSourceFile) {
//--- Check for illegal name
if (classOrPackage.startsWith(".")
|| classOrPackage.endsWith(".")
|| classOrPackage.indexOf("..") > 0
|| !checkCharSet(classOrPackage,
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_."))
{
throw new ParseException("Illegal class or package name '"
+ classOrPackage + "'");
}
//--- Assemble absolute path to package
String classOrPackageRelPath = classOrPackage.replace('.',
File.separatorChar);
//--- Create one file object each for a possible package directory
// and a possible class file, and find out if they exist.
List<File> packageDirs = rootDoc.findSourceFiles(classOrPackageRelPath);
List<File> sourceFiles = rootDoc.findSourceFiles(classOrPackageRelPath + ".java");
boolean packageDirExists = !packageDirs.isEmpty();
boolean sourceFileExists = !sourceFiles.isEmpty();
//--- Complain if neither exists: not found
if (!packageDirExists && !sourceFileExists)
{
reporter.printError("Class or package " + classOrPackage
+ " not found.");
return false;
}
//--- Complain if both exist: ambigious
else
if (packageDirExists && sourceFileExists)
{
reporter.printError("Ambigious class/package name "
+ classOrPackage + ".");
return false;
}
//--- Otherwise, if the package directory exists, it is a package
else
if (packageDirExists) {
Iterator<File> packageDirIt = packageDirs.iterator();
boolean packageDirFound = false;
while (packageDirIt.hasNext()) {
File packageDir = packageDirIt.next();
if (packageDir.isDirectory()) {
rootDoc.addSpecifiedPackageName(classOrPackage);
packageDirFound = true;
break;
}
}
if (!packageDirFound) {
reporter.printError("No suitable file or directory found for" + classOrPackage);
return false;
}
}
//--- Otherwise, emit error message
else {
reporter.printError("No sources files found for package " + classOrPackage);
}
}
}
//--- Complain if no packages or classes specified
if (option_help) {
usage();
return true;
}
//--- Validate custom options passed on command line
// by asking the Doclet if they are OK.
String[][] customOptionArr = (String[][]) options
.toArray(new String[0][0]);
if (validOptionsMethod != null
&& !((Boolean) validOptionsMethod.invoke(null, new Object[]
{ customOptionArr, reporter })).booleanValue())
{
// Not ok: shutdown system.
reporter.printNotice(STRING_TRY_GJDOC_HELP);
return false;
}
if (!rootDoc.hasSpecifiedPackagesOrClasses()) {
reporter.printError("No packages or classes specified.");
reporter.printNotice(STRING_TRY_GJDOC_HELP);
return false;
}
rootDoc.setOptions(customOptionArr);
rootDoc.build();
//--- Bail out if no classes found
if (0 == rootDoc.classes().length
&& 0 == rootDoc.specifiedPackages().length
&& 0 == rootDoc.specifiedClasses().length)
{
reporter.printError("No packages or classes found(!).");
return false;
}
//--- Our work is done, tidy up memory
System.gc();
System.gc();
//--- Set flag indicating Phase II of documentation generation
docletRunning = true;
//--- Invoke the start method on the Doclet: produce output
reporter.printNotice("Running doclet...");
TemporaryStore tstore = new TemporaryStore(Main.rootDoc);
Thread.currentThread().setContextClassLoader(docletClass.getClassLoader());
if (null != startTempMethod)
{
startTempMethod.invoke(null, new Object[]
{ tstore });
}
else
{
startMethod.invoke(null, new Object[]
{ tstore.getAndClear() });
}
//--- Let the user know how many warnings/errors occured
if (reporter.getWarningCount() > 0)
{
reporter.printNotice(reporter.getWarningCount() + " warnings");
}
if (reporter.getErrorCount() > 0)
{
reporter.printNotice(reporter.getErrorCount() + " errors");
}
System.gc();
//--- Done.
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
private void addFoundPackages(String subpackage, Set<String> foundPackages)
{
if (foundPackages.isEmpty()) {
reporter.printWarning("No classes found under subpackage " + subpackage);
}
else {
boolean onePackageAdded = false;
for (Iterator<String> rit = foundPackages.iterator(); rit.hasNext();) {
String foundPackage = rit.next();
boolean excludeThisPackage = false;
for (Iterator<String> eit = option_exclude.iterator(); eit.hasNext();) {
String excludePackage = eit.next();
if (foundPackage.equals(excludePackage) ||
foundPackage.startsWith(excludePackage + ":")) {
excludeThisPackage = true;
break;
}
}
if (!excludeThisPackage) {
rootDoc.addSpecifiedPackageName(foundPackage);
onePackageAdded = true;
}
}
if (!onePackageAdded) {
if (null != subpackage) {
reporter.printWarning("No non-excluded classes found under subpackage " + subpackage);
}
else {
reporter.printWarning("No non-excluded classes found.");
}
}
}
}
/**
* Verify that the given file is a valid Java source file and that
* it specifies the given package.
*/
private boolean isValidJavaFile(File file,
String expectedPackage)
{
try {
InputStream in = new BufferedInputStream(new FileInputStream(file));
int ch, prevChar = 0;
final int STATE_DEFAULT = 0;
final int STATE_COMMENT = 1;
final int STATE_LINE_COMMENT = 2;
int state = STATE_DEFAULT;
StringBuffer word = new StringBuffer();
int wordIndex = 0;
while ((ch = in.read()) >= 0) {
String completeWord = null;
switch (state) {
case STATE_COMMENT:
if (prevChar == '*' && ch == '/') {
state = STATE_DEFAULT;
}
break;
case STATE_LINE_COMMENT:
if (ch == '\n') {
state = STATE_DEFAULT;
}
break;
case STATE_DEFAULT:
if (prevChar == '/' && ch == '*') {
word.deleteCharAt(word.length() - 1);
if (word.length() > 0) {
completeWord = word.toString();
word.setLength(0);
}
state = STATE_COMMENT;
}
else if (prevChar == '/' && ch == '/') {
word.deleteCharAt(word.length() - 1);
if (word.length() > 0) {
completeWord = word.toString();
word.setLength(0);
}
state = STATE_LINE_COMMENT;
}
else if (" \t\r\n".indexOf(ch) >= 0) {
if (word.length() > 0) {
completeWord = word.toString();
word.setLength(0);
}
}
else if (1 == wordIndex && ';' == ch) {
if (word.length() > 0) {
completeWord = word.toString();
word.setLength(0);
}
else {
// empty package name in source file: "package ;" -> invalid source file
in.close();
return false;
}
}
else {
word.append((char)ch);
}
break;
}
if (null != completeWord) {
if (0 == wordIndex && !"package".equals(completeWord)) {
in.close();
return "".equals(expectedPackage);
}
else if (1 == wordIndex) {
in.close();
return expectedPackage.equals(completeWord);
}
++ wordIndex;
}
prevChar = ch;
}
// no package or class found before end-of-file -> invalid source file
in.close();
return false;
}
catch (IOException e) {
reporter.printWarning("Could not examine file " + file + ": " + e);
return false;
}
}
/**
* Recursively try to locate valid Java packages under the given
* package specified by its name and its directory. Add the names
* of all valid packages to the result list.
*/
private void findPackages(String subpackage,
File packageDir,
Set<String> result)
{
File[] files = packageDir.listFiles();
if (null != files) {
for (int i=0; i<files.length; ++i) {
File file = files[i];
if (!file.isDirectory() && file.getName().endsWith(".java")) {
if (isValidJavaFile(file, subpackage)) {
if ("".equals(subpackage)) {
result.add(null);
}
else {
result.add(subpackage);
}
break;
}
}
}
for (int i=0; i<files.length; ++i) {
File file = files[i];
if (file.isDirectory()) {
String newSubpackage;
if (null != subpackage && subpackage.length() > 0) {
newSubpackage = subpackage + "." + file.getName();
}
else {
newSubpackage = file.getName();
}
findPackages(newSubpackage, file, result);
}
}
}
}
/**
*
*/
private static boolean validOptions(String options[][],
DocErrorReporter reporter)
{
boolean foundDocletOption = false;
for (int i = 0; i < options.length; i++)
{
String[] opt = options[i];
if (opt[0].equalsIgnoreCase("-doclet"))
{
if (foundDocletOption)
{
reporter.printError("Only one -doclet option allowed.");
return false;
}
else
{
foundDocletOption = true;
}
}
}
return true;
}
/**
* Main entry point. This is the method called when gjdoc is invoked from the
* command line.
*
* @param args
* command line arguments
*/
public static void main(String[] args)
{
try
{
//--- Remember current time for profiling purposes
Timer.setStartTime();
//--- Handle control to the Singleton instance of this class
int result = instance.start(args);
if (result < 0) {
// fatal error
System.exit(5);
}
else if (result > 0) {
// errors encountered
System.exit(1);
}
else {
// success
System.exit(0);
}
}
catch (Exception e)
{
//--- unexpected error
e.printStackTrace();
System.exit(1);
}
}
/**
* Parses command line arguments and subsequentially handles control to the
* startDoclet() method
*
* @param args The command line parameters.
*/
public static int execute(String[] args)
{
try
{
int result = instance.start(args);
if (result < 0) {
// fatal error
return 5;
}
else if (result > 0) {
// errors encountered
return 1;
}
else {
// success
return 0;
}
}
catch (Exception e)
{
// unexpected error
return 1;
}
}
/**
* @param programName Name of the program (for error messages). *disregarded*
* @param args The command line parameters.
* @returns The return code.
*/
public static int execute(String programName,
String[] args)
{
return execute(args);
}
/**
* @param programName Name of the program (for error messages).
* @param defaultDocletClassName Fully qualified class name.
* @param args The command line parameters.
* @returns The return code.
*//*
public static int execute(String programName,
String defaultDocletClassName,
String[] args)
{
// not yet implemented
}*/
/**
* @param programName Name of the program (for error messages).
* @param defaultDocletClassName Fully qualified class name.
* @param args The command line parameters.
* @returns The return code.
*//*
public static int execute(String programName,
String defaultDocletClassName,
String[] args)
{
// not yet implemented
}*/
/**
* @param programName Name of the program (for error messages).
* @param errWriter PrintWriter to receive error messages.
* @param warnWriter PrintWriter to receive error messages.
* @param noticeWriter PrintWriter to receive error messages.
* @param defaultDocletClassName Fully qualified class name.
* @param args The command line parameters.
* @returns The return code.
*//*
public static int execute(String programName,
PrintWriter errWriter,
PrintWriter warnWriter,
PrintWriter noticeWriter,
String defaultDocletClassName,
String[] args)
{
// not yet implemented
}*/
/**
* Parses command line arguments and subsequentially handles control to the
* startDoclet() method
*
* @param args
* Command line arguments, as passed to the main() method
* @return {@code -1} in case of a fatal error (invalid arguments),
* or the number of errors encountered.
* @exception ParseException
* FIXME
* @exception IOException
* if an IO problem occur
*/
public int start(String[] args) throws ParseException, IOException
{
//--- Collect unparsed arguments in array and resolve references
// to external argument files.
List<String> arguments = new ArrayList<String>(args.length);
for (int i = 0; i < args.length; ++i)
{
if (!args[i].startsWith("@"))
{
arguments.add(args[i]);
}
else
{
FileReader reader = new FileReader(args[i].substring(1));
StreamTokenizer st = new StreamTokenizer(reader);
st.resetSyntax();
st.wordChars('\u0000', '\uffff');
st.quoteChar('\"');
st.quoteChar('\'');
st.whitespaceChars(' ', ' ');
st.whitespaceChars('\t', '\t');
st.whitespaceChars('\r', '\r');
st.whitespaceChars('\n', '\n');
while (st.nextToken() != StreamTokenizer.TT_EOF)
{
arguments.add(st.sval);
}
}
}
//--- Initialize Map for option parsing
initOptions();
//--- This will hold all options recognized by gjdoc itself
// and their associated arguments.
// Contains objects of type String[], where each entry
// specifies an option along with its aguments.
List<String[]> options = new LinkedList<String[]>();
//--- This will hold all command line tokens not recognized
// to be part of a standard option.
// These options are intended to be processed by the doclet
// Contains objects of type String, where each entry is
// one unrecognized token.
List<String> customOptions = new LinkedList<String>();
rootDoc = new RootDocImpl();
reporter = rootDoc.getReporter();
//--- Iterate over all options given on the command line
for (Iterator<String> it = arguments.iterator(); it.hasNext();)
{
String arg = it.next();
//--- Check if gjdoc recognizes this option as a standard option
// and remember the options' argument count
int optlen = optionLength(arg);
//--- Argument count == 0 indicates that the option is not recognized.
// Add it to the list of custom option tokens
//--- Otherwise the option is recognized as a standard option.
// if all required arguments are supplied. Create a new String
// array for the option and its arguments, and store it
// in the options array.
if (optlen > 0)
{
String[] option = new String[optlen];
option[0] = arg;
boolean optargs_ok = true;
for (int j = 1; j < optlen && optargs_ok; ++j)
{
if (it.hasNext())
{
option[j] = (String) it.next();
if (option[j].startsWith("-"))
{
optargs_ok = false;
}
}
else
{
optargs_ok = false;
}
}
if (optargs_ok)
options.add(option);
else
{
// If the option requires more arguments than given on the
// command line, issue a fatal error
reporter.printFatal("Missing value for option " + arg + ".");
}
}
}
//--- Create an array of String arrays from the dynamic array built above
String[][] optionArr = options.toArray(new String[options.size()][0]);
//--- Validate all options and issue warnings/errors
if (validOptions(optionArr, rootDoc))
{
//--- We got valid options; parse them and store the parsed values
// in 'option_*' fields.
readOptions(optionArr);
//--- Show version and exit if requested by user
if (option_showVersion) {
System.out.println("gjdoc " + getGjdocVersion());
System.exit(0);
}
if (option_bootclasspath_specified) {
reporter.printWarning("-bootclasspath ignored: not supported by"
+ " gjdoc wrapper script, or no wrapper script in use.");
}
// If we have an empty source path list, add the current directory ('.')
if (option_sourcepath.size() == 0)
option_sourcepath.add(new File("."));
//--- We have all information we need to start the doclet at this time
if (null != option_encoding) {
rootDoc.setSourceEncoding(option_encoding);
}
else {
// be quiet about this for now:
// reporter.printNotice("No encoding specified, using platform default: " + System.getProperty("file.encoding"));
rootDoc.setSourceEncoding(System.getProperty("file.encoding"));
}
rootDoc.setSourcePath(option_sourcepath);
//addJavaLangClasses();
if (!startDoclet(arguments)) {
return -1;
}
}
return reporter.getErrorCount();
}
/*
private void addJavaLangClasses()
throws IOException
{
String resourceName = "/java.lang-classes-" + option_source + ".txt";
InputStream in = getClass().getResourceAsStream(resourceName);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
String className = line.trim();
if (className.length() > 0) {
ClassDocImpl classDoc =
new ClassDocImpl(null, new PackageDocImpl("java.lang"),
ProgramElementDocImpl.ACCESS_PUBLIC,
false, false, null);
classDoc.setClass(className);
rootDoc.addClassDoc(classDoc);
}
}
}
*/
/**
* Helper class for parsing command line arguments. An instance of this class
* represents a particular option accepted by gjdoc (e.g. '-sourcepath') along
* with the number of expected arguments and behavior to parse the arguments.
*/
private abstract class OptionProcessor
{
/**
* Number of arguments expected by this option.
*/
private int argCount;
/**
* Initializes this instance.
*
* @param argCount
* number of arguments
*/
public OptionProcessor(int argCount)
{
this.argCount = argCount;
}
/**
* Overridden by derived classes with behavior to parse the arguments
* specified with this option.
*
* @param args
* command line arguments
*/
abstract void process(String[] args);
}
/**
* Maps option tags (e.g. '-sourcepath') to OptionProcessor objects.
* Initialized only once by method initOptions(). FIXME: Rename to
* 'optionProcessors'.
*/
private static Map<String,OptionProcessor> options = null;
/**
* Initialize all OptionProcessor objects needed to scan/parse command line
* options. This cannot be done in a static initializer block because
* OptionProcessors need access to the Singleton instance of the Main class.
*/
private void initOptions()
{
options = new HashMap<String,OptionProcessor>();
//--- Put one OptionProcessor object into the map
// for each option recognized.
options.put("-overview", new OptionProcessor(2)
{
void process(String[] args)
{
System.err.println("WARNING: Unsupported option -overview ignored");
}
});
options.put("-public", new OptionProcessor(1)
{
void process(String[] args)
{
option_coverage = COVERAGE_PUBLIC;
}
});
options.put("-protected", new OptionProcessor(1)
{
void process(String[] args)
{
option_coverage = COVERAGE_PROTECTED;
}
});
options.put("-package", new OptionProcessor(1)
{
void process(String[] args)
{
option_coverage = COVERAGE_PACKAGE;
}
});
options.put("-private", new OptionProcessor(1)
{
void process(String[] args)
{
option_coverage = COVERAGE_PRIVATE;
}
});
OptionProcessor helpProcessor = new OptionProcessor(1)
{
void process(String[] args)
{
option_help = true;
}
};
options.put("-help", helpProcessor);
options.put("--help", helpProcessor);
options.put("-doclet", new OptionProcessor(2)
{
void process(String[] args)
{
option_doclet = args[0];
}
});
options.put("-docletpath", new OptionProcessor(2)
{
void process(String[] args)
{
option_docletpath = args[0];
}
});
options.put("-nowarn", new OptionProcessor(1)
{
void process(String[] args)
{
System.err.println("WARNING: Unsupported option -nowarn ignored");
}
});
options.put("-source", new OptionProcessor(2)
{
void process(String[] args)
{
option_source = args[0];
if ("1.5".equals(option_source)
|| "1.6".equals(option_source)
|| "1.7".equals(option_source)) {
System.err.println("WARNING: support for option -source " + option_source + " is experimental");
}
else if (!"1.2".equals(option_source)
&& !"1.3".equals(option_source)
&& !"1.4".equals(option_source)) {
throw new RuntimeException("Only the following values are currently"
+ " supported for option -source: 1.2, 1.3, 1.4; experimental: 1.5, 1.6, 1.7.");
}
}
});
OptionProcessor sourcePathProcessor = new OptionProcessor(2) {
void process(String[] args)
{
Debug.log(1, "-sourcepath is '" + args[0] + "'");
for (StringTokenizer st = new StringTokenizer(args[0],
File.pathSeparator); st.hasMoreTokens();)
{
String path = st.nextToken();
File file = new File(path);
if (!(file.exists()))
{
throw new RuntimeException("The source path " + path
+ " does not exist.");
}
option_sourcepath.add(file);
}
}
};
options.put("-s", sourcePathProcessor);
options.put("-sourcepath", sourcePathProcessor);
options.put("-subpackages", new OptionProcessor(2)
{
void process(String[] args)
{
StringTokenizer st = new StringTokenizer(args[0], ":");
while (st.hasMoreTokens()) {
String packageName = st.nextToken();
if (packageName.startsWith(".")
|| packageName.endsWith(".")
|| packageName.indexOf("..") > 0
|| !checkCharSet(packageName,
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_.")) {
throw new RuntimeException("Illegal package name '"
+ packageName + "'");
}
option_subpackages.add(packageName);
}
}
});
options.put("-exclude", new OptionProcessor(2)
{
void process(String[] args)
{
StringTokenizer st = new StringTokenizer(args[0], ":");
while (st.hasMoreTokens()) {
String packageName = st.nextToken();
if (packageName.startsWith(".")
|| packageName.endsWith(".")
|| packageName.indexOf("..") > 0
|| !checkCharSet(packageName,
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_.")) {
throw new RuntimeException("Illegal package name '"
+ packageName + "'");
}
option_exclude.add(packageName);
}
}
});
// TODO include other options here
options.put("-verbose", new OptionProcessor(1)
{
void process(String[] args)
{
System.err.println("WARNING: Unsupported option -verbose ignored");
}
});
options.put("-quiet", new OptionProcessor(1)
{
void process(String[] args)
{
reporter.setQuiet(true);
}
});
options.put("-locale", new OptionProcessor(2)
{
void process(String[] args)
{
String localeName = args[0];
String language = null;
String country = null;
String variant = null;
StringTokenizer st = new StringTokenizer(localeName, "_");
if (st.hasMoreTokens()) {
language = st.nextToken();
}
if (st.hasMoreTokens()) {
country = st.nextToken();
}
if (st.hasMoreTokens()) {
variant = st.nextToken();
}
if (variant != null) {
option_locale = new Locale(language, country, variant);
}
else if (country != null) {
option_locale = new Locale(language, country);
}
else if (language != null) {
option_locale = new Locale(language);
}
else {
throw new RuntimeException("Illegal locale specification '"
+ localeName + "'");
}
}
});
options.put("-encoding", new OptionProcessor(2)
{
void process(String[] args)
{
option_encoding = args[0];
}
});
options.put("-breakiterator", new OptionProcessor(1)
{
void process(String[] args)
{
option_breakiterator = true;
}
});
options.put("-licensetext", new OptionProcessor(1)
{
void process(String[] args)
{
option_licensetext = true;
}
});
options.put("-overview", new OptionProcessor(2)
{
void process(String[] args)
{
try {
getRootDoc().setRawCommentText(RootDocImpl.readHtmlBody(new File(args[0])));
}
catch (IOException e) {
throw new RuntimeException("Cannot read file specified in option -overview: " + e.getMessage());
}
}
});
options.put("-classpath", new OptionProcessor(2)
{
void process(String[] args)
{
reporter.printWarning("-classpath option could not be passed to the VM. Faking it with ");
reporter.printWarning(" System.setProperty(\"java.class.path\", \"" + args[0] + "\");");
System.setProperty("java.class.path", args[0]);
}
});
options.put("--version", new OptionProcessor(1)
{
void process(String[] args)
{
option_showVersion = true;
}
});
options.put("-bootclasspath", new OptionProcessor(1)
{
void process(String[] args)
{
option_bootclasspath_specified = true;
}
});
options.put("-all", new OptionProcessor(1)
{
void process(String[] args)
{
option_all = true;
}
});
options.put("-reflection", new OptionProcessor(1)
{
void process(String[] args)
{
option_reflection = true;
}
});
}
/**
* Determine how many arguments the given option requires.
*
* @param option
* The name of the option without leading dash.
*/
private static int optionLength(String option)
{
OptionProcessor op = (OptionProcessor) options.get(option.toLowerCase());
if (op != null)
return op.argCount;
else
return 0;
}
/**
* Process all given options. Assumes that the options have been validated
* before.
*
* @param optionArr
* Each element is a series of Strings where [0] is the name of the
* option and [1..n] are the arguments to the option.
*/
private void readOptions(String[][] optionArr)
{
//--- For each option, find the appropriate OptionProcessor
// and call its process() method
for (int i = 0; i < optionArr.length; ++i)
{
String[] opt = optionArr[i];
String[] args = new String[opt.length - 1];
System.arraycopy(opt, 1, args, 0, opt.length - 1);
OptionProcessor op = (OptionProcessor) options.get(opt[0].toLowerCase());
op.process(args);
}
}
/**
* Print command line usage.
*/
private static void usage()
{
System.out
.print("\n"
+ "USAGE: gjdoc [options] [packagenames] "
+ "[sourcefiles] [@files]\n\n"
+ " --version Show version information and exit\n"
+ " -all Process all source files found in the source path\n"
+ " -overview <file> Read overview documentation from HTML file\n"
+ " -public Include only public classes and members\n"
+ " -protected Include protected and public classes and members\n"
+ " This is the default\n"
+ " -package Include package/protected/public classes and members\n"
+ " -private Include all classes and members\n"
+ " -help, --help Show this information\n"
+ " -doclet <class> Doclet class to use for generating output\n"
+ " -docletpath <classpath> Specifies the search path for the doclet and\n"
+ " dependencies\n"
+ " -source <release> Provide source compatibility with specified\n"
+ " release (1.4 to handle assertion)\n"
+ " -sourcepath <pathlist> Where to look for source files\n"
+ " -s <pathlist> Alias for -sourcepath\n"
+ " -subpackages <spkglist> List of subpackages to recursively load\n"
+ " -exclude <pkglist> List of packages to exclude\n"
+ " -verbose Output messages about what Gjdoc is doing [ignored]\n"
+ " -quiet Do not print non-error and non-warning messages\n"
+ " -locale <name> Locale to be used, e.g. en_US or en_US_WIN\n"
+ " -encoding <name> Source file encoding name\n"
+ " -breakiterator Compute first sentence with BreakIterator\n"
+ " -classpath <pathlist> Set the path used for loading auxilliary classes\n"
+ "\n"
+ "Standard doclet options:\n"
+ " -d Set target directory\n"
+ " -use Includes the 'Use' page for each documented class\n"
+ " and package\n"
+ " -version Includes the '@version' tag\n"
+ " -author Includes the '@author' tag\n"
+ " -splitindex Splits the index file into multiple files\n"
+ " -windowtitle <text> Browser window title\n"
+ " -doctitle <text> Title near the top of the overview summary file\n"
+ " (HTML allowed)\n"
+ " -title <text> Title for this set of API documentation\n"
+ " (deprecated, -doctitle should be used instead)\n"
+ " -header <text> Text to include in the top navigation bar\n"
+ " (HTML allowed)\n"
+ " -footer <text> Text to include in the bottom navigation bar\n"
+ " (HTML allowed)\n"
+ " -bottom <text> Text to include at the bottom of each output file\n"
+ " (HTML allowed)\n"
+ " -link <extdoc URL> Link to external generated documentation at URL\n"
+ " -linkoffline <extdoc URL> <packagelistLoc>\n"
+ " Link to external generated documentation for\n"
+ " the specified package-list\n"
+ " -linksource Creates an HTML version of each source file\n"
+ " -group <groupheading> <packagepattern:packagepattern:...>\n"
+ " Separates packages on the overview page into groups\n"
+ " -nodeprecated Prevents the generation of any deprecated API\n"
+ " -nodeprecatedlist Prevents the generation of the file containing\n"
+ " the list of deprecated APIs and the link to the\n"
+ " navigation bar to that page\n"
+ " -nosince Omit the '@since' tag\n"
+ " -notree Do not generate the class/interface hierarchy page\n"
+ " -noindex Do not generate the index file\n"
+ " -nohelp Do not generate the help link\n"
+ " -nonavbar Do not generate the navbar, header and footer\n"
+ " -helpfile <filen> Path to an alternate help file\n"
+ " -stylesheetfile <file> Path to an alternate CSS stylesheet\n"
+ " -addstylesheet <file> Path to an additional CSS stylesheet\n"
+ " -serialwarn Complain about missing '@serial' tags [ignored]\n"
+ " -charset <IANACharset> Specifies the HTML charset\n"
+ " -docencoding <IANACharset>\n"
+ " Specifies the encoding of the generated HTML files\n"
+ " -tag <tagname>:Xaoptcmf:\"<taghead>\"\n"
+ " Enables gjdoc to interpret a custom tag\n"
+ " -taglet Adds a Taglet class to the map of taglets\n"
+ " -tagletpath Sets the CLASSPATH to load subsequent Taglets from\n"
+ " -docfilessubdirs Enables deep copy of 'doc-files' directories\n"
+ " -excludedocfilessubdir <name1:name2:...>\n"
+ " Excludes 'doc-files' subdirectories with a give name\n"
+ " -noqualifier all|<packagename1:packagename2:...>\n"
+ " Do never fully qualify given package names\n"
+ " -nocomment Suppress the entire comment body including the main\n"
+ " description and all tags, only generate declarations\n"
+ "\n"
+ "Gjdoc extension options:\n"
+ " -reflection Use reflection for resolving unqualified class names\n"
+ " -licensetext Include license text from source files\n"
+ " -validhtml Use valid HTML/XML names (breaks compatibility)\n"
+ " -baseurl <url> Hardwire the given base URL into generated pages\n"
/**
+ " -genhtml Generate HTML code instead of XML code. This is the\n"
+ " default.\n"
+ " -geninfo Generate Info code instead of XML code.\n"
+ " -xslsheet <file> If specified, XML files will be written to a\n"
+ " temporary directory and transformed using the\n"
+ " given XSL sheet. The result of the transformation\n"
+ " is written to the output directory. Not required if\n"
+ " -genhtml or -geninfo has been specified.\n"
+ " -xmlonly Generate XML code only, do not generate HTML code.\n"
+ " -bottomnote HTML code to include at the bottom of each page.\n"
+ " -nofixhtml If not specified, heurestics will be applied to\n"
+ " fix broken HTML code in comments.\n"
+ " -nohtmlwarn Do not emit warnings when encountering broken HTML\n"
+ " code.\n"
+ " -noemailwarn Do not emit warnings when encountering strings like\n"
+ " <abc@foo.com>.\n"
+ " -indentstep <n> How many spaces to indent each tag level in\n"
+ " generated XML code.\n"
+ " -xsltdriver <class> Specifies the XSLT driver to use for transformation.\n"
+ " By default, xsltproc is used.\n"
+ " -postprocess <class> XmlDoclet postprocessor class to apply after XSL\n"
+ " transformation.\n"
+ " -compress Generated info pages will be Zip-compressed.\n"
+ " -workpath Specify a temporary directory to use.\n"
+ " -authormail <type> Specify handling of mail addresses in @author tags.\n"
+ " no-replace do not replace mail addresses (default).\n"
+ " mailto-name replace by <a>Real Name</a>.\n"
+ " name-mailto-address replace by Real Name (<a>abc@foo.com</a>).\n"
+ " name-mangled-address replace by Real Name (<a>abc AT foo DOT com</a>).\n"
**/
);
}
/**
* The root of the gjdoc tool.
*
* @return all the options of the gjdoc application.
*/
public static RootDocImpl getRootDoc()
{
return rootDoc;
}
/**
* Get the gjdoc singleton.
*
* @return the gjdoc instance.
*/
public static Main getInstance()
{
return instance;
}
/**
* Is this access level covered?
*
* @param accessLevel
* the access level we want to know if it is covered.
* @return true if the access level is covered.
*/
public boolean includeAccessLevel(int accessLevel)
{
return coverageTemplates[option_coverage][accessLevel];
}
/**
* Is the doclet running?
*
* @return true if it's running
*/
public boolean isDocletRunning()
{
return docletRunning;
}
/**
* Check the charset. Check that all the characters of the string 'toCheck'
* and query if they exist in the 'charSet'. The order does not matter. The
* number of times a character is in the variable does not matter.
*
* @param toCheck
* the charset to check.
* @param charSet
* the reference charset
* @return true if they match.
*/
public static boolean checkCharSet(String toCheck, String charSet)
{
for (int i = 0; i < toCheck.length(); ++i)
{
if (charSet.indexOf(toCheck.charAt(i)) < 0)
return false;
}
return true;
}
/**
* Makes the RootDoc eligible for the GC.
*/
public static void releaseRootDoc()
{
rootDoc.flush();
}
/**
* Return whether the -breakiterator option has been specified.
*/
public boolean isUseBreakIterator()
{
return this.option_breakiterator
|| !getLocale().getLanguage().equals(Locale.ENGLISH.getLanguage());
}
/**
* Return whether boilerplate license text should be copied.
*/
public boolean isCopyLicenseText()
{
return this.option_licensetext;
}
/**
* Return the locale specified using the -locale option or the
* default locale;
*/
public Locale getLocale()
{
return this.option_locale;
}
/**
* Return the collator to use based on the specified -locale
* option. If no collator can be found for the given locale, a
* warning is emitted and the default collator is used instead.
*/
public Collator getCollator()
{
if (null == this.collator) {
Locale locale = getLocale();
this.collator = Collator.getInstance(locale);
Locale defaultLocale = Locale.getDefault();
if (null == this.collator
&& !defaultLocale.equals(locale)) {
this.collator = Collator.getInstance(defaultLocale);
if (null != this.collator) {
reporter.printWarning("No collator found for locale "
+ locale.getDisplayName()
+ "; using collator for default locale "
+ defaultLocale.getDisplayName()
+ ".");
}
else {
this.collator = Collator.getInstance();
reporter.printWarning("No collator found for specified locale "
+ locale.getDisplayName()
+ " or default locale "
+ defaultLocale.getDisplayName()
+ ": using default collator.");
}
}
if (null == this.collator) {
this.collator = Collator.getInstance();
reporter.printWarning("No collator found for locale "
+ locale.getDisplayName()
+ ": using default collator.");
}
}
return this.collator;
}
public boolean isCacheRawComments()
{
return true;
}
public String getGjdocVersion()
{
if (null == gjdocVersion) {
try {
Properties versionProperties = new Properties();
versionProperties.load(getClass().getResourceAsStream("version.properties"));
gjdocVersion = versionProperties.getProperty("gjdoc.version");
}
catch (IOException ignore) {
}
if (null == gjdocVersion) {
gjdocVersion = "unknown";
}
}
return gjdocVersion;
}
public boolean isReflectionEnabled()
{
return this.option_reflection;
}
}
|
gpl-2.0
|
jaimefreire/wordpress
|
wp-content/themes/zinnia/image.php
|
789
|
<?php get_header(); ?>
<section class="section-wide" role="main">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class( "article" ); ?> id="post-<?php the_ID(); ?>" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h1 class="post-title"><?php the_title(); ?></h1>
</header>
<img src="<?php echo wp_get_attachment_url( $post->ID ); ?>" alt="<?php the_title(); ?>" class="centered" />
<article class="attachment-caption"><?php the_excerpt(); ?></article>
<article class="attachment-desc"><?php the_content(); ?></article>
</article><!-- .article -->
<?php endwhile; endif; ?>
</section><!-- .section -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
gpl-2.0
|
ratbird/hope
|
lib/include/deprecated_tabs_layout.php
|
732
|
<div id="layout_page">
<? if (PageLayout::isHeaderEnabled() && is_object($GLOBALS['user']) && $GLOBALS['user']->id != 'nobody' && Navigation::hasItem('/course') && Navigation::getItem('/course')->isActive() && $_SESSION['seminar_change_view_'.$GLOBALS['SessionSeminar']]) : ?>
<?= $GLOBALS["template_factory"]->open('change_view')->render() ?>
<? endif ?>
<? $navigation = PageLayout::getTabNavigation() ?>
<? if (PageLayout::isHeaderEnabled() && isset($navigation)) : ?>
<? $tabs_template = $GLOBALS["template_factory"]->open('tabs') ?>
<? $tabs_template->set_attribute("navigation", $navigation) ?>
<?= $tabs_template->render() ?>
<? endif ?>
|
gpl-2.0
|
Kev/maybelater
|
static/ext-2.1/source/locale/ext-lang-nl.js
|
8692
|
/*
* Ext JS Library 2.1
* Copyright(c) 2006-2008, Ext JS, LLC.
* licensing@extjs.com
*
* http://extjs.com/license
*/
/*
* List compiled by mystix on the extjs.com forums.
* Thank you Mystix!
*
* Dutch Translations
* by Ido Sebastiaan Bas van Oostveen (12 Oct 2007)
*/
/* Ext Core translations */
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">Bezig met laden...</div>';
/* Ext single string translations */
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.Grid){
Ext.grid.Grid.prototype.ddText = "{0} geselecteerde rij(en)";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "Sluit dit tabblad";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "De waarde in dit veld is onjuist";
}
if(Ext.LoadMask){
Ext.LoadMask.prototype.msg = "Bezig met laden...";
}
/* Javascript month and days translations */
Date.monthNames = [
"Januari",
"Februari",
"Maart",
"April",
"Mei",
"Juni",
"Juli",
"Augustus",
"September",
"Oktober",
"November",
"December"
];
Date.getShortMonthName = function(month) {
return Date.monthNames[month].substring(0, 3);
};
Date.monthNumbers = {
Jan : 0,
Feb : 1,
Maa : 2,
Apr : 3,
Mei : 4,
Jun : 5,
Jul : 6,
Aug : 7,
Sep : 8,
Okt : 9,
Nov : 10,
Dec : 11
};
Date.getMonthNumber = function(name) {
return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
};
Date.dayNames = [
"Zondag",
"Maandag",
"Dinsdag",
"Woensdag",
"Donderdag",
"Vrijdag",
"Zaterdag"
];
Date.getShortDayName = function(day) {
return Date.dayNames[day].substring(0, 3);
};
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "OK",
cancel : "Annuleren",
yes : "Ja",
no : "Nee"
};
}
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 || "d-m-y");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "Vandaag",
minText : "Deze datum is eerder dan de minimum datum",
maxText : "Deze datum is later dan de maximum datum",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : 'Volgende Maand (Control+Rechts)',
prevText : 'Vorige Maand (Control+Links)',
monthYearText : 'Kies een maand (Control+Omhoog/Beneden volgend/vorige jaar)',
todayTip : "{0} (Spatie)",
format : "d-m-y",
okText : " OK ",
cancelText : "Annuleren",
startDay : 1
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "Pagina",
afterPageText : "van {0}",
firstText : "Eerste Pagina",
prevText : "Vorige Pagina",
nextText : "Volgende Pagina",
lastText : "Laatste Pagina",
refreshText : "Ververs",
displayMsg : "Getoond {0} - {1} van {2}",
emptyMsg : 'Geen gegeven om weer te geven'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "De minimale lengte voor dit veld is {0}",
maxLengthText : "De maximale lengte voor dit veld is {0}",
blankText : "Dit veld is verplicht",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "De minimale waarde voor dit veld is {0}",
maxText : "De maximale waarde voor dit veld is {0}",
nanText : "{0} is geen geldig getal"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "Uitgeschakeld",
disabledDatesText : "Uitgeschakeld",
minText : "De datum in dit veld moet na {0} liggen",
maxText : "De datum in dit veld moet voor {0} liggen",
invalidText : "{0} is geen geldige datum - formaat voor datum is {1}",
format : "d-m-y",
altFormats : "d/m/Y|d-m-y|d-m-Y|d/m|d-m|dm|dmy|dmY|d|Y-m-d"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "Bezig met laden...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : 'Dit veld moet een e-mail adres zijn in het formaat "gebruiker@domein.nl"',
urlText : 'Dit veld moet een URL zijn in het formaat "http:/'+'/www.domein.nl"',
alphaText : 'Dit veld mag alleen letters en _ bevatten',
alphanumText : 'Dit veld mag alleen letters, cijfers en _ bevatten'
});
}
if(Ext.form.HtmlEditor){
Ext.apply(Ext.form.HtmlEditor.prototype, {
createLinkText : 'Vul hier het Internet adres voor de link in:',
buttonTips : {
bold : {
title: 'Vet (Ctrl+B)',
text: 'Maak de geselecteerde tekst vet gedrukt.',
cls: 'x-html-editor-tip'
},
italic : {
title: 'Cursief (Ctrl+I)',
text: 'Maak de geselecteerde tekst cursief.',
cls: 'x-html-editor-tip'
},
underline : {
title: 'Onderstrepen (Ctrl+U)',
text: 'Onderstreep de geselecteerde tekst.',
cls: 'x-html-editor-tip'
},
increasefontsize : {
title: 'Tekst Vergroten',
text: 'Vergroot het lettertype.',
cls: 'x-html-editor-tip'
},
decreasefontsize : {
title: 'Tekst Verkleinen',
text: 'Verklein het lettertype.',
cls: 'x-html-editor-tip'
},
backcolor : {
title: 'Tekst Achtergrond Kleur',
text: 'Verander de achtergrond kleur van de geselecteerde tekst.',
cls: 'x-html-editor-tip'
},
forecolor : {
title: 'Lettertype Kleur',
text: 'Verander de kleur van de geselecteerde tekst.',
cls: 'x-html-editor-tip'
},
justifyleft : {
title: 'Tekst Links Uitlijnen',
text: 'Lijn de tekst links uit.',
cls: 'x-html-editor-tip'
},
justifycenter : {
title: 'Tekst Centreren',
text: 'Centreer de tekst in de editor.',
cls: 'x-html-editor-tip'
},
justifyright : {
title: 'Tekst Richts Uitlijnen',
text: 'Lijn de tekst rechts uit.',
cls: 'x-html-editor-tip'
},
insertunorderedlist : {
title: 'Punten Lijst',
text: 'Begin een ongenummerde lijst.',
cls: 'x-html-editor-tip'
},
insertorderedlist : {
title: 'Genummerde Lijst',
text: 'Begin een genummerde lijst.',
cls: 'x-html-editor-tip'
},
createlink : {
title: 'Hyperlink',
text: 'Maak van de geselecteerde tekst een hyperlink.',
cls: 'x-html-editor-tip'
},
sourceedit : {
title: 'Bron Aanpassen',
text: 'Schakel modus over naar bron aanpassen.',
cls: 'x-html-editor-tip'
}
}
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "Sorteer Oplopend",
sortDescText : "Sorteer Aflopend",
lockText : "Kolom Vastzetten",
unlockText : "Kolom Vrijgeven",
columnsText : "Kolommen"
});
}
if(Ext.grid.GroupingView){
Ext.apply(Ext.grid.GroupingView.prototype, {
emptyGroupText : '(Geen)',
groupByText : 'Dit veld groeperen',
showGroupsText : 'Zien als groepen'
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "Naam",
valueText : "Waarde",
dateFormat : "Y-m-j"
});
}
if(Ext.layout.BorderLayout.SplitRegion){
Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
splitTip : "Sleep om grootte aan te passen.",
collapsibleSplitTip : "Sleep om grootte aan te passen. Dubbel klikken om te verbergen."
});
}
|
gpl-2.0
|
lucasicf/metricgenerator-jdk-compiler
|
test/tools/javac/generics/Crash02.java
|
1455
|
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4881292
* @summary compiler crash in class writer
* @author gafter
*
* @compile Crash02.java
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
class Bug2<T> implements Iterable<T> {
private List<T> data;
public Bug2() {
data = new ArrayList<T>();
}
public Iterator<T> iterator() {
return data.iterator();
}
}
|
gpl-2.0
|
opinkerfi/check_mk
|
web/plugins/config/bi.py
|
1626
|
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2013 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# ails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
aggregation_rules = {}
aggregations = []
host_aggregations = []
bi_compile_log = None
bi_precompile_on_demand = False
|
gpl-2.0
|
ehiggs/easybuild-easyblocks
|
easybuild/easyblocks/i/inspector.py
|
3554
|
# #
# Copyright 2013 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (http://www.herculesstichting.be/in_English)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild 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 v2.
#
# EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>.
# #
"""
EasyBuild support for installing Intel Inspector, implemented as an easyblock
@author: Kenneth Hoste (Ghent University)
"""
from distutils.version import LooseVersion
from easybuild.easyblocks.generic.intelbase import IntelBase, ACTIVATION_NAME_2012, LICENSE_FILE_NAME_2012
class EB_Inspector(IntelBase):
"""
Support for installing Intel Inspector
"""
def install_step(self):
"""
Actual installation
- create silent cfg file
- execute command
"""
silent_cfg_names_map = None
if LooseVersion(self.version) <= LooseVersion('2013_update6'):
silent_cfg_names_map = {
'activation_name': ACTIVATION_NAME_2012,
'license_file_name': LICENSE_FILE_NAME_2012,
}
super(EB_Inspector, self).install_step(silent_cfg_names_map=silent_cfg_names_map)
def make_module_req_guess(self):
"""
A dictionary of possible directories to look for
"""
guesses = super(EB_Inspector, self).make_module_req_guess()
if self.cfg['m32']:
guesses.update({
'PATH': ['bin32'],
'LD_LIBRARY_PATH': ['lib32'],
'LIBRARY_PATH': ['lib32'],
})
else:
guesses.update({
'PATH': ['bin64'],
'LD_LIBRARY_PATH': ['lib64'],
'LIBRARY_PATH': ['lib64'],
})
guesses.update({
'CPATH': ['include'],
'FPATH': ['include'],
})
return guesses
def make_module_extra(self):
"""Custom variable definitions in module file."""
txt = super(EB_Inspector, self).make_module_extra()
txt += self.module_generator.prepend_paths(self.license_env_var, self.license_file, allow_abs=True)
return txt
def sanity_check_step(self):
"""Custom sanity check paths for Intel Inspector."""
binaries = ['inspxe-cl', 'inspxe-feedback', 'inspxe-gui', 'inspxe-runmc', 'inspxe-runtc']
if self.cfg['m32']:
files = ["bin32/%s" % x for x in binaries]
dirs = ["lib32", "include"]
else:
files = ["bin64/%s" % x for x in binaries]
dirs = ["lib64", "include"]
custom_paths = {
'files': files,
'dirs': dirs,
}
super(EB_Inspector, self).sanity_check_step(custom_paths=custom_paths)
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.