repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
kohoumas/click-ns3 | elements/wifi/sr/counterflood.cc | 10369 | /*
* CounterFlood.{cc,hh} -- DSR implementation
* John Bicket
*
* Copyright (c) 1999-2001 Massachuscounterfloods Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "counterflood.hh"
#include <click/ipaddress.hh>
#include <click/confparse.hh>
#include <click/error.hh>
#include <click/glue.hh>
#include <click/straccum.hh>
#include <clicknet/ether.h>
#include "srpacket.hh"
CLICK_DECLS
CounterFlood::CounterFlood()
: _en(),
_et(0),
_packets_originated(0),
_packets_tx(0),
_packets_rx(0)
{
static unsigned char bcast_addr[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
_bcast = EtherAddress(bcast_addr);
}
CounterFlood::~CounterFlood()
{
}
int
CounterFlood::configure (Vector<String> &conf, ErrorHandler *errh)
{
int ret;
_debug = false;
_count = 1;
_max_delay_ms = 750;
_history = 100;
ret = cp_va_kparse(conf, this, errh,
"ETHTYPE", 0, cpUnsigned, &_et,
"IP", 0, cpIPAddress, &_ip,
"BCAST_IP", 0, cpIPAddress, &_bcast_ip,
"ETH", 0, cpEtherAddress, &_en,
"COUNT", 0, cpInteger, &_count,
"MAX_DELAY_MS", 0, cpUnsigned, &_max_delay_ms,
/* below not required */
"DEBUG", 0, cpBool, &_debug,
"HISTORY", 0, cpUnsigned, &_history,
cpEnd);
if (!_et)
return errh->error("ETHTYPE not specified");
if (!_ip)
return errh->error("IP not specified");
if (!_bcast_ip)
return errh->error("BCAST_IP not specified");
if (!_en)
return errh->error("ETH not specified");
return ret;
}
int
CounterFlood::initialize (ErrorHandler *)
{
return 0;
}
void
CounterFlood::forward(Broadcast *bcast) {
if (_debug) {
click_chatter("%{element} seq %d my_expected_rx %d sending\n",
this,
bcast->_seq
);
}
if (_debug) {
click_chatter("%{element} forwarding seq %d\n",
this,
bcast->_seq);
}
Packet *p_in = bcast->_p;
if (!p_in) {
return;
}
click_ether *eh_in = (click_ether *) p_in->data();
struct srpacket *pk_in = (struct srpacket *) (eh_in+1);
int hops = 1;
int len = 0;
if (bcast->_originated) {
hops = 1;
len = srpacket::len_with_data(hops, p_in->length());
} else {
hops = pk_in->num_links() + 1;
len = srpacket::len_with_data(hops, pk_in->data_len());
}
WritablePacket *p = Packet::make(len + sizeof(click_ether));
if (p == 0)
return;
click_ether *eh = (click_ether *) p->data();
struct srpacket *pk = (struct srpacket *) (eh+1);
memset(pk, '\0', len);
pk->_version = _sr_version;
pk->_type = PT_DATA;
pk->_flags = 0;
pk->_qdst = _bcast_ip;
pk->set_num_links(hops);
for (int x = 0; x < hops; x++) {
pk->set_link_node(x, pk_in->get_link_node(x));
}
pk->set_link_node(hops,_ip);
pk->set_next(hops);
pk->set_seq(bcast->_seq);
uint32_t link_seq = click_random();
pk->set_seq2(link_seq);
bcast->_sent_seq.push_back(link_seq);
if (bcast->_originated) {
memcpy(pk->data(), p_in->data(), p_in->length());
pk->set_data_len(p_in->length());
} else {
memcpy(pk->data(), pk_in->data(), pk_in->data_len());
pk->set_data_len(pk_in->data_len());
}
eh->ether_type = htons(_et);
memcpy(eh->ether_shost, _en.data(), 6);
memset(eh->ether_dhost, 0xff, 6);
output(0).push(p);
_packets_tx++;
bcast->_actually_sent = true;
bcast->_rx_from.push_back(_ip);
bcast->_rx_from_seq.push_back(link_seq);
}
void
CounterFlood::forward_hook()
{
Timestamp now = Timestamp::now();
for (int x = 0; x < _packets.size(); x++) {
if (now > _packets[x]._to_send) {
/* this timer has expired */
if (!_packets[x]._forwarded &&
(!_count || _packets[x]._num_rx < _count)) {
/* we haven't forwarded this packet yet */
forward(&_packets[x]);
}
_packets[x]._forwarded = true;
}
}
}
void
CounterFlood::trim_packets() {
/* only keep track of the last _max_packets */
while ((_packets.size() > _history)) {
/* unschedule and remove packet*/
if (_debug) {
click_chatter("%{element} removing seq %d\n",
this,
_packets[0]._seq);
}
_packets[0].del_timer();
if (_packets[0]._p != 0) {
_packets[0]._p->kill();
}
_packets.pop_front();
}
}
void
CounterFlood::push(int port, Packet *p_in)
{
Timestamp now = Timestamp::now();
if (port == 1) {
_packets_originated++;
/* from me */
int index = _packets.size();
_packets.push_back(Broadcast());
_packets[index]._seq = click_random();
_packets[index]._originated = true;
_packets[index]._p = p_in->clone();
_packets[index]._num_rx = 0;
_packets[index]._first_rx = now;
_packets[index]._forwarded = true;
_packets[index]._actually_sent = false;
_packets[index].t = NULL;
_packets[index]._to_send = now;
if (_debug) {
click_chatter("%{element} original packet %d, seq %d\n",
this,
_packets_originated,
_packets[index]._seq);
}
p_in->kill();
forward(&_packets[index]);
} else {
_packets_rx++;
click_ether *eh = (click_ether *) p_in->data();
struct srpacket *pk = (struct srpacket *) (eh+1);
uint32_t seq = pk->seq();
uint32_t link_seq = pk->seq2();
int index = -1;
for (int x = 0; x < _packets.size(); x++) {
if (_packets[x]._seq == seq) {
index = x;
break;
}
}
IPAddress src = pk->get_link_node(pk->num_links() - 1);
if (index == -1) {
/* haven't seen this packet before */
index = _packets.size();
_packets.push_back(Broadcast());
_packets[index]._seq = seq;
_packets[index]._originated = false;
_packets[index]._p = p_in->clone();
_packets[index]._num_rx = 0;
_packets[index]._first_rx = now;
_packets[index]._forwarded = false;
_packets[index]._actually_sent = false;
_packets[index].t = NULL;
_packets[index]._rx_from.push_back(src);
_packets[index]._rx_from_seq.push_back(link_seq);
/* schedule timer */
int delay_time = click_random(1, _max_delay_ms);
sr_assert(delay_time > 0);
_packets[index]._to_send = now + Timestamp::make_msec(delay_time);
_packets[index].t = new Timer(static_forward_hook, (void *) this);
_packets[index].t->initialize(this);
_packets[index].t->schedule_at(_packets[index]._to_send);
if (_debug) {
click_chatter("%{element} first_rx seq %d src %s",
this,
_packets[index]._seq,
src.unparse().c_str());
}
/* finally, clone the packet and push it out */
output(1).push(p_in);
} else {
if (_debug) {
click_chatter("%{element} extra_rx seq %d src %s",
this,
_packets[index]._seq,
src.unparse().c_str());
}
/* we've seen this packet before */
p_in->kill();
}
_packets[index]._num_rx++;
_packets[index]._rx_from.push_back(src);
_packets[index]._rx_from_seq.push_back(link_seq);
}
trim_packets();
}
String
CounterFlood::print_packets()
{
StringAccum sa;
for (int x = 0; x < _packets.size(); x++) {
sa << "ip " << _ip;
sa << " seq " << _packets[x]._seq;
sa << " originated " << _packets[x]._originated;
sa << " actual_first_rx true";
sa << " num_rx " << _packets[x]._num_rx;
sa << " num_tx " << (int) _packets[x]._actually_sent;
sa << " sent_seqs ";
for (int y = 0; y < _packets[x]._sent_seq.size(); y++) {
sa << _packets[x]._sent_seq[y] << " ";
}
sa << " rx_from ";
for (int y = 0; y < _packets[x]._rx_from.size(); y++) {
sa << _packets[x]._rx_from[y] << " " << _packets[x]._rx_from_seq[y] << " ";
}
sa << "\n";
}
return sa.take_string();
}
String
CounterFlood::read_param(Element *e, void *vparam)
{
CounterFlood *f = (CounterFlood *) e;
switch ((intptr_t)vparam) {
case 0:
return cp_unparse_bool(f->_debug) + "\n";
case 1:
return String(f->_history) + "\n";
case 2:
return String(f->_count) + "\n";
case 3:
return String(f->_max_delay_ms) + "\n";
case 4:
return f->print_packets();
default:
return "";
}
}
int
CounterFlood::write_param(const String &in_s, Element *e, void *vparam,
ErrorHandler *errh)
{
CounterFlood *f = (CounterFlood *)e;
String s = cp_uncomment(in_s);
switch((intptr_t)vparam) {
case 0: { //debug
bool debug;
if (!cp_bool(s, &debug))
return errh->error("debug parameter must be boolean");
f->_debug = debug;
break;
}
case 1: { // history
int history;
if (!cp_integer(s, &history))
return errh->error("history parameter must be integer");
f->_history = history;
break;
}
case 2: { // count
int count;
if (!cp_integer(s, &count))
return errh->error("count parameter must be integer");
f->_count = count;
break;
}
case 3: { // max_delay_ms
int max_delay_ms;
if (!cp_integer(s, &max_delay_ms))
return errh->error("max_delay_ms parameter must be integer");
f->_max_delay_ms = max_delay_ms;
break;
}
case 5: { // clear
f->_packets.clear();
break;
}
}
return 0;
}
void
CounterFlood::add_handlers()
{
add_read_handler("debug", read_param, (void *) 0);
add_read_handler("history", read_param, (void *) 1);
add_read_handler("count", read_param, (void *) 2);
add_read_handler("max_delay_ms", read_param, (void *) 3);
add_read_handler("packets", read_param, (void *) 4);
add_write_handler("debug", write_param, (void *) 0);
add_write_handler("history", write_param, (void *) 1);
add_write_handler("count", write_param, (void *) 2);
add_write_handler("max_delay_ms", write_param , (void *) 3);
add_write_handler("clear", write_param, (void *) 5);
}
CLICK_ENDDECLS
EXPORT_ELEMENT(CounterFlood)
| gpl-2.0 |
Zarel/warzone2100 | lib/ivis_opengl/imdload.cpp | 20395 | /*
This file is part of Warzone 2100.
Copyright (C) 1999-2004 Eidos Interactive
Copyright (C) 2005-2011 Warzone 2100 Project
Warzone 2100 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.
Warzone 2100 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 Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*!
* \file imdload.c
*
* Load IMD (.pie) files
*/
#include "lib/framework/frame.h"
#include "lib/framework/string_ext.h"
#include "lib/framework/frameresource.h"
#include "lib/framework/fixedpoint.h"
#include "lib/ivis_opengl/piematrix.h"
#include "ivisdef.h" // for imd structures
#include "imd.h" // for imd structures
#include "tex.h" // texture page loading
static bool AtEndOfFile(const char *CurPos, const char *EndOfFile)
{
while ( *CurPos == 0x00 || *CurPos == 0x09 || *CurPos == 0x0a || *CurPos == 0x0d || *CurPos == 0x20 )
{
CurPos++;
if (CurPos >= EndOfFile)
{
return true;
}
}
if (CurPos >= EndOfFile)
{
return true;
}
return false;
}
/*!
* Load shape level polygons
* \param ppFileData Pointer to the data (usualy read from a file)
* \param s Pointer to shape level
* \return false on error (memory allocation failure/bad file format), true otherwise
* \pre ppFileData loaded
* \pre s allocated
* \pre s->npolys set
* \post s->polys allocated (iFSDPoly * s->npolys)
* \post s->pindex allocated for each poly
*/
static bool _imd_load_polys( const char **ppFileData, iIMDShape *s, int pieVersion)
{
const char *pFileData = *ppFileData;
unsigned int i, j;
iIMDPoly *poly;
s->numFrames = 0;
s->animInterval = 0;
s->polys = (iIMDPoly*)malloc(sizeof(iIMDPoly) * s->npolys);
if (s->polys == NULL)
{
debug(LOG_ERROR, "(_load_polys) Out of memory (polys)");
return false;
}
for (i = 0, poly = s->polys; i < s->npolys; i++, poly++)
{
unsigned int flags, npnts;
int cnt;
if (sscanf(pFileData, "%x %u%n", &flags, &npnts, &cnt) != 2)
{
debug(LOG_ERROR, "(_load_polys) [poly %u] error loading flags and npoints", i);
}
pFileData += cnt;
poly->flags = flags;
poly->npnts = npnts;
ASSERT_OR_RETURN(false, npnts == 3, "Invalid polygon size (%d)", npnts);
if (sscanf(pFileData, "%d %d %d%n", &poly->pindex[0], &poly->pindex[1], &poly->pindex[2], &cnt) != 3)
{
debug(LOG_ERROR, "failed reading triangle, point %d", i);
return false;
}
pFileData += cnt;
// calc poly normal
{
Vector3f p0, p1, p2;
//assumes points already set
p0.x = s->points[poly->pindex[0]].x;
p0.y = s->points[poly->pindex[0]].y;
p0.z = s->points[poly->pindex[0]].z;
p1.x = s->points[poly->pindex[1]].x;
p1.y = s->points[poly->pindex[1]].y;
p1.z = s->points[poly->pindex[1]].z;
p2.x = s->points[poly->pindex[poly->npnts-1]].x;
p2.y = s->points[poly->pindex[poly->npnts-1]].y;
p2.z = s->points[poly->pindex[poly->npnts-1]].z;
poly->normal = pie_SurfaceNormal3fv(p0, p1, p2);
}
if (poly->flags & iV_IMD_TEXANIM)
{
int nFrames, pbRate, tWidth, tHeight;
// even the psx needs to skip the data
if (sscanf(pFileData, "%d %d %d %d%n", &nFrames, &pbRate, &tWidth, &tHeight, &cnt) != 4)
{
debug(LOG_ERROR, "(_load_polys) [poly %u] error reading texanim data", i);
return false;
}
pFileData += cnt;
ASSERT(tWidth > 0, "%s: texture width = %d", GetLastResourceFilename(), tWidth);
ASSERT(tHeight > 0, "%s: texture height = %d (width=%d)", GetLastResourceFilename(), tHeight, tWidth);
/* Must have same number of frames and same playback rate for all polygons */
s->numFrames = nFrames;
s->animInterval = pbRate;
poly->texAnim.x = tWidth / OLD_TEXTURE_SIZE_FIX;
poly->texAnim.y = tHeight / OLD_TEXTURE_SIZE_FIX;
}
else
{
poly->texAnim.x = 0;
poly->texAnim.y = 0;
}
// PC texture coord routine
if (poly->flags & iV_IMD_TEX)
{
int nFrames, framesPerLine, frame;
nFrames = MAX(1, s->numFrames);
poly->texCoord = (Vector2f *)malloc(sizeof(*poly->texCoord) * nFrames * poly->npnts);
ASSERT_OR_RETURN(false, poly->texCoord, "Out of memory allocating texture coordinates");
framesPerLine = OLD_TEXTURE_SIZE_FIX / (poly->texAnim.x * OLD_TEXTURE_SIZE_FIX);
for (j = 0; j < poly->npnts; j++)
{
float VertexU, VertexV;
if (sscanf(pFileData, "%f %f%n", &VertexU, &VertexV, &cnt) != 2)
{
debug(LOG_ERROR, "(_load_polys) [poly %u] error reading tex outline", i);
return false;
}
pFileData += cnt;
if (pieVersion != PIE_FLOAT_VER)
{
VertexU /= OLD_TEXTURE_SIZE_FIX;
VertexV /= OLD_TEXTURE_SIZE_FIX;
}
for (frame = 0; frame < nFrames; frame++)
{
const int uFrame = (frame % framesPerLine) * (poly->texAnim.x * OLD_TEXTURE_SIZE_FIX);
const int vFrame = (frame / framesPerLine) * (poly->texAnim.y * OLD_TEXTURE_SIZE_FIX);
Vector2f *c = &poly->texCoord[frame * poly->npnts + j];
c->x = VertexU + uFrame / OLD_TEXTURE_SIZE_FIX;
c->y = VertexV + vFrame / OLD_TEXTURE_SIZE_FIX;
}
}
}
else
{
ASSERT_OR_RETURN(false, !(poly->flags & iV_IMD_TEXANIM), "Polygons with texture animation must have textures!");
poly->texCoord = NULL;
}
}
*ppFileData = pFileData;
return true;
}
static bool ReadPoints( const char **ppFileData, iIMDShape *s )
{
const char *pFileData = *ppFileData;
unsigned int i;
int cnt;
for (i = 0; i < s->npoints; i++)
{
if (sscanf(pFileData, "%f %f %f%n", &s->points[i].x, &s->points[i].y, &s->points[i].z, &cnt) != 3)
{
debug(LOG_ERROR, "(_load_points) file corrupt -K");
return false;
}
pFileData += cnt;
}
*ppFileData = pFileData;
return true;
}
static bool _imd_load_points( const char **ppFileData, iIMDShape *s )
{
Vector3f *p = NULL;
int32_t tempXMax, tempXMin, tempZMax, tempZMin;
int32_t xmax, ymax, zmax;
double dx, dy, dz, rad_sq, rad, old_to_p_sq, old_to_p, old_to_new;
double xspan, yspan, zspan, maxspan;
Vector3f dia1, dia2, cen;
Vector3f vxmin(0, 0, 0), vymin(0, 0, 0), vzmin(0, 0, 0),
vxmax(0, 0, 0), vymax(0, 0, 0), vzmax(0, 0, 0);
//load the points then pass through a second time to setup bounding datavalues
s->points = (Vector3f*)malloc(sizeof(Vector3f) * s->npoints);
if (s->points == NULL)
{
return false;
}
// Read in points and remove duplicates (!)
if ( ReadPoints( ppFileData, s ) == false )
{
free(s->points);
s->points = NULL;
return false;
}
s->max.x = s->max.y = s->max.z = tempXMax = tempZMax = -FP12_MULTIPLIER;
s->min.x = s->min.y = s->min.z = tempXMin = tempZMin = FP12_MULTIPLIER;
vxmax.x = vymax.y = vzmax.z = -FP12_MULTIPLIER;
vxmin.x = vymin.y = vzmin.z = FP12_MULTIPLIER;
// set up bounding data for minimum number of vertices
for (p = s->points; p < s->points + s->npoints; p++)
{
if (p->x > s->max.x)
{
s->max.x = p->x;
}
if (p->x < s->min.x)
{
s->min.x = p->x;
}
/* Biggest x coord so far within our height window? */
if( p->x > tempXMax && p->y > DROID_VIS_LOWER && p->y < DROID_VIS_UPPER )
{
tempXMax = p->x;
}
/* Smallest x coord so far within our height window? */
if( p->x < tempXMin && p->y > DROID_VIS_LOWER && p->y < DROID_VIS_UPPER )
{
tempXMin = p->x;
}
if (p->y > s->max.y)
{
s->max.y = p->y;
}
if (p->y < s->min.y)
{
s->min.y = p->y;
}
if (p->z > s->max.z)
{
s->max.z = p->z;
}
if (p->z < s->min.z)
{
s->min.z = p->z;
}
/* Biggest z coord so far within our height window? */
if( p->z > tempZMax && p->y > DROID_VIS_LOWER && p->y < DROID_VIS_UPPER )
{
tempZMax = p->z;
}
/* Smallest z coord so far within our height window? */
if( p->z < tempZMax && p->y > DROID_VIS_LOWER && p->y < DROID_VIS_UPPER )
{
tempZMin = p->z;
}
// for tight sphere calculations
if (p->x < vxmin.x)
{
vxmin.x = p->x;
vxmin.y = p->y;
vxmin.z = p->z;
}
if (p->x > vxmax.x)
{
vxmax.x = p->x;
vxmax.y = p->y;
vxmax.z = p->z;
}
if (p->y < vymin.y)
{
vymin.x = p->x;
vymin.y = p->y;
vymin.z = p->z;
}
if (p->y > vymax.y)
{
vymax.x = p->x;
vymax.y = p->y;
vymax.z = p->z;
}
if (p->z < vzmin.z)
{
vzmin.x = p->x;
vzmin.y = p->y;
vzmin.z = p->z;
}
if (p->z > vzmax.z)
{
vzmax.x = p->x;
vzmax.y = p->y;
vzmax.z = p->z;
}
}
// no need to scale an IMD shape (only FSD)
xmax = MAX(s->max.x, -s->min.x);
ymax = MAX(s->max.y, -s->min.y);
zmax = MAX(s->max.z, -s->min.z);
s->radius = MAX(xmax, MAX(ymax, zmax));
s->sradius = sqrtf(xmax*xmax + ymax*ymax + zmax*zmax);
// START: tight bounding sphere
// set xspan = distance between 2 points xmin & xmax (squared)
dx = vxmax.x - vxmin.x;
dy = vxmax.y - vxmin.y;
dz = vxmax.z - vxmin.z;
xspan = dx*dx + dy*dy + dz*dz;
// same for yspan
dx = vymax.x - vymin.x;
dy = vymax.y - vymin.y;
dz = vymax.z - vymin.z;
yspan = dx*dx + dy*dy + dz*dz;
// and ofcourse zspan
dx = vzmax.x - vzmin.x;
dy = vzmax.y - vzmin.y;
dz = vzmax.z - vzmin.z;
zspan = dx*dx + dy*dy + dz*dz;
// set points dia1 & dia2 to maximally seperated pair
// assume xspan biggest
dia1 = vxmin;
dia2 = vxmax;
maxspan = xspan;
if (yspan > maxspan)
{
maxspan = yspan;
dia1 = vymin;
dia2 = vymax;
}
if (zspan > maxspan)
{
maxspan = zspan;
dia1 = vzmin;
dia2 = vzmax;
}
// dia1, dia2 diameter of initial sphere
cen.x = (dia1.x + dia2.x) / 2.;
cen.y = (dia1.y + dia2.y) / 2.;
cen.z = (dia1.z + dia2.z) / 2.;
// calc initial radius
dx = dia2.x - cen.x;
dy = dia2.y - cen.y;
dz = dia2.z - cen.z;
rad_sq = dx*dx + dy*dy + dz*dz;
rad = sqrt((double)rad_sq);
// second pass (find tight sphere)
for (p = s->points; p < s->points + s->npoints; p++)
{
dx = p->x - cen.x;
dy = p->y - cen.y;
dz = p->z - cen.z;
old_to_p_sq = dx*dx + dy*dy + dz*dz;
// do r**2 first
if (old_to_p_sq>rad_sq)
{
// this point outside current sphere
old_to_p = sqrt((double)old_to_p_sq);
// radius of new sphere
rad = (rad + old_to_p) / 2.;
// rad**2 for next compare
rad_sq = rad*rad;
old_to_new = old_to_p - rad;
// centre of new sphere
cen.x = (rad*cen.x + old_to_new*p->x) / old_to_p;
cen.y = (rad*cen.y + old_to_new*p->y) / old_to_p;
cen.z = (rad*cen.z + old_to_new*p->z) / old_to_p;
}
}
s->ocen = cen;
// END: tight bounding sphere
return true;
}
/*!
* Load shape level connectors
* \param ppFileData Pointer to the data (usualy read from a file)
* \param s Pointer to shape level
* \return false on error (memory allocation failure/bad file format), true otherwise
* \pre ppFileData loaded
* \pre s allocated
* \pre s->nconnectors set
* \post s->connectors allocated
*/
static bool _imd_load_connectors(const char **ppFileData, iIMDShape *s)
{
const char *pFileData = *ppFileData;
int cnt;
Vector3i *p = NULL, newVector(0, 0, 0);
s->connectors = (Vector3i *)malloc(sizeof(Vector3i) * s->nconnectors);
if (s->connectors == NULL)
{
debug(LOG_ERROR, "(_load_connectors) MALLOC fail");
return false;
}
for (p = s->connectors; p < s->connectors + s->nconnectors; p++)
{
if (sscanf(pFileData, "%d %d %d%n", &newVector.x, &newVector.y, &newVector.z, &cnt) != 3 &&
sscanf(pFileData, "%d%*[.0-9] %d%*[.0-9] %d%*[.0-9]%n", &newVector.x, &newVector.y, &newVector.z, &cnt) != 3)
{
debug(LOG_ERROR, "(_load_connectors) file corrupt -M");
return false;
}
pFileData += cnt;
*p = newVector;
}
*ppFileData = pFileData;
return true;
}
/*!
* Load shape levels recursively
* \param ppFileData Pointer to the data (usualy read from a file)
* \param FileDataEnd ???
* \param nlevels Number of levels to load
* \return pointer to iFSDShape structure (or NULL on error)
* \pre ppFileData loaded
* \post s allocated
*/
static iIMDShape *_imd_load_level(const char **ppFileData, const char *FileDataEnd, int nlevels, int pieVersion)
{
const char *pTmp, *pFileData = *ppFileData;
char buffer[PATH_MAX] = {'\0'};
int cnt = 0, n = 0, i;
iIMDShape *s = NULL;
if (nlevels == 0)
{
return NULL;
}
// Load optional MATERIALS directive
pTmp = pFileData; // remember position
i = sscanf(pFileData, "%255s %n", buffer, &cnt);
ASSERT_OR_RETURN(NULL, i == 1, "Bad directive following LEVEL");
s = (iIMDShape*)malloc(sizeof(iIMDShape));
if (s == NULL)
{
/* Failed to allocate memory for s */
debug(LOG_ERROR, "_imd_load_level: Memory allocation error");
return NULL;
}
s->flags = 0;
s->nconnectors = 0; // Default number of connectors must be 0
s->npoints = 0;
s->npolys = 0;
s->points = NULL;
s->polys = NULL;
s->connectors = NULL;
s->next = NULL;
s->shadowEdgeList = NULL;
s->nShadowEdges = 0;
s->texpage = iV_TEX_INVALID;
s->tcmaskpage = iV_TEX_INVALID;
memset(s->material, 0, sizeof(s->material));
s->material[LIGHT_AMBIENT][3] = 1.0f;
s->material[LIGHT_DIFFUSE][3] = 1.0f;
s->material[LIGHT_SPECULAR][3] = 1.0f;
if (strcmp(buffer, "MATERIALS") == 0)
{
i = sscanf(pFileData, "%255s %f %f %f %f %f %f %f %f %f %f%n", buffer,
&s->material[LIGHT_AMBIENT][0], &s->material[LIGHT_AMBIENT][1], &s->material[LIGHT_AMBIENT][2],
&s->material[LIGHT_DIFFUSE][0], &s->material[LIGHT_DIFFUSE][1], &s->material[LIGHT_DIFFUSE][2],
&s->material[LIGHT_SPECULAR][0], &s->material[LIGHT_SPECULAR][1], &s->material[LIGHT_SPECULAR][2],
&s->shininess, &cnt);
ASSERT_OR_RETURN(NULL, i == 11, "Bad MATERIALS directive");
pFileData += cnt;
}
else
{
// Set default values
s->material[LIGHT_AMBIENT][0] = 1.0f;
s->material[LIGHT_AMBIENT][1] = 1.0f;
s->material[LIGHT_AMBIENT][2] = 1.0f;
s->material[LIGHT_DIFFUSE][0] = 1.0f;
s->material[LIGHT_DIFFUSE][1] = 1.0f;
s->material[LIGHT_DIFFUSE][2] = 1.0f;
s->material[LIGHT_SPECULAR][0] = 1.0f;
s->material[LIGHT_SPECULAR][1] = 1.0f;
s->material[LIGHT_SPECULAR][2] = 1.0f;
s->shininess = 10;
pFileData = pTmp;
}
if (sscanf(pFileData, "%255s %d%n", buffer, &s->npoints, &cnt) != 2)
{
debug(LOG_ERROR, "_imd_load_level(2): file corrupt");
return NULL;
}
pFileData += cnt;
// load points
ASSERT_OR_RETURN(NULL, strcmp(buffer, "POINTS") == 0, "Expecting 'POINTS' directive, got: %s", buffer);
_imd_load_points( &pFileData, s );
if (sscanf(pFileData, "%255s %d%n", buffer, &s->npolys, &cnt) != 2)
{
debug(LOG_ERROR, "_imd_load_level(3): file corrupt");
return NULL;
}
pFileData += cnt;
ASSERT_OR_RETURN(NULL, strcmp(buffer, "POLYGONS") == 0, "Expecting 'POLYGONS' directive, got: %s", buffer);
_imd_load_polys( &pFileData, s, pieVersion);
// NOW load optional stuff
while (!AtEndOfFile(pFileData, FileDataEnd)) // check for end of file (give or take white space)
{
// Scans in the line ... if we don't get 2 parameters then quit
if (sscanf(pFileData, "%255s %d%n", buffer, &n, &cnt) != 2)
{
break;
}
pFileData += cnt;
// check for next level ... or might be a BSP - This should handle an imd if it has a BSP tree attached to it
// might be "BSP" or "LEVEL"
if (strcmp(buffer, "LEVEL") == 0)
{
debug(LOG_3D, "imd[_load_level] = npoints %d, npolys %d", s->npoints, s->npolys);
s->next = _imd_load_level(&pFileData, FileDataEnd, nlevels - 1, pieVersion);
}
else if (strcmp(buffer, "CONNECTORS") == 0)
{
//load connector stuff
s->nconnectors = n;
_imd_load_connectors( &pFileData, s );
}
else
{
debug(LOG_ERROR, "(_load_level) unexpected directive %s %d", buffer, n);
break;
}
}
*ppFileData = pFileData;
return s;
}
/*!
* Load ppFileData into a shape
* \param ppFileData Data from the IMD file
* \param FileDataEnd Endpointer
* \return The shape, constructed from the data read
*/
// ppFileData is incremented to the end of the file on exit!
iIMDShape *iV_ProcessIMD( const char **ppFileData, const char *FileDataEnd )
{
const char *pFileName = GetLastResourceFilename(); // Last loaded texture page filename
const char *pFileData = *ppFileData;
char buffer[PATH_MAX], texfile[PATH_MAX];
int cnt, nlevels;
iIMDShape *shape, *psShape;
UDWORD level;
int32_t imd_version;
uint32_t imd_flags;
bool bTextured = false;
if (sscanf(pFileData, "%255s %d%n", buffer, &imd_version, &cnt) != 2)
{
debug(LOG_ERROR, "iV_ProcessIMD %s bad version: (%s)", pFileName, buffer);
assert(false);
return NULL;
}
pFileData += cnt;
if (strcmp(PIE_NAME, buffer) != 0)
{
debug(LOG_ERROR, "iV_ProcessIMD %s not an IMD file (%s %d)", pFileName, buffer, imd_version);
return NULL;
}
//Now supporting version PIE_VER and PIE_FLOAT_VER files
if (imd_version != PIE_VER && imd_version != PIE_FLOAT_VER)
{
debug(LOG_ERROR, "iV_ProcessIMD %s version %d not supported", pFileName, imd_version);
return NULL;
}
// Read flag
if (sscanf(pFileData, "%255s %x%n", buffer, &imd_flags, &cnt) != 2)
{
debug(LOG_ERROR, "iV_ProcessIMD %s bad flags: %s", pFileName, buffer);
return NULL;
}
pFileData += cnt;
/* This can be either texture or levels */
if (sscanf(pFileData, "%255s %d%n", buffer, &nlevels, &cnt) != 2)
{
debug(LOG_ERROR, "iV_ProcessIMD %s expecting TEXTURE or LEVELS: %s", pFileName, buffer);
return NULL;
}
pFileData += cnt;
// get texture page if specified
if (strncmp(buffer, "TEXTURE", 7) == 0)
{
int i, pwidth, pheight;
char ch, texType[PATH_MAX];
/* the first parameter for textures is always ignored; which is why we ignore
* nlevels read in above */
ch = *pFileData++;
// Run up to the dot or till the buffer is filled. Leave room for the extension.
for (i = 0; i < PATH_MAX-5 && (ch = *pFileData++) != '\0' && ch != '.'; ++i)
{
texfile[i] = ch;
}
texfile[i] = '\0';
if (sscanf(pFileData, "%255s%n", texType, &cnt) != 1)
{
debug(LOG_ERROR, "iV_ProcessIMD %s texture info corrupt: %s", pFileName, buffer);
return NULL;
}
pFileData += cnt;
if (strcmp(texType, "png") != 0)
{
debug(LOG_ERROR, "iV_ProcessIMD %s: only png textures supported", pFileName);
return NULL;
}
sstrcat(texfile, ".png");
if (sscanf(pFileData, "%d %d%n", &pwidth, &pheight, &cnt) != 2)
{
debug(LOG_ERROR, "iV_ProcessIMD %s bad texture size: %s", pFileName, buffer);
return NULL;
}
pFileData += cnt;
/* Now read in LEVELS directive */
if (sscanf(pFileData, "%255s %d%n", buffer, &nlevels, &cnt) != 2)
{
debug(LOG_ERROR, "iV_ProcessIMD %s bad levels info: %s", pFileName, buffer);
return NULL;
}
pFileData += cnt;
bTextured = true;
}
if (strncmp(buffer, "LEVELS", 6) != 0)
{
debug(LOG_ERROR, "iV_ProcessIMD: expecting 'LEVELS' directive (%s)", buffer);
return NULL;
}
/* Read first LEVEL directive */
if (sscanf(pFileData, "%255s %d%n", buffer, &level, &cnt) != 2)
{
debug(LOG_ERROR, "(_load_level) file corrupt -J");
return NULL;
}
pFileData += cnt;
if (strncmp(buffer, "LEVEL", 5) != 0)
{
debug(LOG_ERROR, "iV_ProcessIMD(2): expecting 'LEVEL' directive (%s)", buffer);
return NULL;
}
shape = _imd_load_level(&pFileData, FileDataEnd, nlevels, imd_version);
if (shape == NULL)
{
debug(LOG_ERROR, "iV_ProcessIMD %s unsuccessful", pFileName);
return NULL;
}
// load texture page if specified
if (bTextured)
{
int texpage = iV_GetTexture(texfile);
ASSERT_OR_RETURN(NULL, texpage >= 0, "%s could not load tex page %s", pFileName, texfile);
// assign tex page to levels
for (psShape = shape; psShape != NULL; psShape = psShape->next)
{
psShape->texpage = texpage;
}
// check if model should use team colour mask
if (imd_flags & iV_IMD_TCMASK)
{
int texpage_mask;
pie_MakeTexPageTCMaskName(texfile);
sstrcat(texfile, ".png");
texpage_mask = iV_GetTexture(texfile);
ASSERT_OR_RETURN(shape, texpage_mask >= 0, "%s could not load tcmask %s", pFileName, texfile);
// Propagate settings through levels
for (psShape = shape; psShape != NULL; psShape = psShape->next)
{
psShape->flags |= iV_IMD_TCMASK;
psShape->tcmaskpage = texpage_mask;
}
}
}
*ppFileData = pFileData;
return shape;
}
| gpl-2.0 |
DarkShadow07/TechXProject | src/main/java/DarkS/TechXProject/blocks/machine/BlockActivator.java | 6831 | package DarkS.TechXProject.blocks.machine;
import DarkS.TechXProject.blocks.base.BlockRotatingBase;
import DarkS.TechXProject.blocks.tile.highlight.IHighlightProvider;
import DarkS.TechXProject.blocks.tile.highlight.SelectionBox;
import DarkS.TechXProject.machines.activator.TileActivator;
import DarkS.TechXProject.util.ChatUtil;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.*;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Random;
public class BlockActivator extends BlockRotatingBase implements ITileEntityProvider
{
public static PropertyBool active = PropertyBool.create("active");
public BlockActivator()
{
super(Material.IRON, 5.4f, 1, "pickaxe");
setDefaultState(getDefaultState().withProperty(active, false).withProperty(facing, EnumFacing.UP));
}
@Override
public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn)
{
for (SelectionBox box : ((IHighlightProvider) worldIn.getTileEntity(pos)).getBoxes())
if (box != null)
for (AxisAlignedBB aabb : box.getBoxes())
addCollisionBoxToList(pos, entityBox, collidingBoxes, aabb);
}
@Nullable
@Override
public RayTraceResult collisionRayTrace(IBlockState blockState, World worldIn, BlockPos pos, Vec3d start, Vec3d end)
{
return ((IHighlightProvider) worldIn.getTileEntity(pos)).rayTrace(pos, start, end);
}
@SideOnly(Side.CLIENT)
public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand)
{
if (rand.nextBoolean() && worldIn.getTileEntity(pos) != null && ((TileActivator) worldIn.getTileEntity(pos)).timeOn > 0)
{
worldIn.spawnParticle(EnumParticleTypes.REDSTONE, pos.getX() + rand.nextFloat(), pos.getY() + rand.nextFloat(), pos.getZ() + rand.nextFloat(), 0.0D, 0.0D, 0.0D);
}
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
{
switch (getMetaFromState(state))
{
case 0:
return new AxisAlignedBB(0, 0, 0, 1, 0.125, 1);
case 1:
return new AxisAlignedBB(0, 1, 0, 1, 0.875, 1);
case 2:
return new AxisAlignedBB(0, 0, 0, 1, 1, 0.125);
case 3:
return new AxisAlignedBB(0, 0, 0.875, 1, 1, 1);
case 4:
return new AxisAlignedBB(0, 0, 0, 0.125, 1, 1);
case 5:
return new AxisAlignedBB(0.875, 0, 0, 1, 1, 1);
}
return new AxisAlignedBB(0, 0, 0, 1, 1, 1);
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
TileActivator tile = (TileActivator) worldIn.getTileEntity(pos);
return getDefaultState().withProperty(facing, EnumFacing.getFront(getMetaFromState(state))).withProperty(BlockActivator.active, tile != null && tile.timeOn > 0);
}
@Override
public boolean isFullCube(IBlockState state)
{
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ)
{
TileActivator tile = (TileActivator) worldIn.getTileEntity(pos);
if (tile != null)
if (playerIn.isSneaking())
{
tile.defaultOn -= GuiScreen.isCtrlKeyDown() ? 10 : 1;
tile.defaultOn = MathHelper.clamp_int(tile.defaultOn, 5, Integer.MAX_VALUE);
ChatUtil.sendNoSpam(playerIn, "Time On: " + tile.defaultOn, "Time Off: " + tile.defaultOff);
worldIn.playSound(playerIn, pos, SoundEvents.BLOCK_STONE_BUTTON_CLICK_ON, SoundCategory.BLOCKS, 1.0f, 1.1f);
return true;
} else
{
tile.defaultOn += GuiScreen.isCtrlKeyDown() ? 10 : 1;
tile.defaultOn = MathHelper.clamp_int(tile.defaultOn, 5, Integer.MAX_VALUE);
ChatUtil.sendNoSpam(playerIn, "Time On: " + tile.defaultOn, "Time Off: " + tile.defaultOff);
worldIn.playSound(playerIn, pos, SoundEvents.BLOCK_STONE_BUTTON_CLICK_OFF, SoundCategory.BLOCKS, 1.0f, 1.25f);
return true;
}
return false;
}
@Override
public void onBlockClicked(World worldIn, BlockPos pos, EntityPlayer playerIn)
{
TileActivator tile = (TileActivator) worldIn.getTileEntity(pos);
if (tile != null)
if (playerIn.isSneaking())
{
tile.defaultOff -= GuiScreen.isCtrlKeyDown() ? 10 : 1;
tile.defaultOff = MathHelper.clamp_int(tile.defaultOff, 5, Integer.MAX_VALUE);
ChatUtil.sendNoSpam(playerIn, "Time On: " + tile.defaultOn, "Time Off: " + tile.defaultOff);
worldIn.playSound(playerIn, pos, SoundEvents.BLOCK_STONE_BUTTON_CLICK_ON, SoundCategory.BLOCKS, 1.0f, 1.1f);
} else
{
tile.defaultOff += GuiScreen.isCtrlKeyDown() ? 10 : 1;
tile.defaultOff = MathHelper.clamp_int(tile.defaultOff, 5, Integer.MAX_VALUE);
ChatUtil.sendNoSpam(playerIn, "Time On: " + tile.defaultOn, "Time Off: " + tile.defaultOff);
worldIn.playSound(playerIn, pos, SoundEvents.BLOCK_STONE_BUTTON_CLICK_OFF, SoundCategory.BLOCKS, 1.0f, 1.5f);
}
}
@Override
public int getWeakPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
if (blockAccess.getTileEntity(pos) != null)
{
return ((TileActivator) blockAccess.getTileEntity(pos)).getPower();
}
return 0;
}
@Override
public int getStrongPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
if (blockAccess.getTileEntity(pos) != null)
{
return ((TileActivator) blockAccess.getTileEntity(pos)).getPower();
}
return 0;
}
@Override
public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side)
{
return true;
}
@Override
public boolean canProvidePower(IBlockState state)
{
return true;
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer.Builder(this).add(facing, active).build();
}
@Override
public TileEntity createNewTileEntity(World worldIn, int meta)
{
return new TileActivator();
}
}
| gpl-2.0 |
FJuette/PRanger.NET | WpfProxyTool/App.xaml.cs | 328 | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace WpfProxyTool
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| gpl-2.0 |
ascii1011/basecat | apps/mediacenter/migrations/0001_initial.py | 5827 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Publication'
db.create_table(u'mediacenter_publication', (
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_column='DateAdded', blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_column='DateModified', blank=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('desc', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, blank=True)),
('active', self.gf('django.db.models.fields.BooleanField')(default=False)),
('authors', self.gf('django.db.models.fields.CharField')(max_length=512, blank=True)),
('publisher', self.gf('django.db.models.fields.CharField')(max_length=512, blank=True)),
('date_published', self.gf('django.db.models.fields.DateTimeField')(blank=True)),
))
db.send_create_signal(u'mediacenter', ['Publication'])
# Adding model 'Page'
db.create_table(u'mediacenter_page', (
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_column='DateAdded', blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_column='DateModified', blank=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('desc', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, blank=True)),
('active', self.gf('django.db.models.fields.BooleanField')(default=False)),
('tracking', self.gf('django.db.models.fields.CharField')(max_length=255)),
('number', self.gf('django.db.models.fields.IntegerField')(default=0)),
('image', self.gf('django.db.models.fields.CharField')(max_length=255)),
))
db.send_create_signal(u'mediacenter', ['Page'])
# Adding M2M table for field pub on 'Page'
m2m_table_name = db.shorten_name(u'mediacenter_page_pub')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('page', models.ForeignKey(orm[u'mediacenter.page'], null=False)),
('publication', models.ForeignKey(orm[u'mediacenter.publication'], null=False))
))
db.create_unique(m2m_table_name, ['page_id', 'publication_id'])
def backwards(self, orm):
# Deleting model 'Publication'
db.delete_table(u'mediacenter_publication')
# Deleting model 'Page'
db.delete_table(u'mediacenter_page')
# Removing M2M table for field pub on 'Page'
db.delete_table(db.shorten_name(u'mediacenter_page_pub'))
models = {
u'mediacenter.page': {
'Meta': {'object_name': 'Page'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_column': "'DateAdded'", 'blank': 'True'}),
'desc': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_column': "'DateModified'", 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'number': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'pub': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'page_of_publication'", 'blank': 'True', 'to': u"orm['mediacenter.Publication']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'blank': 'True'}),
'tracking': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'mediacenter.publication': {
'Meta': {'object_name': 'Publication'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'authors': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_column': "'DateAdded'", 'blank': 'True'}),
'date_published': ('django.db.models.fields.DateTimeField', [], {'blank': 'True'}),
'desc': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_column': "'DateModified'", 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'publisher': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'blank': 'True'})
}
}
complete_apps = ['mediacenter'] | gpl-2.0 |
lvoinescu/efisSQL | DBMS/DBMS.SQLServer/SQLServerCodeCompletionProvider.cs | 9977 | /*
efisSQL - data base management tool
Copyright (C) 2011 Lucian Voinescu
This file is part of efisSQL
efisSQL is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
efisSQL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with efisSQL. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using DBMS.core;
using System.Windows.Forms;
using ICSharpCode.TextEditor.Gui.CompletionWindow;
using System.Text.RegularExpressions;
namespace DBMS.SQLServer
{
public class SQLServerCodeCompletionProvider : CodeCompletionProvider
{
private string currentDataBase = null;
public string CurrentDataBase
{
get { return currentDataBase; }
set { currentDataBase = value; }
}
public SQLServerCodeCompletionProvider(ImageList iList, List<ICompletionData> data)
: base(iList, data)
{
PreselectionData = this.CompletionData;
}
public override int FindItemWithCurrentWord(string word)
{
if (word.Length < 1)
{
return -1;
}
int selectedIndex = -1;
for (int i = 0; i < this.CompletionData.Count; i++)
{
if (CompletionData[i].Text.ToLower().StartsWith(word.ToLower()))
{
if (selectedIndex == -1)
{
selectedIndex = i;
return selectedIndex;
}
}
}
return selectedIndex;
}
public override bool FindAndPreparePreselection(string lastWord, Keys keyData, char c, char lastChar, int carretPos)
{
string word = lastWord.TrimEnd('.');
if (word!="" && WordIsDatabase(word))
{
PreselectionData = GenerateDataBaseCompletion(currentDataBase);
this.OnKeywordFound(this, new KeywordFoundEventArgs(word, PreselectionData, -1, c, carretPos));
return true;
}
if (c == ' ')
{
if (lastWord.ToLower() == "from" || lastWord.ToLower() == "join" || lastWord.ToLower() == "on")
{
PreselectionData = GenerateDataBaseCompletion(currentDataBase);
if (PreselectionData != null)
{
this.OnKeywordFound(this, new KeywordFoundEventArgs(lastWord, PreselectionData, -1, c, carretPos));
return true;
}
}
return true;
}
if (c == '.')
{
if (WordIsDatabase(lastWord))
{
PreselectionData = GenerateDataBaseCompletion(currentDataBase);
this.OnKeywordFound(this, new KeywordFoundEventArgs(lastWord, PreselectionData, -1, c, carretPos));
return true;
}
if (WordIsTable(lastWord))
{
string table = lastWord.TrimEnd('\'', '"', '`').TrimStart('\'', '"', '`');
PreselectionData = GenerateTableCompletion(currentDataBase, table);
int index = FindItemWithCurrentWord(lastWord);
this.OnKeywordFound(this, new KeywordFoundEventArgs(lastWord, PreselectionData, index, c, carretPos));
return true;
}
return true;
}
if (keyData == (Keys.Control | Keys.Space))
{
bool isKeyWord = false;
if (WordIsDatabase(word))
{
PreselectionData = GenerateDataBaseCompletion(currentDataBase);
isKeyWord = true;
}
string w1 = word.TrimEnd('.');
string table = w1.TrimEnd('\'', '"', '`').TrimStart('\'', '"', '`');
if (WordIsTable(table))
{
PreselectionData = GenerateTableCompletion(currentDataBase,table);
isKeyWord = true;
}
else
{
PreselectionData = new List<ICompletionData>(CompletionData.ToArray());
//if (SpecificCompletionData.ContainsKey("database"))
//{
List<ICompletionData> tables = GenerateDataBaseCompletion(currentDataBase);// (List < ICompletionData >) SpecificCompletionData["database"];
PreselectionData.AddRange(tables.ToArray());
//}
}
if (isKeyWord)
{
this.OnKeywordFound(this, new KeywordFoundEventArgs(lastWord, PreselectionData, -1, c, carretPos));
return true;
}
int index =-1;
if (lastChar == ' ' || lastChar == '.' ||lastChar=='\t')
{
}
else
{
index = FindItemWithCurrentWord(lastWord);
}
if (index == -1)
{
PreselectionData = new List<ICompletionData>(CompletionData.ToArray());
//if (SpecificCompletionData.ContainsKey("database"))
//{
List<ICompletionData> tables = GenerateDataBaseCompletion(currentDataBase);//(List<ICompletionData>)SpecificCompletionData["database"];
PreselectionData.AddRange(tables.ToArray());
//}
return false;
}
this.OnKeywordFound(this, new KeywordFoundEventArgs(lastWord, PreselectionData, index, c, carretPos));
return true;
}
PreselectionData = this.CompletionData;
return false;
}
protected bool WordIsDatabase(string word)
{
if (currentDataBase == null)
return false;
if (word == currentDataBase)
return true;
string pattern = currentDataBase;
if (word.Length > 2)
{
pattern = "[\\\'\\\"\\`]" + pattern + "[\\\'\\\"\\`]";
}
return Regex.Match(word, pattern).Success;
}
protected bool WordIsTable(string word)
{
if (currentDataBase == null)
return false;
string aux = word.TrimEnd('\'', '"', '`');
aux = aux.TrimStart('\'', '"', '`');
if (SpecificCompletionData[currentDataBase].ContainsKey(aux.ToLower()))
return true;
return false;
}
protected List<ICompletionData> GenerateCompletionData(string key)
{
if (SpecificCompletionData.ContainsKey(key))
{
//List<ICompletionData> data = (List<ICompletionData>) SpecificCompletionData[key];
//return data;
}
return null;
}
public void AddDataBase(string database)
{
SpecificCompletionData[database] = new Dictionary<string,string[]>();
}
public void AddTableCompletionToDB(string database, string[] tables)
{
if(!SpecificCompletionData.ContainsKey(database))
SpecificCompletionData[database] = new Dictionary<string,string[]>();
for (int i = 0; i < tables.Length; i++)
if (!SpecificCompletionData[database].ContainsKey(tables[i]))
SpecificCompletionData[database][tables[i]] = new string[] { };
}
public void AddColumnCompletionToTableDB(string database, string table, string[] columns)
{
if (!SpecificCompletionData.ContainsKey(database))
SpecificCompletionData[database] = new Dictionary<string,string[]>();
if (!SpecificCompletionData[database].ContainsKey(table))
SpecificCompletionData[database][table] = new string[] { };
SpecificCompletionData[database][table] = columns;
}
private List<ICompletionData> GenerateDataBaseCompletion(string database)
{
List<ICompletionData> ret = new List<ICompletionData>();
if (database == null)
return ret;
if (!SpecificCompletionData.ContainsKey(database))
return null;
foreach (string table in SpecificCompletionData[database].Keys)
{
ret.Add(new DefaultCompletionData(table,"table",2));
}
return ret;
}
private List<ICompletionData> GenerateTableCompletion(string database, string table)
{
List<ICompletionData> ret = new List<ICompletionData>();
if (!SpecificCompletionData.ContainsKey(database))
return null;
if (!SpecificCompletionData[database].ContainsKey(table))
return null;
foreach (string column in SpecificCompletionData[database][table])
{
ret.Add(new DefaultCompletionData(column, "column", 3));
}
return ret;
}
}
}
| gpl-2.0 |
AlexanderPaniutin/Algorithms | Easy/RemoveDuplicatesFromSortedList/src/RemoveDuplicatesFromSortedList_gtest.cpp | 361 | /*
* GTests for: RemoveDuplicatesFromSortedList.h
* Author: Alex Paniutin
* Created: Feb 21, 2016
*
*/
#include <gtest/gtest.h>
#include "RemoveDuplicatesFromSortedList.h"
TEST(RemoveDuplicatesFromSortedList, Empty)
{
RemoveDuplicatesFromSortedList solution;
ListNode *head = NULL;
EXPECT_EQ(NULL, solution.deleteDuplicates(head));
}
| gpl-2.0 |
yuri12015/leluan | modules/mod_zt_contact_pro/elements/ajax.php | 4071 | <?php
/**
* @package ZT Contact pro module for Joomla!
* @author http://www.zootemplate.com
* @copyright (C) 2010- ZooTemplate.Com
* @license PHP files are GNU/GPL
**/
//Initiate environment
define( 'DS', DIRECTORY_SEPARATOR );
$rootFolder = explode(DS,dirname(__FILE__));
//current level in diretoty structure
$currentfolderlevel = 3;
array_splice($rootFolder,-$currentfolderlevel);
$base_folder = implode(DS,$rootFolder);
if(is_dir($base_folder.DS.'libraries'.DS.'joomla')) {
define( '_JEXEC', 1 );
define('JPATH_BASE',implode(DS,$rootFolder));
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
require_once(JPATH_BASE .DS.'libraries/joomla/factory.php');
$app =& JFactory::getApplication('site');
$app->initialise();
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
class ZTContactXml{
var $moduleId;
var $element;
function __construct($element,$moduleId){
$this->moduleId = $moduleId;
$this->element = $element;
}
function writeXmlData(){
$valid = 1;
if(count($this->element)){
$fileOrder = JRequest::getVar('fieldorder');
$exfield = explode('|', $fileOrder);
$data = "<contact version=\"1\" xmlns=\"http://xspf.org/ns/0/\">
<elementList>\n";
foreach ($exfield as $order){
if($order !=''){
if(@$this->element[$order]['type']!=''){
$data .= "<param>\n
<type>".$this->element[$order]['type']."</type>\n";
if($this->element[$order]['type']!='text'){
$data .= "<fieldtitle><![CDATA[".$this->element[$order]['fieldtitle']."]]></fieldtitle>\n
<fieldname><![CDATA[".$this->element[$order]['fieldname']."]]></fieldname>\n
<valid>".$this->element[$order]['required']."</valid>\n";
}
if($this->element[$order]['type']=='textfield'){
$data .= "<size>".$this->element[$order]['size']."</size>\n
<length>".$this->element[$order]['maxlength']."</length>\n";
}
if($this->element[$order]['type']=='textarea'){
$data .= "<cols>".$this->element[$order]['cols']."</cols>\n
<rows>".$this->element[$order]['rows']."</rows>\n";
}
if($this->element[$order]['type']=='radio'){
foreach ($this->element[$order]['value'] as $value) {
$data .= "<value><![CDATA[".$value."]]></value>\n";
}
}
if($this->element[$order]['type']=='selected'){
$data .= "<size>".$this->element[$order]['size']."</size>\n
<multi>".$this->element[$order]['multi']."</multi>\n";
foreach ($this->element[$order]['value'] as $value) {
$data .= "<value><![CDATA[".$value."]]></value>\n";
}
}
if($this->element[$order]['type']=='checkbox'){
foreach ($this->element[$order]['value'] as $value) {
$data .= "<value><![CDATA[".$value."]]></value>\n";
}
}
if($this->element[$order]['type']=='text'){
$data .= "<intro><![CDATA[".$this->element[$order]['fieldtext']."]]></intro>\n";
}
$data .="</param>\n";
}
}
}
$data.="</elementList>
</contact>";
$this->exeWriteXmlData($data);
} else {
$valid = 0;
}
return $valid;
}
function exeWriteXmlData($data){
$xml = JPATH_BASE.DS.'modules'.DS.'mod_zt_contact_pro'.DS.'assets'.DS.'data'.DS.'contact'.$this->moduleId.'.xml';
if(JFile::write($xml,$data)) return true;
else {
echo 'Write file error';
}
}
}
$element = JRequest::getVar('element');
$moduleId = JRequest::getVar('module_id');
$ztContactXml = new ZTContactXml($element,$moduleId);
$valid = $ztContactXml->writeXmlData();
}
| gpl-2.0 |
USGS-CIDA/SOS | hibernate/common/src/main/java/org/n52/sos/ds/hibernate/entities/interfaces/CategoryObservation.java | 1587 | /**
* Copyright (C) 2012-2014 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.ds.hibernate.entities.interfaces;
import org.n52.sos.ds.hibernate.entities.HibernateRelations.HasValue;
/**
* Interface for Hibernate category observations entities
*
* @since 4.0.0
*
*/
public interface CategoryObservation extends HasValue<String>{
}
| gpl-2.0 |
enbits/mandala_framework | core/controller.php | 657 | <?php
class controller {
/*
* The controller name
*/
protected $name;
/*
* Parameters passed trough url
*/
public $params;
/*
* Parameters passed trough POST
*/
public $post;
/*
* Parameters passed trough GET
*/
public $get;
public function __construct() {
$this->post = $_POST;
$this->get = $_GET;
$this->load = new load();
}
public function set_params(array $params = array()) {
$this->params = $params;
}
public function output($action, $params) {
$this->set_params($params);
echo $this->$action();
}
} | gpl-2.0 |
jackaudio/jack2 | linux/alsarawmidi/JackALSARawMidiInputPort.cpp | 4191 | /*
Copyright (C) 2011 Devin Anderson
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <cassert>
#include <memory>
#include "JackALSARawMidiInputPort.h"
#include "JackMidiUtil.h"
#include "JackError.h"
using Jack::JackALSARawMidiInputPort;
JackALSARawMidiInputPort::JackALSARawMidiInputPort(const char* client_name,
snd_rawmidi_info_t *info,
size_t index,
size_t max_bytes,
size_t max_messages):
JackALSARawMidiPort(client_name, info, index, POLLIN)
{
alsa_event = 0;
jack_event = 0;
receive_queue = new JackALSARawMidiReceiveQueue(rawmidi, max_bytes);
std::unique_ptr<JackALSARawMidiReceiveQueue> receive_ptr(receive_queue);
thread_queue = new JackMidiAsyncQueue(max_bytes, max_messages);
std::unique_ptr<JackMidiAsyncQueue> thread_ptr(thread_queue);
write_queue = new JackMidiBufferWriteQueue();
std::unique_ptr<JackMidiBufferWriteQueue> write_ptr(write_queue);
raw_queue = new JackMidiRawInputWriteQueue(thread_queue, max_bytes,
max_messages);
write_ptr.release();
thread_ptr.release();
receive_ptr.release();
}
JackALSARawMidiInputPort::~JackALSARawMidiInputPort()
{
delete raw_queue;
delete receive_queue;
delete thread_queue;
delete write_queue;
}
bool
JackALSARawMidiInputPort::ProcessJack(JackMidiBuffer *port_buffer,
jack_nframes_t frames)
{
write_queue->ResetMidiBuffer(port_buffer, frames);
bool dequeued = false;
if (! jack_event) {
goto dequeue_event;
}
for (;;) {
switch (write_queue->EnqueueEvent(jack_event, frames)) {
case JackMidiWriteQueue::BUFFER_TOO_SMALL:
jack_error("JackALSARawMidiInputPort::ProcessJack - The write "
"queue couldn't enqueue a %d-byte event. Dropping "
"event.", jack_event->size);
// Fallthrough on purpose.
case JackMidiWriteQueue::OK:
break;
default:
goto trigger_queue_event;
}
dequeue_event:
jack_event = thread_queue->DequeueEvent();
if (! jack_event) {
break;
}
dequeued = true;
}
trigger_queue_event:
return dequeued ? TriggerQueueEvent() : true;
}
bool
JackALSARawMidiInputPort::ProcessPollEvents(jack_nframes_t current_frame)
{
if (GetQueuePollEvent() == -1) {
return false;
}
int io_event = GetIOPollEvent();
switch (io_event) {
case -1:
return false;
case 1:
alsa_event = receive_queue->DequeueEvent();
}
if (alsa_event) {
size_t size = alsa_event->size;
size_t space = raw_queue->GetAvailableSpace();
bool enough_room = space >= size;
if (enough_room) {
assert(raw_queue->EnqueueEvent(current_frame, size,
alsa_event->buffer) ==
JackMidiWriteQueue::OK);
alsa_event = 0;
} else if (space) {
assert(raw_queue->EnqueueEvent(current_frame, space,
alsa_event->buffer) ==
JackMidiWriteQueue::OK);
alsa_event->buffer += space;
alsa_event->size -= space;
}
SetIOEventsEnabled(enough_room);
}
raw_queue->Process();
return true;
}
| gpl-2.0 |
hkaimio/photovault | src/main/java/org/photovault/dcraw/AHDInterpolateDescriptor.java | 3938 | /*
Copyright (c) 2009 Harri Kaimio
This file is part of Photovault.
Photovault 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.
Photovault 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 Photovault; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
package org.photovault.dcraw;
import javax.media.jai.JAI;
import javax.media.jai.OperationDescriptorImpl;
import javax.media.jai.OperationRegistry;
import javax.media.jai.registry.RIFRegistry;
import javax.media.jai.util.Range;
/**
* Operator that interpolates a 3 channel RGB image from raw bayer data produced
* by {@link DCRawReaderOp}.
* @author Harri Kaimio
* @since 0.6.0
*/
public class AHDInterpolateDescriptor extends OperationDescriptorImpl {
// A map-like array of strings with resources information.
private static final String[][] resources =
{
{"GlobalName", "AHDInterpolate"},
{"LocalName", "AHDInterpolate"},
{"Vendor", "org.photovault"},
{"Description", "Do AHD demosaicing for bayer pattern image"},
{"DocURL", "http://www.photovault.org"},
{"Version", "1.0"}
};
// An array of strings with the supported modes for this operator.
private static final String[] supportedModes = {"rendered" };
// An array of strings with the parameter names for this operator.
private static final String[] paramNames = {
"rmult",
"gmult",
"bmult",
"downsample"
};
// An array of Classes with the parameters' classes for this operator.
private static final Class[] paramClasses = {
Double.class,
Double.class,
Double.class,
Integer.class
};
// An array of Objects with the parameters' default values.
private static final Object[] paramDefaults = {
1.0, 1.0, 1.0, 1
};
// An array of Ranges with ranges of valid parameter values.
private static final Range[] validParamValues = {
new Range( Double.class, Double.valueOf( 0.0 ), Double.valueOf( 100.0 ) ),
new Range( Double.class, Double.valueOf( 0.0 ), Double.valueOf( 100.0 ) ),
new Range( Double.class, Double.valueOf( 0.0 ), Double.valueOf( 100.0 ) ),
new Range( Integer.class, 1, Integer.MAX_VALUE )
};
// The number of sources required for this operator.
private static final int numSources = 1;
// A flag that indicates whether the operator is already registered.
private static boolean registered = false;
/**
* The constructor for this descriptor, which just calls the constructor
* for its ancestral class (OperationDescriptorImpl).
*/
public AHDInterpolateDescriptor()
{
super(resources,supportedModes,numSources,paramNames,
paramClasses,paramDefaults,validParamValues);
}
/**
* A method to register this operator with the OperationRegistry and
* RIFRegistry.
*/
public static void register()
{
if (!registered)
{
// Get the OperationRegistry.
OperationRegistry op = JAI.getDefaultInstance().getOperationRegistry();
// Register the operator's descriptor.
AHDInterpolateDescriptor desc =
new AHDInterpolateDescriptor();
op.registerDescriptor(desc);
// Register the operators's RIF.
AHDInterpolateRIF rif = new AHDInterpolateRIF();
RIFRegistry.register(op,"AHDInterpolate","org.photovault",rif);
// CRIFRegistry.register( op, "DCRawReader", rif );
registered = true;
}
}
}
| gpl-2.0 |
BIORIMP/biorimp | BIO-RIMP/HAEAsrc/unalcol/math/algebra/Groupoid.java | 735 | package unalcol.math.algebra;
/**
* <p>Title: grupoid</p>
*
* <p>Description: Abstract definition of a Grupoid</p>
*
* <p>Copyright: Copyright (c) 2009</p>
*
* <p>Company: Kunsamu</p>
*
* @author Jonatan Gomez Perdomo
* @version 1.0
*/
public interface Groupoid<T> {
/**
* Adds the object one and the object two
* @param one The first Object
* @param two The second Object
* @return The first object after being modified by the group operation
*/
public abstract T fastPlus(T one, T two);
/**
* Adds object the one clone and the two clone
* @param one The first Object
* @param two The second Object
* @return The result
*/
public T plus(T one, T two);
}
| gpl-2.0 |
hajuuk/R7000 | ap/gpl/amule/wxWidgets-2.8.12/src/mac/classic/dc.cpp | 75659 | /////////////////////////////////////////////////////////////////////////////
// Name: src/mac/classic/dc.cpp
// Purpose: wxDC class
// Author: Stefan Csomor
// Modified by:
// Created: 01/02/97
// RCS-ID: $Id: dc.cpp 39957 2006-07-03 19:02:54Z ABX $
// Copyright: (c) Stefan Csomor
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h"
#include "wx/dc.h"
#ifndef WX_PRECOMP
#include "wx/log.h"
#include "wx/app.h"
#include "wx/dcmemory.h"
#include "wx/dcprint.h"
#include "wx/region.h"
#include "wx/image.h"
#endif
#include "wx/mac/uma.h"
#if __MSL__ >= 0x6000
namespace std {}
using namespace std ;
#endif
#include "wx/mac/private.h"
#include <ATSUnicode.h>
#include <TextCommon.h>
#include <TextEncodingConverter.h>
#include <FixMath.h>
IMPLEMENT_ABSTRACT_CLASS(wxDC, wxObject)
//-----------------------------------------------------------------------------
// constants
//-----------------------------------------------------------------------------
const double RAD2DEG = 180.0 / M_PI;
const short kEmulatedMode = -1 ;
const short kUnsupportedMode = -2 ;
extern TECObjectRef s_TECNativeCToUnicode ;
// set to 0 if problems arise
#define wxMAC_EXPERIMENTAL_DC 1
wxMacPortSetter::wxMacPortSetter( const wxDC* dc ) :
m_ph( (GrafPtr) dc->m_macPort )
{
wxASSERT( dc->Ok() ) ;
m_dc = dc ;
dc->MacSetupPort(&m_ph) ;
}
wxMacPortSetter::~wxMacPortSetter()
{
m_dc->MacCleanupPort(&m_ph) ;
}
#if wxMAC_EXPERIMENTAL_DC
class wxMacFastPortSetter
{
public :
wxMacFastPortSetter( const wxDC *dc )
{
wxASSERT( dc->Ok() ) ;
GetPort( &m_oldPort ) ;
SetPort( (GrafPtr) dc->m_macPort ) ;
m_clipRgn = NewRgn() ;
GetClip( m_clipRgn ) ;
m_dc = dc ;
dc->MacSetupPort( NULL ) ;
}
~wxMacFastPortSetter()
{
SetPort( (GrafPtr) m_dc->m_macPort ) ;
SetClip( m_clipRgn ) ;
SetPort( m_oldPort ) ;
m_dc->MacCleanupPort( NULL ) ;
DisposeRgn( m_clipRgn ) ;
}
private :
RgnHandle m_clipRgn ;
GrafPtr m_oldPort ;
const wxDC* m_dc ;
} ;
#else
typedef wxMacPortSetter wxMacFastPortSetter ;
#endif
#if 0
// start moving to a dual implementation for QD and CGContextRef
class wxMacGraphicsContext
{
public :
void DrawBitmap( const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask ) = 0 ;
void SetClippingRegion( wxCoord x, wxCoord y, wxCoord width, wxCoord height ) = 0 ;
void SetClippingRegion( const wxRegion ®ion ) = 0 ;
void DestroyClippingRegion() = 0 ;
void SetTextForeground( const wxColour &col ) = 0 ;
void SetTextBackground( const wxColour &col ) = 0 ;
void SetLogicalScale( double x , double y ) = 0 ;
void SetUserScale( double x , double y ) = 0;
} ;
class wxMacQuickDrawContext : public wxMacGraphicsContext
{
public :
} ;
#endif
wxMacWindowClipper::wxMacWindowClipper( const wxWindow* win )
{
m_formerClip = NewRgn() ;
m_newClip = NewRgn() ;
GetClip( m_formerClip ) ;
if ( win )
{
#if 0
// this clipping area was set to the parent window's drawing area, lead to problems
// with MacOSX controls drawing outside their wx' rectangle
RgnHandle insidergn = NewRgn() ;
int x = 0 , y = 0;
wxWindow *parent = win->GetParent() ;
parent->MacWindowToRootWindow( &x,&y ) ;
wxSize size = parent->GetSize() ;
SetRectRgn( insidergn , parent->MacGetLeftBorderSize() , parent->MacGetTopBorderSize() ,
size.x - parent->MacGetRightBorderSize(),
size.y - parent->MacGetBottomBorderSize()) ;
CopyRgn( (RgnHandle) parent->MacGetVisibleRegion(false).GetWXHRGN() , m_newClip ) ;
SectRgn( m_newClip , insidergn , m_newClip ) ;
OffsetRgn( m_newClip , x , y ) ;
SetClip( m_newClip ) ;
DisposeRgn( insidergn ) ;
#else
int x = 0 , y = 0;
win->MacWindowToRootWindow( &x,&y ) ;
CopyRgn( (RgnHandle) ((wxWindow*)win)->MacGetVisibleRegion().GetWXHRGN() , m_newClip ) ;
OffsetRgn( m_newClip , x , y ) ;
SetClip( m_newClip ) ;
#endif
}
}
wxMacWindowClipper::~wxMacWindowClipper()
{
SetClip( m_formerClip ) ;
DisposeRgn( m_newClip ) ;
DisposeRgn( m_formerClip ) ;
}
//-----------------------------------------------------------------------------
// Local functions
//-----------------------------------------------------------------------------
static inline double dmin(double a, double b) { return a < b ? a : b; }
static inline double dmax(double a, double b) { return a > b ? a : b; }
static inline double DegToRad(double deg) { return (deg * M_PI) / 180.0; }
//-----------------------------------------------------------------------------
// wxDC
//-----------------------------------------------------------------------------
// this function emulates all wx colour manipulations, used to verify the implementation
// by setting the mode in the blitting functions to kEmulatedMode
void wxMacCalculateColour( int logical_func , const RGBColor &srcColor , RGBColor &dstColor ) ;
void wxMacCalculateColour( int logical_func , const RGBColor &srcColor , RGBColor &dstColor )
{
switch ( logical_func )
{
case wxAND: // src AND dst
dstColor.red = dstColor.red & srcColor.red ;
dstColor.green = dstColor.green & srcColor.green ;
dstColor.blue = dstColor.blue & srcColor.blue ;
break ;
case wxAND_INVERT: // (NOT src) AND dst
dstColor.red = dstColor.red & ~srcColor.red ;
dstColor.green = dstColor.green & ~srcColor.green ;
dstColor.blue = dstColor.blue & ~srcColor.blue ;
break ;
case wxAND_REVERSE:// src AND (NOT dst)
dstColor.red = ~dstColor.red & srcColor.red ;
dstColor.green = ~dstColor.green & srcColor.green ;
dstColor.blue = ~dstColor.blue & srcColor.blue ;
break ;
case wxCLEAR: // 0
dstColor.red = 0 ;
dstColor.green = 0 ;
dstColor.blue = 0 ;
break ;
case wxCOPY: // src
dstColor.red = srcColor.red ;
dstColor.green = srcColor.green ;
dstColor.blue = srcColor.blue ;
break ;
case wxEQUIV: // (NOT src) XOR dst
dstColor.red = dstColor.red ^ ~srcColor.red ;
dstColor.green = dstColor.green ^ ~srcColor.green ;
dstColor.blue = dstColor.blue ^ ~srcColor.blue ;
break ;
case wxINVERT: // NOT dst
dstColor.red = ~dstColor.red ;
dstColor.green = ~dstColor.green ;
dstColor.blue = ~dstColor.blue ;
break ;
case wxNAND: // (NOT src) OR (NOT dst)
dstColor.red = ~dstColor.red | ~srcColor.red ;
dstColor.green = ~dstColor.green | ~srcColor.green ;
dstColor.blue = ~dstColor.blue | ~srcColor.blue ;
break ;
case wxNOR: // (NOT src) AND (NOT dst)
dstColor.red = ~dstColor.red & ~srcColor.red ;
dstColor.green = ~dstColor.green & ~srcColor.green ;
dstColor.blue = ~dstColor.blue & ~srcColor.blue ;
break ;
case wxNO_OP: // dst
break ;
case wxOR: // src OR dst
dstColor.red = dstColor.red | srcColor.red ;
dstColor.green = dstColor.green | srcColor.green ;
dstColor.blue = dstColor.blue | srcColor.blue ;
break ;
case wxOR_INVERT: // (NOT src) OR dst
dstColor.red = dstColor.red | ~srcColor.red ;
dstColor.green = dstColor.green | ~srcColor.green ;
dstColor.blue = dstColor.blue | ~srcColor.blue ;
break ;
case wxOR_REVERSE: // src OR (NOT dst)
dstColor.red = ~dstColor.red | srcColor.red ;
dstColor.green = ~dstColor.green | srcColor.green ;
dstColor.blue = ~dstColor.blue | srcColor.blue ;
break ;
case wxSET: // 1
dstColor.red = 0xFFFF ;
dstColor.green = 0xFFFF ;
dstColor.blue = 0xFFFF ;
break ;
case wxSRC_INVERT: // (NOT src)
dstColor.red = ~srcColor.red ;
dstColor.green = ~srcColor.green ;
dstColor.blue = ~srcColor.blue ;
break ;
case wxXOR: // src XOR dst
dstColor.red = dstColor.red ^ srcColor.red ;
dstColor.green = dstColor.green ^ srcColor.green ;
dstColor.blue = dstColor.blue ^ srcColor.blue ;
break ;
}
}
wxDC::wxDC()
{
m_ok = false;
m_colour = true;
m_mm_to_pix_x = mm2pt;
m_mm_to_pix_y = mm2pt;
m_internalDeviceOriginX = 0;
m_internalDeviceOriginY = 0;
m_externalDeviceOriginX = 0;
m_externalDeviceOriginY = 0;
m_logicalScaleX = 1.0;
m_logicalScaleY = 1.0;
m_userScaleX = 1.0;
m_userScaleY = 1.0;
m_scaleX = 1.0;
m_scaleY = 1.0;
m_needComputeScaleX = false;
m_needComputeScaleY = false;
m_macPort = NULL ;
m_macMask = NULL ;
m_ok = false ;
m_macFontInstalled = false ;
m_macBrushInstalled = false ;
m_macPenInstalled = false ;
m_macLocalOrigin.x = m_macLocalOrigin.y = 0 ;
m_macBoundaryClipRgn = NewRgn() ;
m_macCurrentClipRgn = NewRgn() ;
SetRectRgn( (RgnHandle) m_macBoundaryClipRgn , -32000 , -32000 , 32000 , 32000 ) ;
SetRectRgn( (RgnHandle) m_macCurrentClipRgn , -32000 , -32000 , 32000 , 32000 ) ;
m_pen = *wxBLACK_PEN;
m_font = *wxNORMAL_FONT;
m_brush = *wxWHITE_BRUSH;
#ifdef __WXDEBUG__
// needed to debug possible errors with two active drawing methods at the same time on
// the same DC
m_macCurrentPortStateHelper = NULL ;
#endif
m_macATSUIStyle = NULL ;
m_macAliasWasEnabled = false;
m_macForegroundPixMap = NULL ;
m_macBackgroundPixMap = NULL ;
}
wxDC::~wxDC(void)
{
DisposeRgn( (RgnHandle) m_macBoundaryClipRgn ) ;
DisposeRgn( (RgnHandle) m_macCurrentClipRgn ) ;
}
void wxDC::MacSetupPort(wxMacPortStateHelper* help) const
{
#ifdef __WXDEBUG__
wxASSERT( m_macCurrentPortStateHelper == NULL ) ;
m_macCurrentPortStateHelper = help ;
#endif
SetClip( (RgnHandle) m_macCurrentClipRgn);
#if ! wxMAC_EXPERIMENTAL_DC
m_macFontInstalled = false ;
m_macBrushInstalled = false ;
m_macPenInstalled = false ;
#endif
}
void wxDC::MacCleanupPort(wxMacPortStateHelper* help) const
{
#ifdef __WXDEBUG__
wxASSERT( m_macCurrentPortStateHelper == help ) ;
m_macCurrentPortStateHelper = NULL ;
#endif
if( m_macATSUIStyle )
{
::ATSUDisposeStyle((ATSUStyle)m_macATSUIStyle);
m_macATSUIStyle = NULL ;
}
if ( m_macAliasWasEnabled )
{
SetAntiAliasedTextEnabled(m_macFormerAliasState, m_macFormerAliasSize);
m_macAliasWasEnabled = false ;
}
if ( m_macForegroundPixMap )
{
Pattern blackColor ;
::PenPat(GetQDGlobalsBlack(&blackColor));
DisposePixPat( (PixPatHandle) m_macForegroundPixMap ) ;
m_macForegroundPixMap = NULL ;
}
if ( m_macBackgroundPixMap )
{
Pattern whiteColor ;
::BackPat(GetQDGlobalsWhite(&whiteColor));
DisposePixPat( (PixPatHandle) m_macBackgroundPixMap ) ;
m_macBackgroundPixMap = NULL ;
}
}
void wxDC::DoDrawBitmap( const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask )
{
wxCHECK_RET( Ok(), wxT("invalid window dc") );
wxCHECK_RET( bmp.Ok(), wxT("invalid bitmap") );
wxMacFastPortSetter helper(this) ;
wxCoord xx = XLOG2DEVMAC(x);
wxCoord yy = YLOG2DEVMAC(y);
wxCoord w = bmp.GetWidth();
wxCoord h = bmp.GetHeight();
wxCoord ww = XLOG2DEVREL(w);
wxCoord hh = YLOG2DEVREL(h);
// Set up drawing mode
short mode = (m_logicalFunction == wxCOPY ? srcCopy :
//m_logicalFunction == wxCLEAR ? WHITENESS :
//m_logicalFunction == wxSET ? BLACKNESS :
m_logicalFunction == wxINVERT ? hilite :
//m_logicalFunction == wxAND ? MERGECOPY :
m_logicalFunction == wxOR ? srcOr :
m_logicalFunction == wxSRC_INVERT ? notSrcCopy :
m_logicalFunction == wxXOR ? srcXor :
m_logicalFunction == wxOR_REVERSE ? notSrcOr :
//m_logicalFunction == wxAND_REVERSE ? SRCERASE :
//m_logicalFunction == wxSRC_OR ? srcOr :
//m_logicalFunction == wxSRC_AND ? SRCAND :
srcCopy );
if ( bmp.GetBitmapType() == kMacBitmapTypePict ) {
Rect bitmaprect = { 0 , 0 , hh, ww };
::OffsetRect( &bitmaprect, xx, yy ) ;
::DrawPicture( (PicHandle) bmp.GetPict(), &bitmaprect ) ;
}
else if ( bmp.GetBitmapType() == kMacBitmapTypeGrafWorld )
{
GWorldPtr bmapworld = MAC_WXHBITMAP( bmp.GetHBITMAP() );
PixMapHandle bmappixels ;
// Set foreground and background colours (for bitmaps depth = 1)
if(bmp.GetDepth() == 1)
{
RGBColor fore = MAC_WXCOLORREF(m_textForegroundColour.GetPixel());
RGBColor back = MAC_WXCOLORREF(m_textBackgroundColour.GetPixel());
RGBForeColor(&fore);
RGBBackColor(&back);
}
else
{
RGBColor white = { 0xFFFF, 0xFFFF,0xFFFF} ;
RGBColor black = { 0,0,0} ;
RGBForeColor( &black ) ;
RGBBackColor( &white ) ;
}
bmappixels = GetGWorldPixMap( bmapworld ) ;
wxCHECK_RET(LockPixels(bmappixels),
wxT("DoDrawBitmap: Unable to lock pixels"));
Rect source = { 0, 0, h, w };
Rect dest = { yy, xx, yy + hh, xx + ww };
if ( useMask && bmp.GetMask() )
{
if( LockPixels(GetGWorldPixMap(MAC_WXHBITMAP(bmp.GetMask()->GetMaskBitmap()))))
{
CopyDeepMask
(
GetPortBitMapForCopyBits(bmapworld),
GetPortBitMapForCopyBits(MAC_WXHBITMAP(bmp.GetMask()->GetMaskBitmap())),
GetPortBitMapForCopyBits( MAC_WXHBITMAP(m_macPort) ),
&source, &source, &dest, mode, NULL
);
UnlockPixels(GetGWorldPixMap(MAC_WXHBITMAP(bmp.GetMask()->GetMaskBitmap())));
}
}
else {
CopyBits( GetPortBitMapForCopyBits( bmapworld ),
GetPortBitMapForCopyBits( MAC_WXHBITMAP(m_macPort) ),
&source, &dest, mode, NULL ) ;
}
UnlockPixels( bmappixels ) ;
}
else if ( bmp.GetBitmapType() == kMacBitmapTypeIcon )
{
Rect bitmaprect = { 0 , 0 , bmp.GetHeight(), bmp.GetWidth() } ;
OffsetRect( &bitmaprect, xx, yy ) ;
PlotCIconHandle( &bitmaprect , atNone , ttNone , MAC_WXHICON(bmp.GetHICON()) ) ;
}
m_macPenInstalled = false ;
m_macBrushInstalled = false ;
m_macFontInstalled = false ;
}
void wxDC::DoDrawIcon( const wxIcon &icon, wxCoord x, wxCoord y )
{
wxCHECK_RET(Ok(), wxT("Invalid dc wxDC::DoDrawIcon"));
wxCHECK_RET(icon.Ok(), wxT("Invalid icon wxDC::DoDrawIcon"));
DoDrawBitmap( icon , x , y , icon.GetMask() != NULL ) ;
}
void wxDC::DoSetClippingRegion( wxCoord x, wxCoord y, wxCoord width, wxCoord height )
{
wxCHECK_RET(Ok(), wxT("wxDC::DoSetClippingRegion Invalid DC"));
wxCoord xx, yy, ww, hh;
xx = XLOG2DEVMAC(x);
yy = YLOG2DEVMAC(y);
ww = XLOG2DEVREL(width);
hh = YLOG2DEVREL(height);
SetRectRgn( (RgnHandle) m_macCurrentClipRgn , xx , yy , xx + ww , yy + hh ) ;
SectRgn( (RgnHandle) m_macCurrentClipRgn , (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ;
if( m_clipping )
{
m_clipX1 = wxMax( m_clipX1 , xx );
m_clipY1 = wxMax( m_clipY1 , yy );
m_clipX2 = wxMin( m_clipX2, (xx + ww));
m_clipY2 = wxMin( m_clipY2, (yy + hh));
}
else
{
m_clipping = true;
m_clipX1 = xx;
m_clipY1 = yy;
m_clipX2 = xx + ww;
m_clipY2 = yy + hh;
}
}
void wxDC::DoSetClippingRegionAsRegion( const wxRegion ®ion )
{
wxCHECK_RET( Ok(), wxT("invalid window dc") ) ;
if (region.Empty())
{
DestroyClippingRegion();
return;
}
wxMacFastPortSetter helper(this) ;
wxCoord x, y, w, h;
region.GetBox( x, y, w, h );
wxCoord xx, yy, ww, hh;
xx = XLOG2DEVMAC(x);
yy = YLOG2DEVMAC(y);
ww = XLOG2DEVREL(w);
hh = YLOG2DEVREL(h);
// if we have a scaling that we cannot map onto native regions
// we must use the box
if ( ww != w || hh != h )
{
wxDC::DoSetClippingRegion( x, y, w, h );
}
else
{
CopyRgn( (RgnHandle) region.GetWXHRGN() , (RgnHandle) m_macCurrentClipRgn ) ;
if ( xx != x || yy != y )
{
OffsetRgn( (RgnHandle) m_macCurrentClipRgn , xx - x , yy - y ) ;
}
SectRgn( (RgnHandle) m_macCurrentClipRgn , (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ;
if( m_clipping )
{
m_clipX1 = wxMax( m_clipX1 , xx );
m_clipY1 = wxMax( m_clipY1 , yy );
m_clipX2 = wxMin( m_clipX2, (xx + ww));
m_clipY2 = wxMin( m_clipY2, (yy + hh));
}
else
{
m_clipping = true;
m_clipX1 = xx;
m_clipY1 = yy;
m_clipX2 = xx + ww;
m_clipY2 = yy + hh;
}
}
}
void wxDC::DestroyClippingRegion()
{
wxMacFastPortSetter helper(this) ;
CopyRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ;
ResetClipping();
}
void wxDC::DoGetSizeMM( int* width, int* height ) const
{
int w = 0;
int h = 0;
GetSize( &w, &h );
*width = long( double(w) / (m_scaleX*m_mm_to_pix_x) );
*height = long( double(h) / (m_scaleY*m_mm_to_pix_y) );
}
void wxDC::SetTextForeground( const wxColour &col )
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
m_textForegroundColour = col;
m_macFontInstalled = false ;
}
void wxDC::SetTextBackground( const wxColour &col )
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
m_textBackgroundColour = col;
m_macFontInstalled = false ;
}
void wxDC::SetMapMode( int mode )
{
switch (mode)
{
case wxMM_TWIPS:
SetLogicalScale( twips2mm*m_mm_to_pix_x, twips2mm*m_mm_to_pix_y );
break;
case wxMM_POINTS:
SetLogicalScale( pt2mm*m_mm_to_pix_x, pt2mm*m_mm_to_pix_y );
break;
case wxMM_METRIC:
SetLogicalScale( m_mm_to_pix_x, m_mm_to_pix_y );
break;
case wxMM_LOMETRIC:
SetLogicalScale( m_mm_to_pix_x/10.0, m_mm_to_pix_y/10.0 );
break;
default:
case wxMM_TEXT:
SetLogicalScale( 1.0, 1.0 );
break;
}
if (mode != wxMM_TEXT)
{
m_needComputeScaleX = true;
m_needComputeScaleY = true;
}
}
void wxDC::SetUserScale( double x, double y )
{
// allow negative ? -> no
m_userScaleX = x;
m_userScaleY = y;
ComputeScaleAndOrigin();
}
void wxDC::SetLogicalScale( double x, double y )
{
// allow negative ?
m_logicalScaleX = x;
m_logicalScaleY = y;
ComputeScaleAndOrigin();
}
void wxDC::SetLogicalOrigin( wxCoord x, wxCoord y )
{
m_logicalOriginX = x * m_signX; // is this still correct ?
m_logicalOriginY = y * m_signY;
ComputeScaleAndOrigin();
}
void wxDC::SetDeviceOrigin( wxCoord x, wxCoord y )
{
m_externalDeviceOriginX = x;
m_externalDeviceOriginY = y;
ComputeScaleAndOrigin();
}
#if 0
void wxDC::SetInternalDeviceOrigin( long x, long y )
{
m_internalDeviceOriginX = x;
m_internalDeviceOriginY = y;
ComputeScaleAndOrigin();
}
void wxDC::GetInternalDeviceOrigin( long *x, long *y )
{
if (x) *x = m_internalDeviceOriginX;
if (y) *y = m_internalDeviceOriginY;
}
#endif
void wxDC::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
{
m_signX = (xLeftRight ? 1 : -1);
m_signY = (yBottomUp ? -1 : 1);
ComputeScaleAndOrigin();
}
wxSize wxDC::GetPPI() const
{
return wxSize(72, 72);
}
int wxDC::GetDepth() const
{
if ( IsPortColor( (CGrafPtr) m_macPort ) )
{
return ( (**GetPortPixMap( (CGrafPtr) m_macPort)).pixelSize ) ;
}
return 1 ;
}
void wxDC::ComputeScaleAndOrigin()
{
// CMB: copy scale to see if it changes
double origScaleX = m_scaleX;
double origScaleY = m_scaleY;
m_scaleX = m_logicalScaleX * m_userScaleX;
m_scaleY = m_logicalScaleY * m_userScaleY;
m_deviceOriginX = m_internalDeviceOriginX + m_externalDeviceOriginX;
m_deviceOriginY = m_internalDeviceOriginY + m_externalDeviceOriginY;
// CMB: if scale has changed call SetPen to recalulate the line width
if (m_scaleX != origScaleX || m_scaleY != origScaleY)
{
// this is a bit artificial, but we need to force wxDC to think
// the pen has changed
wxPen* pen = & GetPen();
wxPen tempPen;
m_pen = tempPen;
SetPen(* pen);
}
}
void wxDC::SetPalette( const wxPalette& palette )
{
}
void wxDC::SetBackgroundMode( int mode )
{
m_backgroundMode = mode ;
}
void wxDC::SetFont( const wxFont &font )
{
m_font = font;
m_macFontInstalled = false ;
}
void wxDC::SetPen( const wxPen &pen )
{
if ( m_pen == pen )
return ;
m_pen = pen;
m_macPenInstalled = false ;
}
void wxDC::SetBrush( const wxBrush &brush )
{
if (m_brush == brush)
return;
m_brush = brush;
m_macBrushInstalled = false ;
}
void wxDC::SetBackground( const wxBrush &brush )
{
if (m_backgroundBrush == brush)
return;
m_backgroundBrush = brush;
if (!m_backgroundBrush.Ok())
return;
m_macBrushInstalled = false ;
}
void wxDC::SetLogicalFunction( int function )
{
if (m_logicalFunction == function)
return;
m_logicalFunction = function ;
m_macFontInstalled = false ;
m_macBrushInstalled = false ;
m_macPenInstalled = false ;
}
extern bool wxDoFloodFill(wxDC *dc, wxCoord x, wxCoord y,
const wxColour & col, int style);
bool wxDC::DoFloodFill(wxCoord x, wxCoord y,
const wxColour& col, int style)
{
return wxDoFloodFill(this, x, y, col, style);
}
bool wxDC::DoGetPixel( wxCoord x, wxCoord y, wxColour *col ) const
{
wxCHECK_MSG( Ok(), false, wxT("wxDC::DoGetPixel Invalid DC") );
wxMacFastPortSetter helper(this) ;
RGBColor colour;
GetCPixel( XLOG2DEVMAC(x), YLOG2DEVMAC(y), &colour );
// Convert from Mac colour to wx
col->Set( colour.red >> 8,
colour.green >> 8,
colour.blue >> 8);
return true ;
}
void wxDC::DoDrawLine( wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2 )
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
if (m_pen.GetStyle() != wxTRANSPARENT)
{
MacInstallPen() ;
wxCoord offset = ( (m_pen.GetWidth() == 0 ? 1 :
m_pen.GetWidth() ) * (wxCoord)m_scaleX - 1) / 2;
wxCoord xx1 = XLOG2DEVMAC(x1) - offset;
wxCoord yy1 = YLOG2DEVMAC(y1) - offset;
wxCoord xx2 = XLOG2DEVMAC(x2) - offset;
wxCoord yy2 = YLOG2DEVMAC(y2) - offset;
if ((m_pen.GetCap() == wxCAP_ROUND) &&
(m_pen.GetWidth() <= 1))
{
// Implement LAST_NOT for MAC at least for
// orthogonal lines. RR.
if (xx1 == xx2)
{
if (yy1 < yy2)
yy2--;
if (yy1 > yy2)
yy2++;
}
if (yy1 == yy2)
{
if (xx1 < xx2)
xx2--;
if (xx1 > xx2)
xx2++;
}
}
::MoveTo(xx1, yy1);
::LineTo(xx2, yy2);
}
}
void wxDC::DoCrossHair( wxCoord x, wxCoord y )
{
wxCHECK_RET( Ok(), wxT("wxDC::DoCrossHair Invalid window dc") );
wxMacFastPortSetter helper(this) ;
if (m_pen.GetStyle() != wxTRANSPARENT)
{
int w = 0;
int h = 0;
GetSize( &w, &h );
wxCoord xx = XLOG2DEVMAC(x);
wxCoord yy = YLOG2DEVMAC(y);
MacInstallPen();
::MoveTo( XLOG2DEVMAC(0), yy );
::LineTo( XLOG2DEVMAC(w), yy );
::MoveTo( xx, YLOG2DEVMAC(0) );
::LineTo( xx, YLOG2DEVMAC(h) );
CalcBoundingBox(x, y);
CalcBoundingBox(x+w, y+h);
}
}
/*
* To draw arcs properly the angles need to be converted from the WX style:
* Angles start on the +ve X axis and go anti-clockwise (As you would draw on
* a normal axis on paper).
* TO
* the Mac style:
* Angles start on the +ve y axis and go clockwise.
*/
static double wxConvertWXangleToMACangle(double angle)
{
double newAngle = 90 - angle ;
if ( newAngle < 0 )
newAngle += 360 ;
return newAngle ;
}
void wxDC::DoDrawArc( wxCoord x1, wxCoord y1,
wxCoord x2, wxCoord y2,
wxCoord xc, wxCoord yc )
{
wxCHECK_RET(Ok(), wxT("wxDC::DoDrawArc Invalid DC"));
wxMacFastPortSetter helper(this) ;
wxCoord xx1 = XLOG2DEVMAC(x1);
wxCoord yy1 = YLOG2DEVMAC(y1);
wxCoord xx2 = XLOG2DEVMAC(x2);
wxCoord yy2 = YLOG2DEVMAC(y2);
wxCoord xxc = XLOG2DEVMAC(xc);
wxCoord yyc = YLOG2DEVMAC(yc);
double dx = xx1 - xxc;
double dy = yy1 - yyc;
double radius = sqrt((double)(dx*dx+dy*dy));
wxCoord rad = (wxCoord)radius;
double radius1, radius2;
if (xx1 == xx2 && yy1 == yy2)
{
radius1 = 0.0;
radius2 = 360.0;
}
else if (radius == 0.0)
{
radius1 = radius2 = 0.0;
}
else
{
radius1 = (xx1 - xxc == 0) ?
(yy1 - yyc < 0) ? 90.0 : -90.0 :
-atan2(double(yy1-yyc), double(xx1-xxc)) * RAD2DEG;
radius2 = (xx2 - xxc == 0) ?
(yy2 - yyc < 0) ? 90.0 : -90.0 :
-atan2(double(yy2-yyc), double(xx2-xxc)) * RAD2DEG;
}
wxCoord alpha2 = wxCoord(radius2 - radius1);
wxCoord alpha1 = wxCoord(wxConvertWXangleToMACangle(radius1));
if( (xx1 > xx2) || (yy1 > yy2) ) {
alpha2 *= -1;
}
Rect r = { yyc - rad, xxc - rad, yyc + rad, xxc + rad };
if(m_brush.GetStyle() != wxTRANSPARENT) {
MacInstallBrush();
PaintArc(&r, alpha1, alpha2);
}
if(m_pen.GetStyle() != wxTRANSPARENT) {
MacInstallPen();
FrameArc(&r, alpha1, alpha2);
}
}
void wxDC::DoDrawEllipticArc( wxCoord x, wxCoord y, wxCoord w, wxCoord h,
double sa, double ea )
{
wxCHECK_RET(Ok(), wxT("wxDC::DoDrawEllepticArc Invalid DC"));
wxMacFastPortSetter helper(this) ;
Rect r;
double angle = sa - ea; // Order important Mac in opposite direction to wx
// we have to make sure that the filling is always counter-clockwise
if ( angle > 0 )
angle -= 360 ;
wxCoord xx = XLOG2DEVMAC(x);
wxCoord yy = YLOG2DEVMAC(y);
wxCoord ww = m_signX * XLOG2DEVREL(w);
wxCoord hh = m_signY * YLOG2DEVREL(h);
// handle -ve width and/or height
if (ww < 0) { ww = -ww; xx = xx - ww; }
if (hh < 0) { hh = -hh; yy = yy - hh; }
sa = wxConvertWXangleToMACangle(sa);
r.top = yy;
r.left = xx;
r.bottom = yy + hh;
r.right = xx + ww;
if(m_brush.GetStyle() != wxTRANSPARENT) {
MacInstallBrush();
PaintArc(&r, (short)sa, (short)angle);
}
if(m_pen.GetStyle() != wxTRANSPARENT) {
MacInstallPen();
FrameArc(&r, (short)sa, (short)angle);
}
}
void wxDC::DoDrawPoint( wxCoord x, wxCoord y )
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
if (m_pen.GetStyle() != wxTRANSPARENT)
{
wxCoord xx1 = XLOG2DEVMAC(x);
wxCoord yy1 = YLOG2DEVMAC(y);
RGBColor pencolor = MAC_WXCOLORREF( m_pen.GetColour().GetPixel());
::SetCPixel( xx1,yy1,&pencolor) ;
CalcBoundingBox(x, y);
}
}
void wxDC::DoDrawLines(int n, wxPoint points[],
wxCoord xoffset, wxCoord yoffset)
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
if (m_pen.GetStyle() == wxTRANSPARENT)
return;
MacInstallPen() ;
wxCoord offset = ( (m_pen.GetWidth() == 0 ? 1 :
m_pen.GetWidth() ) * (wxCoord)m_scaleX - 1) / 2 ;
wxCoord x1, x2 , y1 , y2 ;
x1 = XLOG2DEVMAC(points[0].x + xoffset);
y1 = YLOG2DEVMAC(points[0].y + yoffset);
::MoveTo(x1 - offset, y1 - offset );
for (int i = 0; i < n-1; i++)
{
x2 = XLOG2DEVMAC(points[i+1].x + xoffset);
y2 = YLOG2DEVMAC(points[i+1].y + yoffset);
::LineTo( x2 - offset, y2 - offset );
}
}
void wxDC::DoDrawPolygon(int n, wxPoint points[],
wxCoord xoffset, wxCoord yoffset,
int fillStyle )
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
wxCoord x1, x2 , y1 , y2 ;
if ( m_brush.GetStyle() == wxTRANSPARENT && m_pen.GetStyle() == wxTRANSPARENT )
return ;
PolyHandle polygon = OpenPoly();
x2 = x1 = XLOG2DEVMAC(points[0].x + xoffset);
y2 = y1 = YLOG2DEVMAC(points[0].y + yoffset);
::MoveTo(x1,y1);
for (int i = 1; i < n; i++)
{
x2 = XLOG2DEVMAC(points[i].x + xoffset);
y2 = YLOG2DEVMAC(points[i].y + yoffset);
::LineTo(x2, y2);
}
// close the polyline if necessary
if ( x1 != x2 || y1 != y2 )
{
::LineTo(x1,y1 ) ;
}
ClosePoly();
if (m_brush.GetStyle() != wxTRANSPARENT)
{
MacInstallBrush();
::PaintPoly( polygon );
}
if (m_pen.GetStyle() != wxTRANSPARENT)
{
MacInstallPen() ;
::FramePoly( polygon ) ;
}
KillPoly( polygon );
}
void wxDC::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
wxCoord xx = XLOG2DEVMAC(x);
wxCoord yy = YLOG2DEVMAC(y);
wxCoord ww = m_signX * XLOG2DEVREL(width);
wxCoord hh = m_signY * YLOG2DEVREL(height);
// CMB: draw nothing if transformed w or h is 0
if (ww == 0 || hh == 0)
return;
// CMB: handle -ve width and/or height
if (ww < 0)
{
ww = -ww;
xx = xx - ww;
}
if (hh < 0)
{
hh = -hh;
yy = yy - hh;
}
Rect rect = { yy , xx , yy + hh , xx + ww } ;
if (m_brush.GetStyle() != wxTRANSPARENT)
{
MacInstallBrush() ;
::PaintRect( &rect ) ;
}
if (m_pen.GetStyle() != wxTRANSPARENT)
{
MacInstallPen() ;
::FrameRect( &rect ) ;
}
}
void wxDC::DoDrawRoundedRectangle(wxCoord x, wxCoord y,
wxCoord width, wxCoord height,
double radius)
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
if (radius < 0.0)
radius = - radius * ((width < height) ? width : height);
wxCoord xx = XLOG2DEVMAC(x);
wxCoord yy = YLOG2DEVMAC(y);
wxCoord ww = m_signX * XLOG2DEVREL(width);
wxCoord hh = m_signY * YLOG2DEVREL(height);
// CMB: draw nothing if transformed w or h is 0
if (ww == 0 || hh == 0)
return;
// CMB: handle -ve width and/or height
if (ww < 0)
{
ww = -ww;
xx = xx - ww;
}
if (hh < 0)
{
hh = -hh;
yy = yy - hh;
}
Rect rect = { yy , xx , yy + hh , xx + ww } ;
if (m_brush.GetStyle() != wxTRANSPARENT)
{
MacInstallBrush() ;
::PaintRoundRect( &rect , int(radius * 2) , int(radius * 2) ) ;
}
if (m_pen.GetStyle() != wxTRANSPARENT)
{
MacInstallPen() ;
::FrameRoundRect( &rect , int(radius * 2) , int(radius * 2) ) ;
}
}
void wxDC::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
wxCoord xx = XLOG2DEVMAC(x);
wxCoord yy = YLOG2DEVMAC(y);
wxCoord ww = m_signX * XLOG2DEVREL(width);
wxCoord hh = m_signY * YLOG2DEVREL(height);
// CMB: draw nothing if transformed w or h is 0
if (ww == 0 || hh == 0)
return;
// CMB: handle -ve width and/or height
if (ww < 0)
{
ww = -ww;
xx = xx - ww;
}
if (hh < 0)
{
hh = -hh;
yy = yy - hh;
}
Rect rect = { yy , xx , yy + hh , xx + ww } ;
if (m_brush.GetStyle() != wxTRANSPARENT)
{
MacInstallBrush() ;
::PaintOval( &rect ) ;
}
if (m_pen.GetStyle() != wxTRANSPARENT)
{
MacInstallPen() ;
::FrameOval( &rect ) ;
}
}
bool wxDC::CanDrawBitmap(void) const
{
return true ;
}
bool wxDC::DoBlit(wxCoord xdest, wxCoord ydest, wxCoord width, wxCoord height,
wxDC *source, wxCoord xsrc, wxCoord ysrc, int logical_func , bool useMask,
wxCoord xsrcMask, wxCoord ysrcMask )
{
wxCHECK_MSG(Ok(), false, wxT("wxDC::DoBlit Illegal dc"));
wxCHECK_MSG(source->Ok(), false, wxT("wxDC::DoBlit Illegal source DC"));
if ( logical_func == wxNO_OP )
return true ;
if (xsrcMask == -1 && ysrcMask == -1)
{
xsrcMask = xsrc; ysrcMask = ysrc;
}
// correct the parameter in case this dc does not have a mask at all
if ( useMask && !source->m_macMask )
useMask = false ;
Rect srcrect , dstrect ;
srcrect.top = source->YLOG2DEVMAC(ysrc) ;
srcrect.left = source->XLOG2DEVMAC(xsrc) ;
srcrect.right = source->XLOG2DEVMAC(xsrc + width ) ;
srcrect.bottom = source->YLOG2DEVMAC(ysrc + height) ;
dstrect.top = YLOG2DEVMAC(ydest) ;
dstrect.left = XLOG2DEVMAC(xdest) ;
dstrect.bottom = YLOG2DEVMAC(ydest + height ) ;
dstrect.right = XLOG2DEVMAC(xdest + width ) ;
short mode = kUnsupportedMode ;
bool invertDestinationFirst = false ;
switch ( logical_func )
{
case wxAND: // src AND dst
mode = adMin ; // ok
break ;
case wxAND_INVERT: // (NOT src) AND dst
mode = notSrcOr ; // ok
break ;
case wxAND_REVERSE:// src AND (NOT dst)
invertDestinationFirst = true ;
mode = srcOr ;
break ;
case wxCLEAR: // 0
mode = kEmulatedMode ;
break ;
case wxCOPY: // src
mode = srcCopy ; // ok
break ;
case wxEQUIV: // (NOT src) XOR dst
mode = srcXor ; // ok
break ;
case wxINVERT: // NOT dst
mode = kEmulatedMode ; //or hilite ;
break ;
case wxNAND: // (NOT src) OR (NOT dst)
invertDestinationFirst = true ;
mode = srcBic ;
break ;
case wxNOR: // (NOT src) AND (NOT dst)
invertDestinationFirst = true ;
mode = notSrcOr ;
break ;
case wxNO_OP: // dst
mode = kEmulatedMode ; // this has already been handled upon entry
break ;
case wxOR: // src OR dst
mode = notSrcBic ;
break ;
case wxOR_INVERT: // (NOT src) OR dst
mode = srcBic ;
break ;
case wxOR_REVERSE: // src OR (NOT dst)
invertDestinationFirst = true ;
mode = notSrcBic ;
break ;
case wxSET: // 1
mode = kEmulatedMode ;
break ;
case wxSRC_INVERT: // (NOT src)
mode = notSrcCopy ; // ok
break ;
case wxXOR: // src XOR dst
mode = notSrcXor ; // ok
break ;
default :
break ;
}
if ( mode == kUnsupportedMode )
{
wxFAIL_MSG(wxT("unsupported blitting mode" ));
return false ;
}
CGrafPtr sourcePort = (CGrafPtr) source->m_macPort ;
PixMapHandle bmappixels = GetGWorldPixMap( sourcePort ) ;
if ( LockPixels(bmappixels) )
{
wxMacFastPortSetter helper(this) ;
if ( source->GetDepth() == 1 )
{
RGBForeColor( &MAC_WXCOLORREF(m_textForegroundColour.GetPixel()) ) ;
RGBBackColor( &MAC_WXCOLORREF(m_textBackgroundColour.GetPixel()) ) ;
}
else
{
// the modes need this, otherwise we'll end up having really nice colors...
RGBColor white = { 0xFFFF, 0xFFFF,0xFFFF} ;
RGBColor black = { 0,0,0} ;
RGBForeColor( &black ) ;
RGBBackColor( &white ) ;
}
if ( useMask && source->m_macMask )
{
if ( mode == srcCopy )
{
if ( LockPixels( GetGWorldPixMap( MAC_WXHBITMAP(source->m_macMask) ) ) )
{
CopyMask( GetPortBitMapForCopyBits( sourcePort ) ,
GetPortBitMapForCopyBits( MAC_WXHBITMAP(source->m_macMask) ) ,
GetPortBitMapForCopyBits( MAC_WXHBITMAP(m_macPort) ) ,
&srcrect, &srcrect , &dstrect ) ;
UnlockPixels( GetGWorldPixMap( MAC_WXHBITMAP(source->m_macMask) ) ) ;
}
}
else
{
RgnHandle clipRgn = NewRgn() ;
LockPixels( GetGWorldPixMap( MAC_WXHBITMAP(source->m_macMask) ) ) ;
BitMapToRegion( clipRgn , (BitMap*) *GetGWorldPixMap( MAC_WXHBITMAP(source->m_macMask) ) ) ;
UnlockPixels( GetGWorldPixMap( MAC_WXHBITMAP(source->m_macMask) ) ) ;
OffsetRgn( clipRgn , -srcrect.left + dstrect.left, -srcrect.top + dstrect.top ) ;
if ( mode == kEmulatedMode )
{
Pattern pat ;
::PenPat(GetQDGlobalsBlack(&pat));
if ( logical_func == wxSET )
{
RGBColor col= { 0xFFFF, 0xFFFF, 0xFFFF } ;
::RGBForeColor( &col ) ;
::PaintRgn( clipRgn ) ;
}
else if ( logical_func == wxCLEAR )
{
RGBColor col= { 0x0000, 0x0000, 0x0000 } ;
::RGBForeColor( &col ) ;
::PaintRgn( clipRgn ) ;
}
else if ( logical_func == wxINVERT )
{
MacInvertRgn( clipRgn ) ;
}
else
{
for ( int y = 0 ; y < srcrect.right - srcrect.left ; ++y )
{
for ( int x = 0 ; x < srcrect.bottom - srcrect.top ; ++x )
{
Point dstPoint = { dstrect.top + y , dstrect.left + x } ;
Point srcPoint = { srcrect.top + y , srcrect.left + x } ;
if ( PtInRgn( dstPoint , clipRgn ) )
{
RGBColor srcColor ;
RGBColor dstColor ;
SetPort( (GrafPtr) sourcePort ) ;
GetCPixel( srcPoint.h , srcPoint.v , &srcColor) ;
SetPort( (GrafPtr) m_macPort ) ;
GetCPixel( dstPoint.h , dstPoint.v , &dstColor ) ;
wxMacCalculateColour( logical_func , srcColor , dstColor ) ;
SetCPixel( dstPoint.h , dstPoint.v , &dstColor ) ;
}
}
}
}
}
else
{
if ( invertDestinationFirst )
{
MacInvertRgn( clipRgn ) ;
}
CopyBits( GetPortBitMapForCopyBits( sourcePort ) ,
GetPortBitMapForCopyBits( MAC_WXHBITMAP(m_macPort) ) ,
&srcrect, &dstrect, mode, clipRgn ) ;
}
DisposeRgn( clipRgn ) ;
}
}
else
{
RgnHandle clipRgn = NewRgn() ;
SetRectRgn( clipRgn , dstrect.left , dstrect.top , dstrect.right , dstrect.bottom ) ;
if ( mode == kEmulatedMode )
{
Pattern pat ;
::PenPat(GetQDGlobalsBlack(&pat));
if ( logical_func == wxSET )
{
RGBColor col= { 0xFFFF, 0xFFFF, 0xFFFF } ;
::RGBForeColor( &col ) ;
::PaintRgn( clipRgn ) ;
}
else if ( logical_func == wxCLEAR )
{
RGBColor col= { 0x0000, 0x0000, 0x0000 } ;
::RGBForeColor( &col ) ;
::PaintRgn( clipRgn ) ;
}
else if ( logical_func == wxINVERT )
{
MacInvertRgn( clipRgn ) ;
}
else
{
for ( int y = 0 ; y < srcrect.right - srcrect.left ; ++y )
{
for ( int x = 0 ; x < srcrect.bottom - srcrect.top ; ++x )
{
Point dstPoint = { dstrect.top + y , dstrect.left + x } ;
Point srcPoint = { srcrect.top + y , srcrect.left + x } ;
{
RGBColor srcColor ;
RGBColor dstColor ;
SetPort( (GrafPtr) sourcePort ) ;
GetCPixel( srcPoint.h , srcPoint.v , &srcColor) ;
SetPort( (GrafPtr) m_macPort ) ;
GetCPixel( dstPoint.h , dstPoint.v , &dstColor ) ;
wxMacCalculateColour( logical_func , srcColor , dstColor ) ;
SetCPixel( dstPoint.h , dstPoint.v , &dstColor ) ;
}
}
}
}
}
else
{
if ( invertDestinationFirst )
{
MacInvertRgn( clipRgn ) ;
}
CopyBits( GetPortBitMapForCopyBits( sourcePort ) ,
GetPortBitMapForCopyBits( MAC_WXHBITMAP(m_macPort) ) ,
&srcrect, &dstrect, mode, NULL ) ;
}
DisposeRgn( clipRgn ) ;
}
UnlockPixels( bmappixels ) ;
}
m_macPenInstalled = false ;
m_macBrushInstalled = false ;
m_macFontInstalled = false ;
return true;
}
#ifndef FixedToInt
// as macro in FixMath.h for 10.3
inline Fixed IntToFixed( int inInt )
{
return (((SInt32) inInt) << 16);
}
inline int FixedToInt( Fixed inFixed )
{
return (((SInt32) inFixed) >> 16);
}
#endif
void wxDC::DoDrawRotatedText(const wxString& str, wxCoord x, wxCoord y,
double angle)
{
wxCHECK_RET( Ok(), wxT("wxDC::DoDrawRotatedText Invalid window dc") );
if (angle == 0.0 )
{
DrawText(str, x, y);
return;
}
if ( str.length() == 0 )
return ;
wxMacFastPortSetter helper(this) ;
MacInstallFont() ;
if ( 0 )
{
m_macFormerAliasState = IsAntiAliasedTextEnabled(&m_macFormerAliasSize);
SetAntiAliasedTextEnabled(true, SInt16(m_scaleY * m_font.GetMacFontSize()));
m_macAliasWasEnabled = true ;
}
OSStatus status = noErr ;
ATSUTextLayout atsuLayout ;
UniCharCount chars = str.length() ;
#if wxUSE_UNICODE
status = ::ATSUCreateTextLayoutWithTextPtr( (UniCharArrayPtr) (const wxChar*) str , 0 , str.length() , str.length() , 1 ,
&chars , (ATSUStyle*) &m_macATSUIStyle , &atsuLayout ) ;
#else
wxWCharBuffer wchar = str.wc_str( wxConvLocal ) ;
int wlen = wxWcslen( wchar.data() ) ;
status = ::ATSUCreateTextLayoutWithTextPtr( (UniCharArrayPtr) wchar.data() , 0 , wlen , wlen , 1 ,
&chars , (ATSUStyle*) &m_macATSUIStyle , &atsuLayout ) ;
#endif
wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the rotated text") );
int iAngle = int( angle );
int drawX = XLOG2DEVMAC(x) ;
int drawY = YLOG2DEVMAC(y) ;
ATSUTextMeasurement textBefore ;
ATSUTextMeasurement textAfter ;
ATSUTextMeasurement ascent ;
ATSUTextMeasurement descent ;
if ( abs(iAngle) > 0 )
{
Fixed atsuAngle = IntToFixed( iAngle ) ;
ATSUAttributeTag atsuTags[] =
{
kATSULineRotationTag ,
} ;
ByteCount atsuSizes[sizeof(atsuTags)/sizeof(ATSUAttributeTag)] =
{
sizeof( Fixed ) ,
} ;
ATSUAttributeValuePtr atsuValues[sizeof(atsuTags)/sizeof(ATSUAttributeTag)] =
{
&atsuAngle ,
} ;
status = ::ATSUSetLayoutControls(atsuLayout , sizeof(atsuTags)/sizeof(ATSUAttributeTag),
atsuTags, atsuSizes, atsuValues ) ;
}
status = ::ATSUMeasureText( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
&textBefore , &textAfter, &ascent , &descent );
drawX += (int)(sin(angle/RAD2DEG) * FixedToInt(ascent));
drawY += (int)(cos(angle/RAD2DEG) * FixedToInt(ascent));
status = ::ATSUDrawText( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
IntToFixed(drawX) , IntToFixed(drawY) );
wxASSERT_MSG( status == noErr , wxT("couldn't draw the rotated text") );
Rect rect ;
status = ::ATSUMeasureTextImage( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
IntToFixed(drawX) , IntToFixed(drawY) , &rect );
wxASSERT_MSG( status == noErr , wxT("couldn't measure the rotated text") );
OffsetRect( &rect , -m_macLocalOrigin.x , -m_macLocalOrigin.y ) ;
CalcBoundingBox(XDEV2LOG(rect.left), YDEV2LOG(rect.top) );
CalcBoundingBox(XDEV2LOG(rect.right), YDEV2LOG(rect.bottom) );
::ATSUDisposeTextLayout(atsuLayout);
}
void wxDC::DoDrawText(const wxString& strtext, wxCoord x, wxCoord y)
{
wxCHECK_RET(Ok(), wxT("wxDC::DoDrawText Invalid DC"));
wxMacFastPortSetter helper(this) ;
long xx = XLOG2DEVMAC(x);
long yy = YLOG2DEVMAC(y);
#if TARGET_CARBON
bool useDrawThemeText = ( DrawThemeTextBox != (void*) kUnresolvedCFragSymbolAddress ) ;
if ( UMAGetSystemVersion() < 0x1000 || IsKindOf(CLASSINFO( wxPrinterDC ) ) || m_font.GetNoAntiAliasing() )
useDrawThemeText = false ;
#endif
MacInstallFont() ;
if ( 0 )
{
m_macFormerAliasState = IsAntiAliasedTextEnabled(&m_macFormerAliasSize);
SetAntiAliasedTextEnabled(true, 8);
m_macAliasWasEnabled = true ;
}
FontInfo fi ;
::GetFontInfo( &fi ) ;
#if TARGET_CARBON
if ( !useDrawThemeText )
#endif
yy += fi.ascent ;
::MoveTo( xx , yy );
if ( m_backgroundMode == wxTRANSPARENT )
{
::TextMode( srcOr) ;
}
else
{
::TextMode( srcCopy ) ;
}
int length = strtext.length() ;
int laststop = 0 ;
int i = 0 ;
int line = 0 ;
{
#if 0 // we don't have to do all that here
while( i < length )
{
if( strtext[i] == 13 || strtext[i] == 10)
{
wxString linetext = strtext.Mid( laststop , i - laststop ) ;
#if TARGET_CARBON
if ( useDrawThemeText )
{
Rect frame = { yy + line*(fi.descent + fi.ascent + fi.leading) ,xx , yy + (line+1)*(fi.descent + fi.ascent + fi.leading) , xx + 10000 } ;
wxMacCFStringHolder mString( linetext , m_font.GetEncoding() ) ;
if ( m_backgroundMode != wxTRANSPARENT )
{
Point bounds={0,0} ;
Rect background = frame ;
SInt16 baseline ;
::GetThemeTextDimensions( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&bounds,
&baseline );
background.right = background.left + bounds.h ;
background.bottom = background.top + bounds.v ;
::EraseRect( &background ) ;
}
::DrawThemeTextBox( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&frame,
teJustLeft,
nil );
line++ ;
}
else
#endif
{
wxCharBuffer text = linetext.mb_str(wxConvLocal) ;
::DrawText( text , 0 , strlen(text) ) ;
if ( m_backgroundMode != wxTRANSPARENT )
{
Point bounds={0,0} ;
Rect background = frame ;
SInt16 baseline ;
::GetThemeTextDimensions( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&bounds,
&baseline );
background.right = background.left + bounds.h ;
background.bottom = background.top + bounds.v ;
::EraseRect( &background ) ;
}
line++ ;
::MoveTo( xx , yy + line*(fi.descent + fi.ascent + fi.leading) );
}
laststop = i+1 ;
}
i++ ;
}
wxString linetext = strtext.Mid( laststop , i - laststop ) ;
#endif // 0
wxString linetext = strtext ;
#if TARGET_CARBON
if ( useDrawThemeText )
{
Rect frame = { yy + line*(fi.descent + fi.ascent + fi.leading) ,xx , yy + (line+1)*(fi.descent + fi.ascent + fi.leading) , xx + 10000 } ;
wxMacCFStringHolder mString( linetext , m_font.GetEncoding()) ;
if ( m_backgroundMode != wxTRANSPARENT )
{
Point bounds={0,0} ;
Rect background = frame ;
SInt16 baseline ;
::GetThemeTextDimensions( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&bounds,
&baseline );
background.right = background.left + bounds.h ;
background.bottom = background.top + bounds.v ;
::EraseRect( &background ) ;
}
::DrawThemeTextBox( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&frame,
teJustLeft,
nil );
}
else
#endif
{
wxCharBuffer text = linetext.mb_str(wxConvLocal) ;
if ( m_backgroundMode != wxTRANSPARENT )
{
Rect frame = { yy - fi.ascent + line*(fi.descent + fi.ascent + fi.leading) ,xx , yy - fi.ascent + (line+1)*(fi.descent + fi.ascent + fi.leading) , xx + 10000 } ;
short width = ::TextWidth( text , 0 , strlen(text) ) ;
frame.right = frame.left + width ;
::EraseRect( &frame ) ;
}
::DrawText( text , 0 , strlen(text) ) ;
}
}
::TextMode( srcOr ) ;
}
bool wxDC::CanGetTextExtent() const
{
wxCHECK_MSG(Ok(), false, wxT("Invalid DC"));
return true ;
}
void wxDC::DoGetTextExtent( const wxString &strtext, wxCoord *width, wxCoord *height,
wxCoord *descent, wxCoord *externalLeading ,
wxFont *theFont ) const
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
wxFont formerFont = m_font ;
if ( theFont )
{
// work around the constness
*((wxFont*)(&m_font)) = *theFont ;
}
MacInstallFont() ;
FontInfo fi ;
::GetFontInfo( &fi ) ;
#if TARGET_CARBON
bool useGetThemeText = ( GetThemeTextDimensions != (void*) kUnresolvedCFragSymbolAddress ) ;
if ( UMAGetSystemVersion() < 0x1000 || IsKindOf(CLASSINFO( wxPrinterDC ) ) || ((wxFont*)&m_font)->GetNoAntiAliasing() )
useGetThemeText = false ;
#endif
if ( height )
*height = YDEV2LOGREL( fi.descent + fi.ascent ) ;
if ( descent )
*descent =YDEV2LOGREL( fi.descent );
if ( externalLeading )
*externalLeading = YDEV2LOGREL( fi.leading ) ;
int length = strtext.length() ;
int laststop = 0 ;
int i = 0 ;
int curwidth = 0 ;
if ( width )
{
*width = 0 ;
#if 0 // apparently we don't have to do all that
while( i < length )
{
if( strtext[i] == 13 || strtext[i] == 10)
{
wxString linetext = strtext.Mid( laststop , i - laststop ) ;
if ( height )
*height += YDEV2LOGREL( fi.descent + fi.ascent + fi.leading ) ;
#if TARGET_CARBON
if ( useGetThemeText )
{
Point bounds={0,0} ;
SInt16 baseline ;
wxMacCFStringHolder mString( linetext , m_font.GetEncoding() ) ;
::GetThemeTextDimensions( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&bounds,
&baseline );
curwidth = bounds.h ;
}
else
#endif
{
wxCharBuffer text = linetext.mb_str(wxConvLocal) ;
curwidth = ::TextWidth( text , 0 , strlen(text) ) ;
}
if ( curwidth > *width )
*width = XDEV2LOGREL( curwidth ) ;
laststop = i+1 ;
}
i++ ;
}
wxString linetext = strtext.Mid( laststop , i - laststop ) ;
#endif // 0
wxString linetext = strtext ;
#if TARGET_CARBON
if ( useGetThemeText )
{
Point bounds={0,0} ;
SInt16 baseline ;
wxMacCFStringHolder mString( linetext , m_font.GetEncoding() ) ;
::GetThemeTextDimensions( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&bounds,
&baseline );
curwidth = bounds.h ;
}
else
#endif
{
wxCharBuffer text = linetext.mb_str(wxConvLocal) ;
curwidth = ::TextWidth( text , 0 , strlen(text) ) ;
}
if ( curwidth > *width )
*width = XDEV2LOGREL( curwidth ) ;
}
if ( theFont )
{
// work around the constness
*((wxFont*)(&m_font)) = formerFont ;
m_macFontInstalled = false ;
}
}
bool wxDC::DoGetPartialTextExtents(const wxString& text, wxArrayInt& widths) const
{
wxCHECK_MSG(Ok(), false, wxT("Invalid DC"));
widths.Empty();
widths.Add(0, text.length());
if (text.length() == 0)
return false;
wxMacFastPortSetter helper(this) ;
MacInstallFont() ;
#if TARGET_CARBON
bool useGetThemeText = ( GetThemeTextDimensions != (void*) kUnresolvedCFragSymbolAddress ) ;
if ( UMAGetSystemVersion() < 0x1000 || IsKindOf(CLASSINFO( wxPrinterDC ) ) || ((wxFont*)&m_font)->GetNoAntiAliasing() )
useGetThemeText = false ;
if ( useGetThemeText )
{
// If anybody knows how to do this more efficiently yet still handle
// the fractional glyph widths that may be present when using AA
// fonts, please change it. Currently it is measuring from the
// begining of the string for each succeding substring, which is much
// slower than this should be.
for (size_t i=0; i<text.length(); i++)
{
wxString str(text.Left(i+1));
Point bounds = {0,0};
SInt16 baseline ;
wxMacCFStringHolder mString(str, m_font.GetEncoding());
::GetThemeTextDimensions( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&bounds,
&baseline );
widths[i] = XDEV2LOGREL(bounds.h);
}
}
else
#endif
{
wxCharBuffer buff = text.mb_str(wxConvLocal);
size_t len = strlen(buff);
short* measurements = new short[len+1];
MeasureText(len, buff.data(), measurements);
// Copy to widths, starting at measurements[1]
// NOTE: this doesn't take into account any multi-byte characters
// in buff, it probabkly should...
for (size_t i=0; i<text.length(); i++)
widths[i] = XDEV2LOGREL(measurements[i+1]);
delete [] measurements;
}
return true;
}
wxCoord wxDC::GetCharWidth(void) const
{
wxCHECK_MSG(Ok(), 1, wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
MacInstallFont() ;
int width = 0 ;
#if TARGET_CARBON
bool useGetThemeText = ( GetThemeTextDimensions != (void*) kUnresolvedCFragSymbolAddress ) ;
if ( UMAGetSystemVersion() < 0x1000 || ((wxFont*)&m_font)->GetNoAntiAliasing() )
useGetThemeText = false ;
#endif
char text[] = "g" ;
#if TARGET_CARBON
if ( useGetThemeText )
{
Point bounds={0,0} ;
SInt16 baseline ;
CFStringRef mString = CFStringCreateWithBytes( NULL , (UInt8*) text , 1 , CFStringGetSystemEncoding(), false ) ;
::GetThemeTextDimensions( mString,
kThemeCurrentPortFont,
kThemeStateActive,
false,
&bounds,
&baseline );
CFRelease( mString ) ;
width = bounds.h ;
}
else
#endif
{
width = ::TextWidth( text , 0 , 1 ) ;
}
return YDEV2LOGREL(width) ;
}
wxCoord wxDC::GetCharHeight(void) const
{
wxCHECK_MSG(Ok(), 1, wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
MacInstallFont() ;
FontInfo fi ;
::GetFontInfo( &fi ) ;
return YDEV2LOGREL( fi.descent + fi.ascent );
}
void wxDC::Clear(void)
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
wxMacFastPortSetter helper(this) ;
Rect rect = { -31000 , -31000 , 31000 , 31000 } ;
if (m_backgroundBrush.GetStyle() != wxTRANSPARENT)
{
::PenNormal() ;
//MacInstallBrush() ;
MacSetupBackgroundForCurrentPort( m_backgroundBrush ) ;
::EraseRect( &rect ) ;
}
}
void wxDC::MacInstallFont() const
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
// if ( m_macFontInstalled )
// return ;
Pattern blackColor ;
MacSetupBackgroundForCurrentPort(m_backgroundBrush) ;
if ( m_font.Ok() )
{
::TextFont( m_font.GetMacFontNum() ) ;
::TextSize( (short)(m_scaleY * m_font.GetMacFontSize()) ) ;
::TextFace( m_font.GetMacFontStyle() ) ;
m_macFontInstalled = true ;
m_macBrushInstalled = false ;
m_macPenInstalled = false ;
RGBColor forecolor = MAC_WXCOLORREF( m_textForegroundColour.GetPixel());
RGBColor backcolor = MAC_WXCOLORREF( m_textBackgroundColour.GetPixel());
::RGBForeColor( &forecolor );
::RGBBackColor( &backcolor );
}
else
{
FontFamilyID fontId ;
Str255 fontName ;
SInt16 fontSize ;
Style fontStyle ;
GetThemeFont(kThemeSmallSystemFont , GetApplicationScript() , fontName , &fontSize , &fontStyle ) ;
GetFNum( fontName, &fontId );
::TextFont( fontId ) ;
::TextSize( short(m_scaleY * fontSize) ) ;
::TextFace( fontStyle ) ;
// todo reset after spacing changes - or store the current spacing somewhere
m_macFontInstalled = true ;
m_macBrushInstalled = false ;
m_macPenInstalled = false ;
RGBColor forecolor = MAC_WXCOLORREF( m_textForegroundColour.GetPixel());
RGBColor backcolor = MAC_WXCOLORREF( m_textBackgroundColour.GetPixel());
::RGBForeColor( &forecolor );
::RGBBackColor( &backcolor );
}
short mode = patCopy ;
// todo :
switch( m_logicalFunction )
{
case wxCOPY: // src
mode = patCopy ;
break ;
case wxINVERT: // NOT dst
::PenPat(GetQDGlobalsBlack(&blackColor));
mode = patXor ;
break ;
case wxXOR: // src XOR dst
mode = patXor ;
break ;
case wxOR_REVERSE: // src OR (NOT dst)
mode = notPatOr ;
break ;
case wxSRC_INVERT: // (NOT src)
mode = notPatCopy ;
break ;
case wxAND: // src AND dst
mode = adMin ;
break ;
// unsupported TODO
case wxCLEAR: // 0
case wxAND_REVERSE:// src AND (NOT dst)
case wxAND_INVERT: // (NOT src) AND dst
case wxNO_OP: // dst
case wxNOR: // (NOT src) AND (NOT dst)
case wxEQUIV: // (NOT src) XOR dst
case wxOR_INVERT: // (NOT src) OR dst
case wxNAND: // (NOT src) OR (NOT dst)
case wxOR: // src OR dst
case wxSET: // 1
// case wxSRC_OR: // source _bitmap_ OR destination
// case wxSRC_AND: // source _bitmap_ AND destination
break ;
}
::PenMode( mode ) ;
OSStatus status = noErr ;
Fixed atsuSize = IntToFixed( int(m_scaleY * m_font.GetMacFontSize()) ) ;
Style qdStyle = m_font.GetMacFontStyle() ;
ATSUFontID atsuFont = m_font.GetMacATSUFontID() ;
status = ::ATSUCreateStyle((ATSUStyle *)&m_macATSUIStyle) ;
wxASSERT_MSG( status == noErr , wxT("couldn't create ATSU style") ) ;
ATSUAttributeTag atsuTags[] =
{
kATSUFontTag ,
kATSUSizeTag ,
// kATSUColorTag ,
// kATSUBaselineClassTag ,
kATSUVerticalCharacterTag,
kATSUQDBoldfaceTag ,
kATSUQDItalicTag ,
kATSUQDUnderlineTag ,
kATSUQDCondensedTag ,
kATSUQDExtendedTag ,
} ;
ByteCount atsuSizes[sizeof(atsuTags)/sizeof(ATSUAttributeTag)] =
{
sizeof( ATSUFontID ) ,
sizeof( Fixed ) ,
// sizeof( RGBColor ) ,
// sizeof( BslnBaselineClass ) ,
sizeof( ATSUVerticalCharacterType),
sizeof( Boolean ) ,
sizeof( Boolean ) ,
sizeof( Boolean ) ,
sizeof( Boolean ) ,
sizeof( Boolean ) ,
} ;
Boolean kTrue = true ;
Boolean kFalse = false ;
//BslnBaselineClass kBaselineDefault = kBSLNHangingBaseline ;
ATSUVerticalCharacterType kHorizontal = kATSUStronglyHorizontal;
ATSUAttributeValuePtr atsuValues[sizeof(atsuTags)/sizeof(ATSUAttributeTag)] =
{
&atsuFont ,
&atsuSize ,
// &MAC_WXCOLORREF( m_textForegroundColour.GetPixel() ) ,
// &kBaselineDefault ,
&kHorizontal,
(qdStyle & bold) ? &kTrue : &kFalse ,
(qdStyle & italic) ? &kTrue : &kFalse ,
(qdStyle & underline) ? &kTrue : &kFalse ,
(qdStyle & condense) ? &kTrue : &kFalse ,
(qdStyle & extend) ? &kTrue : &kFalse ,
} ;
status = ::ATSUSetAttributes((ATSUStyle)m_macATSUIStyle, sizeof(atsuTags)/sizeof(ATSUAttributeTag) ,
atsuTags, atsuSizes, atsuValues);
wxASSERT_MSG( status == noErr , wxT("couldn't set create ATSU style") ) ;
}
Pattern gPatterns[] =
{ // hatch patterns
{ { 0xFF , 0xFF , 0xFF , 0xFF , 0xFF , 0xFF , 0xFF , 0xFF } } ,
{ { 0x01 , 0x02 , 0x04 , 0x08 , 0x10 , 0x20 , 0x40 , 0x80 } } ,
{ { 0x80 , 0x40 , 0x20 , 0x10 , 0x08 , 0x04 , 0x02 , 0x01 } } ,
{ { 0x10 , 0x10 , 0x10 , 0xFF , 0x10 , 0x10 , 0x10 , 0x10 } } ,
{ { 0x00 , 0x00 , 0x00 , 0xFF , 0x00 , 0x00 , 0x00 , 0x00 } } ,
{ { 0x10 , 0x10 , 0x10 , 0x10 , 0x10 , 0x10 , 0x10 , 0x10 } } ,
{ { 0x81 , 0x42 , 0x24 , 0x18 , 0x18 , 0x24 , 0x42 , 0x81 } } ,
// dash patterns
{ { 0xCC , 0x99 , 0x33 , 0x66 , 0xCC , 0x99 , 0x33 , 0x66 } } , // DOT
{ { 0xFE , 0xFD , 0xFB , 0xF7 , 0xEF , 0xDF , 0xBF , 0x7F } } , // LONG_DASH
{ { 0xEE , 0xDD , 0xBB , 0x77 , 0xEE , 0xDD , 0xBB , 0x77 } } , // SHORT_DASH
{ { 0xDE , 0xBD , 0x7B , 0xF6 , 0xED , 0xDB , 0xB7 , 0x6F } } , // DOT_DASH
} ;
static void wxMacGetPattern(int penStyle, Pattern *pattern)
{
int index = 0; // solid pattern by default
switch(penStyle)
{
// hatches
case wxBDIAGONAL_HATCH: index = 1; break;
case wxFDIAGONAL_HATCH: index = 2; break;
case wxCROSS_HATCH: index = 3; break;
case wxHORIZONTAL_HATCH: index = 4; break;
case wxVERTICAL_HATCH: index = 5; break;
case wxCROSSDIAG_HATCH: index = 6; break;
// dashes
case wxDOT: index = 7; break;
case wxLONG_DASH: index = 8; break;
case wxSHORT_DASH: index = 9; break;
case wxDOT_DASH: index = 10; break;
}
*pattern = gPatterns[index];
}
void wxDC::MacInstallPen() const
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
//Pattern blackColor;
// if ( m_macPenInstalled )
// return ;
RGBColor forecolor = MAC_WXCOLORREF( m_pen.GetColour().GetPixel());
RGBColor backcolor = MAC_WXCOLORREF( m_backgroundBrush.GetColour().GetPixel());
::RGBForeColor( &forecolor );
::RGBBackColor( &backcolor );
::PenNormal() ;
int penWidth = (int) (m_pen.GetWidth() * m_scaleX) ; ;
// null means only one pixel, at whatever resolution
if ( penWidth == 0 )
penWidth = 1 ;
::PenSize(penWidth, penWidth);
int penStyle = m_pen.GetStyle();
Pattern pat;
if (penStyle == wxUSER_DASH)
{
// FIXME: there should be exactly 8 items in the dash
wxDash* dash ;
int number = m_pen.GetDashes(&dash) ;
int index = 0;
for ( int i = 0 ; i < 8 ; ++i )
{
pat.pat[i] = dash[index] ;
if (index < number - 1)
index++;
}
}
else
{
wxMacGetPattern(penStyle, &pat);
}
::PenPat(&pat);
short mode = patCopy ;
// todo :
switch( m_logicalFunction )
{
case wxCOPY: // only foreground color, leave background (thus not patCopy)
mode = patOr ;
break ;
case wxINVERT: // NOT dst
// ::PenPat(GetQDGlobalsBlack(&blackColor));
mode = patXor ;
break ;
case wxXOR: // src XOR dst
mode = patXor ;
break ;
case wxOR_REVERSE: // src OR (NOT dst)
mode = notPatOr ;
break ;
case wxSRC_INVERT: // (NOT src)
mode = notPatCopy ;
break ;
case wxAND: // src AND dst
mode = adMin ;
break ;
// unsupported TODO
case wxCLEAR: // 0
case wxAND_REVERSE:// src AND (NOT dst)
case wxAND_INVERT: // (NOT src) AND dst
case wxNO_OP: // dst
case wxNOR: // (NOT src) AND (NOT dst)
case wxEQUIV: // (NOT src) XOR dst
case wxOR_INVERT: // (NOT src) OR dst
case wxNAND: // (NOT src) OR (NOT dst)
case wxOR: // src OR dst
case wxSET: // 1
// case wxSRC_OR: // source _bitmap_ OR destination
// case wxSRC_AND: // source _bitmap_ AND destination
break ;
}
::PenMode( mode ) ;
m_macPenInstalled = true ;
m_macBrushInstalled = false ;
m_macFontInstalled = false ;
}
void wxDC::MacSetupBackgroundForCurrentPort(const wxBrush& background )
{
Pattern whiteColor ;
switch( background.MacGetBrushKind() )
{
case kwxMacBrushTheme :
{
::SetThemeBackground( background.GetMacTheme() , wxDisplayDepth() , true ) ;
break ;
}
case kwxMacBrushThemeBackground :
{
Rect extent ;
ThemeBackgroundKind bg = background.GetMacThemeBackground( &extent ) ;
::ApplyThemeBackground( bg , &extent ,kThemeStateActive , wxDisplayDepth() , true ) ;
break ;
}
case kwxMacBrushColour :
{
::RGBBackColor( &MAC_WXCOLORREF( background.GetColour().GetPixel()) );
int brushStyle = background.GetStyle();
if (brushStyle == wxSOLID)
::BackPat(GetQDGlobalsWhite(&whiteColor));
else if (background.IsHatch())
{
Pattern pat ;
wxMacGetPattern(brushStyle, &pat);
::BackPat(&pat);
}
else
{
::BackPat(GetQDGlobalsWhite(&whiteColor));
}
break ;
}
}
}
void wxDC::MacInstallBrush() const
{
wxCHECK_RET(Ok(), wxT("Invalid DC"));
Pattern blackColor ;
// if ( m_macBrushInstalled )
// return ;
// foreground
bool backgroundTransparent = (GetBackgroundMode() == wxTRANSPARENT) ;
::RGBForeColor( &MAC_WXCOLORREF( m_brush.GetColour().GetPixel()) );
::RGBBackColor( &MAC_WXCOLORREF( m_backgroundBrush.GetColour().GetPixel()) );
int brushStyle = m_brush.GetStyle();
if (brushStyle == wxSOLID)
{
::PenPat(GetQDGlobalsBlack(&blackColor));
}
else if (m_brush.IsHatch())
{
Pattern pat ;
wxMacGetPattern(brushStyle, &pat);
::PenPat(&pat);
}
else if ( m_brush.GetStyle() == wxSTIPPLE || m_brush.GetStyle() == wxSTIPPLE_MASK_OPAQUE )
{
// we force this in order to be compliant with wxMSW
backgroundTransparent = false ;
// for these the text fore (and back for MASK_OPAQUE) colors are used
wxBitmap* bitmap = m_brush.GetStipple() ;
int width = bitmap->GetWidth() ;
int height = bitmap->GetHeight() ;
GWorldPtr gw = NULL ;
if ( m_brush.GetStyle() == wxSTIPPLE )
gw = MAC_WXHBITMAP(bitmap->GetHBITMAP()) ;
else
gw = MAC_WXHBITMAP(bitmap->GetMask()->GetMaskBitmap()) ;
PixMapHandle gwpixmaphandle = GetGWorldPixMap( gw ) ;
LockPixels( gwpixmaphandle ) ;
bool isMonochrome = !IsPortColor( gw ) ;
if ( !isMonochrome )
{
if ( (**gwpixmaphandle).pixelSize == 1 )
isMonochrome = true ;
}
if ( isMonochrome && width == 8 && height == 8 )
{
::RGBForeColor( &MAC_WXCOLORREF( m_textForegroundColour.GetPixel()) );
::RGBForeColor( &MAC_WXCOLORREF( m_textBackgroundColour.GetPixel()) );
BitMap* gwbitmap = (BitMap*) *gwpixmaphandle ; // since the color depth is 1 it is a BitMap
UInt8 *gwbits = (UInt8*) gwbitmap->baseAddr ;
int alignment = gwbitmap->rowBytes & 0x7FFF ;
Pattern pat ;
for ( int i = 0 ; i < 8 ; ++i )
{
pat.pat[i] = gwbits[i*alignment+0] ;
}
UnlockPixels( GetGWorldPixMap( gw ) ) ;
::PenPat( &pat ) ;
}
else
{
// this will be the code to handle power of 2 patterns, we will have to arrive at a nice
// caching scheme before putting this into production
Handle image;
long imageSize;
PixPatHandle pixpat = NewPixPat() ;
CopyPixMap(gwpixmaphandle, (**pixpat).patMap);
imageSize = GetPixRowBytes((**pixpat).patMap) *
((**(**pixpat).patMap).bounds.bottom -
(**(**pixpat).patMap).bounds.top);
PtrToHand( (**gwpixmaphandle).baseAddr, &image, imageSize );
(**pixpat).patData = image;
if ( isMonochrome )
{
CTabHandle ctable = ((**((**pixpat).patMap)).pmTable) ;
ColorSpecPtr ctspec = (ColorSpecPtr) &(**ctable).ctTable ;
if ( ctspec[0].rgb.red == 0x0000 )
{
ctspec[1].rgb = MAC_WXCOLORREF( m_textBackgroundColour.GetPixel()) ;
ctspec[0].rgb = MAC_WXCOLORREF( m_textForegroundColour.GetPixel()) ;
}
else
{
ctspec[0].rgb = MAC_WXCOLORREF( m_textBackgroundColour.GetPixel()) ;
ctspec[1].rgb = MAC_WXCOLORREF( m_textForegroundColour.GetPixel()) ;
}
::CTabChanged( ctable ) ;
}
::PenPixPat(pixpat);
m_macForegroundPixMap = pixpat ;
}
UnlockPixels( gwpixmaphandle ) ;
}
else
{
::PenPat(GetQDGlobalsBlack(&blackColor));
}
short mode = patCopy ;
switch( m_logicalFunction )
{
case wxCOPY: // src
if ( backgroundTransparent )
mode = patOr ;
else
mode = patCopy ;
break ;
case wxINVERT: // NOT dst
if ( !backgroundTransparent )
{
::PenPat(GetQDGlobalsBlack(&blackColor));
}
mode = patXor ;
break ;
case wxXOR: // src XOR dst
mode = patXor ;
break ;
case wxOR_REVERSE: // src OR (NOT dst)
mode = notPatOr ;
break ;
case wxSRC_INVERT: // (NOT src)
mode = notPatCopy ;
break ;
case wxAND: // src AND dst
mode = adMin ;
break ;
// unsupported TODO
case wxCLEAR: // 0
case wxAND_REVERSE:// src AND (NOT dst)
case wxAND_INVERT: // (NOT src) AND dst
case wxNO_OP: // dst
case wxNOR: // (NOT src) AND (NOT dst)
case wxEQUIV: // (NOT src) XOR dst
case wxOR_INVERT: // (NOT src) OR dst
case wxNAND: // (NOT src) OR (NOT dst)
case wxOR: // src OR dst
case wxSET: // 1
// case wxSRC_OR: // source _bitmap_ OR destination
// case wxSRC_AND: // source _bitmap_ AND destination
break ;
}
::PenMode( mode ) ;
m_macBrushInstalled = true ;
m_macPenInstalled = false ;
m_macFontInstalled = false ;
}
// ---------------------------------------------------------------------------
// coordinates transformations
// ---------------------------------------------------------------------------
wxCoord wxDCBase::DeviceToLogicalX(wxCoord x) const
{
return ((wxDC *)this)->XDEV2LOG(x);
}
wxCoord wxDCBase::DeviceToLogicalY(wxCoord y) const
{
return ((wxDC *)this)->YDEV2LOG(y);
}
wxCoord wxDCBase::DeviceToLogicalXRel(wxCoord x) const
{
return ((wxDC *)this)->XDEV2LOGREL(x);
}
wxCoord wxDCBase::DeviceToLogicalYRel(wxCoord y) const
{
return ((wxDC *)this)->YDEV2LOGREL(y);
}
wxCoord wxDCBase::LogicalToDeviceX(wxCoord x) const
{
return ((wxDC *)this)->XLOG2DEV(x);
}
wxCoord wxDCBase::LogicalToDeviceY(wxCoord y) const
{
return ((wxDC *)this)->YLOG2DEV(y);
}
wxCoord wxDCBase::LogicalToDeviceXRel(wxCoord x) const
{
return ((wxDC *)this)->XLOG2DEVREL(x);
}
wxCoord wxDCBase::LogicalToDeviceYRel(wxCoord y) const
{
return ((wxDC *)this)->YLOG2DEVREL(y);
}
| gpl-2.0 |
mambax7/tdmlinks | config/paths.php | 823 | <?php
$moduleDirName = \basename(\dirname(__DIR__));
$moduleDirNameUpper = mb_strtoupper($moduleDirName);
return (object)[
'name' => mb_strtoupper($moduleDirName) . ' PathConfigurator',
'dirname' => $moduleDirName,
'admin' => XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/admin',
'modPath' => XOOPS_ROOT_PATH . '/modules/' . $moduleDirName,
'modUrl' => XOOPS_URL . '/modules/' . $moduleDirName,
'uploadPath' => XOOPS_UPLOAD_PATH . '/' . $moduleDirName,
'uploadUrl' => XOOPS_UPLOAD_URL . '/' . $moduleDirName,
'uploadFolders' => [
XOOPS_UPLOAD_PATH . '/' . $moduleDirName,
XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/category',
XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/screenshots',
//XOOPS_UPLOAD_PATH . '/flags'
],
];
| gpl-2.0 |
sdrobotics101/cubeception-2-tools | microzed/gyrocal/src/main.cc | 1351 | #include <iostream>
#include <unistd.h>
#include "IMU/mpu9250.h"
#define SAMPLE_SIZE 100
int main(int argc, char *argv[])
{
MPU9250 *mpu0 = new MPU9250(0x00040000, 0);
MPU9250 *mpu1 = new MPU9250(0x00050000, 0);
mpu0->set_gyro_scale(MPU9250G_250dps);
mpu1->set_gyro_scale(MPU9250G_250dps);
double mpu0Xavg = 0;
double mpu0Yavg = 0;
double mpu0Zavg = 0;
double mpu1Xavg = 0;
double mpu1Yavg = 0;
double mpu1Zavg = 0;
double mpu0Xcurr = 0;
double mpu0Ycurr = 0;
double mpu0Zcurr = 0;
double mpu1Xcurr = 0;
double mpu1Ycurr = 0;
double mpu1Zcurr = 0;
double a;
for (int i = 0;i < SAMPLE_SIZE;i++) {
mpu0->read_robot(&a, &a, &a,
&mpu0Xcurr, &mpu0Ycurr, &mpu0Zcurr,
&a, &a, &a);
mpu1->read_robot(&a, &a, &a,
&mpu1Xcurr, &mpu1Ycurr, &mpu1Zcurr,
&a, &a, &a);
mpu0Xavg += mpu0Xcurr;
mpu0Yavg += mpu0Ycurr;
mpu0Zavg += mpu0Zcurr;
mpu1Xavg += mpu1Xcurr;
mpu1Yavg += mpu1Ycurr;
mpu1Zavg += mpu1Zcurr;
usleep(10000);
}
mpu0Xavg /= SAMPLE_SIZE;
mpu0Yavg /= SAMPLE_SIZE;
mpu0Zavg /= SAMPLE_SIZE;
mpu1Xavg /= SAMPLE_SIZE;
mpu1Yavg /= SAMPLE_SIZE;
mpu1Zavg /= SAMPLE_SIZE;
std::cout << "MPU0: " << mpu0Xavg << " " << mpu0Yavg << " " << mpu0Zavg << std::endl;
std::cout << "MPU1: " << mpu1Xavg << " " << mpu1Yavg << " " << mpu1Zavg << std::endl;
delete mpu0;
delete mpu1;
return 0;
}
| gpl-2.0 |
jamesharry/foothillfreak | 2007/september/andes/araucarias-old.php | 3612 | <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The Andes, Skiing Las Araucarias Ski Resort</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="description" content="A ski blog about backcountry skiing the Wasatch foothills,
near Salt Lake City, Utah. It covers year round skiing, snowboarding, touring, skinning,
alpine ski mountaineering, and the occasional peak bagging.">
<meta name="robots" content="index,follow" />
<link rel="stylesheet" href="http://www.foothillfreak.com/masterstyle2.css" type="text/css">
<link rel="shortcut icon" href="http://www.foothillfreak.com/images/ffzz.ico" type="image/ico" />
<script type="text/javascript" src="http://www.foothillfreak.com/masterjava.js"></script>
</head>
<body bgcolor="#50616F" background="http://www.foothillfreak.com/images/bgphoto2.gif" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<?php include ($_SERVER['DOCUMENT_ROOT']. "/includes/header.php"); ?>
<table width="777" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#C5D6E4">
<table width="777px" border="0" cellspacing="0" cellpadding="0">
<tr>
<?php include ($_SERVER['DOCUMENT_ROOT']. "/includes/sidenav.php"); ?>
<td valign="top" id="maincontent">
<h2>Andes, Frontside and Back: </h2>
<h1>Skiing El Centro de Ski Las Araucarias</h1>
<?php include ($_SERVER['DOCUMENT_ROOT']. "/includes/nav-andes.php"); ?>
<h6>September, 2007</h6>
<p>Skiing at Las Araucarias Ski Resort reminded me of everything
I love about skiing: the simple, mystical charm of being on a mountain
in the sun in wintertime. People didn't care what they were wearing,
they didn't care what kind of gear they had, they didn't even care
if their car couldn't make the last 2 icy miles to the resort.
People were outside, and they were happy.</p>
<p>If you're skiing in Chile I'd higly recommend skipping a day at
one of the bigger resorts to hang with the locals of <a href="http://www.skiaraucarias.cl/">El
Centro de Ski Las Araucarias.</a></p>
<p><img src="images/DSC00373.jpg" alt="Las Aruncarias" width="600" height="578" />
<br />This is about 3km away from Las Aruncarias Ski resort. We
should have parked here and started walking, like the people on
this bus did. We would have gotten to the slopes sooner than trying
to drive...
<p> </p>
<p><img src="images/DSC04053.jpg" alt="1" width="600" height="417" /></p>
<p><img src="images/DSC04088.jpg" alt="2" width="600" height="450" /></p>
<p><img src="images/DSC04093.jpg" alt="4" width="600" height="423" /></p>
<p><img src="images/DSC04095.jpg" alt="5" width="600" height="432" /></p>
<p><img src="images/DSC04102.jpg" alt="6" width="600" height="407" /></p>
<p><img src="images/DSC04091.jpg" alt="3" width="600" height="456" /></p>
<p><img src="images/DSC04105.jpg" alt="7" width="600" height="446" /><br />
This is lift served backcountry at it's finest...</p>
</td>
</tr>
</table> </td>
</tr>
</table>
<?php include ($_SERVER['DOCUMENT_ROOT']. "/includes/footer.php"); ?>
</body>
</html>
| gpl-2.0 |
edijman/SOEN_6431_Colonization_Game | src/net/sf/freecol/client/gui/panel/ReportHistoryPanel.java | 1774 | /**
* Copyright (C) 2002-2015 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.panel;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.model.HistoryEvent;
/**
* This panel displays the History Report.
*/
public final class ReportHistoryPanel extends ReportPanel {
/**
* The constructor that will add the items to this panel.
*
* @param freeColClient The <code>FreeColClient</code> for the game.
*/
public ReportHistoryPanel(FreeColClient freeColClient) {
super(freeColClient, "reportHistoryAction");
List<HistoryEvent> history = getMyPlayer().getHistory();
// Display Panel
reportPanel.removeAll();
if (history.isEmpty()) return;
reportPanel.setLayout(new MigLayout("wrap 2", "[]20[fill]", ""));
for (HistoryEvent event : history) {
reportPanel.add(Utility.localizedLabel(event.getTurn().getLabel()));
reportPanel.add(Utility.localizedTextArea(event, 40));
}
}
}
| gpl-2.0 |
soulik/luambedtls | src/objects/x509crl.cpp | 5282 | #include "objects/x509crl.hpp"
#include "objects/x509crlEntry.hpp"
#include "objects/ASN1buf.hpp"
#include "objects/ASN1named.hpp"
#include "objects/PKContext.hpp"
namespace luambedtls {
mbedtls_x509_crl * x509crl::constructor(State & state, bool & managed){
mbedtls_x509_crl * certificate = new mbedtls_x509_crl;
mbedtls_x509_crl_init(certificate);
return certificate;
}
void x509crl::destructor(State & state, mbedtls_x509_crl * certificate){
mbedtls_x509_crl_free(certificate);
delete certificate;
}
int x509crl::parse(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
if (stack->is<LUA_TSTRING>(1)){
const std::string data = stack->toLString(1);
stack->push<int>(mbedtls_x509_crl_parse(certificate, reinterpret_cast<const unsigned char*>(data.c_str()), data.length()));
return 1;
}
return 0;
}
int x509crl::parseDER(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
if (stack->is<LUA_TSTRING>(1)){
const std::string data = stack->toLString(1);
stack->push<int>(mbedtls_x509_crl_parse_der(certificate, reinterpret_cast<const unsigned char*>(data.c_str()), data.length()));
return 1;
}
return 0;
}
int x509crl::parseFile(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
if (stack->is<LUA_TSTRING>(1)){
const std::string path = stack->to<const std::string>(1);
stack->push<int>(mbedtls_x509_crl_parse_file(certificate, path.c_str()));
return 1;
}
return 0;
}
int x509crl::info(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
std::string prefix = "";
size_t bufferSize = 4096;
if (stack->is<LUA_TNUMBER>(1)){
bufferSize = stack->to<int>(1);
}
if (stack->is<LUA_TSTRING>(2)){
prefix = stack->to<const std::string>(2);
}
char * buffer = new char[bufferSize];
int result = mbedtls_x509_crl_info(buffer, bufferSize, prefix.c_str(), certificate);
if (result == 0){
stack->push<const std::string &>(buffer);
}
else{
stack->push<int>(result);
}
delete[] buffer;
return 1;
}
int x509crl::getRaw(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
ASN1buf * interfaceASN1buf = OBJECT_IFACE(ASN1buf);
interfaceASN1buf->pushX509(&certificate->raw);
return 1;
}
int x509crl::getTBS(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
ASN1buf * interfaceASN1buf = OBJECT_IFACE(ASN1buf);
interfaceASN1buf->pushX509(&certificate->tbs);
return 1;
}
int x509crl::getVersion(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
stack->push<int>(certificate->version);
return 1;
}
int x509crl::getSigOID(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
ASN1buf * interfaceASN1buf = OBJECT_IFACE(ASN1buf);
interfaceASN1buf->pushX509(&certificate->sig_oid);
return 1;
}
int x509crl::getIssuerRaw(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
ASN1buf * interfaceASN1buf = OBJECT_IFACE(ASN1buf);
interfaceASN1buf->pushX509(&certificate->issuer_raw);
return 1;
}
int x509crl::getIssuer(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
ASN1named * interfaceASN1named = OBJECT_IFACE(ASN1named);
interfaceASN1named->push(&certificate->issuer);
return 1;
}
int x509crl::getThisUpdate(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
return pushX509time(state, &certificate->this_update);
}
int x509crl::getNextUpdate(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
return pushX509time(state, &certificate->next_update);
}
int x509crl::getEntry(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
x509crlEntry * interfaceEntry = OBJECT_IFACE(x509crlEntry);
interfaceEntry->push(&certificate->entry);
return 1;
}
int x509crl::getCrlExt(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
ASN1buf * interfaceASN1buf = OBJECT_IFACE(ASN1buf);
interfaceASN1buf->pushX509(&certificate->crl_ext);
return 1;
}
int x509crl::getSigOID2(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
ASN1buf * interfaceASN1buf = OBJECT_IFACE(ASN1buf);
interfaceASN1buf->pushX509(&certificate->sig_oid2);
return 1;
}
int x509crl::getSig(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
ASN1buf * interfaceASN1buf = OBJECT_IFACE(ASN1buf);
interfaceASN1buf->pushX509(&certificate->sig);
return 1;
}
int x509crl::getSigMD(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
stack->push<LUA_NUMBER>(certificate->sig_md);
return 1;
}
int x509crl::getSigPK(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
stack->push<LUA_NUMBER>(certificate->sig_md);
return 1;
}
int x509crl::getNext(State & state, mbedtls_x509_crl * certificate){
Stack * stack = state.stack;
x509crl * interfaceCRL = OBJECT_IFACE(x509crl);
if (certificate->next){
interfaceCRL->push(certificate->next);
return 1;
}
else{
return 0;
}
}
void initx509crl(State * state, Module & module){
INIT_OBJECT(x509crl);
}
};
| gpl-2.0 |
danieljabailey/inkscape_experiments | src/2geom/d2-sbasis.cpp | 11979 | /**
* \file
* \brief Some two-dimensional SBasis operations
*//*
* Authors:
* MenTaLguy <mental@rydia.net>
* Jean-François Barraud <jf.barraud@gmail.com>
* Johan Engelen <j.b.c.engelen@alumnus.utwente.nl>
*
* Copyright 2007-2012 Authors
*
* This library is free software; you can redistribute it and/or
* modify it either under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* (the "LGPL") or, at your option, under the terms of the Mozilla
* Public License Version 1.1 (the "MPL"). If you do not alter this
* notice, a recipient may use your version of this file under either
* the MPL or the LGPL.
*
* You should have received a copy of the LGPL along with this library
* in the file COPYING-LGPL-2.1; if not, output to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* You should have received a copy of the MPL along with this library
* in the file COPYING-MPL-1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
* OF ANY KIND, either express or implied. See the LGPL or the MPL for
* the specific language governing rights and limitations.
*
*/
#include <2geom/d2.h>
#include <2geom/piecewise.h>
namespace Geom {
SBasis L2(D2<SBasis> const & a, unsigned k) { return sqrt(dot(a, a), k); }
D2<SBasis> multiply(Linear const & a, D2<SBasis> const & b) {
return D2<SBasis>(multiply(a, b[X]), multiply(a, b[Y]));
}
D2<SBasis> multiply(SBasis const & a, D2<SBasis> const & b) {
return D2<SBasis>(multiply(a, b[X]), multiply(a, b[Y]));
}
D2<SBasis> truncate(D2<SBasis> const & a, unsigned terms) {
return D2<SBasis>(truncate(a[X], terms), truncate(a[Y], terms));
}
unsigned sbasis_size(D2<SBasis> const & a) {
return std::max((unsigned) a[0].size(), (unsigned) a[1].size());
}
//TODO: Is this sensical? shouldn't it be like pythagorean or something?
double tail_error(D2<SBasis> const & a, unsigned tail) {
return std::max(a[0].tailError(tail), a[1].tailError(tail));
}
Piecewise<D2<SBasis> > sectionize(D2<Piecewise<SBasis> > const &a) {
Piecewise<SBasis> x = partition(a[0], a[1].cuts), y = partition(a[1], a[0].cuts);
assert(x.size() == y.size());
Piecewise<D2<SBasis> > ret;
for(unsigned i = 0; i < x.size(); i++)
ret.push_seg(D2<SBasis>(x[i], y[i]));
ret.cuts.insert(ret.cuts.end(), x.cuts.begin(), x.cuts.end());
return ret;
}
D2<Piecewise<SBasis> > make_cuts_independent(Piecewise<D2<SBasis> > const &a) {
D2<Piecewise<SBasis> > ret;
for(unsigned d = 0; d < 2; d++) {
for(unsigned i = 0; i < a.size(); i++)
ret[d].push_seg(a[i][d]);
ret[d].cuts.insert(ret[d].cuts.end(), a.cuts.begin(), a.cuts.end());
}
return ret;
}
Piecewise<D2<SBasis> > rot90(Piecewise<D2<SBasis> > const &M){
Piecewise<D2<SBasis> > result;
if (M.empty()) return M;
result.push_cut(M.cuts[0]);
for (unsigned i=0; i<M.size(); i++){
result.push(rot90(M[i]),M.cuts[i+1]);
}
return result;
}
/** @brief Calculates the 'dot product' or 'inner product' of \c a and \c b
* @return \f[
* f(t) \rightarrow \left\{
* \begin{array}{c}
* a_1 \bullet b_1 \\
* a_2 \bullet b_2 \\
* \ldots \\
* a_n \bullet b_n \\
* \end{array}\right.
* \f]
* @relates Piecewise */
Piecewise<SBasis> dot(Piecewise<D2<SBasis> > const &a, Piecewise<D2<SBasis> > const &b)
{
Piecewise<SBasis > result;
if (a.empty() || b.empty()) return result;
Piecewise<D2<SBasis> > aa = partition(a,b.cuts);
Piecewise<D2<SBasis> > bb = partition(b,a.cuts);
result.push_cut(aa.cuts.front());
for (unsigned i=0; i<aa.size(); i++){
result.push(dot(aa.segs[i],bb.segs[i]),aa.cuts[i+1]);
}
return result;
}
/** @brief Calculates the 'dot product' or 'inner product' of \c a and \c b
* @return \f[
* f(t) \rightarrow \left\{
* \begin{array}{c}
* a_1 \bullet b \\
* a_2 \bullet b \\
* \ldots \\
* a_n \bullet b \\
* \end{array}\right.
* \f]
* @relates Piecewise */
Piecewise<SBasis> dot(Piecewise<D2<SBasis> > const &a, Point const &b)
{
Piecewise<SBasis > result;
if (a.empty()) return result;
result.push_cut(a.cuts.front());
for (unsigned i = 0; i < a.size(); ++i){
result.push(dot(a.segs[i],b), a.cuts[i+1]);
}
return result;
}
Piecewise<SBasis> cross(Piecewise<D2<SBasis> > const &a,
Piecewise<D2<SBasis> > const &b){
Piecewise<SBasis > result;
if (a.empty() || b.empty()) return result;
Piecewise<D2<SBasis> > aa = partition(a,b.cuts);
Piecewise<D2<SBasis> > bb = partition(b,a.cuts);
result.push_cut(aa.cuts.front());
for (unsigned i=0; i<a.size(); i++){
result.push(cross(aa.segs[i],bb.segs[i]),aa.cuts[i+1]);
}
return result;
}
Piecewise<D2<SBasis> > operator*(Piecewise<D2<SBasis> > const &a, Affine const &m) {
Piecewise<D2<SBasis> > result;
if(a.empty()) return result;
result.push_cut(a.cuts[0]);
for (unsigned i = 0; i < a.size(); i++) {
result.push(a[i] * m, a.cuts[i+1]);
}
return result;
}
//if tol>0, only force continuity where the jump is smaller than tol.
Piecewise<D2<SBasis> > force_continuity(Piecewise<D2<SBasis> > const &f, double tol, bool closed)
{
if (f.size()==0) return f;
Piecewise<D2<SBasis> > result=f;
unsigned cur = (closed)? 0:1;
unsigned prev = (closed)? f.size()-1:0;
while(cur<f.size()){
Point pt0 = f.segs[prev].at1();
Point pt1 = f.segs[cur ].at0();
if (tol<=0 || L2sq(pt0-pt1)<tol*tol){
pt0 = (pt0+pt1)/2;
for (unsigned dim=0; dim<2; dim++){
SBasis &prev_sb=result.segs[prev][dim];
SBasis &cur_sb =result.segs[cur][dim];
Coord const c=pt0[dim];
if (prev_sb.isZero(0)) {
prev_sb = SBasis(Linear(0.0, c));
} else {
prev_sb[0][1] = c;
}
if (cur_sb.isZero(0)) {
cur_sb = SBasis(Linear(c, 0.0));
} else {
cur_sb[0][0] = c;
}
}
}
prev = cur++;
}
return result;
}
std::vector<Geom::Piecewise<Geom::D2<Geom::SBasis> > >
split_at_discontinuities (Geom::Piecewise<Geom::D2<Geom::SBasis> > const & pwsbin, double tol)
{
using namespace Geom;
std::vector<Piecewise<D2<SBasis> > > ret;
unsigned piece_start = 0;
for (unsigned i=0; i<pwsbin.segs.size(); i++){
if (i==(pwsbin.segs.size()-1) || L2(pwsbin.segs[i].at1()- pwsbin.segs[i+1].at0()) > tol){
Piecewise<D2<SBasis> > piece;
piece.cuts.push_back(pwsbin.cuts[piece_start]);
for (unsigned j = piece_start; j<i+1; j++){
piece.segs.push_back(pwsbin.segs[j]);
piece.cuts.push_back(pwsbin.cuts[j+1]);
}
ret.push_back(piece);
piece_start = i+1;
}
}
return ret;
}
Point unitTangentAt(D2<SBasis> const & a, Coord t, unsigned n)
{
std::vector<Point> derivs = a.valueAndDerivatives(t, n);
for (unsigned deriv_n = 1; deriv_n < derivs.size(); deriv_n++) {
Coord length = derivs[deriv_n].length();
if ( ! are_near(length, 0) ) {
// length of derivative is non-zero, so return unit vector
return derivs[deriv_n] / length;
}
}
return Point (0,0);
}
static void set_first_point(Piecewise<D2<SBasis> > &f, Point const &a){
if ( f.empty() ){
f.concat(Piecewise<D2<SBasis> >(D2<SBasis>(SBasis(Linear(a[X])), SBasis(Linear(a[Y])))));
return;
}
for (unsigned dim=0; dim<2; dim++){
f.segs.front()[dim][0][0] = a[dim];
}
}
static void set_last_point(Piecewise<D2<SBasis> > &f, Point const &a){
if ( f.empty() ){
f.concat(Piecewise<D2<SBasis> >(D2<SBasis>(SBasis(Linear(a[X])), SBasis(Linear(a[Y])))));
return;
}
for (unsigned dim=0; dim<2; dim++){
f.segs.back()[dim][0][1] = a[dim];
}
}
std::vector<Piecewise<D2<SBasis> > > fuse_nearby_ends(std::vector<Piecewise<D2<SBasis> > > const &f, double tol){
if ( f.empty()) return f;
std::vector<Piecewise<D2<SBasis> > > result;
std::vector<std::vector<unsigned> > pre_result;
for (unsigned i=0; i<f.size(); i++){
bool inserted = false;
Point a = f[i].firstValue();
Point b = f[i].lastValue();
for (unsigned j=0; j<pre_result.size(); j++){
Point aj = f.at(pre_result[j].back()).lastValue();
Point bj = f.at(pre_result[j].front()).firstValue();
if ( L2(a-aj) < tol ) {
pre_result[j].push_back(i);
inserted = true;
break;
}
if ( L2(b-bj) < tol ) {
pre_result[j].insert(pre_result[j].begin(),i);
inserted = true;
break;
}
}
if (!inserted) {
pre_result.push_back(std::vector<unsigned>());
pre_result.back().push_back(i);
}
}
for (unsigned i=0; i<pre_result.size(); i++){
Piecewise<D2<SBasis> > comp;
for (unsigned j=0; j<pre_result[i].size(); j++){
Piecewise<D2<SBasis> > new_comp = f.at(pre_result[i][j]);
if ( j>0 ){
set_first_point( new_comp, comp.segs.back().at1() );
}
comp.concat(new_comp);
}
if ( L2(comp.firstValue()-comp.lastValue()) < tol ){
//TODO: check sizes!!!
set_last_point( comp, comp.segs.front().at0() );
}
result.push_back(comp);
}
return result;
}
/*
* Computes the intersection of two sets given as (ordered) union of intervals.
*/
static std::vector<Interval> intersect( std::vector<Interval> const &a, std::vector<Interval> const &b){
std::vector<Interval> result;
//TODO: use order!
for (unsigned i=0; i < a.size(); i++){
for (unsigned j=0; j < b.size(); j++){
OptInterval c( a[i] );
c &= b[j];
if ( c ) {
result.push_back( *c );
}
}
}
return result;
}
std::vector<Interval> level_set( D2<SBasis> const &f, Rect region){
std::vector<Rect> regions( 1, region );
return level_sets( f, regions ).front();
}
std::vector<Interval> level_set( D2<SBasis> const &f, Point p, double tol){
Rect region(p, p);
region.expandBy( tol );
return level_set( f, region );
}
std::vector<std::vector<Interval> > level_sets( D2<SBasis> const &f, std::vector<Rect> regions){
std::vector<Interval> regsX (regions.size(), Interval() );
std::vector<Interval> regsY (regions.size(), Interval() );
for ( unsigned i=0; i < regions.size(); i++ ){
regsX[i] = regions[i][X];
regsY[i] = regions[i][Y];
}
std::vector<std::vector<Interval> > x_in_regs = level_sets( f[X], regsX );
std::vector<std::vector<Interval> > y_in_regs = level_sets( f[Y], regsY );
std::vector<std::vector<Interval> >result(regions.size(), std::vector<Interval>() );
for (unsigned i=0; i<regions.size(); i++){
result[i] = intersect ( x_in_regs[i], y_in_regs[i] );
}
return result;
}
std::vector<std::vector<Interval> > level_sets( D2<SBasis> const &f, std::vector<Point> pts, double tol){
std::vector<Rect> regions( pts.size(), Rect() );
for (unsigned i=0; i<pts.size(); i++){
regions[i] = Rect( pts[i], pts[i] );
regions[i].expandBy( tol );
}
return level_sets( f, regions );
}
} // namespace Geom
/*
Local Variables:
mode:c++
c-file-style:"stroustrup"
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
indent-tabs-mode:nil
fill-column:99
End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :
| gpl-2.0 |
DotNetSparky/circuitdiagram | CircuitDiagram/ComponentCompiler/Program.cs | 11987 | // Program.cs
//
// Circuit Diagram http://www.circuit-diagram.org/
//
// Copyright (C) 2012 Sam Fisher
//
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NDesk.Options;
using System.Xml;
using System.IO;
using CircuitDiagram.Components;
using CircuitDiagram.IO;
using CircuitDiagram.Components.Description;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;
using System.Text.RegularExpressions;
using CircuitDiagram.IO.Descriptions;
using CircuitDiagram.IO.Descriptions.Xml;
namespace cdcompile
{
class Program
{
static void Main(string[] args)
{
var compileOptions = new CompileOptions();
bool help = false;
var p = new OptionSet() {
{ "i|input=", "Path to input XML component or component folder.", v => compileOptions.Input = v },
{ "o|output=", "Path to write compiled component to.", v => compileOptions.Output = v },
{ "icon=", "Path to PNG icon.", v => compileOptions.IconPaths.Add(v)},
{ "icondir=", "Find icons automatically in the specified directory.", v => compileOptions.DefaultIconPath = v},
{ "sign", "If present, presents a dialog for choosing a certificate for component signing.", v => compileOptions.Sign = v != null },
{ "certificate=", "Thumbprint of certificate to use for signing.", v => compileOptions.CertificateThumbprint = v},
{ "h|?|help", "Display help and options.", v => help = v != null },
};
List<string> extra = p.Parse(args);
if (compileOptions.Input == null || compileOptions.Output == null || help)
{
p.WriteOptionDescriptions(Console.Out);
return;
}
if (File.Exists(compileOptions.Input))
{
// Compile a single component
CompileComponent(compileOptions.Input, compileOptions);
Console.WriteLine("Compiled {0}", Path.GetFileName(compileOptions.Input));
}
else if (Directory.Exists(compileOptions.Input))
{
// Compile a directory of components
Console.WriteLine("Compiling components");
int failed = 0;
string[] inputPaths = Directory.GetFiles(compileOptions.Input, "*.xml");
foreach (string input in inputPaths)
{
if (!CompileComponent(input, compileOptions))
failed++;
}
Console.WriteLine("Compiled {0} components", inputPaths.Length - failed);
}
}
private static bool CompileComponent(string inputPath, CompileOptions compileOptions)
{
List<ComponentDescription> componentDescriptions = new List<ComponentDescription>();
List<BinaryResource> binaryResources = new List<BinaryResource>();
XmlLoader loader = new XmlLoader();
loader.Load(new FileStream(inputPath, FileMode.Open));
if (loader.LoadErrors.Count(e => e.Category == LoadErrorCategory.Error) > 0)
{
foreach (var error in loader.LoadErrors)
Console.WriteLine(error.ToString());
return false;
}
ComponentDescription description = loader.GetDescriptions()[0];
description.ID = "C0";
componentDescriptions.Add(description);
SetIcons(compileOptions, description);
string output = compileOptions.Output;
if (!Path.HasExtension(output))
{
if (!Directory.Exists(output))
Directory.CreateDirectory(output);
output += "\\" + description.ComponentName.ToLowerInvariant() + ".cdcom";
}
FileStream stream = new FileStream(output, FileMode.Create, FileAccess.Write);
X509Certificate2 certificate = SelectCertificate(compileOptions);
CircuitDiagram.IO.BinaryWriter.BinaryWriterSettings settings = new CircuitDiagram.IO.BinaryWriter.BinaryWriterSettings();
settings.Certificate = certificate;
CircuitDiagram.IO.BinaryWriter writer = new CircuitDiagram.IO.BinaryWriter(stream, settings);
writer.Descriptions.AddRange(componentDescriptions);
writer.Resources.AddRange(binaryResources);
writer.Write();
stream.Flush();
return true;
}
private static void SetIcons(CompileOptions compileOptions, ComponentDescription description)
{
if (compileOptions.DefaultIconPath != null)
{
// Set icon from default path
description.Metadata.Icon = SetDefaultIcon(description.ComponentName, "", compileOptions.DefaultIconPath);
}
else
{
// Icon was specified manually
// First icon is default
if (compileOptions.IconPaths.Count > 0)
{
byte[] iconData = File.ReadAllBytes(compileOptions.IconPaths[0]);
description.Metadata.Icon = new MultiResolutionImage();
description.Metadata.Icon.Add(new SingleResolutionImage() { Data = iconData, MimeType = "image/png" });
// Icons with same base name are different resolutions
string baseName = GetIconBaseName(compileOptions.IconPaths[0]);
if (baseName != null)
{
var otherResolutions = compileOptions.IconPaths.Where(ic => ic != compileOptions.IconPaths[0] && GetIconBaseName(ic) == baseName);
foreach (var otherResolution in otherResolutions)
{
iconData = File.ReadAllBytes(otherResolution);
description.Metadata.Icon.Add(new SingleResolutionImage() { Data = iconData, MimeType = "image/png" });
}
}
}
}
// Map remaining icons to configurations
if (compileOptions.DefaultIconPath != null)
{
for (int i = 1; i < description.Metadata.Configurations.Count; i++)
{
var configuration = description.Metadata.Configurations[i];
// Set icon from default path
configuration.Icon = SetDefaultIcon(description.ComponentName, configuration.Name, compileOptions.DefaultIconPath);
}
}
else
{
// Icon was specified manually
for (int i = 1; i < compileOptions.IconPaths.Count && i < description.Metadata.Configurations.Count; i++)
{
var configuration = description.Metadata.Configurations[i];
byte[] iconData = File.ReadAllBytes(compileOptions.IconPaths[i]);
configuration.Icon = new MultiResolutionImage();
configuration.Icon.Add(new SingleResolutionImage() { Data = iconData, MimeType = "image/png" });
}
}
}
private static X509Certificate2 SelectCertificate(CompileOptions compileOptions)
{
X509Certificate2 certificate = null;
if (compileOptions.Sign && compileOptions.CertificateThumbprint == null)
{
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly);
//Put certificates from the store into a collection so user can select one.
X509Certificate2Collection fcollection = (X509Certificate2Collection)store.Certificates;
IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(fcollection, "Select an X509 Certificate",
"Choose a certificate to sign your component with.", X509SelectionFlag.SingleSelection, handle);
certificate = collection[0];
}
else if (compileOptions.Sign)
{
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly);
X509Certificate2Collection fcollection = (X509Certificate2Collection)store.Certificates;
certificate = fcollection.Find(X509FindType.FindByThumbprint, compileOptions.CertificateThumbprint, false)[0];
}
return certificate;
}
private static MultiResolutionImage SetDefaultIcon(string componentName, string configuration, string defaultIconPath)
{
// Construct base name
string baseName = String.Format("{0}", FormatNameForIcon(componentName));
if (!String.IsNullOrEmpty(configuration))
baseName += String.Format("_{0}", FormatNameForIcon(configuration));
// Attempt to set common DPI values: 32, 64
int[] resolutions = new int[] { 32, 64 };
var returnIcon = new MultiResolutionImage();
foreach(int resolution in resolutions)
{
string iconFileName = String.Format("{0}_{1}.png", baseName, resolution);
string iconPath = Path.Combine(defaultIconPath, iconFileName);
if (!File.Exists(iconPath))
continue;
var iconData = File.ReadAllBytes(iconPath);
returnIcon.Add(new SingleResolutionImage() { Data = iconData, MimeType = "image/png" });
}
if (returnIcon.Count > 0)
return returnIcon;
else
return null;
}
private static string FormatNameForIcon(string componentName)
{
componentName = componentName.ToLowerInvariant();
componentName = componentName.Replace(" ", "_");
componentName = Regex.Replace(componentName, @"[\(\)-]", "");
return componentName;
}
private static string GetIconBaseName(string path)
{
string fileName = Path.GetFileNameWithoutExtension(path);
int pos = fileName.LastIndexOf("_");
if (pos > 0)
return fileName.Substring(0, pos);
else
return null;
}
private static int GetIconResolutionFromPath(string path)
{
string fileName = Path.GetFileNameWithoutExtension(path);
int pos = fileName.LastIndexOf("_");
if (pos > 0)
return int.Parse(fileName.Substring(pos + 1));
else
return 0;
}
}
}
| gpl-2.0 |
vinhnghi/entertainment | activity_pkg/com_talent/admin/models/rules/parent.php | 791 | <?php
// No direct access to this file
defined ( '_JEXEC' ) or die ( 'Restricted access' );
class JFormRuleParent extends JFormRule {
protected $regex = '^[\w\W]+$';
public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null) {
if (empty ( $this->regex )) {
throw new UnexpectedValueException ( sprintf ( '%s has invalid regex.', get_class ( $this ) ) );
}
// Add unicode property support if available.
if (JCOMPAT_UNICODE_PROPERTIES) {
$this->modifiers = (strpos ( $this->modifiers, 'u' ) !== false) ? $this->modifiers : $this->modifiers . 'u';
}
// Test the value against the regular expression.
if (preg_match ( chr ( 1 ) . $this->regex . chr ( 1 ) . $this->modifiers, $value )) {
return true;
}
}
} | gpl-2.0 |
andreaiervolino/waterinneu | sites/all/modules/features_banish/features_banish.api.php | 933 | <?php
/**
* @file
* Hooks provided by features_banish.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Alter the banished feature items provided by features_banish_get_banished().
*
* Items are loaded from:
* - module.info files (feature modules only): To use this, change the info item
* from features[something].. to features_banish[something]..
* - features_banish_items variable: You can set the same way you can set all
* system variables: drush vset, variable_set(), or $conf['settings'].
*
* @param $banished_items
* An array whose keys are feature component names and values are an array of
* items to bansish. See a features export as an example.
*/
function hook_features_banish_alter(&$banished_items) {
// Banish the cron_last variable when using strongarm. It should never
// be exported because it's a timestamp when cron ran last and changes.
$banished_items['stongarm'][] = 'cron_last';
}
| gpl-2.0 |
cscenter/hpcourse | csc/2017/3.TBBFlowGraph/ShkviroIA/flow.cpp | 11563 |
#include <iostream>
#include <fstream>
#include <algorithm>
#include <array>
#include <cmath>
#include <tbb/flow_graph.h>
using namespace std;
using namespace tbb::flow;
struct pixel {
uint8_t r;
uint8_t g;
uint8_t b;
};
using image = vector<vector<pixel>>;
image imread(const string& path) {
if (path.compare(path.size() - 4, 4, ".dat") != 0) {
cerr << "Can read only prepared .dat files!" << endl;
throw invalid_argument(path);
}
ifstream file(path, ios::binary | ios::in);
uint32_t h, w, d;
file.read(reinterpret_cast<char*>(&h), 4);
file.read(reinterpret_cast<char*>(&w), 4);
file.read(reinterpret_cast<char*>(&d), 4);
auto data = vector<vector<pixel> >(h);
for (auto& row : data) {
row.resize(w);
}
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
auto pix = array<char, 3>();
file.read(pix.data(), 3);
data[i][j] = pixel{ uint8_t(pix[0]),
uint8_t(pix[1]),
uint8_t(pix[2]) };
}
}
return data;
}
image source_img;
uint32_t sourse_height;
uint32_t sourse_width;
void imwrite(const image& source, const string& path) {
uint32_t h = source.size();
uint32_t w = source[0].size();
uint32_t d = 3;
ofstream file(path, ios::binary);
file.write(reinterpret_cast<char*>(&h), 4);
file.write(reinterpret_cast<char*>(&w), 4);
file.write(reinterpret_cast<char*>(&d), 4);
for (auto& row : source) {
for (auto& pix : row) {
file.write(reinterpret_cast<const char*>(&pix.r), 1);
file.write(reinterpret_cast<const char*>(&pix.g), 1);
file.write(reinterpret_cast<const char*>(&pix.b), 1);
}
}
file.close();
}
struct reader {
image operator()(const string& path) {
return imread(path);
}
};
struct my_rectangle {
tuple<uint32_t, uint32_t> coords;
tuple<uint32_t, uint32_t> sizes;
my_rectangle(tuple<uint32_t, uint32_t> coords, tuple<uint32_t, uint32_t> sizes)
: coords(coords)
, sizes(sizes)
{
}
my_rectangle()
: coords(make_tuple(0, 0))
, sizes(make_tuple(0, 0))
{
}
};
class generator {
public:
generator(uint32_t height, uint32_t width) {
uint32_t h_steps = sourse_height - height;
uint32_t w_steps = sourse_width - width;
for (uint32_t i = 0; i < h_steps + 1; ++i) {
for (uint32_t j = 0; j < w_steps + 1; ++j) {
rectangles.push_back(new my_rectangle(make_tuple(i, j), make_tuple(height, width)));
}
}
}
bool operator()(my_rectangle& rect) {
if (!rectangles.empty()) {
rect = *rectangles.back();
rectangles.pop_back();
return true;
}
return false;
}
private:
vector<my_rectangle*> rectangles;
};
class difference {
public:
difference(const image& to_compare)
: to_compare(to_compare)
{
}
tuple<uint32_t, tuple<uint32_t, uint32_t> > operator()(my_rectangle curr_rect) {
uint32_t diff = 0;
uint32_t curr_height = get<0>(curr_rect.sizes);
uint32_t curr_width = get<1>(curr_rect.sizes);
uint32_t curr_y = get<0>(curr_rect.coords);
uint32_t curr_x = get<1>(curr_rect.coords);
//cout << curr_y << ", " << curr_x << endl;
for (uint32_t i = 0; i < curr_height; ++i) {
for (uint32_t j = 0; j < curr_width; ++j) {
diff += abs(source_img[curr_y + i][curr_x + j].r - to_compare[i][j].r);
diff += abs(source_img[curr_y + i][curr_x + j].g - to_compare[i][j].g);
diff += abs(source_img[curr_y + i][curr_x + j].b - to_compare[i][j].b);
}
}
return make_tuple(diff, curr_rect.coords);
}
private:
image to_compare;
};
class min_difference {
public:
min_difference(tuple<uint32_t, tuple<uint32_t, uint32_t> > &s) : my_min(s) {}
tuple<uint32_t, tuple<uint32_t, uint32_t> > operator()(tuple<uint32_t, tuple<uint32_t, uint32_t> > x) {
if (get<0>(my_min) > get<0>(x)) {
my_min = x;
}
return my_min;
}
private:
tuple<uint32_t, tuple<uint32_t, uint32_t> > &my_min;
};
void write_result(tuple<uint32_t, tuple<uint32_t, uint32_t> > result, const image& to_compare, const string& path) {
cout << "Min difference: " << get<0>(result) << endl;
uint32_t y_coord = get<0>(get<1>(result)), x_coord = get<1>(get<1>(result));
cout << "Coords are: (" << y_coord << ", " << x_coord << ")" << endl;
int h = to_compare.size();
int w = to_compare[0].size();
int d = 3;
auto data = vector<vector<pixel>>(h);
for (auto& row : data) {
row.resize(w);
}
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
data[i][j] = source_img[i + y_coord][j + x_coord];
}
}
imwrite(data, path + "_my_res.dat");
}
void make_graph(const string& path) {
tuple<uint32_t, tuple<uint32_t, uint32_t> > result = make_tuple(UINT32_MAX, make_tuple(0, 0));
image to_compare = imread(path);
uint32_t height = to_compare.size();
uint32_t width = to_compare[0].size();
graph g;
cout << "Create empty graph" << endl;
source_node<my_rectangle> generator_node(g, generator(height, width), false);
buffer_node<my_rectangle> rect_buffer_node(g);
function_node<my_rectangle, tuple<uint32_t, tuple<uint32_t, uint32_t> > >
difference_node(g, unlimited, difference(to_compare));
buffer_node<tuple<uint32_t, tuple<uint32_t, uint32_t> > > diff_buffer(g);
function_node<tuple<uint32_t, tuple<uint32_t, uint32_t> >, tuple<uint32_t, tuple<uint32_t, uint32_t> >>
min_difference_node(g, serial, min_difference(result));
cout << "Create nodes" << endl;
make_edge(generator_node, rect_buffer_node);
make_edge(rect_buffer_node, difference_node);
make_edge(difference_node, diff_buffer);
make_edge(diff_buffer, min_difference_node);
cout << "Create edges" << endl;
generator_node.activate();
g.wait_for_all();
cout << "Write res" << endl;
write_result(result, to_compare, path);
}
int main() {
source_img = imread("C:\\CSC\\Parallel\\hw3\\data\\image.dat");
sourse_height = source_img.size();
sourse_width = source_img[0].size();
cout << "Start for hat" << endl;
make_graph("C:\\CSC\\Parallel\\hw3\\data\\hat.dat");
cout << "Start for chicken" << endl;
make_graph("C:\\CSC\\Parallel\\hw3\\data\\chicken.dat");
cout << "Start for cheer" << endl;
make_graph("C:\\CSC\\Parallel\\hw3\\data\\cheer.dat");
system("pause");
return 0;
}
/*
#include "tbb/flow_graph.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <array>
#include <cmath>
using namespace std;
using namespace tbb::flow;
struct pixel {
uint8_t r;
uint8_t g;
uint8_t b;
};
using image = vector<vector<pixel>>;
image imread(const std::string &path) {
if (path.compare(path.size() - 4, 4, ".dat") != 0) {
cerr << "Can read only prepared .dat files!" << endl;
throw invalid_argument(path);
}
ifstream file(path, ios::binary | ios::in);
std::uint32_t h, w, d;
file.read(reinterpret_cast<char*>(&h), 4);
file.read(reinterpret_cast<char*>(&w), 4);
file.read(reinterpret_cast<char*>(&d), 4);
auto data = vector<vector<pixel>>(h);
for (auto& row : data) {
row.resize(w);
}
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
auto pix = array<char, 3>();
file.read(pix.data(), 3);
data[i][j] = pixel{ uint8_t(pix[0]), uint8_t(pix[1]), uint8_t(pix[2]) };
}
}
return data;
}
void imwrite(const image& source, const string& path) {
int h = source.size();
int w = source[0].size();
int d = 3;
ofstream file(path, ios::binary);
file.write(reinterpret_cast<char*>(&h), 4);
file.write(reinterpret_cast<char*>(&w), 4);
file.write(reinterpret_cast<char*>(&d), 4);
for (auto& row : source) {
for (auto& pix : row) {
file.write(reinterpret_cast<const char*>(&pix.r), 1);
file.write(reinterpret_cast<const char*>(&pix.g), 1);
file.write(reinterpret_cast<const char*>(&pix.b), 1);
}
}
file.close();
}
struct rectangle {
long start_w;
long end_w;
long start_h;
long end_h;
rectangle() {}
rectangle(long start_w, long start_h, long width, long height) {
this->start_w = start_w;
end_w = start_w + width;
this->start_h = start_h;
end_h = start_h + height;
}
rectangle &operator=(const rectangle &other) {
start_w = other.start_w;
end_w = other.end_w;
start_h = other.start_h;
end_h = other.end_h;
return *this;
}
};
image big_image = imread("C:\\CSC\\Parallel\\hw3\\data\\image.dat");
image small_image;
long min_dif = LONG_MAX;
rectangle min_rectangle;
class generate_rectangles {
public:
generate_rectangles() {
long width = small_image.size();
long height = small_image.at(0).size();
std::cout << "Small image: width = " << width << ", height = " << height << std::endl;
vector<rectangle> result;
for (long w = 0; w < big_image.size() - width; ++w) {
for (long h = 0; h < big_image.at(0).size() - height; ++h) {
rectangles.push_back(rectangle(w, h, width, height));
}
}
index = 0;
}
bool operator()(rectangle &result) {
if (index >= rectangles.size()) {
return false;
}
result = rectangles[index];
index++;
return true;
}
private:
std::vector<rectangle> rectangles;
long index;
};
std::tuple<rectangle, long> calculate_difference(rectangle const &rect) {
long difference = 0;
for (long w = rect.start_w; w < rect.end_w; ++w) {
for (long h = rect.start_h; h < rect.end_h; ++h) {
pixel p1 = big_image[w][h];
pixel p2 = small_image[w - rect.start_w][h - rect.start_h];
difference += abs(p1.b - p2.b) + abs(p2.g - p1.g) + abs(p1.r - p2.r);
}
}
return std::make_tuple(rect, difference);
}
void get_minimum_difference(std::tuple<rectangle, long> const &candidate) {
if (std::get<1>(candidate) < min_dif) {
min_dif = std::get<1>(candidate);
min_rectangle = std::get<0>(candidate);
}
std::cout << "IP" << to_string(min_rectangle.start_w) << endl;
}
image convert_to_image(const rectangle &rect) {
long width = rect.end_w - rect.start_w;
long height = rect.end_h - rect.start_h;
std::cout << "Result image: width = " << width << ", height = " << height << std::endl;
image result;
result.resize(width);
for (vector<pixel> &row : result) {
row.resize(height);
}
for (long w = 0; w < width; ++w) {
for (long h = 0; h < height; ++h) {
result[w][h] = big_image[w + rect.start_w][h + rect.start_h];
}
}
return result;
}
void process_image(std::string path) {
std::cout << "Image: '" << path << ".dat'" << std::endl;
small_image.clear();
small_image = imread(path + ".dat");
min_dif = INT_MAX;
graph g;
source_node<rectangle> generateRectangles(g, generate_rectangles(), true);
buffer_node<rectangle> rectanglesBuffer(g);
function_node<rectangle, std::tuple<rectangle, long>> calculateDifference(g, unlimited, calculate_difference);
buffer_node<std::tuple<rectangle, long>> differenceBuffer(g);
function_node<std::tuple<rectangle, long>> getMinimumDifference(g, unlimited, get_minimum_difference);
make_edge(generateRectangles, rectanglesBuffer);
make_edge(rectanglesBuffer, calculateDifference);
make_edge(calculateDifference, differenceBuffer);
make_edge(differenceBuffer, getMinimumDifference);
g.wait_for_all();
std::cout << "Minimum difference: " << min_dif << std::endl;
std::cout << "Height borders: " << min_rectangle.start_w << " " << min_rectangle.end_w << std::endl;
std::cout << "Width borders: " << min_rectangle.start_h << " " << min_rectangle.end_h << std::endl;
imwrite(convert_to_image(min_rectangle), path + "_result.dat");
std::cout << "--------------------------------------" << std::endl;
}
int main() {
std::vector<string> images_to_process;
images_to_process.push_back("C:\\CSC\\Parallel\\hw3\\data\\cheer");
images_to_process.push_back("C:\\CSC\\Parallel\\hw3\\data\\chicken");
images_to_process.push_back("C:\\CSC\\Parallel\\hw3\\data\\hat");
for (auto img : images_to_process) {
process_image(img);
}
system("pause");
return 0;
} */ | gpl-2.0 |
AbuseIO/AbuseIO | resources/lang/en/installer_messages.php | 10600 | <?php
return [
/*
*
* Shared translations.
*
*/
'title' => 'AbuseIO Installer',
'next' => 'Next Step',
'back' => 'Previous',
'finish' => 'Install',
'forms' => [
'errorTitle' => 'The Following errors occurred:',
],
/*
*
* Home page translations.
*
*/
'welcome' => [
'templateTitle' => 'Welcome',
'title' => 'AbuseIO Installer',
'message' => 'Setup Wizard.',
'next' => 'Check Requirements',
],
/*
*
* Requirements page translations.
*
*/
'requirements' => [
'templateTitle' => 'Step 1 | Server Requirements',
'title' => 'Server Requirements',
'next' => 'Check Permissions',
],
/*
*
* Permissions page translations.
*
*/
'permissions' => [
'templateTitle' => 'Step 2 | Permissions',
'title' => 'Permissions',
'next' => 'Configure Environment',
],
/*
*
* Environment page translations.
*
*/
'environment' => [
'menu' => [
'templateTitle' => 'Step 3 | Environment Settings',
'title' => 'Environment Settings',
'desc' => 'Please select how you want to configure the apps <code>.env</code> file.',
'wizard-button' => 'Form Wizard Setup',
'classic-button' => 'Classic Text Editor',
],
'wizard' => [
'templateTitle' => 'Step 3 | Environment Settings | Guided Wizard',
'title' => 'Guided <code>.env</code> Wizard',
'tabs' => [
'environment' => 'Environment',
'database' => 'Database',
'application' => 'Application',
'admin' => 'Administrator',
],
'form' => [
'name_required' => 'An environment name is required.',
'app_name_label' => 'App Name',
'app_name_placeholder' => 'App Name',
'app_environment_label' => 'App Environment',
'app_environment_label_local' => 'Local',
'app_environment_label_developement' => 'Development',
'app_environment_label_qa' => 'Qa',
'app_environment_label_production' => 'Production',
'app_environment_label_other' => 'Other',
'app_environment_placeholder_other' => 'Enter your environment...',
'app_debug_label' => 'App Debug',
'app_debug_label_true' => 'True',
'app_debug_label_false' => 'False',
'app_log_level_label' => 'App Log Level',
'app_log_level_label_debug' => 'debug',
'app_log_level_label_info' => 'info',
'app_log_level_label_notice' => 'notice',
'app_log_level_label_warning' => 'warning',
'app_log_level_label_error' => 'error',
'app_log_level_label_critical' => 'critical',
'app_log_level_label_alert' => 'alert',
'app_log_level_label_emergency' => 'emergency',
'app_url_label' => 'App Url',
'app_url_placeholder' => 'App Url',
'db_connection_failed' => 'Could not connect to the database.',
'db_connection_label' => 'Database Connection',
'db_connection_label_mysql' => 'mysql',
'db_connection_label_sqlite' => 'sqlite',
'db_connection_label_pgsql' => 'pgsql',
'db_connection_label_sqlsrv' => 'sqlsrv',
'db_host_label' => 'Database Host',
'db_host_placeholder' => 'Database Host',
'db_port_label' => 'Database Port',
'db_port_placeholder' => 'Database Port',
'db_name_label' => 'Database Name',
'db_name_placeholder' => 'Database Name',
'db_username_label' => 'Database User Name',
'db_username_placeholder' => 'Database User Name',
'db_password_label' => 'Database Password',
'db_password_placeholder' => 'Database Password',
'admin_email' => 'Administrator e-mail',
'admin_email_default' => 'admin@isp.local',
'admin_password' => 'Administrator Password',
'admin_password_placeholder' => '********',
'admin_password_repeat' => 'Repeat Password',
'app_tabs' => [
'more_info' => 'More Info',
'broadcasting_title' => 'Broadcasting, Caching, Session, & Queue',
'broadcasting_label' => 'Broadcast Driver',
'broadcasting_placeholder' => 'Broadcast Driver',
'cache_label' => 'Cache Driver',
'cache_placeholder' => 'Cache Driver',
'session_label' => 'Session Driver',
'session_placeholder' => 'Session Driver',
'queue_label' => 'Queue Driver',
'queue_placeholder' => 'Queue Driver',
'redis_label' => 'Redis Driver',
'redis_host' => 'Redis Host',
'redis_password' => 'Redis Password',
'redis_port' => 'Redis Port',
'mail_label' => 'Mail',
'mail_driver_label' => 'Mail Driver',
'mail_driver_placeholder' => 'Mail Driver',
'mail_host_label' => 'Mail Host',
'mail_host_placeholder' => 'Mail Host',
'mail_port_label' => 'Mail Port',
'mail_port_placeholder' => 'Mail Port',
'mail_username_label' => 'Mail Username',
'mail_username_placeholder' => 'Mail Username',
'mail_password_label' => 'Mail Password',
'mail_password_placeholder' => 'Mail Password',
'mail_encryption_label' => 'Mail Encryption',
'mail_encryption_placeholder' => 'Mail Encryption',
'pusher_label' => 'Pusher',
'pusher_app_id_label' => 'Pusher App Id',
'pusher_app_id_palceholder' => 'Pusher App Id',
'pusher_app_key_label' => 'Pusher App Key',
'pusher_app_key_palceholder' => 'Pusher App Key',
'pusher_app_secret_label' => 'Pusher App Secret',
'pusher_app_secret_palceholder' => 'Pusher App Secret',
],
'buttons' => [
'setup_database' => 'Setup Database',
'setup_application' => 'Setup Application',
'setup_admin' => 'Setup Administrator',
'install' => 'Install',
],
],
],
'classic' => [
'templateTitle' => 'Step 3 | Environment Settings | Classic Editor',
'title' => 'Classic Environment Editor',
'save' => 'Save .env',
'back' => 'Use Form Wizard',
'install' => 'Save and Install',
],
'success' => 'Your .env file settings have been saved.',
'errors' => 'Unable to save the .env file, Please create it manually.',
],
'install' => 'Install',
/*
*
* Installed Log translations.
*
*/
'installed' => [
'success_log_message' => 'AbuseIO Installer successfully INSTALLED on ',
],
/*
* Migration page translations
*/
'migrate' => [
'title' => 'Migrating',
'templateTitle' => 'Migrating',
'migrating' => 'Migrating...',
'seeding' => 'Seeding the database...',
'adding' => 'Adding admin account...',
'finished' => 'Finished',
],
/*
*
* Final page translations.
*
*/
'final' => [
'title' => 'Installation Finished',
'templateTitle' => 'Installation Finished',
'finished' => 'AbuseIO has been successfully installed.',
'migration' => 'Migration & Seed Console Output:',
'console' => 'AbuseIO Console Output:',
'log' => 'Installation Log Entry:',
'env' => 'Final .env File:',
'exit' => 'Click here to exit',
],
/*
*
* Update specific translations
*
*/
'updater' => [
/*
*
* Shared translations.
*
*/
'title' => 'AbuseIO Updater',
/*
*
* Welcome page translations for update feature.
*
*/
'welcome' => [
'title' => 'Welcome To The Updater',
'message' => 'Welcome to the update wizard.',
],
/*
*
* Welcome page translations for update feature.
*
*/
'overview' => [
'title' => 'Overview',
'message' => 'There is 1 update.|There are :number updates.',
'install_updates' => 'Install Updates',
],
/*
*
* Final page translations.
*
*/
'final' => [
'title' => 'Finished',
'finished' => 'AbuseIO\'s database has been successfully updated.',
'exit' => 'Click here to exit',
],
'log' => [
'success_message' => 'AbuseIO Installer successfully UPDATED on ',
],
],
];
| gpl-2.0 |
kannon92/psi4 | psi4/src/psi4/cclambda/Lamp_write.cc | 8608 | /*
* @BEGIN LICENSE
*
* Psi4: an open-source quantum chemistry software package
*
* Copyright (c) 2007-2016 The Psi4 Developers.
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* 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.
*
* @END LICENSE
*/
/*! \file
\ingroup CCLAMBDA
\brief Enter brief description of file here
*/
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include "psi4/libdpd/dpd.h"
#include "MOInfo.h"
#include "Params.h"
#define EXTERN
#include "globals.h"
namespace psi { namespace cclambda {
struct onestack {
double value;
int i;
int a;
};
struct twostack {
double value;
int i; int j;
int a; int b;
};
void onestack_insert(struct onestack *stack, double value, int i, int a,
int level, int stacklen);
void twostack_insert(struct twostack *stack, double value, int i, int j,
int a, int b, int level, int stacklen);
void amp_write_L1(dpdfile2 *L1, int length, const char *label, std::string out);
void amp_write_L2(dpdbuf4 *L2, int length, const char *label, std::string out);
/* print largest elements in CC_LAMBDA */
void Lamp_write(struct L_Params L_params) {
dpdfile2 L1;
dpdbuf4 L2;
int L_irr;
L_irr = L_params.irrep;
if(params.ref == 0) { /** RHF **/
global_dpd_->file2_init(&L1, PSIF_CC_LAMBDA, L_irr, 0, 1, "LIA");
amp_write_L1(&L1, params.num_amps, "\n\tLargest LIA Amplitudes:\n", "outfile");
global_dpd_->file2_close(&L1);
global_dpd_->buf4_init(&L2, PSIF_CC_LAMBDA, L_irr, 0, 5, 0, 5, 0, "LIjAb");
amp_write_L2(&L2, params.num_amps, "\n\tLargest LIjAb Amplitudes:\n", "outfile");
global_dpd_->buf4_close(&L2);
}
else if(params.ref == 1) { /** ROHF **/
global_dpd_->file2_init(&L1, PSIF_CC_LAMBDA, L_irr, 0, 1, "LIA");
amp_write_L1(&L1, params.num_amps, "\n\tLargest LIA Amplitudes:\n", "outfile");
global_dpd_->file2_close(&L1);
global_dpd_->file2_init(&L1, PSIF_CC_LAMBDA, L_irr, 0, 1, "Lia");
amp_write_L1(&L1, params.num_amps, "\n\tLargest Lia Amplitudes:\n", "outfile");
global_dpd_->file2_close(&L1);
global_dpd_->buf4_init(&L2, PSIF_CC_LAMBDA, L_irr, 2, 7, 2, 7, 0, "LIJAB");
amp_write_L2(&L2, params.num_amps, "\n\tLargest LIJAB Amplitudes:\n", "outfile");
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_LAMBDA, L_irr, 2, 7, 2, 7, 0, "Lijab");
amp_write_L2(&L2, params.num_amps, "\n\tLargest Lijab Amplitudes:\n", "outfile");
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_LAMBDA, L_irr, 0, 5, 0, 5, 0, "LIjAb");
amp_write_L2(&L2, params.num_amps, "\n\tLargest LIjAb Amplitudes:\n", "outfile");
global_dpd_->buf4_close(&L2);
}
else if(params.ref == 2) { /** UHF **/
global_dpd_->file2_init(&L1, PSIF_CC_LAMBDA, L_irr, 0, 1, "LIA");
amp_write_L1(&L1, params.num_amps, "\n\tLargest LIA Amplitudes:\n", "outfile");
global_dpd_->file2_close(&L1);
global_dpd_->file2_init(&L1, PSIF_CC_LAMBDA, L_irr, 2, 3, "Lia");
amp_write_L1(&L1, params.num_amps, "\n\tLargest Lia Amplitudes:\n", "outfile");
global_dpd_->file2_close(&L1);
global_dpd_->buf4_init(&L2, PSIF_CC_LAMBDA, L_irr, 2, 7, 2, 7, 0, "LIJAB");
amp_write_L2(&L2, params.num_amps, "\n\tLargest LIJAB Amplitudes:\n", "outfile");
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_LAMBDA, L_irr, 12, 17, 12, 17, 0, "Lijab");
amp_write_L2(&L2, params.num_amps, "\n\tLargest Lijab Amplitudes:\n", "outfile");
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_LAMBDA, L_irr, 22, 28, 22, 28, 0, "LIjAb");
amp_write_L2(&L2, params.num_amps, "\n\tLargest LIjAb Amplitudes:\n", "outfile");
global_dpd_->buf4_close(&L2);
}
}
void amp_write_L1(dpdfile2 *L1, int length, const char *label, std::string out)
{
int m, h, nirreps, Gia;
int i, I, a, A, numt1;
int num2print=0;
double value;
struct onestack *t1stack;
nirreps = L1->params->nirreps;
Gia = L1->my_irrep;
t1stack = (struct onestack *) malloc(length * sizeof(struct onestack));
for(m=0; m < length; m++) { t1stack[m].value = 0; t1stack[m].i = 0; t1stack[m].a = 0; }
global_dpd_->file2_mat_init(L1);
global_dpd_->file2_mat_rd(L1);
numt1 = 0;
for(h=0; h < nirreps; h++) {
numt1 += L1->params->rowtot[h] * L1->params->coltot[h^Gia];
for(i=0; i < L1->params->rowtot[h]; i++) {
I = L1->params->roworb[h][i];
for(a=0; a < L1->params->coltot[h^Gia]; a++) {
A = L1->params->colorb[h^Gia][a];
value = L1->matrix[h][i][a];
for(m=0; m < length; m++) {
if((fabs(value) - fabs(t1stack[m].value)) > 1e-12) {
onestack_insert(t1stack, value, I, A, m, length);
break;
}
}
}
}
}
global_dpd_->file2_mat_close(L1);
for(m=0; m < ((numt1 < length) ? numt1 : length); m++)
if(fabs(t1stack[m].value) > 1e-8) num2print++;
if(num2print) outfile->Printf( "%s", label);
for(m=0; m < ((numt1 < length) ? numt1 : length); m++)
if(fabs(t1stack[m].value) > 1e-8)
outfile->Printf( "\t %3d %3d %20.10f\n", t1stack[m].i, t1stack[m].a, t1stack[m].value);
free(t1stack);
}
void onestack_insert(struct onestack *stack, double value, int i, int a, int level, int stacklen)
{
int l;
struct onestack temp;
temp = stack[level];
stack[level].value = value;
stack[level].i = i;
stack[level].a = a;
value = temp.value;
i = temp.i;
a = temp.a;
for(l=level; l < stacklen-1; l++) {
temp = stack[l+1];
stack[l+1].value = value;
stack[l+1].i = i;
stack[l+1].a = a;
value = temp.value;
i = temp.i;
a = temp.a;
}
}
void amp_write_L2(dpdbuf4 *L2, int length, const char *label, std::string out)
{
int m, h, nirreps, Gijab, numt2;
int ij, ab, i, j, a, b;
int num2print=0;
double value;
struct twostack *t2stack;
nirreps = L2->params->nirreps;
Gijab = L2->file.my_irrep;
t2stack = (struct twostack *) malloc(length * sizeof(struct twostack));
for(m=0; m < length; m++) {
t2stack[m].value = 0;
t2stack[m].i = 0; t2stack[m].j = 0;
t2stack[m].a = 0; t2stack[m].b = 0;
}
numt2 = 0;
for(h=0; h < nirreps; h++) {
global_dpd_->buf4_mat_irrep_init(L2, h);
global_dpd_->buf4_mat_irrep_rd(L2, h);
numt2 += L2->params->rowtot[h] * L2->params->coltot[h^Gijab];
for(ij=0; ij < L2->params->rowtot[h]; ij++) {
i = L2->params->roworb[h][ij][0];
j = L2->params->roworb[h][ij][1];
for(ab=0; ab < L2->params->coltot[h^Gijab]; ab++) {
a = L2->params->colorb[h^Gijab][ab][0];
b = L2->params->colorb[h^Gijab][ab][1];
value = L2->matrix[h][ij][ab];
for(m=0; m < length; m++) {
if((fabs(value) - fabs(t2stack[m].value)) > 1e-12) {
twostack_insert(t2stack, value, i, j, a, b, m, length);
break;
}
}
}
}
global_dpd_->buf4_mat_irrep_close(L2, h);
}
for(m=0; m < ((numt2 < length) ? numt2 : length); m++)
if(fabs(t2stack[m].value) > 1e-8) num2print++;
if(num2print) outfile->Printf( "%s", label);
for(m=0; m < ((numt2 < length) ? numt2 : length); m++)
if(fabs(t2stack[m].value) > 1e-8)
outfile->Printf( "\t%3d %3d %3d %3d %20.10f\n", t2stack[m].i, t2stack[m].j,
t2stack[m].a, t2stack[m].b, t2stack[m].value);
free(t2stack);
}
void twostack_insert(struct twostack *stack, double value, int i, int j, int a, int b,
int level, int stacklen)
{
int l;
struct twostack temp;
temp = stack[level];
stack[level].value = value;
stack[level].i = i;
stack[level].j = j;
stack[level].a = a;
stack[level].b = b;
value = temp.value;
i = temp.i;
j = temp.j;
a = temp.a;
b = temp.b;
for(l=level; l < stacklen-1; l++) {
temp = stack[l+1];
stack[l+1].value = value;
stack[l+1].i = i;
stack[l+1].j = j;
stack[l+1].a = a;
stack[l+1].b = b;
value = temp.value;
i = temp.i;
j = temp.j;
a = temp.a;
b = temp.b;
}
}
}} // namespace psi::cclambda
| gpl-2.0 |
StephaneDiot/PlatformUIBundle-1 | Tests/js/alloyeditor/plugins/assets/ez-alloyeditor-plugin-embed-tests.js | 23562 | /*
* Copyright (C) eZ Systems AS. All rights reserved.
* For full copyright and license information view LICENSE file distributed with this source code.
*/
/* global CKEDITOR, AlloyEditor */
YUI.add('ez-alloyeditor-plugin-embed-tests', function (Y) {
var definePluginTest, embedWidgetTest, focusTest,
setHrefTest, setWidgetContentTest, setConfigTest, imageTypeTest,
getHrefTest, getConfigTest, initTest, alignMethodsTest,
Assert = Y.Assert, Mock = Y.Mock;
definePluginTest = new Y.Test.Case({
name: "eZ AlloyEditor embed plugin define test",
setUp: function () {
this.editor = {};
this.editor.widgets = new Mock();
},
tearDown: function () {
delete this.editor;
},
"Should define the embed plugin": function () {
var plugin = CKEDITOR.plugins.get('ezembed');
Assert.isObject(
plugin,
"The ezembed should be defined"
);
Assert.areEqual(
plugin.name,
"ezembed",
"The plugin name should be ezembed"
);
},
"Should define the ezembed widget": function () {
var plugin = CKEDITOR.plugins.get('ezembed');
Mock.expect(this.editor.widgets, {
method: 'add',
args: ['ezembed', Mock.Value.Object],
});
plugin.init(this.editor);
Mock.verify(this.editor.widgets);
},
});
embedWidgetTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
},
"Should recognize embed element as a widget": function () {
var container = this.container;
Assert.isTrue(
CKEDITOR.plugins.widget.isDomWidgetElement(
new CKEDITOR.dom.node(container.one('#embed').getDOMNode())
)
);
},
"Should fire editorInteraction on focus": function () {
var container = this.container,
editorInteractionFired = false,
nativeEditor = this.editor.get('nativeEditor'),
widget, embedDOM;
embedDOM = container.one('#embed').getDOMNode();
widget = nativeEditor.widgets.getByElement(
new CKEDITOR.dom.node(embedDOM)
);
nativeEditor.on('editorInteraction', function (evt) {
editorInteractionFired = true;
Assert.areSame(
embedDOM, evt.data.nativeEvent.target,
"The embed dom node should be the event target"
);
Assert.isObject(
evt.data.selectionData,
"selectionData should be an object"
);
Assert.areEqual(
0, Y.Object.size(evt.data.selectionData),
"selectionData should be empty"
);
});
widget.fire('focus');
Assert.isTrue(
editorInteractionFired,
"The editorInteraction event should have been fired"
);
},
});
setHrefTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget setHref test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
},
"Should set the data-href attribute": function () {
var embed = this.container.one('#embed'),
href = 'ezcontent://42',
widget = this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(embed.getDOMNode())
),
ret;
ret = widget.setHref(href);
Assert.areEqual(
href, embed.getData('href'),
"The data-href attribute should have been updated"
);
Assert.areSame(
widget, ret,
"The widget should be returned"
);
},
});
getHrefTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget getHref test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
},
"Should return the href": function () {
var embed = this.container.one('#embed'),
href = 'ezcontent://43',
widget = this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(embed.getDOMNode())
);
widget.setHref(href);
Assert.areEqual(
href, widget.getHref(),
"The href should have been updated"
);
},
});
setWidgetContentTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget setWidgetContent test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.containerContent = this.container.getHTML();
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
this.container.setHTML(this.containerContent);
},
"Should remove and set the text content": function () {
var embed = this.container.one('#embed'),
content = 'Foo Fighters',
widget = this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(embed.getDOMNode())
),
ret;
ret = widget.setWidgetContent(content);
Assert.areEqual(
content, embed.get('text'),
"The text content should have been updated"
);
Assert.areSame(
widget, ret,
"The widget should be returned"
);
},
"Should preserve the `ezelements` and set text content": function () {
var embed = this.container.one('#rich-embed'),
content = 'Foo Fighters',
widget = this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(embed.getDOMNode())
);
widget.setWidgetContent(content);
Assert.areEqual(
content, embed.get('text').replace(embed.one('[data-ezelement="ezvalue"]').getContent(), ''),
"The text content should have been updated"
);
Assert.isNotNull(
embed.one('[data-ezelement]'),
"The ezelement should have been kept"
);
},
"Should preserve the `ezelements` and append the element": function () {
var embed = this.container.one('#rich-embed'),
content = new CKEDITOR.dom.element('span'),
contentId = 'newly-added-content',
widget = this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(embed.getDOMNode())
);
content.setAttribute('id', contentId);
widget.setWidgetContent(content);
Assert.isNotNull(
embed.one('#' + contentId),
"The content should have been added to the widget"
);
Assert.isNotNull(
embed.one('[data-ezelement]'),
"The ezelement should have been kept"
);
Assert.areEqual(
2, embed.get('children').size(),
"The content of the embed should have been updated"
);
},
});
setConfigTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget setConfig test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.containerContent = this.container.getHTML();
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
this.container.setHTML(this.containerContent);
},
_testConfig: function (embedSelector, key, value) {
var embed = this.container.one(embedSelector),
widget = this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(embed.getDOMNode())
),
ret, valueElement, configElement;
ret = widget.setConfig(key, value);
configElement = embed.one('[data-ezelement="ezconfig"]');
Assert.isNotNull(configElement, "The config element should be available in the widget DOM");
valueElement = configElement.one('[data-ezvalue-key="' + key + '"]');
Assert.isNotNull(valueElement, "The value element should be available under the config element");
Assert.areEqual(
value, valueElement.get('text'),
"The text content of the value element should be the config value"
);
Assert.areSame(
widget, ret,
"The widget should be returned"
);
},
"Should set the config value element": function () {
this._testConfig('#rich-embed', 'volume', '23%');
},
"Should update the config element": function () {
this._testConfig('#rich-embed', 'size', 'huge');
},
"Should create the config element": function () {
this._testConfig('#embed', 'volume', '23%');
},
});
getConfigTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget getConfig test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.containerContent = this.container.getHTML();
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
this.container.setHTML(this.containerContent);
},
"Should return the config": function () {
var embed = this.container.one('#rich-embed'),
widget = this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(embed.getDOMNode())
),
key = 'whatever',
value = 'whatever value';
widget.setConfig(key, value);
Assert.areEqual(
value, widget.getConfig(key),
"The new config value should have been returned"
);
},
"Should return undefined for an unknown config": function () {
var embed = this.container.one('#rich-embed'),
widget = this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(embed.getDOMNode())
),
key = 'unknown config';
Assert.isUndefined(
widget.getConfig(key),
"undefined should have been returned"
);
},
});
imageTypeTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget setImageType / isImage test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.containerContent = this.container.getHTML();
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
this.container.setHTML(this.containerContent);
},
_getWidget: function (embedSelector) {
return this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(this.container.one(embedSelector).getDOMNode())
);
},
"Should detect image embed": function () {
var widget = this._getWidget('#image-embed');
Assert.isTrue(
widget.isImage(), "The widget should be detected as an image"
);
},
"Should set the widget as an image": function () {
var widget = this._getWidget('#embed');
Assert.isFalse(
widget.isImage(), "The widget should not be detected as an image"
);
widget.setImageType();
Assert.isTrue(
widget.isImage(), "The widget should be detected as an image"
);
},
});
initTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget init test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.containerContent = this.container.getHTML();
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
this.container.setHTML(this.containerContent);
},
_getWidget: function (embedSelector) {
return this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(this.container.one(embedSelector).getDOMNode())
);
},
"Should set the data-ezalign attribute on the wrapper": function () {
var widget = this._getWidget('#aligned-embed');
Assert.areEqual(
'center', widget.wrapper.data('ezalign'),
"The data-ezalign should have been added"
);
},
"Should not set the data-ezalign attribute on the wrapper": function () {
var widget = this._getWidget('#embed');
Assert.isNull(
widget.wrapper.data('ezalign'),
"The data-ezalign should not have been added"
);
},
"Should empty the widget": function () {
Assert.areEqual(
"", this.container.one('#embed').get('text'),
"The content of the widget should be removed"
);
},
"Should create the config element": function () {
Assert.isNotNull(
this.container.one('#embed').get('[data-ezelement="ezconfig"]'),
"The config element should be initialized"
);
},
});
alignMethodsTest = new Y.Test.Case({
name: "eZ AlloyEditor embed widget align methods test",
"async:init": function () {
var startTest = this.callback();
CKEDITOR.plugins.addExternal('lineutils', '../../../lineutils/');
CKEDITOR.plugins.addExternal('widget', '../../../widget/');
this.container = Y.one('.container');
this.containerContent = this.container.getHTML();
this.editor = AlloyEditor.editable(
this.container.getDOMNode(), {
extraPlugins: AlloyEditor.Core.ATTRS.extraPlugins.value + ',widget,ezembed',
eZ: {
editableRegion: '.editable',
},
}
);
this.editor.get('nativeEditor').on('instanceReady', function () {
startTest();
});
},
destroy: function () {
this.editor.destroy();
this.container.setHTML(this.containerContent);
},
_getWidget: function (embedSelector) {
return this.editor.get('nativeEditor').widgets.getByElement(
new CKEDITOR.dom.node(this.container.one(embedSelector).getDOMNode())
);
},
"isAligned should detect the correct alignment": function () {
var widget = this._getWidget('#aligned-embed');
Assert.isTrue(
widget.isAligned('center'),
"The embed should be seen as embed"
);
Assert.isFalse(
widget.isAligned('right'),
"The embed should be detected as aligned on the right"
);
},
"setAlignment should align the embed": function () {
var widget = this._getWidget('#embed');
widget.setAlignment('right');
Assert.isTrue(
widget.isAligned('right'),
"The widget should be aligned on the right"
);
Assert.areEqual(
'right', widget.element.data('ezalign'),
"The 'data-ezalign' attribute should have been added"
);
},
"setAlignment should handle a previously added alignment": function () {
var widget = this._getWidget('#aligned-embed');
widget.setAlignment('right');
Assert.isFalse(
widget.isAligned('center'),
"The widget should not be aligned on the center"
);
Assert.isTrue(
widget.isAligned('right'),
"The widget should be aligned on the right"
);
Assert.areEqual(
'right', widget.element.data('ezalign'),
"The 'data-ezalign' attribute should have been added"
);
},
"unsetAlignment should unset the alignment": function () {
var widget = this._getWidget('#aligned-embed');
widget.unsetAlignment('right');
Assert.isFalse(
widget.isAligned('right'),
"The widget should not be aligned anymore"
);
Assert.isNull(
widget.wrapper.data('ezalign'),
"The 'data-ezalign' attribute should have been removed from the wrapper"
);
Assert.isNull(
widget.element.data('ezalign'),
"The 'data-ezalign' attribute should have been removed from the element"
);
},
});
Y.Test.Runner.setName("eZ AlloyEditor embed plugin tests");
Y.Test.Runner.add(definePluginTest);
Y.Test.Runner.add(embedWidgetTest);
Y.Test.Runner.add(focusTest);
Y.Test.Runner.add(setHrefTest);
Y.Test.Runner.add(getHrefTest);
Y.Test.Runner.add(setWidgetContentTest);
Y.Test.Runner.add(setConfigTest);
Y.Test.Runner.add(getConfigTest);
Y.Test.Runner.add(imageTypeTest);
Y.Test.Runner.add(initTest);
Y.Test.Runner.add(alignMethodsTest);
}, '', {requires: ['test', 'node-event-simulate', 'ez-alloyeditor-plugin-embed']});
| gpl-2.0 |
joachimwieland/xcsoar-jwieland | src/Screen/OpenGL/Texture.hpp | 3285 | /*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2011 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_SCREEN_OPENGL_TEXTURE_HPP
#define XCSOAR_SCREEN_OPENGL_TEXTURE_HPP
#include "Screen/OpenGL/Features.hpp"
#include "Asset.hpp"
#include <assert.h>
#ifdef HAVE_GLES
#include <GLES/gl.h>
#else
#include <SDL.h>
#include <SDL_opengl.h>
#endif
#ifndef NDEBUG
extern unsigned num_textures;
#endif
/**
* This class represents an OpenGL texture.
*/
class GLTexture {
protected:
GLuint id;
unsigned width, height;
#ifndef HAVE_GLES
/**
* The real dimensions of the texture. This may differ when
* ARB_texture_non_power_of_two is not available.
*/
GLsizei allocated_width, allocated_height;
#endif
public:
#ifdef ANDROID
GLTexture(GLuint _id, unsigned _width, unsigned _height)
:id(_id), width(_width), height(_height) {
#ifndef NDEBUG
++num_textures;
#endif
}
#endif
/**
* Create a texture with undefined content.
*/
GLTexture(unsigned _width, unsigned _height);
#ifndef ANDROID
GLTexture(SDL_Surface *surface) {
init();
load(surface);
}
#endif
~GLTexture() {
glDeleteTextures(1, &id);
#ifndef NDEBUG
assert(num_textures > 0);
--num_textures;
#endif
}
unsigned get_width() const {
return width;
}
unsigned get_height() const {
return height;
}
protected:
void init(bool mag_linear=false) {
#ifndef NDEBUG
++num_textures;
#endif
glGenTextures(1, &id);
bind();
configure(mag_linear);
}
static inline void configure(bool mag_linear=false) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if (is_embedded()) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
} else {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
!is_embedded() || mag_linear ? GL_LINEAR : GL_NEAREST);
}
#ifndef ANDROID
void load(SDL_Surface *surface);
#endif
public:
void bind() {
glBindTexture(GL_TEXTURE_2D, id);
}
void draw(int dest_x, int dest_y,
unsigned dest_width, unsigned dest_height,
int src_x, int src_y,
unsigned src_width, unsigned src_height) const;
void draw(int dest_x, int dest_y) const {
draw(dest_x, dest_y, width, height,
0, 0, width, height);
}
};
#endif
| gpl-2.0 |
espertechinc/nesper | src/NEsper.Common/common/internal/view/groupwin/MergeViewFactoryForge.cs | 2552 | ///////////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2006-2019 Esper Team. All rights reserved. /
// http://esper.codehaus.org /
// ---------------------------------------------------------------------------------- /
// 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. /
///////////////////////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
using com.espertech.esper.common.client;
using com.espertech.esper.common.@internal.bytecodemodel.@base;
using com.espertech.esper.common.@internal.bytecodemodel.model.expression;
using com.espertech.esper.common.@internal.compile.stage3;
using com.espertech.esper.common.@internal.epl.expression.core;
using com.espertech.esper.common.@internal.view.core;
using com.espertech.esper.compat;
using com.espertech.esper.compat.collections;
namespace com.espertech.esper.common.@internal.view.groupwin
{
public class MergeViewFactoryForge : ViewFactoryForge
{
public IList<ExprNode> ViewParameters { get; private set; }
public void SetViewParameters(
IList<ExprNode> parameters,
ViewForgeEnv viewForgeEnv,
int streamNumber)
{
ViewParameters = parameters;
}
public void Attach(
EventType parentEventType,
int streamNumber,
ViewForgeEnv viewForgeEnv)
{
EventType = parentEventType;
}
public CodegenExpression Make(
CodegenMethodScope parent,
CodegenSymbolProvider symbols,
CodegenClassScope classScope)
{
throw new UnsupportedOperationException("not supported for merge forge");
}
public virtual IList<StmtClassForgeableFactory> InitAdditionalForgeables(ViewForgeEnv viewForgeEnv)
{
return EmptyList<StmtClassForgeableFactory>.Instance;
}
public IList<ViewFactoryForge> InnerForges => EmptyList<ViewFactoryForge>.Instance;
public EventType EventType { get; private set; }
public string ViewName => "merge";
public void Accept(ViewForgeVisitor visitor)
{
visitor.Visit(this);
}
}
} // end of namespace | gpl-2.0 |
JMaNGOS/JMaNGOS | Tools/src/main/java/org/jmangos/tools/openGL/FontTT.java | 19938 | /*******************************************************************************
* Copyright (C) 2013 JMaNGOS <http://jmangos.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.jmangos.tools.openGL;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.IOException;
import java.util.HashMap;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
/**
* @author Jeremy Adams (elias4444)
*
* This module utilizes the modules Texture and TextureLoader in order
* to load and store
* texture information. The most complicated thing to know about these
* classes is that
* TextureLoader takes the BufferedImage and converts it into a Texture.
* If an image is not
* "power of 2" Textureloader makes it a power of 2 and sets the texture
* coordinates
* appropriately.
*
*/
public class FontTT {
private Texture[] charactersp, characterso;
private final HashMap<String, IntObject> charlistp = new HashMap<String, IntObject>();
private final HashMap<String, IntObject> charlisto = new HashMap<String, IntObject>();
private final TextureLoader textureloader;
private final int kerneling;
private int fontsize = 32;
private final Font font;
/*
* Need a special class to hold character information in the hasmaps
*/
private class IntObject {
public int charnum;
IntObject(final int charnumpass) {
this.charnum = charnumpass;
}
}
/*
* Pass in the preloaded truetype font, the resolution at which you wish the
* initial texture to
* be rendered at, and any extra kerneling you want inbetween characters
*/
public FontTT(final Font font, final int fontresolution, final int extrakerneling) {
this.textureloader = new TextureLoader();
this.kerneling = extrakerneling;
this.font = font;
this.fontsize = fontresolution;
createPlainSet();
createOutlineSet();
}
/*
* Create a standard Java2D bufferedimage to later be transferred into a
* texture
*/
private BufferedImage getFontImage(final char ch) {
Font tempfont;
tempfont = this.font.deriveFont((float) this.fontsize);
// Create a temporary image to extract font size
final BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
// // Add AntiAliasing /////
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// /////////////////////////
g.setFont(tempfont);
final FontMetrics fm = g.getFontMetrics();
int charwidth = fm.charWidth(ch);
if (charwidth <= 0) {
charwidth = 1;
}
int charheight = fm.getHeight();
if (charheight <= 0) {
charheight = this.fontsize;
}
// Create another image for texture creation
BufferedImage fontImage;
fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB);
final Graphics2D gt = (Graphics2D) fontImage.getGraphics();
// // Add AntiAliasing /////
gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// /////////////////////////
gt.setFont(tempfont);
// // Uncomment these to fill in the texture with a background color
// // (used for debugging)
// gt.setColor(Color.RED);
// gt.fillRect(0, 0, charwidth, fontsize);
gt.setColor(Color.WHITE);
final int charx = 0;
final int chary = 0;
gt.drawString(String.valueOf(ch), (charx), (chary) + fm.getAscent());
return fontImage;
}
/*
* Create a standard Java2D bufferedimage for the font outline to later be
* converted into a
* texture
*/
private BufferedImage getOutlineFontImage(final char ch) {
Font tempfont;
tempfont = this.font.deriveFont((float) this.fontsize);
// Create a temporary image to extract font size
final BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
// // Add AntiAliasing /////
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// /////////////////////////
g.setFont(tempfont);
final FontMetrics fm = g.getFontMetrics();
int charwidth = fm.charWidth(ch);
if (charwidth <= 0) {
charwidth = 1;
}
int charheight = fm.getHeight();
if (charheight <= 0) {
charheight = this.fontsize;
}
// Create another image for texture creation
final int ot = (int) (this.fontsize / 24f);
BufferedImage fontImage;
fontImage =
new BufferedImage(charwidth + (4 * ot), charheight + (4 * ot),
BufferedImage.TYPE_INT_ARGB);
final Graphics2D gt = (Graphics2D) fontImage.getGraphics();
// // Add AntiAliasing /////
gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// /////////////////////////
gt.setFont(tempfont);
// // Uncomment these to fill in the texture with a background color
// // (used for debugging)
// gt.setColor(Color.RED);
// gt.fillRect(0, 0, charwidth, fontsize);
// // Create Outline by painting the character in multiple positions and
// blurring it
gt.setColor(Color.WHITE);
final int charx = -fm.getLeading() + (2 * ot);
final int chary = 2 * ot;
gt.drawString(String.valueOf(ch), (charx) + ot, (chary) + fm.getAscent());
gt.drawString(String.valueOf(ch), (charx) - ot, (chary) + fm.getAscent());
gt.drawString(String.valueOf(ch), (charx), (chary) + ot + fm.getAscent());
gt.drawString(String.valueOf(ch), (charx), ((chary) - ot) + fm.getAscent());
gt.drawString(String.valueOf(ch), (charx) + ot, (chary) + ot + fm.getAscent());
gt.drawString(String.valueOf(ch), (charx) + ot, ((chary) - ot) + fm.getAscent());
gt.drawString(String.valueOf(ch), (charx) - ot, (chary) + ot + fm.getAscent());
gt.drawString(String.valueOf(ch), (charx) - ot, ((chary) - ot) + fm.getAscent());
final float ninth = 1.0f / 9.0f;
final float[] blurKernel =
{ ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth };
final BufferedImageOp blur = new ConvolveOp(new Kernel(3, 3, blurKernel));
final BufferedImage returnimage = blur.filter(fontImage, null);
return returnimage;
}
/*
* Create and store the plain (non-outlined) set of the given fonts
*/
private void createPlainSet() {
this.charactersp = new Texture[256];
try {
for (int i = 0; i < 256; i++) {
final char ch = (char) i;
BufferedImage fontImage = getFontImage(ch);
final String temptexname = "Char." + i;
this.charactersp[i] = this.textureloader.getTexture(temptexname, fontImage);
this.charlistp.put(String.valueOf(ch), new IntObject(i));
fontImage = null;
}
} catch (final IOException e) {
System.out.println("FAILED!!!");
e.printStackTrace();
}
}
/*
* creates and stores the outlined set for the font
*/
private void createOutlineSet() {
this.characterso = new Texture[256];
try {
for (int i = 0; i < 256; i++) {
final char ch = (char) i;
BufferedImage fontImage = getOutlineFontImage(ch);
final String temptexname = "Charo." + i;
this.characterso[i] = this.textureloader.getTexture(temptexname, fontImage);
this.charlisto.put(String.valueOf(ch), new IntObject(i));
fontImage = null;
}
} catch (final IOException e) {
System.out.println("FAILED!!!");
e.printStackTrace();
}
}
/*
* Draws the given characters to the screen size = size of the font (does
* not change resolution)
* x,y,z = position to draw at color = color of font to draw rotx, roty,
* rotz = how much to
* rotate the font on each axis centered = center the font at the given
* location, or left
* justify
*/
public void drawText(final String whatchars, final float size, final float x, final float y,
final float z, final Color color, final float rotxpass, final float rotypass,
final float rotzpass, final boolean centered) {
final float fontsizeratio = size / this.fontsize;
final int tempkerneling = this.kerneling;
int k = 0;
final float realwidth = getWidth(whatchars, size, false);
GL11.glPushMatrix();
final boolean islightingon = GL11.glIsEnabled(GL11.GL_LIGHTING);
if (islightingon) {
GL11.glDisable(GL11.GL_LIGHTING);
}
GL11.glTranslatef(x, y, z);
GL11.glRotatef(rotxpass, 1, 0, 0);
GL11.glRotatef(rotypass, 0, 1, 0);
GL11.glRotatef(rotzpass, 0, 0, 1);
float totalwidth = 0;
if (centered) {
totalwidth = -realwidth / 2f;
}
for (int i = 0; i < whatchars.length(); i++) {
final String tempstr = whatchars.substring(i, i + 1);
k = ((this.charlistp.get(tempstr))).charnum;
drawtexture(this.charactersp[k], fontsizeratio, totalwidth, 0, color, rotxpass,
rotypass, rotzpass);
totalwidth += ((this.charactersp[k].getImageWidth() * fontsizeratio) + tempkerneling);
}
if (islightingon) {
GL11.glEnable(GL11.GL_LIGHTING);
}
GL11.glPopMatrix();
}
/*
* Draws the given characters to the screen with a drop shadow size = size
* of the font (does not
* change resolution) x,y,z = position to draw at color = color of font to
* draw shadowcolor =
* color of the drop shadow rotx, roty, rotz = how much to rotate the font
* on each axis centered
* = center the font at the given location, or left justify
*/
public void drawText(final String whatchars, final float size, final float x, final float y,
final float z, final Color color, final Color shadowcolor, final float rotxpass,
final float rotypass, final float rotzpass, final boolean centered) {
drawText(whatchars, size, x + 1f, y - 1f, z, shadowcolor, rotxpass, rotypass, rotzpass,
centered);
drawText(whatchars, size, x, y, z, color, rotxpass, rotypass, rotzpass, centered);
}
/*
* Draws the given characters to the screen size = size of the font (does
* not change resolution)
* x,y,z = position to draw at color = color of font to draw outlinecolor =
* color of the font's
* outline rotx, roty, rotz = how much to rotate the font on each axis
* centered = center the
* font at the given location, or left justify
*/
public void drawOutlinedText(final String whatchars, final float size, final float x,
final float y, final float z, final Color color, final Color outlinecolor,
final float rotxpass, final float rotypass, final float rotzpass, final boolean centered) {
final float fontsizeratio = size / this.fontsize;
final float tempkerneling = this.kerneling;
int k = 0;
int ko = 0;
final float realwidth = getWidth(whatchars, size, true);
GL11.glPushMatrix();
final boolean islightingon = GL11.glIsEnabled(GL11.GL_LIGHTING);
if (islightingon) {
GL11.glDisable(GL11.GL_LIGHTING);
}
GL11.glTranslatef(x, y, z);
GL11.glRotatef(rotxpass, 1, 0, 0);
GL11.glRotatef(rotypass, 0, 1, 0);
GL11.glRotatef(rotzpass, 0, 0, 1);
float xoffset, yoffset;
float totalwidth = 0;
if (centered) {
totalwidth = -realwidth / 2f;
}
for (int i = 0; i < whatchars.length(); i++) {
final String tempstr = whatchars.substring(i, i + 1);
ko = ((this.charlisto.get(tempstr))).charnum;
drawtexture(this.characterso[ko], fontsizeratio, totalwidth, 0, outlinecolor, rotxpass,
rotypass, rotzpass);
k = ((this.charlistp.get(tempstr))).charnum;
xoffset =
((this.characterso[k].getImageWidth() - this.charactersp[k].getImageWidth()) * fontsizeratio) / 2f;
yoffset =
((this.characterso[k].getImageHeight() - this.charactersp[k].getImageHeight()) * fontsizeratio) / 2f;
drawtexture(this.charactersp[k], fontsizeratio, totalwidth + xoffset, yoffset, color,
rotxpass, rotypass, rotzpass);
totalwidth += ((this.characterso[k].getImageWidth() * fontsizeratio) + tempkerneling);
}
if (islightingon) {
GL11.glEnable(GL11.GL_LIGHTING);
}
GL11.glPopMatrix();
}
/*
* Draw the actual quad with character texture
*/
private void drawtexture(final Texture texture, final float ratio, final float x,
final float y, final Color color, final float rotx, final float roty, final float rotz) {
// Get the appropriate measurements from the texture itself
final float imgwidth = texture.getImageWidth() * ratio;
final float imgheight = -texture.getImageHeight() * ratio;
final float texwidth = texture.getWidth();
final float texheight = texture.getHeight();
// Bind the texture
texture.bind();
// translate to the right location
GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
// draw a quad with to place the character onto
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0 + x, 0 - y);
GL11.glTexCoord2f(0, texheight);
GL11.glVertex2f(0 + x, imgheight - y);
GL11.glTexCoord2f(texwidth, texheight);
GL11.glVertex2f(imgwidth + x, imgheight - y);
GL11.glTexCoord2f(texwidth, 0);
GL11.glVertex2f(imgwidth + x, 0 - y);
}
GL11.glEnd();
}
/*
* Returns the width in pixels of the given string, size, outlined or not
* used for determining
* how to position the string, either for the user or for this object
*/
public float getWidth(final String whatchars, final float size, final boolean outlined) {
final float fontsizeratio = size / this.fontsize;
final float tempkerneling = (this.kerneling * fontsizeratio);
float totalwidth = 0;
int k = 0;
for (int i = 0; i < whatchars.length(); i++) {
final String tempstr = whatchars.substring(i, i + 1);
if (outlined) {
k = ((this.charlisto.get(tempstr))).charnum;
totalwidth += (this.characterso[k].getImageWidth() * fontsizeratio) + tempkerneling;
} else {
k = ((this.charlistp.get(tempstr))).charnum;
totalwidth += (this.charactersp[k].getImageWidth() * fontsizeratio) + tempkerneling;
}
}
return totalwidth;
}
/*
* For convenience of checking user input keys Can be taken out if you're
* not going to use it
*/
public boolean keyrangevalid(final int currentKey) {
boolean retvalue = false;
if ((currentKey == Keyboard.KEY_A) ||
(currentKey == Keyboard.KEY_B) ||
(currentKey == Keyboard.KEY_C) ||
(currentKey == Keyboard.KEY_D) ||
(currentKey == Keyboard.KEY_E) ||
(currentKey == Keyboard.KEY_F) ||
(currentKey == Keyboard.KEY_G) ||
(currentKey == Keyboard.KEY_H) ||
(currentKey == Keyboard.KEY_I) ||
(currentKey == Keyboard.KEY_J) ||
(currentKey == Keyboard.KEY_K) ||
(currentKey == Keyboard.KEY_L) ||
(currentKey == Keyboard.KEY_M) ||
(currentKey == Keyboard.KEY_N) ||
(currentKey == Keyboard.KEY_O) ||
(currentKey == Keyboard.KEY_P) ||
(currentKey == Keyboard.KEY_Q) ||
(currentKey == Keyboard.KEY_R) ||
(currentKey == Keyboard.KEY_S) ||
(currentKey == Keyboard.KEY_T) ||
(currentKey == Keyboard.KEY_U) ||
(currentKey == Keyboard.KEY_V) ||
(currentKey == Keyboard.KEY_W) ||
(currentKey == Keyboard.KEY_X) ||
(currentKey == Keyboard.KEY_Y) ||
(currentKey == Keyboard.KEY_Z) ||
(currentKey == Keyboard.KEY_0) ||
(currentKey == Keyboard.KEY_1) ||
(currentKey == Keyboard.KEY_2) ||
(currentKey == Keyboard.KEY_3) ||
(currentKey == Keyboard.KEY_4) ||
(currentKey == Keyboard.KEY_5) ||
(currentKey == Keyboard.KEY_6) ||
(currentKey == Keyboard.KEY_7) ||
(currentKey == Keyboard.KEY_8) ||
(currentKey == Keyboard.KEY_9) ||
(currentKey == Keyboard.KEY_PERIOD) ||
(currentKey == Keyboard.KEY_SPACE) ||
(currentKey == Keyboard.KEY_RETURN) ||
(currentKey == Keyboard.KEY_COMMA) ||
(currentKey == Keyboard.KEY_SLASH) ||
(currentKey == Keyboard.KEY_SEMICOLON) ||
(currentKey == Keyboard.KEY_LBRACKET) ||
(currentKey == Keyboard.KEY_RBRACKET) ||
(currentKey == Keyboard.KEY_EQUALS) ||
(currentKey == Keyboard.KEY_MINUS) ||
(currentKey == Keyboard.KEY_APOSTROPHE) ||
(currentKey == Keyboard.KEY_BACK)) {
retvalue = true;
}
return retvalue;
}
public boolean keyrangevalidnumbers(final int currentKey) {
boolean retvalue = false;
if ((currentKey == Keyboard.KEY_0) ||
(currentKey == Keyboard.KEY_1) ||
(currentKey == Keyboard.KEY_2) ||
(currentKey == Keyboard.KEY_3) ||
(currentKey == Keyboard.KEY_4) ||
(currentKey == Keyboard.KEY_5) ||
(currentKey == Keyboard.KEY_6) ||
(currentKey == Keyboard.KEY_7) ||
(currentKey == Keyboard.KEY_8) ||
(currentKey == Keyboard.KEY_9) ||
(currentKey == Keyboard.KEY_PERIOD) ||
(currentKey == Keyboard.KEY_BACK)) {
retvalue = true;
}
return retvalue;
}
}
| gpl-2.0 |
aknox-va/stat-view | domain/internalScrapers/chart7DErrorDetails.js | 421 | //
function chart7DErrorDetails() {
this.scrapeType = "xml";
this.url = function(appId) { return "https://appengine.google.com/dashboard/stats?type=4&window=7&app_id=s~" + appId; };
this.captionText = "7 Day Error Details Chart";
this.process = function (doc, settings, callback) {
callback("<caption>" + this.captionText + "</caption><img src='" + JSON.parse(doc)['chart_url'] + "' />");
}
} | gpl-2.0 |
Open-Wide/owattributebackoffice | attribute_handler/ezobjectrelationattributehandler.php | 440 | <?php
class ezobjectrelationAttributeHandler extends DefaultDatatypeAttributeHandler {
static public function toString( eZContentObjectAttribute $attribute ) {
$result = '';
if($attribute->hasContent()) {
$content = $attribute->content();
if($content instanceof eZContentObject) {
$result = $content->attribute('name');
}
}
return $result;
}
}
?> | gpl-2.0 |
joelbrock/PFC_CORE | fannie/install/sql/op/meminfo.php | 2426 | <?php
/*
Table: meminfo
Columns:
card_no int
last_name varchar
first_name varchar
othlast_name varchar
othfirst_name varchar
street varchar
city varchar
state varchar
zip varchar 10
phone varchar
email_1 varchar
email_2 varchar
ads_OK tinyint
Depends on:
custdata (table)
Use:
This table has contact information for a member,
i.e. it extends custdata on card_no.
See also: memContact.
Usage doesn't have to match mine (AT). The member section of
fannie should be modular enough to support alternate
usage of some fields.
card_no key to custdata and other customer tables.
Straightforward:
- street varchar 255
- city
- state
- zip
- phone
long enough to include extension but don't put more than
one number in it.
The name fields are for two different people.
This approach will work if your co-op allows only
1 or 2 people per membership, but custdata can hold
the same information in a more future-proof way,
i.e. support any number of people per membership,
so better to not use them in favour of custdata.
- email_1 for email
- email_2 for second phone
- ads_OK EL: Perhaps: flag for whether OK to send ads.
Don't know whether implemented for this or any purpose.
--COMMENTS - - - - - - - - - - - - - - - - - - - -
26Jun12 EL Reformatted and rephrased Use section
Added zip to columns list
Added note about ads_OK
epoch AT Original notes by Andy Theuninck.
*/
$CREATE['op.meminfo'] = "
CREATE TABLE `meminfo` (
`card_no` int(11) default NULL,
`last_name` varchar(30) default NULL,
`first_name` varchar(30) default NULL,
`othlast_name` varchar(30) default NULL,
`othfirst_name` varchar(30) default NULL,
`street` varchar(255) default NULL,
`city` varchar(20) default NULL,
`state` varchar(2) default NULL,
`zip` varchar(10) default NULL,
`phone` varchar(30) default NULL,
`email_1` varchar(50) default NULL,
`email_2` varchar(50) default NULL,
`ads_OK` tinyint(1) default '1',
PRIMARY KEY (`card_no`)
)
";
if ($dbms == "MSSQL"){
$CREATE['op.meminfo'] = "
CREATE TABLE meminfo (
card_no int ,
last_name varchar(30) ,
first_name varchar(30) ,
othlast_name varchar(30) ,
othfirst_name varchar(30) ,
street varchar(255) ,
city varchar(20) ,
state varchar(2) ,
zip varchar(10) ,
phone varchar(30) ,
email_1 varchar(50) ,
email_2 varchar(50) ,
ads_OK tinyint
)
";
}
?>
| gpl-2.0 |
muromec/qtopia-ezx | src/server/core_server/qabstractmessagebox.cpp | 10798 | /****************************************************************************
**
** This file is part of the Qtopia Opensource Edition Package.
**
** Copyright (C) 2008 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** versions 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#include "qabstractmessagebox.h"
#include "qtopiaserverapplication.h"
#include <QBasicTimer>
#ifndef Q_WS_X11
# include <qtopia/private/testslaveinterface_p.h>
# define QTOPIA_USE_TEST_SLAVE 1
#endif
// declare QAbstractMessageBoxPrivate
class QAbstractMessageBoxPrivate : public QObject
{
Q_OBJECT
public:
QAbstractMessageBoxPrivate(int time, QAbstractMessageBox::Button but,
QObject *parent)
: QObject(parent), button(but), timeout(time)
{
}
void changeTimeout(int time, QAbstractMessageBox::Button but)
{
endTimeout();
timeout = time;
button = but;
}
void startTimeout()
{
if (timeout > 0)
timer.start(timeout, this);
}
void endTimeout()
{
timer.stop();
}
signals:
void done(int);
protected:
virtual void timerEvent(QTimerEvent *e)
{
if (timer.timerId() == e->timerId()) {
endTimeout();
emit done(button);
}
}
private:
QAbstractMessageBox::Button button;
int timeout;
QBasicTimer timer;
};
/*!
\class QAbstractMessageBox
\brief The QAbstractMessageBox class allows developers to replace the message box portion of the Qtopia server UI.
\ingroup QtopiaServer
\ingroup QtopiaServer::PhoneUI::TTSmartPhone
The abstract message box is part of the
\l {QtopiaServerApplication#qtopia-server-widgets}{server widgets framework}
and represents the portion of the Qtopia server UI that is shown to users
when a message box is needed.
A small tutorial on how to develop new server widgets using one of the
abstract widgets as base can be found in QAbstractServerInterface class
documentation.
The QAbstractMessageBox API is intentionally designed to be similar to the
QMessageBox API to facilitate easily replacing one with the other.
This class is part of the Qtopia server and cannot be used by other Qtopia applications.
*/
/*!
\enum QAbstractMessageBox::Icon
Represents the icon to show in the message box.
\value NoIcon No icon will be shown.
\value Question A question icon will be shown.
\value Information An information icon will be shown.
\value Warning A warning icon will be shown.
\value Critical A critical condition icon will be shown.
*/
/*!
\enum QAbstractMessageBox::Button
Represents a standard button that may be displayed on the message box.
\value NoButton An empty button. This indicates that no button is required.
\value Ok An Ok button.
\value Cancel A cancel button.
\value Yes A yes button.
\value No A no button.
*/
/*!
\fn void QAbstractMessageBox::setButtons(Button button1, Button button2)
Sets the buttons on the message box to the standard buttons \a button1 and
\a button2.
*/
/*!
\fn void QAbstractMessageBox::setButtons(const QString &button0Text, const QString &button1Text, const QString &button2Text, int defaultButtonNumber, int escapeButtonNumber)
Sets the buttons on the message box to custom buttons.
Up to three custom buttons may be specified with \a button0Text,
\a button1Text and \a button2Text which are mapped to keys in a system
specific way. The exec() return value for each of these buttons will be
0, 1 or 2 repspectively.
The \a defaultButtonNumber id is returned from exec if the dialog is simply
"accepted" - usually by pressing the select key. Likewise the
\a escapeButtonNumber is returned if the dialog is dismissed.
*/
/*!
\fn QString QAbstractMessageBox::title() const
Returns the title text of the message box.
*/
/*!
\fn void QAbstractMessageBox::setTitle(const QString &title)
Sets the \a title text of the message box.
*/
/*!
\fn QAbstractMessageBox::Icon QAbstractMessageBox::icon() const
Returns the message box icon.
*/
/*!
\fn void QAbstractMessageBox::setIcon(Icon icon)
Sets the message box \a icon.
*/
/*!
\fn QString QAbstractMessageBox::text() const
Returns the message box text.
*/
/*!
\fn void QAbstractMessageBox::setText(const QString &text)
Sets the message box \a text.
*/
/*!
Constructs a new QAbstractMessageBox instance, with the specified
\a parent and widget \a flags.
*/
QAbstractMessageBox::QAbstractMessageBox(QWidget *parent,
Qt::WFlags flags)
: QDialog(parent, flags), d(0)
{
}
static int QAbstractMessageBox_exec(QWidget *parent, QAbstractMessageBox::Icon icon, const QString &title, const QString &text, QAbstractMessageBox::Button button1, QAbstractMessageBox::Button button2)
{
QAbstractMessageBox *box = qtopiaWidget<QAbstractMessageBox>(parent);
box->setIcon(icon);
box->setTitle(title);
box->setText(text);
box->setButtons(button1, button2);
int rv = QtopiaApplication::execDialog(box);
delete box;
return rv;
}
/*!
Opens a critical message box with the \a title and \a text. The standard
buttons \a button1 and \a button2 are added to the message box.
Returns the identity of the standard button that was activated.
If \a parent is 0, the message box becomes an application-global message box.
If \a parent is a widget, the message box becomes modal relative to
\a parent.
*/
int QAbstractMessageBox::critical(QWidget *parent, const QString &title, const QString &text, Button button1, Button button2)
{
return QAbstractMessageBox_exec(parent, Critical, title, text, button1, button2);
}
/*!
Opens a warning message box with the \a title and \a text. The standard
buttons \a button1 and \a button2 are added to the message box.
Returns the identity of the standard button that was activated.
If \a parent is 0, the message box becomes an application-global message box.
If \a parent is a widget, the message box becomes modal relative to
\a parent.
*/
int QAbstractMessageBox::warning(QWidget *parent, const QString &title, const QString &text, Button button1, Button button2)
{
return QAbstractMessageBox_exec(parent, Warning, title, text, button1, button2);
}
/*!
Opens an informational message box with the \a title and \a text. The
standard buttons \a button1 and \a button2 are added to the message box.
Returns the identity of the standard button that was activated.
If \a parent is 0, the message box becomes an application-global message box.
If \a parent is a widget, the message box becomes modal relative to
\a parent.
*/
int QAbstractMessageBox::information(QWidget *parent, const QString &title, const QString &text, Button button1, Button button2)
{
return QAbstractMessageBox_exec(parent, Information, title, text, button1, button2);
}
/*!
Opens a question message box with the \a title and \a text. The standard
buttons \a button1 and \a button2 are added to the message box.
Returns the identity of the standard button that was activated.
If \a parent is 0, the message box becomes an application-global message box.
If \a parent is a widget, the message box becomes modal relative to
\a parent.
*/
int QAbstractMessageBox::question(QWidget *parent, const QString &title, const QString &text, Button button1, Button button2)
{
return QAbstractMessageBox_exec(parent, Question, title, text, button1, button2);
}
/*!
Returns a new message box instance with the specified \a parent, \a title,
\a text, \a icon and standard buttons \a button0 and \a button1.
*/
QAbstractMessageBox *QAbstractMessageBox::messageBox(QWidget *parent, const QString &title, const QString &text, Icon icon, Button button0, Button button1)
{
QAbstractMessageBox *box = qtopiaWidget<QAbstractMessageBox>(parent);
box->setIcon(icon);
box->setTitle(title);
box->setText(text);
box->setButtons(button0, button1);
return box;
}
/*!
Returns a new custom message box instance with the specified \a parent,
\a title, \a text and \a icon.
Up to three custom buttons may be specified with \a button0Text,
\a button1Text and \a button2Text which are mapped to keys in a system
specific way. The exec() return value for each of these buttons will be
0, 1 or 2 repspectively.
The \a defaultButtonNumber id is returned from exec if the dialog is simply
"accepted" - usually by pressing the select key. Likewise the
\a escapeButtonNumber is returned if the dialog is dismissed.
*/
QAbstractMessageBox *QAbstractMessageBox::messageBoxCustomButton(QWidget *parent, const QString &title, const QString &text, Icon icon,
const QString & button0Text, const QString &button1Text,
const QString &button2Text, int defaultButtonNumber, int escapeButtonNumber)
{
QAbstractMessageBox *box = qtopiaWidget<QAbstractMessageBox>(parent);
box->setIcon(icon);
box->setTitle(title);
box->setText(text);
box->setButtons(button0Text, button1Text, button2Text, defaultButtonNumber, escapeButtonNumber);
return box;
}
/*!
Set an auto timeout value of \a timeoutMs milliseconds. The dialog will be
automatically accepted as though the user pressed the \a button key after
this time.
*/
void QAbstractMessageBox::setTimeout(int timeoutMs, Button button)
{
if(timeoutMs) {
if(d) {
d->changeTimeout(timeoutMs, button);
} else {
d = new QAbstractMessageBoxPrivate(timeoutMs, button, this);
connect( d, SIGNAL(done(int)), this, SLOT(done(int)) );
}
if(!isHidden())
d->startTimeout();
} else {
if(d) {
delete d;
d = 0;
}
}
}
/*! \internal */
void QAbstractMessageBox::hideEvent(QHideEvent *e)
{
if(d)
d->endTimeout();
QDialog::hideEvent(e);
}
/*! \internal */
void QAbstractMessageBox::showEvent(QShowEvent *e)
{
if(d)
d->startTimeout();
#ifdef QTOPIA_USE_TEST_SLAVE
if (QtopiaApplication::instance()->testSlave()) {
QtopiaApplication::instance()->testSlave()->showMessageBox(this, windowTitle(), text());
}
#endif
QDialog::showEvent(e);
}
#include "qabstractmessagebox.moc"
| gpl-2.0 |
uq-eresearch/oztrack | src/main/java/org/oztrack/util/ExcelToCsvConverter.java | 2417 | package org.oztrack.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import au.com.bytecode.opencsv.CSVWriter;
public class ExcelToCsvConverter {
public static void convertExcelToCsv(InputStream in, OutputStream out)
throws IOException, InvalidFormatException, FileNotFoundException, UnsupportedEncodingException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Workbook workbook = WorkbookFactory.create(in);
Sheet sheet = workbook.getSheetAt(0);
CSVWriter csvWriter = null;
try {
csvWriter = new CSVWriter(new OutputStreamWriter(out, "UTF-8"));
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
String[] csvValues = new String[row.getLastCellNum()];
for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
Cell cell = row.getCell(cellNum);
if (cell == null) {
csvValues[cellNum] = "";
}
else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (DateUtil.isCellDateFormatted(cell)) {
csvValues[cellNum] = dateFormat.format(cell.getDateCellValue());
} else {
csvValues[cellNum] = String.valueOf(cell.getNumericCellValue());
}
}
else {
csvValues[cellNum] = cell.getStringCellValue();
}
}
csvWriter.writeNext(csvValues);
}
}
finally {
try {csvWriter.close();} catch (Exception e) {}
}
}
}
| gpl-2.0 |
vrtadmin/clamav-bytecode-compiler | clang/test/SemaTemplate/enum-argument.cpp | 367 | // RUN: %clang_cc1 -fsyntax-only -verify %s
enum Enum { val = 1 };
template <Enum v> struct C {
typedef C<v> Self;
};
template struct C<val>;
template<typename T>
struct get_size {
static const unsigned value = sizeof(T);
};
template<typename T>
struct X0 {
enum {
Val1 = get_size<T>::value,
Val2,
SumOfValues = Val1 + Val2
};
};
X0<int> x0i;
| gpl-2.0 |
38695248/require-gulp | moblie/require/js/kefu.js | 3407 | // 砍价
require.config({
paths: {//模块(modules)的相对目录。
jquery: 'libs/jquery-1.8.3.min',
config: 'comm/config',
base: 'comm/base',
ajax: 'comm/ajax',
up:'comm/uploadUtils',
pjax:'comm/pjax',
mas:'comm/masonry',
share:'comm/shareViewcomm',
swiper:'libs/swiper.min',
jquery_ui:'jqui/jquery-ui.min',
infinitescroll: 'plugin/jquery.infinitescroll.min',
lazyload: 'plugin/jquery.lazyload.min',
jquerypjax:'plugin/jquery.pjax',
baguettebox:'plugin/baguettebox.min',
checkInput:'plugin/checkInput.min',
checkImgExists:'plugin/checkImgExists',
checkboxFn:'plugin/checkboxFn.min',
serializeJson:'plugin/serializeJson.min',
setTagPos:'plugin/setTagPos.min',
stopscroll:'plugin/stopscroll.min',
plus:'plugin/plus.min',
countdown:'plugin/countdown.min',
scrollToEnd:'plugin/scroll.min',
fixedTop:'plugin/fixedTop.min',
hoverclick:'plugin/hoverclick.min',
jcrop:'jcrop/jquery.Jcrop.min'
}
});
require(['jquery','ajax','base','ui/scroll','swiper','ui/textIn','baguettebox'],function($,ajax,base,s){
//显示隐藏表情
$("#expression-toggle").unbind("click").bind("click",function(){
var isv = $("#control").is(":visible");
//alert(isv);
if(isv){
$("#control").hide();
}else{
$("#control").show();
require(['ui/expression'],function(e){
$(document).unbind("click").bind('click',function(e){
var target = $(e.target);
if(target.closest($("#footer_kf")).length == 0){
$("#control").hide();
};
});
});
}
});
base.init();
//回到底部
s.scrollToEnd();
//上传图片按钮
$("#tool-toggle").unbind("click").bind("click",function(){
//上传按钮
require(['up',"ui/message"],function(up,m){
up.uploadInit({
tip:true,
uptitle:'请选择图片上传',
yzlogin:true,
container:'allcontainer',
browse_button:'allpickfiles',
drop_element:'allcontainer',
bucket:'other_sns',
isarray:true,
multi_selection:false,
auto_start:true,
fileNumLimit:1,
callback:function(oimgdata){
//console.log(oimgdata);
m.appendMsg(oimgdata[0].key,1,oimgdata[0].src);
},
bcallback:function(){}
});
});
});
var refreshpage = function(){
function getdatapage(){
var suid = $("#send").attr("data-suid");
var tosuid = $("#send").attr("data-tosuid");
var admin = $("#send").attr("data-admin");
var gdid = $("#send").attr("data-gdid");
ajax.ajaxInit({
url: '/message/getmsglist.html?suid='+suid+'&tosuid='+tosuid+'&admin='+admin+'&gdid='+gdid,
params:{},
callback:function(res){
if(res.status == 1){
var lihtml = '';
$.each(res.data,function(index,o){
lihtml += '<li class="'+o.rorl+' animated fadeInUp item">'+
'<i class="avatar '+o.rorl+'">'+
'<img src="'+o.avatar[2]+'" data-original="'+o.avatar[1]+'" class="avatar_lazy userThumb">'+
'</i>'+
'<div class="msg-content">'+o.msg+'</div>'+
'</li>';
});
$("#masonry").html(lihtml);
require(['baguettebox'],function(){
baguetteBox.run('.baguetteBoxOne');
});
//头像图片懒加载
$("img.avatar_lazy").checkImgExists(function(obj,imgurl){});
//回到底部
s.scrollToEnd();
}
}
});
}
setInterval(getdatapage, 10000);
};
return refreshpage(),baguetteBox.run('.baguetteBoxOne');
});
| gpl-2.0 |
taxjar/taxjar-woocommerce-plugin | tests/specs/tax-calculation/test-cart-tax-applicator.php | 12204 | <?php
namespace TaxJar;
use TaxJar\Tests\Framework\Cart_Builder;
use TaxJar_Coupon_Helper;
use TaxJar_Product_Helper;
use TaxJar_Shipping_Helper;
use WC_Cart_Totals;
use WP_UnitTestCase;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class Test_Cart_Tax_Applicator extends WP_UnitTestCase {
/**
* @dataProvider provide_cart_data
*
* @param $expected_values
* @param $items
* @param $coupons
*
* @throws Tax_Calculation_Exception
*/
public function test_correct_tax_values( $cart_data, $items, $coupons = [], $fees = [] ) {
TaxJar_Shipping_Helper::create_simple_flat_rate( 10 );
$tax_details_stub = $this->createMock( Tax_Details::class );
$tax_details_stub->method( 'has_nexus' )->willReturn( true );
$tax_details_stub->method( 'get_shipping_tax_rate' )->willReturn( $cart_data['shipping_tax_rate'] );
$tax_details_stub->method( 'get_rate' )->willReturn( $cart_data['average_rate'] ?? 0.0 );
$cart_builder = Cart_Builder::a_cart();
$item_stubs = [];
foreach( $items as $item ) {
$product = TaxJar_Product_Helper::create_product( $item['type'], $item['options'] );
$cart_builder = $cart_builder->with_product( $product->get_id(), $item['quantity'] );
$item_stubs[ $product->get_id() ] = $this->create_tax_detail_item_stub( $item['tax_rate'], $item['expected_tax_total'] );
}
foreach( $coupons as $coupon ) {
$cart_builder = $cart_builder->with_coupon( TaxJar_Coupon_Helper::create_coupon( $coupon )->get_code() );
}
foreach( $fees as $fee_id => $fee ) {
$cart_builder = $cart_builder->with_fee( $fee['data'] );
$item_stubs[ $fee_id ] = $this->create_tax_detail_item_stub( $fee['tax_rate'], $fee['expected_tax'] );
}
$cart = $cart_builder->build();
new WC_Cart_Totals( $cart );
$tax_details_stub->method( 'get_line_item' )->willReturnCallback( function( $key ) use ( $item_stubs ) {
if ( isset( $item_stubs[ $key ] ) ) {
return $item_stubs[ $key ];
}
return $item_stubs[ explode( '-', $key )[0] ];
} );
$cart_tax_applicator = new Cart_Tax_Applicator( $cart );
$cart_tax_applicator->apply_tax( $tax_details_stub );
$index = 0;
foreach( $cart->get_cart() as $cart_item ) {
$this->assertEquals( $items[ $index ]['expected_tax_subtotal'], $cart_item['line_subtotal_tax'] );
$this->assertEquals( $items[ $index ]['expected_tax_subtotal'], reset( $cart_item['line_tax_data']['subtotal'] ) );
$this->assertEquals( $items[ $index ]['expected_tax_total'], $cart_item['line_tax'] );
$this->assertEquals( $items[ $index ]['expected_tax_total'], reset( $cart_item['line_tax_data']['total'] ) );
$index++;
}
foreach( $cart->get_fees() as $fee_key => $fee ) {
$this->assertEquals( $fees[ $fee_key ]['expected_tax'], $fee->tax );
$this->assertEquals( $fees[ $fee_key ]['expected_tax'], reset($fee->tax_data ) );
}
$this->assertEquals( $cart_data['tax_subtotal'], $cart->get_subtotal_tax() );
$this->assertEquals( $cart_data['cart_contents_tax'], $cart->get_cart_contents_tax() );
if ( isset( $cart->get_cart_contents_taxes()[0] ) ) {
$this->assertEquals( $cart_data['cart_contents_tax'], $cart->get_cart_contents_taxes()[0] );
}
$this->assertEquals( $cart_data['shipping_tax'], $cart->get_shipping_tax() );
$shipping_taxes = $cart->get_shipping_taxes();
$this->assertEquals( $cart_data['shipping_tax'], reset( $shipping_taxes ) );
$this->assertEquals( $cart_data['fee_tax'], $cart->get_fee_tax() );
if ( isset( $cart->get_fee_taxes()[0] ) ) {
$fee_taxes = $cart->get_fee_taxes();
$this->assertEquals( $cart_data['fee_tax'], reset( $fee_taxes ) );
}
$this->assertEquals( $cart_data['total_tax'], $cart->get_total_tax() );
$this->assertEquals( $cart_data['cart_total'], $cart->get_total( 'amount' ) );
}
public function provide_cart_data(): array {
return [
'cart with a single simple product' => [
[
'tax_subtotal' => 1.0,
'cart_contents_tax' => 1.0,
'shipping_tax' => 0.0,
'shipping_tax_rate' => 0.0,
'fee_tax' => 0.0,
'total_tax' => 1.0,
'cart_total' => 21.00,
],
[
[
'type' => 'simple',
'options' => [],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 1.0,
'expected_tax_total' => 1.0
],
],
],
'cart with a two items with different rates' => [
[
'tax_subtotal' => 3.0,
'cart_contents_tax' => 3.0,
'shipping_tax' => 0.0,
'shipping_tax_rate' => 0.0,
'fee_tax' => 0.0,
'total_tax' => 3.00,
'cart_total' => 33.00,
],
[
[
'type' => 'simple',
'options' => [],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 1.0,
'expected_tax_total' => 1.0
],
[
'type' => 'simple',
'options' => [],
'quantity' => 1,
'tax_rate' => .2,
'expected_tax_subtotal' => 2.0,
'expected_tax_total' => 2.0
],
],
],
'cart with a single simple item and coupon' => [
[
'tax_subtotal' => 1.0,
'cart_contents_tax' => .9,
'shipping_tax' => 0.0,
'shipping_tax_rate' => 0.0,
'fee_tax' => 0.0,
'total_tax' => 0.90,
'cart_total' => 19.90,
],
[
[
'type' => 'simple',
'options' => [],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 1.0,
'expected_tax_total' => .9
],
],
[
[
'amount' => '1'
]
]
],
'cart with a single simple item and shipping rate' => [
[
'tax_subtotal' => 1.0,
'cart_contents_tax' => 1.0,
'shipping_tax' => 1.0,
'shipping_tax_rate' => .1,
'fee_tax' => 0.0,
'total_tax' => 2.00,
'cart_total' => 22.00,
],
[
[
'type' => 'simple',
'options' => [],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 1.0,
'expected_tax_total' => 1.0
],
],
],
'cart with a single simple item and fee' => [
[
'tax_subtotal' => 1.0,
'cart_contents_tax' => 1.0,
'shipping_tax' => 0.0,
'shipping_tax_rate' => 0.0,
'fee_tax' => 2.0,
'total_tax' => 3.00,
'cart_total' => 33.00,
],
[
[
'type' => 'simple',
'options' => [],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 1.0,
'expected_tax_total' => 1.0
],
],
[],
[
'test-fee-1' => [
'data' => [
'name' => 'test fee 1',
'amount' => 10,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .2,
'expected_tax' => 2.0
],
]
],
'cart with a single simple item and two fees with different tax rates' => [
[
'tax_subtotal' => 1.0,
'cart_contents_tax' => 1.0,
'shipping_tax' => 0.0,
'shipping_tax_rate' => 0.0,
'fee_tax' => 3.0,
'total_tax' => 4.00,
'cart_total' => 44.00,
],
[
[
'type' => 'simple',
'options' => [],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 1.0,
'expected_tax_total' => 1.0
],
],
[],
[
'test-fee-1' => [
'data' => [
'name' => 'test fee 1',
'amount' => 10,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .2,
'expected_tax' => 2.0
],
'test-fee-2' => [
'data' => [
'name' => 'test fee 2',
'amount' => 10,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .1,
'expected_tax' => 1.0
]
]
],
'cart with a single item, coupon, fee and taxable shipping' => [
[
'tax_subtotal' => 10.00,
'cart_contents_tax' => 9.0,
'shipping_tax' => 2.00,
'shipping_tax_rate' => 0.2,
'fee_tax' => 3.00,
'total_tax' => 14.00,
'cart_total' => 124.00,
],
[
[
'type' => 'simple',
'options' => [
'price' => 100
],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 10.00,
'expected_tax_total' => 9.00
],
],
[
[
'amount' => '10'
]
],
[
'test-fee-1' => [
'data' => [
'name' => 'test fee 1',
'amount' => 10,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .3,
'expected_tax' => 3.0
],
]
],
'cart with only a fee' => [
[
'tax_subtotal' => 0.00,
'cart_contents_tax' => 0.00,
'shipping_tax' => 0.00,
'shipping_tax_rate' => 0.0,
'fee_tax' => 1.00,
'total_tax' => 1.00,
'cart_total' => 11.00,
],
[],
[],
[
'test-fee-1' => [
'data' => [
'name' => 'test fee 1',
'amount' => 10,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => 0.1,
'expected_tax' => 1.0
],
]
],
'cart with item and negative taxable fee' => [
[
'tax_subtotal' => 10.00,
'cart_contents_tax' => 10.00,
'shipping_tax' => 0.00,
'shipping_tax_rate' => 0.0,
'fee_tax' => -1.00,
'total_tax' => 9.00,
'cart_total' => 109.00,
'average_rate' => 0.1
],
[
[
'type' => 'simple',
'options' => [
'price' => 100
],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 10.00,
'expected_tax_total' => 10.00
],
],
[],
[
'test-fee-1' => [
'data' => [
'name' => 'test fee 1',
'amount' => -10,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .3,
'expected_tax' => -1.0
],
]
],
'cart with item and negative taxable fee that exceeds subtotals' => [
[
'tax_subtotal' => 10.00,
'cart_contents_tax' => 10.00,
'shipping_tax' => 0.00,
'shipping_tax_rate' => 0.0,
'fee_tax' => -10.00,
'total_tax' => 0.00,
'cart_total' => 0.00,
'average_rate' => 0.1
],
[
[
'type' => 'simple',
'options' => [
'price' => 100
],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 10.00,
'expected_tax_total' => 10.00
],
],
[],
[
'test-fee-1' => [
'data' => [
'name' => 'test fee 1',
'amount' => -200,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .3,
'expected_tax' => -10.00
],
]
],
'cart with item and multiple positive and negative fees' => [
[
'tax_subtotal' => 10.00,
'cart_contents_tax' => 10.00,
'shipping_tax' => 0.00,
'shipping_tax_rate' => 0.0,
'fee_tax' => -10.00,
'total_tax' => 0.00,
'cart_total' => 0.00,
'average_rate' => 0.1
],
[
[
'type' => 'simple',
'options' => [
'price' => 100
],
'quantity' => 1,
'tax_rate' => .1,
'expected_tax_subtotal' => 10.00,
'expected_tax_total' => 10.00
],
],
[],
[
'test-fee-1' => [
'data' => [
'name' => 'test fee 1',
'amount' => 10,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .1,
'expected_tax' => 1.00
],
'test-fee-2' => [
'data' => [
'name' => 'test fee 2',
'amount' => -10,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .1,
'expected_tax' => -1.00
],
'test-fee-3' => [
'data' => [
'name' => 'test fee 3',
'amount' => -200,
'taxable' => true,
'tax_class' => ''
],
'tax_rate' => .3,
'expected_tax' => -10.00
],
'test-fee-4' => [
'data' => [
'name' => 'test fee 4',
'amount' => 10,
'taxable' => false,
'tax_class' => ''
],
'tax_rate' => 0.00,
'expected_tax' => 0
],
]
],
];
}
private function create_tax_detail_item_stub( $rate, $tax_collectable ) {
$tax_detail_item_stub = $this->createMock( Tax_Detail_Line_Item::class );
$tax_detail_item_stub->method( 'get_tax_rate' )->willReturn( $rate );
$tax_detail_item_stub->method( 'get_tax_collectable' )->willReturn( floatval( $tax_collectable ) );
return $tax_detail_item_stub;
}
}
| gpl-2.0 |
MariaDB/server | extra/mariabackup/ds_xbstream.cc | 5266 | /******************************************************
Copyright (c) 2011-2013 Percona LLC and/or its affiliates.
Streaming implementation for XtraBackup.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
*******************************************************/
#include <my_global.h>
#include <my_base.h>
#include "common.h"
#include "datasink.h"
#include "xbstream.h"
typedef struct {
xb_wstream_t *xbstream;
ds_file_t *dest_file;
pthread_mutex_t mutex;
} ds_stream_ctxt_t;
typedef struct {
xb_wstream_file_t *xbstream_file;
ds_stream_ctxt_t *stream_ctxt;
} ds_stream_file_t;
/***********************************************************************
General streaming interface */
static ds_ctxt_t *xbstream_init(const char *root);
static ds_file_t *xbstream_open(ds_ctxt_t *ctxt, const char *path,
MY_STAT *mystat);
static int xbstream_write(ds_file_t *file, const uchar *buf, size_t len);
static int xbstream_close(ds_file_t *file);
static void xbstream_deinit(ds_ctxt_t *ctxt);
datasink_t datasink_xbstream = {
&xbstream_init,
&xbstream_open,
&xbstream_write,
&xbstream_close,
&dummy_remove,
&xbstream_deinit
};
static
ssize_t
my_xbstream_write_callback(xb_wstream_file_t *f __attribute__((unused)),
void *userdata, const void *buf, size_t len)
{
ds_stream_ctxt_t *stream_ctxt;
stream_ctxt = (ds_stream_ctxt_t *) userdata;
xb_ad(stream_ctxt != NULL);
xb_ad(stream_ctxt->dest_file != NULL);
if (!ds_write(stream_ctxt->dest_file, buf, len)) {
return len;
}
return -1;
}
static
ds_ctxt_t *
xbstream_init(const char *root __attribute__((unused)))
{
ds_ctxt_t *ctxt;
ds_stream_ctxt_t *stream_ctxt;
xb_wstream_t *xbstream;
ctxt = (ds_ctxt_t *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(ds_ctxt_t) + sizeof(ds_stream_ctxt_t), MYF(MY_FAE));
stream_ctxt = (ds_stream_ctxt_t *)(ctxt + 1);
if (pthread_mutex_init(&stream_ctxt->mutex, NULL)) {
msg("xbstream_init: pthread_mutex_init() failed.");
goto err;
}
xbstream = xb_stream_write_new();
if (xbstream == NULL) {
msg("xb_stream_write_new() failed.");
goto err;
}
stream_ctxt->xbstream = xbstream;
stream_ctxt->dest_file = NULL;
ctxt->ptr = stream_ctxt;
return ctxt;
err:
my_free(ctxt);
return NULL;
}
static
ds_file_t *
xbstream_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat)
{
ds_file_t *file;
ds_stream_file_t *stream_file;
ds_stream_ctxt_t *stream_ctxt;
ds_ctxt_t *dest_ctxt;
xb_wstream_t *xbstream;
xb_wstream_file_t *xbstream_file;
xb_ad(ctxt->pipe_ctxt != NULL);
dest_ctxt = ctxt->pipe_ctxt;
stream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr;
pthread_mutex_lock(&stream_ctxt->mutex);
if (stream_ctxt->dest_file == NULL) {
stream_ctxt->dest_file = ds_open(dest_ctxt, path, mystat);
}
pthread_mutex_unlock(&stream_ctxt->mutex);
if (stream_ctxt->dest_file == NULL) {
return NULL;
}
file = (ds_file_t *) my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(ds_file_t) +
sizeof(ds_stream_file_t),
MYF(MY_FAE));
if (!file) {
msg("my_malloc() failed.");
goto err;
}
stream_file = (ds_stream_file_t *) (file + 1);
xbstream = stream_ctxt->xbstream;
xbstream_file = xb_stream_write_open(xbstream, path, mystat,
stream_ctxt,
my_xbstream_write_callback);
if (xbstream_file == NULL) {
msg("xb_stream_write_open() failed.");
goto err;
}
stream_file->xbstream_file = xbstream_file;
stream_file->stream_ctxt = stream_ctxt;
file->ptr = stream_file;
file->path = stream_ctxt->dest_file->path;
return file;
err:
if (stream_ctxt->dest_file) {
ds_close(stream_ctxt->dest_file);
stream_ctxt->dest_file = NULL;
}
my_free(file);
return NULL;
}
static
int
xbstream_write(ds_file_t *file, const uchar *buf, size_t len)
{
ds_stream_file_t *stream_file;
xb_wstream_file_t *xbstream_file;
stream_file = (ds_stream_file_t *) file->ptr;
xbstream_file = stream_file->xbstream_file;
if (xb_stream_write_data(xbstream_file, buf, len)) {
msg("xb_stream_write_data() failed.");
return 1;
}
return 0;
}
static
int
xbstream_close(ds_file_t *file)
{
ds_stream_file_t *stream_file;
int rc = 0;
stream_file = (ds_stream_file_t *)file->ptr;
rc = xb_stream_write_close(stream_file->xbstream_file);
my_free(file);
return rc;
}
static
void
xbstream_deinit(ds_ctxt_t *ctxt)
{
ds_stream_ctxt_t *stream_ctxt;
stream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr;
if (xb_stream_write_done(stream_ctxt->xbstream)) {
msg("xb_stream_done() failed.");
}
if (stream_ctxt->dest_file) {
ds_close(stream_ctxt->dest_file);
stream_ctxt->dest_file = NULL;
}
pthread_mutex_destroy(&stream_ctxt->mutex);
my_free(ctxt);
}
| gpl-2.0 |
V-Web/vwebadmin | administrator/components/com_layer_slider/models/fields/timecreated.php | 1610 | <?php
/*-------------------------------------------------------------------------
# com_layer_slider - com_layer_slider
# -------------------------------------------------------------------------
# @ author John Gera, George Krupa, Janos Biro, Balint Polgarfi
# @ copyright Copyright (C) 2016 Offlajn.com All Rights Reserved.
# @ license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# @ website http://www.offlajn.com
-------------------------------------------------------------------------*/
?><?php
defined('JPATH_BASE') or die;
jimport('joomla.form.formfield');
/**
* Supports an HTML select list of categories
*/
class JFormFieldTimecreated extends JFormField
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
protected $type = 'timecreated';
/**
* Method to get the field input markup.
*
* @return string The field input markup.
* @since 1.6
*/
protected function getInput() {
// Initialize variables.
$html = array();
$time_created = $this->value;
if (!strtotime($time_created)) {
$time_created = date("Y-m-d H:i:s");
$html[] = '<input type="hidden" name="' . $this->name . '" value="' . $time_created . '" />';
}
$hidden = (boolean) $this->element['hidden'];
if ($hidden == null || !$hidden) {
$jdate = new JDate($time_created);
$pretty_date = $jdate->format(JText::_('DATE_FORMAT_LC2'));
$html[] = "<div>" . $pretty_date . "</div>";
}
return implode($html);
}
} | gpl-2.0 |
UOC/Tandem | src/js/mailing.js | 1836 | // Default strings
mailingStrings = mailingStrings || {
inProgress: 'In progress',
doneWithoutErrors: 'Done without errors.',
doneWithErrors: 'Finished with errors.'
};
$(function () {
var $confirmModal = $("#confirm-modal");
$('.btn-confirm').click(function () {
var $confirmButton = $(this);
var currentAction = $confirmButton.data('action');
var actionDescription = $confirmButton.closest('tr').find('.tool-name').html();
$('input[name="modal-action"]').val(currentAction);
$('#modal-action-name').html(actionDescription);
$confirmModal.modal('show');
});
$("#modal-btn-cancel").on("click", function () {
$("#confirm-modal").modal('hide');
});
function runAction(action, onSuccess, onError) {
var controller;
switch (action) {
case 'send-ranking':
controller = 'api/mailingSendRankingToAllUsers.php';
break;
default:
onError();
break;
}
$.post(controller, function (res) {
if (res.result === 'ok') {
onSuccess();
} else {
onError();
}
}).fail(function () {
onError();
});
}
$("#modal-btn-confirm").on("click", function () {
$("#confirm-modal").modal('hide');
var action = $('input[name="modal-action"]').val();
var $actionBtn = $('a[data-action="' + action + '"]');
var $status = $actionBtn.closest('tr').find('.status');
$status.html(mailingStrings.inProgress);
runAction(action, function () {
$status.html(mailingStrings.doneWithoutErrors);
}, function () {
$status.html(mailingStrings.doneWithErrors);
});
});
});
| gpl-2.0 |
projectestac/jclic | lib/jmf-api/src/javax/media/protocol/DataSource.java | 1196 | /*
* This is just an INCOMPLETE, EMPTY and NO-OPERATIONAL implementation of the
* Java Media Framework library, based on the public API available at:
* http://java.sun.com/products/java-media/jmf/2.1.1/apidocs
*
* The information contained in this file is used only at compile-time to make
* possible the complete build process of JClic without external non-free
* dependencies.
*
* A full operational version of the library is available at:
* http://java.sun.com/products/java-media/jmf
*/
package javax.media.protocol;
import javax.media.*;
import javax.media.Duration;
import java.io.IOException;
import java.net.*;
abstract public class DataSource implements Controls, Duration {
MediaLocator sourceLocator;
public DataSource() {}
public DataSource(MediaLocator source) {}
public void setLocator(MediaLocator source) {}
public MediaLocator getLocator() {return null;}
protected void initCheck() {}
public abstract String getContentType();
public abstract void connect() throws IOException;
public abstract void disconnect();
public abstract void start() throws IOException;
public abstract void stop() throws IOException;
}
| gpl-2.0 |
vishwaAbhinav/OpenNMS | opennms-services/src/test/java/org/opennms/netmgt/poller/mock/MockScheduler.java | 4047 | /*******************************************************************************
* 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.poller.mock;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.opennms.netmgt.scheduler.ReadyRunnable;
import org.opennms.netmgt.scheduler.Scheduler;
public class MockScheduler implements Scheduler {
private MockTimer m_timer;
/*
* TODO: Use it or loose it.
* Commented out because it is not currently used in this monitor
*/
//private long m_currentTime = 0;
private SortedMap<Long, List<ReadyRunnable>> m_scheduleEntries = new TreeMap<Long, List<ReadyRunnable>>();
public MockScheduler() {
this(new MockTimer());
}
public MockScheduler(MockTimer timer) {
m_timer = timer;
}
public void schedule(long interval, ReadyRunnable schedule) {
Long nextTime = new Long(getCurrentTime()+interval);
//MockUtil.println("Scheduled "+schedule+" for "+nextTime);
List<ReadyRunnable> entries = m_scheduleEntries.get(nextTime);
if (entries == null) {
entries = new LinkedList<ReadyRunnable>();
m_scheduleEntries.put(nextTime, entries);
}
entries.add(schedule);
}
public int getEntryCount() {
return m_scheduleEntries.size();
}
public Map<Long, List<ReadyRunnable>> getEntries() {
return m_scheduleEntries;
}
public long getNextTime() {
if (m_scheduleEntries.isEmpty()) {
throw new IllegalStateException("Nothing scheduled");
}
Long nextTime = m_scheduleEntries.firstKey();
return nextTime.longValue();
}
public long next() {
if (m_scheduleEntries.isEmpty()) {
throw new IllegalStateException("Nothing scheduled");
}
Long nextTime = m_scheduleEntries.firstKey();
List<ReadyRunnable> entries = m_scheduleEntries.get(nextTime);
Runnable runnable = entries.get(0);
m_timer.setCurrentTime(nextTime.longValue());
entries.remove(0);
if (entries.isEmpty()) {
m_scheduleEntries.remove(nextTime);
}
runnable.run();
return getCurrentTime();
}
public long tick(int step) {
if (m_scheduleEntries.isEmpty()) {
throw new IllegalStateException("Nothing scheduled");
}
long endTime = getCurrentTime()+step;
while (getNextTime() <= endTime) {
next();
}
m_timer.setCurrentTime(endTime);
return getCurrentTime();
}
public long getCurrentTime() {
return m_timer.getCurrentTime();
}
public void start() {
}
public void stop() {
}
public void pause() {
}
public void resume() {
}
public int getStatus() {
return 0;
}
} | gpl-2.0 |
HHXYOJ/hhxyoj | trunk/web/template/sae/loginpage.php | 1429 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><?php echo $view_title?></title>
<link rel=stylesheet href='./template/<?php echo $OJ_TEMPLATE?>/<?php echo isset($OJ_CSS)?$OJ_CSS:"hoj.css" ?>' type='text/css'>
</head>
<body>
<div id="wrapper">
<?php require_once("oj-header.php");?>
<div id=main class="span8 offset1">
<form action=login.php method=post>
<center>
<table width=480 algin=center>
<tr><td width=240><?php echo $MSG_USER_ID?>:<td width=200><input style="height:24px" name="user_id" type="text" size=20></tr>
<tr><td><?php echo $MSG_PASSWORD?>:<td><input name="password" type="password" size=20 style="height:24px"></tr>
<?php if($OJ_VCODE){?>
<tr><td><?php echo $MSG_VCODE?>:</td>
<td><input name="vcode" size=4 type=text style="height:24px"><img alt="click to change" src=vcode.php onclick="this.src='vcode.php?'+Math.random()">*</td>
</tr>
<?php }?>
<tr><td colspan=3><input name="submit" type="submit" size=10 value="Submit">
<a href="lostpassword.php">Lost Password</a>
</tr>
</table>
<center>
</form>
<div id=foot>
<?php require_once("oj-footer.php");?>
</div><!--end foot-->
</div><!--end main-->
</div><!--end wrapper-->
</body>
</html>
| gpl-2.0 |
edwardoid/tweets_grabber | stream_listener.py | 675 | #!/usr/bin/python2
import tweepy
import twitter
import couchdb
import json
from config import *
from database import DB
class StreamListener(tweepy.streaming.StreamListener):
"""description of class"""
def on_status(self, status):
print ("Adding " + str(status.id))
try:
DB.save(status)
except Exception as e:
print("Exception: " + str(e));
f = open("exception.log", "a");
f.write("Exception: " + str(e) + "\n");
f.close();
except:
print("Unknown error")
return
def on_error(self, status):
print(status)
| gpl-2.0 |
mviitanen/marsmod | mcp/temp/src/minecraft/net/minecraft/item/ItemCoal.java | 1187 | package net.minecraft.item;
import java.util.List;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class ItemCoal extends Item {
private IIcon field_111220_a;
private static final String __OBFID = "CL_00000002";
public ItemCoal() {
this.func_77627_a(true);
this.func_77656_e(0);
this.func_77637_a(CreativeTabs.field_78035_l);
}
public String func_77667_c(ItemStack p_77667_1_) {
return p_77667_1_.func_77960_j() == 1?"item.charcoal":"item.coal";
}
public void func_150895_a(Item p_150895_1_, CreativeTabs p_150895_2_, List p_150895_3_) {
p_150895_3_.add(new ItemStack(p_150895_1_, 1, 0));
p_150895_3_.add(new ItemStack(p_150895_1_, 1, 1));
}
public IIcon func_77617_a(int p_77617_1_) {
return p_77617_1_ == 1?this.field_111220_a:super.func_77617_a(p_77617_1_);
}
public void func_94581_a(IIconRegister p_94581_1_) {
super.func_94581_a(p_94581_1_);
this.field_111220_a = p_94581_1_.func_94245_a("charcoal");
}
}
| gpl-2.0 |
symac/theses | stats_tools/get_theses.php | 3907 | <?php
require_once dirname(__FILE__).'/../include/utils.php';
// ********************************************************************************************** //
// Ce script va aller interroger le serveur OAI de HAL pour récupérer les métadonnées des thèses //
// ********************************************************************************************** //
// Variable à mettre à 1 pour le chargement initial
$get_all = 1;
$datestamp = "";
// On va commencer par regarder la thèse la plus récente dans la base
if ($get_all == 0)
{
$res = SQL("select max(datestamp) as max from ".RECORDS_TABLE);
$row = mysql_fetch_assoc($res);
$datestamp = $row["max"];
print "Import delta : récupération après $datestamp\n";
}
// On va aller appeler la page
$resumptionToken = "-1";
$nb = 1;
while ($resumptionToken != "")
{
$url_oai = "";
if ($resumptionToken == "-1")
{
if ($datestamp != "")
{
$url_oai = "http://tel.archives-ouvertes.fr/oai/oai.php?verb=ListRecords&set=".$code_tampon."&metadataPrefix=oai_tel&from=$datestamp";
}
else
{
$url_oai = "http://tel.archives-ouvertes.fr/oai/oai.php?verb=ListRecords&set=".$code_tampon."&metadataPrefix=oai_tel";
}
}
else
{
$url_oai = "http://tel.archives-ouvertes.fr/oai/oai.php?verb=ListRecords&resumptionToken=".$resumptionToken;
}
// On utilise curl avec un timeout de 60 secondes pour éviter les réponses lentes du serveur
$ch = curl_init($url_oai);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$xml_oai_s = curl_exec($ch);
if (!curl_error($ch))
{
$xml_oai_s = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2_$3", $xml_oai_s);
$xml_oai = simplexml_load_string($xml_oai_s);
foreach ($xml_oai->{'ListRecords'}->{'record'} as $record)
{
$identifier = $record->{'header'}->{'identifier'};
$datestamp = $record->{'header'}->{'datestamp'};
$title = $record->{'metadata'}->{'oai_tel_tel'}->{'tel_titre'};
$tel_authors = $record->{'metadata'}->{'oai_tel_tel'}->{'tel_authors'};
if (sizeof($tel_authors) != 1)
{
print "Trop d'auteurs ???";
exit;
}
else
{
$creator = $tel_authors->{'tel_author'}->{'tel_lastname'}.", ".$tel_authors->{'tel_author'}->{'tel_firstname'};
}
$date_soutenance = $record->{'metadata'}->{'oai_tel_tel'}->{'tel_defencedate'};
$date_en_ligne = $record->{'metadata'}->{'oai_tel_tel'}->{'tel_submission_date'};
// On va stocker la thèse dans la base de données si elle n'existe pas
$res_exists = SQL("select * from ".RECORDS_TABLE." where identifier = '$identifier';");
if (mysql_numrows($res_exists) == 0)
{
// On va stocker la notice
$sql = "insert into ".RECORDS_TABLE." (`identifier`,`title`,`creator`,`date_soutenance`,`date_en_ligne`,`datestamp`,`xml`) values (";
$sql .= "'".addslashes($identifier)."', ";
$sql .= "'".addslashes($title)."', ";
$sql .= "'".addslashes($creator)."', ";
$sql .= "'".addslashes($date_soutenance)."', ";
$sql .= "'".addslashes($date_en_ligne)."', ";
$sql .= "'".addslashes($datestamp)."', ";
$sql .= "'".addslashes($record->asXML())."');";
SQL($sql);
print "#$nb : $identifier [".substr($title, 0, 30)."] :: AJOUT\n";
}
else
{
print "#$nb : $identifier [".substr($title, 0, 30)."] :: DEJA PRESENT\n";
}
$nb++;
}
$resumptionToken = $xml_oai->{'ListRecords'}->{'resumptionToken'};
}
else
{
print "Erreur : ".curl_errno($ch)." [".curl_error($ch)."]\n";
}
}
?>
| gpl-2.0 |
lycoben/veneflights | components/com_jomres/core-minicomponents/j04110savepropertyfeature.class.php | 3641 | <?php
/**
#
* Mini-component core file: Save a property feature (global property features off - else managed in backend)
#
* @author Vince Wooll <sales@jomres.net>
#
* @version Jomres 3
#
* @package Jomres
* @subpackage mini-components
#
* @copyright 2005-2008 Vince Wooll
#
* This is not free software, please do not distribute it. For licencing information, please visit http://www.jomres.net/
* All rights reserved.
*/
// ################################################################
if (!defined('JPATH_BASE'))
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
else
{
if (file_exists(JPATH_BASE .'/includes/defines.php') )
defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );
else
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
}
// ################################################################
/**
#
* Save a property feature (global property features off - else managed in backend)
#
* @package Jomres
#
*/
class j04110savepropertyfeature {
/**
#
* Save a property feature (global property features off - else managed in backend)
#
*/
function j04110savepropertyfeature($componentArgs)
{
// Must be in all minicomponents. Minicomponents with templates that can contain editable text should run $this->template_touch() else just return
global $MiniComponents;
if ($MiniComponents->template_touch)
{
$this->template_touchable=false; return;
}
global $mrConfig,$Itemid;
if (!jomresCheckToken()) {trigger_error ("Invalid token", E_USER_ERROR);}
$defaultProperty=getDefaultProperty();
$propertyFeatureUid = intval(jomresGetParam( $_POST, 'propertyFeatureUid', "" ) );
$hotel_feature_abbv = getEscaped( jomresGetParam( $_POST, 'feature_abbv', "" ) );
$hotel_feature_full_desc = getEscaped( jomresGetParam( $_POST, 'feature_description', "" ) );
if ($propertyFeatureUid=="")
{
$saveMessage=jr_gettext('_JOMRES_COM_MR_VRCT_PROPERTYFEATURES_SAVE_INSERT',_JOMRES_COM_MR_VRCT_PROPERTYFEATURES_SAVE_INSERT,FALSE);
$query="INSERT INTO #__jomres_hotel_features (`hotel_feature_abbv`,`hotel_feature_full_desc`,`property_uid` )VALUES ('$hotel_feature_abbv','$hotel_feature_full_desc','".(int)$defaultProperty."')";
if (doInsertSql($query,jr_gettext('_JOMRES_MR_AUDIT_INSERT_PROPERTY_FEATURE',_JOMRES_MR_AUDIT_INSERT_PROPERTY_FEATURE,FALSE)))
returnToPropertyConfig($saveMessage);
trigger_error ("Unable to insert into hotel features table, mysql db failure", E_USER_ERROR);
}
else
{
$saveMessage=jr_gettext('_JOMRES_COM_MR_VRCT_PROPERTYFEATURES_SAVE_UPDATE',_JOMRES_COM_MR_VRCT_PROPERTYFEATURES_SAVE_UPDATE,FALSE);
$query="UPDATE #__jomres_hotel_features SET `hotel_feature_abbv`='$hotel_feature_abbv',`hotel_feature_full_desc`='$hotel_feature_full_desc' WHERE hotel_features_uid='".(int)$propertyFeatureUid."' AND property_uid = '".(int)$defaultProperty."'";
if (doInsertSql($query,jr_gettext('_JOMRES_MR_AUDIT_UPDATE_PROPERTY_FEATURE',_JOMRES_MR_AUDIT_UPDATE_PROPERTY_FEATURE,FALSE)))
returnToPropertyConfig($saveMessage);
trigger_error ("Unable to update hotel features table, mysql db failure", E_USER_ERROR);
}
}
/**
#
* Must be included in every mini-component
#
* Returns any settings the the mini-component wants to send back to the calling script. In addition to being returned to the calling script they are put into an array in the mcHandler object as eg. $mcHandler->miniComponentData[$ePoint][$eName]
#
*/
// This must be included in every Event/Mini-component
function getRetVals()
{
return null;
}
}
?> | gpl-2.0 |
nedy13/AgilityContest | agility/scripts/results_and_scores.js.php | 20323 | /*
results_and_scores.js.php
Copyright 2013-2016 by Juan Antonio Martinez ( juansgaviota at gmail dot com )
This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.
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.
*/
<?php
require_once(__DIR__."/../server/auth/Config.php");
require_once(__DIR__."/../server/tools.php");
$config =Config::getInstance();
?>
/**
* Funciones relacionadas presentacion de resultados y clasificaciones
*/
/**
* Limpia datos de jueces, trs y trm.
* Se usa en los eventos "init" para borrar informacion previa
*/
function clearParcialRoundInformation() {
$('#parciales-NombreManga').html("<?php _e('No round selected'); ?>");
$('#parciales-Juez1').html("<?php _e('Judge'); ?> 1:");
$('#parciales-Juez2').html("<?php _e('Judge'); ?> 2:");
$('#parciales-Distancia').html("<?php _e('Dist'); ?>:");
$('#parciales-Obstaculos').html("<?php _e('Obst'); ?>:");
$('#parciales-TRS').html("<?php _e('S.C.T.'); ?>:");
$('#parciales-TRM').html("<?php _e('M.C.T.'); ?>:");
$('#parciales-Velocidad').html("<?php _e('Vel'); ?>:");
}
function clearFinalRoundInformation() {
$('#finales-NombreRonda').html("<?php _e('No round selected'); ?>");
$('#finales-Juez1').html("<?php _e('Judge'); ?> 1:");
$('#finales-Juez2').html("<?php _e('Judge'); ?> 2:");
$('#finales-Ronda1').html("<?php _e('Data info for round'); ?> 1:");
$('#finales-Distancia1').html("<?php _e('Dist'); ?>:");
$('#finales-Obstaculos1').html("<?php _e('Obst'); ?>:");
$('#inales-TRS1').html("<?php _e('S.C.T.'); ?>:");
$('#finales-TRM1').html("<?php _e('M.C.T.'); ?>:");
$('#finales-Velocidad1').html("<?php _e('Vel'); ?>:");
$('#finales-Ronda2').html("<?php _e('Data info for round'); ?> 2:");
$('#finales-Distancia2').html("><?php _e('Dist'); ?>:");
$('#finales-Obstaculos2').html("<?php _e('Obst'); ?>:");
$('#finales-TRS2').html("<?php _e('S.C.T.'); ?>:");
$('#finales-TRM2').html("<?php _e('M.C.T.'); ?>:");
$('#finales-Velocidad2').html("<?php _e('Vel'); ?>:");
}
/**
* Muestra clasificacion final de los miembros de un equipo
* @param parent datagrid de datos de equipos
* @param idx indice de la fila del equipo asociado
* @param row contendido de la fila del equipo asociado
*/
function showFinalScoresByTeam(parent,idx,row) {
var mySelf=parent+"-"+parseInt(row.ID);
// retrieve datagrid contents
var maxdogs=getMaxDogsByTeam();
var datos=[];
for(var n=0; n<workingData.individual.length;n++) {
var competitor=workingData.individual[n];
if (competitor['Equipo']!=row.ID) continue;
datos.push(competitor);
if (datos.length>=maxdogs) break; // to speedup parsing data
}
// deploy datagrid
$(mySelf).datagrid({
fit:false,
pagination: false,
rownumbers: false,
fitColumns: true,
singleSelect: true,
width: '100%',
height: 'auto',
remote:false,
idField: 'Perro',
data: datos,
columns: [[
{field:'Perro', hidden:true },
{field:'Equipo', hidden:true },
{field:'Dorsal', width:'4%', align:'left', title:"<?php _e('Dors'); ?>" },
{field:'LogoClub', hidden:true },
{field:'Nombre', width:'8%', align:'center', title:"<?php _e('Name'); ?>", formatter:formatBold},
{field:'Licencia', width:'4%', align:'center', title:"<?php _e('Lic'); ?>." },
{field:'Categoria', width:'4%', align:'center', title:"<?php _e('Cat'); ?>.", formatter:formatCategoria },
{field:'Grado', hidden:true },
{field:'NombreEquipo',hidden:true },
{field:'NombreGuia',width:'13%', align:'right', title:"<?php _e('Handler'); ?>" },
{field:'NombreClub',width:'12%', align:'right', title:"<?php _e('Club'); ?>" },
{field:'F1', width:'2%', align:'center', title:"<?php _e('F/T'); ?>", styler:formatBorder },
{field:'R1', width:'2%', align:'center', title:"R." },
{field:'T1', width:'5%', align:'right', title:"<?php _e('Time'); ?>.", formatter:formatT1 },
{field:'V1', width:'3%', align:'right', title:"<?php _e('Vel'); ?>.", formatter:formatV1 },
{field:'P1', width:'5%', align:'right', title:"<?php _e('Penal'); ?>.", formatter:formatP1},
{field:'C1', width:'3%', align:'center', title:"<?php _e('Cal'); ?>."},
{field:'F2', width:'2%', align:'center', title:"<?php _e('F/T'); ?>", styler:formatBorder },
{field:'R2', width:'2%', align:'center', title:" <?php _e('R'); ?>." },
{field:'T2', width:'5%', align:'right', title:"<?php _e('Time'); ?>.", formatter:formatT2 },
{field:'V2', width:'3%', align:'right', title:"<?php _e('Vel'); ?>.", formatter:formatV2 },
{field:'P2', width:'5%', align:'right', title:"<?php _e('Penal'); ?>.", formatter:formatP2 },
{field:'C2', width:'3%', align:'center', title:"<?php _e('Cal'); ?>." },
{field:'Tiempo', width:'4%', align:'right', title:"<?php _e('Time'); ?>", formatter:formatTF,styler:formatBorder },
{field:'Penalizacion',width:'5%',align:'right', title:"<?php _e('Penaliz'); ?>.",formatter:formatPenalizacionFinal },
{field:'Calificacion',width:'3%',align:'center', title:"<?php _e('Calif'); ?>." },
{field:'Puesto', width:'3%', align:'center', title:"<?php _e('Position'); ?>",formatter:formatBold }
]],
// colorize rows. notice that overrides default css, so need to specify proper values on datagrid.css
rowStyler:myRowStyler,
onResize:function(){
$(parent).datagrid('fixDetailRowHeight',idx);
},
onLoadSuccess:function(data){
setTimeout(function(){ $(parent).datagrid('fixDetailRowHeight',idx); },0);
}
});
$(parent).datagrid('fixDetailRowHeight',idx);
}
/**
* Muestra clasificacion parcial de los miembros de un equipo
* @param parent datagrid de datos de equipos
* @param idx indice de la fila del equipo asociado
* @param row contendido de la fila del equipo asociado
*/
function showPartialScoresByTeam(parent,idx,row) {
var mySelf=parent+"-"+parseInt(row.ID);
// retrieve datagrid contents
var datos=[];
var maxdogs=getMaxDogsByTeam();
for(var n=0; n<workingData.individual.length;n++) {
var competitor=workingData.individual[n];
if (competitor['Equipo']!=row.ID) continue;
datos.push(competitor);
if (datos.lenght>=maxdogs) break; // to speedup parse data
}
// deploy datagrid
$(mySelf).datagrid({
fit:false,
pagination: false,
rownumbers: false,
fitColumns: true,
singleSelect: true,
width: '100%',
height: 'auto',
remote:false,
idField: 'Perro',
data: datos,
columns: [[
{field:'Perro', hidden:true },
{field:'Equipo', hidden:true },
{field:'Dorsal', width:'4%', align:'left', title:"<?php _e('Dorsal'); ?>" },
{field:'LogoClub', hidden:true },
{field:'Nombre', width:'10%', align:'center', title:"<?php _e('Name'); ?>", formatter:formatBold},
{field:'Licencia', width:'6%', align:'center', title:"<?php _e('Lic'); ?>." },
{field:'Categoria', width:'6%', align:'center', title:"<?php _e('Cat'); ?>.", formatter:formatCatGrad },
{field:'Grado', hidden:true },
{field:'NombreEquipo', hidden:true },
{field:'NombreGuia', width:'18%',align:'right', title:"<?php _e('Handler'); ?>" },
{field:'NombreClub', width:'14%',align:'right', title:"<?php _e('Club'); ?>" },
{field:'Faltas', width:'4%', align:'center', title:"<?php _e('F/T'); ?>", formatter:formatFaltasTocados,styler:formatBorder },
{field:'Tocados', hidden:true },
{field:'Rehuses', width:'4%', align:'center', title:"R." },
{field:'Tiempo', width:'6%', align:'right', title:"<?php _e('Time'); ?>.", formatter:formatTiempo },
{field:'Velocidad', width:'6%', align:'right', title:"<?php _e('Vel'); ?>.", formatter:formatVelocidad },
{field:'Penalizacion', width:'6%', align:'right', title:"<?php _e('Penal'); ?>.", formatter:formatPenalizacion,styler:formatBorder},
{field:'Calificacion', width:'10%', align:'center', title:"<?php _e('Calif'); ?>." },
{field:'Puesto', width:'6%', align:'center', title:"<?php _e('Position'); ?>",formatter:formatBold }
]],
// colorize rows. notice that overrides default css, so need to specify proper values on datagrid.css
rowStyler:myRowStyler,
onResize:function(){
$(parent).datagrid('fixDetailRowHeight',idx);
},
onLoadSuccess:function(data){
setTimeout(function(){ $(parent).datagrid('fixDetailRowHeight',idx); },0);
}
});
$(parent).datagrid('fixDetailRowHeight',idx);
}
/**
* Actualizacion de resultados parciales en consola
* Actualiza los datos de TRS y TRM de la fila especificada
* Si se le indica, rellena tambien el datagrid re resultados parciales
* @param {int} val 0:L 1:M 2:S 3:T
* @param {boolean} fill true to fill resultados datagrid; else false
*/
function consoleReloadParcial(val,fill) {
var mode=getMangaMode(workingData.datosPrueba.RSCE,workingData.datosManga.Recorrido,parseInt(val));
if (mode==-1) {
$.messager.alert('<?php _e('Error'); ?>','<?php _e('Internal error: invalid Federation/Course/Category combination'); ?>','error');
return;
}
workingData.teamCounter=1; // reset team's puesto counter
// reload resultados
// en lugar de invocar al datagrid, lo que vamos a hacer es
// una peticion ajax, para obtener a la vez los datos tecnicos de la manga
$.ajax({
type:'GET',
url:"/agility/server/database/resultadosFunctions.php",
dataType:'json',
data: {
Operation: (isJornadaEquipos())?'getResultadosEquipos':'getResultados',
Prueba: workingData.prueba,
Jornada: workingData.jornada,
Manga: workingData.manga,
Mode: mode
},
success: function(dat) {
// update TRS data
var suffix='L';
switch (mode) {
case 0: case 4: case 6: case 8: suffix='L'; break;
case 1: case 3: suffix='M'; break;
case 2: case 7: suffix='S'; break;
case 5: suffix='T'; break;
}
$('#rm_DIST_'+suffix).val(dat['trs'].dist);
$('#rm_OBST_'+suffix).val(dat['trs'].obst);
$('#rm_TRS_'+suffix).val(dat['trs'].trs);
$('#rm_TRM_'+suffix).val(dat['trs'].trm);
var vel=(''+dat['trs'].vel).replace('≈','\u2248');
$('#rm_VEL_'+suffix).val(vel);
// actualizar datagrid
if (!fill) return;
if ( isJornadaEquipos() ) {
var dg=$('#parciales_equipos-datagrid');
workingData.individual=dat.individual;
dg.datagrid('options').expandCount = 0;
dg.datagrid('loadData',dat.equipos);
} else {
var dg=$('#parciales_individual-datagrid');
workingData.individual=dat.rows;
dg.datagrid('loadData',dat.rows);
}
}
});
}
/**
* Actualiza los datos de TRS y TRM de la fila especificada
* Rellena tambien el datagrid de resultados parciales
*/
function updateParciales(mode,row) {
// si no nos pasan parametro, leemos el valor del combogrid
if (typeof (mode) === "undefined") {
var row=$('#enumerateParciales').combogrid('grid').datagrid('getSelected');
if (!row) return;
setManga(row);
mode=row.Mode;
} else {
// informacion de la manga ya definida: ajusta texto y modo
var modestr=getModeString(workingData.datosPrueba.RSCE,mode);
$('#vw_header-infomanga').html(row.Manga.Nombre + " - " + modestr);
}
// en lugar de invocar al datagrid, lo que vamos a hacer es
// una peticion ajax, para obtener a la vez los datos tecnicos de la manga
// y de los jueces
$.ajax({
type:'GET',
url:"/agility/server/database/resultadosFunctions.php",
dataType:'json',
data: {
Operation: (isJornadaEquipos())?'getResultadosEquipos':'getResultados',
Prueba: workingData.prueba,
Jornada: workingData.jornada,
Manga: workingData.manga,
Mode: parseInt(mode)
},
success: function(dat) {
// use html() instead of text() to handle html special chars
$('#parciales-NombreManga').html(workingData.nombreManga);
$('#parciales-Juez1').html((dat['manga'].Juez1<=1)?"":'<?php _e('Judge');?> 1: ' + dat['manga'].NombreJuez1);
$('#parciales-Juez2').html((dat['manga'].Juez2<=1)?"":'<?php _e('Judge');?> 2: ' + dat['manga'].NombreJuez2);
// datos de TRS
$('#parciales-Distancia').html('<?php _e('Dist');?>: ' + dat['trs'].dist + 'm.');
$('#parciales-Obstaculos').html('<?php _e('Obst');?>: ' + dat['trs'].obst);
$('#parciales-TRS').html('<?php _e('S.C.T.');?>: ' + dat['trs'].trs + 's.');
$('#parciales-TRM').html('<?php _e('M.C.T.');?>: ' + dat['trs'].trm + 's.');
$('#parciales-Velocidad').html('<?php _e('Vel');?>: ' + dat['trs'].vel + 'm/s');
// actualizar datagrid
if ( isJornadaEquipos() ) {
var dg=$('#parciales_equipos-datagrid');
workingData.individual=dat.individual;
dg.datagrid('options').expandCount = 0;
dg.datagrid('loadData',dat.equipos);
} else {
var dg=$('#parciales_individual-datagrid');
workingData.individual=dat.rows;
dg.datagrid('loadData',dat.rows);
}
}
});
}
/**
* Actualiza datos de la clasificacion general
*/
function updateFinales(ronda,callback) {
if (typeof(ronda)==="undefined") {
ronda=$('#enumerateFinales').combogrid('grid').datagrid('getSelected');
if (ronda==null) {
// $.messager.alert("Error:","!No ha seleccionado ninguna ronda de esta jornada!","warning");
return; // no way to know which ronda is selected
}
}
// do not call doResults cause expected json data
$.ajax({
type:'GET',
url:"/agility/server/database/clasificacionesFunctions.php",
dataType:'json',
data: {
Operation: (isJornadaEquipos())?'clasificacionEquipos':'clasificacionIndividual',
Prueba: ronda.Prueba,
Jornada:ronda.Jornada,
Manga1: ronda.Manga1,
Manga2: ronda.Manga2,
Rondas: ronda.Rondas,
Mode: ronda.Mode
},
success: function(dat) {
// nombres de las mangas
$('#finales-NombreRonda').html(ronda.Nombre);
// datos de los jueces
$('#finales-Juez1').html((dat['jueces'][0]=="-- Sin asignar --")?"":'<?php _e('Judge');?> 1: ' + dat['jueces'][0]);
$('#finales-Juez2').html((dat['jueces'][1]=="-- Sin asignar --")?"":'<?php _e('Judge');?> 2: ' + dat['jueces'][1]);
// datos de trs manga 1
$('#finales-Ronda1').html(ronda.NombreManga1);
$('#finales-Distancia1').html('<?php _e('Dist');?>: ' + dat['trs1'].dist + 'm.');
$('#finales-Obstaculos1').html('<?php _e('Obst');?>: ' + dat['trs1'].obst);
$('#finales-TRS1').html('<?php _e('S.C.T.');?>: ' + dat['trs1'].trs + 's.');
$('#finales-TRM1').html('<?php _e('M.C.T.');?>: ' + dat['trs1'].trm + 's.');
$('#finales-Velocidad1').html('<?php _e('Vel');?>: ' + dat['trs1'].vel + 'm/s');
// datos de trs manga 2
if (ronda.Manga2==0) { // single round
$('#finales-Ronda2').html("");
$('#finales-Distancia2').html("");
$('#finales-Obstaculos2').html("");
$('#finales-TRS2').html("");
$('#finales-TRM2').html("");
$('#finales-Velocidad2').html("");
} else {
$('#finales-Ronda2').html(ronda.NombreManga2);
$('#finales-Distancia2').html('<?php _e('Dist');?>: ' + dat['trs2'].dist + 'm.');
$('#finales-Obstaculos2').html('<?php _e('Obst');?>: ' + dat['trs2'].obst);
$('#finales-TRS2').html('<?php _e('S.C.T.');?>: ' + dat['trs2'].trs + 's.');
$('#finales-TRM2').html('<?php _e('M.C.T.');?>: ' + dat['trs2'].trm + 's.');
$('#finales-Velocidad2').html('<?php _e('Vel');?>: ' + dat['trs2'].vel + 'm/s');
}
// clasificaciones
if ( isJornadaEquipos() ) {
$('#finales_equipos_roundname_m1').html(ronda.NombreManga1);
$('#finales_equipos_roundname_m2').html(ronda.NombreManga2);
var dg=$('#finales_equipos-datagrid');
workingData.individual=dat.individual;
dg.datagrid('options').expandCount = 0;
dg.datagrid('loadData',dat.equipos);
} else {
$('#finales_individual_roundname_m1').html(ronda.NombreManga1);
$('#finales_individual_roundname_m2').html(ronda.NombreManga2);
var dg=$('#finales_individual-datagrid');
workingData.individual=dat.rows;
dg.datagrid('loadData',dat.rows);
}
// if defined, invoke callback
if (typeof(callback)==='function') callback(dat);
}
});
}
function setFinalIndividualOrTeamView(data) {
var team=false;
if (parseInt(data.Jornada.Equipos3)!=0) { team=true; }
if (parseInt(data.Jornada.Equipos4)!=0) { team=true; }
// limpiamos tablas
// activamos la visualizacion de la tabla correcta
if (team) {
$("#finales_individual-table").css("display","none");
$("#finales_equipos-table").css("display","inherit");
$("#finales_equipos-datagrid").datagrid('loadData', {"total":0,"rows":[]});
$("#finales_equipos-datagrid").datagrid('fitColumns');
} else {
$("#finales_individual-table").css("display","inherit");
$("#finales_equipos-table").css("display","none");
$("#finales_individual-datagrid").datagrid('loadData', {"total":0,"rows":[]});
$("#finales_individual-datagrid").datagrid('fitColumns');
}
}
function setParcialIndividualOrTeamView(data) {
var team=false;
if (parseInt(data.Jornada.Equipos3)!=0) { team=true; }
if (parseInt(data.Jornada.Equipos4)!=0) { team=true; }
// limpiamos tablas
// activamos la visualizacion de la tabla correcta
if (team) {
$("#parciales_individual-table").css("display","none");
$("#parciales_equipos-table").css("display","inherit");
$("#parciales_equipos-datagrid").datagrid('loadData', {"total":0,"rows":[]});
$("#parciales_equipos-datagrid").datagrid('fitColumns');
} else {
$("#parciales_individual-table").css("display","inherit");
$("#parciales_equipos-table").css("display","none");
$("#parciales_individual-datagrid").datagrid('loadData', {"total":0,"rows":[]});
$("#parciales_individual-datagrid").datagrid('fitColumns');
}
} | gpl-2.0 |
DevendraThakare/housing.news | wp-content/themes/mytheme/template-parts/content-single.php | 1956 | <?php
/**
* The template part for displaying single posts
*
* @package WordPress
* @subpackage Twenty_Sixteen
* @since Twenty Sixteen 1.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="post-meta">
<?php post_meta(); ?>
</div>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php if(function_exists('the_subtitle')){the_subtitle('<h3 class="entry-subtitle">', '</h3>');} ?>
</header><!-- .entry-header -->
<?php
// if(get_post_type()!='glossary'){
// echo do_shortcode('[addtoany]');
// }
?>
<div class="entry-content">
<?php
the_content();
wp_link_pages( array(
'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'twentysixteen' ) . '</span>',
'after' => '</div>',
'link_before' => '<span>',
'link_after' => '</span>',
'pagelink' => '<span class="screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>%',
'separator' => '<span class="screen-reader-text">, </span>',
) );
?>
</div><!-- .entry-content -->
<?php
// if(get_post_type()!='glossary'){
// echo do_shortcode('[addtoany]');
// }
?>
<?php if(function_exists('wp_related_posts') && get_post_type()!='glossary'){ wp_related_posts(); } ?>
<div class="tags-section page-section">
<?php echo get_the_tag_list('<ul class="tag-list"><li>','</li><li>','</li></ul>'); ?>
</div>
<?php if(get_post_type()!='glossary'){ ?>
<div class="fb-comment-section page-section">
<?php echo do_shortcode('[fbcomments]'); ?>
</div>
<?php } ?>
<footer class="entry-footer">
<?php
edit_post_link(
sprintf(
/* translators: %s: Name of current post */
__( 'Edit<span class="screen-reader-text"> "%s"</span>', 'twentysixteen' ),
get_the_title()
),
'<span class="edit-link">',
'</span>'
);
?>
</footer><!-- .entry-footer -->
</article><!-- #post-## -->
| gpl-2.0 |
alriddoch/cyphesis | server/CommPeer.cpp | 3881 | // Cyphesis Online RPG Server and AI Engine
// Copyright (C) 2004 Alistair Riddoch
//
// 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
// $Id$
#include "CommPeer.h"
#include "Peer.h"
#include "CommServer.h"
#include "common/globals.h"
#include "common/serialno.h"
#include "common/log.h"
#include <Atlas/Negotiate.h>
#include <Atlas/Objects/Operation.h>
#include <Atlas/Objects/Anonymous.h>
using Atlas::Objects::Entity::Anonymous;
using Atlas::Objects::Operation::Info;
/// \brief Constructor remote peer socket object.
///
/// @param svr Reference to the object that manages all socket communication.
/// @param username Username to login with on peer
/// @param password Password to login with on peer
CommPeer::CommPeer(CommServer & svr, const std::string & name) :
CommClient<tcp_socket_stream>(svr, name)
{
}
CommPeer::~CommPeer()
{
}
/// \brief Connect to a remote peer on a specific port
///
/// @param host The hostname of the peer to connect to
/// @param port The port to connect on
/// @return Returns 0 on success and -1 on failure.
int CommPeer::connect(const std::string & host, int port)
{
return m_clientIos.open(host, port, true);
}
/// \brief Connect to a remote peer wath a specific address info
///
/// @param info The address info of the peer to connect to
/// @return Returns 0 on success and -1 on failure.
int CommPeer::connect(struct addrinfo * info)
{
return m_clientIos.open(info, true);
}
void CommPeer::setup(Link * connection)
{
m_link = connection;
assert(!m_clientIos.connect_pending());
m_negotiate->poll(false);
m_clientIos << std::flush;
}
bool CommPeer::eof()
{
if (m_clientIos.connect_pending()) {
if (m_clientIos.isReady(0)) {
connected.emit();
return false;
} else {
// With the cyphesis socket model, this object gets deleted
// if its fd gets closed, so trying a second fd is useless
// This object is done.
failed.emit();
return true;
}
} else {
return CommStreamClient<tcp_socket_stream>::eof();
}
}
/// \brief Called periodically by the server
///
/// \param t The current time at the time of calling
void CommPeer::idle(time_t t)
{
// Wait for the negotiation to finish with the peer
if (m_negotiate != 0) {
if ((t - m_connectTime) > 10) {
log(NOTICE, "Client disconnected because of negotiation timeout.");
m_clientIos.shutdown();
}
} else {
Peer *peer = dynamic_cast<Peer*>(m_link);
if (peer == NULL) {
log(WARNING, "Casting CommPeer connection to Peer failed");
return;
}
// Check if we have been stuck in a state of authentication in-progress
// for over 20 seconds. If so, disconnect from and remove peer.
if ((t - m_connectTime) > 20) {
if (peer->getAuthState() == PEER_AUTHENTICATING) {
log(NOTICE, "Peer disconnected because authentication timed out.");
m_clientIos.shutdown();
}
}
if (peer->getAuthState() == PEER_AUTHENTICATED) {
peer->cleanTeleports();
}
}
}
| gpl-2.0 |
ryanwi/snapblast | app/classes/team_phone_number_collector.rb | 1163 | class TeamPhoneNumberCollector
# Collect all phone numbers for a collection of rosters
#
# @param rosters
# Array of roster objects for a team
#
def self.collect(rosters)
phone_numbers = []
rosters.each do |roster|
phone_numbers << roster_phone_numbers(roster)
phone_numbers << contact_phone_numbers(roster)
end
# Flatten and only take unique numbers
phone_numbers.flatten!
phone_numbers.uniq!
phone_numbers
end
# Find the player phone number(s) on the primary roster object
#
# @param roster
# Individual roster object
#
def self.roster_phone_numbers(roster)
roster["roster"]["roster_telephone_numbers"].collect{|phone| phone["phone_number"]}
end
# Find the contact phone number(s) associated with a roster object
#
# @param rosters
# Individual roster object
#
def self.contact_phone_numbers(roster)
phone_numbers = []
roster["roster"]["contacts"].each do |contact|
contact["contact_telephone_numbers"].each do |phone|
phone_numbers << phone["phone_number"] unless phone["phone_number"].blank?
end
end
phone_numbers
end
end
| gpl-2.0 |
MagicMediaInc/copperfield | wp-content/themes/trendytravel/framework/theme_shortcodes.php | 56902 | <?php
#CONTACT FORM SHORTCODE...
if(!function_exists('dt_contact_form')) {
function dt_contact_form( $atts, $content = null ) {
extract(shortcode_atts(array(
'to_email' => get_bloginfo('admin_email'),
'success_msg' => __('Thanks for Contacting Us, We will call back to you soon.', 'iamd_text_domain'),
'error_msg' => __('Sorry your message not sent, Try again Later.', 'iamd_text_domain')
), $atts));
$out = '';
$out .= '<div id="ajax_message"> </div>';
$out .= '<form class="wpcf7-form contact-frm" method="post" action="'.get_template_directory_uri().'/framework/sendmail.php">';
$out .= '<div class="dt-sc-one-half column first">';
$out .= '<p><input type="text" name="cname" placeholder="'.__('Name *', 'iamd_text_domain').'" required="required" /></p>';
$out .= '<p><input type="email" name="cemail" placeholder="'.__('Email *','iamd_text_domain').'" required="required" /></p>';
$out .= '<p><input type="text" name="csubject" placeholder="'.__('Subject', 'iamd_text_domain').'" /></p>';
$out .= '</div>';
$out .= '<p class="dt-sc-one-half column"><textarea cols="12" rows="7" name="cmessage" placeholder="'.__('Message *', 'iamd_text_domain').'"></textarea></p>';
$out .= '<input type="submit" name="submit" value="'.__('Send Message', 'iamd_text_domain').'" />';
$out .= '<input type="hidden" name="hidadminemail" value="'.$to_email.'" />';
$out .= '<input type="hidden" name="hidsuccess" value="'.$success_msg.'" />';
$out .= '<input type="hidden" name="hiderror" value="'.$error_msg.'" />';
$out .= '</form>';
return $out;
}
add_shortcode('dt_contact_form', 'dt_contact_form');
add_shortcode('dt_sc_contact_form', 'dt_contact_form');
}
#SOCIAL ICONS...
if(!function_exists('dt_social')) {
function dt_social($attrs, $content=null,$shortcodename="") {
extract(shortcode_atts(array(
'text' => ''
), $attrs));
$text = !empty($text) ? "<p class='social-media-text'>$text</p>" : "";
$dt_theme_options = get_option(IAMD_THEME_SETTINGS);
$out = "";
if(is_array($dt_theme_options['social'])):
$out .= $text;
$out .= "<ul class='dt-sc-social-icons'>";
foreach($dt_theme_options['social'] as $social):
$link = $social['link'];
$icon = $social['icon'];
$out .= "<li class='".substr($icon, 3)."'>";
$out .= "<a class='fa {$icon}' href='{$link}'></a>";
$out .= "</li>";
endforeach;
$out .= "</ul>";
endif;
return $out;
}
add_shortcode('dt_social','dt_social');
}
#BLOG LIST...
if(!function_exists('dt_blog_posts')) {
function dt_blog_posts( $atts, $content = null ) {
extract(shortcode_atts(array(
'excerpt_length' => 25,
'show_meta' => 'true',
'limit' => -1,
'categories' => '',
'posts_column' => 'one-third-column', // one-column, one-half-column, one-third-column, one-fourth-column
), $atts));
global $post;
$meta_set = get_post_meta(get_queried_object_id(), '_tpl_default_settings', true);
$page_layout = !empty($meta_set['layout']) ? $meta_set['layout'] : 'content-full-width';
$post_layout = $posts_column;
$article_class = "";
$feature_image = "blog-full";
$column = ""; $out = "";
//POST LAYOUT CHECK...
if($post_layout == "one-column") {
$article_class = "column dt-sc-one-column";
}
elseif($post_layout == "one-half-column") {
$article_class = "column dt-sc-one-half";
$column = 2;
}
elseif($post_layout == "one-third-column") {
$article_class = "column dt-sc-one-third";
$column = 3;
}
elseif($post_layout == "one-fourth-column") {
$article_class = "column dt-sc-one-fourth";
$column = 4;
}
//PAGE LAYOUT CHECK...
if($page_layout != "content-full-width") {
$article_class = $article_class." with-sidebar";
}
//POST VALUES....
if($categories == "") $categories = 0;
$args = array('post_type' => 'post', 'posts_per_page' => $limit, 'cat' => $categories, 'ignore_sticky_posts' => 1);
$the_query = new WP_Query($args);
if($the_query->have_posts()): $i = 1;
$out .= '<div class="blog-entry-posts">';
while($the_query->have_posts()): $the_query->the_post();
$temp_class = "";
if($i == 1) $temp_class = $article_class." first"; else $temp_class = $article_class;
if($i == $column) $i = 1; else $i = $i + 1;
$out .= '<div class="'.$temp_class.'">';
$out .= '<div id="post-'.get_the_ID().'" class="'.implode(" ", get_post_class("entry-post", $post->ID)).'">';
if($show_meta != "false"):
$out .= '<div class="entry-date">';
$out .= '<p>'.get_the_date('d').'<span>'.get_the_date('M').' '.get_the_date('Y').'</span></p>';
$out .= '<span></span>';
$out .= '</div>';
endif;
$out .= '<div class="entry-container">';
$format = get_post_format();
$out .= '<div class="entry-thumb">';
if(is_sticky()):
$out .= '<div class="featured-post"><span>'.__('Featured','iamd_text_domain').'</span></div>';
endif;
//Post Format Starts...
if( $format === "image" || empty($format) ):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
if(has_post_thumbnail()):
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail($post->ID, $feature_image, $attr);
else:
$out .= '<img src="http://placehold.it/1170x800&text=Image" width="1170" height="800" alt="'.get_the_title().'" />';
endif;
$out .= '<div class="image-overlay"><span class="image-overlay-inside"></span></div>';
$out .= '</a>';
elseif( $format === "gallery" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
if( @array_key_exists("items", $post_meta) ):
$out .= "<ul class='entry-gallery-post-slider'>";
foreach ( $post_meta['items'] as $item ) { $out .= "<li><img src='{$item}' alt='gal-img' /></li>"; }
$out .= "</ul>";
$out .= '<div class="image-overlay"><span class="image-overlay-inside"></span></div>';
endif;
elseif( $format === "video" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
if( @array_key_exists('oembed-url', $post_meta) || array_key_exists('self-hosted-url', $post_meta) ):
if( array_key_exists('oembed-url', $post_meta) ):
$out .= "<div class='dt-video-wrap'>".wp_oembed_get($post_meta['oembed-url']).'</div>';
elseif( array_key_exists('self-hosted-url', $post_meta) ):
$out .= "<div class='dt-video-wrap'>".apply_filters( 'the_content', $post_meta['self-hosted-url'] ).'</div>';
endif;
endif;
elseif( $format === "audio" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
if( @array_key_exists('oembed-url', $post_meta) || array_key_exists('self-hosted-url', $post_meta) ):
if( array_key_exists('oembed-url', $post_meta) ):
$out .= wp_oembed_get($post_meta['oembed-url']);
elseif( array_key_exists('self-hosted-url', $post_meta) ):
$out .= apply_filters( 'the_content', $post_meta['self-hosted-url'] );
endif;
endif;
else:
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
if(has_post_thumbnail()):
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail($post->ID, $feature_image, $attr);
else:
$out .= '<img src="http://placehold.it/1170x800&text=Image" width="1170" height="800" alt="'.get_the_title().'" />';
endif;
$out .= '<div class="image-overlay"><span class="image-overlay-inside"></span></div>';
$out .= '</a>';
endif;
$out .= '</div>';
$out .= '<div class="entry-detail">';
$out .= '<h2><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
if($show_meta != "false"):
$out .= '<ul class="entry-post-meta">';
$out .= '<li><span class="fa fa-user"></span>'.__('Posted By: ', 'iamd_text_domain').'<a href="'.get_author_posts_url(get_the_author_meta('ID')).'">'.get_the_author_meta('display_name').'</a></li>';
$out .= '<li>';
$commtext = "";
if((wp_count_comments($post->ID)->approved) == 0) $commtext = '0';
else $commtext = wp_count_comments($post->ID)->approved;
$out .= '<a href="'.get_permalink().'/#comments"><span class="fa fa-comment"></span>'.$commtext.'</a>';
$out .= '</li>';
$out .= '</ul>';
endif;
if($excerpt_length != "" || $excerpt_length != 0) $out .= dt_theme_excerpt($excerpt_length);
$out .= '<p class="aligncenter"><a href="'.get_permalink().'" class="dt-sc-button too-small">'.__('Read More','iamd_text_domain').'</a></p>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
endwhile;
$out .= '</div>';
else:
$out .= '<h2>'.__('Nothing Found.', 'iamd_text_domain').'</h2>';
$out .= '<p>'.__('Apologies, but no results were found for the requested archive.', 'iamd_text_domain').'</p>';
endif;
return $out;
}
add_shortcode('dt_blog_posts', 'dt_blog_posts');
add_shortcode('dt_sc_blogposts', 'dt_blog_posts');
}
//FB LIKE...
add_shortcode('fblike','fblike');
function fblike( $attrs = null, $content = null,$shortcodename ="" ){
extract(shortcode_atts(array('layout'=>'box_count','width'=>'','height'=>'','send'=>false,'show_faces'=>false,'action'=>'like','font'=> 'lucida+grande'
,'colorscheme'=>'light'), $attrs));
if ($layout == 'standard') { $width = '450'; $height = '35'; if ($show_faces == 'true') { $height = '80'; } }
if ($layout == 'box_count') { $width = '55'; $height = '65'; }
if ($layout == 'button_count') { $width = '90'; $height = '20'; }
$layout = 'data-layout = "'.$layout.'" ';
$width = 'data-width = "'.$width.'" ';
$font = 'data-font = "'.str_replace("+", " ", $font).'" ';
$colorscheme = 'data-colorscheme = "'.$colorscheme.'" ';
$action = 'data-action = "'.$action.'" ';
if ( $show_faces ) { $show_faces = 'data-show-faces = "true" '; } else { $show_faces = ''; }
if ( $send ) { $send = 'data-send = "true" '; } else { $send = ''; }
$out = '<div id="fb-root"></div><script>(function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) return;js = d.createElement(s); js.id = id;js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";fjs.parentNode.insertBefore(js, fjs);}(document, "script", "facebook-jssdk"));</script>';
$out .= '<div class = "fb-like" data-href = "'.get_permalink().'" '.$layout.$width.$font.$colorscheme.$action.$show_faces.$send.'></div>';
return $out;
}
//GOOGLE PLUS...
add_shortcode('googleplusone','googleplusone');
function googleplusone( $attrs = null, $content = null,$shortcodename ="" ){
extract(shortcode_atts(array('size'=> '','lang'=> ''), $attrs));
$size = empty($size) ? "size='small'" : "size='{$size}'";
$lang = empty($lang) ? "{lang:en_GB}" : "{lang:'{$lang}'}";
$out = '<script type="text/javascript" src="https://apis.google.com/js/plusone.js">'.$lang.'</script>';
$out .= '<g:plusone '.$size.'></g:plusone>';
return $out;
}
//TWITTER BUTTON...
add_shortcode('twitter','twitter');
function twitter( $attrs = null, $content = null,$shortcodename ="" ){
extract(shortcode_atts(array('layout'=>'vertical','username'=>'','text'=>'','url'=>'','related'=> '','lang'=> ''), $attrs));
$p_url= get_permalink();
$p_title = get_the_title();
$text = !empty($text) ? "data-text='{$text}'" :"data-text='{$p_title}'";
$url = !empty($url) ? "data-url='{$url}'" :"data-url='{$p_url}'";
$related = !empty($related) ? "data-related='{$related}'" :'';
$lang = !empty($lang) ? "data-lang='{$lang}'" :'';
$twitter_url = "http://twitter.com/share";
$out = '<a href="{$twitter_url}" class="twitter-share-button" '.$url.' '.$lang.' '.$text.' '.$related.' data-count="'.$layout.'" data-via="'.$username.'">'.
__('Tweet','iamd_text_domain').'</a>';
$out .= '<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
return $out;
}
//STUMBLEUPON...
add_shortcode('stumbleupon','stumbleupon');
function stumbleupon( $attrs = null, $content = null,$shortcodename ="" ){
extract(shortcode_atts(array('layout'=>'5','url'=>get_permalink()),$attrs));
$url = "&r='{$url}'";
$out = '<script src="http://www.stumbleupon.com/hostedbadge.php?s='.$layout.$url.'"></script>';
return $out;
}
//LINKEDIN...
add_shortcode('linkedin','linkedin');
function linkedin( $attrs = null, $content = null,$shortcodename ="" ){
extract(shortcode_atts(array('layout'=>'2','url'=>get_permalink()),$attrs));
if ($url != '') { $url = "data-url='".$url."'"; }
if ($layout == '2') { $layout = 'right'; }
if ($layout == '3') { $layout = 'top'; }
$out = '<script type="text/javascript" src="http://platform.linkedin.com/in.js"></script><script type="in/share" data-counter = "'.$layout.'" '.$url.'></script>';
return $out;
}
//DELICIES...
add_shortcode('delicious','delicious');
function delicious( $attrs = null, $content = null,$shortcodename ="" ){
extract(shortcode_atts(array('text'=>__("Delicious",'iamd_text_domain')),$attrs));
$delicious_url = "http://www.delicious.com/save";
$out = '<img src="http://www.delicious.com/static/img/delicious.small.gif" height="10" width="10" alt="Delicious" /> <a href="{$delicious_url}" onclick="window.open('http://www.delicious.com/save?v=5&noui&jump=close&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550'); return false;">'.$text.'</a>';
return $out;
}
//PINTEREST...
add_shortcode('pintrest','pintrest');
function pintrest( $attrs = null, $content = null,$shortcodename ="" ){
extract(shortcode_atts(array('text'=>get_the_excerpt(),'layout'=>'horizontal','image'=>'','url'=>get_permalink(),'prompt'=>false),$attrs));
$out = '<div class = "mysite_sociable"><a href="http://pinterest.com/pin/create/button/?url='.$url.'&media='.$image.'&description='.$text.'" class="pin-it-button" count-layout="'.$layout.'">'.__("Pin It",'iamd_text_domain').'</a>';
$out .= '<script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>';
if($prompt):
$out = '<a title="'.__('Pin It on Pinterest','iamd_text_domain').'" class="pin-it-button" href="javascript:void(0)">'.__("Pin It",'iamd_text_domain').'</a>';
$out .= '<script type = "text/javascript">';
$out .= 'jQuery(document).ready(function(){';
$out .= 'jQuery(".pin-it-button").click(function(event) {';
$out .= 'event.preventDefault();';
$out .= 'jQuery.getScript("http://assets.pinterest.com/js/pinmarklet.js?r=" + Math.random()*99999999);';
$out .= '});';
$out .= '});';
$out .= '</script>';
$out .= '<style type = "text/css">a.pin-it-button {position: absolute;background: url(http://assets.pinterest.com/images/pinit6.png);font: 11px Arial, sans-serif;text-indent: -9999em;font-size: .01em;color: #CD1F1F;height: 20px;width: 43px;background-position: 0 -7px;}a.pin-it-button:hover {background-position: 0 -28px;}a.pin-it-button:active {background-position: 0 -49px;}</style>';
endif;
return $out;
}
//DIGG...
add_shortcode('digg','digg');
function digg( $attrs = null, $content = null,$shortcodename ="" ){
extract(shortcode_atts(array('layout'=>'DiggMedium','url'=>get_permalink(),'title'=>get_the_title(),'type'=>'','description'=>get_the_content(),'related'=>''),$attrs));
if ($title != '') { $title = "&title='".$title."'"; }
if ($type != '') { $type = "rev='".$type."'"; }
if ($description != '') { $description = "<span style = 'display: none;'>".$description."</span>"; }
if ($related != '') { $related = "&related=no"; }
$out = '<a class="DiggThisButton '.$layout.'" href="http://digg.com/submit?url='.$url.$title.$related.'"'.$type.'>'.$description.'</a>';
$out .= '<script type = "text/javascript" src = "http://widgets.digg.com/buttons.js"></script>';
return $out;
}
#GALLERY ITEMS
if(!function_exists('dt_gallery_items')) {
function dt_gallery_items( $atts, $content = null ) {
extract(shortcode_atts(array(
'limit' => -1,
'categories' => '',
'posts_column' => 'one-half-column', // one-third-column, one-fourth-column
'filter' => ''
), $atts));
global $post;
$meta_set = get_post_meta(get_queried_object_id(), '_tpl_default_settings', true);
$page_layout = !empty($meta_set['layout']) ? $meta_set['layout'] : 'content-full-width';
$post_layout = $posts_column;
$li_class = "";
$out = "";
//POST LAYOUT CHECK...
if($post_layout == "one-half-column") {
$li_class = "portfolio dt-sc-one-half column";
}
elseif($post_layout == "one-third-column") {
$li_class = "portfolio dt-sc-one-third column";
}
elseif($post_layout == "one-fourth-column") {
$li_class = "portfolio dt-sc-one-fourth column";
}
//PAGE LAYOUT CHECK...
if($page_layout != "content-full-width") {
$li_class = $li_class." with-sidebar";
}
if(empty($categories)) {
$cats = get_categories('taxonomy=gallery_entries&hide_empty=1');
$cats = get_terms( array('gallery_entries'), array('fields' => 'ids'));
} else {
$cats = explode(',', $categories);
}
//PERFORMING QUERY...
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }
//PERFORMING QUERY...
$args = array('post_type' => 'dt_galleries', 'paged' => $paged , 'posts_per_page' => $limit,
'tax_query' => array(
array(
'taxonomy' => 'gallery_entries',
'field' => 'id',
'terms' => $cats
)));
$the_query = new WP_Query($args);
if($the_query->have_posts()):
if($filter != "false"):
$out .= '<div class="dt-sc-sorting-container">';
$out .= '<a data-filter="*" href="#" class="first active-sort">'.__("All", "iamd_text_domain").'</a>';
foreach($cats as $term) {
$myterm = get_term_by('id', $term, 'gallery_entries');
$out .= '<a href="#" data-filter=".'.strtolower($myterm->slug).'">'.$myterm->name.'</a>';
}
$out .= '</div>';
endif;
$out .= '<div class="dt-sc-portfolio-container">';
while($the_query->have_posts()): $the_query->the_post();
$terms = wp_get_post_terms(get_the_ID(), 'gallery_entries', array("fields" => "slugs")); array_walk($terms, "arr_strfun");
$out .= '<div class="'.$li_class." ".strtolower(implode(" ", $terms)).' no-space">';
$out .= '<figure>';
$fullimg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full', false);
$currenturl = $fullimg[0];
$currenticon = "fa-plus";
$pmeta_set = get_post_meta($post->ID, '_gallery_settings', true);
if( @array_key_exists('items_thumbnail', $pmeta_set) && ($pmeta_set ['items_name'] [0] == 'video' )) {
$currenturl = $pmeta_set ['items'] [0];
$currenticon = "fa-video-camera";
}
//GALLERY IMAGES...
if(has_post_thumbnail()):
$attr = array('title' => get_the_title(), 'alt' => get_the_title());
$out .= get_the_post_thumbnail($post->ID, 'full', $attr);
else:
$out .= '<img src="http://placehold.it/1170X800.jpg&text=No Image" alt="'.get_the_title().'" title="'.get_the_title().'" />';
endif;
$out .= '<figcaption>';
$out .= '<div class="fig-content-wrapper">';
$out .= '<div class="fig-content">';
$out .= '<h5><a href="'.get_permalink().'">'.get_the_title().'</a></h5>';
$out .= '<p>'.get_the_term_list($post->ID, 'gallery_entries', ' ', ', ', ' ').'</p>';
$out .= '<div class="fig-overlay">';
$out .= '<a class="zoom" title="'.get_the_title().'" data-gal="prettyPhoto[gallery]" href="'.$currenturl.'"><span class="fa '.$currenticon.'"> </span></a>';
$out .= '<a class="link" href="'.get_permalink().'"> <span class="fa fa-link"> </span> </a>';
if(dt_theme_is_plugin_active('roses-like-this/likethis.php')):
$out .= generateLikeString($post->ID, '');
endif;
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
$out .= '</figcaption>';
$out .= '</figure>';
$out .= '</div>';
endwhile;
$out .= '</div>';
else:
$out .= '<h2>'.__("Nothing Found.", "iamd_text_domain").'</h2>';
$out .= '<p>'.__("Apologies, but no results were found for the requested archive.", "iamd_text_domain").'</p>';
endif;
return $out;
}
add_shortcode('dt_gallery_items', 'dt_gallery_items');
add_shortcode('dt_sc_gallery_items', 'dt_gallery_items');
}
#EVENTS LIST SHORTCODE...
if(!function_exists('dt_events_list') && dt_theme_is_plugin_active('the-events-calendar/the-events-calendar.php')) {
function dt_events_list( $atts, $content = null ) {
extract(shortcode_atts(array(
'limit' => '-1',
'excerpt_length' => '18',
'post_column' => 'one-third-column', // one-half-column, one-third-column, one-fourth-column
), $atts));
$post_column = !empty($post_column) ? $post_column : 'one-third-column';
if($post_column == "one-half-column") {
$div_class = "column dt-sc-one-half";
$column = 2;
}
elseif($post_column == "one-third-column") {
$div_class = "column dt-sc-one-third";
$column = 3;
}
elseif($post_column == "one-fourth-column") {
$div_class = "column dt-sc-one-fourth";
$column = 4;
}
global $post; $out = ""; $i = 1;
$all_events = tribe_get_events(array( 'eventDisplay'=>'all', 'posts_per_page'=> $limit ));
foreach($all_events as $post) {
setup_postdata($post);
$tmpclass = "";
if($i == 1) $tmpclass = $div_class." first"; else $tmpclass = $div_class;
if($i == $column) $i = 1; else $i = $i + 1;
$out .= '<div id="post-'.$post->ID.'" class="'.$tmpclass.'">';
$out .= '<div class="dt-sc-event">';
$out .= '<h4><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></h4>';
$out .= '<div class="event-thumb">';
$out .= '<a href="'.get_permalink($post->ID).'" title="'.$post->post_title.'">';
$attr = array('title' => $post->post_title); $out .= get_the_post_thumbnail($post->ID, 'full', $attr);
$out .= '<div class="image-overlay">';
$out .= '<span class="image-overlay-inside"></span>';
$out .= '</div>';
$out .= '</a>';
$out .= '</div>';
$out .= dt_theme_excerpt($excerpt_length);
$out .= '<div class="dt-sc-event-detail">';
$cost = get_post_meta($post->ID, '_EventCost', true);
if(!empty($cost)) {
$out .= '<div class="event-price">';
$out .= '<p>'.__('Starts From', 'iamd_text_domain').'</p>';
$sym = get_post_meta($post->ID, '_EventCurrencySymbol', true);
$out .= '<span>'.$sym.$cost.'</span>';
$out .= '</div>';
}
$out .= '<a href="'.get_permalink($post->ID).'" class="dt-sc-button too-small">'.__('View details', 'iamd_text_domain').'</a>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
}
return $out;
}
add_shortcode('dt_events_list', 'dt_events_list');
add_shortcode('dt_sc_events_list', 'dt_events_list');
}
//WELCOME TEXT...
if(!function_exists('dt_welcome_text')) {
function dt_welcome_text($attrs, $content=null, $shortcodename =""){
$out = '';
$out .= '<div class="welcome-txt aligncenter">'.do_shortcode($content).'</div>';
return $out;
}
add_shortcode('dt_welcome_text', 'dt_welcome_text');
add_shortcode('dt_sc_welcome_text', 'dt_welcome_text');
}
//BEST PACKAGES WIDGET...
if(!function_exists('dt_packages_list') && dt_theme_is_plugin_active('woocommerce/woocommerce.php')) {
function dt_packages_list( $atts, $content = null ) {
extract(shortcode_atts(array(
'limit' => '-1',
'carousel' => 'false',
'categories' => '',
'post_column' => 'one-fourth-column', // one-half-column, one-third-column, one-fourth-column
), $atts));
$post_column = !empty($post_column) ? $post_column : 'one-fourth-column';
if($post_column == "one-half-column") {
$div_class = "column dt-sc-one-half";
$column = 2;
}
elseif($post_column == "one-third-column") {
$div_class = "column dt-sc-one-third";
$column = 3;
}
elseif($post_column == "one-fourth-column") {
$div_class = "column dt-sc-one-fourth";
$column = 4;
}
if(empty($categories)) {
$cats = get_categories('taxonomy=product_cat&hide_empty=1');
$cats = get_terms( array('product_cat'), array('fields' => 'ids'));
} else {
$cats = explode(',', $categories);
}
$out = "";
$args = array('post_type' => 'product', 'posts_per_page' => $limit, 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $cats )));
$the_query = new WP_Query($args);
if($the_query->have_posts()): $i = 1;
if($carousel == 'true')
$out .= '<div class="package-wrapper dt_carousel" data-items="'.$column.'">';
else
$out .= '<div class="package-wrapper">';
while($the_query->have_posts()): $the_query->the_post();
$tclass = "";
if($i == 1 && $carousel != 'true') $tclass = $div_class." first"; else $tclass = $div_class;
if($i == $column) $i = 1; else $i = $i + 1;
$out .= '<div id="'.get_the_ID().'" class="'.$tclass.'">';
$out .= '<div class="package-item">';
if(has_post_thumbnail()):
$out .= '<div class="package-thumb">';
$out .= '<a href="'.get_permalink(get_the_ID()).'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail(get_the_ID(), 'full', $attr);
$out .= '<div class="image-overlay">';
$out .= '<span class="image-overlay-inside"></span>';
$out .= '</div>';
$out .= '</a>';
$out .= '</div>';
endif;
$out .= '<div class="package-details">';
$out .= '<h5><a href="'.get_permalink().'">'.get_the_title().'</a></h5>';
$city = get_post_meta(get_the_ID(), '_package_place', true);
if(!empty($city))
$out .= '<p>'.$city.'</p>';
$out .= '<div class="package-content">';
$out .= '<ul class="package-meta">';
$days = get_post_meta(get_the_ID(), '_package_days_duration', true);
if(!empty($days))
$out .= '<li> <span class="fa fa-calendar"></span>No of Days: '.$days.' </li>';
$people = get_post_meta(get_the_ID(), '_package_people', true);
if(!empty($people))
$out .= '<li> <span class="fa fa-user"></span>People: '.$people.' </li>';
$out .= '</ul>';
$sprice = get_post_meta(get_the_ID(), '_sale_price', true);
if(!empty($sprice))
$out .= '<span class="package-price">'.get_woocommerce_currency_symbol().$sprice.'</span>';
$out .= '<a href="'.get_permalink().'" class="dt-sc-button too-small">'.__('View details', 'iamd_text_domain').'</a>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
endwhile;
$out .= '</div>';
endif;
if($carousel == 'true') {
return '<div class="carousel_items">'
.$out
.'<div class="carousel-arrows">
<a class="prev-arrow" href="#"><span class="fa fa-angle-left"> </span></a>
<a class="next-arrow" href="#"><span class="fa fa-angle-right"> </span></a>
</div>
</div>';
} else {
return $out;
}
}
add_shortcode('dt_packages_list', 'dt_packages_list');
add_shortcode('dt_sc_packages_list', 'dt_packages_list');
}
//MAP MARKER...
if(!function_exists('dt_marker')) {
function dt_marker($attrs, $content=null, $shortcodename =""){
extract(shortcode_atts(array(
'title' => '',
'color' => 'green'
), $attrs));
$out = "";
$out .= '<p class="map-marker"><span class="'.$color.'"></span>'.$title.'</p>';
return $out;
}
add_shortcode('dt_marker', 'dt_marker');
add_shortcode('dt_sc_marker', 'dt_marker');
}
//NUMBER COUNT...
if(!function_exists('dt_number_count')) {
function dt_number_count($attrs, $content=null, $shortcodename =""){
extract(shortcode_atts(array(
'icon' => 'location-arrow',
'value' => '1540',
'title' => ''
), $attrs));
$out = "";
$out .= '<div class="dt-sc-ico-content type3">';
$out .= '<div class="icon">';
$out .= '<span class="fa fa-'.$icon.'"></span>';
$out .= '</div>';
$out .= '<span class="dt-sc-num-count" data-value="'.$value.'">'.$value.'</span>';
if($title != NULL) $out .= '<h4>'.$title.'</h4>';
$out .= '</div>';
return $out;
}
add_shortcode('dt_number_count','dt_number_count');
add_shortcode('dt_sc_number_count','dt_number_count');
}
//TOUR PACKAGES...
if(!function_exists('dt_tourpackage_list') && dt_theme_is_plugin_active('woocommerce/woocommerce.php')) {
function dt_tourpackage_list( $atts, $content = null ) {
extract(shortcode_atts(array(
'limit' => '-1',
'carousel' => 'false',
'excerpt_length' => 30
), $atts));
$out = "";
$div_class = "column dt-sc-one-half";
$column = 2;
$args = array('post_type' => 'product', 'posts_per_page' => $limit);
$the_query = new WP_Query($args);
if($the_query->have_posts()): $i = 1;
if($carousel == 'true')
$out .= '<div class="dt-sc-packages-wrapper dt_carousel" data-items="2">';
else
$out .= '<div class="dt-sc-packages-wrapper">';
while($the_query->have_posts()): $the_query->the_post();
$tclass = "";
if($i == 1 && $carousel != 'true') $tclass = $div_class." first"; else $tclass = $div_class;
if($i == $column) $i = 1; else $i = $i + 1;
$out .= '<div id="'.get_the_ID().'" class="'.$tclass.'">';
$out .= '<div class="dt-sc-package-item">';
if(get_post_meta(get_the_ID(), '_featured', true) == 'yes')
$out .= '<p class="dt-sc-packtype new"><span>'.__('New ', 'iamd_text_domain').'<br>'.__('Addition', 'iamd_text_domain').'</span></p>';
elseif(get_post_meta(get_the_ID(), '_stock_status', true) == 'outofstock')
$out .= '<p class="dt-sc-packtype sold"><span>'.__('Sold ', 'iamd_text_domain').'<br>'.__('Out', 'iamd_text_domain').'</span></p>';
$out .= '<div class="dt-sc-pack-thumb">';
$out .= '<a href="'.get_permalink(get_the_ID()).'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail(get_the_ID(), 'thumb', $attr);
$out .= '</a>';
if(get_post_meta(get_the_ID(), '_sale_price', true) != "")
$out .= '<p class="dt-sc-pack-price">'.__('From', 'iamd_text_domain').'<span>'.get_woocommerce_currency().' '.get_woocommerce_currency_symbol().get_post_meta(get_the_ID(), '_sale_price', true).'</span></p>';
$arr_rate = dt_theme_comment_rating_count(get_the_ID());
$all_avg = dt_theme_comment_rating_average(get_the_ID());
$out.= '<div class="star-rating-wrapper"><div class="star-rating"><span style="width:'.(($all_avg/5)*100).'%"></span></div>('.count($arr_rate).__(' Ratings', 'iamd_text_domain').')</div>'; $out .= '</div>';
$out .= '<div class="dt-sc-pack-detail">';
$out .= '<h5><a href="'.get_permalink(get_the_ID()).'">'.get_the_title().'</a></h5>';
$out .= '<span class="subtitle">'.get_post_meta(get_the_ID(), '_package_place', true).'</span>';
$out .= '<ul class="dt-sc-pack-meta">';
$out .= '<li><span class="fa fa-clock-o"> </span>No of Days: '.get_post_meta(get_the_ID(), '_package_days_duration', true).'</li>';
$out .= '<li><span class="fa fa-user"></span> People: '.get_post_meta(get_the_ID(), '_package_days_duration', true).'</li>';
$out .= '</ul>';
$excerpt_length = !empty($excerpt_length) ? $excerpt_length : 30;
$out .= dt_theme_excerpt($excerpt_length);
$out .= '<a href="'.get_permalink(get_the_ID()).'">'.__('Read More', 'iamd_text_domain').'</a>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
endwhile;
$out .= '</div>';
endif;
if($carousel == 'true') {
return '<div class="carousel_items">'
.$out
.'<div class="carousel-arrows">
<a class="prev-arrow" href="#"><span class="fa fa-angle-left"> </span></a>
<a class="next-arrow" href="#"><span class="fa fa-angle-right"> </span></a>
</div>
</div>';
} else {
return $out;
}
}
add_shortcode('dt_tourpackage_list', 'dt_tourpackage_list');
add_shortcode('dt_sc_tourpackage_list', 'dt_tourpackage_list');
}
//TOUR PACKAGES...
if(!function_exists('dt_latest_hotel_reviews')) {
function dt_latest_hotel_reviews( $atts, $content = null ) {
extract(shortcode_atts(array(
'limit' => '-1'
), $atts));
$out = "";
$comm_arr = get_comments( array('number' => $limit, 'post_type' => 'dt_hotels', 'status' => 'approve'));
if(count($comm_arr) > 0):
$out .= '<ul class="reviews-wrapper dt_carousel" data-items="1">';
foreach($comm_arr as $com) :
$out .= '<li>';
$out .= '<div class="review-thumb">';
$attr = array('title' => $com->post_title);
$out .= '<a href="'.get_permalink($com->ID).'">'.get_the_post_thumbnail($com->ID, array(100, 80), $attr).'</a>';
$out .= '</div>';
$out .= '<div class="review-detail">';
$hmeta = get_post_meta($com->ID ,'_hotel_settings', true);
$out .= '<h6><a href="'.get_permalink($com->ID).'">'.$com->post_title.', <sub>'.$hmeta['hotel_add'].'</sub></a></h6>';
$out .= '<i>'.get_comment_meta($com->comment_ID, 'title', true).'</i>';
$rate = get_comment_meta($com->comment_ID, 'rating', true);
$out .= '<div class="star-rating-wrapper">';
$out .= '<div class="star-rating">';
$out .= '<span style="width:'.(($rate/5)*100).'%"></span>';
$out .= '</div>';
$out .= '('.$rate.' '.__('out of 5', 'iamd_text_domain').')';
$out .= '</div>';
$out .= '<blockquote><q>"'.$com->comment_content.'"</q></blockquote>';
$out .= '<div class="author-detail">';
$out .= get_avatar($com->ID, 62);
$out .= '<cite>'.$com->comment_author.'<span>'.get_comment_meta($com->comment_ID, 'profession', true).'</span></cite>';
$out .= '</div>';
$out .= '</div>';
$out .= '</li>';
endforeach;
$out .= '</ul>';
return '<div class="carousel_items">'
.$out
.'<div class="carousel-arrows">
<a class="prev-arrow" href="#"><span class="fa fa-angle-left"> </span></a>
<a class="next-arrow" href="#"><span class="fa fa-angle-right"> </span></a>
</div>
</div>';
else:
return '<h2>'.__('No Reviews Found.', 'iamd_text_domain').'</h2>';
endif;
}
add_shortcode('dt_latest_hotel_reviews', 'dt_latest_hotel_reviews');
add_shortcode('dt_sc_latest_hotel_reviews', 'dt_latest_hotel_reviews');
}
//DESTINATION PLACE...
if(!function_exists('dt_destination_place')) {
function dt_destination_place( $atts, $content = null ) {
extract(shortcode_atts(array(
'place_id' => '1'
), $atts));
$out = "";
$args = array('post_type' => 'dt_places', 'p' => $place_id);
$the_query = new WP_Query($args);
$out .= '<div class="dt-travel-place-wrapper">';
if($the_query->have_posts()):
while($the_query->have_posts()): $the_query->the_post();
$out .= '<div class="dt-sc-two-third column first">';
$out .= '<div class="dt-sc-two-fifth column first">';
$out .= '<div class="place-thumb">';
$out .= '<div class="thumb-inner">';
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail(get_the_ID(), 'full', $attr);
$out .= '<div class="image-overlay">';
$out .= '<span class="image-overlay-inside"></span>';
$out .= '</div>';
$out .= '</a>';
$out .= '</div>';
$out .= '<a href="'.get_permalink().'" class="dt-sc-button too-small">'.__('View Gallery', 'iamd_text_domain').'</a>';
$out .= '</div>';
$out .= '</div>';
$out .= '<div class="place-details dt-sc-three-fifth column">';
$out .= '<h5><a href="'.get_permalink().'">'.get_the_title().'</a></h5>';
$pmeta = get_post_meta(get_the_ID() ,'_place_settings', true);
$out .= '<span class="subtitle">'.@$pmeta['place_add'].'</span>';
$out .= '<p>'.get_the_excerpt().'</p>';
$out .= '</div>';
$out .= '</div>';
$out .= '<div class="dt-sc-one-third column">';
#check hotels...
$harray = @array_filter($pmeta['place-hotels-list']);
if($harray != NULL):
$out .= '<div class="widget hotels-list-widget">';
$out .= '<h3 class="widgettitle">'.__('Hotels to Stay', 'iamd_text_domain').'</h3>';
$out .= '<div class="recent-hotels-widget">';
$out .= '<ul>';
foreach($harray as $hid):
$tpost = get_post($hid);
$attr = array('title' => $tpost->post_title);
$hmeta = get_post_meta($hid, '_hotel_settings', true);
$arr_rate = dt_theme_comment_rating_count($hid);
$all_avg = dt_theme_comment_rating_average($hid);
$out .= '<li>';
$out .= '<a class="thumb" href="'.get_permalink($hid).'">'.get_the_post_thumbnail($hid, array(100, 80), $attr).'</a>';
$out .= '<h6><a href="'.get_permalink($hid).'">'.$tpost->post_title.'</a> <sub>'.@$hmeta['hotel_add'].'</sub></h6>';
$out .= '<div class="star-rating-wrapper"><div class="star-rating"><span style="width:'.(($all_avg/5)*100).'%"></span></div>('.count($arr_rate).__(' Ratings', 'iamd_text_domain').')</div>';
$out .= '<a href="'.get_permalink($hid).'#hotel_map_'.$hid.'" class="map-marker"><span class="red"></span>'.__('View on Map', 'iamd_text_domain').'</a>';
$out .= '</li>';
endforeach;
$out .= '</ul>';
$out .= '</div>';
$out .= '</div>';
else:
$out .= '<h4>'.__('No Hotels Found.', 'iamd_text_domain').'</h4>';
$out .= '<p>'.__('Choose hotels from back-end to show in this section.', 'iamd_text_domain').'</h2>';
endif;
$out .= '</div>';
$out .= '<div class="read-more">';
$out .= '<a href="'.get_permalink().'">'.__('Read More', 'iamd_text_domain').'</a>';
$out .= '</div>';
endwhile;
else:
$out .= '<h4>'.__('No Place Found.', 'iamd_text_domain').'</h4>';
$out .= '<p>'.__('Put the correct place id from back end.', 'iamd_text_domain').'</h2>';
endif;
$out .= '</div>';
return $out;
}
add_shortcode('dt_destination_place', 'dt_destination_place');
add_shortcode('dt_sc_destination_place', 'dt_destination_place');
}
//BEST DESTINATION PLACE...
if(!function_exists('dt_best_destination_place')) {
function dt_best_destination_place( $atts, $content = null ) {
extract(shortcode_atts(array(
'place_ids' => '-1',
'carousel' => 'false'
), $atts));
$out = "";
$args = array('post_type' => 'dt_places', 'posts_per_page' => '-1', 'post__in' => explode(',', $place_ids));
$the_query = new WP_Query($args);
if($carousel == 'true')
$out .= '<div class="dt-best-entry-place-wrapper dt_carousel" data-items="1">';
else
$out .= '<div class="dt-best-entry-place-wrapper">';
if($the_query->have_posts()):
while($the_query->have_posts()): $the_query->the_post();
$out .= '<div class="dt-entry-place-item">';
$out .= '<div class="dt-sc-one-half column first">';
$out .= '<div class="entry-place-thumb">';
$out .= '<div class="thumb-inner">';
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail(get_the_ID(), 'full', $attr);
$out .= '<div class="image-overlay">';
$out .= '<span class="image-overlay-inside"></span>';
$out .= '</div>';
$out .= '</a>';
$out .= '</div>';
$out .= '<a href="'.get_permalink().'" class="dt-sc-button too-small">'.__('View Gallery', 'iamd_text_domain').'</a>';
$out .= '</div>';
$out .= '</div>';
$out .= '<div class="dt-sc-one-half column">';
$out .= '<div class="entry-place-detail">';
$out .= '<div class="entry-place-title">';
$out .= '<div class="float-left">';
$out .= '<h5><a href="'.get_permalink().'">'.get_the_title().'</a></h5>';
$pmeta = get_post_meta(get_the_ID() ,'_place_settings', true);
$out .= '<p>'.@$pmeta['place_add'].'</p>';
$out .= '</div>';
$arr_rate = dt_theme_comment_rating_count(get_the_ID());
$all_avg = dt_theme_comment_rating_average(get_the_ID());
$out .= '<div class="star-rating-wrapper float-right"><div class="star-rating"><span style="width:'.(($all_avg/5)*100).'%"></span></div>('.count($arr_rate).__(' Ratings', 'iamd_text_domain').')</div>';
$out .= '</div>';
$out .= '<h6>'.__('Why it is best?', 'iamd_text_domain').'</h6>';
$out .= dt_theme_excerpt(20);
$out .= '<div class="dt-sc-hr-invisible-small"></div>';
$out .= '<h6>'.__('Hotels to Stay', 'iamd_text_domain').'</h6>';
$out .= '<div class="entry-place-meta">';
$harray = @array_filter($pmeta['place-hotels-list']);
if($harray != NULL):
$out .= '<ul>';
foreach($harray as $hid):
$tpost = get_post($hid);
$attr = array('title' => $tpost->post_title);
$hmeta = get_post_meta($hid, '_hotel_settings', true);
$arr_rate = dt_theme_comment_rating_count($hid);
$all_avg = dt_theme_comment_rating_average($hid);
$out .= '<li>';
$out .= '<ul>';
$out .= '<li><p>'.$tpost->post_title.', <sub>'.@$hmeta['hotel_add'].'</sub></p></li>';
$out .= '<li><a href="'.get_permalink($hid).'#hotel_map_'.$hid.'" class="map-marker small"><span class="red"></span>'.__('View on Map', 'iamd_text_domain').'</a></li>';
$out .= '</ul>';
$out .= '<div class="star-rating-wrapper"><div class="star-rating"><span style="width:'.(($all_avg/5)*100).'%"></span></div>('.count($arr_rate).__(' Ratings', 'iamd_text_domain').')</div>';
$out .= '</li>';
endforeach;
$out .= '</ul>';
$out .= '<a href="'.get_permalink().'" class="aligncenter">'.__('Read More', 'iamd_text_domain').'</a>';
else:
$out .= '<h4>'.__('No Hotels Found.', 'iamd_text_domain').'</h4>';
$out .= '<p>'.__('Choose hotels from back-end to show in this section.', 'iamd_text_domain').'</h2>';
endif;
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
endwhile;
else:
$out .= '<h4>'.__('No Place Found.', 'iamd_text_domain').'</h4>';
$out .= '<p>'.__('Put the correct place ids from back end.', 'iamd_text_domain').'</h2>';
endif;
$out .= '</div>';
if($carousel == 'true') {
return '<div class="carousel_items">'
.$out
.'<div class="carousel-arrows">
<a class="prev-arrow" href="#"><span class="fa fa-angle-left"> </span></a>
<a class="next-arrow" href="#"><span class="fa fa-angle-right"> </span></a>
</div>
</div>';
} else {
return $out;
}
}
add_shortcode('dt_best_destination_place', 'dt_best_destination_place');
add_shortcode('dt_sc_best_destination_place', 'dt_best_destination_place');
}
//CONTACT SUPPORT SECTION...
if(!function_exists('dt_support_section')) {
function dt_support_section( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
'link' => '#',
'phone' => '',
'image' => ''
), $atts));
$out = "";
$out .= '<div class="support-info">';
if($title != '')
$out .= '<h2 class="section-title">'.$title.'</h2>';
if($content != '')
$out .= '<p>'.do_shortcode($content).'</p>';
if($phone != '')
$out .= '<a class="dt-sc-button medium" href="'.$link.'"><span class="fa fa-phone"></span>'.$phone.'</a>';
if($image != '')
$out .= '<img alt="'.__('support_img', 'iamd_text_domain').'" src="'.$image.'">';
$out .= '</div>';
return $out;
}
add_shortcode('dt_support_section', 'dt_support_section');
add_shortcode('dt_sc_support_section', 'dt_support_section');
}
//RECOMMENDED PLACES...
if(!function_exists('dt_recommend_places')) {
function dt_recommend_places( $atts, $content = null ) {
extract(shortcode_atts(array(
'limit' => '-1',
'posts_column' => 'one-fourth' // one-half, one-third, one-fourth
), $atts));
$out = "";
$args = array('orderby' => 'rand', 'post_type' => 'dt_places', 'posts_per_page' => $limit);
$the_query = new WP_Query($args);
if($the_query->have_posts()):
if($the_query->post_count == 2):
$maxitems = 2;
elseif($the_query->post_count == 3):
$maxitems = 3;
elseif($the_query->post_count >= 4):
if($posts_column == 'one-half'):
$posts_column = 'dt-sc-one-half';
$maxitems = 2;
elseif($posts_column == 'one-third'):
$posts_column = 'dt-sc-one-third';
$maxitems = 3;
else:
$posts_column = 'dt-sc-one-fourth';
$maxitems = 4;
endif;
endif;
$out .= '<div class="carousel_items">';
$out .= '<div class="dt-sc-places-wrapper dt_carousel" data-items="'.$maxitems.'">';
while($the_query->have_posts()): $the_query->the_post();
$place_meta = get_post_meta(get_the_id() ,'_place_settings', true);
$out .= '<div class="'.$posts_column.' column">';
$out .= '<div class="place-item">';
$out .= '<div class="place-thumb">';
if( has_post_thumbnail() ):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail(get_the_id(), 'place-thumb', $attr);
$out .= '<div class="image-overlay">';
$out .= '<span class="image-overlay-inside"></span>';
$out .= '</div>';
$out .= '</a>';
endif;
$out .= '</div>';
$out .= '<div class="place-detail-wrapper">';
$out .= '<div class="place-title">';
$out .= '<h5><a href="'.get_permalink().'">'.get_the_title().'</a></h5>';
$out .= '<p>'.@$place_meta['place_add'].'</p>';
$out .= '</div>';
$out .= '<div class="place-content">';
$out .= '<a class="map-marker" href="'.get_permalink().'#place_map_'.get_the_ID().'"> <span class="red"></span>'.__('View on Map', 'iamd_text_domain').'</a>';
$out .= '<a class="dt-sc-button too-small" href="'.get_permalink().'">'.__('View details', 'iamd_text_domain').'</a>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
endwhile;
$out .= '</div>';
$out .= '<div class="carousel-arrows">';
$out .= '<a class="prev-arrow" href="#"><span class="fa fa-angle-left"> </span></a>';
$out .= '<a class="next-arrow" href="#"><span class="fa fa-angle-right"> </span></a>';
$out .= '</div>';
$out .= '</div>';
endif;
return $out;
}
add_shortcode('dt_recommend_places', 'dt_recommend_places');
add_shortcode('dt_sc_recommend_places', 'dt_recommend_places');
}
//FEATURE ICON...
if(!function_exists('dt_feature_icon')) {
function dt_feature_icon( $atts, $content = null ) {
extract(shortcode_atts(array(
'icon' => '',
'text' => ''
), $atts));
$out = "";
$out .= '<p class="dt-feature-icon"><span class="fa fa-'.$icon.'"></span>'.$text.'</p>';
return $out;
}
add_shortcode('dt_feature_icon', 'dt_feature_icon');
add_shortcode('dt_sc_feature_icon', 'dt_feature_icon');
}
//INTRO TEXT...
if(!function_exists('dt_intro_text')) {
function dt_intro_text( $atts, $content = null ) {
extract(shortcode_atts(array(
'type' => ''
), $atts));
$out = "";
$out .= '<div class="introtext '.$type.'">'.do_shortcode($content).'</div>';
return $out;
}
add_shortcode('dt_intro_text', 'dt_intro_text');
add_shortcode('dt_sc_intro_text', 'dt_intro_text');
}
//TIMELINE SHORTCODE...
if(!function_exists('dt_timeline_posts')) {
function dt_timeline_posts( $atts, $content = null ) {
extract(shortcode_atts(array(
'limit' => -1
), $atts));
$out = '';
$lrclass = 'left';
$args = array('post_type' => 'post', 'posts_per_page' => $limit);
$the_query = new WP_Query($args);
if($the_query->have_posts()):
$out .= '<div class="dt-timeline-posts-wrapper">';
$out .= '<div id="dt-timeline-posts">';
while($the_query->have_posts()): $the_query->the_post();
$out .= '<div class="dt-timeline-post '.$lrclass.'">';
$out .= '<div class="dt-sc-one-half column first">';
$out .= '<div class="dt-timeline-content">';
$out .= '<div class="dt-timeline-tilte"><h2><a href="'.get_permalink().'">'.get_the_title().'</a><span></span></h2></div>';
$out .= dt_theme_excerpt(30);
$out .= '</div>';
$out .= '</div>';
$out .= '<div class="dt-sc-one-half column">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail(get_the_id(), 'thumb', $attr);
$out .= '</div>';
$out .= '</div>';
if($lrclass == 'left') $lrclass = 'right'; else $lrclass = 'left';
endwhile;
$out .= '</div>';
$out .= '</div>';
endif;
return $out;
}
add_shortcode('dt_timeline_posts', 'dt_timeline_posts');
add_shortcode('dt_sc_timeline_posts', 'dt_timeline_posts');
}
//CUSTOM ICON BOXES...
if(!function_exists('dt_theme_iconbox')) {
function dt_theme_iconbox( $atts, $content = null ) {
extract(shortcode_atts(array(
'icon' => '',
'title' => '',
'text' => ''
), $atts));
$out = "";
$out .= '<div class="dt-sc-ico">';
if($icon != '')
$out .= '<span class="fa fa-'.$icon.'"></span>';
if($title != '')
$out .= '<h5>'.$title.'</h5>';
if($text != '')
$out .= '<p>'.$text.'</p>';
$out .= '</div>';
return $out;
}
add_shortcode('dt_theme_iconbox', 'dt_theme_iconbox');
add_shortcode('dt_sc_theme_iconbox', 'dt_theme_iconbox');
}
//HOTEL ROOM...
if(!function_exists('dt_hotel_room')) {
function dt_hotel_room( $atts, $content = null ) {
extract(shortcode_atts(array(
'room_type' => '',
'persons' => '',
'facilities' => '',
'price' => '',
'available' => ''
), $atts));
$out = '';
$out .= '<div class="dt-hotel-room-wrapper">';
$out .= '<ul>';
$out .= '<li class="room-name"> <span class="fa fa-building-o"></span> <a href="#">'.$room_type.'</a></li>';
$out .= '<li class="room-persons"> <span class="fa fa-users"></span> '.$persons.' </li>';
$out .= '<li class="room-details"> <span class="fa fa-bell"></span> '.$facilities.' </li>';
$out .= '<li>';
$out .= '<div class="hotel-thumb-meta">';
$out .= '<div class="hotel-price">';
$out .= __('Starts From', 'iamd_text_domain').' <span>'.$price.'</span>';
$out .= '</div>';
$out .= '<span class="hotel-option-type">';
$out .= '<a href="#">'.$available.'</a>';
$out .= '</span>';
$out .= '</div>';
$out .= '</li>';
$out .= '</ul>';
$out .= '</div>';
return $out;
}
add_shortcode('dt_hotel_room', 'dt_hotel_room');
add_shortcode('dt_sc_hotel_room', 'dt_hotel_room');
}
//CUSTOM TIMELINE POST...
if(!function_exists('dt_history_entry')) {
function dt_history_entry( $atts, $content = null ) {
extract(shortcode_atts(array(
'align' => 'left',
'title' => '',
'link' => '',
'image' => 'http://placehold.it/150x200'
), $atts));
$out = '';
$out .= '<div class="dt-timeline-post '.$align.'">';
$out .= '<div class="dt-sc-one-half column first">';
$out .= '<div class="dt-timeline-content">';
$out .= '<div class="dt-timeline-tilte"><h2><a href="'.$link.'">'.$title.'</a><span></span></h2></div>';
$out .= do_shortcode($content);
$out .= '</div>';
$out .= '</div>';
$out .= '<div class="dt-sc-one-half column">';
$out .= '<img src="'.$image.'" alt="'.$title.'" title="'.$title.'" />';
$out .= '</div>';
$out .= '</div>';
return $out;
}
add_shortcode('dt_history_entry', 'dt_history_entry');
}
//CUSTOM TIMELINE WRAPPER...
if(!function_exists('dt_history_wrapper')) {
function dt_history_wrapper( $atts, $content = null ) {
$out = '';
$out .= '<div class="dt-timeline-posts-wrapper">';
$out .= '<div id="dt-timeline-posts">';
$out .= do_shortcode($content);
$out .= '</div>';
$out .= '</div>';
return $out;
}
add_shortcode('dt_history_wrapper', 'dt_history_wrapper');
}
//HOLIDAY PACKAGE...
if(!function_exists('dt_holiday_ads')) {
function dt_holiday_ads( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
'subtitle' => '',
'link' => '',
'image' => 'http://placehold.it/232x224',
'button_text' => __('Hurry Book', 'iamd_text_domain')
), $atts));
$out = '';
$out .= '<div class="holioday-pack-wrapper">';
$out .= '<div class="holioday-pack">';
$out .= '<h3>'.$title.'<br> <span>'.$subtitle.'</span></h3>';
$out .= '<img src="'.$image.'" alt="holiday-img" />';
$out .= '<h2><a href="'.$link.'">'.$button_text.'<br> <span>'.__('Now', 'iamd_text_domain').'</span></a></h2>';
$out .= '</div>';
$out .= '</div>';
return $out;
}
add_shortcode('dt_holiday_ads', 'dt_holiday_ads');
}
//THEME STATISTICS...
if(!function_exists('dt_theme_status')) {
function dt_theme_status( $atts, $content = null ) {
extract(shortcode_atts(array(
'number' => '',
'text' => ''
), $atts));
$out = '';
$out .= '<p><span>'.$number.'</span> '.$text.'</p>';
return $out;
}
add_shortcode('dt_theme_status', 'dt_theme_status');
}
//SUBSCRIBE SHORTCODE...
if(!function_exists('dt_subscribe_form')) {
function dt_subscribe_form( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
'subtitle' => '',
'list_id' => ''
), $atts));
$out = '';
$out .= '<div class="dt-footer-newsletter">';
if($title != "")
$out .= '<h3 class="widgettitle">'.$title.'</h3>';
if($subtitle != "")
$out .= '<p>'.$subtitle.'</p>';
$out .= '<form name="frmsubscribe" method="post" class="subscribe-frm">';
$out .= '<input type="email" name="mythem_mc_emailid" required="" placeholder="'.__('Enter Email', 'iamd_text_domain').'" />';
$out .= "<input type='hidden' name='mythem_mc_listid' value='".$list_id."' />";
$out .= '<input type="submit" name="submit" class="dt-sc-button small" value="'.__('Subscribe', 'iamd_text_domain').'" />';
$out .= '</form>';
if( isset( $_REQUEST['mythem_mc_emailid']) ):
require_once(IAMD_FW."theme_widgets/mailchimp/MCAPI.class.php");
$mcapi = new MCAPI( dt_theme_option('general','mailchimp-key') );
$merge_vars = Array( 'EMAIL' => $_REQUEST['mythem_mc_emailid'] );
if($mcapi->listSubscribe($list_id, $_REQUEST['mythem_mc_emailid'], $merge_vars ) ):
$msg = '<span style="color:green;">'.__('Success! Check your inbox or spam folder for a message containing a confirmation link.', 'iamd_text_domain').'</span>';
else:
$msg = '<span style="color:red;"><b>'.__('Error:', 'iamd_text_domain').'</b> ' . $mcapi->errorMessage.'</span>';
endif;
if ( isset ( $msg ) ) $out .= '<span class="zn_mailchimp_result">'.$msg.'</span>';
endif;
$out .= '</div>';
return $out;
}
add_shortcode('dt_subscribe_form', 'dt_subscribe_form');
}
//IMAGE MAP CONTAINER...
if(!function_exists('dt_image_map_container')) {
function dt_image_map_container( $atts, $content = null ) {
extract(shortcode_atts(array(
'bg_image' => 'http://placehold.it/1031x600&text=Map%20Image'
), $atts));
$out = '';
$out .= '<div id="dt-image-map-container"><img src="'.$bg_image.'" />'.do_shortcode($content).'</div>';
return $out;
}
add_shortcode('dt_image_map_container', 'dt_image_map_container');
}
//IMAGE MAP POINTER...
if(!function_exists('dt_image_map_pointer')) {
function dt_image_map_pointer( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
'top' => '162',
'left' => '574',
'color' => 'blue'
), $atts));
$out = '';
$style = "style='left:{$left}px; top:{$top}px;'";
$divID = mt_rand();
$out .= '<a href="#div_id_'.$divID.'" class="dt-sc-map-tooltip dt-map-pointer '.$color.'" title="'.$title.'" '.$style.'></a>';
$out .= '<div id="div_id_'.$divID.'" class="dt-pointer-content" style="display:none;">'.do_shortcode($content).'</div>';
return $out;
}
add_shortcode('dt_image_map_pointer', 'dt_image_map_pointer');
} ?> | gpl-2.0 |
Hacksign/configs | .config/awesome/configs/init.lua | 3645 | local gears = require("gears")
local awful = require("awful")
local wibox = require("wibox")
local widgets = require("widgets")
local beautiful = require("beautiful")
local naughty = require("naughty")
local xresources = require("beautiful.xresources")
local dpi = xresources.apply_dpi
local mytaglist = {}
-- Mouse Click event
mytaglist.buttons = awful.util.table.join(
awful.button({ }, 1, awful.tag.viewonly),
awful.button({ }, 3, awful.tag.viewtoggle)
)
-- {{{ Variable definitions
-- Themes define colours, icons, and wallpapers
editor = os.getenv("EDITOR") or "vim"
modkey = "Mod4"
-- }}}
beautiful.init(os.getenv("HOME") .. "/.config/awesome/themes/arch/theme.lua")
if beautiful.wallpaper then
for s = 1, screen.count() do
gears.wallpaper.fit(beautiful.wallpaper, s, beautiful.bg_normal)
end
end
for s in screen do
awful.tag(
{"Work"},
s,
awful.layout.suit.floating
)
end
-- {{{ Wibox
-- Create a wibox for each screen and add it
mylayoutbox = {}
mytasklist = {}
-- mouse click event handler
mytasklist.buttons = awful.util.table.join(
awful.button({ }, 1, function (c)
if c == client.focus then
c.minimized = true
else
-- Without this, the following
-- :isvisible() makes no sense
c.minimized = false
if not c:isvisible() then
awful.tag.viewonly(c:tags()[1])
end
-- This will also un-minimize
-- the client, if needed
client.focus = c
c:raise()
end
end)
)
-- mouse event handler end
-- top & battom bar widgets
local cpuwidget = widgets.cpu(
{
width = 175,
interval = 3,
step_width = 2,
step_spacing = 1,
theme = beautiful,
}
)
local memwidget = widgets.memory
local batterywidget = widgets.battery
local networkwidget = widgets.network
local temperaturewidget = widgets.temperature
local weatherwidget = widgets.weather.init(
{
interval = 5,
theme = beautiful
}
)
updateScreens = widgets.screenful.init()
for s = 1, screen.count() do
if screen[s] == screen.primary then
-- We need one layoutbox per screen.
mylayoutbox[s] = awful.widget.layoutbox(s)
-- Create a taglist widget
mytaglist[s] = awful.widget.taglist(
s,
awful.widget.taglist.filter.all,
mytaglist.buttons
)
-- Create the wibox
local topBar = {}
topBar[s] = awful.wibar(
{
position = "top",
screen = s
}
)
-- Widgets that are aligned to the left
local left_layout = wibox.layout.fixed.horizontal()
left_layout:add(mytaglist[s])
left_layout:add(weatherwidget)
-- Widgets that are aligned to the right
local right_layout = wibox.layout.fixed.horizontal()
right_layout.spacing = dpi(2)
right_layout:add(networkwidget)
right_layout:add(temperaturewidget)
if batterywidget then
right_layout:add(batterywidget)
end
right_layout:add(memwidget)
right_layout:add(cpuwidget)
if s == 1 then
right_layout:add(wibox.widget.systray())
end
right_layout:add(mylayoutbox[s])
-- Now bring it all together (with the tasklist in the middle)
local layout = wibox.layout.align.horizontal()
layout:set_left(left_layout)
layout:set_right(right_layout)
topBar[s]:set_widget(layout)
end
end
| gpl-2.0 |
gaoxiaojun/dync | src/share/vm/logging/logTagLevelExpression.hpp | 2620 | /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_LOGGING_LOGTAGLEVELEXPRESSION_HPP
#define SHARE_VM_LOGGING_LOGTAGLEVELEXPRESSION_HPP
#include "logging/logConfiguration.hpp"
#include "logging/logLevel.hpp"
#include "logging/logTag.hpp"
#include "memory/allocation.hpp"
#include "utilities/debug.hpp"
#include "utilities/globalDefinitions.hpp"
class LogTagSet;
// Class used to temporary encode a 'what'-expression during log configuration.
// Consists of a combination of tags and levels, e.g. "tag1+tag2=level1,tag3*=level2".
class LogTagLevelExpression : public StackObj {
friend void LogConfiguration::configure_stdout(LogLevelType, bool, ...);
private:
static const size_t MaxCombinations = 32;
static const char* DefaultExpressionString;
size_t _ntags, _ncombinations;
LogTagType _tags[MaxCombinations][LogTag::MaxTags];
LogLevelType _level[MaxCombinations];
bool _allow_other_tags[MaxCombinations];
void new_combination() {
_ncombinations++;
_ntags = 0;
}
void add_tag(LogTagType tag) {
assert(_ntags < LogTag::MaxTags, "Can't have more tags than MaxTags!");
_tags[_ncombinations][_ntags++] = tag;
}
void set_level(LogLevelType level) {
_level[_ncombinations] = level;
}
void set_allow_other_tags() {
_allow_other_tags[_ncombinations] = true;
}
void clear();
public:
LogTagLevelExpression() : _ntags(0), _ncombinations(0) {
}
bool parse(const char* str, outputStream* errstream = NULL);
LogLevelType level_for(const LogTagSet& ts) const;
};
#endif // SHARE_VM_LOGGING_LOGTAGLEVELEXPRESSION_HPP
| gpl-2.0 |
pastebt/yeast | yeast/cache.py | 4235 | #! /usr/bin/python
import sys
from socket import socket
from heapq import heappop, heappush
from acore import Acore, Worker
class Cache(Acore):
def __init__(self, timeout=120):
self.timeout = timeout
# key : (last, dat)
self.dat_map = {}
# (last, dat)
self.dat_que = []
def get(self, key):
# query data with key
ret = self.dat_map.get(key)
if not ret:
return ret
ts = self.last_time + self.timeout
heappush(self.dat_que, (ts, key))
if ts > ret[0]:
self.dat_map[key] = (ts, ret[1])
return ret[1]
def pop(self, key, default=None):
return self.dat_map.pop(key, default)
def put(self, key, data):
# save data with key
ts = self.last_time + self.timeout
heappush(self.dat_que, (ts, key))
self.dat_map[key] = (ts, data)
def chk(self):
# check if any data expire and clean
while len(self.dat_que):
ts, key = heappop(self.dat_que)
if ts > self.last_time:
heappush((ts, key))
return
last, dat = self.dat_map.pop(key, (0, None))
if last > ts:
self.dat_map[key] = (last, dat)
def run(self):
ts = max(self.timeout / 10, 1)
while True:
for y in self.sleep(ts):
yield y
self.chk()
class DiskCache(Cache):
""" will save cache in disk """
def __init__(self, filename, timeout=120):
Cache.__init__(self, timeout)
def save_to(self, key, value):
pass
def get_from(self, key):
pass
def close(self):
pass
class CacheWorker(Worker):
""" A Cache worker accept GET and PUT via tcp connect """
cache = None
dispatcher = None
def run(self):
for y in self.read_exactly(self, seps=('\n',)):
yield y
cmd, l = self.rdata.split(None, 1)
size = len(l.strip())
for y in self.read_exactly(self, size=int(self.rdata.strip())):
yield y
if cmd == 'GET':
data = self.cache.get(self.rdata)
for y in self.writeall(self.sock, "%d\n%s" % (len(data), data)):
yield y
elif cmd == 'PUT':
key, value = self.rdata.split('\n', 1)
self.cache.put(key, value)
for y in self.writeall(self.sock, "2\nOK"):
yield y
elif cmd == 'STOP':
if hasattr(selr.cache, 'close'):
self.cache.close()
self.dispatcher.running = False
def start_cache_server(addr=('', 1234), filename=''):
""" A TCP server accept GET and PUT cache request """
if filename:
CacheWorker.cache = DiskCache("filename")
else:
CacheWorker.cache = Cache()
l = Listern(addr, CacheWorker)
CacheWorker.dispatcher = l
l.start()
l.loop()
class CacheClient(Acore):
"""
cache protocol is:
GET nnn\npickled string
PUT nnn\npickled string
"""
svr_addr = ('127.0.01', 1234)
def __init__(self):
Acore.__init__(self)
self.cache_key = ''
self.cache_data = ''
self.running = True
def get(self, key):
self.post(self, "GET %d\n%s" % (len(key), key))
yield self.WAIT_POST
self.cache_key = key
self.cache_data = self._data
def put(self, key, value):
dat = "%s\n%s" % (key, value)
self.post(self, "PUT %d\n%s" % (len(dat), dat))
yield self.WAIT_POST
def stop(self):
self.running = False
self.post(self)
def run_one(self):
for y in self.writeall(self.sock, self._data):
yield y
self.rdata_left = ''
for y in self.read_exactly(self, seps=('\n',)):
yield y
for y in self.read_exactly(self, size=int(self.rdata.strip())):
yield y
self.post(self, self.rdata)
def run(self):
self.sock = socket()
self.sock.connect(self.svr_addr)
while self.running:
yield self.WAIT_POST
if not self._data:
continue
for y in self.run_one():
yield y
| gpl-2.0 |
braunsg/manifold-impact-analytics | inc/resources/resources-content/h_index_demo.php | 7635 | <!--
manifold-impact-analytics
https://github.com/braunsg/manifold-impact-analytics
Open source code for Manifold, an automated impact analytics and visualization platform developed by
Steven Braun.
COPYRIGHT (C) 2015 Steven Braun
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.
A full copy of the license is included in LICENSE.md.
//////////////////////////////////////////////////////////////////////////////////////////
/////// About this file
A visualization based on D3.js that helps explain how the h-index is calculated
-->
<style>
#hChart, #hflChart {
font-family: Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif;
}
.xAxis {
stroke:black;
fill: none;
shape-rendering: crispEdges;
}
.yAxis {
stroke:black;
fill: none;
shape-rendering: crispEdges;
}
.xAxis text, .yAxis text {
stroke: none;
fill: black;
font-size: 11px;
}
.axisLabel {
stroke: none;
fill: black;
font-size: 13px;
font-weight: bold;
}
.hLine {
stroke:black;
stroke-width: 2;
}
.dashLine {
stroke:black;
stroke-width: 2;
}
.specialMarker {
font-family: sans-serif;
font-weight: bold;
font-size: 20px;
fill: red;
stroke:none;
}
#start_animation {
cursor: pointer;
}
</style>
<script>
var selection = "<?php echo $selection; ?>";
// Define basic parameters
var windowPadding = {top:50, left:50, right:50, bottom:50},
windowWidth = window.innerWidth - windowPadding.left - windowPadding.right,
windowHeight = window.innerHeight - windowPadding.top - windowPadding.bottom;
// For each individual chart
var margin = {top:15, left:50, right:15, bottom:50};
var width = $("#" + selection).width(),
height = 350,
barWidth = 15,
barPadding = 30; //15
var keyPress = 0;
var transitions = [];
var data = [];
getData = $.get("inc/resources/resources-content/data.txt",function(getData) {
var lines = getData.split("\n");
for(var i = 0; i < lines.length; i++) {
data.push(Number(lines[i].trim()));
}
var min = Math.min.apply(null,data);
var max = Math.max.apply(null,data);
// Define transitions //
// transitions = [transition_0, transition_1, transition_2, transition_3, transition_4, transition_5, transition_6, transition_7, transition_8];
transitions = [transition_0, transition_1, transition_2, transition_3];
function transition_0() {
h_bars.transition()
.duration(250)
.ease("quad")
.delay(function(d,i) {
return i*100;
})
.attr("x", function(d,i) { return xScale(sortedIndexArray[i]+1) + (barWidth/2); })
.each("end", function(d,i) {
if(i == data.length-1) {
h_xAxisLine.selectAll("text")
.transition()
.duration(1000)
.style("fill","black");
h_xAxisLabel.text("Published Papers -- Rank Order");
}
});
}
function transition_1() {
hLine.transition()
.duration(1000)
.attr("x2",xScale(data.length)+barWidth)
.attr("y2",yScale(data.length));
}
function transition_2() {
h_bars.transition()
.duration(100)
.delay(function(d,i) {
var k = sortedIndexArray[i];
return k*100;
})
.style("fill",function(d,i) {
var k = sortedIndexArray[i];
if((k+1) <= hIndex) {
return "blue";
} else {
return "gray";
}
});
}
function transition_3() {
var h_dashLine = hChart.append("line")
.attr("class","dashLine")
.style("stroke-dasharray",("3, 3"))
.attr("x1",xScale(hIndex) + barWidth)
.attr("y1", yScale(hIndex))
.attr("x2",xScale(hIndex) + barWidth)
.attr("y2",yScale(hIndex));
h_dashLine.transition()
.duration(1000)
.attr("x2",margin.left)
.attr("y2",yScale(hIndex))
.each("end",function() {
hChart.append("text")
.attr("class","specialMarker")
.attr("x",25)
.attr("y",yScale(hIndex)+7)
.attr("text-anchor","middle")
.text(hIndex);
start_button.text("Restart");
});
}
// Define chart parameters
var xLabels = d3.range(1,data.length+1);
var xScale = d3.scale.ordinal()
.domain(xLabels)
.rangeRoundBands([margin.left, width-margin.right],0,0.25);
// .range(data);
// .range([margin.left+barPadding,width-margin.right]);
var yScale = d3.scale.linear()
.domain([min, max])
.range([height-margin.bottom, margin.top]);
var xAxis = d3.svg.axis()
.orient("bottom")
.ticks(10)
// .tickFormat(function(d,i) {
// return xLabels[i];
// })
.scale(xScale);
var yAxis = d3.svg.axis()
.orient("left")
.ticks(max/20)
.scale(yScale);
var barWidth = xScale.rangeBand()/2;
function vis_reset() {
if(typeof svg !== "undefined") {
svg.remove();
}
svg = d3.select("#" + selection).append("svg")
.attr("width",width)
.attr("height",height);
hChart = svg.append("g")
.attr("id","hChart")
.attr("width",width)
.attr("height",height);
h_bars = hChart.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("class","dataBar")
.attr("x",function(d,i) {
return xScale(i+1) + barWidth/2;
})
.attr("y",function(d) { return yScale(d); })
.attr("width",barWidth)
.attr("height",function(d) { return (height-margin.bottom) - yScale(d); });
h_xAxisLine = hChart.append("g")
.attr("class","xAxis")
.attr("transform","translate(" + 0 + "," + (height-margin.bottom) + ")")
.call(xAxis);
h_xAxisLine.selectAll("text")
.style("fill","#fff");
h_yAxisLine = hChart.append("g")
.attr("class","yAxis")
.attr("transform","translate(" + margin.left + "," + 0 + ")")
.call(yAxis);
h_xAxisLabel = hChart.append("text")
.attr("class","axisLabel")
.attr("x",margin.left + (width-margin.left-margin.right)/2)
.attr("y",height-15)
.attr("text-anchor","middle")
.text("Published Papers -- By Time");
h_yAxisLabel = hChart.append("text")
.attr("class","axisLabel")
.attr("text-anchor","middle")
.attr("transform","rotate(-90)")
.attr("y",15)
.attr("x",-(margin.top+(height-margin.top-margin.bottom)/2))
.text("Citation Count");
start_button = hChart.append("text")
.attr("id","start_animation")
.attr("text-anchor","end")
.attr("y",10)
.attr("x",width-margin.right)
.text("Start");
hLine = hChart.append("line")
.attr("class","hLine")
.attr("x1",margin.left)
.attr("y1",height-margin.bottom)
.attr("x2",margin.left)
.attr("y2",height-margin.bottom);
start_button.on("click", function() {
if(keyPress == 0) {
start_button.text("Next");
}
if (keyPress > 3) {
vis_reset();
keyPress = 0;
} else if (keyPress <= 3) {
svg.call(transitions[keyPress]);
keyPress++;
}
});
}
vis_reset();
// Now transition to rank-ordering papers
var sortedData = data.slice(0);
sortedData.sort(function(a,b) {
return b-a;
});
var hIndex = 0;
var counter = 0;
for(var j = 0; j < sortedData.length; j++) {
counter++;
if(sortedData[j] >= counter) {
hIndex++;
} else {
break;
}
}
var sortedIndexArray = [];
for(var i = 0; i < data.length; i++) {
var k = sortedData.indexOf(data[i]);
sortedIndexArray.push(k);
sortedData[k] = null;
}
});
</script> | gpl-2.0 |
AlexYuriy/store | test_yuriiq/catalog/language/russian/total/voucher.php | 88 | <?php
// text
$_['text_voucher'] = 'Подарочный Сертификат (%s)';
?> | gpl-2.0 |
yelu/leetcode | RestoreIPAddresses.py | 839 | def validIP(ip) :
for e in ip :
if int(e) > 255 :
return False
if len(e) > 1 and e.startwith('0'):
return False
return True
class Solution:
# @param s, a string
# @return a list of strings
def permutation(self, s, m) :
if m >= 4 :
return [] if s else [[]]
result = []
for i in range(1, min(4, len(s)+1)) :
for ele in self.permutation(s[i:], m+1) :
ele.append(s[0:i])
result.append(ele)
return result
def restoreIpAddresses(self, s):
result = self.permutation(s, 0)
result = map(lambda e : e[-1::-1], result)
result = filter(validIP, result)
return map(lambda e: '.'.join(e), result)
s = '25525511135'
sol = Solution()
print sol.restoreIpAddresses(s)
| gpl-2.0 |
VinceRafale/lifeguide | wp-content/plugins/Tevolution/wp-updates-plugin.php | 5050 | <?php
/*
WPUpdates Plugin Updater Class
http://wp-updates.com
v1.3
Example Usage:
require_once('wp-updates-plugin.php');
new WPUpdatesPluginUpdater( 'http://wp-updates.com/api/1/plugin', 1, plugin_basename(__FILE__) );
*/
if( !class_exists('WPUpdatesTevolutionUpdater') ) {
class WPUpdatesTevolutionUpdater {
var $api_url;
var $plugin_path;
var $plugin_slug=TEVOLUTION_SLUG;
var $plugin_version=TEVOLUTION_VERSION;
function __construct( $api_url, $plugin_path ) {
$plugin_path = plugin_dir_path( __FILE__ );
$plugin_file = $plugin_path ."templatic.php";
$plugin_data = get_plugin_data( $plugin_file, $markup = true, $translate = true );
$plugin_version = $plugin_data['Version'];
$this->api_url = $api_url;
$this->plugin_path = $plugin_path;
if(strstr($plugin_path, '/')) list ($t1, $t2) = explode('/', $plugin_path);
else $t2 = $plugin_path;
add_filter( 'pre_set_site_transient_update_plugins', array(&$this, 'tevolution_check_for_update') );
add_filter( 'plugins_api', array(&$this, 'tevolution_plugin_api_call'), 10, 3 );
// This is for testing only!
set_site_transient( 'update_plugins', null );
if ( is_network_admin() || !is_multisite() ) {
add_action('after_plugin_row_'.TEVOLUTION_SLUG, array(&$this, 'tevolution_templatic_plugin_row') );
}
}
/*
* add action for set the auto update for tevolution plugin
* Functio Name: tevolution_plugin_row
* Return : Display the plugin new version update message
*/
function tevolution_templatic_plugin_row()
{
//check the remote version
global $plugin_response;
$remote_version=$plugin_response[TEVOLUTION_SLUG]['new_version'];
if (version_compare($this->plugin_version , $remote_version, '<'))
{
$new_version = version_compare($this->plugin_version , $remote_version, '<') ? __('There is a new version of tevolution plugin available ', DOMAIN): '';
$ajax_url = esc_url( add_query_arg( array( 'slug' => 'tevolution', 'action' => 'tevolution' , '_ajax_nonce' => wp_create_nonce( 'tevolution' ), 'TB_iframe' => true ,'width'=>500,'height'=>400), admin_url( 'admin-ajax.php' ) ) );
$file='Tevolution/templatic.php';
$download= wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=').$file, 'upgrade-plugin_' . $file);
echo '<tr class="plugin-update-tr"><td colspan="3" class="plugin-update"><div class="update-message">' . $new_version . __( ' <a href="'.$ajax_url.'" class="thickbox" title="Templatic Tevolution Update">update now</a>.', DOMAIN) .'</div></td></tr>';
}
}
function tevolution_check_for_update( $transient ) {
global $plugin_response,$wp_version;
if (empty($transient->checked)) return $transient;
$request_args = array(
'slug' => $this->plugin_slug,
'version' => $transient->checked[$this->plugin_slug]
);
$request_string = $this->tevolution_prepare_request( 'templatic_plugin_update', $request_args );
$raw_response = wp_remote_post( $this->api_url, $request_string );
$response = null;
if( !is_wp_error($raw_response) && ($raw_response['response']['code'] == 200) )
$response = json_decode($raw_response['body']);
if( !empty($response) ) {// Feed the update data into WP updater
$transient->response[$this->plugin_slug] = $response;
$plugin_response[$this->plugin_slug] = (array)$response;
update_option($this->plugin_slug.'_theme_version',$plugin_response);
}
return $transient;
}
function tevolution_plugin_api_call( $def, $action, $args ) {
if( !isset($args->slug) || $args->slug != $this->plugin_slug ) return $def;
$plugin_info = get_site_transient('update_plugins');
$request_args = array(
'slug' => $this->plugin_slug,
'version' => (isset($plugin_info->checked)) ? $plugin_info->checked[$this->plugin_path] : 0 // Current version
);
$request_string = $this->tevolution_prepare_request( $action, $request_args );
$raw_response = wp_remote_post( $this->api_url, $request_string );
if( is_wp_error($raw_response) ){
$res = new WP_Error('plugins_api_failed', __('An Unexpected HTTP Error occurred during the API request.</p> <p><a href="?" onclick="document.location.reload(); return false;">Try again</a>'), $raw_response->get_error_message());
} else {
$res = json_decode($raw_response['body']);
if ($res === false)
$res = new WP_Error('plugins_api_failed', __('An unknown error occurred'), $raw_response['body']);
}
return $res;
}
function tevolution_prepare_request( $action, $args ) {
global $wp_version;
return array(
'body' => array(
'action' => $action,
'request' => serialize($args),
'api-key' => md5(home_url())
),
'user-agent' => 'WordPress/'. $wp_version .'; '. home_url()
);
}
}
}
?> | gpl-2.0 |
ryan-gyger/senior-web | src/main/java/org/nized/web/controllers/PersonController.java | 558 | package org.nized.web.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/person")
public class PersonController {
@RequestMapping("error")
public String catchAllErrors(@RequestParam(value = "name", required = false,
defaultValue = "World") String name, Model model) {
model.addAttribute("name", name);
return "error";
}
}
| gpl-2.0 |
ThiagoScar/mixerp | src/Libraries/Web API/Core/CashAccountSelectorViewController.cs | 5679 | using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MixERP.Net.ApplicationState.Cache;
using MixERP.Net.Common.Extensions;
using MixERP.Net.EntityParser;
using Newtonsoft.Json;
using PetaPoco;
namespace MixERP.Net.Api.Core
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Cash Account Selector Views.
/// </summary>
[RoutePrefix("api/v1.5/core/cash-account-selector-view")]
public class CashAccountSelectorViewController : ApiController
{
/// <summary>
/// The CashAccountSelectorView data context.
/// </summary>
private readonly MixERP.Net.Schemas.Core.Data.CashAccountSelectorView CashAccountSelectorViewContext;
public CashAccountSelectorViewController()
{
this.LoginId = AppUsers.GetCurrent().View.LoginId.ToLong();
this.UserId = AppUsers.GetCurrent().View.UserId.ToInt();
this.OfficeId = AppUsers.GetCurrent().View.OfficeId.ToInt();
this.Catalog = AppUsers.GetCurrentUserDB();
this.CashAccountSelectorViewContext = new MixERP.Net.Schemas.Core.Data.CashAccountSelectorView
{
Catalog = this.Catalog,
LoginId = this.LoginId
};
}
public long LoginId { get; }
public int UserId { get; private set; }
public int OfficeId { get; private set; }
public string Catalog { get; }
/// <summary>
/// Counts the number of cash account selector views.
/// </summary>
/// <returns>Returns the count of the cash account selector views.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/core/cash-account-selector-view/count")]
public long Count()
{
try
{
return this.CashAccountSelectorViewContext.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Creates a paginated collection containing 25 cash account selector views on each page, sorted by the property .
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/core/cash-account-selector-view")]
public IEnumerable<MixERP.Net.Entities.Core.CashAccountSelectorView> GetPagedResult()
{
try
{
return this.CashAccountSelectorViewContext.GetPagedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Creates a paginated collection containing 25 cash account selector views on each page, sorted by the property .
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/core/cash-account-selector-view/page/{pageNumber}")]
public IEnumerable<MixERP.Net.Entities.Core.CashAccountSelectorView> GetPagedResult(long pageNumber)
{
try
{
return this.CashAccountSelectorViewContext.GetPagedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Creates a filtered and paginated collection containing 25 cash account selector views on each page, sorted by the property .
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/core/cash-account-selector-view/get-where/{pageNumber}")]
public IEnumerable<MixERP.Net.Entities.Core.CashAccountSelectorView> GetWhere(long pageNumber, [FromBody]dynamic filters)
{
try
{
List<EntityParser.Filter> f = JsonConvert.DeserializeObject<List<EntityParser.Filter>>(filters);
return this.CashAccountSelectorViewContext.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
}
} | gpl-2.0 |
sugang/coolmap-core | src/coolmap/utils/statistics/LabelToColor.java | 958 | package coolmap.utils.statistics;
import java.awt.Color;
import java.util.Map;
/**
*
* @author Keqiang Li
*/
public class LabelToColor {
private final Map<String, Double> labelToValue;
private final ValueToColorUtil valueToColorUtil;
public LabelToColor(Map<String, Double> labelToValue, double min, double max) {
this.labelToValue = labelToValue;
valueToColorUtil = new ValueToColorUtil(min, max);
}
public Color getLabelColor(String label) {
return valueToColorUtil.convertToColor(labelToValue.get(label));
}
public boolean containsLabel(String label) {
return labelToValue.containsKey(label);
}
public double getValue(String label) {
return labelToValue.get(label);
}
public Color getColor(double value) {
return valueToColorUtil.convertToColor(value);
}
public Map<String, Double> getLabelToValue() {
return labelToValue;
}
}
| gpl-2.0 |
H0zen/M2-server | src/game/WorldHandlers/Group.cpp | 73766 | /**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2019 MaNGOS project <https://getmangos.eu>
*
* 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "Common.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Player.h"
#include "World.h"
#include "ObjectMgr.h"
#include "ObjectGuid.h"
#include "Group.h"
#include "Formulas.h"
#include "ObjectAccessor.h"
#include "BattleGround/BattleGround.h"
#include "BattleGround/BattleGroundMgr.h"
#include "MapManager.h"
#include "MapPersistentStateMgr.h"
#include "Util.h"
#include "LootMgr.h"
#ifdef ENABLE_ELUNA
#include "LuaEngine.h"
#endif /* ENABLE_ELUNA */
#define LOOT_ROLL_TIMEOUT (1*MINUTE*IN_MILLISECONDS)
//===================================================
//============== Roll ===============================
//===================================================
void Roll::targetObjectBuildLink()
{
// called from link()
getTarget()->addLootValidatorRef(this);
}
void Roll::CalculateCommonVoteMask(uint32 max_enchanting_skill)
{
m_commonVoteMask = ROLL_VOTE_MASK_ALL;
ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(itemid);
if (itemProto->Flags2 & ITEM_FLAG2_NEED_ROLL_DISABLED)
m_commonVoteMask = RollVoteMask(m_commonVoteMask & ~ROLL_VOTE_MASK_NEED);
if (!itemProto->DisenchantID || uint32(itemProto->RequiredDisenchantSkill) > max_enchanting_skill)
m_commonVoteMask = RollVoteMask(m_commonVoteMask & ~ROLL_VOTE_MASK_DISENCHANT);
}
RollVoteMask Roll::GetVoteMaskFor(Player* player) const
{
ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(itemid);
// In NEED_BEFORE_GREED need disabled for non-usable item for player
if (m_method != NEED_BEFORE_GREED || player->CanUseItem(itemProto) == EQUIP_ERR_OK)
return m_commonVoteMask;
else
return RollVoteMask(m_commonVoteMask & ~ROLL_VOTE_MASK_NEED);
}
//===================================================
//============== Group ==============================
//===================================================
Group::Group() : m_Id(0), m_groupType(GROUPTYPE_NORMAL),
m_dungeonDifficulty(REGULAR_DIFFICULTY), m_raidDifficulty(REGULAR_DIFFICULTY),
m_bgGroup(NULL), m_lootMethod(FREE_FOR_ALL), m_lootThreshold(ITEM_QUALITY_UNCOMMON),
m_subGroupsCounts(NULL)
{
}
Group::~Group()
{
if (m_bgGroup)
{
DEBUG_LOG("Group::~Group: battleground group being deleted.");
if (m_bgGroup->GetBgRaid(ALLIANCE) == this)
{ m_bgGroup->SetBgRaid(ALLIANCE, NULL); }
else if (m_bgGroup->GetBgRaid(HORDE) == this)
{ m_bgGroup->SetBgRaid(HORDE, NULL); }
else
{ sLog.outError("Group::~Group: battleground group is not linked to the correct battleground."); }
}
Rolls::iterator itr;
while (!RollId.empty())
{
itr = RollId.begin();
Roll* r = *itr;
RollId.erase(itr);
delete(r);
}
// it is undefined whether objectmgr (which stores the groups) or instancesavemgr
// will be unloaded first so we must be prepared for both cases
// this may unload some dungeon persistent state
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
for (BoundInstancesMap::iterator itr2 = m_boundInstances[i].begin(); itr2 != m_boundInstances[i].end(); ++itr2)
{ itr2->second.state->RemoveGroup(this); }
// Sub group counters clean up
delete[] m_subGroupsCounts;
}
bool Group::Create(ObjectGuid guid, const char* name)
{
m_leaderGuid = guid;
m_leaderName = name;
m_groupType = isBGGroup() ? GROUPTYPE_BGRAID : GROUPTYPE_NORMAL;
if (m_groupType == GROUPTYPE_RAID)
{ _initRaidSubGroupsCounter(); }
m_lootMethod = GROUP_LOOT;
m_lootThreshold = ITEM_QUALITY_UNCOMMON;
m_looterGuid = guid;
m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
if (!isBGGroup())
{
m_Id = sObjectMgr.GenerateGroupLowGuid();
Player* leader = sObjectMgr.GetPlayer(guid);
if (leader)
{
m_dungeonDifficulty = leader->GetDungeonDifficulty();
m_raidDifficulty = leader->GetRaidDifficulty();
}
Player::ConvertInstancesToGroup(leader, this, guid);
// store group in database
CharacterDatabase.BeginTransaction();
CharacterDatabase.PExecute("DELETE FROM groups WHERE groupId ='%u'", m_Id);
CharacterDatabase.PExecute("DELETE FROM group_member WHERE groupId ='%u'", m_Id);
CharacterDatabase.PExecute("INSERT INTO groups (groupId,leaderGuid,mainTank,mainAssistant,lootMethod,looterGuid,lootThreshold,icon1,icon2,icon3,icon4,icon5,icon6,icon7,icon8,groupType,difficulty,raiddifficulty) "
"VALUES ('%u','%u','%u','%u','%u','%u','%u','" UI64FMTD "','" UI64FMTD "','" UI64FMTD "','" UI64FMTD "','" UI64FMTD "','" UI64FMTD "','" UI64FMTD "','" UI64FMTD "','%u','%u','%u')",
m_Id, m_leaderGuid.GetCounter(), m_mainTankGuid.GetCounter(), m_mainAssistantGuid.GetCounter(), uint32(m_lootMethod),
m_looterGuid.GetCounter(), uint32(m_lootThreshold),
m_targetIcons[0].GetRawValue(), m_targetIcons[1].GetRawValue(),
m_targetIcons[2].GetRawValue(), m_targetIcons[3].GetRawValue(),
m_targetIcons[4].GetRawValue(), m_targetIcons[5].GetRawValue(),
m_targetIcons[6].GetRawValue(), m_targetIcons[7].GetRawValue(),
uint8(m_groupType), uint32(m_dungeonDifficulty), uint32(m_raidDifficulty));
}
if (!AddMember(guid, name))
{ return false; }
if (!isBGGroup())
{ CharacterDatabase.CommitTransaction(); }
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->OnCreate(this, m_leaderGuid, m_groupType);
#endif /* ENABLE_ELUNA */
return true;
}
bool Group::LoadGroupFromDB(Field* fields)
{
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, groupType, difficulty, raiddifficulty, leaderGuid, groupId FROM groups");
m_Id = fields[17].GetUInt32();
m_leaderGuid = ObjectGuid(HIGHGUID_PLAYER, fields[16].GetUInt32());
// group leader not exist
if (!sObjectMgr.GetPlayerNameByGUID(m_leaderGuid, m_leaderName))
{ return false; }
m_groupType = GroupType(fields[13].GetUInt8());
if (m_groupType == GROUPTYPE_RAID)
{ _initRaidSubGroupsCounter(); }
uint32 diff = fields[14].GetUInt8();
if (diff >= MAX_DUNGEON_DIFFICULTY)
diff = DUNGEON_DIFFICULTY_NORMAL;
m_dungeonDifficulty = Difficulty(diff);
uint32 r_diff = fields[15].GetUInt8();
if (r_diff >= MAX_RAID_DIFFICULTY)
r_diff = RAID_DIFFICULTY_10MAN_NORMAL;
m_raidDifficulty = Difficulty(r_diff);
m_mainTankGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32());
m_mainAssistantGuid = ObjectGuid(HIGHGUID_PLAYER, fields[1].GetUInt32());
m_lootMethod = LootMethod(fields[2].GetUInt8());
m_looterGuid = ObjectGuid(HIGHGUID_PLAYER, fields[3].GetUInt32());
m_lootThreshold = ItemQualities(fields[4].GetUInt16());
for (int i = 0; i < TARGET_ICON_COUNT; ++i)
{ m_targetIcons[i] = ObjectGuid(fields[5 + i].GetUInt64()); }
return true;
}
bool Group::LoadMemberFromDB(uint32 guidLow, uint8 subgroup, bool assistant)
{
MemberSlot member;
member.guid = ObjectGuid(HIGHGUID_PLAYER, guidLow);
// skip nonexistent member
if (!sObjectMgr.GetPlayerNameByGUID(member.guid, member.name))
{ return false; }
member.group = subgroup;
member.assistant = assistant;
m_memberSlots.push_back(member);
SubGroupCounterIncrease(subgroup);
return true;
}
void Group::ConvertToRaid()
{
m_groupType = GroupType(m_groupType | GROUPTYPE_RAID);
_initRaidSubGroupsCounter();
if (!isBGGroup())
CharacterDatabase.PExecute("UPDATE groups SET groupType = %u WHERE groupId='%u'", uint8(m_groupType), m_Id);
SendUpdate();
// update quest related GO states (quest activity dependent from raid membership)
for (member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
if (Player* player = sObjectMgr.GetPlayer(citr->guid))
{ player->UpdateForQuestWorldObjects(); }
}
bool Group::AddInvite(Player* player)
{
if (!player || player->GetGroupInvite())
{ return false; }
Group* group = player->GetGroup();
if (group && group->isBGGroup())
{ group = player->GetOriginalGroup(); }
if (group)
{ return false; }
RemoveInvite(player);
m_invitees.insert(player);
player->SetGroupInvite(this);
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->OnInviteMember(this, player->GetObjectGuid());
#endif /* ENABLE_ELUNA */
return true;
}
bool Group::AddLeaderInvite(Player* player)
{
if (!AddInvite(player))
{ return false; }
m_leaderGuid = player->GetObjectGuid();
m_leaderName = player->GetName();
return true;
}
uint32 Group::RemoveInvite(Player* player)
{
m_invitees.erase(player);
player->SetGroupInvite(NULL);
return GetMembersCount();
}
void Group::RemoveAllInvites()
{
for (InvitesList::iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr)
{ (*itr)->SetGroupInvite(NULL); }
m_invitees.clear();
}
Player* Group::GetInvited(ObjectGuid guid) const
{
for (InvitesList::const_iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr)
if ((*itr)->GetObjectGuid() == guid)
{ return (*itr); }
return NULL;
}
Player* Group::GetInvited(const std::string& name) const
{
for (InvitesList::const_iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr)
{
if ((*itr)->GetName() == name)
{ return (*itr); }
}
return NULL;
}
bool Group::AddMember(ObjectGuid guid, const char* name)
{
if (!_addMember(guid, name))
{ return false; }
SendUpdate();
if (Player* player = sObjectMgr.GetPlayer(guid))
{
if (!IsLeader(player->GetObjectGuid()) && !isBGGroup())
{
// reset the new member's instances, unless he is currently in one of them
// including raid/heroic instances that they are not permanently bound to!
player->ResetInstances(INSTANCE_RESET_GROUP_JOIN, false);
player->ResetInstances(INSTANCE_RESET_GROUP_JOIN, true);
if (player->getLevel() >= LEVELREQUIREMENT_HEROIC)
{
if (player->GetDungeonDifficulty() != GetDungeonDifficulty())
{
player->SetDungeonDifficulty(GetDungeonDifficulty());
player->SendDungeonDifficulty(true);
}
if (player->GetRaidDifficulty() != GetRaidDifficulty())
{
player->SetRaidDifficulty(GetRaidDifficulty());
player->SendRaidDifficulty(true);
}
}
}
player->SetGroupUpdateFlag(GROUP_UPDATE_FULL);
UpdatePlayerOutOfRange(player);
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->OnAddMember(this, player->GetObjectGuid());
#endif /* ENABLE_ELUNA */
// quest related GO state dependent from raid membership
if (isRaidGroup())
{ player->UpdateForQuestWorldObjects(); }
}
return true;
}
uint32 Group::RemoveMember(ObjectGuid guid, uint8 method)
{
// remove member and change leader (if need) only if strong more 2 members _before_ member remove
if (GetMembersCount() > uint32(isBGGroup() ? 1 : 2)) // in BG group case allow 1 members group
{
bool leaderChanged = _removeMember(guid);
if (Player* player = sObjectMgr.GetPlayer(guid))
{
// quest related GO state dependent from raid membership
if (isRaidGroup())
{ player->UpdateForQuestWorldObjects(); }
WorldPacket data;
if (method == 1)
{
data.Initialize(SMSG_GROUP_UNINVITE, 0);
player->GetSession()->SendPacket(&data);
}
// we already removed player from group and in player->GetGroup() is his original group!
if (Group* group = player->GetGroup())
{
group->SendUpdate();
}
else
{
data.Initialize(SMSG_GROUP_LIST, 1 + 1 + 1 + 1 + 8 + 4 + 4 + 8);
data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0);
data << uint64(0) << uint32(0) << uint32(0) << uint64(0);
player->GetSession()->SendPacket(&data);
}
_homebindIfInstance(player);
}
if (leaderChanged)
{
WorldPacket data(SMSG_GROUP_SET_LEADER, (m_memberSlots.front().name.size() + 1));
data << m_memberSlots.front().name;
BroadcastPacket(&data, true);
}
SendUpdate();
}
// if group before remove <= 2 disband it
else
{ Disband(true); }
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->OnRemoveMember(this, guid, method); // Kicker and Reason not a part of Mangos, implement?
#endif /* ENABLE_ELUNA */
return m_memberSlots.size();
}
void Group::ChangeLeader(ObjectGuid guid)
{
member_citerator slot = _getMemberCSlot(guid);
if (slot == m_memberSlots.end())
{ return; }
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->OnChangeLeader(this, guid, GetLeaderGuid());
#endif /* ENABLE_ELUNA */
_setLeader(guid);
WorldPacket data(SMSG_GROUP_SET_LEADER, slot->name.size() + 1);
data << slot->name;
BroadcastPacket(&data, true);
SendUpdate();
}
void Group::Disband(bool hideDestroy)
{
Player* player;
for (member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
{
player = sObjectMgr.GetPlayer(citr->guid);
if (!player)
{ continue; }
// we can not call _removeMember because it would invalidate member iterator
// if we are removing player from battleground raid
if (isBGGroup())
{ player->RemoveFromBattleGroundRaid(); }
else
{
// we can remove player who is in battleground from his original group
if (player->GetOriginalGroup() == this)
{ player->SetOriginalGroup(NULL); }
else
{ player->SetGroup(NULL); }
}
// quest related GO state dependent from raid membership
if (isRaidGroup())
{ player->UpdateForQuestWorldObjects(); }
if (!player->GetSession())
{ continue; }
WorldPacket data;
if (!hideDestroy)
{
data.Initialize(SMSG_GROUP_DESTROYED, 0);
player->GetSession()->SendPacket(&data);
}
// we already removed player from group and in player->GetGroup() is his original group, send update
if (Group* group = player->GetGroup())
{
group->SendUpdate();
}
else
{
data.Initialize(SMSG_GROUP_LIST, 1 + 1 + 1 + 1 + 8 + 4 + 4 + 8);
data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0);
data << uint64(0) << uint32(0) << uint32(0) << uint64(0);
player->GetSession()->SendPacket(&data);
}
_homebindIfInstance(player);
}
RollId.clear();
m_memberSlots.clear();
RemoveAllInvites();
if (!isBGGroup())
{
CharacterDatabase.BeginTransaction();
CharacterDatabase.PExecute("DELETE FROM groups WHERE groupId='%u'", m_Id);
CharacterDatabase.PExecute("DELETE FROM group_member WHERE groupId='%u'", m_Id);
CharacterDatabase.CommitTransaction();
ResetInstances(INSTANCE_RESET_GROUP_DISBAND, false, NULL);
ResetInstances(INSTANCE_RESET_GROUP_DISBAND, true, NULL);
}
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->OnDisband(this);
#endif /* ENABLE_ELUNA */
m_leaderGuid.Clear();
m_leaderName.clear();
}
/*********************************************************/
/*** LOOT SYSTEM ***/
/*********************************************************/
void Group::SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll& r)
{
WorldPacket data(SMSG_LOOT_START_ROLL, (8 + 4 + 4 + 4 + 4 + 4 + 4 + 1));
data << r.lootedTargetGUID; // creature guid what we're looting
data << uint32(mapid); // 3.3.3 mapid
data << uint32(r.itemSlot); // item slot in loot
data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
data << uint32(r.itemRandomSuffix); // randomSuffix
data << uint32(r.itemRandomPropId); // item random property ID
data << uint32(r.itemCount); // items in stack
data << uint32(CountDown); // the countdown time to choose "need" or "greed"
size_t voteMaskPos = data.wpos();
data << uint8(0); // roll type mask, allowed choices (placeholder)
for (Roll::PlayerVote::const_iterator itr = r.playerVote.begin(); itr != r.playerVote.end(); ++itr)
{
Player* p = sObjectMgr.GetPlayer(itr->first);
if (!p || !p->GetSession())
{ continue; }
if (itr->second == ROLL_NOT_VALID)
{ continue; }
// dependent from player
RollVoteMask mask = r.GetVoteMaskFor(p);
data.put<uint8>(voteMaskPos, uint8(mask));
p->GetSession()->SendPacket(&data);
}
}
void Group::SendLootRoll(ObjectGuid const& targetGuid, uint8 rollNumber, uint8 rollType, const Roll& r)
{
WorldPacket data(SMSG_LOOT_ROLL, (8 + 4 + 8 + 4 + 4 + 4 + 1 + 1 + 1));
data << r.lootedTargetGUID; // creature guid what we're looting
data << uint32(r.itemSlot); // unknown, maybe amount of players, or item slot in loot
data << targetGuid;
data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
data << uint32(r.itemRandomSuffix); // randomSuffix
data << uint32(r.itemRandomPropId); // Item random property ID
data << uint8(rollNumber); // 0: "Need for: [item name]" > 127: "you passed on: [item name]" Roll number
data << uint8(rollType); // 0: "Need for: [item name]" 0: "You have selected need for [item name] 1: need roll 2: greed roll
data << uint8(0); // auto pass on loot
for (Roll::PlayerVote::const_iterator itr = r.playerVote.begin(); itr != r.playerVote.end(); ++itr)
{
Player* p = sObjectMgr.GetPlayer(itr->first);
if (!p || !p->GetSession())
{ continue; }
if (itr->second != ROLL_NOT_VALID)
{ p->GetSession()->SendPacket(&data); }
}
}
void Group::SendLootRollWon(ObjectGuid const& targetGuid, uint8 rollNumber, RollVote rollType, const Roll& r)
{
WorldPacket data(SMSG_LOOT_ROLL_WON, (8 + 4 + 4 + 4 + 4 + 8 + 1 + 1));
data << r.lootedTargetGUID; // creature guid what we're looting
data << uint32(r.itemSlot); // item slot in loot
data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
data << uint32(r.itemRandomSuffix); // randomSuffix
data << uint32(r.itemRandomPropId); // Item random property
data << targetGuid; // guid of the player who won.
data << uint8(rollNumber); // rollnumber related to SMSG_LOOT_ROLL
data << uint8(rollType); // Rolltype related to SMSG_LOOT_ROLL
for (Roll::PlayerVote::const_iterator itr = r.playerVote.begin(); itr != r.playerVote.end(); ++itr)
{
Player* p = sObjectMgr.GetPlayer(itr->first);
if (!p || !p->GetSession())
{ continue; }
if (itr->second != ROLL_NOT_VALID)
{ p->GetSession()->SendPacket(&data); }
}
}
void Group::SendLootAllPassed(Roll const& r)
{
WorldPacket data(SMSG_LOOT_ALL_PASSED, (8 + 4 + 4 + 4 + 4));
data << r.lootedTargetGUID; // creature guid what we're looting
data << uint32(r.itemSlot); // item slot in loot
data << uint32(r.itemid); // The itemEntryId for the item that shall be rolled for
data << uint32(r.itemRandomPropId); // Item random property ID
data << uint32(r.itemRandomSuffix); // Item random suffix ID
for (Roll::PlayerVote::const_iterator itr = r.playerVote.begin(); itr != r.playerVote.end(); ++itr)
{
Player* p = sObjectMgr.GetPlayer(itr->first);
if (!p || !p->GetSession())
{ continue; }
if (itr->second != ROLL_NOT_VALID)
{ p->GetSession()->SendPacket(&data); }
}
}
void Group::GroupLoot(WorldObject* pSource, Loot* loot)
{
uint32 maxEnchantingSkill = GetMaxSkillValueForGroup(SKILL_ENCHANTING);
for (uint8 itemSlot = 0; itemSlot < loot->items.size(); ++itemSlot)
{
LootItem& lootItem = loot->items[itemSlot];
ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(lootItem.itemid);
if (!itemProto)
{
DEBUG_LOG("Group::GroupLoot: missing item prototype for item with id: %d", lootItem.itemid);
continue;
}
// roll for over-threshold item if it's one-player loot
if (itemProto->Quality >= uint32(m_lootThreshold) && !lootItem.freeforall)
StartLootRoll(pSource, GROUP_LOOT, loot, itemSlot, maxEnchantingSkill);
else
{ lootItem.is_underthreshold = 1; }
}
}
void Group::NeedBeforeGreed(WorldObject* pSource, Loot* loot)
{
uint32 maxEnchantingSkill = GetMaxSkillValueForGroup(SKILL_ENCHANTING);
for (uint8 itemSlot = 0; itemSlot < loot->items.size(); ++itemSlot)
{
LootItem& lootItem = loot->items[itemSlot];
ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(lootItem.itemid);
if (!itemProto)
{
DEBUG_LOG("Group::NeedBeforeGreed: missing item prototype for item with id: %d", lootItem.itemid);
continue;
}
// only roll for one-player items, not for ones everyone can get
if (itemProto->Quality >= uint32(m_lootThreshold) && !lootItem.freeforall)
StartLootRoll(pSource, NEED_BEFORE_GREED, loot, itemSlot, maxEnchantingSkill);
else
{ lootItem.is_underthreshold = 1; }
}
}
void Group::MasterLoot(WorldObject* pSource, Loot* loot)
{
for (LootItemList::iterator i = loot->items.begin(); i != loot->items.end(); ++i)
{
ItemPrototype const* item = ObjectMgr::GetItemPrototype(i->itemid);
if (!item)
{ continue; }
if (item->Quality < uint32(m_lootThreshold))
{ i->is_underthreshold = 1; }
}
uint32 real_count = 0;
WorldPacket data(SMSG_LOOT_MASTER_LIST, 330);
data << uint8(GetMembersCount());
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* looter = itr->getSource();
if (!looter->IsInWorld())
{ continue; }
if (looter->IsWithinDist(pSource, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false))
{
data << looter->GetObjectGuid();
++real_count;
}
}
data.put<uint8>(0, real_count);
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* looter = itr->getSource();
if (looter->IsWithinDist(pSource, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false))
{ looter->GetSession()->SendPacket(&data); }
}
}
bool Group::CountRollVote(Player* player, ObjectGuid const& lootedTarget, uint32 itemSlot, RollVote vote)
{
Rolls::iterator rollI = RollId.begin();
for (; rollI != RollId.end(); ++rollI)
if ((*rollI)->isValid() && (*rollI)->lootedTargetGUID == lootedTarget && (*rollI)->itemSlot == itemSlot)
{ break; }
if (rollI == RollId.end())
{ return false; }
// possible cheating
RollVoteMask voteMask = (*rollI)->GetVoteMaskFor(player);
if ((voteMask & (1 << vote)) == 0)
return false;
CountRollVote(player->GetObjectGuid(), rollI, vote); // result not related this function result meaning, ignore
return true;
}
bool Group::CountRollVote(ObjectGuid const& playerGUID, Rolls::iterator& rollI, RollVote vote)
{
Roll* roll = *rollI;
Roll::PlayerVote::iterator itr = roll->playerVote.find(playerGUID);
// this condition means that player joins to the party after roll begins
if (itr == roll->playerVote.end())
{ return true; } // result used for need iterator ++, so avoid for end of list
if (roll->getLoot())
if (roll->getLoot()->items.empty())
{ return false; }
switch (vote)
{
case ROLL_PASS: // Player choose pass
{
SendLootRoll(playerGUID, 128, 128, *roll);
++roll->totalPass;
itr->second = ROLL_PASS;
break;
}
case ROLL_NEED: // player choose Need
{
SendLootRoll(playerGUID, 0, 0, *roll);
++roll->totalNeed;
itr->second = ROLL_NEED;
break;
}
case ROLL_GREED: // player choose Greed
{
SendLootRoll(playerGUID, 128, ROLL_GREED, *roll);
++roll->totalGreed;
itr->second = ROLL_GREED;
break;
}
case ROLL_DISENCHANT: // player choose Disenchant
{
SendLootRoll(playerGUID, 128, ROLL_DISENCHANT, *roll);
++roll->totalGreed;
itr->second = ROLL_DISENCHANT;
break;
}
default: // Roll removed case
break;
}
if (roll->totalPass + roll->totalNeed + roll->totalGreed >= roll->totalPlayersRolling)
{
CountTheRoll(rollI);
return true;
}
return false;
}
void Group::StartLootRoll(WorldObject* lootTarget, LootMethod method, Loot* loot, uint8 itemSlot, uint32 maxEnchantingSkill)
{
if (itemSlot >= loot->items.size())
{ return; }
LootItem const& lootItem = loot->items[itemSlot];
Roll* r = new Roll(lootTarget->GetObjectGuid(), method, lootItem);
// a vector is filled with only near party members
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* playerToRoll = itr->getSource();
if (!playerToRoll || !playerToRoll->GetSession())
{ continue; }
if (lootItem.AllowedForPlayer(playerToRoll, lootTarget))
{
if (playerToRoll->IsWithinDistInMap(lootTarget, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false))
{
r->playerVote[playerToRoll->GetObjectGuid()] = ROLL_NOT_EMITED_YET;
++r->totalPlayersRolling;
}
}
}
if (r->totalPlayersRolling > 0) // has looters
{
r->setLoot(loot);
r->itemSlot = itemSlot;
if (r->totalPlayersRolling == 1) // single looter
{ r->playerVote.begin()->second = ROLL_NEED; }
else
{
// Only GO-group looting and NPC-group looting possible
MANGOS_ASSERT(lootTarget->isType(TYPEMASK_CREATURE_OR_GAMEOBJECT));
r->CalculateCommonVoteMask(maxEnchantingSkill); // dependent from item and possible skill
SendLootStartRoll(LOOT_ROLL_TIMEOUT, lootTarget->GetMapId(), *r);
loot->items[itemSlot].is_blocked = true;
lootTarget->StartGroupLoot(this, LOOT_ROLL_TIMEOUT);
}
RollId.push_back(r);
}
else // no looters??
{ delete r; }
}
// called when roll timer expires
void Group::EndRoll()
{
while (!RollId.empty())
{
// need more testing here, if rolls disappear
Rolls::iterator itr = RollId.begin();
CountTheRoll(itr); // i don't have to edit player votes, who didn't vote ... he will pass
}
}
void Group::CountTheRoll(Rolls::iterator& rollI)
{
Roll* roll = *rollI;
if (!roll->isValid()) // is loot already deleted ?
{
rollI = RollId.erase(rollI);
delete roll;
return;
}
// end of the roll
if (roll->totalNeed > 0)
{
if (!roll->playerVote.empty())
{
uint8 maxresul = 0;
ObjectGuid maxguid = (*roll->playerVote.begin()).first;
Player* player;
for (Roll::PlayerVote::const_iterator itr = roll->playerVote.begin(); itr != roll->playerVote.end(); ++itr)
{
if (itr->second != ROLL_NEED)
{ continue; }
uint8 randomN = urand(1, 100);
SendLootRoll(itr->first, randomN, ROLL_NEED, *roll);
if (maxresul < randomN)
{
maxguid = itr->first;
maxresul = randomN;
}
}
SendLootRollWon(maxguid, maxresul, ROLL_NEED, *roll);
player = sObjectMgr.GetPlayer(maxguid);
if (player && player->GetSession())
{
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT, roll->itemid, maxresul);
ItemPosCountVec dest;
LootItem* item = &(roll->getLoot()->items[roll->itemSlot]);
InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, roll->itemid, item->count);
if (msg == EQUIP_ERR_OK)
{
item->is_looted = true;
roll->getLoot()->NotifyItemRemoved(roll->itemSlot);
--roll->getLoot()->unlootedCount;
player->StoreNewItem(dest, roll->itemid, true, item->randomPropertyId);
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM, roll->itemid, item->count);
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE, roll->getLoot()->loot_type, item->count);
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM, roll->itemid, item->count);
}
else
{
item->is_blocked = false;
player->SendEquipError(msg, NULL, NULL, roll->itemid);
}
}
}
}
else if (roll->totalGreed > 0)
{
if (!roll->playerVote.empty())
{
uint8 maxresul = 0;
ObjectGuid maxguid = (*roll->playerVote.begin()).first;
Player* player;
RollVote rollvote = ROLL_PASS; // Fixed: Using uninitialized memory 'rollvote'
Roll::PlayerVote::iterator itr;
for (itr = roll->playerVote.begin(); itr != roll->playerVote.end(); ++itr)
{
if (itr->second != ROLL_GREED && itr->second != ROLL_DISENCHANT)
{ continue; }
uint8 randomN = urand(1, 100);
SendLootRoll(itr->first, randomN, itr->second, *roll);
if (maxresul < randomN)
{
maxguid = itr->first;
maxresul = randomN;
rollvote = itr->second;
}
}
SendLootRollWon(maxguid, maxresul, rollvote, *roll);
player = sObjectMgr.GetPlayer(maxguid);
if (player && player->GetSession())
{
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT, roll->itemid, maxresul);
LootItem* item = &(roll->getLoot()->items[roll->itemSlot]);
if (rollvote == ROLL_GREED)
{
ItemPosCountVec dest;
InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, roll->itemid, item->count);
if (msg == EQUIP_ERR_OK)
{
item->is_looted = true;
roll->getLoot()->NotifyItemRemoved(roll->itemSlot);
--roll->getLoot()->unlootedCount;
player->StoreNewItem(dest, roll->itemid, true, item->randomPropertyId);
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM, roll->itemid, item->count);
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE, roll->getLoot()->loot_type, item->count);
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM, roll->itemid, item->count);
}
else
{
item->is_blocked = false;
player->SendEquipError(msg, NULL, NULL, roll->itemid);
}
}
else if (rollvote == ROLL_DISENCHANT)
{
item->is_looted = true;
roll->getLoot()->NotifyItemRemoved(roll->itemSlot);
--roll->getLoot()->unlootedCount;
ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(roll->itemid);
player->AutoStoreLoot(roll->getLoot()->GetLootTarget(), pProto->DisenchantID, LootTemplates_Disenchant, true);
}
}
}
}
else
{
SendLootAllPassed(*roll);
LootItem* item = &(roll->getLoot()->items[roll->itemSlot]);
if (item) { item->is_blocked = false; }
}
rollI = RollId.erase(rollI);
delete roll;
}
void Group::SetTargetIcon(uint8 id, ObjectGuid whoGuid, ObjectGuid targetGuid)
{
if (id >= TARGET_ICON_COUNT)
{ return; }
// clean other icons
if (targetGuid)
for (int i = 0; i < TARGET_ICON_COUNT; ++i)
if (m_targetIcons[i] == targetGuid)
SetTargetIcon(i, ObjectGuid(), ObjectGuid());
m_targetIcons[id] = targetGuid;
WorldPacket data(MSG_RAID_TARGET_UPDATE, (1 + 8 + 1 + 8));
data << uint8(0); // set targets
data << whoGuid;
data << uint8(id);
data << targetGuid;
BroadcastPacket(&data, true);
}
static void GetDataForXPAtKill_helper(Player* player, Unit const* victim, uint32& sum_level, Player*& member_with_max_level, Player*& not_gray_member_with_max_level)
{
sum_level += player->getLevel();
if (!member_with_max_level || member_with_max_level->getLevel() < player->getLevel())
{ member_with_max_level = player; }
uint32 gray_level = MaNGOS::XP::GetGrayLevel(player->getLevel());
if (victim->getLevel() > gray_level && (!not_gray_member_with_max_level
|| not_gray_member_with_max_level->getLevel() < player->getLevel()))
{ not_gray_member_with_max_level = player; }
}
void Group::GetDataForXPAtKill(Unit const* victim, uint32& count, uint32& sum_level, Player*& member_with_max_level, Player*& not_gray_member_with_max_level, Player* additional)
{
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
if (!member || !member->IsAlive()) // only for alive
{ continue; }
// will proccesed later
if (member == additional)
{ continue; }
if (!member->IsAtGroupRewardDistance(victim)) // at req. distance
{ continue; }
++count;
GetDataForXPAtKill_helper(member, victim, sum_level, member_with_max_level, not_gray_member_with_max_level);
}
if (additional)
{
if (additional->IsAtGroupRewardDistance(victim)) // at req. distance
{
++count;
GetDataForXPAtKill_helper(additional, victim, sum_level, member_with_max_level, not_gray_member_with_max_level);
}
}
}
void Group::SendTargetIconList(WorldSession* session)
{
if (!session)
{ return; }
WorldPacket data(MSG_RAID_TARGET_UPDATE, (1 + TARGET_ICON_COUNT * 9));
data << uint8(1); // list targets
for (int i = 0; i < TARGET_ICON_COUNT; ++i)
{
if (!m_targetIcons[i])
{ continue; }
data << uint8(i);
data << m_targetIcons[i];
}
session->SendPacket(&data);
}
void Group::SendUpdate()
{
for (member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
{
Player* player = sObjectMgr.GetPlayer(citr->guid);
if (!player || !player->GetSession() || player->GetGroup() != this)
{ continue; }
// guess size
WorldPacket data(SMSG_GROUP_LIST, (1 + 1 + 1 + 1 + 8 + 4 + GetMembersCount() * 20));
data << uint8(m_groupType); // group type (flags in 3.3)
data << uint8(citr->group); // groupid
data << uint8(GetFlags(*citr)); // group flags
data << uint8(isBGGroup() ? 1 : 0); // 2.0.x, isBattleGroundGroup?
if (m_groupType & GROUPTYPE_LFD)
{
data << uint8(0);
data << uint32(0);
}
data << GetObjectGuid(); // group guid
data << uint32(0); // 3.3, this value increments every time SMSG_GROUP_LIST is sent
data << uint32(GetMembersCount() - 1);
for (member_citerator citr2 = m_memberSlots.begin(); citr2 != m_memberSlots.end(); ++citr2)
{
if (citr->guid == citr2->guid)
{ continue; }
Player* member = sObjectMgr.GetPlayer(citr2->guid);
uint8 onlineState = (member) ? MEMBER_STATUS_ONLINE : MEMBER_STATUS_OFFLINE;
onlineState = onlineState | ((isBGGroup()) ? MEMBER_STATUS_PVP : 0);
data << citr2->name;
data << citr2->guid;
data << uint8(onlineState); // online-state
data << uint8(citr2->group); // groupid
data << uint8(GetFlags(*citr2)); // group flags
data << uint8(0); // 3.3, role?
}
data << m_leaderGuid; // leader guid
if (GetMembersCount() - 1)
{
data << uint8(m_lootMethod); // loot method
data << m_looterGuid; // looter guid
data << uint8(m_lootThreshold); // loot threshold
data << uint8(m_dungeonDifficulty); // Dungeon Difficulty
data << uint8(m_raidDifficulty); // Raid Difficulty
data << uint8(0); // 3.3, dynamic difficulty?
}
player->GetSession()->SendPacket(&data);
}
}
void Group::UpdatePlayerOutOfRange(Player* pPlayer)
{
if (!pPlayer || !pPlayer->IsInWorld())
{ return; }
if (pPlayer->GetGroupUpdateFlag() == GROUP_UPDATE_FLAG_NONE)
{ return; }
WorldPacket data;
pPlayer->GetSession()->BuildPartyMemberStatsChangedPacket(pPlayer, &data);
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
if (Player* player = itr->getSource())
if (player != pPlayer && !player->HaveAtClient(pPlayer))
{ player->GetSession()->SendPacket(&data); }
}
void Group::BroadcastPacket(WorldPacket* packet, bool ignorePlayersInBGRaid, int group, ObjectGuid ignore)
{
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pl = itr->getSource();
if (!pl || (ignore && pl->GetObjectGuid() == ignore) || (ignorePlayersInBGRaid && pl->GetGroup() != this))
{ continue; }
if (pl->GetSession() && (group == -1 || itr->getSubGroup() == group))
{ pl->GetSession()->SendPacket(packet); }
}
}
void Group::BroadcastReadyCheck(WorldPacket* packet)
{
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pl = itr->getSource();
if (pl && pl->GetSession())
if (IsLeader(pl->GetObjectGuid()) || IsAssistant(pl->GetObjectGuid()))
{ pl->GetSession()->SendPacket(packet); }
}
}
void Group::OfflineReadyCheck()
{
for (member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
{
Player* pl = sObjectMgr.GetPlayer(citr->guid);
if (!pl || !pl->GetSession())
{
WorldPacket data(MSG_RAID_READY_CHECK_CONFIRM, 9);
data << citr->guid;
data << uint8(0);
BroadcastReadyCheck(&data);
}
}
}
bool Group::_addMember(ObjectGuid guid, const char* name, bool isAssistant)
{
// get first not-full group
uint8 groupid = 0;
if (m_subGroupsCounts)
{
bool groupFound = false;
for (; groupid < MAX_RAID_SUBGROUPS; ++groupid)
{
if (m_subGroupsCounts[groupid] < MAX_GROUP_SIZE)
{
groupFound = true;
break;
}
}
// We are raid group and no one slot is free
if (!groupFound)
{ return false; }
}
return _addMember(guid, name, isAssistant, groupid);
}
bool Group::_addMember(ObjectGuid guid, const char* name, bool isAssistant, uint8 group)
{
if (IsFull())
{ return false; }
if (!guid)
{ return false; }
Player* player = sObjectMgr.GetPlayer(guid, false);
uint32 lastMap = 0;
if (player && player->IsInWorld())
lastMap = player->GetMapId();
else if (player && player->IsBeingTeleported())
lastMap = player->GetTeleportDest().mapid;
MemberSlot member;
member.guid = guid;
member.name = name;
member.group = group;
member.assistant = isAssistant;
member.lastMap = lastMap;
m_memberSlots.push_back(member);
SubGroupCounterIncrease(group);
if (player)
{
player->SetGroupInvite(NULL);
// if player is in group and he is being added to BG raid group, then call SetBattleGroundRaid()
if (player->GetGroup() && isBGGroup())
{ player->SetBattleGroundRaid(this, group); }
// if player is in bg raid and we are adding him to normal group, then call SetOriginalGroup()
else if (player->GetGroup())
{ player->SetOriginalGroup(this, group); }
// if player is not in group, then call set group
else
{ player->SetGroup(this, group); }
if (player->IsInWorld())
{
// if the same group invites the player back, cancel the homebind timer
if (InstanceGroupBind* bind = GetBoundInstance(player->GetMapId(), player))
if (bind->state->GetInstanceId() == player->GetInstanceId())
{ player->m_InstanceValid = true; }
}
}
if (!isRaidGroup()) // reset targetIcons for non-raid-groups
{
for (int i = 0; i < TARGET_ICON_COUNT; ++i)
{ m_targetIcons[i].Clear(); }
}
if (!isBGGroup())
{
// insert into group table
CharacterDatabase.PExecute("INSERT INTO group_member(groupId,memberGuid,assistant,subgroup) VALUES('%u','%u','%u','%u')",
m_Id, member.guid.GetCounter(), ((member.assistant == 1) ? 1 : 0), member.group);
}
return true;
}
bool Group::_removeMember(ObjectGuid guid)
{
Player* player = sObjectMgr.GetPlayer(guid);
if (player)
{
// if we are removing player from battleground raid
if (isBGGroup())
{ player->RemoveFromBattleGroundRaid(); }
else
{
// we can remove player who is in battleground from his original group
if (player->GetOriginalGroup() == this)
{ player->SetOriginalGroup(NULL); }
else
{ player->SetGroup(NULL); }
}
}
_removeRolls(guid);
member_witerator slot = _getMemberWSlot(guid);
if (slot != m_memberSlots.end())
{
SubGroupCounterDecrease(slot->group);
m_memberSlots.erase(slot);
}
if (!isBGGroup())
{ CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid='%u'", guid.GetCounter()); }
if (m_leaderGuid == guid) // leader was removed
{
if (GetMembersCount() > 0)
{ _setLeader(m_memberSlots.front().guid); }
return true;
}
return false;
}
void Group::_setLeader(ObjectGuid guid)
{
member_citerator slot = _getMemberCSlot(guid);
if (slot == m_memberSlots.end())
{ return; }
if (!isBGGroup())
{
uint32 slot_lowguid = slot->guid.GetCounter();
uint32 leader_lowguid = m_leaderGuid.GetCounter();
// TODO: set a time limit to have this function run rarely cause it can be slow
CharacterDatabase.BeginTransaction();
// update the group's bound instances when changing leaders
// remove all permanent binds from the group
// in the DB also remove solo binds that will be replaced with permbinds
// from the new leader
CharacterDatabase.PExecute(
"DELETE FROM group_instance WHERE leaderguid='%u' AND (permanent = 1 OR "
"instance IN (SELECT instance FROM character_instance WHERE guid = '%u')"
")", leader_lowguid, slot_lowguid);
Player* player = sObjectMgr.GetPlayer(slot->guid);
if (player)
{
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end();)
{
if (itr->second.perm)
{
itr->second.state->RemoveGroup(this);
m_boundInstances[i].erase(itr++);
}
else
++itr;
}
}
}
// update the group's solo binds to the new leader
CharacterDatabase.PExecute("UPDATE group_instance SET leaderGuid='%u' WHERE leaderGuid = '%u'",
slot_lowguid, leader_lowguid);
// copy the permanent binds from the new leader to the group
// overwriting the solo binds with permanent ones if necessary
// in the DB those have been deleted already
Player::ConvertInstancesToGroup(player, this, slot->guid);
// update the group leader
CharacterDatabase.PExecute("UPDATE groups SET leaderGuid='%u' WHERE groupId='%u'", slot_lowguid, m_Id);
CharacterDatabase.CommitTransaction();
}
m_leaderGuid = slot->guid;
m_leaderName = slot->name;
}
void Group::_removeRolls(ObjectGuid guid)
{
for (Rolls::iterator it = RollId.begin(); it != RollId.end();)
{
Roll* roll = *it;
Roll::PlayerVote::iterator itr2 = roll->playerVote.find(guid);
if (itr2 == roll->playerVote.end())
{
++it;
continue;
}
if (itr2->second == ROLL_GREED || itr2->second == ROLL_DISENCHANT)
{ --roll->totalGreed; }
if (itr2->second == ROLL_NEED)
{ --roll->totalNeed; }
if (itr2->second == ROLL_PASS)
{ --roll->totalPass; }
if (itr2->second != ROLL_NOT_VALID)
{ --roll->totalPlayersRolling; }
roll->playerVote.erase(itr2);
if (!CountRollVote(guid, it, ROLL_NOT_EMITED_YET))
{ ++it; }
}
}
bool Group::_setMembersGroup(ObjectGuid guid, uint8 group)
{
member_witerator slot = _getMemberWSlot(guid);
if (slot == m_memberSlots.end())
{ return false; }
slot->group = group;
SubGroupCounterIncrease(group);
if (!isBGGroup())
{ CharacterDatabase.PExecute("UPDATE group_member SET subgroup='%u' WHERE memberGuid='%u'", group, guid.GetCounter()); }
return true;
}
bool Group::_setAssistantFlag(ObjectGuid guid, const bool& state)
{
member_witerator slot = _getMemberWSlot(guid);
if (slot == m_memberSlots.end())
{ return false; }
slot->assistant = state;
if (!isBGGroup())
{ CharacterDatabase.PExecute("UPDATE group_member SET assistant='%u' WHERE memberGuid='%u'", (state == true) ? 1 : 0, guid.GetCounter()); }
return true;
}
bool Group::_setMainTank(ObjectGuid guid)
{
if (m_mainTankGuid == guid)
{ return false; }
if (guid)
{
member_citerator slot = _getMemberCSlot(guid);
if (slot == m_memberSlots.end())
{ return false; }
if (m_mainAssistantGuid == guid)
{ _setMainAssistant(ObjectGuid()); }
}
m_mainTankGuid = guid;
if (!isBGGroup())
{ CharacterDatabase.PExecute("UPDATE groups SET mainTank='%u' WHERE groupId='%u'", m_mainTankGuid.GetCounter(), m_Id); }
return true;
}
bool Group::_setMainAssistant(ObjectGuid guid)
{
if (m_mainAssistantGuid == guid)
{ return false; }
if (guid)
{
member_witerator slot = _getMemberWSlot(guid);
if (slot == m_memberSlots.end())
{ return false; }
if (m_mainTankGuid == guid)
{ _setMainTank(ObjectGuid()); }
}
m_mainAssistantGuid = guid;
if (!isBGGroup())
CharacterDatabase.PExecute("UPDATE groups SET mainAssistant='%u' WHERE groupId='%u'",
m_mainAssistantGuid.GetCounter(), m_Id);
return true;
}
bool Group::SameSubGroup(Player const* member1, Player const* member2) const
{
if (!member1 || !member2)
{ return false; }
if (member1->GetGroup() != this || member2->GetGroup() != this)
{ return false; }
else
{ return member1->GetSubGroup() == member2->GetSubGroup(); }
}
// allows setting subgroup for offline members
void Group::ChangeMembersGroup(ObjectGuid guid, uint8 group)
{
if (!isRaidGroup())
{ return; }
Player* player = sObjectMgr.GetPlayer(guid);
if (!player)
{
uint8 prevSubGroup = GetMemberGroup(guid);
if (prevSubGroup == group)
{ return; }
if (_setMembersGroup(guid, group))
{
SubGroupCounterDecrease(prevSubGroup);
SendUpdate();
}
}
else
// This methods handles itself groupcounter decrease
{ ChangeMembersGroup(player, group); }
}
// only for online members
void Group::ChangeMembersGroup(Player* player, uint8 group)
{
if (!player || !isRaidGroup())
{ return; }
uint8 prevSubGroup = player->GetSubGroup();
if (prevSubGroup == group)
{ return; }
if (_setMembersGroup(player->GetObjectGuid(), group))
{
if (player->GetGroup() == this)
{ player->GetGroupRef().setSubGroup(group); }
// if player is in BG raid, it is possible that he is also in normal raid - and that normal raid is stored in m_originalGroup reference
else
{
prevSubGroup = player->GetOriginalSubGroup();
player->GetOriginalGroupRef().setSubGroup(group);
}
SubGroupCounterDecrease(prevSubGroup);
SendUpdate();
}
}
uint32 Group::GetMaxSkillValueForGroup(SkillType skill)
{
uint32 maxvalue = 0;
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
if (!member)
continue;
uint32 value = member->GetSkillValue(skill);
if (maxvalue < value)
maxvalue = value;
}
return maxvalue;
}
void Group::UpdateLooterGuid(WorldObject* pSource, bool ifneed)
{
switch (GetLootMethod())
{
case MASTER_LOOT:
case FREE_FOR_ALL:
return;
default:
// round robin style looting applies for all low
// quality items in each loot method except free for all and master loot
break;
}
member_citerator guid_itr = _getMemberCSlot(GetLooterGuid());
if (guid_itr != m_memberSlots.end())
{
if (ifneed)
{
// not update if only update if need and ok
Player* looter = sObjectAccessor.FindPlayer(guid_itr->guid);
if (looter && looter->IsWithinDist(pSource, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false))
{ return; }
}
++guid_itr;
}
// search next after current
if (guid_itr != m_memberSlots.end())
{
for (member_citerator itr = guid_itr; itr != m_memberSlots.end(); ++itr)
{
if (Player* pl = sObjectAccessor.FindPlayer(itr->guid))
{
if (pl->IsWithinDist(pSource, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false))
{
bool refresh = pl->GetLootGuid() == pSource->GetObjectGuid();
// if(refresh) // update loot for new looter
// pl->GetSession()->DoLootRelease(pl->GetLootGUID());
SetLooterGuid(pl->GetObjectGuid());
SendUpdate();
if (refresh) // update loot for new looter
{ pl->SendLoot(pSource->GetObjectGuid(), LOOT_CORPSE); }
return;
}
}
}
}
// search from start
for (member_citerator itr = m_memberSlots.begin(); itr != guid_itr; ++itr)
{
if (Player* pl = sObjectAccessor.FindPlayer(itr->guid))
{
if (pl->IsWithinDist(pSource, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false))
{
bool refresh = pl->GetLootGuid() == pSource->GetObjectGuid();
// if(refresh) // update loot for new looter
// pl->GetSession()->DoLootRelease(pl->GetLootGUID());
SetLooterGuid(pl->GetObjectGuid());
SendUpdate();
if (refresh) // update loot for new looter
{ pl->SendLoot(pSource->GetObjectGuid(), LOOT_CORPSE); }
return;
}
}
}
SetLooterGuid(ObjectGuid());
SendUpdate();
}
GroupJoinBattlegroundResult Group::CanJoinBattleGroundQueue(BattleGround const* bgOrTemplate, BattleGroundQueueTypeId bgQueueTypeId, uint32 MinPlayerCount, uint32 MaxPlayerCount, bool isRated, uint32 arenaSlot)
{
BattlemasterListEntry const* bgEntry = sBattlemasterListStore.LookupEntry(bgOrTemplate->GetTypeID());
if (!bgEntry)
return ERR_GROUP_JOIN_BATTLEGROUND_FAIL; // shouldn't happen
// check for min / max count
uint32 memberscount = GetMembersCount();
// only check for MinPlayerCount since MinPlayerCount == MaxPlayerCount for arenas...
if (bgOrTemplate->isArena() && memberscount != MinPlayerCount)
return ERR_ARENA_TEAM_PARTY_SIZE;
if (memberscount > bgEntry->maxGroupSize) // no MinPlayerCount for battlegrounds
return ERR_BATTLEGROUND_NONE; // ERR_GROUP_JOIN_BATTLEGROUND_TOO_MANY handled on client side
// get a player as reference, to compare other players' stats to (arena team id, queue id based on level, etc.)
Player* reference = GetFirstMember()->getSource();
// no reference found, can't join this way
if (!reference)
return ERR_BATTLEGROUND_JOIN_FAILED;
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bgOrTemplate->GetMapId(), reference->getLevel());
if (!bracketEntry)
return ERR_BATTLEGROUND_JOIN_FAILED;
uint32 arenaTeamId = reference->GetArenaTeamId(arenaSlot);
Team team = reference->GetTeam();
BattleGroundQueueTypeId bgQueueTypeIdRandom = BattleGroundMgr::BGQueueTypeId(BATTLEGROUND_RB, ARENA_TYPE_NONE);
// check every member of the group to be able to join
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
// offline member? don't let join
if (!member)
return ERR_BATTLEGROUND_JOIN_FAILED;
// don't allow cross-faction join as group
if (member->GetTeam() != team)
return ERR_BATTLEGROUND_JOIN_TIMED_OUT;
// not in the same battleground level bracket, don't let join
PvPDifficultyEntry const* memberBracketEntry = GetBattlegroundBracketByLevel(bracketEntry->mapId, member->getLevel());
if (memberBracketEntry != bracketEntry)
return ERR_BATTLEGROUND_JOIN_RANGE_INDEX;
// don't let join rated matches if the arena team id doesn't match
if (isRated && member->GetArenaTeamId(arenaSlot) != arenaTeamId)
return ERR_BATTLEGROUND_JOIN_FAILED;
// don't let join if someone from the group is already in that bg queue
if (member->InBattleGroundQueueForBattleGroundQueueType(bgQueueTypeId))
return ERR_BATTLEGROUND_JOIN_FAILED; // not blizz-like
// don't let join if someone from the group is in bg queue random
if (member->InBattleGroundQueueForBattleGroundQueueType(bgQueueTypeIdRandom))
return ERR_IN_RANDOM_BG;
// don't let join to bg queue random if someone from the group is already in bg queue
if (bgOrTemplate->GetTypeID() == BATTLEGROUND_RB && member->InBattleGroundQueue())
return ERR_IN_NON_RANDOM_BG;
// check for deserter debuff in case not arena queue
if (bgOrTemplate->GetTypeID() != BATTLEGROUND_AA && !member->CanJoinToBattleground())
return ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS;
// check if member can join any more battleground queues
if (!member->HasFreeBattleGroundQueueId())
return ERR_BATTLEGROUND_TOO_MANY_QUEUES; // not blizz-like
}
return GroupJoinBattlegroundResult(bgOrTemplate->GetTypeID());
}
void Group::SetDungeonDifficulty(Difficulty difficulty)
{
m_dungeonDifficulty = difficulty;
if (!isBGGroup())
CharacterDatabase.PExecute("UPDATE groups SET difficulty = %u WHERE groupId='%u'", m_dungeonDifficulty, m_Id);
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* player = itr->getSource();
if (!player->GetSession() || player->getLevel() < LEVELREQUIREMENT_HEROIC)
continue;
player->SetDungeonDifficulty(difficulty);
player->SendDungeonDifficulty(true);
}
}
void Group::SetRaidDifficulty(Difficulty difficulty)
{
m_raidDifficulty = difficulty;
if (!isBGGroup())
CharacterDatabase.PExecute("UPDATE groups SET raiddifficulty = %u WHERE groupId='%u'", m_raidDifficulty, m_Id);
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* player = itr->getSource();
if (!player->GetSession() || player->getLevel() < LEVELREQUIREMENT_HEROIC)
continue;
player->SetRaidDifficulty(difficulty);
player->SendRaidDifficulty(true);
}
}
bool Group::InCombatToInstance(uint32 instanceId)
{
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pPlayer = itr->getSource();
if (pPlayer->getAttackers().size() && pPlayer->GetInstanceId() == instanceId)
{ return true; }
}
return false;
}
bool Group::SetPlayerMap(ObjectGuid guid, uint32 mapid)
{
member_witerator slot = _getMemberWSlot(guid);
if (slot != m_memberSlots.end())
{
slot->lastMap = mapid;
DEBUG_LOG("Group::SetPlayerMap> map is updated");
return true;
}
return false;
}
void Group::ResetInstances(InstanceResetMethod method, bool isRaid, Player* SendMsgTo)
{
if (isBGGroup())
{ return; }
// method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_DISBAND
// we assume that when the difficulty changes, all instances that can be reset will be
Difficulty diff = GetDifficulty(isRaid);
typedef std::set<uint32> OfflineMapSet;
OfflineMapSet mapsWithOfflinePlayer; // to store map of offline players
if (method != INSTANCE_RESET_GROUP_DISBAND)
{
// Store maps in which are offline members for instance reset check.
for (member_citerator itr = m_memberSlots.begin(); itr != m_memberSlots.end(); ++itr)
{
if (!sObjectAccessor.FindPlayer(itr->guid))
mapsWithOfflinePlayer.insert(itr->lastMap); // add last map from offline player
}
}
for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
{
DungeonPersistentState* state = itr->second.state;
const MapEntry* entry = sMapStore.LookupEntry(itr->first);
if (!entry || entry->IsRaid() != isRaid || (!state->CanReset() && method != INSTANCE_RESET_GROUP_DISBAND))
{
++itr;
continue;
}
if (method == INSTANCE_RESET_ALL)
{
// the "reset all instances" method can only reset normal maps
if (entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
{
++itr;
continue;
}
}
bool isEmpty = true;
// check if there are offline members on the map
if (method != INSTANCE_RESET_GROUP_DISBAND && mapsWithOfflinePlayer.find(state->GetMapId()) != mapsWithOfflinePlayer.end())
isEmpty = false;
// if the map is loaded, reset it if can
if (isEmpty && entry->IsDungeon() && !(method == INSTANCE_RESET_GROUP_DISBAND && !state->CanReset()))
if (Map* map = sMapMgr.FindMap(state->GetMapId(), state->GetInstanceId()))
{ isEmpty = ((DungeonMap*)map)->Reset(method); }
if (SendMsgTo)
{
if (isEmpty)
{ SendMsgTo->SendResetInstanceSuccess(state->GetMapId()); }
else
{ SendMsgTo->SendResetInstanceFailed(0, state->GetMapId()); }
}
// TODO - Adapt here when clear how difficulty changes must be handled
if (isEmpty || method == INSTANCE_RESET_GROUP_DISBAND || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
{
// do not reset the instance, just unbind if others are permanently bound to it
if (state->CanReset())
{ state->DeleteFromDB(); }
else
{ CharacterDatabase.PExecute("DELETE FROM group_instance WHERE instance = '%u'", state->GetInstanceId()); }
// i don't know for sure if hash_map iterators
m_boundInstances[diff].erase(itr);
itr = m_boundInstances[diff].begin();
// this unloads the instance save unless online players are bound to it
// (eg. permanent binds or GM solo binds)
state->RemoveGroup(this);
}
else
{ ++itr; }
}
}
InstanceGroupBind* Group::GetBoundInstance(uint32 mapid, Player* player)
{
MapEntry const* mapEntry = sMapStore.LookupEntry(mapid);
if (!mapEntry)
{ return NULL; }
Difficulty difficulty = player->GetDifficulty(mapEntry->IsRaid());
// some instances only have one difficulty
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapid, difficulty);
if (!mapDiff)
difficulty = DUNGEON_DIFFICULTY_NORMAL;
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
if (itr != m_boundInstances[difficulty].end())
{ return &itr->second; }
else
{ return NULL; }
}
InstanceGroupBind* Group::GetBoundInstance(Map* aMap, Difficulty difficulty)
{
// some instances only have one difficulty
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(aMap->GetId(), difficulty);
if (!mapDiff)
return NULL;
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(aMap->GetId());
if (itr != m_boundInstances[difficulty].end())
return &itr->second;
else
return NULL;
}
InstanceGroupBind* Group::BindToInstance(DungeonPersistentState* state, bool permanent, bool load)
{
if (state && !isBGGroup())
{
InstanceGroupBind& bind = m_boundInstances[state->GetDifficulty()][state->GetMapId()];
if (bind.state)
{
// when a boss is killed or when copying the players's binds to the group
if (permanent != bind.perm || state != bind.state)
if (!load)
CharacterDatabase.PExecute("UPDATE group_instance SET instance = '%u', permanent = '%u' WHERE leaderGuid = '%u' AND instance = '%u'",
state->GetInstanceId(), permanent, GetLeaderGuid().GetCounter(), bind.state->GetInstanceId());
}
else if (!load)
CharacterDatabase.PExecute("INSERT INTO group_instance (leaderGuid, instance, permanent) VALUES ('%u', '%u', '%u')",
GetLeaderGuid().GetCounter(), state->GetInstanceId(), permanent);
if (bind.state != state)
{
if (bind.state)
{ bind.state->RemoveGroup(this); }
state->AddGroup(this);
}
bind.state = state;
bind.perm = permanent;
if (!load)
DEBUG_LOG("Group::BindToInstance: Group (Id: %d) is now bound to map %d, instance %d, difficulty %d",
GetId(), state->GetMapId(), state->GetInstanceId(), state->GetDifficulty());
return &bind;
}
else
{ return NULL; }
}
void Group::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
{
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
if (itr != m_boundInstances[difficulty].end())
{
if (!unload)
CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u' AND instance = '%u'",
GetLeaderGuid().GetCounter(), itr->second.state->GetInstanceId());
itr->second.state->RemoveGroup(this); // save can become invalid
m_boundInstances[difficulty].erase(itr);
}
}
void Group::_homebindIfInstance(Player* player)
{
if (player && !player->isGameMaster())
{
Map* map = player->GetMap();
if (map->IsDungeon())
{
// leaving the group in an instance, the homebind timer is started
// unless the player is permanently saved to the instance
InstancePlayerBind* playerBind = player->GetBoundInstance(map->GetId(), map->GetDifficulty());
if (!playerBind || !playerBind->perm)
{ player->m_InstanceValid = false; }
}
}
}
static void RewardGroupAtKill_helper(Player* pGroupGuy, Unit* pVictim, uint32 count, bool PvP, float group_rate, uint32 sum_level, bool is_dungeon, Player* not_gray_member_with_max_level, Player* member_with_max_level, uint32 xp)
{
// honor can be in PvP and !PvP (racial leader) cases (for alive)
if (pGroupGuy->IsAlive())
{ pGroupGuy->RewardHonor(pVictim, count); }
// xp and reputation only in !PvP case
if (!PvP)
{
float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
// if is in dungeon then all receive full reputation at kill
// rewarded any alive/dead/near_corpse group member
pGroupGuy->RewardReputation(pVictim, is_dungeon ? 1.0f : rate);
// XP updated only for alive group member
if (pGroupGuy->IsAlive() && not_gray_member_with_max_level &&
pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
{
uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp * rate) : uint32((xp * rate / 2) + 1);
pGroupGuy->GiveXP(itr_xp, pVictim);
if (Pet* pet = pGroupGuy->GetPet())
pet->GivePetXP(itr_xp / 2);
}
// quest objectives updated only for alive group member or dead but with not released body
if (pGroupGuy->IsAlive() || !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
{
// normal creature (not pet/etc) can be only in !PvP case
if (pVictim->GetTypeId() == TYPEID_UNIT)
if (CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry()))
pGroupGuy->KilledMonster(normalInfo, pVictim->GetObjectGuid());
}
}
}
/** Provide rewards to group members at unit kill
*
* @param pVictim Killed unit
* @param player_tap Player who tap unit if online, it can be group member or can be not if leaved after tap but before kill target
*
* Rewards received by group members and player_tap
*/
void Group::RewardGroupAtKill(Unit* pVictim, Player* player_tap)
{
bool PvP = pVictim->IsCharmedOwnedByPlayerOrPlayer();
// prepare data for near group iteration (PvP and !PvP cases)
uint32 xp = 0;
uint32 count = 0;
uint32 sum_level = 0;
Player* member_with_max_level = NULL;
Player* not_gray_member_with_max_level = NULL;
GetDataForXPAtKill(pVictim, count, sum_level, member_with_max_level, not_gray_member_with_max_level, player_tap);
if (member_with_max_level)
{
/// not get Xp in PvP or no not gray players in group
xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
/// skip in check PvP case (for speed, not used)
bool is_raid = PvP ? false : sMapStore.LookupEntry(pVictim->GetMapId())->IsRaid() && isRaidGroup();
bool is_dungeon = PvP ? false : sMapStore.LookupEntry(pVictim->GetMapId())->IsDungeon();
float group_rate = MaNGOS::XP::xp_in_group_rate(count, is_raid);
for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pGroupGuy = itr->getSource();
if (!pGroupGuy)
{ continue; }
// will proccessed later
if (pGroupGuy == player_tap)
{ continue; }
if (!pGroupGuy->IsAtGroupRewardDistance(pVictim))
{ continue; } // member (alive or dead) or his corpse at req. distance
RewardGroupAtKill_helper(pGroupGuy, pVictim, count, PvP, group_rate, sum_level, is_dungeon, not_gray_member_with_max_level, member_with_max_level, xp);
}
if (player_tap)
{
// member (alive or dead) or his corpse at req. distance
if (player_tap->IsAtGroupRewardDistance(pVictim))
{ RewardGroupAtKill_helper(player_tap, pVictim, count, PvP, group_rate, sum_level, is_dungeon, not_gray_member_with_max_level, member_with_max_level, xp); }
}
}
}
| gpl-2.0 |
jimthenerd/authfid | src/AuthFID.java | 2268 | import sun.applet.Main;
import javax.swing.*;
import java.awt.*;
import java.io.*;
/**
* Created by jacky on 28/11/15.
*/
public class AuthFID {
static {
System.loadLibrary("SerialRFID");
}
public static UserProfile profile = new UserProfile();
public static MainWindow window;
public static AuthWindow authWindow;
public static void readProfile(){
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(new File("config.dat")));
profile = (UserProfile)is.readObject();
is.close();
} catch (Exception ex) { /*I don't give a shit */ }
}
public static void writeProfile(){
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(new File(("config.dat"))));
os.writeObject(profile);
os.close();
} catch (Exception ex) { /*I don't give a shit */ }
}
public static void main(String[] args) {
profile.services.add(new UserProfile.ProfileAuthInfo("Google", "NSDCNZHIX22UCY4IEDITV76ODQDBDFM7"));
profile.services.add(new UserProfile.ProfileAuthInfo("Facebook", "HXDMVJECHHWSRB3HWIZR4IFUGFTMXBOZ"));
profile.services.add(new UserProfile.ProfileAuthInfo("GitHub", "qvzezxbeyl6mib3x".toUpperCase()));
profile.services.add(new UserProfile.ProfileAuthInfo("DigitalOcean", "w5g522vnoyf53wpu".toUpperCase()));
AuthWindow authWindow = new AuthWindow();
while (true) {
String str = SerialRFID.read();
System.out.println("str = " + str);
if (str.trim().equals("0bbba285")) break;
try {
authWindow.lblWelcome.setForeground(Color.RED);
authWindow.lblWelcome.setText("Incorrect Card ID. ");
Thread.sleep(2000);
authWindow.lblWelcome.setForeground(Color.black);
authWindow.lblWelcome.setText("Please swipe your RFID card...");
} catch (Exception ex) {
}
}
authWindow.setVisible(false);
authWindow.dispose();
MainWindow window = new MainWindow();
window.setVisible(true);
window.resetView();
window.updateProfiles(profile);
}
}
| gpl-2.0 |
frank-fegert/check_mk | dell_powerconnect/pnp-templates/check_mk-dell_powerconnect_bcm_ssh_sessions.php | 1926 | <?php
#
# Copyright (C) 2015 - 2016 Frank Fegert (fra.nospam.nk@gmx.de)
#
# PNP4Nagios template for the:
# dell_powerconnect_bcm_ssh_sessions
# Check_MK check script. This template handles the graph for the number
# of currently active SSH sessions on Dell PowerConnect switches.
# This has currently been verified to work with the following Broadcom
# FastPath silicon based switch models:
# PowerConnect M8024-k
# PowerConnect M6348
#
#
# 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.#
#
#
# RRDtool Options
$pre='';
$vlabel='Sessions';
$uom='';
$min=0;
$warn=$WARN[1];
$crit=$CRIT[1];
# Graph options
$opt[1] = "--width 650 --vertical-label \"$vlabel\" -l $min --title \"SSH sessions - $hostname\" ";
# Graph definitions
$def[1] = "DEF:sessions=$RRDFILE[1]:$DS[1]:AVERAGE " ;
$def[1] .= "LINE2:sessions#40A018:\"SSH sessions \" " ;
$def[1] .= "GPRINT:sessions:LAST:\"Current\: %6.2lf %s$uom\" ";
$def[1] .= "GPRINT:sessions:MIN:\"Minimum\: %6.2lf %s$uom\" ";
$def[1] .= "GPRINT:sessions:AVERAGE:\"Average\: %6.2lf %s$uom\" ";
$def[1] .= "GPRINT:sessions:MAX:\"Maximum\: %6.2lf %s$uom\\n\" ";
$def[1] .= "HRULE:$warn#FFFF00:\"Warning on $warn $pre$uom \\n\" ";
$def[1] .= "HRULE:$crit#FF0000:\"Critical on $crit $pre$uom \\n\" ";
#
# EOF
?>
| gpl-2.0 |
walkley21/speicher | wp-content/themes/TribusCommunity/footer.php | 3108 | </div> <!-- end blog -->
<?php if ( !is_home() || defined('INTERIOR') ) { get_sidebar(); } ?>
</div><!-- end main -->
<div class="fb-banners">
<?php if( is_home() && !defined('INTERIOR') && get_option('tribusFacebookApp') == 'Y' ):?>
<?php //if( get_option('tribusFacebookLike') == 'Y' ):?>
<div class="fb-like" data-href="http://tribus.creative-works.us/" data-send="false" data-width="450" data-show-faces="true"></div>
<?php endif;?>
<?php if( is_home() && !defined('INTERIOR') ):?>
<div style="float: right; width: 300px;">
<span style="color: #136cc0; font-family: Georgia; font-size: 14px; font-style: italic;">Information Sponsored By:</span><br>
<table cellpadding="0" cellspacing="0" width="100%" align="left">
<tr>
<td rowspan="2" width="100px"><?php $avtr = get_avatar(1, 80); echo $avtr; ?></td>
<td style="font-family: Arial; font-size: 14px; font-weight: bold; color: #136cc0; text-transform: uppercase;">
<?php $user_info = get_userdata(1);
echo $user_info->display_name;
?>
</td>
</tr>
<tr>
<td style="font-family: Arial; font-size: 12px; font-weight: bold; color: #585858;">Phone: <?php echo get_option('tribusThemePhoneNumber'); ?></td>
</tr>
</table>
</div>
<?php endif;?>
</div>
<br class="clear"/>
</div> <!-- end content -->
<div class="content_bottom">
</div>
<div class="footer_image">
<div class="footer_custom">
<span class="brand-name"><?php bloginfo( 'name' ); ?></span>
<span class="footer_custom_copyright">
Copyright © 2011 Baird & Warner Real Estate | Login To <a rel="external nofollow" href="<?php echo get_bloginfo('url'); ?>/wp-login.php">Community</a>
</span>
</div>
</div>
<!--div class="footer">
<?php /*$biz_name = ( get_option('tribusBusinessName') ) ? get_option('tribusBusinessName') : get_bloginfo('name'); ?>
<p class="left">Copyright © 2011 <?php echo $biz_name; ?> <?php if ( $license = get_option('tribusBusinessLicenseNumber') ) { echo "DRE#: {$license}"; } ?> | Login To <a rel="external nofollow" href="http://www.TribusCRM.com">TribusCRM</a></p>
<p class="right">TRIpress <a href="http://www.tripressrealestate.com">WordPress Real Estate Theme</a> Powered by <a href="http://www.TribusGroup.com">Tribus Real Estate Technologies</a> <img src="<?php bloginfo('stylesheet_directory'); */?>/images/tribusx15.png"></p>
<div class="clear"></div>
</div--><!-- end footer -->
</div><!-- end innerBody -->
<?php wp_footer(); ?>
</body> <!-- end of body this is the end of the body -->
</html> | gpl-2.0 |
Polytechnique-org/platal | include/validations/address.inc.php | 5851 | <?php
/***************************************************************************
* Copyright (C) 2003-2018 Polytechnique.org *
* http://opensource.polytechnique.org/ *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
***************************************************************************/
// {{{ class AddressReq
class AddressReq extends ProfileValidate
{
// {{{ properties
// Address primary field that are not in its formatted array.
public $key_pid;
public $key_jobid;
public $key_groupid;
public $key_type;
public $key_id;
// We need the text given by the user, and the toy version to try to improve
// the geocoding.
public $address;
public $given_text;
public $toy_text = '';
public $modified = false;
public $rules = 'Si la localisation est bonne, refuser. Sinon, si le texte est faux, le corriger. Si la géolocaliastion ne marche toujours pas, utiliser la version jouet qui ne sera pas stockée, mais dont les données de localisation le seront.';
// }}}
// {{{ constructor
public function __construct(User $_user, array $_address, $_pid, $_jobid, $_groupid, $_type, $_id, $_stamp = 0)
{
$_profile = Profile::get($_pid);
parent::__construct($_user, $_profile, false, 'address', $_stamp);
$this->key_pid = $_pid;
$this->key_jobid = $_jobid;
$this->key_groupid = $_groupid;
$this->key_type = $_type;
$this->key_id = $_id;
$this->given_text = $_address['text'];
$this->address = $_address;
}
// }}}
// {{{ function formu()
public function formu()
{
return 'include/form.valid.address.tpl';
}
// }}}
// {{{ function editor()
public function editor()
{
return 'include/form.valid.edit-address.tpl';
}
// }}}
// {{{ function handle_editor()
protected function handle_editor()
{
$data = Post::v('valid');
if (isset($data['text']) && $data['text'] != $this->toy_text && $data['text'] != $this->given_text) {
$this->toy_text = $data['text'];
$address = new Address(array('changed' => 1, 'text' => $this->toy_text));
$address->format();
$this->address = $address->toFormArray();
}
$this->modified = isset($data['modified']);
return true;
}
// }}}
// {{{ function _mail_subj
protected function _mail_subj()
{
return '[Polytechnique.org/Adresse] Demande d\'amélioration de la localisation d\'une adresse';
}
// }}}
// {{{ function _mail_body
protected function _mail_body($isok)
{
if ($isok) {
return " Nous avons réussi à mieux localiser l'adresse suivante :\n{$this->given_text}.";
} else {
return " L'adresse est suffisemment bien localisée pour les besoins du site (recherche avancée, planisphère), nous avons donc choisi de ne pas la modifier.";
}
}
// }}}
// {{{ function commit()
public function commit()
{
$this->address = array_merge($this->address, array(
'pid' => $this->key_pid,
'jobid' => $this->key_jobid,
'groupid' => $this->key_groupid,
'type' => $this->key_type,
'id' => $this->key_id
));
$this->address['text'] = ($this->modified ? $this->toy_text : $this->given_text);;
$this->address['changed'] = 0;
$address = new Address($this->address);
$address->format();
$address->updateGeocoding();
return true;
}
// }}}
// {{{ function get_request()
static public function get_request($pid, $jobid, $groupid, $type, $id)
{
$reqs = parent::get_typed_requests($pid, 'address');
foreach ($reqs as &$req) {
if ($req->key_pid == $pid && $req->key_jobid == $jobid && $req->key_groupid == $groupid
&& $req->key_type == $type && $req->key_id == $id) {
return $req;
}
}
return null;
}
// }}}
// {{{ function purge_requests()
// Purges address localization requests based on deleted addresses.
static public function purge_requests($pid, $jobid, $groupid, $type)
{
$requests = parent::get_all_typed_requests('address');
foreach ($requests as &$req) {
if ($req->key_pid == $pid && $req->key_jobid == $jobid && $req->key_groupid == $groupid && $req->key_type == $type) {
$req->clean();
}
}
}
// }}}
}
// }}}
// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
?>
| gpl-2.0 |
knocte/getittogether | src/de/kapsi/net/daap/chunks/impl/ContentCodesResponse.java | 1286 | /*
* Digital Audio Access Protocol (DAAP)
* Copyright (C) 2004 Roger Kapsi, info at kapsi dot de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package de.kapsi.net.daap.chunks.impl;
import de.kapsi.net.daap.chunks.ContainerChunk;
/**
* The ContentCodesResponse is a list of ContentCodes-Numbers, Names and Types.
* It is needed to build a list of capabilities of the Server which is
* send to the client...
*
* @author Roger Kapsi
*/
public class ContentCodesResponse extends ContainerChunk {
public ContentCodesResponse() {
super("mccr", "dmap.contentcodesresponse");
}
}
| gpl-2.0 |
rkrdovrgs/weberp-notifications | BankReconciliation.php | 14902 | <?php
/* $Id: BankReconciliation.php 7092 2015-01-22 14:17:10Z rchacon $*/
/* This script displays the bank reconciliation for a selected bank account. */
include('includes/session.inc');
$Title = _('Bank Reconciliation');;// Screen identificator.
$ViewTopic= 'GeneralLedger';// Filename's id in ManualContents.php's TOC.
$BookMark = 'BankAccounts';// Anchor's id in the manual's html document.
include('includes/header.inc');
echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
echo '<div>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
echo '<p class="page_title_text"><img alt="" src="'.$RootPath.'/css/'.$Theme.
'/images/bank.png" title="' .
_('Bank Reconciliation') . '" /> ' .// Icon title.
_('Bank Reconciliation') . '</p>';// Page title.
if (isset($_GET['Account'])) {
$_POST['BankAccount']=$_GET['Account'];
$_POST['ShowRec']=true;
}
if (isset($_POST['BankStatementBalance'])){
$_POST['BankStatementBalance'] = filter_number_format($_POST['BankStatementBalance']);
}
if (isset($_POST['PostExchangeDifference']) AND is_numeric(filter_number_format($_POST['DoExchangeDifference']))){
if (!is_numeric($_POST['BankStatementBalance'])){
prnMsg(_('The entry in the bank statement balance is not numeric. The balance on the bank statement should be entered. The exchange difference has not been calculated and no general ledger journal has been created'),'warn');
echo '<br />' . $_POST['BankStatementBalance'];
} else {
/* Now need to get the currency of the account and the current table ex rate */
$SQL = "SELECT rate,
bankaccountname,
decimalplaces AS currdecimalplaces
FROM bankaccounts INNER JOIN currencies
ON bankaccounts.currcode=currencies.currabrev
WHERE bankaccounts.accountcode = '" . $_POST['BankAccount']."'";
$ErrMsg = _('Could not retrieve the exchange rate for the selected bank account');
$CurrencyResult = DB_query($SQL);
$CurrencyRow = DB_fetch_array($CurrencyResult);
$CalculatedBalance = filter_number_format($_POST['DoExchangeDifference']);
$ExchangeDifference = ($CalculatedBalance - filter_number_format($_POST['BankStatementBalance']))/$CurrencyRow['rate'];
include ('includes/SQL_CommonFunctions.inc');
$ExDiffTransNo = GetNextTransNo(36,$db);
/*Post the exchange difference to the last day of the month prior to current date*/
$PostingDate = Date($_SESSION['DefaultDateFormat'],mktime(0,0,0, Date('m'), 0,Date('Y')));
$PeriodNo = GetPeriod($PostingDate,$db);
$result = DB_Txn_Begin();
//yet to code the journal
$SQL = "INSERT INTO gltrans (type,
typeno,
trandate,
periodno,
account,
narrative,
amount)
VALUES (36,
'" . $ExDiffTransNo . "',
'" . FormatDateForSQL($PostingDate) . "',
'" . $PeriodNo . "',
'" . $_SESSION['CompanyRecord']['exchangediffact'] . "',
'" . $CurrencyRow['bankaccountname'] . ' ' . _('reconciliation on') . " " .
Date($_SESSION['DefaultDateFormat']) . "','" . $ExchangeDifference . "')";
$ErrMsg = _('Cannot insert a GL entry for the exchange difference because');
$DbgMsg = _('The SQL that failed to insert the exchange difference GL entry was');
$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
$SQL = "INSERT INTO gltrans (type,
typeno,
trandate,
periodno,
account,
narrative,
amount)
VALUES (36,
'" . $ExDiffTransNo . "',
'" . FormatDateForSQL($PostingDate) . "',
'" . $PeriodNo . "',
'" . $_POST['BankAccount'] . "',
'" . $CurrencyRow['bankaccountname'] . ' ' . _('reconciliation on') . ' ' . Date($_SESSION['DefaultDateFormat']) . "',
'" . (-$ExchangeDifference) . "')";
$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
$result = DB_Txn_Commit();
prnMsg(_('Exchange difference of') . ' ' . locale_number_format($ExchangeDifference,$_SESSION['CompanyRecord']['decimalplaces']) . ' ' . _('has been posted'),'success');
} //end if the bank statement balance was numeric
}
echo '<table class="selection">';
$SQL = "SELECT bankaccounts.accountcode,
bankaccounts.bankaccountname
FROM bankaccounts, bankaccountusers
WHERE bankaccounts.accountcode=bankaccountusers.accountcode
AND bankaccountusers.userid = '" . $_SESSION['UserID'] ."'
ORDER BY bankaccounts.bankaccountname";
$ErrMsg = _('The bank accounts could not be retrieved by the SQL because');
$DbgMsg = _('The SQL used to retrieve the bank accounts was');
$AccountsResults = DB_query($SQL,$ErrMsg,$DbgMsg);
echo '<tr><td>' . _('Bank Account') . ':</td>
<td><select tabindex="1" name="BankAccount">';
if (DB_num_rows($AccountsResults)==0){
echo '</select></td>
</tr>
</table>
<p>' . _('Bank Accounts have not yet been defined') . '. ' . _('You must first') . '<a href="' . $RootPath . '/BankAccounts.php">' . _('define the bank accounts') . '</a>' . ' ' . _('and general ledger accounts to be affected') . '.';
include('includes/footer.inc');
exit;
} else {
while ($myrow=DB_fetch_array($AccountsResults)){
/*list the bank account names */
if (isset($_POST['BankAccount']) and $_POST['BankAccount']==$myrow['accountcode']){
echo '<option selected="selected" value="' . $myrow['accountcode'] . '">' . $myrow['bankaccountname'] . '</option>';
} else {
echo '<option value="' . $myrow['accountcode'] . '">' . $myrow['bankaccountname'] . '</option>';
}
}
echo '</select></td>
</tr>';
}
/*Now do the posting while the user is thinking about the bank account to select */
include ('includes/GLPostings.inc');
echo '</table>
<br />
<div class="centre">
<input type="submit" tabindex="2" name="ShowRec" value="' . _('Show bank reconciliation statement') . '" />
</div>
<br />';
if (isset($_POST['ShowRec']) OR isset($_POST['DoExchangeDifference'])){
/*Get the balance of the bank account concerned */
$sql = "SELECT MAX(period)
FROM chartdetails
WHERE accountcode='" . $_POST['BankAccount']."'";
$PrdResult = DB_query($sql);
$myrow = DB_fetch_row($PrdResult);
$LastPeriod = $myrow[0];
$SQL = "SELECT bfwd+actual AS balance
FROM chartdetails
WHERE period='" . $LastPeriod . "'
AND accountcode='" . $_POST['BankAccount']."'";
$ErrMsg = _('The bank account balance could not be returned by the SQL because');
$BalanceResult = DB_query($SQL,$ErrMsg);
$myrow = DB_fetch_row($BalanceResult);
$Balance = $myrow[0];
/* Now need to get the currency of the account and the current table ex rate */
$SQL = "SELECT rate,
bankaccounts.currcode,
bankaccounts.bankaccountname,
currencies.decimalplaces AS currdecimalplaces
FROM bankaccounts INNER JOIN currencies
ON bankaccounts.currcode=currencies.currabrev
WHERE bankaccounts.accountcode = '" . $_POST['BankAccount']."'";
$ErrMsg = _('Could not retrieve the currency and exchange rate for the selected bank account');
$CurrencyResult = DB_query($SQL);
$CurrencyRow = DB_fetch_array($CurrencyResult);
echo '<table class="selection">
<tr class="EvenTableRows">
<td colspan="6"><b>' . $CurrencyRow['bankaccountname'] . ' ' . _('Balance as at') . ' ' . Date($_SESSION['DefaultDateFormat']);
if ($_SESSION['CompanyRecord']['currencydefault']!=$CurrencyRow['currcode']){
echo ' (' . $CurrencyRow['currcode'] . ' @ ' . $CurrencyRow['rate'] .')';
}
echo '</b></td>
<td valign="bottom" class="number"><b>' . locale_number_format($Balance*$CurrencyRow['rate'],$CurrencyRow['currdecimalplaces']) . '</b></td></tr>';
$SQL = "SELECT amount/exrate AS amt,
amountcleared,
(amount/exrate)-amountcleared as outstanding,
ref,
transdate,
systypes.typename,
transno
FROM banktrans,
systypes
WHERE banktrans.type = systypes.typeid
AND banktrans.bankact='" . $_POST['BankAccount'] . "'
AND amount < 0
AND ABS((amount/exrate)-amountcleared)>0.009 ORDER BY transdate";
echo '<tr><td><br /></td></tr>'; /*Bang in a blank line */
$ErrMsg = _('The unpresented cheques could not be retrieved by the SQL because');
$UPChequesResult = DB_query($SQL, $ErrMsg);
echo '<tr>
<td colspan="6"><b>' . _('Add back unpresented cheques') . ':</b></td>
</tr>';
$TableHeader = '<tr>
<th>' . _('Date') . '</th>
<th>' . _('Type') . '</th>
<th>' . _('Number') . '</th>
<th>' . _('Reference') . '</th>
<th>' . _('Orig Amount') . '</th>
<th>' . _('Outstanding') . '</th>
</tr>';
echo $TableHeader;
$j = 1;
$k=0; //row colour counter
$TotalUnpresentedCheques =0;
while ($myrow=DB_fetch_array($UPChequesResult)) {
if ($k==1){
echo '<tr class="EvenTableRows">';
$k=0;
} else {
echo '<tr class="OddTableRows">';
$k++;
}
printf('<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td class="number">%s</td>
<td class="number">%s</td>
</tr>',
ConvertSQLDate($myrow['transdate']),
$myrow['typename'],
$myrow['transno'],
$myrow['ref'],
locale_number_format($myrow['amt'],$CurrencyRow['currdecimalplaces']),
locale_number_format($myrow['outstanding'],$CurrencyRow['currdecimalplaces']));
$TotalUnpresentedCheques +=$myrow['outstanding'];
$j++;
If ($j == 18){
$j=1;
echo $TableHeader;
}
}
//end of while loop
echo '<tr>
<td><br /></td>
</tr>
<tr class="EvenTableRows">
<td colspan="6">' . _('Total of all unpresented cheques') . '</td>
<td class="number">' . locale_number_format($TotalUnpresentedCheques,$CurrencyRow['currdecimalplaces']) . '</td>
</tr>';
$SQL = "SELECT amount/exrate AS amt,
amountcleared,
(amount/exrate)-amountcleared AS outstanding,
ref,
transdate,
systypes.typename,
transno
FROM banktrans INNER JOIN systypes
ON banktrans.type = systypes.typeid
WHERE banktrans.bankact='" . $_POST['BankAccount'] . "'
AND amount > 0
AND ABS((amount/exrate)-amountcleared)>0.009 ORDER BY transdate";
echo '<tr><td><br /></td></tr>'; /*Bang in a blank line */
$ErrMsg = _('The uncleared deposits could not be retrieved by the SQL because');
$UPChequesResult = DB_query($SQL,$ErrMsg);
echo '<tr><td colspan="6"><b>' . _('Less deposits not cleared') . ':</b></td></tr>';
$TableHeader = '<tr>
<th>' . _('Date') . '</th>
<th>' . _('Type') . '</th>
<th>' . _('Number') . '</th>
<th>' . _('Reference') . '</th>
<th>' . _('Orig Amount') . '</th>
<th>' . _('Outstanding') . '</th>
</tr>';
echo $TableHeader;
$j = 1;
$k=0; //row colour counter
$TotalUnclearedDeposits =0;
while ($myrow=DB_fetch_array($UPChequesResult)) {
if ($k==1){
echo '<tr class="EvenTableRows">';
$k=0;
} else {
echo '<tr class="OddTableRows">';
$k++;
}
printf('<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td class="number">%s</td>
<td class="number">%s</td>
</tr>',
ConvertSQLDate($myrow['transdate']),
$myrow['typename'],
$myrow['transno'],
$myrow['ref'],
locale_number_format($myrow['amt'],$CurrencyRow['currdecimalplaces']),
locale_number_format($myrow['outstanding'],$CurrencyRow['currdecimalplaces']) );
$TotalUnclearedDeposits +=$myrow['outstanding'];
$j++;
if ($j == 18){
$j=1;
echo $TableHeader;
}
}
//end of while loop
echo '<tr>
<td><br /></td>
</tr>
<tr class="EvenTableRows">
<td colspan="6">' . _('Total of all uncleared deposits') . '</td>
<td class="number">' . locale_number_format($TotalUnclearedDeposits,$CurrencyRow['currdecimalplaces']) . '</td>
</tr>';
$FXStatementBalance = ($Balance*$CurrencyRow['rate'] - $TotalUnpresentedCheques -$TotalUnclearedDeposits);
echo '<tr>
<td><br /></td>
</tr>
<tr class="EvenTableRows">
<td colspan="6"><b>' . _('Bank statement balance should be') . ' (' . $CurrencyRow['currcode'] . ')</b></td>
<td class="number">' . locale_number_format($FXStatementBalance,$CurrencyRow['currdecimalplaces']) . '</td>
</tr>';
if (isset($_POST['DoExchangeDifference'])){
echo '<input type="hidden" name="DoExchangeDifference" value="' . $FXStatementBalance . '" />';
if (!isset($_POST['BankStatementBalance'])){
$_POST['BankStatementBalance'] =0;
}
echo '<tr>
<td colspan="6">' . _('Enter the actual bank statement balance') . ' (' . $CurrencyRow['currcode'] . ')</b></td>
<td class="number"><input type="text" name="BankStatementBalance" class="number" autofocus="autofocus" required="required" maxlength="15" size="15" value="' . locale_number_format($_POST['BankStatementBalance'],$CurrencyRow['currdecimalplaces']) . '" /><td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="PostExchangeDifference" value="' . _('Calculate and Post Exchange Difference') . '" onclick="return confirm(\'' . _('This will create a general ledger journal to write off the exchange difference in the current balance of the account. It is important that the exchange rate above reflects the current value of the bank account currency') . ' - ' . _('Are You Sure?') . '\');" /></td>
</tr>';
}
if ($_SESSION['CompanyRecord']['currencydefault']!=$CurrencyRow['currcode'] AND !isset($_POST['DoExchangeDifference'])){
echo '<tr>
<td colspan="7"><hr /></td>
</tr>
<tr>
<td colspan="7">' . _('It is normal for foreign currency accounts to have exchange differences that need to be reflected as the exchange rate varies. This reconciliation is prepared using the exchange rate set up in the currencies table (see the set-up tab). This table must be maintained with the current exchange rate before running the reconciliation. If you wish to create a journal to reflect the exchange difference based on the current exchange rate to correct the reconciliation to the actual bank statement balance click below.') . '</td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="DoExchangeDifference" value="' . _('Calculate and Post Exchange Difference') . '" /></td>
</tr>';
}
echo '</table>';
}
if (isset($_POST['BankAccount'])) {
echo '<div class="centre">
<p>
<a tabindex="4" href="' . $RootPath . '/BankMatching.php?Type=Payments&Account='.$_POST['BankAccount'].'">' . _('Match off cleared payments') . '</a>
</p>
<br />
<a tabindex="5" href="' . $RootPath . '/BankMatching.php?Type=Receipts&Account='.$_POST['BankAccount'].'">' . _('Match off cleared deposits') . '</a>
</div>';
} else {
echo '<div class="centre">
<p>
<a tabindex="4" href="' . $RootPath . '/BankMatching.php?Type=Payments">' . _('Match off cleared payments') . '</a>
</p>
<br />
<a tabindex="5" href="' . $RootPath . '/BankMatching.php?Type=Receipts">' . _('Match off cleared deposits') . '</a>
</div>';
}
echo '</div>';
echo '</form>';
include('includes/footer.inc');
?>
| gpl-2.0 |
inleadmedia/ebog | sites/all/modules/ting/modules/ting_search/js/ting_search.js | 7586 |
/**
* @file ting_search.js
* JavaScript file holding most of the ting search related functions.
*/
/**
* Set up the results page.
*
* This is _not_ a Drupal.behavior, since those take a lot longer to load.
*/
$(function () {
$("#search :text")
// Put the search keys into the main searchbox.
.val(Drupal.settings.tingSearch.keys)
// And trigger the change event so that InFieldLabes will work correctly.
.change();
// Configure our tabs
$("#ting-search-tabs")
.tabs( { select: Drupal.tingSearch.selectTab } )
// Disable the website tab until we have some results.
.tabs("disable", 1);
Drupal.tingSearch.getTingData(Drupal.settings.tingSearch.ting_url,
Drupal.settings.tingSearch.keys);
Drupal.tingSearch.getContentData(Drupal.settings.tingSearch.content_url,
Drupal.settings.tingSearch.keys);
});
// Container object
Drupal.tingSearch = {
// Holds the number of results for each of the different types of search.
summary: {}
};
// Get search data from Ting
Drupal.tingSearch.getTingData = function(url, keys) {
var vars = Drupal.getAnchorVars();
vars.query = keys;
$.getJSON(url, vars, function (result) {
if (result.count > 0) {
Drupal.tingSearch.summary.ting = { count: result.count, page: result.page };
$("#ting-search-spinner").hide("normal");
// Add the template for ting result and facet browser.
$("#ting-search-placeholder").replaceWith(Drupal.settings.tingSearch.result_template);
// Pass the data on to the result and facet browser handlers.
Drupal.tingResult("#ting-search-result", "#ting-facet-browser", result);
Drupal.tingFacetBrowser("#ting-facet-browser", "#ting-search-result", result);
}
else {
window.location.href = '/nulsoegning/' + vars.query;
}
Drupal.tingSearch.updateTabs("ting");
});
};
// Get search data from Drupal's content search
Drupal.tingSearch.getContentData = function(url, keys, show) {
// Set up a params object to send along to getJSON.
var params = {};
// If we get new search keys via the keys parameter, they'll get
// attached to the object here
if (keys) {
params.query = keys;
}
$.getJSON(url, params, function (data) {
// Store some of the data returned on the tingSearch object in case
// we should need it later.
Drupal.tingSearch.summary.content = { count: data.count, page: data.page };
Drupal.tingSearch.contentData = data;
Drupal.tingSearch.updateTabs("content");
if (data.count) {
$("#content-search-result").html(Drupal.tingSearch.contentData.result_html);
if (data.feed_icon) {
if ($("#content-search-result .feed_icon").size() > 0) {
$("#content-search-result .feed_icon").replaceWith(data.feed_icon);
}
else {
$("#content-search-result").append(data.feed_icon);
}
}
// Redo the click event bindings for the contentPager, since we'll
// have a new pager from the result HTML.
Drupal.tingSearch.contentPager();
Drupal.tingSearch.updateSummary($('#content-search-summary'), data);
// If the show parameter is specified, show our results.
if (show) {
$("#content-result").show("fast", function() {
//jQuery.show adds style="display:block" after transition.
//This conflicts with jQuery.tabs as it overrides styles from
//classes and makes content results appear in other tabs even
//if that tab is not selected.
//Strip the entire style attribute to fix.
//Note: This may cause problems if other code adds inline styles
//without causing problems
$(this).removeAttr('style');
});
}
}
});
};
// Redirect clicks on the pager to reload the content search.
Drupal.tingSearch.contentPager = function() {
$("#content-result .pager a").click(function (eventObject) {
$("#content-result").hide("fast");
$("#ting-search-spinner").show("normal");
Drupal.tingSearch.getContentData(this.href, false, true);
return false;
});
};
Drupal.tingSearch.tabLoading = function (sender) {
if (Drupal.tingSearch.summary.hasOwnProperty(sender)) {
var result, tab;
tab = $('#ting-search-tabs li.' + sender);
tab.addClass('spinning').find('span.count').remove();
result = $("#" + sender + "-result");
result.addClass('loading');
}
};
// Helper function to update the state of our tabs.
Drupal.tingSearch.updateTabs = function (sender) {
if (Drupal.tingSearch.summary.hasOwnProperty(sender)) {
var tab, count, result;
tab = $('#ting-search-tabs li.' + sender);
count = Drupal.tingSearch.summary[sender].count;
result = $("#" + sender + "-result");
if (count == 0) {
// For no results, replace the contents of the results container
// with the no results message.
result.html('<h4>' + Drupal.settings.tingResult.noResultsHeader + '</h4><p>' + Drupal.settings.tingResult.noResultsText + '</p>');
}
else if (sender == 'content') {
// If we have a non-zero result count for content, enable its tab.
$("#ting-search-tabs").tabs("enable", 1);
}
tab.removeClass('spinning');
result.removeClass('loading');
if (tab.find('span.count').length) {
tab.find('span.count em').text(count);
}
else {
tab.find('a').append(' <span class="count">(<em>' + count + '</em>)</span>');
}
}
if (Drupal.tingSearch.summary.hasOwnProperty("ting") && Drupal.tingSearch.summary.hasOwnProperty("content")) {
// When both searches has returned, make sure that we're in a
// reasonably consistent state.
$("#ting-search-spinner").hide("normal");
// If there were no results from Ting and website results available,
// switch to the website tab and diable the Ting tab.
if (Drupal.tingSearch.summary.ting.count == 0 && Drupal.tingSearch.summary.content.count > 0) {
$("#ting-search-tabs")
.tabs("select", 1)
.tabs("disable", 0);
}
}
};
Drupal.tingSearch.updateSummary = function (element, result) {
element.find('.count').text(result.count);
element.find('.firstResult').text((result.page - 1) * result.resultsPerPage + 1);
element.find('.lastResult').text(Math.min(result.count, result.page * result.resultsPerPage));
};
Drupal.tingSearch.selectTab = function (event, ui) {
window.location.href = $(ui.tab).attr('href');
if (window.location.href.lastIndexOf('#ting-result') > -1) {
//facet browser elements do not have dimensions before their tab is shown
//so wait bit before updating them
window.setTimeout(function() {
Drupal.resetFacetBrowser('#ting-facet-browser');
Drupal.bindResizeEvent('#ting-facet-browser');
Drupal.bindSelectEvent("#ting-facet-browser", "#ting-search-result");
Drupal.resizeFacets('#ting-facet-browser');
}, 250);
}
};
Drupal.getAnchorVars = function() {
anchorValues = {};
if (!jQuery.url) {
return anchorValues;
}
anchor = jQuery.url.attr('anchor');
anchor = (anchor == null) ? '' : anchor;
anchor = anchor.split('&');
for (a in anchor) {
keyValue = anchor[a].split('=');
if (keyValue.length > 1) {
anchorValues[keyValue[0]] = keyValue[1];
}
}
return anchorValues;
};
Drupal.setAnchorVars = function(vars) {
anchorArray = new Array();
for (v in vars) {
anchorArray.push(v + '=' + vars[v]);
}
anchorString = anchorArray.join('&');
window.location.hash = '#' + anchorString;
};
| gpl-2.0 |
SirBirne/PearOS | common/source/fs/FileSystemType.cpp | 636 | /**
* @file FileSystemType.cpp
*/
#include "fs/FileSystemType.h"
#include "assert.h"
FileSystemType::FileSystemType(const char *fs_name) :
fs_name_ ( fs_name ),
fs_flags_ ( 0 )
{}
FileSystemType::~FileSystemType()
{}
const char* FileSystemType::getFSName() const
{
return fs_name_;
}
int32 FileSystemType::getFSFlags() const
{
return fs_flags_;
}
Superblock *FileSystemType::readSuper ( Superblock* /*superblock*/, void* /*data*/ ) const
{
assert ( 0 );
return ( 0 );
}
Superblock *FileSystemType::createSuper ( Dentry* /*dentry*/, uint32 /*s_dev*/ ) const
{
assert ( 0 );
return ( Superblock* ) 0;
}
| gpl-2.0 |
ruancarvalho/wda-theme | search.php | 1108 | <?php
/**
* The template for displaying search results pages.
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
*
* @package wda-theme
*/
get_header(); ?>
<section id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( esc_html__( 'Search Results for: %s', 'wda-theme' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header><!-- .page-header -->
<?php
/* Start the Loop */
while ( have_posts() ) : the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/content', 'search' );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
</main><!-- #main -->
</section><!-- #primary -->
<?php
get_sidebar();
get_footer();
| gpl-2.0 |
crftr/axis_snap | WindowsService1/ProjectInstaller.cs | 338 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
namespace WindowsService1
{
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
}
} | gpl-2.0 |
fdtarzan/ITStep | Lesson8/WindowsFormsApplication1/User.cs | 351 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
class User
{
public string Name { set; get; }
public int Id { set; get; }
public DateTime Time { set; get; }
public double Doubled { set; get; }
}
}
| gpl-2.0 |
andrewtf/drupal8-badcamp | sites/default/files/php/twig/1#2a#60#a85414938471bcbbf154335b7bf45942ca995349b1622d6bf3be6f20c4d5/b603f061f2800c16e3cf40480b2b0c12fde78615267aabd4d200206cd0d8d83f.php | 1397 | <?php
/* core/modules/system/templates/form.html.twig */
class __TwigTemplate_2a60a85414938471bcbbf154335b7bf45942ca995349b1622d6bf3be6f20c4d5 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 15
echo "<form";
echo twig_drupal_escape_filter($this->env, (isset($context["attributes"]) ? $context["attributes"] : null), "html", null, true);
echo ">
";
// line 16
echo twig_drupal_escape_filter($this->env, (isset($context["children"]) ? $context["children"] : null), "html", null, true);
echo "
</form>
";
}
public function getTemplateName()
{
return "core/modules/system/templates/form.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 73 => 46, 65 => 44, 62 => 43, 56 => 41, 54 => 40, 49 => 39, 43 => 37, 41 => 36, 33 => 33, 26 => 31, 24 => 16, 95 => 87, 89 => 84, 84 => 83, 81 => 82, 75 => 80, 72 => 79, 66 => 77, 64 => 76, 59 => 75, 53 => 72, 48 => 71, 45 => 70, 39 => 68, 36 => 67, 30 => 65, 28 => 32, 23 => 25, 21 => 24, 19 => 15,);
}
}
| gpl-2.0 |
telemed-duth/Metamorphosis-Meducator | mod/companion/views/default/companion/edit/form.php | 2102 | <script type="text/javascript" src="jquery.asmselect.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select[multiple]").asmSelect({
addItemTarget: 'bottom',
animate: true,
highlight: true,
sortable: true
});
});
</script>
<link rel="stylesheet" type="text/css" href="jquery.asmselect.css" />
<?php $luser=$_SESSION['guid'];
$orguid=$_GET['compost'];
$original=get_entity($orguid);
?>
<div class="contentWrapper">
<form id="myForm" action="<?php echo $vars['url']; ?>action/companion/edit" method="post">
<p><?php echo "Collection Title";?><br />
<?php echo elgg_view('input/text',array('internalname' => 'title','value' =>$original->title)); ?></p>
<p><?php echo "Collection Description"; ?><br />
<?php echo elgg_view('input/longtext',array('internalname' => 'body','value' =>$original->description)); ?></p>
<p><?php echo "Collection Keywords"; ?><br />
<?php echo elgg_view('input/tags',array('internalname' => 'tags','value' =>$original->tags)); ?></p>
<p><?php echo "Please select the resources to add to this collection"; ?><br />
<select name="resources[]" multiple="multiple">
<?php
$query4= "SELECT guid FROM {$CONFIG->dbprefix}_content_item_discrimination WHERE creator_guid = \"".$luser."\" and is_content_item = \"1\"";
$result4 = mysql_query($query4);
while($row = mysql_fetch_array($result4, MYSQL_ASSOC))
{ $nikolas4=$row['guid'];
if (get_entity($nikolas4)){
$nikob=get_user($nikolas4);
$objur=$nikob->getURL();
echo "<option value=\"$nikob->guid\">";
echo $nikob->name;
echo "</option>"; }
}
?>
</select> </p>
<?php
$ori=implode(",",$original->identifiers);
echo elgg_view('input/hidden',array('internalname' => 'oriden','value' =>$ori)); ?></p>
<?php echo elgg_view('input/hidden',array('internalname' => 'orgu','value' =>$original->guid)); ?></p>
<?php echo elgg_view('input/securitytoken'); ?>
<p><?php echo elgg_view('input/submit', array('value' => elgg_echo('save'))); ?></p>
</form>
</div> | gpl-2.0 |
marioaugustorama/uzix-apps | SIMPLE/RENICE.C | 2329 | /* renice.c vr. 1.0
* descripton: change processes priority
* author: Adriano Cunha <adrcunha@dcc.unicamp.br>
* license: GNU Public License version 2
*/
#include <stdio.h>
#include <syscalls.h>
#include <unix.h>
#include <string.h>
#include <pwd.h>
#include <stdlib.h>
#define CHG_PID 1
#define CHG_GRP 2
#define CHG_USER 3
#define NONE 0
int verifynice(char nice) {
if (nice < -20 || nice > 19) {
printf("renice: invalid priority value\n");
exit(1);
}
}
int main(argc, argv)
int argc;
char **argv;
{
char *pp, *nicestr;
char oldnice, nice, useridknown, niced;
char mode = CHG_PID;
info_t info;
ptptr p;
int i, value, err = 0;
struct passwd *pwd;
struct s_pdata pdata;
argc--;
argv++;
if (argc < 2) {
printf("usage: renice [+]prio [[-p] pid...] [-g pgrp...] [-u user...]\n");
exit(1);
}
nicestr = *argv++;
verifynice(nice = atoi(nicestr));
argc--;
getfsys(GI_PTAB, &info);
while (argc > 0) {
argc--;
pp = *argv++ ;
if (!strcmp("-p", pp)) {
mode = CHG_PID;
continue;
}
if (!strcmp("-g", pp)) {
mode = CHG_GRP;
continue;
}
if (!strcmp("-u", pp)) {
mode = CHG_USER;
continue;
}
value = atoi(pp);
if (mode == CHG_USER) {
if ((pwd = getpwnam(pp)) != NULL) value = pwd->pw_uid;
else {
printf("renice: unknown user %s\n", pp);
exit(1);
}
}
niced = 0;
for (p = (ptptr)info.ptr, i = 0; i < info.size; ++i, ++p) {
if (p->p_status < P_READY) continue;
if (mode == CHG_PID && p->p_pid != value) continue;
if (mode == CHG_USER && p->p_uid != value) continue;
if (mode == CHG_GRP) {
pdata.u_pid = p->p_pid;
if (getfsys(GI_PDAT, &pdata) < 0) continue;
if (pdata.u_gid != value) continue;
}
oldnice = p->p_nice;
nice = atoi(nicestr);
if (*nicestr == '+') nice = oldnice + atoi(++nicestr);
verifynice(nice);
if (setprio(p->p_pid, nice) < 0) {
printf("PID %d: %s\n", p->p_pid, strerror(errno));
err = 1;
}
niced = 1;
}
if (!niced) {
printf("renice: no process found with");
if (mode == CHG_PID) printf(" pid %d\n", value);
if (mode == CHG_GRP) printf(" group id %d\n", value);
if (mode == CHG_USER) printf(" owner %s\n", pp);
err = 1;
}
}
return (err);
}
| gpl-2.0 |
jramosdc/politiciansgrader | include/footer.php | 1361 | <!--
<tr>
<td colspan="3" align="left" width="1000" valign="top">
<table width="1000" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="left" width="11" valign="top" class="left_bottom_corner"> </td>
<td valign="top" width="978" align="center" class="center_bottom_line"> </td>
<td align="right" width="11" valign="top" class="right_bottom_corner"> </td>
</tr>
</table>
</td>
</tr>
-->
<footer>
<div style="width:100%; float:left; margin-top:70px;">
<hr>
<!-- Purchase a site license to remove this link from the footer: http://www.portnine.com/bootstrap-themes -->
<p class="pull-right">Developed by:<a target="_blank" href="http://www.milliardinfoworld.com/">Milliard Infoworld</a></p>
<p> Copyright <?php echo COPY_RIGHT_SENTENCE; ?>, All rights reserved.</a></p>
</div>
</footer>
<script type="text/javascript" src="<?php echo ADMIN_THEME; ?>css/bootstrap/js/bootstrap.js"></script>
</body>
</html> | gpl-2.0 |
gltn/stdm | stdm/third_party/sqlalchemy/orm/mapper.py | 130942 | # orm/mapper.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Logic to map Python classes to and from selectables.
Defines the :class:`~sqlalchemy.orm.mapper.Mapper` class, the central
configurational unit which associates a class with a database table.
This is a semi-private module; the main configurational API of the ORM is
available in :class:`~sqlalchemy.orm.`.
"""
from __future__ import absolute_import
from collections import deque
from itertools import chain
import sys
import types
import weakref
from . import attributes
from . import exc as orm_exc
from . import instrumentation
from . import loading
from . import properties
from . import util as orm_util
from .base import _class_to_mapper
from .base import _INSTRUMENTOR
from .base import _state_mapper
from .base import class_mapper
from .base import state_str
from .interfaces import _MappedAttribute
from .interfaces import EXT_SKIP
from .interfaces import InspectionAttr
from .interfaces import MapperProperty
from .path_registry import PathRegistry
from .. import event
from .. import exc as sa_exc
from .. import inspection
from .. import log
from .. import schema
from .. import sql
from .. import util
from ..sql import expression
from ..sql import operators
from ..sql import util as sql_util
from ..sql import visitors
_mapper_registry = weakref.WeakKeyDictionary()
_already_compiling = False
_memoized_configured_property = util.group_expirable_memoized_property()
# a constant returned by _get_attr_by_column to indicate
# this mapper is not handling an attribute for a particular
# column
NO_ATTRIBUTE = util.symbol("NO_ATTRIBUTE")
# lock used to synchronize the "mapper configure" step
_CONFIGURE_MUTEX = util.threading.RLock()
@inspection._self_inspects
@log.class_logger
class Mapper(InspectionAttr):
"""Define the correlation of class attributes to database table
columns.
The :class:`_orm.Mapper` object is instantiated using the
:func:`~sqlalchemy.orm.mapper` function. For information
about instantiating new :class:`_orm.Mapper` objects, see
that function's documentation.
When :func:`.mapper` is used
explicitly to link a user defined class with table
metadata, this is referred to as *classical mapping*.
Modern SQLAlchemy usage tends to favor the
:mod:`sqlalchemy.ext.declarative` extension for class
configuration, which
makes usage of :func:`.mapper` behind the scenes.
Given a particular class known to be mapped by the ORM,
the :class:`_orm.Mapper` which maintains it can be acquired
using the :func:`_sa.inspect` function::
from sqlalchemy import inspect
mapper = inspect(MyClass)
A class which was mapped by the :mod:`sqlalchemy.ext.declarative`
extension will also have its mapper available via the ``__mapper__``
attribute.
"""
_new_mappers = False
_dispose_called = False
@util.deprecated_params(
extension=(
"0.7",
":class:`.MapperExtension` is deprecated in favor of the "
":class:`.MapperEvents` listener interface. The "
":paramref:`.mapper.extension` parameter will be "
"removed in a future release.",
),
order_by=(
"1.1",
"The :paramref:`.mapper.order_by` parameter "
"is deprecated, and will be removed in a future release. "
"Use :meth:`_query.Query.order_by` "
"to determine the ordering of a "
"result set.",
),
non_primary=(
"1.3",
"The :paramref:`.mapper.non_primary` parameter is deprecated, "
"and will be removed in a future release. The functionality "
"of non primary mappers is now better suited using the "
":class:`.AliasedClass` construct, which can also be used "
"as the target of a :func:`_orm.relationship` in 1.3.",
),
)
def __init__(
self,
class_,
local_table=None,
properties=None,
primary_key=None,
non_primary=False,
inherits=None,
inherit_condition=None,
inherit_foreign_keys=None,
extension=None,
order_by=False,
always_refresh=False,
version_id_col=None,
version_id_generator=None,
polymorphic_on=None,
_polymorphic_map=None,
polymorphic_identity=None,
concrete=False,
with_polymorphic=None,
polymorphic_load=None,
allow_partial_pks=True,
batch=True,
column_prefix=None,
include_properties=None,
exclude_properties=None,
passive_updates=True,
passive_deletes=False,
confirm_deleted_rows=True,
eager_defaults=False,
legacy_is_orphan=False,
_compiled_cache_size=100,
):
r"""Return a new :class:`_orm.Mapper` object.
This function is typically used behind the scenes
via the Declarative extension. When using Declarative,
many of the usual :func:`.mapper` arguments are handled
by the Declarative extension itself, including ``class_``,
``local_table``, ``properties``, and ``inherits``.
Other options are passed to :func:`.mapper` using
the ``__mapper_args__`` class variable::
class MyClass(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
type = Column(String(50))
alt = Column("some_alt", Integer)
__mapper_args__ = {
'polymorphic_on' : type
}
Explicit use of :func:`.mapper`
is often referred to as *classical mapping*. The above
declarative example is equivalent in classical form to::
my_table = Table("my_table", metadata,
Column('id', Integer, primary_key=True),
Column('type', String(50)),
Column("some_alt", Integer)
)
class MyClass(object):
pass
mapper(MyClass, my_table,
polymorphic_on=my_table.c.type,
properties={
'alt':my_table.c.some_alt
})
.. seealso::
:ref:`classical_mapping` - discussion of direct usage of
:func:`.mapper`
:param class\_: The class to be mapped. When using Declarative,
this argument is automatically passed as the declared class
itself.
:param local_table: The :class:`_schema.Table` or other selectable
to which the class is mapped. May be ``None`` if
this mapper inherits from another mapper using single-table
inheritance. When using Declarative, this argument is
automatically passed by the extension, based on what
is configured via the ``__table__`` argument or via the
:class:`_schema.Table`
produced as a result of the ``__tablename__``
and :class:`_schema.Column` arguments present.
:param always_refresh: If True, all query operations for this mapped
class will overwrite all data within object instances that already
exist within the session, erasing any in-memory changes with
whatever information was loaded from the database. Usage of this
flag is highly discouraged; as an alternative, see the method
:meth:`_query.Query.populate_existing`.
:param allow_partial_pks: Defaults to True. Indicates that a
composite primary key with some NULL values should be considered as
possibly existing within the database. This affects whether a
mapper will assign an incoming row to an existing identity, as well
as if :meth:`.Session.merge` will check the database first for a
particular primary key value. A "partial primary key" can occur if
one has mapped to an OUTER JOIN, for example.
:param batch: Defaults to ``True``, indicating that save operations
of multiple entities can be batched together for efficiency.
Setting to False indicates
that an instance will be fully saved before saving the next
instance. This is used in the extremely rare case that a
:class:`.MapperEvents` listener requires being called
in between individual row persistence operations.
:param column_prefix: A string which will be prepended
to the mapped attribute name when :class:`_schema.Column`
objects are automatically assigned as attributes to the
mapped class. Does not affect explicitly specified
column-based properties.
See the section :ref:`column_prefix` for an example.
:param concrete: If True, indicates this mapper should use concrete
table inheritance with its parent mapper.
See the section :ref:`concrete_inheritance` for an example.
:param confirm_deleted_rows: defaults to True; when a DELETE occurs
of one more rows based on specific primary keys, a warning is
emitted when the number of rows matched does not equal the number
of rows expected. This parameter may be set to False to handle the
case where database ON DELETE CASCADE rules may be deleting some of
those rows automatically. The warning may be changed to an
exception in a future release.
.. versionadded:: 0.9.4 - added
:paramref:`.mapper.confirm_deleted_rows` as well as conditional
matched row checking on delete.
:param eager_defaults: if True, the ORM will immediately fetch the
value of server-generated default values after an INSERT or UPDATE,
rather than leaving them as expired to be fetched on next access.
This can be used for event schemes where the server-generated values
are needed immediately before the flush completes. By default,
this scheme will emit an individual ``SELECT`` statement per row
inserted or updated, which note can add significant performance
overhead. However, if the
target database supports :term:`RETURNING`, the default values will
be returned inline with the INSERT or UPDATE statement, which can
greatly enhance performance for an application that needs frequent
access to just-generated server defaults.
.. seealso::
:ref:`orm_server_defaults`
.. versionchanged:: 0.9.0 The ``eager_defaults`` option can now
make use of :term:`RETURNING` for backends which support it.
:param exclude_properties: A list or set of string column names to
be excluded from mapping.
See :ref:`include_exclude_cols` for an example.
:param extension: A :class:`.MapperExtension` instance or
list of :class:`.MapperExtension` instances which will be applied
to all operations by this :class:`_orm.Mapper`.
:param include_properties: An inclusive list or set of string column
names to map.
See :ref:`include_exclude_cols` for an example.
:param inherits: A mapped class or the corresponding
:class:`_orm.Mapper`
of one indicating a superclass to which this :class:`_orm.Mapper`
should *inherit* from. The mapped class here must be a subclass
of the other mapper's class. When using Declarative, this argument
is passed automatically as a result of the natural class
hierarchy of the declared classes.
.. seealso::
:ref:`inheritance_toplevel`
:param inherit_condition: For joined table inheritance, a SQL
expression which will
define how the two tables are joined; defaults to a natural join
between the two tables.
:param inherit_foreign_keys: When ``inherit_condition`` is used and
the columns present are missing a :class:`_schema.ForeignKey`
configuration, this parameter can be used to specify which columns
are "foreign". In most cases can be left as ``None``.
:param legacy_is_orphan: Boolean, defaults to ``False``.
When ``True``, specifies that "legacy" orphan consideration
is to be applied to objects mapped by this mapper, which means
that a pending (that is, not persistent) object is auto-expunged
from an owning :class:`.Session` only when it is de-associated
from *all* parents that specify a ``delete-orphan`` cascade towards
this mapper. The new default behavior is that the object is
auto-expunged when it is de-associated with *any* of its parents
that specify ``delete-orphan`` cascade. This behavior is more
consistent with that of a persistent object, and allows behavior to
be consistent in more scenarios independently of whether or not an
orphan object has been flushed yet or not.
See the change note and example at :ref:`legacy_is_orphan_addition`
for more detail on this change.
:param non_primary: Specify that this :class:`_orm.Mapper`
is in addition
to the "primary" mapper, that is, the one used for persistence.
The :class:`_orm.Mapper` created here may be used for ad-hoc
mapping of the class to an alternate selectable, for loading
only.
:paramref:`_orm.Mapper.non_primary` is not an often used option, but
is useful in some specific :func:`_orm.relationship` cases.
.. seealso::
:ref:`relationship_non_primary_mapper`
:param order_by: A single :class:`_schema.Column` or list of
:class:`_schema.Column`
objects for which selection operations should use as the default
ordering for entities. By default mappers have no pre-defined
ordering.
:param passive_deletes: Indicates DELETE behavior of foreign key
columns when a joined-table inheritance entity is being deleted.
Defaults to ``False`` for a base mapper; for an inheriting mapper,
defaults to ``False`` unless the value is set to ``True``
on the superclass mapper.
When ``True``, it is assumed that ON DELETE CASCADE is configured
on the foreign key relationships that link this mapper's table
to its superclass table, so that when the unit of work attempts
to delete the entity, it need only emit a DELETE statement for the
superclass table, and not this table.
When ``False``, a DELETE statement is emitted for this mapper's
table individually. If the primary key attributes local to this
table are unloaded, then a SELECT must be emitted in order to
validate these attributes; note that the primary key columns
of a joined-table subclass are not part of the "primary key" of
the object as a whole.
Note that a value of ``True`` is **always** forced onto the
subclass mappers; that is, it's not possible for a superclass
to specify passive_deletes without this taking effect for
all subclass mappers.
.. versionadded:: 1.1
.. seealso::
:ref:`passive_deletes` - description of similar feature as
used with :func:`_orm.relationship`
:paramref:`.mapper.passive_updates` - supporting ON UPDATE
CASCADE for joined-table inheritance mappers
:param passive_updates: Indicates UPDATE behavior of foreign key
columns when a primary key column changes on a joined-table
inheritance mapping. Defaults to ``True``.
When True, it is assumed that ON UPDATE CASCADE is configured on
the foreign key in the database, and that the database will handle
propagation of an UPDATE from a source column to dependent columns
on joined-table rows.
When False, it is assumed that the database does not enforce
referential integrity and will not be issuing its own CASCADE
operation for an update. The unit of work process will
emit an UPDATE statement for the dependent columns during a
primary key change.
.. seealso::
:ref:`passive_updates` - description of a similar feature as
used with :func:`_orm.relationship`
:paramref:`.mapper.passive_deletes` - supporting ON DELETE
CASCADE for joined-table inheritance mappers
:param polymorphic_load: Specifies "polymorphic loading" behavior
for a subclass in an inheritance hierarchy (joined and single
table inheritance only). Valid values are:
* "'inline'" - specifies this class should be part of the
"with_polymorphic" mappers, e.g. its columns will be included
in a SELECT query against the base.
* "'selectin'" - specifies that when instances of this class
are loaded, an additional SELECT will be emitted to retrieve
the columns specific to this subclass. The SELECT uses
IN to fetch multiple subclasses at once.
.. versionadded:: 1.2
.. seealso::
:ref:`with_polymorphic_mapper_config`
:ref:`polymorphic_selectin`
:param polymorphic_on: Specifies the column, attribute, or
SQL expression used to determine the target class for an
incoming row, when inheriting classes are present.
This value is commonly a :class:`_schema.Column` object that's
present in the mapped :class:`_schema.Table`::
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
discriminator = Column(String(50))
__mapper_args__ = {
"polymorphic_on":discriminator,
"polymorphic_identity":"employee"
}
It may also be specified
as a SQL expression, as in this example where we
use the :func:`.case` construct to provide a conditional
approach::
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
discriminator = Column(String(50))
__mapper_args__ = {
"polymorphic_on":case([
(discriminator == "EN", "engineer"),
(discriminator == "MA", "manager"),
], else_="employee"),
"polymorphic_identity":"employee"
}
It may also refer to any attribute
configured with :func:`.column_property`, or to the
string name of one::
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
discriminator = Column(String(50))
employee_type = column_property(
case([
(discriminator == "EN", "engineer"),
(discriminator == "MA", "manager"),
], else_="employee")
)
__mapper_args__ = {
"polymorphic_on":employee_type,
"polymorphic_identity":"employee"
}
When setting ``polymorphic_on`` to reference an
attribute or expression that's not present in the
locally mapped :class:`_schema.Table`, yet the value
of the discriminator should be persisted to the database,
the value of the
discriminator is not automatically set on new
instances; this must be handled by the user,
either through manual means or via event listeners.
A typical approach to establishing such a listener
looks like::
from sqlalchemy import event
from sqlalchemy.orm import object_mapper
@event.listens_for(Employee, "init", propagate=True)
def set_identity(instance, *arg, **kw):
mapper = object_mapper(instance)
instance.discriminator = mapper.polymorphic_identity
Where above, we assign the value of ``polymorphic_identity``
for the mapped class to the ``discriminator`` attribute,
thus persisting the value to the ``discriminator`` column
in the database.
.. warning::
Currently, **only one discriminator column may be set**, typically
on the base-most class in the hierarchy. "Cascading" polymorphic
columns are not yet supported.
.. seealso::
:ref:`inheritance_toplevel`
:param polymorphic_identity: Specifies the value which
identifies this particular class as returned by the
column expression referred to by the ``polymorphic_on``
setting. As rows are received, the value corresponding
to the ``polymorphic_on`` column expression is compared
to this value, indicating which subclass should
be used for the newly reconstructed object.
:param properties: A dictionary mapping the string names of object
attributes to :class:`.MapperProperty` instances, which define the
persistence behavior of that attribute. Note that
:class:`_schema.Column`
objects present in
the mapped :class:`_schema.Table` are automatically placed into
``ColumnProperty`` instances upon mapping, unless overridden.
When using Declarative, this argument is passed automatically,
based on all those :class:`.MapperProperty` instances declared
in the declared class body.
:param primary_key: A list of :class:`_schema.Column`
objects which define
the primary key to be used against this mapper's selectable unit.
This is normally simply the primary key of the ``local_table``, but
can be overridden here.
:param version_id_col: A :class:`_schema.Column`
that will be used to keep a running version id of rows
in the table. This is used to detect concurrent updates or
the presence of stale data in a flush. The methodology is to
detect if an UPDATE statement does not match the last known
version id, a
:class:`~sqlalchemy.orm.exc.StaleDataError` exception is
thrown.
By default, the column must be of :class:`.Integer` type,
unless ``version_id_generator`` specifies an alternative version
generator.
.. seealso::
:ref:`mapper_version_counter` - discussion of version counting
and rationale.
:param version_id_generator: Define how new version ids should
be generated. Defaults to ``None``, which indicates that
a simple integer counting scheme be employed. To provide a custom
versioning scheme, provide a callable function of the form::
def generate_version(version):
return next_version
Alternatively, server-side versioning functions such as triggers,
or programmatic versioning schemes outside of the version id
generator may be used, by specifying the value ``False``.
Please see :ref:`server_side_version_counter` for a discussion
of important points when using this option.
.. versionadded:: 0.9.0 ``version_id_generator`` supports
server-side version number generation.
.. seealso::
:ref:`custom_version_counter`
:ref:`server_side_version_counter`
:param with_polymorphic: A tuple in the form ``(<classes>,
<selectable>)`` indicating the default style of "polymorphic"
loading, that is, which tables are queried at once. <classes> is
any single or list of mappers and/or classes indicating the
inherited classes that should be loaded at once. The special value
``'*'`` may be used to indicate all descending classes should be
loaded immediately. The second tuple argument <selectable>
indicates a selectable that will be used to query for multiple
classes.
.. seealso::
:ref:`with_polymorphic` - discussion of polymorphic querying
techniques.
"""
self.class_ = util.assert_arg_type(class_, type, "class_")
self.class_manager = None
self._primary_key_argument = util.to_list(primary_key)
self.non_primary = non_primary
if order_by is not False:
self.order_by = util.to_list(order_by)
else:
self.order_by = order_by
self.always_refresh = always_refresh
if isinstance(version_id_col, MapperProperty):
self.version_id_prop = version_id_col
self.version_id_col = None
else:
self.version_id_col = version_id_col
if version_id_generator is False:
self.version_id_generator = False
elif version_id_generator is None:
self.version_id_generator = lambda x: (x or 0) + 1
else:
self.version_id_generator = version_id_generator
self.concrete = concrete
self.single = False
self.inherits = inherits
self.local_table = local_table
self.inherit_condition = inherit_condition
self.inherit_foreign_keys = inherit_foreign_keys
self._init_properties = properties or {}
self._delete_orphans = []
self.batch = batch
self.eager_defaults = eager_defaults
self.column_prefix = column_prefix
self.polymorphic_on = expression._clause_element_as_expr(
polymorphic_on
)
self._dependency_processors = []
self.validators = util.immutabledict()
self.passive_updates = passive_updates
self.passive_deletes = passive_deletes
self.legacy_is_orphan = legacy_is_orphan
self._clause_adapter = None
self._requires_row_aliasing = False
self._inherits_equated_pairs = None
self._memoized_values = {}
self._compiled_cache_size = _compiled_cache_size
self._reconstructor = None
self._deprecated_extensions = util.to_list(extension or [])
self.allow_partial_pks = allow_partial_pks
if self.inherits and not self.concrete:
self.confirm_deleted_rows = False
else:
self.confirm_deleted_rows = confirm_deleted_rows
if isinstance(self.local_table, expression.SelectBase):
raise sa_exc.InvalidRequestError(
"When mapping against a select() construct, map against "
"an alias() of the construct instead."
"This because several databases don't allow a "
"SELECT from a subquery that does not have an alias."
)
self._set_with_polymorphic(with_polymorphic)
self.polymorphic_load = polymorphic_load
# our 'polymorphic identity', a string name that when located in a
# result set row indicates this Mapper should be used to construct
# the object instance for that row.
self.polymorphic_identity = polymorphic_identity
# a dictionary of 'polymorphic identity' names, associating those
# names with Mappers that will be used to construct object instances
# upon a select operation.
if _polymorphic_map is None:
self.polymorphic_map = {}
else:
self.polymorphic_map = _polymorphic_map
if include_properties is not None:
self.include_properties = util.to_set(include_properties)
else:
self.include_properties = None
if exclude_properties:
self.exclude_properties = util.to_set(exclude_properties)
else:
self.exclude_properties = None
self.configured = False
# prevent this mapper from being constructed
# while a configure_mappers() is occurring (and defer a
# configure_mappers() until construction succeeds)
_CONFIGURE_MUTEX.acquire()
try:
self.dispatch._events._new_mapper_instance(class_, self)
self._configure_inheritance()
self._configure_legacy_instrument_class()
self._configure_class_instrumentation()
self._configure_listeners()
self._configure_properties()
self._configure_polymorphic_setter()
self._configure_pks()
Mapper._new_mappers = True
self._log("constructed")
self._expire_memoizations()
finally:
_CONFIGURE_MUTEX.release()
# major attributes initialized at the classlevel so that
# they can be Sphinx-documented.
is_mapper = True
"""Part of the inspection API."""
represents_outer_join = False
@property
def mapper(self):
"""Part of the inspection API.
Returns self.
"""
return self
@property
def entity(self):
r"""Part of the inspection API.
Returns self.class\_.
"""
return self.class_
local_table = None
"""The :class:`_expression.Selectable` which this :class:`_orm.Mapper`
manages.
Typically is an instance of :class:`_schema.Table` or
:class:`_expression.Alias`.
May also be ``None``.
The "local" table is the
selectable that the :class:`_orm.Mapper` is directly responsible for
managing from an attribute access and flush perspective. For
non-inheriting mappers, the local table is the same as the
"mapped" table. For joined-table inheritance mappers, local_table
will be the particular sub-table of the overall "join" which
this :class:`_orm.Mapper` represents. If this mapper is a
single-table inheriting mapper, local_table will be ``None``.
.. seealso::
:attr:`_orm.Mapper.persist_selectable`.
"""
persist_selectable = None
"""The :class:`_expression.Selectable` to which this :class:`_orm.Mapper`
is mapped.
Typically an instance of :class:`_schema.Table`,
:class:`_expression.Join`, or :class:`_expression.Alias`.
The :attr:`_orm.Mapper.persist_selectable` is separate from
:attr:`_orm.Mapper.selectable` in that the former represents columns
that are mapped on this class or its superclasses, whereas the
latter may be a "polymorphic" selectable that contains additional columns
which are in fact mapped on subclasses only.
"persist selectable" is the "thing the mapper writes to" and
"selectable" is the "thing the mapper selects from".
:attr:`_orm.Mapper.persist_selectable` is also separate from
:attr:`_orm.Mapper.local_table`, which represents the set of columns that
are locally mapped on this class directly.
.. seealso::
:attr:`_orm.Mapper.selectable`.
:attr:`_orm.Mapper.local_table`.
"""
inherits = None
"""References the :class:`_orm.Mapper` which this :class:`_orm.Mapper`
inherits from, if any.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
configured = None
"""Represent ``True`` if this :class:`_orm.Mapper` has been configured.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
.. seealso::
:func:`.configure_mappers`.
"""
concrete = None
"""Represent ``True`` if this :class:`_orm.Mapper` is a concrete
inheritance mapper.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
tables = None
"""An iterable containing the collection of :class:`_schema.Table` objects
which this :class:`_orm.Mapper` is aware of.
If the mapper is mapped to a :class:`_expression.Join`, or an
:class:`_expression.Alias`
representing a :class:`_expression.Select`, the individual
:class:`_schema.Table`
objects that comprise the full construct will be represented here.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
primary_key = None
"""An iterable containing the collection of :class:`_schema.Column`
objects
which comprise the 'primary key' of the mapped table, from the
perspective of this :class:`_orm.Mapper`.
This list is against the selectable in
:attr:`_orm.Mapper.persist_selectable`.
In the case of inheriting mappers, some columns may be managed by a
superclass mapper. For example, in the case of a
:class:`_expression.Join`, the
primary key is determined by all of the primary key columns across all
tables referenced by the :class:`_expression.Join`.
The list is also not necessarily the same as the primary key column
collection associated with the underlying tables; the :class:`_orm.Mapper`
features a ``primary_key`` argument that can override what the
:class:`_orm.Mapper` considers as primary key columns.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
class_ = None
"""The Python class which this :class:`_orm.Mapper` maps.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
class_manager = None
"""The :class:`.ClassManager` which maintains event listeners
and class-bound descriptors for this :class:`_orm.Mapper`.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
single = None
"""Represent ``True`` if this :class:`_orm.Mapper` is a single table
inheritance mapper.
:attr:`_orm.Mapper.local_table` will be ``None`` if this flag is set.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
non_primary = None
"""Represent ``True`` if this :class:`_orm.Mapper` is a "non-primary"
mapper, e.g. a mapper that is used only to select rows but not for
persistence management.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
polymorphic_on = None
"""The :class:`_schema.Column` or SQL expression specified as the
``polymorphic_on`` argument
for this :class:`_orm.Mapper`, within an inheritance scenario.
This attribute is normally a :class:`_schema.Column` instance but
may also be an expression, such as one derived from
:func:`.cast`.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
polymorphic_map = None
"""A mapping of "polymorphic identity" identifiers mapped to
:class:`_orm.Mapper` instances, within an inheritance scenario.
The identifiers can be of any type which is comparable to the
type of column represented by :attr:`_orm.Mapper.polymorphic_on`.
An inheritance chain of mappers will all reference the same
polymorphic map object. The object is used to correlate incoming
result rows to target mappers.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
polymorphic_identity = None
"""Represent an identifier which is matched against the
:attr:`_orm.Mapper.polymorphic_on` column during result row loading.
Used only with inheritance, this object can be of any type which is
comparable to the type of column represented by
:attr:`_orm.Mapper.polymorphic_on`.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
base_mapper = None
"""The base-most :class:`_orm.Mapper` in an inheritance chain.
In a non-inheriting scenario, this attribute will always be this
:class:`_orm.Mapper`. In an inheritance scenario, it references
the :class:`_orm.Mapper` which is parent to all other :class:`_orm.Mapper`
objects in the inheritance chain.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
columns = None
"""A collection of :class:`_schema.Column` or other scalar expression
objects maintained by this :class:`_orm.Mapper`.
The collection behaves the same as that of the ``c`` attribute on
any :class:`_schema.Table` object,
except that only those columns included in
this mapping are present, and are keyed based on the attribute name
defined in the mapping, not necessarily the ``key`` attribute of the
:class:`_schema.Column` itself. Additionally, scalar expressions mapped
by :func:`.column_property` are also present here.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
validators = None
"""An immutable dictionary of attributes which have been decorated
using the :func:`_orm.validates` decorator.
The dictionary contains string attribute names as keys
mapped to the actual validation method.
"""
c = None
"""A synonym for :attr:`_orm.Mapper.columns`."""
@property
@util.deprecated("1.3", "Use .persist_selectable")
def mapped_table(self):
return self.persist_selectable
@util.memoized_property
def _path_registry(self):
return PathRegistry.per_mapper(self)
def _configure_inheritance(self):
"""Configure settings related to inheriting and/or inherited mappers
being present."""
# a set of all mappers which inherit from this one.
self._inheriting_mappers = util.WeakSequence()
if self.inherits:
if isinstance(self.inherits, type):
self.inherits = class_mapper(self.inherits, configure=False)
if not issubclass(self.class_, self.inherits.class_):
raise sa_exc.ArgumentError(
"Class '%s' does not inherit from '%s'"
% (self.class_.__name__, self.inherits.class_.__name__)
)
if self.non_primary != self.inherits.non_primary:
np = not self.non_primary and "primary" or "non-primary"
raise sa_exc.ArgumentError(
"Inheritance of %s mapper for class '%s' is "
"only allowed from a %s mapper"
% (np, self.class_.__name__, np)
)
# inherit_condition is optional.
if self.local_table is None:
self.local_table = self.inherits.local_table
self.persist_selectable = self.inherits.persist_selectable
self.single = True
elif self.local_table is not self.inherits.local_table:
if self.concrete:
self.persist_selectable = self.local_table
for mapper in self.iterate_to_root():
if mapper.polymorphic_on is not None:
mapper._requires_row_aliasing = True
else:
if self.inherit_condition is None:
# figure out inherit condition from our table to the
# immediate table of the inherited mapper, not its
# full table which could pull in other stuff we don't
# want (allows test/inheritance.InheritTest4 to pass)
self.inherit_condition = sql_util.join_condition(
self.inherits.local_table, self.local_table
)
self.persist_selectable = sql.join(
self.inherits.persist_selectable,
self.local_table,
self.inherit_condition,
)
fks = util.to_set(self.inherit_foreign_keys)
self._inherits_equated_pairs = sql_util.criterion_as_pairs(
self.persist_selectable.onclause,
consider_as_foreign_keys=fks,
)
else:
self.persist_selectable = self.local_table
if self.polymorphic_identity is not None and not self.concrete:
self._identity_class = self.inherits._identity_class
else:
self._identity_class = self.class_
if self.version_id_col is None:
self.version_id_col = self.inherits.version_id_col
self.version_id_generator = self.inherits.version_id_generator
elif (
self.inherits.version_id_col is not None
and self.version_id_col is not self.inherits.version_id_col
):
util.warn(
"Inheriting version_id_col '%s' does not match inherited "
"version_id_col '%s' and will not automatically populate "
"the inherited versioning column. "
"version_id_col should only be specified on "
"the base-most mapper that includes versioning."
% (
self.version_id_col.description,
self.inherits.version_id_col.description,
)
)
if (
self.order_by is False
and not self.concrete
and self.inherits.order_by is not False
):
self.order_by = self.inherits.order_by
self.polymorphic_map = self.inherits.polymorphic_map
self.batch = self.inherits.batch
self.inherits._inheriting_mappers.append(self)
self.base_mapper = self.inherits.base_mapper
self.passive_updates = self.inherits.passive_updates
self.passive_deletes = (
self.inherits.passive_deletes or self.passive_deletes
)
self._all_tables = self.inherits._all_tables
if self.polymorphic_identity is not None:
if self.polymorphic_identity in self.polymorphic_map:
util.warn(
"Reassigning polymorphic association for identity %r "
"from %r to %r: Check for duplicate use of %r as "
"value for polymorphic_identity."
% (
self.polymorphic_identity,
self.polymorphic_map[self.polymorphic_identity],
self,
self.polymorphic_identity,
)
)
self.polymorphic_map[self.polymorphic_identity] = self
if self.polymorphic_load and self.concrete:
raise sa_exc.ArgumentError(
"polymorphic_load is not currently supported "
"with concrete table inheritance"
)
if self.polymorphic_load == "inline":
self.inherits._add_with_polymorphic_subclass(self)
elif self.polymorphic_load == "selectin":
pass
elif self.polymorphic_load is not None:
raise sa_exc.ArgumentError(
"unknown argument for polymorphic_load: %r"
% self.polymorphic_load
)
else:
self._all_tables = set()
self.base_mapper = self
self.persist_selectable = self.local_table
if self.polymorphic_identity is not None:
self.polymorphic_map[self.polymorphic_identity] = self
self._identity_class = self.class_
if self.persist_selectable is None:
raise sa_exc.ArgumentError(
"Mapper '%s' does not have a persist_selectable specified."
% self
)
def _set_with_polymorphic(self, with_polymorphic):
if with_polymorphic == "*":
self.with_polymorphic = ("*", None)
elif isinstance(with_polymorphic, (tuple, list)):
if isinstance(
with_polymorphic[0], util.string_types + (tuple, list)
):
self.with_polymorphic = with_polymorphic
else:
self.with_polymorphic = (with_polymorphic, None)
elif with_polymorphic is not None:
raise sa_exc.ArgumentError("Invalid setting for with_polymorphic")
else:
self.with_polymorphic = None
if isinstance(self.local_table, expression.SelectBase):
raise sa_exc.InvalidRequestError(
"When mapping against a select() construct, map against "
"an alias() of the construct instead."
"This because several databases don't allow a "
"SELECT from a subquery that does not have an alias."
)
if self.with_polymorphic and isinstance(
self.with_polymorphic[1], expression.SelectBase
):
self.with_polymorphic = (
self.with_polymorphic[0],
self.with_polymorphic[1].alias(),
)
if self.configured:
self._expire_memoizations()
def _add_with_polymorphic_subclass(self, mapper):
subcl = mapper.class_
if self.with_polymorphic is None:
self._set_with_polymorphic((subcl,))
elif self.with_polymorphic[0] != "*":
self._set_with_polymorphic(
(self.with_polymorphic[0] + (subcl,), self.with_polymorphic[1])
)
def _set_concrete_base(self, mapper):
"""Set the given :class:`_orm.Mapper` as the 'inherits' for this
:class:`_orm.Mapper`, assuming this :class:`_orm.Mapper` is concrete
and does not already have an inherits."""
assert self.concrete
assert not self.inherits
assert isinstance(mapper, Mapper)
self.inherits = mapper
self.inherits.polymorphic_map.update(self.polymorphic_map)
self.polymorphic_map = self.inherits.polymorphic_map
for mapper in self.iterate_to_root():
if mapper.polymorphic_on is not None:
mapper._requires_row_aliasing = True
self.batch = self.inherits.batch
for mp in self.self_and_descendants:
mp.base_mapper = self.inherits.base_mapper
self.inherits._inheriting_mappers.append(self)
self.passive_updates = self.inherits.passive_updates
self._all_tables = self.inherits._all_tables
for key, prop in mapper._props.items():
if key not in self._props and not self._should_exclude(
key, key, local=False, column=None
):
self._adapt_inherited_property(key, prop, False)
def _set_polymorphic_on(self, polymorphic_on):
self.polymorphic_on = polymorphic_on
self._configure_polymorphic_setter(True)
def _configure_legacy_instrument_class(self):
if self.inherits:
self.dispatch._update(self.inherits.dispatch)
super_extensions = set(
chain(
*[
m._deprecated_extensions
for m in self.inherits.iterate_to_root()
]
)
)
else:
super_extensions = set()
for ext in self._deprecated_extensions:
if ext not in super_extensions:
ext._adapt_instrument_class(self, ext)
def _configure_listeners(self):
if self.inherits:
super_extensions = set(
chain(
*[
m._deprecated_extensions
for m in self.inherits.iterate_to_root()
]
)
)
else:
super_extensions = set()
for ext in self._deprecated_extensions:
if ext not in super_extensions:
ext._adapt_listener(self, ext)
def _configure_class_instrumentation(self):
"""If this mapper is to be a primary mapper (i.e. the
non_primary flag is not set), associate this Mapper with the
given class and entity name.
Subsequent calls to ``class_mapper()`` for the ``class_`` / ``entity``
name combination will return this mapper. Also decorate the
`__init__` method on the mapped class to include optional
auto-session attachment logic.
"""
manager = attributes.manager_of_class(self.class_)
if self.non_primary:
if not manager or not manager.is_mapped:
raise sa_exc.InvalidRequestError(
"Class %s has no primary mapper configured. Configure "
"a primary mapper first before setting up a non primary "
"Mapper." % self.class_
)
self.class_manager = manager
self._identity_class = manager.mapper._identity_class
_mapper_registry[self] = True
return
if manager is not None:
assert manager.class_ is self.class_
if manager.is_mapped:
raise sa_exc.ArgumentError(
"Class '%s' already has a primary mapper defined. "
"Use non_primary=True to "
"create a non primary Mapper. clear_mappers() will "
"remove *all* current mappers from all classes."
% self.class_
)
# else:
# a ClassManager may already exist as
# ClassManager.instrument_attribute() creates
# new managers for each subclass if they don't yet exist.
_mapper_registry[self] = True
# note: this *must be called before instrumentation.register_class*
# to maintain the documented behavior of instrument_class
self.dispatch.instrument_class(self, self.class_)
if manager is None:
manager = instrumentation.register_class(self.class_)
self.class_manager = manager
manager.mapper = self
manager.deferred_scalar_loader = util.partial(
loading.load_scalar_attributes, self
)
# The remaining members can be added by any mapper,
# e_name None or not.
if manager.info.get(_INSTRUMENTOR, False):
return
event.listen(manager, "first_init", _event_on_first_init, raw=True)
event.listen(manager, "init", _event_on_init, raw=True)
for key, method in util.iterate_attributes(self.class_):
if key == "__init__" and hasattr(method, "_sa_original_init"):
method = method._sa_original_init
if isinstance(method, types.MethodType):
method = method.im_func
if isinstance(method, types.FunctionType):
if hasattr(method, "__sa_reconstructor__"):
self._reconstructor = method
event.listen(manager, "load", _event_on_load, raw=True)
elif hasattr(method, "__sa_validators__"):
validation_opts = method.__sa_validation_opts__
for name in method.__sa_validators__:
if name in self.validators:
raise sa_exc.InvalidRequestError(
"A validation function for mapped "
"attribute %r on mapper %s already exists."
% (name, self)
)
self.validators = self.validators.union(
{name: (method, validation_opts)}
)
manager.info[_INSTRUMENTOR] = self
@classmethod
def _configure_all(cls):
"""Class-level path to the :func:`.configure_mappers` call."""
configure_mappers()
def dispose(self):
# Disable any attribute-based compilation.
self.configured = True
self._dispose_called = True
if hasattr(self, "_configure_failed"):
del self._configure_failed
if (
not self.non_primary
and self.class_manager is not None
and self.class_manager.is_mapped
and self.class_manager.mapper is self
):
instrumentation.unregister_class(self.class_)
def _configure_pks(self):
self.tables = sql_util.find_tables(self.persist_selectable)
self._pks_by_table = {}
self._cols_by_table = {}
all_cols = util.column_set(
chain(*[col.proxy_set for col in self._columntoproperty])
)
pk_cols = util.column_set(c for c in all_cols if c.primary_key)
# identify primary key columns which are also mapped by this mapper.
tables = set(self.tables + [self.persist_selectable])
self._all_tables.update(tables)
for t in tables:
if t.primary_key and pk_cols.issuperset(t.primary_key):
# ordering is important since it determines the ordering of
# mapper.primary_key (and therefore query.get())
self._pks_by_table[t] = util.ordered_column_set(
t.primary_key
).intersection(pk_cols)
self._cols_by_table[t] = util.ordered_column_set(t.c).intersection(
all_cols
)
# if explicit PK argument sent, add those columns to the
# primary key mappings
if self._primary_key_argument:
for k in self._primary_key_argument:
if k.table not in self._pks_by_table:
self._pks_by_table[k.table] = util.OrderedSet()
self._pks_by_table[k.table].add(k)
# otherwise, see that we got a full PK for the mapped table
elif (
self.persist_selectable not in self._pks_by_table
or len(self._pks_by_table[self.persist_selectable]) == 0
):
raise sa_exc.ArgumentError(
"Mapper %s could not assemble any primary "
"key columns for mapped table '%s'"
% (self, self.persist_selectable.description)
)
elif self.local_table not in self._pks_by_table and isinstance(
self.local_table, schema.Table
):
util.warn(
"Could not assemble any primary "
"keys for locally mapped table '%s' - "
"no rows will be persisted in this Table."
% self.local_table.description
)
if (
self.inherits
and not self.concrete
and not self._primary_key_argument
):
# if inheriting, the "primary key" for this mapper is
# that of the inheriting (unless concrete or explicit)
self.primary_key = self.inherits.primary_key
else:
# determine primary key from argument or persist_selectable pks -
# reduce to the minimal set of columns
if self._primary_key_argument:
primary_key = sql_util.reduce_columns(
[
self.persist_selectable.corresponding_column(c)
for c in self._primary_key_argument
],
ignore_nonexistent_tables=True,
)
else:
primary_key = sql_util.reduce_columns(
self._pks_by_table[self.persist_selectable],
ignore_nonexistent_tables=True,
)
if len(primary_key) == 0:
raise sa_exc.ArgumentError(
"Mapper %s could not assemble any primary "
"key columns for mapped table '%s'"
% (self, self.persist_selectable.description)
)
self.primary_key = tuple(primary_key)
self._log("Identified primary key columns: %s", primary_key)
# determine cols that aren't expressed within our tables; mark these
# as "read only" properties which are refreshed upon INSERT/UPDATE
self._readonly_props = set(
self._columntoproperty[col]
for col in self._columntoproperty
if self._columntoproperty[col] not in self._identity_key_props
and (
not hasattr(col, "table")
or col.table not in self._cols_by_table
)
)
def _configure_properties(self):
# Column and other ClauseElement objects which are mapped
self.columns = self.c = util.OrderedProperties()
# object attribute names mapped to MapperProperty objects
self._props = util.OrderedDict()
# table columns mapped to lists of MapperProperty objects
# using a list allows a single column to be defined as
# populating multiple object attributes
self._columntoproperty = _ColumnMapping(self)
# load custom properties
if self._init_properties:
for key, prop in self._init_properties.items():
self._configure_property(key, prop, False)
# pull properties from the inherited mapper if any.
if self.inherits:
for key, prop in self.inherits._props.items():
if key not in self._props and not self._should_exclude(
key, key, local=False, column=None
):
self._adapt_inherited_property(key, prop, False)
# create properties for each column in the mapped table,
# for those columns which don't already map to a property
for column in self.persist_selectable.columns:
if column in self._columntoproperty:
continue
column_key = (self.column_prefix or "") + column.key
if self._should_exclude(
column.key,
column_key,
local=self.local_table.c.contains_column(column),
column=column,
):
continue
# adjust the "key" used for this column to that
# of the inheriting mapper
for mapper in self.iterate_to_root():
if column in mapper._columntoproperty:
column_key = mapper._columntoproperty[column].key
self._configure_property(
column_key, column, init=False, setparent=True
)
def _configure_polymorphic_setter(self, init=False):
"""Configure an attribute on the mapper representing the
'polymorphic_on' column, if applicable, and not
already generated by _configure_properties (which is typical).
Also create a setter function which will assign this
attribute to the value of the 'polymorphic_identity'
upon instance construction, also if applicable. This
routine will run when an instance is created.
"""
setter = False
if self.polymorphic_on is not None:
setter = True
if isinstance(self.polymorphic_on, util.string_types):
# polymorphic_on specified as a string - link
# it to mapped ColumnProperty
try:
self.polymorphic_on = self._props[self.polymorphic_on]
except KeyError as err:
util.raise_(
sa_exc.ArgumentError(
"Can't determine polymorphic_on "
"value '%s' - no attribute is "
"mapped to this name." % self.polymorphic_on
),
replace_context=err,
)
if self.polymorphic_on in self._columntoproperty:
# polymorphic_on is a column that is already mapped
# to a ColumnProperty
prop = self._columntoproperty[self.polymorphic_on]
elif isinstance(self.polymorphic_on, MapperProperty):
# polymorphic_on is directly a MapperProperty,
# ensure it's a ColumnProperty
if not isinstance(
self.polymorphic_on, properties.ColumnProperty
):
raise sa_exc.ArgumentError(
"Only direct column-mapped "
"property or SQL expression "
"can be passed for polymorphic_on"
)
prop = self.polymorphic_on
elif not expression._is_column(self.polymorphic_on):
# polymorphic_on is not a Column and not a ColumnProperty;
# not supported right now.
raise sa_exc.ArgumentError(
"Only direct column-mapped "
"property or SQL expression "
"can be passed for polymorphic_on"
)
else:
# polymorphic_on is a Column or SQL expression and
# doesn't appear to be mapped. this means it can be 1.
# only present in the with_polymorphic selectable or
# 2. a totally standalone SQL expression which we'd
# hope is compatible with this mapper's persist_selectable
col = self.persist_selectable.corresponding_column(
self.polymorphic_on
)
if col is None:
# polymorphic_on doesn't derive from any
# column/expression isn't present in the mapped
# table. we will make a "hidden" ColumnProperty
# for it. Just check that if it's directly a
# schema.Column and we have with_polymorphic, it's
# likely a user error if the schema.Column isn't
# represented somehow in either persist_selectable or
# with_polymorphic. Otherwise as of 0.7.4 we
# just go with it and assume the user wants it
# that way (i.e. a CASE statement)
setter = False
instrument = False
col = self.polymorphic_on
if isinstance(col, schema.Column) and (
self.with_polymorphic is None
or self.with_polymorphic[1].corresponding_column(col)
is None
):
raise sa_exc.InvalidRequestError(
"Could not map polymorphic_on column "
"'%s' to the mapped table - polymorphic "
"loads will not function properly"
% col.description
)
else:
# column/expression that polymorphic_on derives from
# is present in our mapped table
# and is probably mapped, but polymorphic_on itself
# is not. This happens when
# the polymorphic_on is only directly present in the
# with_polymorphic selectable, as when use
# polymorphic_union.
# we'll make a separate ColumnProperty for it.
instrument = True
key = getattr(col, "key", None)
if key:
if self._should_exclude(col.key, col.key, False, col):
raise sa_exc.InvalidRequestError(
"Cannot exclude or override the "
"discriminator column %r" % col.key
)
else:
self.polymorphic_on = col = col.label("_sa_polymorphic_on")
key = col.key
prop = properties.ColumnProperty(col, _instrument=instrument)
self._configure_property(key, prop, init=init, setparent=True)
# the actual polymorphic_on should be the first public-facing
# column in the property
self.polymorphic_on = prop.columns[0]
polymorphic_key = prop.key
else:
# no polymorphic_on was set.
# check inheriting mappers for one.
for mapper in self.iterate_to_root():
# determine if polymorphic_on of the parent
# should be propagated here. If the col
# is present in our mapped table, or if our mapped
# table is the same as the parent (i.e. single table
# inheritance), we can use it
if mapper.polymorphic_on is not None:
if self.persist_selectable is mapper.persist_selectable:
self.polymorphic_on = mapper.polymorphic_on
else:
self.polymorphic_on = (
self.persist_selectable
).corresponding_column(mapper.polymorphic_on)
# we can use the parent mapper's _set_polymorphic_identity
# directly; it ensures the polymorphic_identity of the
# instance's mapper is used so is portable to subclasses.
if self.polymorphic_on is not None:
self._set_polymorphic_identity = (
mapper._set_polymorphic_identity
)
self._validate_polymorphic_identity = (
mapper._validate_polymorphic_identity
)
else:
self._set_polymorphic_identity = None
return
if setter:
def _set_polymorphic_identity(state):
dict_ = state.dict
state.get_impl(polymorphic_key).set(
state,
dict_,
state.manager.mapper.polymorphic_identity,
None,
)
def _validate_polymorphic_identity(mapper, state, dict_):
if (
polymorphic_key in dict_
and dict_[polymorphic_key]
not in mapper._acceptable_polymorphic_identities
):
util.warn_limited(
"Flushing object %s with "
"incompatible polymorphic identity %r; the "
"object may not refresh and/or load correctly",
(state_str(state), dict_[polymorphic_key]),
)
self._set_polymorphic_identity = _set_polymorphic_identity
self._validate_polymorphic_identity = (
_validate_polymorphic_identity
)
else:
self._set_polymorphic_identity = None
_validate_polymorphic_identity = None
@_memoized_configured_property
def _version_id_prop(self):
if self.version_id_col is not None:
return self._columntoproperty[self.version_id_col]
else:
return None
@_memoized_configured_property
def _acceptable_polymorphic_identities(self):
identities = set()
stack = deque([self])
while stack:
item = stack.popleft()
if item.persist_selectable is self.persist_selectable:
identities.add(item.polymorphic_identity)
stack.extend(item._inheriting_mappers)
return identities
@_memoized_configured_property
def _prop_set(self):
return frozenset(self._props.values())
def _adapt_inherited_property(self, key, prop, init):
if not self.concrete:
self._configure_property(key, prop, init=False, setparent=False)
elif key not in self._props:
# determine if the class implements this attribute; if not,
# or if it is implemented by the attribute that is handling the
# given superclass-mapped property, then we need to report that we
# can't use this at the instance level since we are a concrete
# mapper and we don't map this. don't trip user-defined
# descriptors that might have side effects when invoked.
implementing_attribute = self.class_manager._get_class_attr_mro(
key, prop
)
if implementing_attribute is prop or (
isinstance(
implementing_attribute, attributes.InstrumentedAttribute
)
and implementing_attribute._parententity is prop.parent
):
self._configure_property(
key,
properties.ConcreteInheritedProperty(),
init=init,
setparent=True,
)
def _configure_property(self, key, prop, init=True, setparent=True):
self._log("_configure_property(%s, %s)", key, prop.__class__.__name__)
if not isinstance(prop, MapperProperty):
prop = self._property_from_column(key, prop)
if isinstance(prop, properties.ColumnProperty):
col = self.persist_selectable.corresponding_column(prop.columns[0])
# if the column is not present in the mapped table,
# test if a column has been added after the fact to the
# parent table (or their parent, etc.) [ticket:1570]
if col is None and self.inherits:
path = [self]
for m in self.inherits.iterate_to_root():
col = m.local_table.corresponding_column(prop.columns[0])
if col is not None:
for m2 in path:
m2.persist_selectable._reset_exported()
col = self.persist_selectable.corresponding_column(
prop.columns[0]
)
break
path.append(m)
# subquery expression, column not present in the mapped
# selectable.
if col is None:
col = prop.columns[0]
# column is coming in after _readonly_props was
# initialized; check for 'readonly'
if hasattr(self, "_readonly_props") and (
not hasattr(col, "table")
or col.table not in self._cols_by_table
):
self._readonly_props.add(prop)
else:
# if column is coming in after _cols_by_table was
# initialized, ensure the col is in the right set
if (
hasattr(self, "_cols_by_table")
and col.table in self._cols_by_table
and col not in self._cols_by_table[col.table]
):
self._cols_by_table[col.table].add(col)
# if this properties.ColumnProperty represents the "polymorphic
# discriminator" column, mark it. We'll need this when rendering
# columns in SELECT statements.
if not hasattr(prop, "_is_polymorphic_discriminator"):
prop._is_polymorphic_discriminator = (
col is self.polymorphic_on
or prop.columns[0] is self.polymorphic_on
)
self.columns[key] = col
for col in prop.columns + prop._orig_columns:
for col in col.proxy_set:
self._columntoproperty[col] = prop
prop.key = key
if setparent:
prop.set_parent(self, init)
if key in self._props and getattr(
self._props[key], "_mapped_by_synonym", False
):
syn = self._props[key]._mapped_by_synonym
raise sa_exc.ArgumentError(
"Can't call map_column=True for synonym %r=%r, "
"a ColumnProperty already exists keyed to the name "
"%r for column %r" % (syn, key, key, syn)
)
if (
key in self._props
and not isinstance(prop, properties.ColumnProperty)
and not isinstance(
self._props[key],
(
properties.ColumnProperty,
properties.ConcreteInheritedProperty,
),
)
):
util.warn(
"Property %s on %s being replaced with new "
"property %s; the old property will be discarded"
% (self._props[key], self, prop)
)
oldprop = self._props[key]
self._path_registry.pop(oldprop, None)
self._props[key] = prop
if not self.non_primary:
prop.instrument_class(self)
for mapper in self._inheriting_mappers:
mapper._adapt_inherited_property(key, prop, init)
if init:
prop.init()
prop.post_instrument_class(self)
if self.configured:
self._expire_memoizations()
def _property_from_column(self, key, prop):
"""generate/update a :class:`.ColumnProprerty` given a
:class:`_schema.Column` object."""
# we were passed a Column or a list of Columns;
# generate a properties.ColumnProperty
columns = util.to_list(prop)
column = columns[0]
if not expression._is_column(column):
raise sa_exc.ArgumentError(
"%s=%r is not an instance of MapperProperty or Column"
% (key, prop)
)
prop = self._props.get(key, None)
if isinstance(prop, properties.ColumnProperty):
if (
(
not self._inherits_equated_pairs
or (prop.columns[0], column)
not in self._inherits_equated_pairs
)
and not prop.columns[0].shares_lineage(column)
and prop.columns[0] is not self.version_id_col
and column is not self.version_id_col
):
warn_only = prop.parent is not self
msg = (
"Implicitly combining column %s with column "
"%s under attribute '%s'. Please configure one "
"or more attributes for these same-named columns "
"explicitly." % (prop.columns[-1], column, key)
)
if warn_only:
util.warn(msg)
else:
raise sa_exc.InvalidRequestError(msg)
# existing properties.ColumnProperty from an inheriting
# mapper. make a copy and append our column to it
prop = prop.copy()
prop.columns.insert(0, column)
self._log(
"inserting column to existing list "
"in properties.ColumnProperty %s" % (key)
)
return prop
elif prop is None or isinstance(
prop, properties.ConcreteInheritedProperty
):
mapped_column = []
for c in columns:
mc = self.persist_selectable.corresponding_column(c)
if mc is None:
mc = self.local_table.corresponding_column(c)
if mc is not None:
# if the column is in the local table but not the
# mapped table, this corresponds to adding a
# column after the fact to the local table.
# [ticket:1523]
self.persist_selectable._reset_exported()
mc = self.persist_selectable.corresponding_column(c)
if mc is None:
raise sa_exc.ArgumentError(
"When configuring property '%s' on %s, "
"column '%s' is not represented in the mapper's "
"table. Use the `column_property()` function to "
"force this column to be mapped as a read-only "
"attribute." % (key, self, c)
)
mapped_column.append(mc)
return properties.ColumnProperty(*mapped_column)
else:
raise sa_exc.ArgumentError(
"WARNING: when configuring property '%s' on %s, "
"column '%s' conflicts with property '%r'. "
"To resolve this, map the column to the class under a "
"different name in the 'properties' dictionary. Or, "
"to remove all awareness of the column entirely "
"(including its availability as a foreign key), "
"use the 'include_properties' or 'exclude_properties' "
"mapper arguments to control specifically which table "
"columns get mapped." % (key, self, column.key, prop)
)
def _post_configure_properties(self):
"""Call the ``init()`` method on all ``MapperProperties``
attached to this mapper.
This is a deferred configuration step which is intended
to execute once all mappers have been constructed.
"""
self._log("_post_configure_properties() started")
l = [(key, prop) for key, prop in self._props.items()]
for key, prop in l:
self._log("initialize prop %s", key)
if prop.parent is self and not prop._configure_started:
prop.init()
if prop._configure_finished:
prop.post_instrument_class(self)
self._log("_post_configure_properties() complete")
self.configured = True
def add_properties(self, dict_of_properties):
"""Add the given dictionary of properties to this mapper,
using `add_property`.
"""
for key, value in dict_of_properties.items():
self.add_property(key, value)
def add_property(self, key, prop):
"""Add an individual MapperProperty to this mapper.
If the mapper has not been configured yet, just adds the
property to the initial properties dictionary sent to the
constructor. If this Mapper has already been configured, then
the given MapperProperty is configured immediately.
"""
self._init_properties[key] = prop
self._configure_property(key, prop, init=self.configured)
def _expire_memoizations(self):
for mapper in self.iterate_to_root():
_memoized_configured_property.expire_instance(mapper)
@property
def _log_desc(self):
return (
"("
+ self.class_.__name__
+ "|"
+ (
self.local_table is not None
and self.local_table.description
or str(self.local_table)
)
+ (self.non_primary and "|non-primary" or "")
+ ")"
)
def _log(self, msg, *args):
self.logger.info("%s " + msg, *((self._log_desc,) + args))
def _log_debug(self, msg, *args):
self.logger.debug("%s " + msg, *((self._log_desc,) + args))
def __repr__(self):
return "<Mapper at 0x%x; %s>" % (id(self), self.class_.__name__)
def __str__(self):
return "mapped class %s%s->%s" % (
self.class_.__name__,
self.non_primary and " (non-primary)" or "",
self.local_table.description
if self.local_table is not None
else self.persist_selectable.description,
)
def _is_orphan(self, state):
orphan_possible = False
for mapper in self.iterate_to_root():
for (key, cls) in mapper._delete_orphans:
orphan_possible = True
has_parent = attributes.manager_of_class(cls).has_parent(
state, key, optimistic=state.has_identity
)
if self.legacy_is_orphan and has_parent:
return False
elif not self.legacy_is_orphan and not has_parent:
return True
if self.legacy_is_orphan:
return orphan_possible
else:
return False
def has_property(self, key):
return key in self._props
def get_property(self, key, _configure_mappers=True):
"""return a MapperProperty associated with the given key."""
if _configure_mappers and Mapper._new_mappers:
configure_mappers()
try:
return self._props[key]
except KeyError as err:
util.raise_(
sa_exc.InvalidRequestError(
"Mapper '%s' has no property '%s'" % (self, key)
),
replace_context=err,
)
def get_property_by_column(self, column):
"""Given a :class:`_schema.Column` object, return the
:class:`.MapperProperty` which maps this column."""
return self._columntoproperty[column]
@property
def iterate_properties(self):
"""return an iterator of all MapperProperty objects."""
if Mapper._new_mappers:
configure_mappers()
return iter(self._props.values())
def _mappers_from_spec(self, spec, selectable):
"""given a with_polymorphic() argument, return the set of mappers it
represents.
Trims the list of mappers to just those represented within the given
selectable, if present. This helps some more legacy-ish mappings.
"""
if spec == "*":
mappers = list(self.self_and_descendants)
elif spec:
mappers = set()
for m in util.to_list(spec):
m = _class_to_mapper(m)
if not m.isa(self):
raise sa_exc.InvalidRequestError(
"%r does not inherit from %r" % (m, self)
)
if selectable is None:
mappers.update(m.iterate_to_root())
else:
mappers.add(m)
mappers = [m for m in self.self_and_descendants if m in mappers]
else:
mappers = []
if selectable is not None:
tables = set(
sql_util.find_tables(selectable, include_aliases=True)
)
mappers = [m for m in mappers if m.local_table in tables]
return mappers
def _selectable_from_mappers(self, mappers, innerjoin):
"""given a list of mappers (assumed to be within this mapper's
inheritance hierarchy), construct an outerjoin amongst those mapper's
mapped tables.
"""
from_obj = self.persist_selectable
for m in mappers:
if m is self:
continue
if m.concrete:
raise sa_exc.InvalidRequestError(
"'with_polymorphic()' requires 'selectable' argument "
"when concrete-inheriting mappers are used."
)
elif not m.single:
if innerjoin:
from_obj = from_obj.join(
m.local_table, m.inherit_condition
)
else:
from_obj = from_obj.outerjoin(
m.local_table, m.inherit_condition
)
return from_obj
@_memoized_configured_property
def _single_table_criterion(self):
if self.single and self.inherits and self.polymorphic_on is not None:
return self.polymorphic_on._annotate({"parentmapper": self}).in_(
m.polymorphic_identity for m in self.self_and_descendants
)
else:
return None
@_memoized_configured_property
def _with_polymorphic_mappers(self):
if Mapper._new_mappers:
configure_mappers()
if not self.with_polymorphic:
return []
return self._mappers_from_spec(*self.with_polymorphic)
@_memoized_configured_property
def _with_polymorphic_selectable(self):
if not self.with_polymorphic:
return self.persist_selectable
spec, selectable = self.with_polymorphic
if selectable is not None:
return selectable
else:
return self._selectable_from_mappers(
self._mappers_from_spec(spec, selectable), False
)
with_polymorphic_mappers = _with_polymorphic_mappers
"""The list of :class:`_orm.Mapper` objects included in the
default "polymorphic" query.
"""
@_memoized_configured_property
def _insert_cols_evaluating_none(self):
return dict(
(
table,
frozenset(
col for col in columns if col.type.should_evaluate_none
),
)
for table, columns in self._cols_by_table.items()
)
@_memoized_configured_property
def _insert_cols_as_none(self):
return dict(
(
table,
frozenset(
col.key
for col in columns
if not col.primary_key
and not col.server_default
and not col.default
and not col.type.should_evaluate_none
),
)
for table, columns in self._cols_by_table.items()
)
@_memoized_configured_property
def _propkey_to_col(self):
return dict(
(
table,
dict(
(self._columntoproperty[col].key, col) for col in columns
),
)
for table, columns in self._cols_by_table.items()
)
@_memoized_configured_property
def _pk_keys_by_table(self):
return dict(
(table, frozenset([col.key for col in pks]))
for table, pks in self._pks_by_table.items()
)
@_memoized_configured_property
def _pk_attr_keys_by_table(self):
return dict(
(
table,
frozenset([self._columntoproperty[col].key for col in pks]),
)
for table, pks in self._pks_by_table.items()
)
@_memoized_configured_property
def _server_default_cols(self):
return dict(
(
table,
frozenset(
[
col.key
for col in columns
if col.server_default is not None
]
),
)
for table, columns in self._cols_by_table.items()
)
@_memoized_configured_property
def _server_default_plus_onupdate_propkeys(self):
result = set()
for table, columns in self._cols_by_table.items():
for col in columns:
if (
col.server_default is not None
or col.server_onupdate is not None
) and col in self._columntoproperty:
result.add(self._columntoproperty[col].key)
return result
@_memoized_configured_property
def _server_onupdate_default_cols(self):
return dict(
(
table,
frozenset(
[
col.key
for col in columns
if col.server_onupdate is not None
]
),
)
for table, columns in self._cols_by_table.items()
)
@property
def selectable(self):
"""The :func:`_expression.select` construct this :class:`_orm.Mapper`
selects from
by default.
Normally, this is equivalent to :attr:`.persist_selectable`, unless
the ``with_polymorphic`` feature is in use, in which case the
full "polymorphic" selectable is returned.
"""
return self._with_polymorphic_selectable
def _with_polymorphic_args(
self, spec=None, selectable=False, innerjoin=False
):
if self.with_polymorphic:
if not spec:
spec = self.with_polymorphic[0]
if selectable is False:
selectable = self.with_polymorphic[1]
elif selectable is False:
selectable = None
mappers = self._mappers_from_spec(spec, selectable)
if selectable is not None:
return mappers, selectable
else:
return mappers, self._selectable_from_mappers(mappers, innerjoin)
@_memoized_configured_property
def _polymorphic_properties(self):
return list(
self._iterate_polymorphic_properties(
self._with_polymorphic_mappers
)
)
def _iterate_polymorphic_properties(self, mappers=None):
"""Return an iterator of MapperProperty objects which will render into
a SELECT."""
if mappers is None:
mappers = self._with_polymorphic_mappers
if not mappers:
for c in self.iterate_properties:
yield c
else:
# in the polymorphic case, filter out discriminator columns
# from other mappers, as these are sometimes dependent on that
# mapper's polymorphic selectable (which we don't want rendered)
for c in util.unique_list(
chain(
*[
list(mapper.iterate_properties)
for mapper in [self] + mappers
]
)
):
if getattr(c, "_is_polymorphic_discriminator", False) and (
self.polymorphic_on is None
or c.columns[0] is not self.polymorphic_on
):
continue
yield c
@_memoized_configured_property
def attrs(self):
"""A namespace of all :class:`.MapperProperty` objects
associated this mapper.
This is an object that provides each property based on
its key name. For instance, the mapper for a
``User`` class which has ``User.name`` attribute would
provide ``mapper.attrs.name``, which would be the
:class:`.ColumnProperty` representing the ``name``
column. The namespace object can also be iterated,
which would yield each :class:`.MapperProperty`.
:class:`_orm.Mapper` has several pre-filtered views
of this attribute which limit the types of properties
returned, including :attr:`.synonyms`, :attr:`.column_attrs`,
:attr:`.relationships`, and :attr:`.composites`.
.. warning::
The :attr:`_orm.Mapper.attrs` accessor namespace is an
instance of :class:`.OrderedProperties`. This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.attrs[somename]`` over
``getattr(mapper.attrs, somename)`` to avoid name collisions.
.. seealso::
:attr:`_orm.Mapper.all_orm_descriptors`
"""
if Mapper._new_mappers:
configure_mappers()
return util.ImmutableProperties(self._props)
@_memoized_configured_property
def all_orm_descriptors(self):
"""A namespace of all :class:`.InspectionAttr` attributes associated
with the mapped class.
These attributes are in all cases Python :term:`descriptors`
associated with the mapped class or its superclasses.
This namespace includes attributes that are mapped to the class
as well as attributes declared by extension modules.
It includes any Python descriptor type that inherits from
:class:`.InspectionAttr`. This includes
:class:`.QueryableAttribute`, as well as extension types such as
:class:`.hybrid_property`, :class:`.hybrid_method` and
:class:`.AssociationProxy`.
To distinguish between mapped attributes and extension attributes,
the attribute :attr:`.InspectionAttr.extension_type` will refer
to a constant that distinguishes between different extension types.
The sorting of the attributes is based on the following rules:
1. Iterate through the class and its superclasses in order from
subclass to superclass (i.e. iterate through ``cls.__mro__``)
2. For each class, yield the attributes in the order in which they
appear in ``__dict__``, with the exception of those in step
3 below. In Python 3.6 and above this ordering will be the
same as that of the class' construction, with the exception
of attributes that were added after the fact by the application
or the mapper.
3. If a certain attribute key is also in the superclass ``__dict__``,
then it's included in the iteration for that class, and not the
class in which it first appeared.
The above process produces an ordering that is deterministic in terms
of the order in which attributes were assigned to the class.
.. versionchanged:: 1.3.19 ensured deterministic ordering for
:meth:`_orm.Mapper.all_orm_descriptors`.
When dealing with a :class:`.QueryableAttribute`, the
:attr:`.QueryableAttribute.property` attribute refers to the
:class:`.MapperProperty` property, which is what you get when
referring to the collection of mapped properties via
:attr:`_orm.Mapper.attrs`.
.. warning::
The :attr:`_orm.Mapper.all_orm_descriptors`
accessor namespace is an
instance of :class:`.OrderedProperties`. This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.all_orm_descriptors[somename]`` over
``getattr(mapper.all_orm_descriptors, somename)`` to avoid name
collisions.
.. seealso::
:attr:`_orm.Mapper.attrs`
"""
return util.ImmutableProperties(
dict(self.class_manager._all_sqla_attributes())
)
@_memoized_configured_property
def synonyms(self):
"""Return a namespace of all :class:`.SynonymProperty`
properties maintained by this :class:`_orm.Mapper`.
.. seealso::
:attr:`_orm.Mapper.attrs` - namespace of all
:class:`.MapperProperty`
objects.
"""
return self._filter_properties(properties.SynonymProperty)
@_memoized_configured_property
def column_attrs(self):
"""Return a namespace of all :class:`.ColumnProperty`
properties maintained by this :class:`_orm.Mapper`.
.. seealso::
:attr:`_orm.Mapper.attrs` - namespace of all
:class:`.MapperProperty`
objects.
"""
return self._filter_properties(properties.ColumnProperty)
@_memoized_configured_property
def relationships(self):
"""A namespace of all :class:`.RelationshipProperty` properties
maintained by this :class:`_orm.Mapper`.
.. warning::
the :attr:`_orm.Mapper.relationships` accessor namespace is an
instance of :class:`.OrderedProperties`. This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.relationships[somename]`` over
``getattr(mapper.relationships, somename)`` to avoid name
collisions.
.. seealso::
:attr:`_orm.Mapper.attrs` - namespace of all
:class:`.MapperProperty`
objects.
"""
return self._filter_properties(properties.RelationshipProperty)
@_memoized_configured_property
def composites(self):
"""Return a namespace of all :class:`.CompositeProperty`
properties maintained by this :class:`_orm.Mapper`.
.. seealso::
:attr:`_orm.Mapper.attrs` - namespace of all
:class:`.MapperProperty`
objects.
"""
return self._filter_properties(properties.CompositeProperty)
def _filter_properties(self, type_):
if Mapper._new_mappers:
configure_mappers()
return util.ImmutableProperties(
util.OrderedDict(
(k, v) for k, v in self._props.items() if isinstance(v, type_)
)
)
@_memoized_configured_property
def _get_clause(self):
"""create a "get clause" based on the primary key. this is used
by query.get() and many-to-one lazyloads to load this item
by primary key.
"""
params = [
(primary_key, sql.bindparam(None, type_=primary_key.type))
for primary_key in self.primary_key
]
return (
sql.and_(*[k == v for (k, v) in params]),
util.column_dict(params),
)
@_memoized_configured_property
def _equivalent_columns(self):
"""Create a map of all equivalent columns, based on
the determination of column pairs that are equated to
one another based on inherit condition. This is designed
to work with the queries that util.polymorphic_union
comes up with, which often don't include the columns from
the base table directly (including the subclass table columns
only).
The resulting structure is a dictionary of columns mapped
to lists of equivalent columns, e.g.::
{
tablea.col1:
{tableb.col1, tablec.col1},
tablea.col2:
{tabled.col2}
}
"""
result = util.column_dict()
def visit_binary(binary):
if binary.operator == operators.eq:
if binary.left in result:
result[binary.left].add(binary.right)
else:
result[binary.left] = util.column_set((binary.right,))
if binary.right in result:
result[binary.right].add(binary.left)
else:
result[binary.right] = util.column_set((binary.left,))
for mapper in self.base_mapper.self_and_descendants:
if mapper.inherit_condition is not None:
visitors.traverse(
mapper.inherit_condition, {}, {"binary": visit_binary}
)
return result
def _is_userland_descriptor(self, obj):
if isinstance(
obj,
(
_MappedAttribute,
instrumentation.ClassManager,
expression.ColumnElement,
),
):
return False
else:
return True
def _should_exclude(self, name, assigned_name, local, column):
"""determine whether a particular property should be implicitly
present on the class.
This occurs when properties are propagated from an inherited class, or
are applied from the columns present in the mapped table.
"""
# check for class-bound attributes and/or descriptors,
# either local or from an inherited class
if local:
if self.class_.__dict__.get(
assigned_name, None
) is not None and self._is_userland_descriptor(
self.class_.__dict__[assigned_name]
):
return True
else:
attr = self.class_manager._get_class_attr_mro(assigned_name, None)
if attr is not None and self._is_userland_descriptor(attr):
return True
if (
self.include_properties is not None
and name not in self.include_properties
and (column is None or column not in self.include_properties)
):
self._log("not including property %s" % (name))
return True
if self.exclude_properties is not None and (
name in self.exclude_properties
or (column is not None and column in self.exclude_properties)
):
self._log("excluding property %s" % (name))
return True
return False
def common_parent(self, other):
"""Return true if the given mapper shares a
common inherited parent as this mapper."""
return self.base_mapper is other.base_mapper
def _canload(self, state, allow_subtypes):
s = self.primary_mapper()
if self.polymorphic_on is not None or allow_subtypes:
return _state_mapper(state).isa(s)
else:
return _state_mapper(state) is s
def isa(self, other):
"""Return True if the this mapper inherits from the given mapper."""
m = self
while m and m is not other:
m = m.inherits
return bool(m)
def iterate_to_root(self):
m = self
while m:
yield m
m = m.inherits
@_memoized_configured_property
def self_and_descendants(self):
"""The collection including this mapper and all descendant mappers.
This includes not just the immediately inheriting mappers but
all their inheriting mappers as well.
"""
descendants = []
stack = deque([self])
while stack:
item = stack.popleft()
descendants.append(item)
stack.extend(item._inheriting_mappers)
return util.WeakSequence(descendants)
def polymorphic_iterator(self):
"""Iterate through the collection including this mapper and
all descendant mappers.
This includes not just the immediately inheriting mappers but
all their inheriting mappers as well.
To iterate through an entire hierarchy, use
``mapper.base_mapper.polymorphic_iterator()``.
"""
return iter(self.self_and_descendants)
def primary_mapper(self):
"""Return the primary mapper corresponding to this mapper's class key
(class)."""
return self.class_manager.mapper
@property
def primary_base_mapper(self):
return self.class_manager.mapper.base_mapper
def _result_has_identity_key(self, result, adapter=None):
pk_cols = self.primary_key
if adapter:
pk_cols = [adapter.columns[c] for c in pk_cols]
for col in pk_cols:
if not result._has_key(col):
return False
else:
return True
def identity_key_from_row(self, row, identity_token=None, adapter=None):
"""Return an identity-map key for use in storing/retrieving an
item from the identity map.
:param row: A :class:`.RowProxy` instance. The columns which are
mapped by this :class:`_orm.Mapper` should be locatable in the row,
preferably via the :class:`_schema.Column`
object directly (as is the case
when a :func:`_expression.select` construct is executed),
or via string names of
the form ``<tablename>_<colname>``.
"""
pk_cols = self.primary_key
if adapter:
pk_cols = [adapter.columns[c] for c in pk_cols]
return (
self._identity_class,
tuple(row[column] for column in pk_cols),
identity_token,
)
def identity_key_from_primary_key(self, primary_key, identity_token=None):
"""Return an identity-map key for use in storing/retrieving an
item from an identity map.
:param primary_key: A list of values indicating the identifier.
"""
return self._identity_class, tuple(primary_key), identity_token
def identity_key_from_instance(self, instance):
"""Return the identity key for the given instance, based on
its primary key attributes.
If the instance's state is expired, calling this method
will result in a database check to see if the object has been deleted.
If the row no longer exists,
:class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
This value is typically also found on the instance state under the
attribute name `key`.
"""
state = attributes.instance_state(instance)
return self._identity_key_from_state(state, attributes.PASSIVE_OFF)
def _identity_key_from_state(
self, state, passive=attributes.PASSIVE_RETURN_NEVER_SET
):
dict_ = state.dict
manager = state.manager
return (
self._identity_class,
tuple(
[
manager[prop.key].impl.get(state, dict_, passive)
for prop in self._identity_key_props
]
),
state.identity_token,
)
def primary_key_from_instance(self, instance):
"""Return the list of primary key values for the given
instance.
If the instance's state is expired, calling this method
will result in a database check to see if the object has been deleted.
If the row no longer exists,
:class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
"""
state = attributes.instance_state(instance)
identity_key = self._identity_key_from_state(
state, attributes.PASSIVE_OFF
)
return identity_key[1]
@_memoized_configured_property
def _persistent_sortkey_fn(self):
key_fns = [col.type.sort_key_function for col in self.primary_key]
if set(key_fns).difference([None]):
def key(state):
return tuple(
key_fn(val) if key_fn is not None else val
for key_fn, val in zip(key_fns, state.key[1])
)
else:
def key(state):
return state.key[1]
return key
@_memoized_configured_property
def _identity_key_props(self):
return [self._columntoproperty[col] for col in self.primary_key]
@_memoized_configured_property
def _all_pk_props(self):
collection = set()
for table in self.tables:
collection.update(self._pks_by_table[table])
return collection
@_memoized_configured_property
def _should_undefer_in_wildcard(self):
cols = set(self.primary_key)
if self.polymorphic_on is not None:
cols.add(self.polymorphic_on)
return cols
@_memoized_configured_property
def _primary_key_propkeys(self):
return {prop.key for prop in self._all_pk_props}
def _get_state_attr_by_column(
self, state, dict_, column, passive=attributes.PASSIVE_RETURN_NEVER_SET
):
prop = self._columntoproperty[column]
return state.manager[prop.key].impl.get(state, dict_, passive=passive)
def _set_committed_state_attr_by_column(self, state, dict_, column, value):
prop = self._columntoproperty[column]
state.manager[prop.key].impl.set_committed_value(state, dict_, value)
def _set_state_attr_by_column(self, state, dict_, column, value):
prop = self._columntoproperty[column]
state.manager[prop.key].impl.set(state, dict_, value, None)
def _get_committed_attr_by_column(self, obj, column):
state = attributes.instance_state(obj)
dict_ = attributes.instance_dict(obj)
return self._get_committed_state_attr_by_column(
state, dict_, column, passive=attributes.PASSIVE_OFF
)
def _get_committed_state_attr_by_column(
self, state, dict_, column, passive=attributes.PASSIVE_RETURN_NEVER_SET
):
prop = self._columntoproperty[column]
return state.manager[prop.key].impl.get_committed_value(
state, dict_, passive=passive
)
def _optimized_get_statement(self, state, attribute_names):
"""assemble a WHERE clause which retrieves a given state by primary
key, using a minimized set of tables.
Applies to a joined-table inheritance mapper where the
requested attribute names are only present on joined tables,
not the base table. The WHERE clause attempts to include
only those tables to minimize joins.
"""
props = self._props
tables = set(
chain(
*[
sql_util.find_tables(c, check_columns=True)
for key in attribute_names
for c in props[key].columns
]
)
)
if self.base_mapper.local_table in tables:
return None
def visit_binary(binary):
leftcol = binary.left
rightcol = binary.right
if leftcol is None or rightcol is None:
return
if leftcol.table not in tables:
leftval = self._get_committed_state_attr_by_column(
state,
state.dict,
leftcol,
passive=attributes.PASSIVE_NO_INITIALIZE,
)
if leftval in orm_util._none_set:
raise _OptGetColumnsNotAvailable()
binary.left = sql.bindparam(
None, leftval, type_=binary.right.type
)
elif rightcol.table not in tables:
rightval = self._get_committed_state_attr_by_column(
state,
state.dict,
rightcol,
passive=attributes.PASSIVE_NO_INITIALIZE,
)
if rightval in orm_util._none_set:
raise _OptGetColumnsNotAvailable()
binary.right = sql.bindparam(
None, rightval, type_=binary.right.type
)
allconds = []
try:
start = False
for mapper in reversed(list(self.iterate_to_root())):
if mapper.local_table in tables:
start = True
elif not isinstance(
mapper.local_table, expression.TableClause
):
return None
if start and not mapper.single:
allconds.append(
visitors.cloned_traverse(
mapper.inherit_condition,
{},
{"binary": visit_binary},
)
)
except _OptGetColumnsNotAvailable:
return None
cond = sql.and_(*allconds)
cols = []
for key in attribute_names:
cols.extend(props[key].columns)
return sql.select(cols, cond, use_labels=True)
def _iterate_to_target_viawpoly(self, mapper):
if self.isa(mapper):
prev = self
for m in self.iterate_to_root():
yield m
if m is not prev and prev not in m._with_polymorphic_mappers:
break
prev = m
if m is mapper:
break
def _should_selectin_load(self, enabled_via_opt, polymorphic_from):
if not enabled_via_opt:
# common case, takes place for all polymorphic loads
mapper = polymorphic_from
for m in self._iterate_to_target_viawpoly(mapper):
if m.polymorphic_load == "selectin":
return m
else:
# uncommon case, selectin load options were used
enabled_via_opt = set(enabled_via_opt)
enabled_via_opt_mappers = {e.mapper: e for e in enabled_via_opt}
for entity in enabled_via_opt.union([polymorphic_from]):
mapper = entity.mapper
for m in self._iterate_to_target_viawpoly(mapper):
if (
m.polymorphic_load == "selectin"
or m in enabled_via_opt_mappers
):
return enabled_via_opt_mappers.get(m, m)
return None
@util.dependencies(
"sqlalchemy.ext.baked", "sqlalchemy.orm.strategy_options"
)
def _subclass_load_via_in(self, baked, strategy_options, entity):
"""Assemble a BakedQuery that can load the columns local to
this subclass as a SELECT with IN.
"""
assert self.inherits
polymorphic_prop = self._columntoproperty[self.polymorphic_on]
keep_props = set([polymorphic_prop] + self._identity_key_props)
disable_opt = strategy_options.Load(entity)
enable_opt = strategy_options.Load(entity)
for prop in self.attrs:
if prop.parent is self or prop in keep_props:
# "enable" options, to turn on the properties that we want to
# load by default (subject to options from the query)
enable_opt.set_generic_strategy(
(prop.key,), dict(prop.strategy_key)
)
else:
# "disable" options, to turn off the properties from the
# superclass that we *don't* want to load, applied after
# the options from the query to override them
disable_opt.set_generic_strategy(
(prop.key,), {"do_nothing": True}
)
if len(self.primary_key) > 1:
in_expr = sql.tuple_(*self.primary_key)
else:
in_expr = self.primary_key[0]
if entity.is_aliased_class:
assert entity.mapper is self
q = baked.BakedQuery(
self._compiled_cache,
lambda session: session.query(entity)
.select_entity_from(entity.selectable)
._adapt_all_clauses(),
(self,),
)
q.spoil()
else:
q = baked.BakedQuery(
self._compiled_cache,
lambda session: session.query(self),
(self,),
)
q += lambda q: q.filter(
in_expr.in_(sql.bindparam("primary_keys", expanding=True))
).order_by(*self.primary_key)
return q, enable_opt, disable_opt
@_memoized_configured_property
def _subclass_load_via_in_mapper(self):
return self._subclass_load_via_in(self)
def cascade_iterator(self, type_, state, halt_on=None):
r"""Iterate each element and its mapper in an object graph,
for all relationships that meet the given cascade rule.
:param type\_:
The name of the cascade rule (i.e. ``"save-update"``, ``"delete"``,
etc.).
.. note:: the ``"all"`` cascade is not accepted here. For a generic
object traversal function, see :ref:`faq_walk_objects`.
:param state:
The lead InstanceState. child items will be processed per
the relationships defined for this object's mapper.
:return: the method yields individual object instances.
.. seealso::
:ref:`unitofwork_cascades`
:ref:`faq_walk_objects` - illustrates a generic function to
traverse all objects without relying on cascades.
"""
visited_states = set()
prp, mpp = object(), object()
assert state.mapper.isa(self)
visitables = deque(
[(deque(state.mapper._props.values()), prp, state, state.dict)]
)
while visitables:
iterator, item_type, parent_state, parent_dict = visitables[-1]
if not iterator:
visitables.pop()
continue
if item_type is prp:
prop = iterator.popleft()
if type_ not in prop.cascade:
continue
queue = deque(
prop.cascade_iterator(
type_,
parent_state,
parent_dict,
visited_states,
halt_on,
)
)
if queue:
visitables.append((queue, mpp, None, None))
elif item_type is mpp:
(
instance,
instance_mapper,
corresponding_state,
corresponding_dict,
) = iterator.popleft()
yield (
instance,
instance_mapper,
corresponding_state,
corresponding_dict,
)
visitables.append(
(
deque(instance_mapper._props.values()),
prp,
corresponding_state,
corresponding_dict,
)
)
@_memoized_configured_property
def _compiled_cache(self):
return util.LRUCache(self._compiled_cache_size)
@_memoized_configured_property
def _sorted_tables(self):
table_to_mapper = {}
for mapper in self.base_mapper.self_and_descendants:
for t in mapper.tables:
table_to_mapper.setdefault(t, mapper)
extra_dependencies = []
for table, mapper in table_to_mapper.items():
super_ = mapper.inherits
if super_:
extra_dependencies.extend(
[(super_table, table) for super_table in super_.tables]
)
def skip(fk):
# attempt to skip dependencies that are not
# significant to the inheritance chain
# for two tables that are related by inheritance.
# while that dependency may be important, it's technically
# not what we mean to sort on here.
parent = table_to_mapper.get(fk.parent.table)
dep = table_to_mapper.get(fk.column.table)
if (
parent is not None
and dep is not None
and dep is not parent
and dep.inherit_condition is not None
):
cols = set(sql_util._find_columns(dep.inherit_condition))
if parent.inherit_condition is not None:
cols = cols.union(
sql_util._find_columns(parent.inherit_condition)
)
return fk.parent not in cols and fk.column not in cols
else:
return fk.parent not in cols
return False
sorted_ = sql_util.sort_tables(
table_to_mapper,
skip_fn=skip,
extra_dependencies=extra_dependencies,
)
ret = util.OrderedDict()
for t in sorted_:
ret[t] = table_to_mapper[t]
return ret
def _memo(self, key, callable_):
if key in self._memoized_values:
return self._memoized_values[key]
else:
self._memoized_values[key] = value = callable_()
return value
@util.memoized_property
def _table_to_equated(self):
"""memoized map of tables to collections of columns to be
synchronized upwards to the base mapper."""
result = util.defaultdict(list)
for table in self._sorted_tables:
cols = set(table.c)
for m in self.iterate_to_root():
if m._inherits_equated_pairs and cols.intersection(
util.reduce(
set.union,
[l.proxy_set for l, r in m._inherits_equated_pairs],
)
):
result[table].append((m, m._inherits_equated_pairs))
return result
class _OptGetColumnsNotAvailable(Exception):
pass
def configure_mappers():
"""Initialize the inter-mapper relationships of all mappers that
have been constructed thus far.
This function can be called any number of times, but in
most cases is invoked automatically, the first time mappings are used,
as well as whenever mappings are used and additional not-yet-configured
mappers have been constructed.
Points at which this occur include when a mapped class is instantiated
into an instance, as well as when the :meth:`.Session.query` method
is used.
The :func:`.configure_mappers` function provides several event hooks
that can be used to augment its functionality. These methods include:
* :meth:`.MapperEvents.before_configured` - called once before
:func:`.configure_mappers` does any work; this can be used to establish
additional options, properties, or related mappings before the operation
proceeds.
* :meth:`.MapperEvents.mapper_configured` - called as each individual
:class:`_orm.Mapper` is configured within the process; will include all
mapper state except for backrefs set up by other mappers that are still
to be configured.
* :meth:`.MapperEvents.after_configured` - called once after
:func:`.configure_mappers` is complete; at this stage, all
:class:`_orm.Mapper` objects that are known to SQLAlchemy will be fully
configured. Note that the calling application may still have other
mappings that haven't been produced yet, such as if they are in modules
as yet unimported.
"""
if not Mapper._new_mappers:
return
_CONFIGURE_MUTEX.acquire()
try:
global _already_compiling
if _already_compiling:
return
_already_compiling = True
try:
# double-check inside mutex
if not Mapper._new_mappers:
return
has_skip = False
Mapper.dispatch._for_class(Mapper).before_configured()
# initialize properties on all mappers
# note that _mapper_registry is unordered, which
# may randomly conceal/reveal issues related to
# the order of mapper compilation
for mapper in list(_mapper_registry):
run_configure = None
for fn in mapper.dispatch.before_mapper_configured:
run_configure = fn(mapper, mapper.class_)
if run_configure is EXT_SKIP:
has_skip = True
break
if run_configure is EXT_SKIP:
continue
if getattr(mapper, "_configure_failed", False):
e = sa_exc.InvalidRequestError(
"One or more mappers failed to initialize - "
"can't proceed with initialization of other "
"mappers. Triggering mapper: '%s'. "
"Original exception was: %s"
% (mapper, mapper._configure_failed)
)
e._configure_failed = mapper._configure_failed
raise e
if not mapper.configured:
try:
mapper._post_configure_properties()
mapper._expire_memoizations()
mapper.dispatch.mapper_configured(
mapper, mapper.class_
)
except Exception:
exc = sys.exc_info()[1]
if not hasattr(exc, "_configure_failed"):
mapper._configure_failed = exc
raise
if not has_skip:
Mapper._new_mappers = False
finally:
_already_compiling = False
finally:
_CONFIGURE_MUTEX.release()
Mapper.dispatch._for_class(Mapper).after_configured()
def reconstructor(fn):
"""Decorate a method as the 'reconstructor' hook.
Designates a method as the "reconstructor", an ``__init__``-like
method that will be called by the ORM after the instance has been
loaded from the database or otherwise reconstituted.
The reconstructor will be invoked with no arguments. Scalar
(non-collection) database-mapped attributes of the instance will
be available for use within the function. Eagerly-loaded
collections are generally not yet available and will usually only
contain the first element. ORM state changes made to objects at
this stage will not be recorded for the next flush() operation, so
the activity within a reconstructor should be conservative.
.. seealso::
:ref:`mapping_constructors`
:meth:`.InstanceEvents.load`
"""
fn.__sa_reconstructor__ = True
return fn
def validates(*names, **kw):
r"""Decorate a method as a 'validator' for one or more named properties.
Designates a method as a validator, a method which receives the
name of the attribute as well as a value to be assigned, or in the
case of a collection, the value to be added to the collection.
The function can then raise validation exceptions to halt the
process from continuing (where Python's built-in ``ValueError``
and ``AssertionError`` exceptions are reasonable choices), or can
modify or replace the value before proceeding. The function should
otherwise return the given value.
Note that a validator for a collection **cannot** issue a load of that
collection within the validation routine - this usage raises
an assertion to avoid recursion overflows. This is a reentrant
condition which is not supported.
:param \*names: list of attribute names to be validated.
:param include_removes: if True, "remove" events will be
sent as well - the validation function must accept an additional
argument "is_remove" which will be a boolean.
:param include_backrefs: defaults to ``True``; if ``False``, the
validation function will not emit if the originator is an attribute
event related via a backref. This can be used for bi-directional
:func:`.validates` usage where only one validator should emit per
attribute operation.
.. versionadded:: 0.9.0
.. seealso::
:ref:`simple_validators` - usage examples for :func:`.validates`
"""
include_removes = kw.pop("include_removes", False)
include_backrefs = kw.pop("include_backrefs", True)
def wrap(fn):
fn.__sa_validators__ = names
fn.__sa_validation_opts__ = {
"include_removes": include_removes,
"include_backrefs": include_backrefs,
}
return fn
return wrap
def _event_on_load(state, ctx):
instrumenting_mapper = state.manager.info[_INSTRUMENTOR]
if instrumenting_mapper._reconstructor:
instrumenting_mapper._reconstructor(state.obj())
def _event_on_first_init(manager, cls):
"""Initial mapper compilation trigger.
instrumentation calls this one when InstanceState
is first generated, and is needed for legacy mutable
attributes to work.
"""
instrumenting_mapper = manager.info.get(_INSTRUMENTOR)
if instrumenting_mapper:
if Mapper._new_mappers:
configure_mappers()
def _event_on_init(state, args, kwargs):
"""Run init_instance hooks.
This also includes mapper compilation, normally not needed
here but helps with some piecemeal configuration
scenarios (such as in the ORM tutorial).
"""
instrumenting_mapper = state.manager.info.get(_INSTRUMENTOR)
if instrumenting_mapper:
if Mapper._new_mappers:
configure_mappers()
if instrumenting_mapper._set_polymorphic_identity:
instrumenting_mapper._set_polymorphic_identity(state)
class _ColumnMapping(dict):
"""Error reporting helper for mapper._columntoproperty."""
__slots__ = ("mapper",)
def __init__(self, mapper):
self.mapper = mapper
def __missing__(self, column):
prop = self.mapper._props.get(column)
if prop:
raise orm_exc.UnmappedColumnError(
"Column '%s.%s' is not available, due to "
"conflicting property '%s':%r"
% (column.table.name, column.name, column.key, prop)
)
raise orm_exc.UnmappedColumnError(
"No column %s is configured on mapper %s..."
% (column, self.mapper)
)
| gpl-2.0 |
ceroberoz/fire-dragon-and-roar | application/modules/property_site/controllers/management/login.php | 3411 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller{
public function __construct(){
parent::__construct();
}
function index(){
$this->load->view('ipapa/bm_login/index');
}
//log the user in
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{
//check to see if the user is logging in
//check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if the login is successful
//redirect them back to the home page
//$this->session->set_flashdata('message', $this->ion_auth->messages());
//redirect('/', 'refresh');
$user_group = $this->ion_auth->get_users_groups()->row();
redirect($user_group->name.'/home');
}
else
{
//if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('management/login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{
//the user is not logging in so display the login page
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->_render_page('management/login', $this->data);
}
}
function register(){
$this->form_validation->set_rules('identity', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$username = $this->input->post('identity');
$password = $this->input->post('password');
$email = $this->input->post('identity');
if($this->form_validation->run() == TRUE){
if(!$this->ion_auth->email_check($email)){
$additional_data = array(
'first_name' => '',
'last_name' => ''
);
$this->ion_auth->register($username, $password, $email, $additional_data);
//if($this->input->post('level')){
// add groups
$this->db->select('users.id')
->from('users')
->where('email',$email);
$uid = $this->db->get()->row()->id;
$group = "2";//$this->input->post('level');
$data = array(
'user_id' => $uid,
'group_id' => $group
);
$this->db->insert('users_groups',$data);
//}
//$this->load->view('ipapa/frontpage/landing');
$data['u_input'] = $email;
$this->load->view('ipapa/frontpage/success',$data);
}else{
echo "<script language='javascript'>alert('You have been registered, please check your email');
window.location='".base_url()."'</script>";
}
}else{
redirect('/','refresh');
//echo "error 0";
}
}
}
| gpl-2.0 |
code-acmer/p02 | CombatServer/GameObject/TransformationHistory.cpp | 4432 | #include "RakAssert.h"
#include "RakMemoryOverride.h"
#include "TransformationHistory.h"
TransformationHistoryCell::TransformationHistoryCell()
{
}
TransformationHistoryCell::TransformationHistoryCell(RakNet::TimeMS t, float x, float y, int vx, int vy, int state):
_time(t),
_x(x),
_y(y),
_velocityX(vx),
_velocityY(vy)
{
}
void TransformationHistory::Init(RakNet::TimeMS maxWriteInterval, RakNet::TimeMS maxHistoryTime)
{
writeInterval = maxWriteInterval;
maxHistoryLength = maxHistoryTime/maxWriteInterval+1;
history.ClearAndForceAllocation(maxHistoryLength+1, _FILE_AND_LINE_ );
RakAssert(writeInterval>0);
}
void TransformationHistory::Write(float x, float y, int vx, int vy, int state, RakNet::TimeMS curTimeMS)
{
if (history.Size() == 0)
{
history.Push(TransformationHistoryCell(curTimeMS, x, y, vx, vy, state), _FILE_AND_LINE_ );
}
else
{
const TransformationHistoryCell &lastCell = history.PeekTail();
if (curTimeMS - lastCell._time >= writeInterval)
{
history.Push(TransformationHistoryCell(curTimeMS, x, y, vx, vy, state), _FILE_AND_LINE_ );
if (history.Size() > maxHistoryLength)
history.Pop();
}
}
}
void TransformationHistory::Overwrite(float x, float y, int vx, int vy, int state, RakNet::TimeMS when)
{
int historySize = history.Size();
if (historySize == 0)
{
history.Push(TransformationHistoryCell(when, x, y ,vx, vy ,state), _FILE_AND_LINE_ );
}
else
{
// Find the history matching this time, and change the values.
int i;
for (i = historySize - 1; i >= 0; i--)
{
TransformationHistoryCell &cell = history[i];
if (when >= cell._time)
{
if (i == historySize-1 && when-cell._time>=writeInterval)
{
// Not an overwrite at all, but a new cell
history.Push(TransformationHistoryCell(when, x, y, vx, vy, state), _FILE_AND_LINE_ );
if (history.Size()>maxHistoryLength)
history.Pop();
return;
}
cell._time = when;
cell._x = x;
cell._y = y;
cell._velocityX = vx;
cell._velocityY = vy;
cell._state = state;
return;
}
}
}
}
TransformationHistory::ReadResult TransformationHistory::Read(float *x, float *y, int *vx, int *vy, int *state, RakNet::TimeMS when, RakNet::TimeMS curTime)
{
int historySize = history.Size();
if (historySize == 0)
{
return VALUES_UNCHANGED;
}
int i;
for (i = historySize - 1; i >= 0; i--)
{
const TransformationHistoryCell &cell = history[i];
if (when >= cell._time)
{
if (i == historySize-1)
{
if (curTime <= cell._time)
return VALUES_UNCHANGED;
float divisor = (float)(curTime - cell._time);
RakAssert(divisor != 0.0f);
float lerp = (float)(when - cell._time) / divisor;
// cell._x === *x ? so the result is always cell.x
// we will improve this later: dead reckoning
if (x)
*x = cell._x + (*x - cell._x) * lerp;
if (y)
*y = cell._y + (*y - cell._y) * lerp;
if (vx)
*vx = cell._velocityX + (*vx - cell._velocityX) * lerp;
if (vy)
*vy = cell._velocityY + (*vy - cell._velocityY) * lerp;
if (state)
*state = cell._state + (*state - cell._state) * lerp;
}
else
{
const TransformationHistoryCell &nextCell = history[i+1];
float divisor = (float)(nextCell._time - cell._time);
RakAssert(divisor != 0.0f);
float lerp = (float)(when - cell._time) / divisor;
if (x)
*x = cell._x + (nextCell._x - cell._x) * lerp;
if (y)
*y = cell._y + (nextCell._y - cell._y) * lerp;
if (vx)
*vx = cell._velocityX + (nextCell._velocityX - cell._velocityX) * lerp;
if (vy)
*vy = cell._velocityY + (nextCell._velocityY - cell._velocityY) * lerp;
if (state)
*state = cell._state + (nextCell._state - cell._state) * lerp;
}
return INTERPOLATED;
}
}
// Return the oldest one
const TransformationHistoryCell &cell = history.Peek();
if (x)
*x = cell._x;
if (y)
*y = cell._y;
if (x)
*x = cell._x;
if (vx)
*vx = cell._velocityX;
if (vy)
*vy = cell._velocityY;
if (state)
*state = cell._state;
return READ_OLDEST;
}
void TransformationHistory::Clear(void)
{
history.Clear(_FILE_AND_LINE_);
} | gpl-2.0 |
davidquantum/hermes2dold | tests/tutorial/13-newton-elliptic-1/main.cpp | 3865 | #include "hermes2d.h"
#include "solver_umfpack.h"
#include "function.h"
// This test makes sure that example 13-newton-elliptic-1 works correctly.
const int P_INIT = 2; // Initial polynomial degree
const double NEWTON_TOL = 1e-6; // Stopping criterion for the Newton's method
const int INIT_GLOB_REF_NUM = 3; // Number of initial uniform mesh refinements
const int INIT_BDY_REF_NUM = 5; // Number of initial refinements towards boundary
// Thermal conductivity (temperature-dependent)
// Note: for any u, this function has to be positive
template<typename Real>
Real lam(Real u) { return 1 + pow(u, 4); }
// Derivative of the thermal conductivity with respect to 'u'
template<typename Real>
Real dlam_du(Real u) { return 4*pow(u, 3); }
// Boundary condition type (essential = Dirichlet)
int bc_types(int marker)
{
return BC_ESSENTIAL;
}
// Heat sources (can be a general function of 'x' and 'y')
template<typename Real>
Real heat_src(Real x, Real y)
{
return 1.0;
}
// Jacobian matrix
template<typename Real, typename Scalar>
Scalar jac(int n, double *wt, Func<Real> *u, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
Func<Scalar>* u_prev = ext->fn[0];
for (int i = 0; i < n; i++)
result += wt[i] * (dlam_du(u_prev->val[i]) * u->val[i] * (u_prev->dx[i] * v->dx[i] + u_prev->dy[i] * v->dy[i])
+ lam(u_prev->val[i]) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
return result;
}
// Fesidual vector
template<typename Real, typename Scalar>
Scalar res(int n, double *wt, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
Func<Scalar>* u_prev = ext->fn[0];
for (int i = 0; i < n; i++)
result += wt[i] * (lam(u_prev->val[i]) * (u_prev->dx[i] * v->dx[i] + u_prev->dy[i] * v->dy[i])
- heat_src(e->x[i], e->y[i]) * v->val[i]);
return result;
}
int main(int argc, char* argv[])
{
// load the mesh file
Mesh mesh;
H2DReader mloader;
mloader.load("square.mesh", &mesh);
// initial mesh refinements
for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh.refine_all_elements();
mesh.refine_towards_boundary(1,INIT_BDY_REF_NUM);
// initialize the shapeset and the cache
H1Shapeset shapeset;
PrecalcShapeset pss(&shapeset);
// create an H1 space
H1Space space(&mesh, &shapeset);
space.set_bc_types(bc_types);
space.set_uniform_order(P_INIT);
space.assign_dofs();
// previous solution for the Newton's iteration
Solution u_prev;
// initialize the weak formulation
WeakForm wf(1);
wf.add_biform(0, 0, callback(jac), UNSYM, ANY, 1, &u_prev);
wf.add_liform(0, callback(res), ANY, 1, &u_prev);
// initialize the nonlinear system and solver
UmfpackSolver umfpack;
NonlinSystem nls(&wf, &umfpack);
nls.set_spaces(1, &space);
nls.set_pss(1, &pss);
// set zero function as the initial condition
u_prev.set_zero(&mesh);
nls.set_ic(&u_prev, &u_prev);
// Newton's loop
int it = 1;
double res_l2_norm;
Solution sln;
do
{
info("\n---- Newton iter %d ---------------------------------\n", it++);
// assemble the Jacobian matrix and residual vector,
// solve the system
nls.assemble();
nls.solve(1, &sln);
// calculate the l2-norm of residual vector
res_l2_norm = nls.get_residuum_l2_norm();
info("Residuum L2 norm: %g\n", res_l2_norm);
// save the new solution as "previous" for the
// next Newton's iteration
u_prev = sln;
if (it > 18) break;
}
while (res_l2_norm > NEWTON_TOL);
#define ERROR_SUCCESS 0
#define ERROR_FAILURE -1
if (it <= 18 && res_l2_norm < 1e-10) { // it should be 18 and res_l2_norm = 4.87539e-12
printf("Success!\n");
return ERROR_SUCCESS;
}
else {
printf("Failure!\n");
return ERROR_FAILURE;
}
}
| gpl-2.0 |
marteenzh/d1 | modules/sparkpost/src/MessageWrapper.php | 2753 | <?php
namespace Drupal\sparkpost;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use SparkPost\SparkPostException;
/**
* Message wrapper class.
*/
class MessageWrapper implements MessageWrapperInterface {
use DependencySerializationTrait;
/**
* The sparkpost message.
*
* @var array
*/
protected $sparkpostMessage;
/**
* The Drupal message.
*
* @var array
*/
protected $drupalMessage;
/**
* Exception, if any.
*
* @var \SparkPost\SparkPostException
*/
protected $apiResponseException;
/**
* Result, if any.
*
* @var array
*/
protected $result;
/**
* Client to use.
*
* @var \Drupal\sparkpost\ClientServiceInterface
*/
protected $clientService;
/**
* SparkpostMessage constructor.
*/
public function __construct(ClientServiceInterface $clientService) {
$this->clientService = $clientService;
}
/**
* {@inheritdoc}
*/
public function setDrupalMessage(array $drupal_message) {
$this->drupalMessage = $drupal_message;
}
/**
* {@inheritdoc}
*/
public function setSparkpostMessage(array $sparkpost_message) {
$this->sparkpostMessage = $sparkpost_message;
}
/**
* {@inheritdoc}
*/
public function setApiResponseException(SparkPostException $sparkPostException) {
$this->apiResponseException = $sparkPostException;
}
/**
* {@inheritdoc}
*/
public function setResult(array $result) {
$this->result = $result;
}
/**
* {@inheritdoc}
*/
public function getSparkpostMessage() {
return $this->sparkpostMessage;
}
/**
* {@inheritdoc}
*/
public function getDrupalMessage() {
return $this->drupalMessage;
}
/**
* {@inheritdoc}
*/
public function getApiResponseException() {
return $this->apiResponseException;
}
/**
* {@inheritdoc}
*/
public function getResult() {
return $this->result;
}
/**
* {@inheritdoc}
*/
public function getClientService() {
return $this->clientService;
}
/**
* {@inheritdoc}
*/
public function sendMessage() {
try {
$data = $this->clientService->sendMessage($this->sparkpostMessage);
$this->setResult($data);
\Drupal::moduleHandler()->invokeAll('sparkpost_mailsend_success', [$this]);
return TRUE;
}
catch (SparkPostException $e) {
$this->setApiResponseException($e);
}
catch (\Exception $e) {
// @todo: Handle sparkpost exceptions separately.
}
\Drupal::moduleHandler()->invokeAll('sparkpost_mailsend_error', [$this]);
return FALSE;
}
/**
* Clears the API response exception.
*/
public function clearApiResposeException() {
$this->apiResponseException = NULL;
}
}
| gpl-2.0 |
isa-group/ideas-studio | src/test/java/es/us/isa/ideas/test/app/pageobject/login/RecoverPasswordPage.java | 4201 | package es.us.isa.ideas.test.app.pageobject.login;
import es.us.isa.ideas.test.app.pageobject.PageObject;
import static es.us.isa.ideas.test.app.pageobject.PageObject.getWebDriver;
import es.us.isa.ideas.test.app.pageobject.TestCase;
import es.us.isa.ideas.test.app.utils.IdeasURLType;
import es.us.isa.ideas.test.app.utils.TestProperty;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
/**
* Applied Software Engineering Research Group (ISA Group) University of
* Sevilla, Spain
*
* @author Felipe Vieira da Cunha Serafim <fvieiradacunha@us.es>
* @version 1.0
*/
public class RecoverPasswordPage extends RegisterSocialGooglePage {
// FORM
@FindBy(id = "email")
WebElement emailField;
@FindBy(id = "submit")
WebElement submitButton;
@FindBy(xpath = "//*[@id=\"loginLoader\"]/div/h2")
WebElement confirmationTitle;
// MODAL
static final Logger LOG = Logger.getLogger(RecoverPasswordPage.class.getName());
static final String URL = TestProperty.getBaseUrl() + "/security/useraccount/resetPassword";
public static RecoverPasswordPage navigateTo() {
getWebDriver().get(URL);
return PageFactory.initElements(getWebDriver(), RecoverPasswordPage.class);
}
// click
public RecoverPasswordPage clickOnSubmit() {
clickOnClickableElement(submitButton);
return PageFactory.initElements(getWebDriver(), RecoverPasswordPage.class);
}
// sendKeys
public RecoverPasswordPage typeEmail(CharSequence email) {
emailField.sendKeys(email);
return PageFactory.initElements(getWebDriver(), RecoverPasswordPage.class);
}
// Tests
public static void testRecoverPassword(CharSequence email, CharSequence emailPass, String user) {
new RegisterTestCase().testRecoverPassword(email, emailPass, user);
}
private static class RegisterTestCase extends TestCase {
public void testRecoverPassword(CharSequence email, CharSequence emailPass, String user) {
RecoverPasswordPage pageRecover = RecoverPasswordPage.navigateTo();
RegisterSocialGooglePage pageGoogle = PageFactory.initElements(getWebDriver(), RegisterSocialGooglePage.class);
PageObject.waitForElementVisible(pageRecover.emailField, 10);
pageRecover.typeEmail(email)
.clickOnSubmit();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(RecoverPasswordPage.class.getName()).log(Level.SEVERE, null, ex);
}
// Modal confirmation
PageObject.waitForElementVisible(pageRecover.confirmationTitle, 10);
TEST_RESULT = pageRecover.confirmationTitle.getText().contains("Please check your email");
Assert.assertTrue(TEST_RESULT);
TEST_RESULT = RegisterSocialGooglePage.confirmEmail();
Assert.assertTrue(TEST_RESULT);
String password = RegisterSocialGooglePage.getPasswordInEmail();
TEST_RESULT = !password.equals("");
Assert.assertTrue(TEST_RESULT);
// Updated test password in properties file
TestProperty.setTestRegisterUserPassword(password);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(RegisterPage.class.getName()).log(Level.SEVERE, null, ex);
}
// Delete current email
pageGoogle.clickOnDeleteEmailButton()
.expectDifferentUrl();
// Login with generated password
LoginPage.testLogin(user, password);
TEST_RESULT = PageObject.currentPageContainsURLType(IdeasURLType.EDITOR_URL);
LOG.log(Level.INFO, "test_result: {0}", TEST_RESULT);
Assert.assertTrue(TEST_RESULT);
}
}
}
| gpl-2.0 |
zomux/deepcommunity | dlmonitor/db_models.py | 2373 | import sys
from sqlalchemy import Column, Integer, String, ForeignKey, Text, DateTime, Unicode, Boolean
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_searchable import make_searchable
from sqlalchemy_utils.types import TSVectorType
if 'Base' not in globals():
Base = declarative_base()
make_searchable()
def str_repr(string):
if sys.version_info.major == 3:
return string
else:
return string.encode('utf-8')
class ArxivModel(Base):
__tablename__ = 'arxiv'
id = Column(Integer, primary_key=True, autoincrement=True)
version = Column(Integer)
popularity = Column(Integer)
title = Column(Unicode(800, collation=''))
arxiv_url = Column(String(255), primary_key=True)
pdf_url = Column(String(255))
published_time = Column(DateTime())
authors = Column(Unicode(800, collation=''))
abstract = Column(Text(collation=''))
journal_link = Column(Text(collation=''), nullable=True)
tag = Column(String(255))
introduction = Column(Text(collation=''))
conclusion = Column(Text(collation=''))
analyzed = Column(Boolean, server_default='false', default=False)
# For full text search
search_vector = Column(
TSVectorType('title', 'abstract', 'authors', weights={'title': 'A', 'abstract': 'B', 'authors': 'C'}))
def __repr__(self):
template = '<Arxiv(id="{0}", url="{1}")>'
return str_repr(template.format(self.id, self.arxiv_url))
class TwitterModel(Base):
__tablename__ = 'twitter'
id = Column(Integer, primary_key=True, autoincrement=True)
tweet_id = Column(String(20), primary_key=True)
popularity = Column(Integer)
pic_url = Column(String(255), nullable=True)
published_time = Column(DateTime())
user = Column(Unicode(255))
text = Column(Text())
# For full text search
search_vector = Column(TSVectorType('text'))
def __repr__(self):
template = '<Twitter(id="{0}", user_name="{1}")>'
return str_repr(template.format(self.id, self.user))
class WorkingQueueModel(Base):
__tablename__ = "working"
id = Column(Integer, primary_key=True, autoincrement=True)
type = Column(String(255), nullable=True)
param = Column(String(255), nullable=True)
def __repr__(self):
return __tablename__ + self.id
| gpl-2.0 |
HardiskFromYT/Trinity-Zero | src/server/game/Handlers/LootHandler.cpp | 17270 | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "WorldPacket.h"
#include "Log.h"
#include "Corpse.h"
#include "GameObject.h"
#include "Player.h"
#include "ObjectAccessor.h"
#include "WorldSession.h"
#include "LootMgr.h"
#include "Object.h"
#include "Group.h"
#include "World.h"
#include "Util.h"
void WorldSession::HandleAutostoreLootItemOpcode(WorldPacket & recv_data)
{
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_AUTOSTORE_LOOT_ITEM");
Player* player = GetPlayer();
uint64 lguid = player->GetLootGUID();
Loot* loot = NULL;
uint8 lootSlot = 0;
recv_data >> lootSlot;
if (IS_GAMEOBJECT_GUID(lguid))
{
GameObject* go = player->GetMap()->GetGameObject(lguid);
// not check distance for GO in case owned GO (fishing bobber case, for example) or Fishing hole GO
if (!go || ((go->GetOwnerGUID() != _player->GetGUID() && go->GetGoType() != GAMEOBJECT_TYPE_FISHINGHOLE) && !go->IsWithinDistInMap(_player, INTERACTION_DISTANCE)))
{
player->SendLootRelease(lguid);
return;
}
loot = &go->loot;
}
else if (IS_ITEM_GUID(lguid))
{
Item* pItem = player->GetItemByGuid(lguid);
if (!pItem)
{
player->SendLootRelease(lguid);
return;
}
loot = &pItem->loot;
}
else if (IS_CORPSE_GUID(lguid))
{
Corpse* bones = ObjectAccessor::GetCorpse(*player, lguid);
if (!bones)
{
player->SendLootRelease(lguid);
return;
}
loot = &bones->loot;
}
else
{
Creature* creature = GetPlayer()->GetMap()->GetCreature(lguid);
bool lootAllowed = creature && creature->isAlive() == (player->getClass() == CLASS_ROGUE && creature->lootForPickPocketed);
if (!lootAllowed || !creature->IsWithinDistInMap(_player, INTERACTION_DISTANCE))
{
player->SendLootRelease(lguid);
return;
}
loot = &creature->loot;
}
player->StoreLootItem(lootSlot, loot);
}
void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recv_data*/)
{
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_LOOT_MONEY");
Player* player = GetPlayer();
uint64 guid = player->GetLootGUID();
if (!guid)
return;
Loot* loot = NULL;
bool shareMoney = true;
switch (GUID_HIPART(guid))
{
case HIGHGUID_GAMEOBJECT:
{
GameObject* go = GetPlayer()->GetMap()->GetGameObject(guid);
// do not check distance for GO if player is the owner of it (ex. fishing bobber)
if (go && ((go->GetOwnerGUID() == player->GetGUID() || go->IsWithinDistInMap(player, INTERACTION_DISTANCE))))
loot = &go->loot;
break;
}
case HIGHGUID_CORPSE: // remove insignia ONLY in BG
{
Corpse* bones = ObjectAccessor::GetCorpse(*player, guid);
if (bones && bones->IsWithinDistInMap(player, INTERACTION_DISTANCE))
{
loot = &bones->loot;
shareMoney = false;
}
break;
}
case HIGHGUID_ITEM:
{
if (Item* item = player->GetItemByGuid(guid))
{
loot = &item->loot;
shareMoney = false;
}
break;
}
case HIGHGUID_UNIT:
{
Creature* creature = player->GetMap()->GetCreature(guid);
bool lootAllowed = creature && creature->isAlive() == (player->getClass() == CLASS_ROGUE && creature->lootForPickPocketed);
if (lootAllowed && creature->IsWithinDistInMap(player, INTERACTION_DISTANCE))
{
loot = &creature->loot;
if (creature->isAlive())
shareMoney = false;
}
break;
}
default:
return; // unlootable type
}
if (loot)
{
loot->NotifyMoneyRemoved();
if (shareMoney && player->GetGroup()) //item, pickpocket and players can be looted only single player
{
Group* group = player->GetGroup();
std::vector<Player*> playersNear;
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
if (!member)
continue;
if (player->IsWithinDistInMap(member, sWorld->getFloatConfig(CONFIG_GROUP_XP_DISTANCE), false))
playersNear.push_back(member);
}
uint32 goldPerPlayer = uint32((loot->gold) / (playersNear.size()));
for (std::vector<Player*>::const_iterator i = playersNear.begin(); i != playersNear.end(); ++i)
{
(*i)->ModifyMoney(goldPerPlayer);
WorldPacket data(SMSG_LOOT_MONEY_NOTIFY, 4 + 1);
data << uint32(goldPerPlayer);
data << uint8(playersNear.size() > 1 ? 0 : 1); // Controls the text displayed in chat. 0 is "Your share is..." and 1 is "You loot..."
(*i)->GetSession()->SendPacket(&data);
}
}
else
{
player->ModifyMoney(loot->gold);
WorldPacket data(SMSG_LOOT_MONEY_NOTIFY, 4 + 1);
data << uint32(loot->gold);
data << uint8(1); // "You loot..."
SendPacket(&data);
}
loot->gold = 0;
}
}
void WorldSession::HandleLootOpcode(WorldPacket & recv_data)
{
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_LOOT");
uint64 guid;
recv_data >> guid;
// Check possible cheat
if (!_player->isAlive())
return;
GetPlayer()->SendLoot(guid, LOOT_CORPSE);
// interrupt cast
if (GetPlayer()->IsNonMeleeSpellCasted(false))
GetPlayer()->InterruptNonMeleeSpells(false);
}
void WorldSession::HandleLootReleaseOpcode(WorldPacket& recvData)
{
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_LOOT_RELEASE");
// cheaters can modify lguid to prevent correct apply loot release code and re-loot
// use internal stored guid
uint64 guid;
recvData >> guid;
if (uint64 lguid = GetPlayer()->GetLootGUID())
if (lguid == guid)
DoLootRelease(lguid);
}
void WorldSession::DoLootRelease(uint64 lguid)
{
Player *player = GetPlayer();
Loot *loot;
player->SetLootGUID(0);
player->SendLootRelease(lguid);
player->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
if (!player->IsInWorld())
return;
if (IS_GAMEOBJECT_GUID(lguid))
{
GameObject* go = GetPlayer()->GetMap()->GetGameObject(lguid);
// not check distance for GO in case owned GO (fishing bobber case, for example) or Fishing hole GO
if (!go || ((go->GetOwnerGUID() != _player->GetGUID() && go->GetGoType() != GAMEOBJECT_TYPE_FISHINGHOLE) && !go->IsWithinDistInMap(_player, INTERACTION_DISTANCE)))
return;
loot = &go->loot;
if (go->GetGoType() == GAMEOBJECT_TYPE_DOOR)
{
// locked doors are opened with spelleffect openlock, prevent remove its as looted
go->UseDoorOrButton();
}
else if (loot->isLooted() || go->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE)
{
// GO is mineral vein? so it is not removed after its looted
if (go->GetGoType() == GAMEOBJECT_TYPE_CHEST)
{
uint32 go_min = go->GetGOInfo()->chest.minSuccessOpens;
uint32 go_max = go->GetGOInfo()->chest.maxSuccessOpens;
// only vein pass this check
if (go_min != 0 && go_max > go_min)
{
float amount_rate = sWorld->getRate(RATE_MINING_AMOUNT);
float min_amount = go_min*amount_rate;
float max_amount = go_max*amount_rate;
go->AddUse();
float uses = float(go->GetUseCount());
if (uses < max_amount)
{
if (uses >= min_amount)
{
float chance_rate = sWorld->getRate(RATE_MINING_NEXT);
int32 ReqValue = 175;
LockEntry const* lockInfo = sLockStore.LookupEntry(go->GetGOInfo()->chest.lockId);
if (lockInfo)
ReqValue = lockInfo->Skill[0];
float skill = float(player->GetSkillValue(SKILL_MINING))/(ReqValue+25);
double chance = pow(0.8*chance_rate, 4*(1/double(max_amount))*double(uses));
if (roll_chance_f((float)(100*chance+skill)))
{
go->SetLootState(GO_READY);
}
else // not have more uses
go->SetLootState(GO_JUST_DEACTIVATED);
}
else // 100% chance until min uses
go->SetLootState(GO_READY);
}
else // max uses already
go->SetLootState(GO_JUST_DEACTIVATED);
}
else // not vein
go->SetLootState(GO_JUST_DEACTIVATED);
}
else if (go->GetGoType() == GAMEOBJECT_TYPE_FISHINGHOLE)
{ // The fishing hole used once more
go->AddUse(); // if the max usage is reached, will be despawned in next tick
if (go->GetUseCount() >= urand(go->GetGOInfo()->fishinghole.minSuccessOpens, go->GetGOInfo()->fishinghole.maxSuccessOpens))
{
go->SetLootState(GO_JUST_DEACTIVATED);
}
else
go->SetLootState(GO_READY);
}
else // not chest (or vein/herb/etc)
go->SetLootState(GO_JUST_DEACTIVATED);
loot->clear();
}
else
{
// not fully looted object
go->SetLootState(GO_ACTIVATED, player);
// if the round robin player release, reset it.
if (player->GetGUID() == loot->roundRobinPlayer)
{
if (Group* group = player->GetGroup())
{
if (group->GetLootMethod() != MASTER_LOOT)
{
loot->roundRobinPlayer = 0;
}
}
else
loot->roundRobinPlayer = 0;
}
}
}
else if (IS_CORPSE_GUID(lguid)) // ONLY remove insignia at BG
{
Corpse* corpse = ObjectAccessor::GetCorpse(*player, lguid);
if (!corpse || !corpse->IsWithinDistInMap(_player, INTERACTION_DISTANCE))
return;
loot = &corpse->loot;
if (loot->isLooted())
{
loot->clear();
corpse->RemoveFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
}
}
else if (IS_ITEM_GUID(lguid))
{
Item* pItem = player->GetItemByGuid(lguid);
if (!pItem)
return;
ItemTemplate const* proto = pItem->GetTemplate();
// destroy only 5 items from stack in case prospecting and milling
if (proto->Flags & (ITEM_PROTO_FLAG_PROSPECTABLE | ITEM_PROTO_FLAG_MILLABLE))
{
pItem->m_lootGenerated = false;
pItem->loot.clear();
uint32 count = pItem->GetCount();
// >=5 checked in spell code, but will work for cheating cases also with removing from another stacks.
if (count > 5)
count = 5;
player->DestroyItemCount(pItem, count, true);
}
else
// FIXME: item must not be deleted in case not fully looted state. But this pre-request implement loot saving in DB at item save. Or cheating possible.
player->DestroyItem(pItem->GetBagSlot(), pItem->GetSlot(), true);
return; // item can be looted only single player
}
else
{
Creature* creature = GetPlayer()->GetMap()->GetCreature(lguid);
bool lootAllowed = creature && creature->isAlive() == (player->getClass() == CLASS_ROGUE && creature->lootForPickPocketed);
if (!lootAllowed || !creature->IsWithinDistInMap(_player, INTERACTION_DISTANCE))
return;
loot = &creature->loot;
if (loot->isLooted())
{
// skip pickpocketing loot for speed, skinning timer reduction is no-op in fact
if (!creature->isAlive())
creature->AllLootRemovedFromCorpse();
creature->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
loot->clear();
}
else
{
// if the round robin player release, reset it.
if (player->GetGUID() == loot->roundRobinPlayer)
{
if (Group* group = player->GetGroup())
{
if (group->GetLootMethod() != MASTER_LOOT)
{
loot->roundRobinPlayer = 0;
group->SendLooter(creature, NULL);
// force update of dynamic flags, otherwise other group's players still not able to loot.
creature->ForceValuesUpdateAtIndex(UNIT_DYNAMIC_FLAGS);
}
}
else
loot->roundRobinPlayer = 0;
}
}
}
//Player is not looking at loot list, he doesn't need to see updates on the loot list
loot->RemoveLooter(player->GetGUID());
}
void WorldSession::HandleLootMasterGiveOpcode(WorldPacket & recv_data)
{
uint8 slotid;
uint64 lootguid, target_playerguid;
recv_data >> lootguid >> slotid >> target_playerguid;
if (!_player->GetGroup() || _player->GetGroup()->GetLooterGuid() != _player->GetGUID())
{
_player->SendLootRelease(GetPlayer()->GetLootGUID());
return;
}
Player* target = ObjectAccessor::FindPlayer(MAKE_NEW_GUID(target_playerguid, 0, HIGHGUID_PLAYER));
if (!target)
return;
sLog->outDebug(LOG_FILTER_NETWORKIO, "WorldSession::HandleLootMasterGiveOpcode (CMSG_LOOT_MASTER_GIVE, 0x02A3) Target = [%s].", target->GetName());
if (_player->GetLootGUID() != lootguid)
return;
Loot* loot = NULL;
if (IS_CREATURE_GUID(GetPlayer()->GetLootGUID()))
{
Creature* creature = GetPlayer()->GetMap()->GetCreature(lootguid);
if (!creature)
return;
loot = &creature->loot;
}
else if (IS_GAMEOBJECT_GUID(GetPlayer()->GetLootGUID()))
{
GameObject* pGO = GetPlayer()->GetMap()->GetGameObject(lootguid);
if (!pGO)
return;
loot = &pGO->loot;
}
if (!loot)
return;
if (slotid > loot->items.size())
{
sLog->outDebug(LOG_FILTER_LOOT, "MasterLootItem: Player %s might be using a hack! (slot %d, size %lu)", GetPlayer()->GetName(), slotid, (unsigned long)loot->items.size());
return;
}
LootItem& item = loot->items[slotid];
ItemPosCountVec dest;
InventoryResult msg = target->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, item.itemid, item.count);
if (msg != EQUIP_ERR_OK)
{
target->SendEquipError(msg, NULL, NULL, item.itemid);
// send duplicate of error massage to master looter
_player->SendEquipError(msg, NULL, NULL, item.itemid);
return;
}
// list of players allowed to receive this item in trade
AllowedLooterSet looters = item.GetAllowedLooters();
// not move item from loot to target inventory
Item* newitem = target->StoreNewItem(dest, item.itemid, true, item.randomPropertyId, looters);
target->SendNewItem(newitem, uint32(item.count), false, false, true);
// mark as looted
item.count=0;
item.is_looted=true;
loot->NotifyItemRemoved(slotid);
--loot->unlootedCount;
}
| gpl-2.0 |
vburlbl/phpbb-anti-spam | root/includes/abm/functions.php | 52139 | <?php
/**
*
* @package Advanced Block MOD
* @version $Id: functions.php, v 1.004 2012/12/19 Martin Truckenbrodt Exp$
* @copyright (c) 2009, 2012 Martin Truckenbrodt
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
if (!defined('IN_PHPBB')) {
exit;
}
/**
* Check if ip is blacklisted
* */
function check_iprbl($action = 'recheck', $ip = false)
{
global $db, $config;
// Need to be listed on all servers...
$weight = 0;
$info = array();
//check only if ip is IPv4
if ($ip && !preg_match(get_preg_expression('ipv6'), $ip)) {
$quads = explode('.', $ip);
$reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
$sql = 'SELECT iprbl_id, iprbl_fqdn, iprbl_lookup, iprbl_weight FROM ' . IPRBL_TABLE . "
WHERE iprbl_weight > '0'
ORDER BY iprbl_weight DESC, iprbl_count DESC";
$result = $db->sql_query($sql);
while (($row = $db->sql_fetchrow($result)) && ($weight < 5 || $action == 'recheck'))
{
if (phpbb_checkdnsrr($reverse_ip . '.' . $row['iprbl_fqdn'] . '.', 'A') === true) {
if ($weight < 5) {
$info['blacklists'][] = array($row['iprbl_fqdn'], $row['iprbl_lookup'] . $ip);
} else if ($weight > 4 && $action == 'recheck') {
$info['next'][] = array($row['iprbl_fqdn'], $row['iprbl_lookup'] . $ip);
}
if ($config['log_check_iprbl'] && $action != 'recheck') {
add_log('block', $row['iprbl_id'], 0, 0, 'LOG_IPRBL_FOUND', $row['iprbl_fqdn'], $ip, $row['iprbl_lookup'] . $ip);
}
$weight += $row['iprbl_weight'];
$sql = 'UPDATE ' . IPRBL_TABLE . '
SET iprbl_count = iprbl_count + 1
WHERE iprbl_id = ' . $row['iprbl_id'];
$db->sql_query($sql);
}
}
$db->sql_freeresult($result);
if ($weight > 4 || $action == 'recheck') {
if ($weight > 4) {
$info['blocked'] = true;
}
if ($config['log_check_iprbl'] && $action != 'recheck') {
add_log('block', 0, 0, 0, 'LOG_IPRBL_' . strtoupper($action));
}
return $info;
}
}
if ($info && $action == 'recheck') {
return $info;
} else {
return false;
}
}
/**
* Check if ip, username, user_email or message is blacklisted
* */
function check_httpbl($action = 'recheck', $ip = false, $username = false, $email = false, $message = false)
{
global $phpbb_root_path, $phpEx, $db, $config;
if (!function_exists('get_remote_file')) {
include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
}
// Need to be listed on all servers...
$next = false;
$weight = 0;
$info = array();
if (($ip || $username || $email || $message)) {
// no reverse_ip for IPv6 clients!!!
if ($ip && !preg_match(get_preg_expression('ipv6'), $ip)) {
$quads = explode('.', $ip);
$reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
} else {
$reverse_ip = '';
}
$sql = 'SELECT * FROM ' . HTTPBL_TABLE . "
WHERE httpbl_weight > '0'
ORDER BY httpbl_weight DESC, httpbl_count DESC";
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
$block_spam = $types_found = false;
// Stop Forum Spam
if ($row['httpbl_name'] == 'sfs') {
$type = $value = $appears = $frequency = $frequency_min = false;
$apiurl = '/api?';
// SFS does not support IPv6
if ($ip && !preg_match(get_preg_expression('ipv6'), $ip) && $row['httpbl_use_ip'] && $row['httpbl_check_ip']) {
$apiurl .= 'ip=' . $ip;
if (($username && $row['httpbl_use_username'] && $row['httpbl_check_username']) || ($email && $row['httpbl_use_email'] && $row['httpbl_check_email'])) {
$apiurl .= '&';
}
}
if ($username && $row['httpbl_use_username'] && $row['httpbl_check_username']) {
$apiurl .= 'username=' . $username;
if ($email && $row['httpbl_use_email'] && $row['httpbl_check_email']) {
$apiurl .= '&';
}
}
if ($email && $row['httpbl_use_email'] && $row['httpbl_check_email']) {
$apiurl .= 'email=' . $email;
}
$file = get_remote_file('stopforumspam.com', '', $apiurl, $errstr, $errno);
if ($file !== false) {
$file = str_replace("\r\n", "\n", $file);
$file = explode("\n", $file);
foreach ($file as $line)
{
if (strpos($line, '<type>') !== false && strpos($line, '</type>') !== false) {
$start = strpos($line, '<type>') + 6;
$end = strpos($line, '</type>') - $start;
$type = substr($line, $start, $end);
switch ($type)
{
case 'ip':
$value = $ip;
//increase the following value if you have false positives with SFS caused by listed ip addresses
$frequency_min = 1;
break;
case 'username':
$value = $username;
//increase the following value if you have false positives with SFS caused by listed usernames
$frequency_min = 1;
break;
case 'email':
$value = $email;
//increase the following value if you have false positives with SFS caused by listed e-mail addresses
$frequency_min = 1;
break;
}
} else if (strpos($line, '<appears>') !== false && strpos($line, '</appears>') !== false) {
$start = strpos($line, '<appears>') + 9;
$end = strpos($line, '</appears>') - $start;
$appears = (substr($line, $start, $end) == 'yes') ? true : false;
} else if (strpos($line, '<frequency>') !== false && strpos($line, '</frequency>') !== false) {
$start = strpos($line, '<frequency>') + 11;
$end = strpos($line, '</frequency>') - $start;
$frequency = (int) substr($line, $start, $end);
if ($appears && $frequency >= $frequency_min) {
$types_found .= (($types_found !== false) ? ', ' : '') . $type;
// block only if at least ip or email have been found - username is easy to change and can have a lot of false positives for regular and legitimate usernames
if ($type == 'ip' || $type == 'email') {
$block_spam = true;
}
$appears = $frequency = false;
}
}
}
}
}
// BotScout
else if ($row['httpbl_name'] == 'botscout') {
$type = $value = $fullapiurl = false;
$apiurl = '/test/?multi';
//increase the following values if you have false positives with BotScout
$frequency_ip_min = 1;
$frequency_username_min = 1;
$frequency_email_min = 1;
// BotScout does not support IPv6
if ($ip && !preg_match(get_preg_expression('ipv6'), $ip) && $row['httpbl_use_ip'] && $row['httpbl_check_ip']) {
$apiurl .= '&ip=' . $ip;
}
if ($username && $row['httpbl_use_username'] && $row['httpbl_check_username']) {
$apiurl .= '&name=' . $username;
}
if ($email && $row['httpbl_use_email'] && $row['httpbl_check_email']) {
$apiurl .= '&mail=' . $email;
}
// without key only 20 requests per day are allowed, with key 300 requests per day are free
// do not add the key to the public lookup URL
if ($row['httpbl_key']) {
$fullapiurl = $apiurl . '&key=' . $row['httpbl_key'];
}
$file = get_remote_file('botscout.com', '', $fullapiurl, $errstr, $errno);
if ($file !== false) {
$response = explode('|', $file);
if (substr($response[0], -1) == 'Y') {
//block only then ip or email are listed, username has a lot of false positives
if ($response[3] >= $frequency_ip_min) {
$types_found .= (($types_found !== false) ? ', ' : '') . 'ip';
$block_spam = true;
}
if ($response[5] >= $frequency_email_min) {
$types_found .= (($types_found !== false) ? ', ' : '') . 'email';
$block_spam = true;
}
if ($response[7] >= $frequency_username_min) {
$types_found .= (($types_found !== false) ? ', ' : '') . 'username';
}
} else if (substr($file, 4, 1) == '!') {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], $errno, $errstr . $file);
}
}
}
// Akismet
// based on http://akismet.com/development/api
// a key always is needed
else if ($row['httpbl_name'] == 'akismet' && $row['httpbl_key']) {
global $phpbb_root_path, $phpEx, $user;
$server_url = generate_board_url();
$apiurl = 'key=' . $row['httpbl_key'] . '&blog=' . urlencode($server_url . '/index.' . $phpEx);
$file = post_remote_file('rest.akismet.com', '/1.1/verify-key', $apiurl, $errstr, $errno);
if ($file[1] != 'valid') {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], $errno, $errstr . $file[0]);
}
$apiurl = '';
if (!$ip) {
$ip = $user->ip;
}
$apiurl = 'user_ip=' . urlencode($ip) . '&user_agent=' . urlencode($user->browser) . '&referrer=' . urlencode($user->referer) . '&blog=' . urlencode($server_url . '/index.' . $phpEx) . '&comment_type=forum';
if ($username && $row['httpbl_use_username'] && $row['httpbl_check_username']) {
$apiurl .= '&comment_author=' . urlencode($username);
}
if ($email && $row['httpbl_use_email'] && $row['httpbl_check_email']) {
$apiurl .= '&comment_author_email=' . urlencode($email);
}
if ($email && $row['httpbl_use_message'] && $row['httpbl_check_message']) {
$apiurl .= '&comment_content=' . urlencode($message);
}
$file = post_remote_file($row['httpbl_key'] . '.rest.akismet.com', '/1.1/comment-check', $apiurl, $errstr, $errno);
if ($file[1] == 'true') {
$types_found = 'N/A';
$block_spam = true;
} else if ($file[1] == 'invalid') {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], $errno, $errstr . $file[0]);
}
}
// Project Honey Pot
// based on http://www.projecthoneypot.org/httpbl_api.php
// a key always is needed
// does not support IPv6
else if ($row['httpbl_name'] == 'honeypot' && $row['httpbl_key'] && $ip && !preg_match(get_preg_expression('ipv6'), $ip)) {
$apiurl = '';
$query = $row['httpbl_key'] . '.' . $reverse_ip . '.dnsbl.httpbl.org';
$response = gethostbyname($query);
if ($response != $query) {
$response = explode('.', $response);
// don't report and block search engines and suspicious ips
// more information on http://www.projecthoneypot.org/httpbl_api.php
if ($response[1] > 0 && $response[2] > 0 && $response[3] > 1 && sizeof($response) == 4) {
$types_found = 'ip';
$block_spam = true;
} else if ($response[0] != '127') {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], 0, implode('.', $response));
}
}
}
// Block Disposable Email Addresses
else if ($row['httpbl_name'] == 'bde' && $row['httpbl_key'] && ($action == 'register' || $action == 'profile') && $email) {
$apiurl = '';
$response = get_remote_file('check.block-disposable-email.com', '', '/check.php?mail=' . $email . '&apikey=' . $row['httpbl_key'], $errstr, $errno);
if ($response !== false) {
if ($response == 'OK') {
break;
} else if ($response == 'BLOCK') {
$types_found = 'email';
$block_spam = true;
} else {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], 0, $response);
}
}
}
// Filter Disposable and Proxy IPS
else if ($row['httpbl_name'] == 'spm' && $row['httpbl_key'] && ($action == 'register' || $action == 'profile') && $email) {
$apiurl = '';
$response = get_remote_file('b.spam-trap.net', '', '/verify.php?mail=' . $email . '&ip='.$ip.'&apikey=' . md5($_SERVER['HTTP_HOST'].'|'.$email), $errstr, $errno);
if(isset($response) && !empty($response)){
$response_r = json_decode($response,TRUE);
}
if (isset($response['status'])) {
if ($response['status'] == 'OK') {
break;
} else if ($response['status'] == 'BLOCK') {
$types_found = 'email';
$block_spam = true;
} else {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], 0, $response);
}
}
}
if ($types_found) {
if ($config['log_check_httpbl'] && $action != 'recheck') {
add_log('block', 0, 0, $row['httpbl_id'], 'LOG_HTTPBL_FOUND', $row['httpbl_fullname'], $types_found, ($row['httpbl_lookup']) ? $row['httpbl_lookup'] . $apiurl : $row['httpbl_website']);
}
if ($block_spam) {
if ($weight > 4 && $action == 'recheck') {
$info['next'][] = array('data' => array($row['httpbl_name'], $row['httpbl_fullname'], ($row['httpbl_lookup']) ? $row['httpbl_lookup'] . $apiurl : $row['httpbl_website'], $types_found), 'report' => ($row['httpbl_use_to_report'] && $row['httpbl_active_to_report']) ? true : false);
$next = true;
}
$weight += $row['httpbl_weight'];
if ($next == false) {
$info['blacklists'][] = array('data' => array($row['httpbl_name'], $row['httpbl_fullname'], ($row['httpbl_lookup']) ? $row['httpbl_lookup'] . $apiurl : $row['httpbl_website'], $types_found), 'report' => ($row['httpbl_use_to_report'] && $row['httpbl_active_to_report']) ? true : false);
}
$sql = 'UPDATE ' . HTTPBL_TABLE . '
SET httpbl_count = httpbl_count + 1
WHERE httpbl_id = ' . $row['httpbl_id'];
$db->sql_query($sql);
}
}
if (($weight > 4 && $block_spam) || $action == 'recheck') {
if ($weight > 4 && $block_spam) {
$info['blocked'] = 'spam';
}
if ($action != 'recheck') {
if ($config['log_check_httpbl']) {
add_log('block', 0, 0, 0, 'LOG_HTTPBL_' . strtoupper($action));
}
return $info;
break;
}
}
}
$db->sql_freeresult($result);
if ($info && $action == 'recheck') {
return $info;
} else {
return false;
}
}
return false;
}
/**
* Check if URI is blacklisted
* */
function check_domainrbl($action = 'recheck', $domains_array)
{
global $db, $config;
if (!is_array($domains_array)) {
$domains_array = array($domains_array);
}
$weight = 0;
$info = array();
if ($domains_array) {
$sql = 'SELECT domainrbl_id, domainrbl_fqdn, domainrbl_lookup, domainrbl_weight FROM ' . DOMAINRBL_TABLE . "
WHERE domainrbl_weight > '0'
ORDER BY domainrbl_weight DESC, domainrbl_count DESC";
$result = $db->sql_query($sql);
while (($row = $db->sql_fetchrow($result)) && ($weight < 5 || $action == 'recheck'))
{
foreach ($domains_array as $domain)
{
if (phpbb_checkdnsrr($domain . '.' . $row['domainrbl_fqdn'] . '.', 'A') === true) {
if ($weight < 5) {
$info['blacklists'][] = array($row['domainrbl_fqdn'], $row['domainrbl_lookup'] . $domain, $domain);
} else if ($weight > 4 && $action == 'recheck') {
$info['next'][] = array($row['domainrbl_fqdn'], $row['domainrbl_lookup'] . $domain, $domain);
}
if ($config['log_check_domainrbl'] && $action != 'recheck') {
add_log('block', 0, $row['domainrbl_id'], 0, 'LOG_DOMAINRBL_FOUND', $row['domainrbl_fqdn'], $domain, $row['domainrbl_lookup'] . $domain);
}
$weight += $row['domainrbl_weight'];
$sql = 'UPDATE ' . DOMAINRBL_TABLE . '
SET domainrbl_count = domainrbl_count + 1
WHERE domainrbl_id = ' . $row['domainrbl_id'];
$db->sql_query($sql);
}
if ($weight > 4 && $action != 'recheck') {
break 2;
}
}
}
$db->sql_freeresult($result);
if ($weight > 4 || $action == 'recheck') {
if ($weight > 4) {
$info['blocked'] = true;
}
if ($action != 'recheck') {
if ($config['log_check_domainrbl']) {
add_log('block', 0, 0, 0, 'LOG_DOMAINRBL_' . strtoupper($action));
}
return $info;
}
}
}
if ($info && $action == 'recheck') {
return $info;
} else {
return false;
}
}
/**
* Check spam ... used to check users and posts for spam
* does not use block log and reporting on recheck!
*/
function check_spam($mode = false, $action = 'recheck', $ip = false, $user_id = 0, $post_id = 0, $data = false, $message = false)
{
global $user, $config, $db, $phpbb_root_path, $phpEx;
$info = $user_data = $post_data = array();
if (!isset($data) || !$data) {
$data = array();
}
$fill_keys = array('user_id', 'user_ip', 'username', 'user_email');
$user_data = array_fill_keys($fill_keys, '');
if ($mode == 'post') {
if ($post_id) {
$sql = 'SELECT poster_id, poster_ip, post_username, post_user_email, post_text, bbcode_bitfield, bbcode_uid FROM ' . POSTS_TABLE . '
WHERE post_id = ' . (int) $post_id;
$result = $db->sql_query($sql);
$post_data = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
} else {
$post_data = $data;
}
if ($post_data['poster_id'] != ANONYMOUS) {
$sql = 'SELECT user_id, user_ip, username, user_email, user_sig, user_sig_bbcode_uid, user_sig_bbcode_bitfield, user_website FROM ' . USERS_TABLE . '
WHERE user_id = ' . (int) $post_data['poster_id'];
$result = $db->sql_query_limit($sql, 1);
$user_data = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
}
$user_data['user_id'] = ($user_data['user_id']) ? $user_data['user_id'] : ((array_key_exists('poster_id', $post_data)) ? $post_data['poster_id'] : '');
$user_data['user_ip'] = ($ip) ? $ip : (($user_data['user_ip']) ? $user_data['user_ip'] : ((array_key_exists('poster_ip', $post_data)) ? $post_data['poster_ip'] : ''));
$user_data['username'] = ($user_data['username']) ? $user_data['username'] : ((array_key_exists('username', $post_data)) ? $post_data['username'] : '');
$user_data['user_email'] = ($user_data['user_email']) ? $user_data['user_email'] : ((array_key_exists('post_user_email', $post_data)) ? $post_data['post_user_email'] : '');
if (empty($message) && $post_data['post_text']) {
if (!function_exists('parse_message')) {
include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
}
$message = new parse_message();
$message->message = &$post_data['post_text'];
$message->bbcode_uid = $post_data['bbcode_uid'];
$message->bbcode_bitfield = $post_data['bbcode_bitfield'];
}
unset($post_data);
} else if ($mode == 'user') {
// used only for recheck
if ($user_id) {
$sql = 'SELECT user_id, user_ip, username, user_email, user_sig, user_sig_bbcode_uid, user_sig_bbcode_bitfield, user_website, user_timezone FROM ' . USERS_TABLE . '
WHERE user_id = ' . (int) $user_id;
$result = $db->sql_query_limit($sql, 1);
$user_data = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
} else {
$user_data['user_ip'] = ($ip) ? $ip : (($user_data['user_ip']) ? $user_data['user_ip'] : ((array_key_exists('user_ip', $data)) ? $data['user_ip'] : ''));
$user_data['username'] = (array_key_exists('username', $data)) ? $data['username'] : ((array_key_exists('username', $data)) ? $data['username'] : '');
$user_data['user_email'] = (array_key_exists('user_email', $data)) ? $data['user_email'] : ((array_key_exists('email', $data)) ? $data['email'] : '');
$user_data['user_timezone'] = (array_key_exists('user_timezone', $data)) ? $data['user_timezone'] : ((array_key_exists('tz', $data)) ? $data['tz'] : '');
$user_data['user_website'] = (array_key_exists('user_website', $data)) ? $data['user_website'] : ((array_key_exists('website', $data)) ? $data['website'] : '');
$user_data['user_sig'] = (array_key_exists('user_sig', $data)) ? $data['user_sig'] : ((array_key_exists('signature', $data)) ? $data['signature'] : '');
}
if (empty($message) && $user_data['user_sig']) {
if (!function_exists('parse_message')) {
include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
}
$message = new parse_message();
$message->message = &$user_data['user_sig'];
$message->bbcode_uid = $user_data['user_sig_bbcode_uid'];
$message->bbcode_bitfield = $user_data['user_sig_bbcode_bitfield'];
}
}
// get the URIs from message or signature
if (isset($message) && $message) {
$data['enable_bbcode'] = (array_key_exists('enable_bbcode', $data)) ? $data['enable_bbcode'] : '';
$data['enable_smilies'] = (array_key_exists('enable_smilies', $data)) ? $data['enable_smilies'] : '';
$data['enable_magic_url'] = (array_key_exists('enable_magic_url', $data)) ? $data['enable_magic_url'] : '';
$bbcode_options = (array_key_exists('user_options', $data)) ? $data['user_options'] : ((($data['enable_bbcode']) ? OPTION_FLAG_BBCODE : 0) +
(($data['enable_smilies']) ? OPTION_FLAG_SMILIES : 0) +
(($data['enable_magic_url']) ? OPTION_FLAG_LINKS : 0));
$message = generate_text_for_display($message->message, $message->bbcode_uid, $message->bbcode_bitfield, $bbcode_options);
$uris_array = array_unique(get_base_domains_from_text($message));
}
// Now let us uncover the bad guys to kill em all! :)
// Like Kaya Yanar says it in Turk-German: Du kommst hier net rein!
$iprbl_array = $httpbl_array = $domainrbl_array = array();
$break = $report_spam = false;
// IPRBL check
// supports only IPv4
if ($user_data['user_ip'] && !preg_match(get_preg_expression('ipv6'), $user_data['user_ip']) && (((($config['check_iprbl_post'] == SPAM_CHECK_ALL || ($config['check_iprbl_post'] == SPAM_CHECK_GUESTS && $user_data['user_id'] == ANONYMOUS)) && $mode == 'post') || ($config['check_iprbl_register'] && $mode == 'user' && $action == 'register')) || $action == 'recheck')) {
if (($iprbl_array = check_iprbl($action, $user_data['user_ip'])) && array_key_exists('blacklists', $iprbl_array)) {
if ($action == 'recheck') {
if (($config['check_iprbl_post'] == SPAM_CHECK_ALL || (($config['check_iprbl_post'] == SPAM_CHECK_GUESTS) && $user_data['user_id'] == ANONYMOUS) && $mode == 'post') || ($config['check_iprbl_register'] && $mode == 'user')) {
if (array_key_exists('blocked', $iprbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_IPRBL'];
} else {
$info[] = $user->lang['RECHECK_SPAM_IPRBL_NOT'];
}
} else {
$info[] = $user->lang['RECHECK_SPAM_IPRBL_NO'];
}
foreach ($iprbl_array['blacklists'] as $iprbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_IPRBL_IP'], $iprbl[0], $iprbl[1]);
}
if ($config['break_after_iprbl'] && array_key_exists('blocked', $iprbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_BREAK'];
$break = true;
} else {
$info[] = '<br />';
}
if (array_key_exists('next', $iprbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_IPRBL_NEXT'];
foreach ($iprbl_array['next'] as $iprbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_IPRBL_IP'], $iprbl[0], $iprbl[1]);
}
$info[] = '<br />';
}
} else {
$report_spam = true;
foreach ($iprbl_array['blacklists'] as $iprbl)
{
$info[] = sprintf($user->lang['IP_BLACKLISTED'], $user_data['user_ip'], $iprbl[1]);
}
}
}
}
// HTTPBL check
if (($user_data['user_ip'] || $user_data['username'] || $user_data['user_email'] || $message) && (((((($config['check_httpbl_register'] && $action == 'register') || ($config['check_httpbl_profile'] && $action == 'profile')) && $mode == 'user') || ((($config['check_httpbl_post'] == SPAM_CHECK_ALL) || ($config['check_httpbl_post'] == SPAM_CHECK_GUESTS && $user_data['user_id'] == ANONYMOUS)) && $mode == 'post')) && ($config['break_after_iprbl'] && $info) == false) || $action == 'recheck')) {
if (($httpbl_array = check_httpbl($action, $user_data['user_ip'], $user_data['username'], $user_data['user_email'], $message)) && array_key_exists('blacklists', $httpbl_array)) {
if ($action == 'recheck') {
if (($config['check_httpbl_register'] && $mode == 'user') || (($config['check_httpbl_post'] == SPAM_CHECK_ALL || (($config['check_httpbl_post'] == SPAM_CHECK_GUESTS) && $user_data['user_id'] == ANONYMOUS) && $mode == 'post'))) {
if (array_key_exists('blocked', $httpbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_HTTPBL'];
} else {
$info[] = $user->lang['RECHECK_SPAM_HTTPBL_NOT'];
}
} else {
$info[] = $user->lang['RECHECK_SPAM_HTTPBL_NO'];
}
foreach ($httpbl_array['blacklists'] as $httpbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_HTTPBL_DATA'], $httpbl['data'][1], $httpbl['data'][2], $httpbl['data'][3]);
}
if ($config['break_after_httpbl'] && array_key_exists('blocked', $httpbl_array) && $break == false) {
$info[] = $user->lang['RECHECK_SPAM_BREAK'];
} else {
$info[] = '<br />';
}
if (array_key_exists('next', $httpbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_HTTPBL_NEXT'];
foreach ($httpbl_array['next'] as $httpbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_HTTPBL_DATA'], $httpbl['data'][1], $httpbl['data'][2], $httpbl['data'][3]);
}
$info[] = '<br />';
}
} else {
foreach ($httpbl_array['blacklists'] as $httpbl)
{
if ($httpbl['report'] == 'spam') {
$report_spam = true;
}
$info[] = sprintf($user->lang['HTTPBL_BLACKLISTED'], ($user_data['user_ip']) ? $user_data['user_ip'] : $user->lang['NA'], ($user_data['username']) ? $user_data['username'] : $user->lang['NA'], ($user_data['user_email']) ? $user_data['user_email'] : $user->lang['NA'], $httpbl['data'][2]);
}
}
}
}
// Domain-RBL check for user_email
if ($user_data['user_email'] && ((((($config['check_domainrbl_email'] == SPAM_CHECK_ALL || $config['check_domainrbl_email'] == SPAM_CHECK_GUESTS) && $mode == 'user') || ($user_data['user_id'] == ANONYMOUS && $mode == 'post')) && ($config['break_after_httpbl'] && $info) == false) || $action == 'recheck')) {
$email_domainrbl_array = $email_uris_array = array();
list(, $uri) = explode('@', $user_data['user_email']);
$email_uris_array[] = get_base_domain($uri, true);
if (($email_domainrbl_array = check_domainrbl($action . '_email', $email_uris_array)) && array_key_exists('blacklists', $email_domainrbl_array)) {
if ($action == 'recheck') {
if ($config['check_domainrbl_email'] == SPAM_CHECK_ALL || $config['check_domainrbl_email'] == SPAM_CHECK_GUESTS) {
if (array_key_exists('blocked', $email_domainrbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_EMAIL'];
} else {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_EMAIL_NOT'];
}
} else {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_EMAIL_NO'];
}
foreach ($email_domainrbl_array['blacklists'] as $domainrbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_DOMAINRBL_EMAIL_URI'], $domainrbl[2], $domainrbl[0], $domainrbl[1]);
}
if (array_key_exists('next', $email_domainrbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_EMAIL_NEXT'];
foreach ($email_domainrbl_array['next'] as $domainrbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_DOMAINRBL_EMAIL_URI'], $domainrbl[2], $domainrbl[0], $domainrbl[1]);
}
}
} else {
$report_spam = true;
foreach ($email_domainrbl_array['blacklists'] as $domainrbl)
{
$info[] = sprintf($user->lang['EMAIL_DOMAIN_BLACKLISTED'], $domainrbl[2], $domainrbl[1]);
}
}
}
}
if ($user_data['user_email'] && ($config['email_check_mx'] || $action == 'recheck')) {
list(, $domain) = explode('@', $user_data['user_email']);
if (phpbb_checkdnsrr($domain, 'A') === false && phpbb_checkdnsrr($domain, 'MX') === false) {
if ($config['log_email_check_mx']) {
add_log('block', 0, 0, 0, 'LOG_DNSMX', $domain);
}
if ($action == 'recheck') {
$info[] = sprintf($user->lang['RECHECK_SPAM_DNSMX'], $domain);
} else {
// do not report human failures!
// $report_spam = true;
$info[] = $user->lang['DOMAIN_NO_MX_RECORD_EMAIL'];
}
}
}
if ($mode == 'user') {
// anti spam check for the former UTC -12 trick
if ($config['check_tz']) {
if ((float) $user_data['user_timezone'] == -19 || (float) $user_data['user_timezone'] == 19) {
if ($config['log_check_tz']) {
add_log('block', 0, 0, 0, 'LOG_WRONG_TZ', (float) $user_data['user_timezone']);
}
// do not report human failures or funny human!
// $report_spam = true;
$info[] = $user->lang['WRONG_TIMEZONE'];
}
}
// Domain-RBL check for user_website
if ($user_data['user_website'] && (($config['check_domainrbl_website'] && ($config['break_after_httpbl'] && $info) == false) || $action == 'recheck')) {
$domainrbl_array = $uris_array = array();
// do not use the large function, it's only one complete hyperlink URL
$uris_array = get_base_domain(parse_url($user_data['user_website'], PHP_URL_HOST), true);
if (($domainrbl_array = check_domainrbl($action . '_website', $uris_array)) && array_key_exists('blacklists', $domainrbl_array)) {
if ($action == 'recheck') {
if ($config['check_domainrbl_website']) {
if (array_key_exists('blocked', $domainrbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_WEBSITE'];
} else {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_WEBSITE_NOT'];
}
} else {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_WEBSITE_NO'];
}
foreach ($domainrbl_array['blacklists'] as $domainrbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_DOMAINRBL_WEBSITE_URI'], $domainrbl[2], $domainrbl[0], $domainrbl[1]);
}
if (array_key_exists('next', $domainrbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_WEBSITE_NEXT'];
foreach ($domainrbl_array['next'] as $domainrbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_DOMAINRBL_WEBSITE_URI'], $domainrbl[2], $domainrbl[0], $domainrbl[1]);
}
}
} else {
$report_spam = true;
foreach ($domainrbl_array['blacklists'] as $domainrbl)
{
$info[] = sprintf($user->lang['WEBSITE_BLACKLISTED'], $domainrbl[2], $domainrbl[1]);
}
}
}
}
// Domain-RBL check for signature
if (isset($uris_array) && $uris_array && (($config['check_domainrbl_signature'] && ($config['break_after_httpbl'] && $info) == false) || $action == 'recheck')) {
if (($domainrbl_array = check_domainrbl($action . '_signature', $uris_array)) && array_key_exists('blacklists', $domainrbl_array)) {
if ($action == 'recheck') {
if ($config['check_domainrbl_signature']) {
if (array_key_exists('blocked', $domainrbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_SIGNATURE'];
} else {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_SIGNATURE_NOT'];
}
} else {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_SIGNATURE_NO'];
}
foreach ($domainrbl_array['blacklists'] as $domainrbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_DOMAINRBL_SIGNATURE_URI'], $domainrbl[2], $domainrbl[0], $domainrbl[1]);
}
if (array_key_exists('next', $domainrbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_SIGNATURE_NEXT'];
foreach ($domainrbl_array['next'] as $domainrbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_DOMAINRBL_SIGNATURE_URI'], $domainrbl[2], $domainrbl[0], $domainrbl[1]);
}
}
} else {
$report_spam = true;
foreach ($domainrbl_array['blacklists'] as $domainrbl)
{
$info[] = sprintf($user->lang['SIGNATURE_BLACKLISTED'], $domainrbl[2], $domainrbl[1]);
}
}
}
}
}
if ($mode == 'post') {
// Domain-RBL check for URIs
if (isset($uris_array) && $uris_array && (((($config['check_domainrbl_post'] == SPAM_CHECK_ALL) || ($config['check_domainrbl_post'] == SPAM_CHECK_GUESTS && $user_data['user_id'] == ANONYMOUS)) && ($config['break_after_httpbl'] && $info) == false) || $action == 'recheck')) {
if (($domainrbl_array = check_domainrbl($action, $uris_array)) && array_key_exists('blacklists', $domainrbl_array)) {
if ($action == 'recheck') {
if ($config['check_domainrbl_post'] == SPAM_CHECK_ALL || (($config['check_domainrbl_post'] == SPAM_CHECK_GUESTS))) {
if (array_key_exists('blocked', $domainrbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_POST'];
} else {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_POST_NOT'];
}
} else {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_POST_NO'];
}
foreach ($domainrbl_array['blacklists'] as $domainrbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_DOMAINRBL_POST_URI'], $domainrbl[2], $domainrbl[0], $domainrbl[1]);
}
if (array_key_exists('next', $domainrbl_array)) {
$info[] = $user->lang['RECHECK_SPAM_DOMAINRBL_POST_NEXT'];
foreach ($domainrbl_array['next'] as $domainrbl)
{
$info[] = sprintf($user->lang['RECHECK_SPAM_DOMAINRBL_POST_URI'], $domainrbl[2], $domainrbl[0], $domainrbl[1]);
}
}
} else {
$report_spam = true;
foreach ($domainrbl_array['blacklists'] as $domainrbl)
{
$info[] = sprintf($user->lang['DOMAIN_BLACKLISTED'], $domainrbl[2], $domainrbl[1]);
}
}
}
}
}
if (!sizeof($info) && $action == 'recheck') {
$info[] = $user->lang['RECHECK_SPAM_NO'];
}
if (sizeof($info) && $action !== 'recheck') {
$info[] = $user->lang['BLACKLISTED_INFO'];
}
// support for Contact Board Administration MOD http://www.phpbb.com/customise/db/mod/contact_board_administration/
if (array_key_exists('contact_enable', $config) && $config['contact_enable'] && sizeof($info) && $info && $action != 'recheck') {
$info[] = sprintf($user->lang['CONTACT_BLACKLISTED'], $phpbb_root_path . 'contact.' . $phpEx);
}
if ($action == 'recheck') {
return implode(' ', $info);
} else {
if ($config['report_httpbl'] && $report_spam) {
report_httpbl($action, $user_data['user_ip'], $user_data['username'], $user_data['user_email'], $message);
}
return $info;
}
}
/**
* Report spam to HTTP Blacklists
* */
function report_httpbl($action = false, $ip = false, $username = false, $email = false, $message = false)
{
global $db, $config;
// for future use if other databases will need it
$quads = explode('.', $ip);
$reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
$sql = 'SELECT * FROM ' . HTTPBL_TABLE . "
WHERE httpbl_weight > '0'
ORDER BY httpbl_weight DESC, httpbl_count DESC";
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
// Stop Forum Spam
// requires ip, username and email - does not support IPv6
if (($row['httpbl_name'] == 'sfs') && $row['httpbl_key'] && $ip && !preg_match(get_preg_expression('ipv6'), $ip) && $username && $email && $row['httpbl_use_for_report'] && $row['httpbl_active_for_report']) {
$apiurl = 'username=';
if ($username && $row['httpbl_use_username'] && $row['httpbl_check_username']) {
$apiurl .= $username;
}
$apiurl .= '&ip_addr=';
if ($ip && $row['httpbl_use_ip'] && $row['httpbl_check_ip']) {
$apiurl .= $ip;
}
$apiurl .= '&email=';
if ($email && $row['httpbl_use_email'] && $row['httpbl_check_email']) {
$apiurl .= $email;
}
$apiurl .= '&api_key=' . $row['httpbl_key'];
$file = post_remote_file('www.stopforumspam.com', '/add.php', $apiurl, $errstr, $errno);
if ($errstr) {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], $errno, $errstr);
} else {
add_log('block', 0, 0, $row['httpbl_id'], 'LOG_HTTPBL_REPORTED_' . strtoupper($action), $row['httpbl_fullname'], $username, $ip, $email, $row['httpbl_lookup'] . '/api?ip=' . $ip . '&username=' . $username . '&email=' . $email);
}
}
// Akismet
// based on http://akismet.com/development/api
// a key always is needed
else if ($row['httpbl_name'] == 'akismet' && $row['httpbl_key']) {
global $phpbb_root_path, $phpEx, $user;
$server_url = generate_board_url();
$apiurl = 'key=' . $row['httpbl_key'] . '&blog=' . urlencode($server_url . '/index.' . $phpEx);
$file = post_remote_file('rest.akismet.com', '/1.1/verify-key', $apiurl, $errstr, $errno);
if ($file[1] != 'valid') {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], $errno, $errstr . $file[0]);
}
$apiurl = '';
if (!$ip) {
$ip = $user->ip;
}
$apiurl = 'user_ip=' . urlencode($ip) . '&user_agent=' . urlencode($user->browser) . '&referrer=' . urlencode($user->referer) . '&blog=' . urlencode($server_url . '/index.' . $phpEx) . '&comment_type=forum';
if ($username && $row['httpbl_use_username'] && $row['httpbl_check_username']) {
$apiurl .= '&comment_author=' . urlencode($username);
}
if ($email && $row['httpbl_use_email'] && $row['httpbl_check_email']) {
$apiurl .= '&comment_author_email=' . urlencode($email);
}
if ($email && $row['httpbl_use_message'] && $row['httpbl_check_message']) {
$apiurl .= '&comment_content=' . urlencode($message);
}
$file = post_remote_file($row['httpbl_key'] . '.rest.akismet.com', '/1.1/submit-spam', $apiurl, $errstr, $errno);
if ($errstr) {
add_log('critical', 'LOG_ERROR_HTTPBL', $row['httpbl_fullname'], $errno, $errstr . $file[0]);
} else {
add_log('block', 0, 0, $row['httpbl_id'], 'LOG_HTTPBL_REPORTED_' . strtoupper($action), $row['httpbl_fullname'], $username, $ip, $email, $row['httpbl_website']);
}
}
}
$db->sql_freeresult($result);
}
/**
* Retrieve contents from remotely written file
* based on http://akismet.com/development/api and phpBB3 core function get_remote_file
* */
function post_remote_file($host, $directory, $filename, &$errstr, &$errno, $port = 80, $timeout = 10)
{
global $user, $phpEx;
$server_url = generate_board_url();
if ($fsock = @fsockopen($host, $port, $errno, $errstr, $timeout)) {
@fwrite($fsock, "POST $directory HTTP/1.0\r\n");
@fwrite($fsock, "HOST: $host\r\n");
@fwrite($fsock, "Content-Type: application/x-www-form-urlencoded\r\n");
@fwrite($fsock, "User-Agent: phpBB/3.0 | Advanced Block MOD/1.1\r\n");
@fwrite($fsock, "Content-Length: " . strlen($filename) . "\r\n\r\n");
@fwrite($fsock, $filename . "\r\n");
$file_info = '';
while (!@feof($fsock))
{
$file_info .= @fgets($fsock, 1160);
}
@fclose($fsock);
$file_info = explode("\r\n\r\n", $file_info, 2);
return $file_info;
} else {
if ($errstr) {
$errstr = utf8_convert_message($errstr);
return false;
} else {
$errstr = $user->lang['FSOCK_DISABLED'];
return false;
}
}
}
/**
* get base domain (domain.tld)
* based on http://phosphorusandlime.blogspot.com/2007/08/php-get-base-domain.html
* */
function get_base_domain($full_domain = '', $reverse_ip = true)
{
$base_domain = '';
// generic tlds (source: http://en.wikipedia.org/wiki/Generic_top-level_domain)
$generic_tlds = array(
'biz', 'com', 'edu', 'gov', 'info', 'int', 'mil', 'name', 'net', 'org',
'aero', 'asia', 'cat', 'coop', 'jobs', 'mobi', 'museum', 'pro', 'tel', 'travel',
'arpa', 'root',
'berlin', 'bzh', 'cym', 'gal', 'geo', 'kid', 'kids', 'lat', 'mail', 'nyc', 'post', 'sco', 'web', 'xxx',
'nato',
'example', 'invalid', 'localhost', 'test',
'bitnet', 'csnet', 'ip', 'local', 'onion', 'uucp',
'co' // note: not technically, but used in things like co.uk
);
// country tlds (source: http://en.wikipedia.org/wiki/Country_code_top-level_domain)
$country_tlds = array(
// active
'ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'an', 'ao', 'aq', 'ar', 'as', 'at', 'au', 'aw', 'ax', 'az',
'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bw', 'by', 'bz',
'ca', 'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr', 'cu', 'cv', 'cx', 'cy', 'cz',
'de', 'dj', 'dk', 'dm', 'do', 'dz', 'ec', 'ee', 'eg', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo',
'fr', 'ga', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp', 'gq', 'gr', 'gs', 'gt', 'gu', 'gw',
'gy', 'hk', 'hm', 'hn', 'hr', 'ht', 'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je',
'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kr', 'kw', 'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk',
'lr', 'ls', 'lt', 'lu', 'lv', 'ly', 'ma', 'mc', 'md', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo', 'mp', 'mq',
'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na', 'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np',
'nr', 'nu', 'nz', 'om', 'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pn', 'pr', 'ps', 'pt', 'pw', 'py', 'qa',
're', 'ro', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd', 'se', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'sr', 'st',
'sv', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw',
'tz', 'ua', 'ug', 'uk', 'us', 'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye', 'yu',
'za', 'zm', 'zw',
// inactive
'eh', 'kp', 'me', 'rs', 'um', 'bv', 'gb', 'pm', 'sj', 'so', 'yt', 'su', 'tp', 'bu', 'cs', 'dd', 'zr'
);
// break up domain, reverse
$domain = explode('.', $full_domain);
$domain = array_reverse($domain);
// first check for ip address
// domain-rbl check needs reverse octects
if (sizeof($domain) == 4 && is_numeric($domain[0]) && is_numeric($domain[3])) {
if ($reverse_ip) {
return $domain[0] . '.' . $domain[1] . '.' . $domain[2] . '.' . $domain[3];
} else {
return $full_domain;
}
}
// if only 2 domain parts, that must be our domain
if (sizeof($domain) <= 2) {
return $full_domain;
}
/*
finally, with 3+ domain parts: obviously D0 is tld
now, if D0 = ctld and D1 = gtld, we might have something like com.uk
so, if D0 = ctld && D1 = gtld && D2 != 'www', domain = D2.D1.D0
else if D0 = ctld && D1 = gtld && D2 == 'www', domain = D1.D0
else domain = D1.D0
these rules are simplified below
*/
if (in_array($domain[0], $country_tlds) && in_array($domain[1], $generic_tlds) && $domain[2] != 'www') {
$full_domain = $domain[2] . '.' . $domain[1] . '.' . $domain[0];
} else {
$full_domain = $domain[1] . '.' . $domain[0];
;
}
// did we succeed?
return $full_domain;
}
/**
* get base domains from text
* text needs to be parsed by generate_text_for_display before
* */
function get_base_domains_from_text($message = '')
{
global $user;
$post_uris_array = array();
//remove phpBB tags to simplyfy the string
$search = array(" class=\"postlink\"", " class=\"postlink-local\"", " alt=\"" . $user->lang['IMAGE'] . "\"");
$replacement = array("", "", "");
$message = str_replace($search, $replacement, $message);
// get the URLs
// decode HTML special chars
$message = htmlspecialchars_decode($message);
//extract the urls from HTML a tags
$message = preg_replace('#<a href="((https?://|mailto:)[^"]+)">(.*?)</a>#', ' \\1 ', $message);
// extract the urls from HTML img tags
$message = preg_replace('#<img src="(https?://[^"]+)" />#', ' \\1 ', $message);
// build array of URLs from text
$urls_array = preg_split('#(https?://\S+(?<![,.]))#', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
// filter URLs from array
$urls_array = preg_grep('#(https?://\S+(?<![,.]))#', $urls_array);
// filter empty entries from array
$urls_array = array_filter($urls_array);
// get the URIs (domain names)
foreach ($urls_array as $url)
{
// extract host (FQDN) and and get base domain
$post_uris_array[] = get_base_domain(parse_url($url, PHP_URL_HOST), true);
}
// remove double entries from array
$post_uris_array = array_unique($post_uris_array);
return $post_uris_array;
}
?> | gpl-2.0 |
rivimey/urg | modules/shopify/src/Plugin/Field/FieldFormatter/ShopifyWeightFormatter.php | 1399 | <?php
/**
* @file
*/
namespace Drupal\shopify\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\NumericFormatterBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the Shopify weight formatter.
*
* @FieldFormatter(
* id = "shopify_weight",
* label = @Translation("Shopify Weight"),
* field_types = {
* "decimal",
* }
* )
*/
class ShopifyWeightFormatter extends NumericFormatterBase {
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
return [];
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$entity = $item->getEntity();
$output = $this->numberFormat($item->value, $entity->weight_unit->value);
$elements[$delta] = ['#markup' => $output];
}
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary[] = 'Format: {{weight}}{{weight_unit}}';
$summary[] = 'Preview: ' . $this->numberFormat(1234.1234567890, 'lb');
return $summary;
}
/**
* {@inheritdoc}
*/
public function numberFormat($number, $format = '') {
$number = number_format($number, 2);
return $number . $format;
}
}
| gpl-2.0 |
flipchan/Nohidy | automation/log_to_ftp.py | 481 | #!/usr/bin/python
#auto upload logfiles to ftp server
import ftplib
import os
from datetime import date
import time
ip = ''
logfile = ''
user = ''
password = ''
logfile = ''
ftpdir = ''
localdir = ''
while 1:
filename = logfile
ftp = ftplib.FTP(ip)
ftp.login(user, password)
today = date.today()
filename = str(today) + filename
ftp.cwd(ftpdir)
os.chdir(localdir)
myfile = open(filename, 'r')
ftp.storlines('STOR ' + filename, myfile)
myfile.close()
time.sleep(86000)
| gpl-2.0 |
iwtwiioi/OnlineJudge | wikioi/Run_277080_Score_100_Date_2013-10-09.cpp | 612 | #include <iostream>
#include <algorithm>
using namespace std;
#define FOR(i,j) for(i=1;i<=(j);i++)
const int MAXN = 60, MAXM = 60;
int n, m, map[MAXN][MAXM], f[MAXN][MAXM][MAXN][MAXM];
int main()
{
int i1, i2, j1, j2;
cin >> n >> m;
FOR(i1,n) FOR(j1,m) cin >> map[i1][j1];
FOR(i1,n) FOR(j1,m) FOR(i2,n) FOR(j2,m)
if((i1!=i2&&j1!=j2) || (i1==n&&j1==m&&i1==i2&&j1==j2))
f[i1][j1][i2][j2] = map[i1][j1] + map[i2][j2] +
max(max(max(f[i1-1][j1][i2-1][j2], f[i1-1][j1][i2][j2-1]),
f[i1][j1-1][i2-1][j2]),f[i1][j1-1][i2][j2-1]);
cout << f[n][m][n][m] << endl;
return 0;
}
| gpl-2.0 |
kunj1988/Magento2 | app/code/Magento/Checkout/Model/Cart/RequestInfoFilterComposite.php | 947 | <?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Checkout\Model\Cart;
/**
* Class RequestInfoFilterComposite
* @api
* @since 100.1.2
*/
class RequestInfoFilterComposite implements RequestInfoFilterInterface
{
/**
* @var RequestInfoFilter[] $params
*/
private $filters = [];
/**
* @param RequestInfoFilter[] $filters
* @since 100.1.2
*/
public function __construct(
$filters = []
) {
$this->filters = $filters;
}
/**
* Loops through all leafs of the composite and calls filter method
*
* @param \Magento\Framework\DataObject $params
* @return $this
* @since 100.1.2
*/
public function filter(\Magento\Framework\DataObject $params)
{
foreach ($this->filters as $filter) {
$filter->filter($params);
}
return $this;
}
}
| gpl-2.0 |
mideveloper/circulate | lib/ios.js | 11179 | var _ = require("lodash"),
Promise = require("bluebird"),
Apn = require("apn"),
Epoch = require("./epoch"), //will be replace with oyster-utils
CacheObj = require("ephemeral").initialize({
client: "local"
}),
client = "ios";
/**
*
* Process notification object internally and remove the data from cache object
* reset the not_payload object in notification object then send back to caller
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param notification
* @returns {Promise}
* @version 0.1
*/
function processNotification(notification) {
return new Promise(function(resolve) {
if(notification && notification.intl) {
CacheObj.get(notification.intl).then(function(not_payload) {
if(not_payload) {
CacheObj.remove(notification.intl);
notification.not_payload = not_payload;
}
return resolve(notification);
});
}
else {
return resolve(notification);
}
});
}
/**
*
* onTransmitted event
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onTransmitted(ctx, notification, recipient) {
return processNotification(notification).then(function(notificationObj) {
ctx.onTransmitted(client, notificationObj, recipient);
});
}
/**
*
* onTransmissionError event
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onTransmissionError(ctx, errorCode, notification, recipient) {
return processNotification(notification).then(function(notificationObj) {
ctx.onTransmissionError(client, errorCode, notificationObj, recipient);
});
}
/**
*
* onConnected event
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onConnected(ctx, openSockets) {
ctx.OnConnected(client, openSockets);
}
/**
*
* onError event
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onError(ctx, error) {
ctx.OnError(error);
}
/**
*
* onDrain event
* connection will be re-initilize whenever onDrain event fire from apple push notification server.
* trick to stay alive always :)
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onDrain(ctx) {
//Re-initializing,
ctx.apn_connection = undefined;
ctx.OnDrain(client);
}
/**
*
* onTimeOut event
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onTimeOut(ctx) {
ctx.OnTimeOut(client);
}
/**
*
* onDisconnected event
* connection will be re-initilize whenever onDrain event fire from apple push notification server.
* trick to stay alive always :)
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onDisconnected(ctx, openSockets) {
//Re-initializing,
ctx.apn_connection = undefined;
ctx.OnDisconnected(client, openSockets);
}
/**
*
* onSocketError event
* connection will be re-initilize whenever onDrain event fire from apple push notification server.
* trick to stay alive always :)
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onSocketError(ctx, socketError) {
//Re-initializing,
ctx.apn_connection = undefined;
ctx.OnSocketError(client, socketError);
}
/**
*
* onFeedback event
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function onFeedback(ctx, devices) {
ctx.onFeedback(client, devices);
}
/**
*
* initialize and attach the apn feedBack event with context (ctx)
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
var initApnFeedback = function initApnFeedback(ctx, options) {
ctx.apnFeedback = new Apn.Feedback(options);
ctx.apnFeedback.on("feedback", function(devices) {
onFeedback(ctx, devices);
});
};
/**
*
* initialize and attach the apn with context (ctx)
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
var initApnSend = function initApnSend(ctx) {
//if apn connection is undefined (on the very first connect or may be drain or disconnect
if (!ctx.apn_connection) {
var options = {
"key": ctx.apn.key,
"cert": ctx.apn.cert,
"interval": 43200,
"batchFeedback": true,
"production": ctx.apn.sandbox,
"passphrase": ctx.apn.pass_phrase
};
ctx.apn_connection = new Apn.Connection(options);
ctx.apn_connection.on("transmissionError", function(errorCode, notification, recipient) {
onTransmissionError(ctx, errorCode, notification, recipient);
});
ctx.apn_connection.on("transmitted", function(notification, recipient) {
onTransmitted(ctx, notification, recipient);
});
ctx.apn_connection.on("connected", function(openSockets) {
onConnected(ctx, openSockets);
});
ctx.apn_connection.on("error", function(error) {
onError(ctx, error);
});
ctx.apn_connection.on("drain", function() {
onDrain(ctx);
});
ctx.apn_connection.on("timeout", function() {
onTimeOut(ctx);
});
ctx.apn_connection.on("disconnected", function(openSockets) {
onDisconnected(ctx, openSockets);
});
ctx.apn_connection.on("socketError", function(socketError) {
onSocketError(ctx, socketError);
});
delete options.gateway;
initApnFeedback(ctx, options);
}
return ctx.apn_connection;
};
/**
*
* create notification payload based on provided on options
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function buildPayload(options) {
var payload = new Apn.Notification(options.payload);
payload.expiry = options.expiry || 0;
if (options.alert) { //
payload.alert = options.alert;
}
else{
payload.payload = {};
payload.payload.smsg = options.data.message;
}
if (options.badge >= 0) {
payload.badge = options.badge;
}
if (options.sound) {
payload.sound = options.sound;
}
if (options.image) {
payload["launch-image"] = options.image;
}
if (options.sqsmessage) {
payload.sqsmessage = options.sqsmessage;
}
if (options.intl) {
payload.intl = options.intl;
}
if (options.data) {
if(payload.payload) {
payload.payload.event_type = options.data.event_type;
}
else {
payload.payload = {
event_type: options.data.event_type
};
}
if (options.data.identifier) {
payload.payload.identifier = options.data.identifier;
}
if(options.data.extras && _.size(options.data.extras) > 0) {
for(var key in options.data.extras) {
payload.payload[key] = options.data.extras[key];
}
}
}
payload["content-available"] = 1;
payload["contentAvailable"] = 1;
return payload;
}
/**
*
* send the notificaiton payload with token to apn
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function push(ctx, tokens, payload) {
var sender = initApnSend(ctx);
sender.pushNotification(payload, tokens);
}
/**
*
* construction with certificate path
*
* @author Faiz <faizulhaque@tenpearls.com>
* @param ctx
* @param notification
* @param recipient
* @returns {*}
* @version 0.1
*/
function Ios(key, cert, pass_phrase, sandbox) {
this.apn = {
key: key,
cert: cert,
pass_phrase: pass_phrase,
sandbox: sandbox
};
}
/************************Exposed function of library************************/
Ios.prototype.send = function(devices, data, is_silent) {
var self = this;
var _message = data.message || null,
_soundFile = data.sound_file || "beep.wav",
_iconFile = data.icon_file || null,
_data = data;
var iosDevices = _.filter(devices, function(device) {
if (device.platform && (device.platform.toLowerCase() === "iphone" || device.platform.toLowerCase() === "ios" || device.platform.toLowerCase() === "apple") && _.size(device.push_token) > 0) {
return true;
}
else {
return false;
}
});
// Need to take unique set as push_token persists across install/uninstalled but device ID changes
var iosTokens = _.unique(_.pluck(iosDevices, "push_token"));
//we are only to push if there are valid devices
if (iosTokens.length > 0) {
//registering one callback per Notification ID
var options = {
alert: (!is_silent) ? _message : null,
sound: (!is_silent) ? _soundFile : null,
badge: _data.badge >= 0 ? _data.badge : null, // badger may have zero (0) value
image: _iconFile,
data: _data
};
//not_payload is object which will be return on events.
if(data.not_payload) {
options.intl = Epoch.now();
CacheObj.set(options.intl, data.not_payload);
}
var notificationPayload = buildPayload(options);
push(self, iosTokens, notificationPayload);
//global.Trace.write(data.to_id, "push sent to user", notificationPayload, null);
return;
}
return;
};
Ios.prototype.onFeedback = function onFeedback() {}; //for lintFix, in params: devices
Ios.prototype.onTransmitted = function onTransmitted() {}; //for lintFix, in params: notification, recipient
Ios.prototype.onTransmissionError = function onTransmissionError() {}; //for lintFix, in params: errorCode, notification, recipient
Ios.prototype.OnConnected = function OnConnected() {}; //for lintFix, in params: openSockets
Ios.prototype.OnError = function OnError() {}; //for lintFix, in params: error
Ios.prototype.OnDrain = function OnDrain() {};
Ios.prototype.OnTimeOut = function OnTimeOut() {};
Ios.prototype.OnDisconnected = function OnDisconnected() {}; //for lintFix, in params: openSockets
Ios.prototype.OnSocketError = function OnSocketError() {}; //for lintFix, in params: socketError
/************************Exposed function of library************************/
module.exports = Ios; | gpl-2.0 |
learning-2016/wordpress-custom-dev | wp-content/themes/abaris/includes/enqueue.php | 2212 | <?php
/**
* Enqueue scripts and styles.
*/
function abaris_scripts() {
wp_enqueue_style( 'abaris-font-roboto', '//fonts.googleapis.com/css?family=Roboto:400,300,700');
wp_enqueue_style( 'abaris-font-bree-serif', '//fonts.googleapis.com/css?family=Bree+Serif');
wp_enqueue_style( 'abaris-bootstrap', ABARIS_PARENT_URL . '/css/bootstrap.css' );
wp_enqueue_style( 'abaris-bootstrap-responsive', ABARIS_PARENT_URL . '/css/bootstrap-responsive.css' );
wp_enqueue_style( 'abaris-elusive', ABARIS_PARENT_URL . '/css/elusive-icons.css' );
wp_enqueue_style( 'abaris-flexslider', ABARIS_PARENT_URL . '/css/flexslider.css' );
wp_enqueue_style( 'abaris-slicknav', ABARIS_PARENT_URL . '/css/slicknav.css' );
wp_enqueue_style( 'abaris-style', get_stylesheet_uri() );
wp_enqueue_style( 'abaris-jigoshop', ABARIS_PARENT_URL . '/css/jigoshop.css' );
wp_enqueue_script( 'abaris-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true );
wp_enqueue_script( 'abaris-flexsliderjs', ABARIS_PARENT_URL . '/js/jquery.flexslider-min.js', array('jquery'), '2.2.2', true );
wp_enqueue_script( 'abaris-slicknavjs', ABARIS_PARENT_URL . '/js/jquery.slicknav.min.js', array('jquery'), '1.0', true );
wp_enqueue_script( 'abaris-waypoints', ABARIS_PARENT_URL . '/js/waypoints.min.js', array('jquery'), '2.0.4', true );
wp_enqueue_script( 'abaris-waypointsticky', ABARIS_PARENT_URL . '/js/waypoints-sticky.min.js', array('jquery'), '2.0.4', true );
wp_enqueue_script( 'abaris-custom', ABARIS_PARENT_URL . '/js/custom.js', array('jquery'), '1.0', true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
global $abaris;
if( isset($abaris['animate']) && $abaris['animate']) {
wp_enqueue_style( 'abaris-animate', ABARIS_PARENT_URL . '/css/animated.css' );
wp_enqueue_script( 'abaris-animatejs', ABARIS_PARENT_URL . '/js/animate.js', array('jquery'), '1.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'abaris_scripts' );
function abaris_admin_style() {
wp_enqueue_style( 'abaris-admin', ABARIS_PARENT_URL . '/css/admin.css' );
}
add_action( 'admin_enqueue_scripts', 'abaris_admin_style' );
| gpl-2.0 |
Tsilopoulos/File-Manager | File-Manager/src/main/java/pm/filemanager/controllers/UndoController.java | 668 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pm.filemanager.controllers;
import pm.filemanager.model.LocalStorage;
import java.io.IOException;
import pm.filemanager.commands.ICommand;
/**
*
* @author PTsilopoulos
*/
public class UndoController {
public void undo() throws NullPointerException {
try {
ICommand command = LocalStorage.popUndo();
command.undo();
} catch(IOException e) {
//TO-DO add logger
}
}
}
| gpl-2.0 |
saiful76/pazpar2 | js/pz2.js | 36410 | /*
* Mine
** pz2.js - pazpar2's javascript client library.
*/
//since explorer is flawed
if (!window['Node']) {
window.Node = new Object();
Node.ELEMENT_NODE = 1;
Node.ATTRIBUTE_NODE = 2;
Node.TEXT_NODE = 3;
Node.CDATA_SECTION_NODE = 4;
Node.ENTITY_REFERENCE_NODE = 5;
Node.ENTITY_NODE = 6;
Node.PROCESSING_INSTRUCTION_NODE = 7;
Node.COMMENT_NODE = 8;
Node.DOCUMENT_NODE = 9;
Node.DOCUMENT_TYPE_NODE = 10;
Node.DOCUMENT_FRAGMENT_NODE = 11;
Node.NOTATION_NODE = 12;
}
// prevent execution of more than once
if(typeof window.pz2 == "undefined") {
window.undefined = window.undefined;
var pz2 = function ( paramArray )
{
// at least one callback required
if ( !paramArray )
throw new Error("Pz2.js: Array with parameters has to be suplied.");
//supported pazpar2's protocol version
this.suppProtoVer = '1';
if (typeof paramArray.pazpar2path != "undefined")
this.pz2String = paramArray.pazpar2path;
else
this.pz2String = "/pazpar2/search.pz2";
this.useSessions = true;
this.stylesheet = paramArray.detailstylesheet || null;
//load stylesheet if required in async mode
if( this.stylesheet ) {
var context = this;
var request = new pzHttpRequest( this.stylesheet );
request.get( {}, function ( doc ) { context.xslDoc = doc; } );
}
this.errorHandler = paramArray.errorhandler || null;
this.showResponseType = paramArray.showResponseType || "xml";
// function callbacks
this.initCallback = paramArray.oninit || null;
this.statCallback = paramArray.onstat || null;
this.showCallback = paramArray.onshow || null;
this.termlistCallback = paramArray.onterm || null;
this.recordCallback = paramArray.onrecord || null;
this.bytargetCallback = paramArray.onbytarget || null;
this.resetCallback = paramArray.onreset || null;
// termlist keys
this.termKeys = paramArray.termlist || "subject";
// some configurational stuff
this.keepAlive = 50000;
if ( paramArray.keepAlive < this.keepAlive )
this.keepAlive = paramArray.keepAlive;
this.sessionID = null;
this.serviceId = paramArray.serviceId || null;
this.initStatusOK = false;
this.pingStatusOK = false;
this.searchStatusOK = false;
// for sorting
this.currentSort = "relevance";
// where are we?
this.currentStart = 0;
this.currentNum = 20;
// last full record retrieved
this.currRecID = null;
// current query
this.currQuery = null;
//current raw record offset
this.currRecOffset = null;
//timers
this.pingTimer = null;
this.statTime = paramArray.stattime || 1000;
this.statTimer = null;
this.termTime = paramArray.termtime || 1000;
this.termTimer = null;
this.showTime = paramArray.showtime || 1000;
this.showTimer = null;
this.showFastCount = 4;
this.bytargetTime = paramArray.bytargettime || 1000;
this.bytargetTimer = null;
this.recordTime = paramArray.recordtime || 500;
this.recordTimer = null;
// counters for each command and applied delay
this.dumpFactor = 500;
this.showCounter = 0;
this.termCounter = 0;
this.statCounter = 0;
this.bytargetCounter = 0;
this.recordCounter = 0;
// active clients, updated by stat and show
// might be an issue since bytarget will poll accordingly
this.activeClients = 1;
// if in proxy mode no need to init
if (paramArray.usesessions != undefined) {
this.useSessions = paramArray.usesessions;
this.initStatusOK = true;
}
// else, auto init session or wait for a user init?
if (this.useSessions && paramArray.autoInit !== false) {
this.init(this.sessionId, this.serviceId);
}
};
pz2.prototype =
{
//error handler for async error throws
throwError: function (errMsg, errCode)
{
var err = new Error(errMsg);
if (errCode) err.code = errCode;
if (this.errorHandler) {
this.errorHandler(err);
}
else {
throw err;
}
},
// stop activity by clearing tiemouts
stop: function ()
{
clearTimeout(this.statTimer);
clearTimeout(this.showTimer);
clearTimeout(this.termTimer);
clearTimeout(this.bytargetTimer);
},
// reset status variables
reset: function ()
{
if ( this.useSessions ) {
this.sessionID = null;
this.initStatusOK = false;
this.pingStatusOK = false;
clearTimeout(this.pingTimer);
}
this.searchStatusOK = false;
this.stop();
if ( this.resetCallback )
this.resetCallback();
},
init: function (sessionId, serviceId)
{
this.reset();
// session id as a param
if (sessionId && this.useSessions ) {
this.initStatusOK = true;
this.sessionID = sessionId;
this.ping();
// old school direct pazpar2 init
} else if (this.useSessions) {
var context = this;
var request = new pzHttpRequest(this.pz2String, this.errorHandler);
var opts = {'command' : 'init'};
if (serviceId) opts.service = serviceId;
request.safeGet(
opts,
function(data) {
if ( data.getElementsByTagName("status")[0]
.childNodes[0].nodeValue == "OK" ) {
if ( data.getElementsByTagName("protocol")[0]
.childNodes[0].nodeValue
!= context.suppProtoVer )
throw new Error(
"Server's protocol not supported by the client"
);
context.initStatusOK = true;
context.sessionID =
data.getElementsByTagName("session")[0]
.childNodes[0].nodeValue;
context.pingTimer =
setTimeout(
function () {
context.ping();
},
context.keepAlive
);
if ( context.initCallback )
context.initCallback();
}
else
context.throwError('Init failed. Malformed WS resonse.',
110);
}
);
// when through proxy no need to init
} else {
this.initStatusOK = true;
}
},
// no need to ping explicitly
ping: function ()
{
// pinging only makes sense when using pazpar2 directly
if( !this.initStatusOK || !this.useSessions )
throw new Error(
'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
);
var context = this;
clearTimeout(context.pingTimer);
var request = new pzHttpRequest(this.pz2String, this.errorHandler);
request.safeGet(
{ "command": "ping", "session": this.sessionID, "windowid" : window.name },
function(data) {
if ( data.getElementsByTagName("status")[0]
.childNodes[0].nodeValue == "OK" ) {
context.pingStatusOK = true;
context.pingTimer =
setTimeout(
function () {
context.ping();
},
context.keepAlive
);
}
else
context.throwError('Ping failed. Malformed WS resonse.',
111);
}
);
},
search: function (query, num, sort, filter, showfrom, addParamsArr)
{
clearTimeout(this.statTimer);
clearTimeout(this.showTimer);
clearTimeout(this.termTimer);
clearTimeout(this.bytargetTimer);
this.showCounter = 0;
this.termCounter = 0;
this.bytargetCounter = 0;
this.statCounter = 0;
this.activeClients = 1;
// no proxy mode
if( !this.initStatusOK )
throw new Error('Pz2.js: session not initialized.');
if( query !== undefined )
this.currQuery = query;
else
throw new Error("Pz2.js: no query supplied to the search command.");
if ( showfrom !== undefined )
var start = showfrom;
else
var start = 0;
var searchParams = {
"command": "search",
"query": this.currQuery,
"session": this.sessionID,
"windowid" : window.name
};
if (filter !== undefined)
searchParams["filter"] = filter;
// copy additional parmeters, do not overwrite
if (addParamsArr != undefined) {
for (var prop in addParamsArr) {
if (!searchParams.hasOwnProperty(prop))
searchParams[prop] = addParamsArr[prop];
}
}
var context = this;
var request = new pzHttpRequest(this.pz2String, this.errorHandler);
request.safeGet(
searchParams,
function(data) {
if ( data.getElementsByTagName("status")[0]
.childNodes[0].nodeValue == "OK" ) {
context.searchStatusOK = true;
//piggyback search
context.show(start, num, sort);
if (context.statCallback)
context.stat();
if (context.termlistCallback)
context.termlist();
if (context.bytargetCallback)
context.bytarget();
}
else
context.throwError('Search failed. Malformed WS resonse.',
112);
}
);
},
stat: function()
{
if( !this.initStatusOK )
throw new Error('Pz2.js: session not initialized.');
// if called explicitly takes precedence
clearTimeout(this.statTimer);
var context = this;
var request = new pzHttpRequest(this.pz2String, this.errorHandler);
request.safeGet(
{ "command": "stat", "session": this.sessionID, "windowid" : window.name },
function(data) {
if ( data.getElementsByTagName("stat") ) {
var activeClients =
Number( data.getElementsByTagName("activeclients")[0]
.childNodes[0].nodeValue );
context.activeClients = activeClients;
var stat = Element_parseChildNodes(data.documentElement);
context.statCounter++;
var delay = context.statTime
+ context.statCounter * context.dumpFactor;
if ( activeClients > 0 )
context.statTimer =
setTimeout(
function () {
context.stat();
},
delay
);
context.statCallback(stat);
}
else
context.throwError('Stat failed. Malformed WS resonse.',
113);
}
);
},
show: function(start, num, sort)
{
if( !this.searchStatusOK && this.useSessions )
throw new Error(
'Pz2.js: show command has to be preceded with a search command.'
);
// if called explicitly takes precedence
clearTimeout(this.showTimer);
if( sort !== undefined )
this.currentSort = sort;
if( start !== undefined )
this.currentStart = Number( start );
if( num !== undefined )
this.currentNum = Number( num );
var context = this;
var request = new pzHttpRequest(this.pz2String, this.errorHandler);
request.safeGet(
{
"command": "show",
"session": this.sessionID,
"start": this.currentStart,
"num": this.currentNum,
"sort": this.currentSort,
"block": 1,
"type": this.showResponseType,
"windowid" : window.name
},
function(data, type) {
var show = null;
var activeClients = 0;
if (type === "json") {
show = {};
activeClients = Number(data.activeclients[0]);
show.activeclients = activeClients;
show.merged = Number(data.merged[0]);
show.total = Number(data.total[0]);
show.start = Number(data.start[0]);
show.num = Number(data.num[0]);
show.hits = data.hit;
} else if (data.getElementsByTagName("status")[0]
.childNodes[0].nodeValue == "OK") {
// first parse the status data send along with records
// this is strictly bound to the format
activeClients =
Number(data.getElementsByTagName("activeclients")[0]
.childNodes[0].nodeValue);
show = {
"activeclients": activeClients,
"merged":
Number( data.getElementsByTagName("merged")[0]
.childNodes[0].nodeValue ),
"total":
Number( data.getElementsByTagName("total")[0]
.childNodes[0].nodeValue ),
"start":
Number( data.getElementsByTagName("start")[0]
.childNodes[0].nodeValue ),
"num":
Number( data.getElementsByTagName("num")[0]
.childNodes[0].nodeValue ),
"hits": []
};
// parse all the first-level nodes for all <hit> tags
var hits = data.getElementsByTagName("hit");
for (i = 0; i < hits.length; i++)
show.hits[i] = Element_parseChildNodes(hits[i]);
} else {
context.throwError('Show failed. Malformed WS resonse.',
114);
}
context.activeClients = activeClients;
context.showCounter++;
var delay = context.showTime;
if (context.showCounter > context.showFastCount)
delay += context.showCounter * context.dumpFactor;
if ( activeClients > 0 )
context.showTimer = setTimeout(
function () {
context.show();
},
delay);
context.showCallback(show);
}
);
},
record: function(id, offset, syntax, handler)
{
// we may call record with no previous search if in proxy mode
if(!this.searchStatusOK && this.useSessions)
throw new Error(
'Pz2.js: record command has to be preceded with a search command.'
);
if( id !== undefined )
this.currRecID = id;
var recordParams = {
"command": "record",
"session": this.sessionID,
"id": this.currRecID,
"windowid" : window.name
};
this.currRecOffset = null;
if (offset != undefined) {
recordParams["offset"] = offset;
this.currRecOffset = offset;
}
if (syntax != undefined)
recordParams['syntax'] = syntax;
//overwrite default callback id needed
var callback = this.recordCallback;
var args = undefined;
if (handler != undefined) {
callback = handler['callback'];
args = handler['args'];
}
var context = this;
var request = new pzHttpRequest(this.pz2String, this.errorHandler);
request.safeGet(
recordParams,
function(data) {
var recordNode;
var record;
//raw record
if (context.currRecOffset !== null) {
record = new Array();
record['xmlDoc'] = data;
record['offset'] = context.currRecOffset;
callback(record, args);
//pz2 record
} else if ( recordNode =
data.getElementsByTagName("record")[0] ) {
// if stylesheet was fetched do not parse the response
if ( context.xslDoc ) {
record = new Array();
record['xmlDoc'] = data;
record['xslDoc'] = context.xslDoc;
record['recid'] =
recordNode.getElementsByTagName("recid")[0]
.firstChild.nodeValue;
//parse record
} else {
record = Element_parseChildNodes(recordNode);
}
var activeClients =
Number( data.getElementsByTagName("activeclients")[0]
.childNodes[0].nodeValue );
context.activeClients = activeClients;
context.recordCounter++;
var delay = context.recordTime + context.recordCounter * context.dumpFactor;
if ( activeClients > 0 )
context.recordTimer =
setTimeout (
function() {
context.record(id, offset, syntax, handler);
},
delay
);
callback(record, args);
}
else
context.throwError('Record failed. Malformed WS resonse.',
115);
}
);
},
termlist: function()
{
if( !this.searchStatusOK && this.useSessions )
throw new Error(
'Pz2.js: termlist command has to be preceded with a search command.'
);
// if called explicitly takes precedence
clearTimeout(this.termTimer);
var context = this;
var request = new pzHttpRequest(this.pz2String, this.errorHandler);
request.safeGet(
{
"command": "termlist",
"session": this.sessionID,
"name": this.termKeys,
"windowid" : window.name
},
function(data) {
if ( data.getElementsByTagName("termlist") ) {
var activeClients =
Number( data.getElementsByTagName("activeclients")[0]
.childNodes[0].nodeValue );
context.activeClients = activeClients;
var termList = { "activeclients": activeClients };
var termLists = data.getElementsByTagName("list");
//for each termlist
for (i = 0; i < termLists.length; i++) {
var listName = termLists[i].getAttribute('name');
termList[listName] = new Array();
var terms = termLists[i].getElementsByTagName('term');
//for each term in the list
for (j = 0; j < terms.length; j++) {
var term = {
"name":
(terms[j].getElementsByTagName("name")[0]
.childNodes.length
? terms[j].getElementsByTagName("name")[0]
.childNodes[0].nodeValue
: 'ERROR'),
"freq":
terms[j]
.getElementsByTagName("frequency")[0]
.childNodes[0].nodeValue || 'ERROR'
};
var termIdNode =
terms[j].getElementsByTagName("id");
if(terms[j].getElementsByTagName("id").length)
term["id"] =
termIdNode[0].childNodes[0].nodeValue;
termList[listName][j] = term;
}
}
context.termCounter++;
var delay = context.termTime
+ context.termCounter * context.dumpFactor;
if ( activeClients > 0 )
context.termTimer =
setTimeout(
function () {
context.termlist();
},
delay
);
context.termlistCallback(termList);
}
else
context.throwError('Termlist failed. Malformed WS resonse.',
116);
}
);
},
bytarget: function()
{
if( !this.initStatusOK && this.useSessions )
throw new Error(
'Pz2.js: bytarget command has to be preceded with a search command.'
);
// no need to continue
if( !this.searchStatusOK )
return;
// if called explicitly takes precedence
clearTimeout(this.bytargetTimer);
var context = this;
var request = new pzHttpRequest(this.pz2String, this.errorHandler);
request.safeGet(
{ "command": "bytarget", "session": this.sessionID, "windowid" : window.name},
function(data) {
if ( data.getElementsByTagName("status")[0]
.childNodes[0].nodeValue == "OK" ) {
var targetNodes = data.getElementsByTagName("target");
var bytarget = new Array();
for ( i = 0; i < targetNodes.length; i++) {
bytarget[i] = new Array();
for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
if ( targetNodes[i].childNodes[j].nodeType
== Node.ELEMENT_NODE ) {
var nodeName =
targetNodes[i].childNodes[j].nodeName;
var nodeText =
targetNodes[i].childNodes[j]
.firstChild.nodeValue;
bytarget[i][nodeName] = nodeText;
}
}
if (bytarget[i]["state"]=="Client_Disconnected") {
bytarget[i]["hits"] = "Error";
} else if (bytarget[i]["state"]=="Client_Error") {
bytarget[i]["hits"] = "Error";
} else if (bytarget[i]["state"]=="Client_Working") {
bytarget[i]["hits"] = "...";
}
if (bytarget[i].diagnostic == "1") {
bytarget[i].diagnostic = "Permanent system error";
} else if (bytarget[i].diagnostic == "2") {
bytarget[i].diagnostic = "Temporary system error";
}
}
context.bytargetCounter++;
var delay = context.bytargetTime
+ context.bytargetCounter * context.dumpFactor;
if ( context.activeClients > 0 )
context.bytargetTimer =
setTimeout(
function () {
context.bytarget();
},
delay
);
context.bytargetCallback(bytarget);
}
else
context.throwError('Bytarget failed. Malformed WS resonse.',
117);
}
);
},
// just for testing, probably shouldn't be here
showNext: function(page)
{
var step = page || 1;
this.show( ( step * this.currentNum ) + this.currentStart );
},
showPrev: function(page)
{
if (this.currentStart == 0 )
return false;
var step = page || 1;
var newStart = this.currentStart - (step * this.currentNum );
this.show( newStart > 0 ? newStart : 0 );
},
showPage: function(pageNum)
{
//var page = pageNum || 1;
this.show(pageNum * this.currentNum);
}
};
/*
********************************************************************************
** AJAX HELPER CLASS ***********************************************************
********************************************************************************
*/
var pzHttpRequest = function ( url, errorHandler ) {
this.maxUrlLength = 2048;
this.request = null;
this.url = url;
this.errorHandler = errorHandler || null;
this.async = true;
this.requestHeaders = {};
if ( window.XMLHttpRequest ) {
this.request = new XMLHttpRequest();
} else if ( window.ActiveXObject ) {
try {
this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
} catch (err) {
this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
}
}
};
pzHttpRequest.prototype =
{
safeGet: function ( params, callback )
{
var encodedParams = this.encodeParams(params);
var url = this._urlAppendParams(encodedParams);
if (url.length >= this.maxUrlLength) {
this.requestHeaders["Content-Type"]
= "application/x-www-form-urlencoded";
this._send( 'POST', this.url, encodedParams, callback );
} else {
this._send( 'GET', url, '', callback );
}
},
get: function ( params, callback )
{
this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
'', callback );
},
post: function ( params, data, callback )
{
this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
data, callback );
},
load: function ()
{
this.async = false;
this.request.open( 'GET', this.url, this.async );
this.request.send('');
if ( this.request.status == 200 )
return this.request.responseXML;
},
encodeParams: function (params)
{
var sep = "";
var encoded = "";
for (var key in params) {
if (params[key] != null) {
encoded += sep + key + '=' + encodeURIComponent(params[key]);
sep = '&';
}
}
return encoded;
},
_send: function ( type, url, data, callback)
{
var context = this;
this.callback = callback;
this.async = true;
this.request.open( type, url, this.async );
for (var key in this.requestHeaders)
this.request.setRequestHeader(key, this.requestHeaders[key]);
this.request.onreadystatechange = function () {
context._handleResponse(url); /// url used ONLY for error reporting
}
this.request.send(data);
},
_urlAppendParams: function (encodedParams)
{
if (encodedParams)
return this.url + "?" + encodedParams;
else
return this.url;
},
_handleResponse: function (savedUrlForErrorReporting)
{
if ( this.request.readyState == 4 ) {
// pick up appplication errors first
var errNode = null;
if (this.request.responseXML &&
(errNode = this.request.responseXML.documentElement)
&& errNode.nodeName == 'error') {
var errMsg = errNode.getAttribute("msg");
var errCode = errNode.getAttribute("code");
var errAddInfo = '';
if (errNode.childNodes.length)
errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
var err = new Error(errMsg + errAddInfo);
err.code = errCode;
if (this.errorHandler) {
this.errorHandler(err);
}
else {
throw err;
}
} else if (this.request.status == 200 &&
this.request.responseXML == null) {
if (this.request.responseText != null) {
//assume JSON
var json = null;
var text = this.request.responseText;
if (typeof window.JSON == "undefined")
json = eval("(" + text + ")");
else {
try {
json = JSON.parse(text);
}
catch (e) {
// Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
/* DEBUG only works in mk2-mobile
if (document.getElementById("log"))
document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
*/
try {
json = eval("(" + text + ")");
}
catch (e) {
/* DEBUG only works in mk2-mobile
if (document.getElementById("log"))
document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
*/
}
}
}
this.callback(json, "json");
} else {
var err = new Error("XML response is empty but no error " +
"for " + savedUrlForErrorReporting);
err.code = -1;
if (this.errorHandler) {
this.errorHandler(err);
} else {
throw err;
}
}
} else if (this.request.status == 200) {
this.callback(this.request.responseXML);
} else {
var err = new Error("HTTP response not OK: "
+ this.request.status + " - "
+ this.request.statusText );
err.code = '00' + this.request.status;
if (this.errorHandler) {
this.errorHandler(err);
}
else {
throw err;
}
}
}
}
};
/*
********************************************************************************
** XML HELPER FUNCTIONS ********************************************************
********************************************************************************
*/
// DOMDocument
if ( window.ActiveXObject) {
var DOMDoc = document;
} else {
var DOMDoc = Document.prototype;
}
DOMDoc.newXmlDoc = function ( root )
{
var doc;
if (document.implementation && document.implementation.createDocument) {
doc = document.implementation.createDocument('', root, null);
} else if ( window.ActiveXObject ) {
doc = new ActiveXObject("MSXML2.DOMDocument");
doc.loadXML('<' + root + '/>');
} else {
throw new Error ('No XML support in this browser');
}
return doc;
}
DOMDoc.parseXmlFromString = function ( xmlString )
{
var doc;
if ( window.DOMParser ) {
var parser = new DOMParser();
doc = parser.parseFromString( xmlString, "text/xml");
} else if ( window.ActiveXObject ) {
doc = new ActiveXObject("MSXML2.DOMDocument");
doc.loadXML( xmlString );
} else {
throw new Error ("No XML parsing support in this browser.");
}
return doc;
}
DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
{
if ( window.XSLTProcessor ) {
var proc = new XSLTProcessor();
proc.importStylesheet( xslDoc );
return proc.transformToDocument(xmlDoc);
} else if ( window.ActiveXObject ) {
return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
} else {
alert( 'Unable to perform XSLT transformation in this browser' );
}
}
// DOMElement
Element_removeFromDoc = function (DOM_Element)
{
DOM_Element.parentNode.removeChild(DOM_Element);
}
Element_emptyChildren = function (DOM_Element)
{
while( DOM_Element.firstChild ) {
DOM_Element.removeChild( DOM_Element.firstChild )
}
}
Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
{
if ( window.XSLTProcessor ) {
var proc = new XSLTProcessor();
proc.importStylesheet( xslDoc );
var docFrag = false;
docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
DOM_Element.appendChild(docFrag);
} else if ( window.ActiveXObject ) {
DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
} else {
alert( 'Unable to perform XSLT transformation in this browser' );
}
}
Element_appendTextNode = function (DOM_Element, tagName, textContent )
{
var node = DOM_Element.ownerDocument.createElement(tagName);
var text = DOM_Element.ownerDocument.createTextNode(textContent);
DOM_Element.appendChild(node);
node.appendChild(text);
return node;
}
Element_setTextContent = function ( DOM_Element, textContent )
{
if (typeof DOM_Element.textContent !== "undefined") {
DOM_Element.textContent = textContent;
} else if (typeof DOM_Element.innerText !== "undefined" ) {
DOM_Element.innerText = textContent;
} else {
throw new Error("Cannot set text content of the node, no such method.");
}
}
Element_getTextContent = function (DOM_Element)
{
if ( typeof DOM_Element.textContent != 'undefined' ) {
return DOM_Element.textContent;
} else if (typeof DOM_Element.text != 'undefined') {
return DOM_Element.text;
} else {
throw new Error("Cannot get text content of the node, no such method.");
}
}
Element_parseChildNodes = function (node)
{
var parsed = {};
var hasChildElems = false;
if (node.hasChildNodes()) {
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.nodeType == Node.ELEMENT_NODE) {
hasChildElems = true;
var nodeName = child.nodeName;
if (!(nodeName in parsed))
parsed[nodeName] = [];
parsed[nodeName].push(Element_parseChildNodes(child));
}
}
}
var attrs = node.attributes;
for (var i = 0; i < attrs.length; i++) {
var attrName = '@' + attrs[i].nodeName;
var attrValue = attrs[i].nodeValue;
parsed[attrName] = attrValue;
}
// if no nested elements, get text content
if (node.hasChildNodes() && !hasChildElems) {
if (node.attributes.length)
parsed['#text'] = node.firstChild.nodeValue;
else
parsed = node.firstChild.nodeValue;
}
return parsed;
}
/* do not remove trailing bracket */
}
| gpl-2.0 |
sasongko26/sideka-desktop | login_edit_profil.py | 2697 | import wx
import edit_profil
import peringatan
import frm_sideka_menu
def create(parent):
return Dialog1(parent)
[wxID_DIALOG1, wxID_DIALOG1BUTTON1, wxID_DIALOG1BUTTON2,
wxID_DIALOG1STATICLINE1, wxID_DIALOG1STATICTEXT1, wxID_DIALOG1STATICTEXT2,
wxID_DIALOG1TEXTCTRL1,
] = [wx.NewId() for _init_ctrls in range(7)]
class Dialog1(wx.Dialog):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Dialog.__init__(self, id=wxID_DIALOG1, name='', parent=prnt,
pos=wx.Point(515, 304), size=wx.Size(402, 140), style=wx.CAPTION,
title=u'Otentifikasi')
self.SetClientSize(wx.Size(402, 140))
self.staticText1 = wx.StaticText(id=wxID_DIALOG1STATICTEXT1,
label=u'Password', name='staticText1', parent=self,
pos=wx.Point(16, 64), size=wx.Size(60, 17), style=0)
self.textCtrl1 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL1, name='textCtrl1',
parent=self, pos=wx.Point(96, 56), size=wx.Size(296, 25),
style=wx.TE_PASSWORD, value='')
self.staticText2 = wx.StaticText(id=wxID_DIALOG1STATICTEXT2,
label=u'MASUKAN PASSWORD DAHULU', name='staticText2', parent=self,
pos=wx.Point(104, 16), size=wx.Size(203, 17), style=0)
self.button1 = wx.Button(id=wxID_DIALOG1BUTTON1, label=u'Lanjutkan',
name='button1', parent=self, pos=wx.Point(208, 96),
size=wx.Size(184, 30), style=0)
self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
id=wxID_DIALOG1BUTTON1)
self.button2 = wx.Button(id=wxID_DIALOG1BUTTON2,
label=u'Kembali Ke Menu', name='button2', parent=self,
pos=wx.Point(16, 96), size=wx.Size(184, 30), style=0)
self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
id=wxID_DIALOG1BUTTON2)
self.staticLine1 = wx.StaticLine(id=wxID_DIALOG1STATICLINE1,
name='staticLine1', parent=self, pos=wx.Point(16, 40),
size=wx.Size(368, 2), style=0)
def __init__(self, parent):
self._init_ctrls(parent)
def OnButton1Button(self, event):
oneng = 'andri'
user_password = self.textCtrl1.GetValue()
if user_password == oneng:
self.main=edit_profil.create(None)
self.main.Show()
self.Close()
else:
self.Close()
self.main=peringatan.create(None)
self.main.Show()
def OnButton2Button(self, event):
self.Close()
self.main=frm_sideka_menu.create(None)
self.main.Show()
| gpl-2.0 |
1ec5/mediawiki-core | tests/phpunit/includes/RecentChangeTest.php | 6935 | <?php
/**
* @group Database
*/
class RecentChangeTest extends MediaWikiTestCase {
protected $title;
protected $target;
protected $user;
protected $user_comment;
protected $context;
function __construct() {
parent::__construct();
$this->title = Title::newFromText( 'SomeTitle' );
$this->target = Title::newFromText( 'TestTarget' );
$this->user = User::newFromName( 'UserName' );
$this->user_comment = '<User comment about action>';
$this->context = RequestContext::newExtraneousContext( $this->title );
}
/**
* The testIrcMsgForAction* tests are supposed to cover the hacky
* LogFormatter::getIRCActionText / bug 34508
*
* Third parties bots listen to those messages. They are clever enough
* to fetch the i18n messages from the wiki and then analyze the IRC feed
* to reverse engineer the $1, $2 messages.
* One thing bots can not detect is when MediaWiki change the meaning of
* a message like what happened when we deployed 1.19. $1 became the user
* performing the action which broke basically all bots around.
*
* Should cover the following log actions (which are most commonly used by bots):
* - block/block
* - block/unblock
* - delete/delete
* - delete/restore
* - newusers/create
* - newusers/create2
* - newusers/autocreate
* - move/move
* - move/move_redir
* - protect/protect
* - protect/modifyprotect
* - protect/unprotect
* - upload/upload
*
* As well as the following Auto Edit Summaries:
* - blank
* - replace
* - rollback
* - undo
*/
/**
* @covers LogFormatter::getIRCActionText
*/
function testIrcMsgForLogTypeBlock() {
# block/block
$this->assertIRCComment(
$this->context->msg( 'blocklogentry', 'SomeTitle' )->plain() . ': ' . $this->user_comment,
'block', 'block',
array(),
$this->user_comment
);
# block/unblock
$this->assertIRCComment(
$this->context->msg( 'unblocklogentry', 'SomeTitle' )->plain() . ': ' . $this->user_comment,
'block', 'unblock',
array(),
$this->user_comment
);
}
/**
* @covers LogFormatter::getIRCActionText
*/
function testIrcMsgForLogTypeDelete() {
# delete/delete
$this->assertIRCComment(
$this->context->msg( 'deletedarticle', 'SomeTitle' )->plain() . ': ' . $this->user_comment,
'delete', 'delete',
array(),
$this->user_comment
);
# delete/restore
$this->assertIRCComment(
$this->context->msg( 'undeletedarticle', 'SomeTitle' )->plain() . ': ' . $this->user_comment,
'delete', 'restore',
array(),
$this->user_comment
);
}
/**
* @covers LogFormatter::getIRCActionText
*/
function testIrcMsgForLogTypeNewusers() {
$this->assertIRCComment(
'New user account',
'newusers', 'newusers',
array()
);
$this->assertIRCComment(
'New user account',
'newusers', 'create',
array()
);
$this->assertIRCComment(
'created new account SomeTitle',
'newusers', 'create2',
array()
);
$this->assertIRCComment(
'Account created automatically',
'newusers', 'autocreate',
array()
);
}
/**
* @covers LogFormatter::getIRCActionText
*/
function testIrcMsgForLogTypeMove() {
$move_params = array(
'4::target' => $this->target->getPrefixedText(),
'5::noredir' => 0,
);
# move/move
$this->assertIRCComment(
$this->context->msg( '1movedto2', 'SomeTitle', 'TestTarget' )->plain() . ': ' . $this->user_comment,
'move', 'move',
$move_params,
$this->user_comment
);
# move/move_redir
$this->assertIRCComment(
$this->context->msg( '1movedto2_redir', 'SomeTitle', 'TestTarget' )->plain() . ': ' . $this->user_comment,
'move', 'move_redir',
$move_params,
$this->user_comment
);
}
/**
* @covers LogFormatter::getIRCActionText
*/
function testIrcMsgForLogTypePatrol() {
# patrol/patrol
$this->assertIRCComment(
$this->context->msg( 'patrol-log-line', 'revision 777', '[[SomeTitle]]', '' )->plain(),
'patrol', 'patrol',
array(
'4::curid' => '777',
'5::previd' => '666',
'6::auto' => 0,
)
);
}
/**
* @covers LogFormatter::getIRCActionText
*/
function testIrcMsgForLogTypeProtect() {
$protectParams = array(
'[edit=sysop] (indefinite) [move=sysop] (indefinite)'
);
# protect/protect
$this->assertIRCComment(
$this->context->msg( 'protectedarticle', 'SomeTitle ' . $protectParams[0] )->plain() . ': ' . $this->user_comment,
'protect', 'protect',
$protectParams,
$this->user_comment
);
# protect/unprotect
$this->assertIRCComment(
$this->context->msg( 'unprotectedarticle', 'SomeTitle' )->plain() . ': ' . $this->user_comment,
'protect', 'unprotect',
array(),
$this->user_comment
);
# protect/modify
$this->assertIRCComment(
$this->context->msg( 'modifiedarticleprotection', 'SomeTitle ' . $protectParams[0] )->plain() . ': ' . $this->user_comment,
'protect', 'modify',
$protectParams,
$this->user_comment
);
}
/**
* @covers LogFormatter::getIRCActionText
*/
function testIrcMsgForLogTypeUpload() {
# upload/upload
$this->assertIRCComment(
$this->context->msg( 'uploadedimage', 'SomeTitle' )->plain() . ': ' . $this->user_comment,
'upload', 'upload',
array(),
$this->user_comment
);
# upload/overwrite
$this->assertIRCComment(
$this->context->msg( 'overwroteimage', 'SomeTitle' )->plain() . ': ' . $this->user_comment,
'upload', 'overwrite',
array(),
$this->user_comment
);
}
/**
* @todo: Emulate these edits somehow and extract
* raw edit summary from RecentChange object
* --
*/
/*
function testIrcMsgForBlankingAES() {
// $this->context->msg( 'autosumm-blank', .. );
}
function testIrcMsgForReplaceAES() {
// $this->context->msg( 'autosumm-replace', .. );
}
function testIrcMsgForRollbackAES() {
// $this->context->msg( 'revertpage', .. );
}
function testIrcMsgForUndoAES() {
// $this->context->msg( 'undo-summary', .. );
}
*/
/**
* @param $expected String Expected IRC text without colors codes
* @param $type String Log type (move, delete, suppress, patrol ...)
* @param $action String A log type action
* @param $comment String (optional) A comment for the log action
* @param $msg String (optional) A message for PHPUnit :-)
*/
function assertIRCComment( $expected, $type, $action, $params, $comment = null, $msg = '' ) {
$logEntry = new ManualLogEntry( $type, $action );
$logEntry->setPerformer( $this->user );
$logEntry->setTarget( $this->title );
if ( $comment !== null ) {
$logEntry->setComment( $comment );
}
$logEntry->setParameters( $params );
$formatter = LogFormatter::newFromEntry( $logEntry );
$formatter->setContext( $this->context );
// Apply the same transformation as done in RecentChange::getIRCLine for rc_comment
$ircRcComment = RecentChange::cleanupForIRC( $formatter->getIRCActionComment() );
$this->assertEquals(
$expected,
$ircRcComment,
$msg
);
}
}
| gpl-2.0 |
ahsquared/arc | arc-assets/themes/ut-thehill/library/includes/utk.php | 3333 | <?php
//===================================================================================================================
// Let's put the UT Logo on the login screen
//===================================================================================================================
function change_ut_wp_login_image() {
echo "
<style>
body.login #login h1 a {
background: url('".get_bloginfo('template_url')."/images/interface/login.png') 8px 0 no-repeat transparent;
background-size: 240px 117px;
height:117px;
width:240px; }
</style>
";
}
add_action("login_head", "change_ut_wp_login_image");
//===================================================================================================================
// UT Site ADMIN
//===================================================================================================================
// Creates a new level of user that has more access than editor but less
// than administrator. Allows us not to use User Role Editor plugin
add_role('UT_site_admin', 'UT Site Admin', array(
'delete_others_pages' => true,
'delete_others_posts' => true,
'delete_pages' => true,
'delete_posts' => true,
'delete_private_pages' => true,
'delete_private_posts' => true,
'delete_published_pages' => true,
'delete_published_posts' => true,
'edit_others_pages' => true,
'edit_others_posts' => true,
'edit_pages' => true,
'edit_posts' => true,
'edit_private_pages' => true,
'edit_private_posts' => true,
'edit_published_pages' => true,
'edit_published_posts' => true,
'edit_theme_options' => true,
'gravityforms_create_form' => true,
'gravityforms_delete_entries' => true,
'gravityforms_delete_forms' => true,
'gravityforms_edit_entries' => true,
'gravityforms_edit_entry_notes' => true,
'gravityforms_edit_forms' => true,
'gravityforms_export_entries' => true,
'gravityforms_feed' => true,
'gravityforms_view_entries' => true,
'gravityforms_view_entry_notes' => true,
'list_users' => true,
'manage_categories' => true,
'manage_links' => true,
'moderate_comments' => true,
'publish_pages' => true,
'publish_posts' => true,
'read' => true,
'read_private_pages' => true,
'read_private_posts' => true,
'upload_files' => true,
'view_stats' => true,
'show_admin_bar' => true,
));
// This fixes a problem where no one except administrators could save theme options
// Fix was found in Twenty Eleven theme, and modified to apply to this theme,
// And confirmed here http://wordpress.org/support/topic/wordpress-settings-api-cheatin-uh-error
function ut_horizontal_option_page_capability( $capability ) {
return 'edit_theme_options';
}
add_filter( 'option_page_capability_ut_theme_options', 'ut_horizontal_option_page_capability' );
// Create Custom Admin Menu
// Hook for adding admin menus
add_action('admin_menu', 'ut_help_menu');
// action function for above hook
function ut_help_menu() {
$favicon=get_template_directory_uri().'/images/interface/custom-admin-icon.png';
// Add a new top-level menu:
$hook=add_menu_page(__('UT WordPress Theme Help'), __('UT Theme Help'), 'edit_published_posts', 'ut-theme-admin-help', 'ut_help', 'dashicons-editor-help', 3 );
}
// displays the page content for the custom UT Help menu
function ut_help() {
require_once ( get_template_directory() . '/library/includes/help/opt-help.php' );
} ?> | gpl-2.0 |
digital-code/problemset | LCS.java | 1168 | import java.util.*;
public class LCS {
public static void main(String[] args) {
Scanner StdIn=new Scanner(System.in);
String x = StdIn.nextLine();
String y = StdIn.nextLine();
int M = x.length();
int N = y.length();
// opt[i][j] = length of LCS of x[i..M] and y[j..N]
int[][] opt = new int[M+1][N+1];
// compute length of LCS and all subproblems via dynamic programming
for (int i = M-1; i >= 0; i--) {
for (int j = N-1; j >= 0; j--) {
if (x.charAt(i) == y.charAt(j))
opt[i][j] = opt[i+1][j+1] + 1;
else
opt[i][j] = Math.max(opt[i+1][j], opt[i][j+1]);
}
}
// recover LCS itself and print it to standard output
int i = 0, j = 0;
while(i < M && j < N) {
if (x.charAt(i) == y.charAt(j)) {
System.out.print(x.charAt(i));
i++;
j++;
}
else if (opt[i+1][j] >= opt[i][j+1]) i++;
else j++;
}
System.out.println();
}
} | gpl-2.0 |