code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.axon.monitor.config;
/**
*
* @author aardvocate
*/
public class Web extends MonitorBase {
public String url;
}
| segun/jmonit | src/za/co/axon/monitor/config/Web.java | Java | gpl-2.0 | 233 |
<?php
error_reporting(E_ALL);
if (!defined('DIR_KVZLIB')) {
define('DIR_KVZLIB', dirname(dirname(dirname(dirname(dirname(__FILE__))))));
}
?>
// LANG::xml
// Sample starts here
<?php
require_once DIR_KVZLIB.'/php/classes/KvzHTML.php';
$H = new KvzHTML(array(
'xml' => true,
));
$cdataOpts = array('__cdata' => true);
$H->setOption('echo', true);
$H->xml(true, array(
'version' => '2.0',
'encoding' => 'UTF-16',
));
$H->setOption('echo', false);
echo $H->auth(
$H->username('kvz', $cdataOpts) .
$H->api_key(sha1('xxxxxxxxxxxxxxxx'), $cdataOpts)
);
echo $H->users_list(true);
echo $H->users(true, array('type' => 'array'));
echo $H->user(
$H->id(442, $cdataOpts) .
$H->name('Jason Shellen', $cdataOpts) .
$H->screen_name('shellen', $cdataOpts) .
$H->location('iPhone: 37.889321,-122.173345', $cdataOpts) .
$H->description('CEO and founder of Thing Labs, makers of Brizzly! Former Blogger/Google dude, father of two little dudes.', $cdataOpts)
);
echo $H->users(false);
echo $H->users_list(false);
?> | thebillkidy/desple.com | wp-content/themes/capsule/ui/lib/phpjs/ext/kvzlib/php/samples/classes/KvzHTML/sample5-xml-complex.php | PHP | gpl-2.0 | 1,109 |
from getdist import loadMCSamples,plots,covmat
import numpy as np
import os,fnmatch
#filenames = fnmatch.filter(os.listdir("../output/chains/"),"mcmc_*.txt")
#for index in range(len(filenames)):
# os.rename("../output/chains/"+str(filenames[index]),"../output/chains/mcmc_final_output_"+str(index+1)+".txt")
number_of_parameters = 10
samples = loadMCSamples('../output/chains/NC-run4/mcmc_final_output',settings={'ignore_rows':0.})
p = samples.getParams()
samples.addDerived(np.log(1.e1**10*p.A_s),name='ln1010As',label='\ln 10^{10}A_s')
samples.addDerived(np.log10(p.cs2_fld),name='logcs2fld',label='\log c_s^2')
bestfit = samples.getLikeStats()
means = samples.setMeans()
filebestfit = open("../output/chains/bestfit.txt",'w')
filemeans = open("../output/chains/means.txt",'w')
for index in range(number_of_parameters) :
filebestfit.write(str(bestfit.names[index].bestfit_sample)+"\n")
filemeans.write(str(means[index])+"\n")
filebestfit.close()
filemeans.close()
covariance_matrix = samples.getCov(pars=[0,1,2,10,4,5,6,11,8,9])#nparam=number_of_parameters)
covariance_matrix_2 = covmat.CovMat(matrix=covariance_matrix)
covariance_matrix_2.saveToFile('../output/chains/covariance_matrix.txt')
print 'COVARIANCE MATRIX CREATED'
exit()
| wilmarcardonac/fisher-mcmc | analyzer/compute_cov.py | Python | gpl-2.0 | 1,275 |
/*
* CINELERRA
* Copyright (C) 2009 Adam Williams <broadcast at earthling dot net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "asset.h"
#include "bcsignals.h"
#include "cache.h"
#include "condition.h"
#include "datatype.h"
#include "edits.h"
#include "edl.h"
#include "edlsession.h"
#include "file.h"
#include "format.inc"
#include "localsession.h"
#include "mainsession.h"
#include "mwindow.h"
#include "overlayframe.h"
#include "playabletracks.h"
#include "playbackengine.h"
#include "preferences.h"
#include "preferencesthread.h"
#include "renderengine.h"
#include "strategies.inc"
#include "tracks.h"
#include "transportque.h"
#include "units.h"
#include "vedit.h"
#include "vframe.h"
#include "videoconfig.h"
#include "videodevice.h"
#include "virtualconsole.h"
#include "virtualvconsole.h"
#include "vmodule.h"
#include "vrender.h"
#include "vtrack.h"
VRender::VRender(RenderEngine *renderengine)
: CommonRender(renderengine)
{
data_type = TRACK_VIDEO;
transition_temp = 0;
overlayer = new OverlayFrame(renderengine->preferences->processors);
input_temp = 0;
vmodule_render_fragment = 0;
playback_buffer = 0;
session_frame = 0;
asynchronous = 0; // render 1 frame at a time
framerate_counter = 0;
video_out = 0;
render_strategy = -1;
}
VRender::~VRender()
{
if(input_temp) delete input_temp;
if(transition_temp) delete transition_temp;
if(overlayer) delete overlayer;
}
VirtualConsole* VRender::new_vconsole_object()
{
return new VirtualVConsole(renderengine, this);
}
int VRender::get_total_tracks()
{
return renderengine->get_edl()->tracks->total_video_tracks();
}
Module* VRender::new_module(Track *track)
{
return new VModule(renderengine, this, 0, track);
}
int VRender::flash_output()
{
if(video_out)
return renderengine->video->write_buffer(video_out, renderengine->get_edl());
else
return 0;
}
int VRender::process_buffer(VFrame *video_out,
int64_t input_position,
int use_opengl)
{
// process buffer for non realtime
int64_t render_len = 1;
int reconfigure = 0;
this->video_out = video_out;
current_position = input_position;
reconfigure = vconsole->test_reconfigure(input_position,
render_len);
if(reconfigure) restart_playback();
return process_buffer(input_position, use_opengl);
}
int VRender::process_buffer(int64_t input_position,
int use_opengl)
{
VEdit *playable_edit = 0;
int colormodel;
int use_vconsole = 1;
int use_brender = 0;
int result = 0;
int use_cache = renderengine->command->single_frame();
int use_asynchronous =
renderengine->command->realtime &&
renderengine->get_edl()->session->video_every_frame &&
renderengine->get_edl()->session->video_asynchronous;
const int debug = 0;
// Determine the rendering strategy for this frame.
use_vconsole = get_use_vconsole(&playable_edit,
input_position,
use_brender);
if(debug) printf("VRender::process_buffer %d use_vconsole=%d\n", __LINE__, use_vconsole);
// Negotiate color model
colormodel = get_colormodel(playable_edit, use_vconsole, use_brender);
if(debug) printf("VRender::process_buffer %d\n", __LINE__);
// Get output buffer from device
if(renderengine->command->realtime &&
!renderengine->is_nested)
{
renderengine->video->new_output_buffer(&video_out, colormodel);
}
if(debug) printf("VRender::process_buffer %d video_out=%p\n", __LINE__, video_out);
// printf("VRender::process_buffer use_vconsole=%d colormodel=%d video_out=%p\n",
// use_vconsole,
// colormodel,
// video_out);
// Read directly from file to video_out
if(!use_vconsole)
{
if(use_brender)
{
Asset *asset = renderengine->preferences->brender_asset;
File *file = renderengine->get_vcache()->check_out(asset,
renderengine->get_edl());
if(file)
{
int64_t corrected_position = current_position;
if(renderengine->command->get_direction() == PLAY_REVERSE)
corrected_position--;
// Cache single frames only
if(use_asynchronous)
file->start_video_decode_thread();
else
file->stop_video_thread();
if(use_cache) file->set_cache_frames(1);
int64_t normalized_position = (int64_t)(corrected_position *
asset->frame_rate /
renderengine->get_edl()->session->frame_rate);
file->set_video_position(normalized_position,
0);
file->read_frame(video_out);
if(use_cache) file->set_cache_frames(0);
renderengine->get_vcache()->check_in(asset);
}
}
else
if(playable_edit)
{
if(debug) printf("VRender::process_buffer %d\n", __LINE__);
result = ((VEdit*)playable_edit)->read_frame(video_out,
current_position,
renderengine->command->get_direction(),
renderengine->get_vcache(),
1,
use_cache,
use_asynchronous);
if(debug) printf("VRender::process_buffer %d\n", __LINE__);
}
video_out->set_opengl_state(VFrame::RAM);
}
else
// Read into virtual console
{
// process this buffer now in the virtual console
result = ((VirtualVConsole*)vconsole)->process_buffer(input_position,
use_opengl);
}
return result;
}
// Determine if virtual console is needed
int VRender::get_use_vconsole(VEdit* *playable_edit,
int64_t position, int &use_brender)
{
*playable_edit = 0;
// Background rendering completed
if((use_brender = renderengine->brender_available(position,
renderengine->command->get_direction())) != 0)
return 0;
// Descend into EDL nest
return renderengine->get_edl()->get_use_vconsole(playable_edit,
position,
renderengine->command->get_direction(),
vconsole->playable_tracks);
}
int VRender::get_colormodel(VEdit *playable_edit,
int use_vconsole, int use_brender)
{
int colormodel = renderengine->get_edl()->session->color_model;
if(!use_vconsole && !renderengine->command->single_frame())
{
// Get best colormodel supported by the file
int driver = renderengine->config->vconfig->driver;
File *file;
Asset *asset;
if(use_brender)
{
asset = renderengine->preferences->brender_asset;
}
else
{
int64_t source_position = 0;
asset = playable_edit->get_nested_asset(&source_position,
current_position,
renderengine->command->get_direction());
}
if(asset)
{
file = renderengine->get_vcache()->check_out(asset,
renderengine->get_edl());
if(file)
{
colormodel = file->get_best_colormodel(driver);
renderengine->get_vcache()->check_in(asset);
}
}
}
return colormodel;
}
void VRender::run()
{
int reconfigure;
const int debug = 0;
// Want to know how many samples rendering each frame takes.
// Then use this number to predict the next frame that should be rendered.
// Be suspicious of frames that render late so have a countdown
// before we start dropping.
int64_t current_sample, start_sample, end_sample; // Absolute counts.
int64_t skip_countdown = VRENDER_THRESHOLD; // frames remaining until drop
int64_t delay_countdown = VRENDER_THRESHOLD; // Frames remaining until delay
// Number of frames before next reconfigure
int64_t current_input_length;
// Number of frames to skip.
int64_t frame_step = 1;
int use_opengl = (renderengine->video &&
renderengine->video->out_config->driver == PLAYBACK_X11_GL);
first_frame = 1;
// Number of frames since start of rendering
session_frame = 0;
framerate_counter = 0;
framerate_timer.update();
start_lock->unlock();
if(debug) printf("VRender::run %d\n", __LINE__);
while(!done && !interrupt )
{
// Perform the most time consuming part of frame decompression now.
// Want the condition before, since only 1 frame is rendered
// and the number of frames skipped after this frame varies.
current_input_length = 1;
reconfigure = vconsole->test_reconfigure(current_position,
current_input_length);
if(debug) printf("VRender::run %d\n", __LINE__);
if(reconfigure) restart_playback();
if(debug) printf("VRender::run %d\n", __LINE__);
process_buffer(current_position, use_opengl);
if(debug) printf("VRender::run %d\n", __LINE__);
if(renderengine->command->single_frame())
{
if(debug) printf("VRender::run %d\n", __LINE__);
flash_output();
frame_step = 1;
done = 1;
}
else
// Perform synchronization
{
// Determine the delay until the frame needs to be shown.
current_sample = (int64_t)(renderengine->sync_position() *
renderengine->command->get_speed());
// latest sample at which the frame can be shown.
end_sample = Units::tosamples(session_frame,
renderengine->get_edl()->session->sample_rate,
renderengine->get_edl()->session->frame_rate);
// earliest sample by which the frame needs to be shown.
start_sample = Units::tosamples(session_frame - 1,
renderengine->get_edl()->session->sample_rate,
renderengine->get_edl()->session->frame_rate);
if(first_frame || end_sample < current_sample)
{
// Frame rendered late or this is the first frame. Flash it now.
//printf("VRender::run %d\n", __LINE__);
flash_output();
if(renderengine->get_edl()->session->video_every_frame)
{
// User wants every frame.
frame_step = 1;
}
else
if(skip_countdown > 0)
{
// Maybe just a freak.
frame_step = 1;
skip_countdown--;
}
else
{
// Get the frames to skip.
delay_countdown = VRENDER_THRESHOLD;
frame_step = 1;
frame_step += (int64_t)Units::toframes(current_sample,
renderengine->get_edl()->session->sample_rate,
renderengine->get_edl()->session->frame_rate);
frame_step -= (int64_t)Units::toframes(end_sample,
renderengine->get_edl()->session->sample_rate,
renderengine->get_edl()->session->frame_rate);
}
}
else
{
// Frame rendered early or just in time.
frame_step = 1;
if(delay_countdown > 0)
{
// Maybe just a freak
delay_countdown--;
}
else
{
skip_countdown = VRENDER_THRESHOLD;
if(start_sample > current_sample)
{
int64_t delay_time = (int64_t)((float)(start_sample - current_sample) *
1000 / renderengine->get_edl()->session->sample_rate);
if( delay_time > 1000 ) delay_time = 1000;
timer.delay(delay_time);
}
else
{
// Came after the earliest sample so keep going
}
}
// Flash frame now.
//printf("VRender::run %d " _LD "\n", __LINE__, current_input_length);
flash_output();
}
}
if(debug) printf("VRender::run %d\n", __LINE__);
// Trigger audio to start
if(first_frame)
{
renderengine->first_frame_lock->unlock();
first_frame = 0;
renderengine->reset_sync_position();
}
if(debug) printf("VRender::run %d\n", __LINE__);
session_frame += frame_step;
// advance position in project
current_input_length = frame_step;
// Subtract frame_step in a loop to allow looped playback to drain
// printf("VRender::run %d %d %d %d\n",
// __LINE__,
// done,
// frame_step,
// current_input_length);
while(frame_step && current_input_length)
{
// trim current_input_length to range
get_boundaries(current_input_length);
// advance 1 frame
advance_position(current_input_length);
frame_step -= current_input_length;
current_input_length = frame_step;
if(done) break;
// printf("VRender::run %d %d %d %d\n",
// __LINE__,
// done,
// frame_step,
// current_input_length);
}
if(debug) printf("VRender::run %d current_position=" _LD " done=%d\n",
__LINE__, current_position, done);
// Update tracking.
if(renderengine->command->realtime &&
renderengine->playback_engine &&
renderengine->command->command != CURRENT_FRAME)
{
renderengine->playback_engine->update_tracking(fromunits(current_position));
}
if(debug) printf("VRender::run %d\n", __LINE__);
// Calculate the framerate counter
framerate_counter++;
if(framerate_counter >= renderengine->get_edl()->session->frame_rate &&
renderengine->command->realtime)
{
renderengine->update_framerate((float)framerate_counter /
((float)framerate_timer.get_difference() / 1000));
framerate_counter = 0;
framerate_timer.update();
}
if(debug) printf("VRender::run %d done=%d\n", __LINE__, done);
if( !interrupt )
interrupt = renderengine->video->interrupt;
}
// In case we were interrupted before the first loop
renderengine->first_frame_lock->unlock();
stop_plugins();
if(debug) printf("VRender::run %d done=%d\n", __LINE__, done);
}
int VRender::start_playback()
{
// start reading input and sending to vrenderthread
// use a thread only if there's a video device
if(renderengine->command->realtime)
{
start();
}
return 0;
}
int64_t VRender::tounits(double position, int round)
{
if(round)
return Units::round(position * renderengine->get_edl()->session->frame_rate);
else
return Units::to_int64(position * renderengine->get_edl()->session->frame_rate);
}
double VRender::fromunits(int64_t position)
{
return (double)position / renderengine->get_edl()->session->frame_rate;
}
| triceratops1/cinelerra | cinelerra-4.6/cinelerra-4.6.mod/cinelerra/vrender.C | C++ | gpl-2.0 | 13,523 |
import os
from core import aleinst
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
class Formula():
def __init__(self, request):
self.request = request
def search(self):
package = aleinst.Aleinst(request=self.request[0:])
package.search()
def main(self):
self.search() | darker0n/ale | core/Formula/install.py | Python | gpl-2.0 | 326 |
package com.austinv11.peripheralsplusplus.capabilities.nano;
import net.minecraft.entity.Entity;
import javax.annotation.Nullable;
import java.util.UUID;
/**
* Capability interface for entities that will hold nano bots
*/
public interface NanoBotHolder {
/**
* Get the bots the entity is infested with
* @return number of bots on entity
*/
int getBots();
/**
* Set the bots on an entity
* @param bots number of bots to set on the entity
*/
void setBots(int bots);
/**
* Set the antenna UUID the item is registered to
* @param antennaIdentifier antenna UUID
*/
void setAntenna(UUID antennaIdentifier);
/**
* Get the registered antenna id
* @return antenna UUID
*/
@Nullable
UUID getAntenna();
/**
* Get the entity that this capability is handling
* @return the entity that the bots are attached to
*/
@Nullable
Entity getEntity();
/**
* Sets the entity that the bots are attached to
* If there is no entity set the entity will not be registered with the antenna registry on (re)load.
* This should be set on the {@link net.minecraftforge.event.AttachCapabilitiesEvent<Entity>} event
* @param entity entity the bots are on
*/
void setEntity(Entity entity);
}
| rolandoislas/PeripheralsPlusPlus | src/main/java/com/austinv11/peripheralsplusplus/capabilities/nano/NanoBotHolder.java | Java | gpl-2.0 | 1,324 |
package impl;
public class StopWordsFilter {
private static String stopWordsList[] = { "的", "我们", "要", "自己", "之", "将",
"“", "”", ",", "(", ")", "后", "应", "到", "某", "后", "个", "是", "位", "新",
"一", "两", "在", "中", "或", "有", "更", "好", "" };// 常用停用词
public static boolean IsStopWord(String word) {
for (int i = 0; i < stopWordsList.length; ++i) {
if (word.equalsIgnoreCase(stopWordsList[i]))
return true;
}
return false;
}
}
| kevin-ww/text.classfication | src/main/java/impl/StopWordsFilter.java | Java | gpl-2.0 | 536 |
<?php
namespace Drupal\Tests\extlink\FunctionalJavascript;
/**
* Testing the basic functionality of External Links.
*
* @group Extlink
*/
class ExtlinkTestTarget extends ExtlinkTestBase {
/**
* Checks to see if extlink adds target and rel attributes.
*/
public function testExtlinkTarget() {
// Target Enabled.
$this->config('extlink.settings')->set('extlink_target', TRUE)->save();
// Login.
$this->drupalLogin($this->adminUser);
// Create a node with an external link.
$settings = [
'type' => 'page',
'title' => 'test page',
'body' => [
[
'value' => '<p><a href="http://google.com">Google!</a></p>',
'format' => $this->emptyFormat->id(),
],
],
];
$node = $this->drupalCreateNode($settings);
// Get the page.
$this->drupalGet($node->toUrl());
$page = $this->getSession()->getPage();
$this->createScreenshot(\Drupal::root() . '/sites/default/files/simpletest/Extlink.png');
$this->assertSession()->statusCodeEquals(200);
$this->assertTrue($page->hasLink('Google!'));
// Test that the page has the external link span.
$externalLink = $page->find('css', 'span.ext');
$this->assertTrue($externalLink->isVisible(), 'External Link Exists.');
$link = $page->findLink('Google!');
// Link should have target attribute.
$this->assertTrue($link->getAttribute('target') === '_blank', 'ExtLink target attribute is not "_blank".');
// Link should have rel attribute 'noopener noreferrer'
$this->assertTrue($link->getAttribute('rel') === 'noopener noreferrer' || $link->getAttribute('rel') === 'noreferrer noopener', 'ExtLink rel attribute is not "noopener noreferrer".');
}
/**
* Checks to see if extlink changes the target attribute
*/
public function testExtlinkTargetNoOverride() {
// Target Enabled.
$this->config('extlink.settings')->set('extlink_target', TRUE)->save();
$this->config('extlink.settings')->set('extlink_target_no_override', TRUE)->save();
// Login.
$this->drupalLogin($this->adminUser);
// Create a node with an external link.
$settings = [
'type' => 'page',
'title' => 'test page',
'body' => [
[
'value' => '<p><a href="http://google.com" target="_self">Google!</a></p>',
'format' => $this->emptyFormat->id(),
],
],
];
$node = $this->drupalCreateNode($settings);
// Get the page.
$this->drupalGet($node->toUrl());
$page = $this->getSession()->getPage();
$this->createScreenshot(\Drupal::root() . '/sites/default/files/simpletest/Extlink.png');
$this->assertSession()->statusCodeEquals(200);
$this->assertTrue($page->hasLink('Google!'));
// Test that the page has the external link span.
$externalLink = $page->find('css', 'span.ext');
$this->assertTrue($externalLink->isVisible(), 'External Link Exists.');
$link = $page->findLink('Google!');
// Link should have target attribute.
$this->assertTrue($link->getAttribute('target') === '_self', 'ExtLink target attribute is not "_self".');
// Link should have rel attribute 'noopener noreferrer'
$this->assertTrue($link->getAttribute('rel') === 'noopener noreferrer' || $link->getAttribute('rel') === 'noreferrer noopener', 'ExtLink rel attribute is not "noopener noreferrer".');
}
}
| dbethala/longwood-volunteers | modules/extlink/tests/src/FunctionalJavascript/ExtlinkTestTarget.php | PHP | gpl-2.0 | 3,385 |
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom, Francis Noel
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
*
* 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 1 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/>.
*/
using System.Windows.Forms;
using Greenshot.IniFile;
using GreenshotPlugin.Core;
namespace GreenshotDropboxPlugin {
/// <summary>
/// Description of ImgurConfiguration.
/// </summary>
[IniSection("Dropbox", Description = "Greenshot Dropbox Plugin configuration")]
public class DropboxPluginConfiguration : IniSection {
[IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
public OutputFormat UploadFormat;
[IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
public int UploadJpegQuality;
[IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send Dropbox link to clipboard.", DefaultValue = "true")]
public bool AfterUploadLinkToClipBoard;
[IniProperty("DropboxToken", Description = "The Dropbox token", Encrypted = true, ExcludeIfNull = true)]
public string DropboxToken;
[IniProperty("DropboxTokenSecret", Description = "The Dropbox token secret", Encrypted = true, ExcludeIfNull = true)]
public string DropboxTokenSecret;
/// <summary>
/// A form for token
/// </summary>
/// <returns>bool true if OK was pressed, false if cancel</returns>
public bool ShowConfigDialog() {
DialogResult result = new SettingsForm().ShowDialog();
if (result == DialogResult.OK) {
return true;
}
return false;
}
}
}
| BartDM/GreenshotPlugin | GreenshotDropboxPlugin/DropboxPluginConfiguration.cs | C# | gpl-2.0 | 2,377 |
# -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn
#
# Copyright (C) 2009 Collabora Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
class MediaRelay(object):
def __init__(self):
self.username = None
self.password = None
self.ip = ""
self.port = 0
def __repr__(self):
return "<Media Relay: %s %i username=\"%s\" password=\"%s\">" % (self.ip,
self.port, self.username, self.password)
| Kjir/papyon | papyon/media/relay.py | Python | gpl-2.0 | 1,127 |
/***************************************************************************
main.cpp
(c) 2000-2013 Benoît Minisini <gambas@users.sourceforge.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, 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.
***************************************************************************/
#define __MAIN_CPP
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include "gb_common.h"
#include "c_clipper.h"
#include "main.h"
extern "C" {
GB_INTERFACE GB EXPORT;
GEOM_INTERFACE GEOM EXPORT;
GB_DESC *GB_CLASSES [] EXPORT =
{
PolygonDesc,
ClipperDesc,
NULL
};
const char *GB_INCLUDE EXPORT = "gb.geom";
int EXPORT GB_INIT(void)
{
GB.Component.Load("gb.geom");
GB.GetInterface("gb.geom", GEOM_INTERFACE_VERSION, &GEOM);
return 0;
}
void EXPORT GB_EXIT()
{
}
}
| justlostintime/gambas | main/lib/clipper/main.cpp | C++ | gpl-2.0 | 1,456 |
using UnityEngine;
using System.Collections;
public class AIController : MonoBehaviour {
Transform lineStart, lineEnd;
GameObject healthBar;
float health = 250;
float maxHealth = 250;
GameObject character;
Stats stats;
Animator animateState;
// Use this for initialization
void Start () {
animateState = transform.gameObject.GetComponent<Animator> ();
character = GameObject.Find ("Character");
stats = GameObject.Find ("Canvas").GetComponent<Stats> ();
lineStart = transform.FindChild ("Start").gameObject.transform;
lineEnd = transform.FindChild ("End").gameObject.transform;
healthBar = new GameObject ("HealthBar");
healthBar.AddComponent<SpriteRenderer> ();
healthBar.GetComponent<SpriteRenderer> ().sprite = Resources.Load ("HealthBarVisual", typeof(Sprite)) as Sprite;
healthBar.transform.parent = this.transform;
healthBar.transform.position = new Vector2 (transform.position.x, transform.position.y + .75f);
if (transform.FindChild ("AttackSpawn") != null) {
//this is a caster
health = 100;
maxHealth = 100;
InvokeRepeating ("FireWeapon", 0, .75f);
} else { //this is a knight
InvokeRepeating ("Attack", 0, .75f);
}
}
// Update is called once per frame
void Update () {
//if there is a character in front of this entity
if (Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Player")) || Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Enemy"))) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, GetComponent<Rigidbody2D> ().velocity.y);
} else if (Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Ground"))) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, 8);
} else if (transform.tag == "Enemy") {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (-2, GetComponent<Rigidbody2D> ().velocity.y);
} else {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (2, GetComponent<Rigidbody2D> ().velocity.y);
}
}
public void RemoveHealth(float amount)
{
health -= amount;
healthBar.transform.localScale = new Vector3 (health / maxHealth, 1, 1);
if (health <= 0 && transform.tag == "Enemy") {
stats.ChangeXP (10);
stats.ChangeGold (25);
GameObject gold = Instantiate (Resources.Load ("gold")) as GameObject;
gold.transform.position = new Vector2 (transform.position.x, transform.position.y + .3f);
GameObject xp = Instantiate (Resources.Load ("xp")) as GameObject;
xp.transform.position = new Vector2 (transform.position.x, transform.position.y + .5f);
Destroy (this.gameObject);
} else if (health <= 0) {
Destroy (this.gameObject);
}
}
void Attack()
{
RaycastHit2D hit = Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Player"));
if (transform.tag == "Enemy" && Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Player")) && hit.collider.transform.name == "Character") {
hit.collider.transform.gameObject.GetComponent<CharacterController>().RemoveHealth(20);
animateState.SetBool ("isAttacking", true);
}
else if (transform.tag == "Enemy" && Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Player"))) {
hit.collider.transform.gameObject.GetComponent<AIController>().RemoveHealth(20);
animateState.SetBool ("isAttacking", true);
} else if (transform.tag == "Player" && Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Enemy"))) {
hit = Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Enemy"));
hit.collider.transform.gameObject.GetComponent<AIController>().RemoveHealth(20);
animateState.SetBool ("isAttacking", true);
} else {
animateState.SetBool ("isAttacking", false);
}
}
void FireWeapon()
{
if (transform.tag == "Enemy") {
float distance = 100;
Transform target = transform;
bool targetFound = false;
if (Vector2.Distance (this.transform.position, character.transform.position) < 10)
{
target = character.transform;
targetFound = true;
}
if (!targetFound)
{
for(int i = 0; i < GameObject.Find ("AllySpawnLocation").transform.childCount; i++)
{
if (Vector2.Distance (this.transform.position, GameObject.Find ("AllySpawnLocation").transform.GetChild(i).transform.position) < 10) {
if (Vector2.Distance (this.transform.position, GameObject.Find ("AllySpawnLocation").transform.GetChild(i).transform.position) < distance)
{
distance = Vector2.Distance (this.transform.position, GameObject.Find ("AllySpawnLocation").transform.GetChild(i).transform.position);
target = GameObject.Find ("AllySpawnLocation").transform.GetChild(i).transform;
targetFound = true;
}
}
}
}
if (targetFound)
{
GameObject IceBall = Instantiate(Resources.Load("Iceball")) as GameObject;
IceBall.GetComponent<IceBolt>().SetTarget = target;
IceBall.transform.position = transform.FindChild ("AttackSpawn").transform.position;
Vector2 direction = new Vector2 (target.position.x - IceBall.transform.position.x, target.position.y - IceBall.transform.position.y);
direction.Normalize ();
IceBall.GetComponent<Rigidbody2D> ().velocity = direction * 10;
}
}
else if (transform.tag == "Player") {
float distance = 100;
Transform target = transform;
bool targetFound = false;
for(int i = 0; i < GameObject.Find ("EnemySpawnLocation").transform.childCount; i++)
{
if (Vector2.Distance (this.transform.position, GameObject.Find ("EnemySpawnLocation").transform.GetChild(i).transform.position) < 10) {
if (Vector2.Distance (this.transform.position, GameObject.Find ("EnemySpawnLocation").transform.GetChild(i).transform.position) < distance)
{
distance = Vector2.Distance (this.transform.position, GameObject.Find ("EnemySpawnLocation").transform.GetChild(i).transform.position);
target = GameObject.Find ("EnemySpawnLocation").transform.GetChild(i).transform;
targetFound = true;
}
}
}
if (targetFound)
{
GameObject IceBall = Instantiate(Resources.Load("Iceball")) as GameObject;
IceBall.GetComponent<IceBolt>().SetTarget = target;
IceBall.transform.position = transform.FindChild ("AttackSpawn").transform.position;
Vector2 direction = new Vector2 (target.position.x - IceBall.transform.position.x, target.position.y - IceBall.transform.position.y);
direction.Normalize ();
IceBall.GetComponent<Rigidbody2D> ().velocity = direction * 10;
}
}
// if (Vector2.Distance (character.transform.position, transform.position) < 10) {
// //attack player
// GameObject IceBall = Instantiate(Resources.Load("Iceball")) as GameObject;
// IceBall.GetComponent<IceBolt>().SetTarget = "Player";
// IceBall.transform.position = transform.FindChild ("AttackSpawn").transform.position;
// Vector2 direction = new Vector2 (character.transform.position.x - IceBall.transform.position.x, character.transform.position.y - IceBall.transform.position.y);
// direction.Normalize ();
// IceBall.GetComponent<Rigidbody2D> ().velocity = direction * 10;
// }
}
}
| UCCS-GDD/CS3350-ChampionOfTheNine | ChampionsOfTheNinePrototype/Assets/Scripts/AIController.cs | C# | gpl-2.0 | 7,286 |
<?php
set_include_path(get_include_path().PATH_SEPARATOR.realpath('../../includes').PATH_SEPARATOR.realpath('../../').PATH_SEPARATOR.realpath('../').PATH_SEPARATOR);
$dir = realpath(getcwd());
chdir("../../");
require_once ( 'WebStart.php');
require_once( 'Wiki.php' );
chdir($dir);
$userRun = $wgUser; #The user that runs this script
$user1 = User::newFromName("ThomasKelder");
$user2 = User::newFromName("TestUser");
$admin = User::newFromName("Thomas");
$anon = User::newFromId(0);
$page_id = Title::newFromText('WP4', NS_PATHWAY)->getArticleId();
$title = Title::newFromId($page_id);
$mgr = new PermissionManager($page_id);
Test::echoStart("No permissions set");
#Remove all permissions from page
$mgr->clearPermissions();
##* can read
$wgUser = $anon;
$can = $title->userCan("read");
Test::assert("anonymous can read", $can, true);
##* can't edit
$wgUser = $anon;
$can = $title->userCan('edit');
Test::assert("anonymous can't edit", $can, false);
##users can read/edit
$wgUser = $user1;
$can = $title->userCan("read");
Test::assert("Users can read", $can, true);
$can = $title->userCan('edit');
Test::assert("Users can edit", $can, true);
#Set private for user1
Test::echoStart("Setting page private for user1");
$pms = new PagePermissions($page_id);
$pms->addReadWrite($user1->getId());
$pms->addManage($user1->getId());
$mgr->setPermissions($pms);
##user1 can read/write/manage
$wgUser = $user1;
$can = $title->userCan("read");
Test::assert("User1 can read", $can, true);
$can = $title->userCan('edit');
Test::assert("User1 can edit", $can, true);
$can = $title->userCan(PermissionManager::$ACTION_MANAGE);
Test::assert("User1 can manage", $can, true);
##admin can read/write/manage
$wgUser = $admin;
$can = $title->userCan("read");
Test::assert("User1 can read", $can, true);
$can = $title->userCan('edit');
Test::assert("User1 can edit", $can, true);
$can = $title->userCan(PermissionManager::$ACTION_MANAGE);
Test::assert("User1 can manage", $can, true);
##user2 cannot read/write/manage
$wgUser = $user2;
$can = $title->userCan("read");
Test::assert("User2 can't read", $can, false);
$can = $title->userCan('edit');
Test::assert("User2 can't read", $can, false);
$can = $title->userCan(PermissionManager::$ACTION_MANAGE);
Test::assert("User2 can't manage", $can, false);
##anonymous cannot read/write/manage
$wgUser = $anon;
$can = $title->userCan("read");
Test::assert("Anonymous can't read", $can, false);
$can = $title->userCan('edit');
Test::assert("Anonymous can't edit", $can, false);
#Add user2
Test::echoStart("Add user2 to read/write users");
$wgUser = $userRun;
$pms->addReadWrite($user2->getId());
$mgr->setPermissions($pms);
##user2 can read/write/manage
$wgUser = $user2;
$can = $title->userCan("read");
Test::assert("User2 can read", $can, true);
$can = $title->userCan('edit');
Test::assert("User1 can edit", $can, true);
##user1 can still read/write/manage
$wgUser = $user1;
$can = $title->userCan("read");
Test::assert("User1 can still read", $can, true);
$can = $title->userCan('edit');
Test::assert("User1 can still edit", $can, true);
#Remove read/write permissions for user2
Test::echoStart("Setting page private for user1");
$pms->clearPermissions($user2->getId());
$mgr->setPermissions($pms);
##user1 can read/write/manage
$wgUser = $user1;
$can = $title->userCan("read");
Test::assert("User1 can read", $can, true);
$can = $title->userCan('edit');
Test::assert("User1 can edit", $can, true);
##user2 cannot read/write/manage
$wgUser = $user2;
$can = $title->userCan("read");
Test::assert("User2 can't read", $can, false);
$can = $title->userCan('edit');
Test::assert("User2 can't read", $can, false);
#Set expiration date to past
##permissions should be removed
Test::echoStart("Simulating expiration");
$wgUser = $userRun;
$pms->setExpires(wfTimestamp(TS_MW) - 1);
$mgr->setPermissions($pms);
##user2 can read/edit again
$wgUser = $user2;
$can = $title->userCan("read");
Test::assert("User2 can read again", $can, true);
$can = $title->userCan('edit');
Test::assert("User2 can edit again", $can, true);
class Test {
static function assert($test, $value, $expected) {
echo("$test: ");
if($value != $expected) {
$e = new Exception();
echo("\t<font color='red'>Fail!</font>: value '$value' doesn't equal expected: '$expected'" .
"<BR>\n" . $e->getTraceAsString() . "<BR>\n");
} else {
echo("\t<font color='green'>Pass!</font><BR>\n");
}
}
static function echoStart($case) {
echo("<h3>Testing $case</h3>\n");
}
}
| hexmode/wikipathways.org | wpi/test/testPrivatePathways.php | PHP | gpl-2.0 | 4,499 |
# ==Paramerer Controller
# This manages the display of a parameter
#
# == Copyright
# Copyright © 2006 Robert Shell, Alces Ltd All Rights Reserved
# See license agreement for additional rights
#
#
class Organize::ParametersController < ApplicationController
use_authorization :organization,
:use => [:list,:show,:new,:create,:edit,:update,:destroy]
def index
list
render :action => 'list'
end
def list
@assay = Assay.load(params[:id])
@report = Biorails::ReportLibrary.parameter_list("ParameterList")
end
def show
@parameter = Parameter.find(params[:id])
end
end
| rshell/biorails | app/controllers/organize/parameters_controller.rb | Ruby | gpl-2.0 | 632 |
using System.Drawing;
using System.Threading.Tasks;
namespace GoF_TryOut.Proxy.Straight {
public class Client {
public Client() {
var myImage = new MyImage("");
var bitmap = myImage.GetImage() ?? myImage.GetPreview();
}
}
public class MyImage {
private readonly string path;
private readonly Bitmap preview;
private Bitmap fullImage;
private Task<Bitmap> task;
public MyImage(string path) {
this.path = path;
preview = new Bitmap(path);
}
private Bitmap LoadImage() {
return new Bitmap(path);
}
public Bitmap GetPreview() {
return preview;
}
public Bitmap GetImage() {
task = new Task<Bitmap>(LoadImage);
task.Start();
if (task.IsCompleted) {
if (fullImage == null) {
fullImage = task.Result;
return fullImage;
}
return fullImage;
}
return preview;
}
}
} | VioletTape/Trainings | DEV-001_GoF/GoF_TryOut/GoF_TryOut/Proxy/Straight/Client.cs | C# | gpl-2.0 | 1,114 |
package core
import (
"github.com/justinsb/gova/log"
)
type CleanupOldMachines struct {
huddle *Huddle
state map[string]int
deleteThreshold int
}
func (self *CleanupOldMachines) Run() error {
state, err := self.huddle.cleanupOldMachines(self.state, self.deleteThreshold)
if err != nil {
log.Warn("Error cleaning up old machines", err)
return err
}
self.state = state
return nil
}
func (self *CleanupOldMachines) String() string {
return "CleanupOldMachines"
}
| jxaas/jxaas | core/scheduled_machine_cleanup.go | GO | gpl-2.0 | 490 |
<?php
/**
* @version $Id: AbstractItem.php 30067 2016-03-08 13:44:25Z matias $
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2016 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
abstract class RokCommon_Form_AbstractItem implements RokCommon_Form_IItem
{
/**
* @var RokCommon_Service_Container
*/
protected $container;
/**
* The JForm object of the form attached to the form field.
*
* @var object
* @since 1.6
*/
protected $form;
/**
* The form control prefix for field names from the JForm object attached to the form field.
*
* @var string
* @since 1.6
*/
protected $formControl;
/**
* The hidden state for the form field.
*
* @var boolean
* @since 1.6
*/
protected $hidden = false;
/**
* True to translate the field label string.
* True to translate the field label string.
*
* @var boolean
* @since 1.6
*/
protected $translateLabel = true;
/**
* True to translate the field description string.
*
* @var boolean
* @since 1.6
*/
protected $translateDescription = true;
/**
* The JXMLElement object of the <field /> XML element that describes the form field.
*
* @var object
* @since 1.6
*/
protected $element;
/**
* The document id for the form field.
*
* @var string
* @since 1.6
*/
protected $id;
/**
* The input for the form field.
*
* @var string
* @since 1.6
*/
protected $input;
/**
* The label for the form field.
*
* @var string
* @since 1.6
*/
protected $label;
/**
* The name of the form field.
*
* @var string
* @since 1.6
*/
protected $name;
/**
* The name of the field.
*
* @var string
* @since 1.6
*/
protected $fieldname;
/**
* The group of the field.
*
* @var string
* @since 1.6
*/
protected $group;
/**
* The form field type.
*
* @var string
* @since 1.6
*/
protected $type;
protected $basetype;
/**
* The value of the form field.
*
* @var mixed
* @since 1.6
*/
protected $value;
/**
* @var string
*/
protected $panel_position = 'left';
/**
* @var bool
*/
protected $show_label = true;
/**
* @var mixed
*/
protected $base_value;
/**
* @var bool
*/
protected $customized = false;
/**
* @var bool
*/
protected $setinoverride = true;
/**
* @var string
*/
protected $class;
/**
* @var bool
*/
protected $detached;
/**
* @var mixed
*/
protected $default;
protected $assets_content;
/**
* Method to instantiate the form field object.
*
* @param object $form The form to attach to the form field object.
*
* @return void
* @since 1.6
*/
public function __construct(RokCommon_Form $form = null)
{
$this->container = RokCommon_Service::getContainer();
// If there is a form passed into the constructor set the form and form control properties.
if ($form instanceof RokCommon_Form) {
$this->form = $form;
$this->formControl = $form->getFormControl();
}
}
/**
* @param $name
* @param $value
*
* @return void
*/
public function __set($name, $value)
{
if (property_exists($this, $name)) {
$this->{$name} = $value;
}
}
/**
* Method to get the field title.
*
* @return string The field title.
* @since 11.1
*/
public function getTitle()
{
// Initialise variables.
$title = '';
if ($this->hidden) {
return $title;
}
// Get the label text from the XML element, defaulting to the element name.
$title = $this->element['label'] ? (string)$this->element['label'] : (string)$this->element['name'];
$title = $this->translateLabel ? JText::_($title) : $title;
return $title;
}
/**
* Method to get the field label markup.
*
* @return string The field label markup.
* @since 1.6
*/
public function getLabel()
{
// Initialise variables.
$label = '';
if ($this->hidden) {
return $label;
}
// Get the label text from the XML element, defaulting to the element name.
$text = $this->element['label'] ? (string)$this->element['label'] : (string)$this->element['name'];
$text = $this->translateLabel ? JText::_($text) : $text;
// Build the class for the label.
$class = !empty($this->description) ? 'hasTip' : '';
$class = $this->required == true ? $class . ' required' : $class;
// Add the opening label tag and main attributes attributes.
$label .= '<label id="' . $this->id . '-lbl" for="' . $this->id . '" class="' . $class . '"';
// If a description is specified, use it to build a tooltip.
if (!empty($this->description)) {
$label .= ' title="' . htmlspecialchars(trim($text, ':') . '::' . ($this->translateDescription ? JText::_($this->description) : $this->description), ENT_COMPAT, 'UTF-8') . '"';
}
// Add the label text and closing tag.
$label .= '>' . $text . '</label>';
return $label;
}
/**
* Method to attach a JForm object to the field.
*
* @param \RokCommon_Form $form The JForm object to attach to the form field.
*
* @return object The form field object so that the method can be used in a chain.
* @since 1.6
*/
public function setForm(RokCommon_Form $form)
{
$this->form = $form;
$this->formControl = $form->getFormControl();
return $this;
}
/**
* Method to get the name used for the field input tag.
*
* @param string $fieldName The field element name.
*
* @return string The name to be used for the field input tag.
*
* @since 11.1
*/
public function getName($fieldName)
{
/** @var $namehandler RokCommon_Form_IItemNameHandler */
$namehandler = $this->container->getService('form.namehandler');
return $namehandler->getName($fieldName, $this->group, $this->formControl, false);
}
/**
* Method to get the id used for the field input tag.
*
* @param string $fieldId The field element id.
* @param string $fieldName The field element name.
*
* @return string The id to be used for the field input tag.
* @since 1.6
*/
public function getId($fieldId, $fieldName)
{
/** @var $namehandler RokCommon_Form_IItemNameHandler */
$namehandler = $this->container->getService('form.namehandler');
return $namehandler->getId($fieldName, $fieldId, $this->group, $this->formControl, false);
}
/**
* Method to get certain otherwise inaccessible properties from the form field object.
*
* @param string $name The property name for which to the the value.
*
* @return mixed|null The property value or null.
* @since 1.6
*/
public function __get($name)
{
switch ($name) {
case 'input':
// If the input hasn't yet been generated, generate it.
if (empty($this->input)) {
$this->input = $this->getInput();
}
return $this->input;
break;
case 'label':
// If the label hasn't yet been generated, generate it.
if (empty($this->label)) {
$this->label = $this->getLabel();
}
return $this->label;
break;
case 'title':
return $this->getTitle();
break;
default :
if (property_exists($this, $name) && isset($this->{$name})) {
return $this->{$name};
} elseif (method_exists($this, 'get' . ucfirst($name))) {
return call_user_func(array($this, 'get' . ucfirst($name)));
} elseif (property_exists($this, $name)) {
return $this->{$name};
} elseif (isset($this->element[$name])) {
return (string)$this->element[$name];
} else {
return null;
}
break;
}
}
/**
* Method to attach a JForm object to the field.
*
* @param object $element The JXMLElement object representing the <field /> tag for the
* form field object.
* @param mixed $value The form field default value for display.
* @param string $group The field name group control value. This acts as as an array
* container for the field. For example if the field has name="foo"
* and the group value is set to "bar" then the full field name
* would end up being "bar[foo]".
*
* @return boolean True on success.
* @since 1.6
*/
public function setup(& $element, $value, $group = null)
{
global $gantry;
// Make sure there is a valid JFormField XML element.
if (!($element instanceof RokCommon_XMLElement)) {
return false;
}
// Reset the input and label values.
$this->input = null;
$this->label = null;
// Set the xml element object.
$this->element = $element;
// Get some important attributes from the form field element.
$class = (string)$element['class'];
$id = (string)$element['id'];
$name = (string)$element['name'];
$type = (string)$element['type'];
$panel_position = (string)$element['panel_position'];
$this->show_label = ((string)$element['show_label'] == 'false') ? false : true;
$this->setinoverride = ((string)$element['setinoverride'] == 'false') ? false : true;
$default = (string)$element['default'];
// if (!empty($name)) {
// if (empty($group)) {
// $gantry_name = $name;
// } else {
// $groups = explode('.', $group);
// if (count($groups > 0)) {
// //array_shift($groups);
// $groups[] = $name;
// $gantry_name = implode('-', $groups);
// }
// }
// // TODO set this up to get for Default not for RokCommon param value
// //$this->base_value = $gantry->get($gantry_name, null);
// }
// Set the field description text.
$this->description = (string)$element['description'];
// Set the visibility.
$this->hidden = ((string)$element['type'] == 'hidden' || (string)$element['hidden'] == 'true');
// Determine whether to translate the field label and/or description.
$this->translateLabel = !((string)$this->element['translate_label'] == 'false' || (string)$this->element['translate_label'] == '0');
$this->translateDescription = !((string)$this->element['translate_description'] == 'false' || (string)$this->element['translate_description'] == '0');
// Set the group of the field.
$this->group = $group;
// Set the field name and id.
$this->fieldname = $name;
$this->name = $this->getName($name, $group);
$this->id = $this->getId($id, $name, $group);
$this->type = $type;
$this->class = $class;
if ($panel_position != null) $this->panel_position = $panel_position;
// Set the field default value.
$this->value = $value;
if (null != $this->default && $this->default != $this->value) $this->customized = true;
return true;
}
/**
* @static
* @return void
*/
public static function initialize()
{
}
/**
* @static
* @return void
*/
public static function finalize()
{
}
/**
* @param $callback
*
* @return mixed
*/
public function render($callback)
{
return call_user_func_array($callback, array($this));
}
}
| bmacenbacher/multison | libraries/rokcommon/RokCommon/Form/AbstractItem.php | PHP | gpl-2.0 | 11,359 |
/* Copyright (C) 2006 - 2011 ScriptDev2 <http://www.scriptdev2.com/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Instance_Dark_Portal
SD%Complete: 50
SDComment: Quest support: 9836, 10297. Currently in progress.
SDCategory: Caverns of Time, The Dark Portal
EndScriptData */
#include "precompiled.h"
#include "dark_portal.h"
inline uint32 RandRiftBoss() { return (urand(0, 1) ? NPC_RKEEP : NPC_RLORD); }
float PortalLocation[4][4]=
{
{-2041.06f, 7042.08f, 29.99f, 1.30f},
{-1968.18f, 7042.11f, 21.93f, 2.12f},
{-1885.82f, 7107.36f, 22.32f, 3.07f},
{-1928.11f, 7175.95f, 22.11f, 3.44f}
};
struct Wave
{
uint32 PortalBoss; // protector of current portal
uint32 NextPortalTime; // time to next portal, or 0 if portal boss need to be killed
};
static Wave RiftWaves[]=
{
{RIFT_BOSS, 0},
{NPC_DEJA, 0},
{RIFT_BOSS, 120000},
{NPC_TEMPO, 140000},
{RIFT_BOSS, 120000},
{NPC_AEONUS, 0}
};
struct MANGOS_DLL_DECL instance_dark_portal : public ScriptedInstance
{
instance_dark_portal(Map* pMap) : ScriptedInstance(pMap) {Initialize();};
uint32 m_auiEncounter[MAX_ENCOUNTER];
uint32 m_uiRiftPortalCount;
uint32 m_uiShieldPercent;
uint8 m_uiRiftWaveCount;
uint8 m_uiRiftWaveId;
uint32 m_uiNextPortal_Timer;
uint64 m_uiMedivhGUID;
uint8 m_uiCurrentRiftId;
void Initialize()
{
m_uiMedivhGUID = 0;
Clear();
}
void Clear()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
m_uiRiftPortalCount = 0;
m_uiShieldPercent = 100;
m_uiRiftWaveCount = 0;
m_uiRiftWaveId = 0;
m_uiCurrentRiftId = 0;
m_uiNextPortal_Timer = 0;
}
void InitWorldState(bool Enable = true)
{
DoUpdateWorldState(WORLD_STATE_BM,Enable ? 1 : 0);
DoUpdateWorldState(WORLD_STATE_BM_SHIELD, 100);
DoUpdateWorldState(WORLD_STATE_BM_RIFT, 0);
}
bool IsEncounterInProgress() const
{
if (m_auiEncounter[0] == IN_PROGRESS)
return true;
return false;
}
void OnPlayerEnter(Player* pPlayer)
{
if (m_auiEncounter[0] == IN_PROGRESS)
return;
pPlayer->SendUpdateWorldState(WORLD_STATE_BM, 0);
}
void OnCreatureCreate(Creature* pCreature)
{
if (pCreature->GetEntry() == NPC_MEDIVH)
m_uiMedivhGUID = pCreature->GetGUID();
}
// what other conditions to check?
bool CanProgressEvent()
{
if (instance->GetPlayers().isEmpty())
return false;
return true;
}
uint8 GetRiftWaveId()
{
switch(m_uiRiftPortalCount)
{
case 6:
m_uiRiftWaveId = 2;
return 1;
case 12:
m_uiRiftWaveId = 4;
return 3;
case 18:
return 5;
default:
return m_uiRiftWaveId;
}
}
void SetData(uint32 uiType, uint32 uiData)
{
switch(uiType)
{
case TYPE_MEDIVH:
if (uiData == SPECIAL && m_auiEncounter[0] == IN_PROGRESS)
{
--m_uiShieldPercent;
DoUpdateWorldState(WORLD_STATE_BM_SHIELD, m_uiShieldPercent);
if (!m_uiShieldPercent)
{
if (Creature* pMedivh = instance->GetCreature(m_uiMedivhGUID))
{
if (pMedivh->isAlive())
{
pMedivh->DealDamage(pMedivh, pMedivh->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
m_auiEncounter[0] = FAIL;
m_auiEncounter[1] = NOT_STARTED;
}
}
}
}
else
{
if (uiData == IN_PROGRESS)
{
debug_log("½Å±¾¿â£º Instance Dark Portal: Starting event.");
InitWorldState();
m_auiEncounter[1] = IN_PROGRESS;
m_uiNextPortal_Timer = 15000;
}
if (uiData == DONE)
{
// this may be completed further out in the post-event
debug_log("½Å±¾¿â£º Instance Dark Portal: Event completed.");
Map::PlayerList const& players = instance->GetPlayers();
if (!players.isEmpty())
{
for(Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
{
if (Player* pPlayer = itr->getSource())
{
if (pPlayer->GetQuestStatus(QUEST_OPENING_PORTAL) == QUEST_STATUS_INCOMPLETE)
pPlayer->AreaExploredOrEventHappens(QUEST_OPENING_PORTAL);
if (pPlayer->GetQuestStatus(QUEST_MASTER_TOUCH) == QUEST_STATUS_INCOMPLETE)
pPlayer->AreaExploredOrEventHappens(QUEST_MASTER_TOUCH);
}
}
}
}
m_auiEncounter[0] = uiData;
}
break;
case TYPE_RIFT:
if (uiData == SPECIAL)
{
if (m_uiRiftPortalCount < 7)
m_uiNextPortal_Timer = 5000;
}
else
m_auiEncounter[1] = uiData;
break;
}
}
uint32 GetData(uint32 uiType)
{
switch(uiType)
{
case TYPE_MEDIVH:
return m_auiEncounter[0];
case TYPE_RIFT:
return m_auiEncounter[1];
case DATA_PORTAL_COUNT:
return m_uiRiftPortalCount;
case DATA_SHIELD:
return m_uiShieldPercent;
}
return 0;
}
uint64 GetData64(uint32 uiData)
{
if (uiData == DATA_MEDIVH)
return m_uiMedivhGUID;
return 0;
}
Creature* SummonedPortalBoss(Creature* pSource)
{
uint32 uiEntry = RiftWaves[GetRiftWaveId()].PortalBoss;
if (uiEntry == RIFT_BOSS)
uiEntry = RandRiftBoss();
float x, y, z;
pSource->GetRandomPoint(pSource->GetPositionX(), pSource->GetPositionY(), pSource->GetPositionZ(), 10.0f, x, y, z);
// uncomment the following if something doesn't work correctly, otherwise just delete
// pSource->UpdateAllowedPositionZ(x, y, z);
debug_log("½Å±¾¿â£º Instance Dark Portal: Summoning rift boss uiEntry %u.", uiEntry);
if (Creature* pSummoned = pSource->SummonCreature(uiEntry, x, y, z, pSource->GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000))
return pSummoned;
debug_log("½Å±¾¿â£º Instance Dark Portal: what just happened there? No boss, no loot, no fun...");
return NULL;
}
void DoSpawnPortal()
{
if (Creature* pMedivh = instance->GetCreature(m_uiMedivhGUID))
{
uint8 uiTmp = urand(0, 2);
if (uiTmp >= m_uiCurrentRiftId)
++uiTmp;
debug_log("½Å±¾¿â£º Instance Dark Portal: Creating Time Rift at locationId %i (old locationId was %u).", uiTmp, m_uiCurrentRiftId);
m_uiCurrentRiftId = uiTmp;
if (Creature* pTemp = pMedivh->SummonCreature(NPC_TIME_RIFT, PortalLocation[uiTmp][0], PortalLocation[uiTmp][1], PortalLocation[uiTmp][2], PortalLocation[uiTmp][3], TEMPSUMMON_CORPSE_DESPAWN, 0))
{
pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
if (Creature* pBoss = SummonedPortalBoss(pTemp))
{
if (pBoss->GetEntry() == NPC_AEONUS)
pBoss->AddThreat(pMedivh);
else
{
pBoss->AddThreat(pTemp);
pTemp->CastSpell(pBoss, SPELL_RIFT_CHANNEL, false);
}
}
}
}
}
void Update(uint32 uiDiff)
{
if (m_auiEncounter[1] != IN_PROGRESS)
return;
//add delay timer?
if (!CanProgressEvent())
{
Clear();
return;
}
if (m_uiNextPortal_Timer)
{
if (m_uiNextPortal_Timer <= uiDiff)
{
++m_uiRiftPortalCount;
DoUpdateWorldState(WORLD_STATE_BM_RIFT, m_uiRiftPortalCount);
DoSpawnPortal();
m_uiNextPortal_Timer = RiftWaves[GetRiftWaveId()].NextPortalTime;
}
else
m_uiNextPortal_Timer -= uiDiff;
}
}
};
InstanceData* GetInstanceData_instance_dark_portal(Map* pMap)
{
return new instance_dark_portal(pMap);
}
void AddSC_instance_dark_portal()
{
Script* newscript;
newscript = new Script;
newscript->Name = "instance_dark_portal";
newscript->GetInstanceData = &GetInstanceData_instance_dark_portal;
newscript->RegisterSelf();
}
| gelu/ChgSD2 | scripts/kalimdor/caverns_of_time/dark_portal/instance_dark_portal.cpp | C++ | gpl-2.0 | 10,305 |
package com.github.randoapp.api.listeners;
import com.github.randoapp.db.model.Rando;
public interface UploadRandoListener {
void onUpload(Rando rando);
}
| RandoApp/Rando-android | src/main/java/com/github/randoapp/api/listeners/UploadRandoListener.java | Java | gpl-2.0 | 162 |
<?php
/**
* Copyright (c) 2007-2011, Servigistics, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of Servigistics, Inc. nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright Copyright 2007-2011 Servigistics, Inc. (http://servigistics.com)
* @license http://solr-php-client.googlecode.com/svn/trunk/COPYING New BSD
* @version $Id: Service.php 59 2011-02-08 20:38:59Z donovan.jimenez $
*
* @package Apache
* @subpackage Solr
* @author Donovan Jimenez <djimenez@conduit-it.com>
*/
// See Issue #1 (http://code.google.com/p/solr-php-client/issues/detail?id=1)
// Doesn't follow typical include path conventions, but is more convenient for users
require_once(dirname(__FILE__) . '/Exception.php');
require_once(dirname(__FILE__) . '/HttpTransportException.php');
require_once(dirname(__FILE__) . '/InvalidArgumentException.php');
require_once(dirname(__FILE__) . '/Document.php');
require_once(dirname(__FILE__) . '/Response.php');
require_once(dirname(__FILE__) . '/HttpTransport/Interface.php');
/**
* Starting point for the Solr API. Represents a Solr server resource and has
* methods for pinging, adding, deleting, committing, optimizing and searching.
*
* Example Usage:
* <code>
* ...
* $solr = new Apache_Solr_Service(); //or explicitly new Apache_Solr_Service('localhost', 8180, '/solr')
*
* if ($solr->ping())
* {
* $solr->deleteByQuery('*:*'); //deletes ALL documents - be careful :)
*
* $document = new Apache_Solr_Document();
* $document->id = uniqid(); //or something else suitably unique
*
* $document->title = 'Some Title';
* $document->content = 'Some content for this wonderful document. Blah blah blah.';
*
* $solr->addDocument($document); //if you're going to be adding documents in bulk using addDocuments
* //with an array of documents is faster
*
* $solr->commit(); //commit to see the deletes and the document
* $solr->optimize(); //merges multiple segments into one
*
* //and the one we all care about, search!
* //any other common or custom parameters to the request handler can go in the
* //optional 4th array argument.
* $solr->search('content:blah', 0, 10, array('sort' => 'timestamp desc'));
* }
* ...
* </code>
*
* @todo Investigate using other HTTP clients other than file_get_contents built-in handler. Could provide performance
* improvements when dealing with multiple requests by using HTTP's keep alive functionality
*/
class Apache_Solr_Service
{
/**
* SVN Revision meta data for this class
*/
const SVN_REVISION = '$Revision: 59 $';
/**
* SVN ID meta data for this class
*/
const SVN_ID = '$Id: Service.php 59 2011-02-08 20:38:59Z donovan.jimenez $';
/**
* Response writer we'll request - JSON. See http://code.google.com/p/solr-php-client/issues/detail?id=6#c1 for reasoning
*/
const SOLR_WRITER = 'json';
/**
* NamedList Treatment constants
*/
const NAMED_LIST_FLAT = 'flat';
const NAMED_LIST_MAP = 'map';
/**
* Search HTTP Methods
*/
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
/**
* Servlet mappings
*/
const PING_SERVLET = 'admin/ping';
const UPDATE_SERVLET = 'update';
const SEARCH_SERVLET = 'select';
const THREADS_SERVLET = 'admin/threads';
const EXTRACT_SERVLET = 'update/extract';
/**
* Server identification strings
*
* @var string
*/
protected $_host, $_port, $_path;
/**
* Whether {@link Apache_Solr_Response} objects should create {@link Apache_Solr_Document}s in
* the returned parsed data
*
* @var boolean
*/
protected $_createDocuments = true;
/**
* Whether {@link Apache_Solr_Response} objects should have multivalue fields with only a single value
* collapsed to appear as a single value would.
*
* @var boolean
*/
protected $_collapseSingleValueArrays = true;
/**
* How NamedLists should be formatted in the output. This specifically effects facet counts. Valid values
* are {@link Apache_Solr_Service::NAMED_LIST_MAP} (default) or {@link Apache_Solr_Service::NAMED_LIST_FLAT}.
*
* @var string
*/
protected $_namedListTreatment = self::NAMED_LIST_MAP;
/**
* Query delimiters. Someone might want to be able to change
* these (to use & instead of & for example), so I've provided them.
*
* @var string
*/
protected $_queryDelimiter = '?', $_queryStringDelimiter = '&', $_queryBracketsEscaped = true;
/**
* Constructed servlet full path URLs
*
* @var string
*/
protected $_pingUrl, $_updateUrl, $_searchUrl, $_threadsUrl;
/**
* Keep track of whether our URLs have been constructed
*
* @var boolean
*/
protected $_urlsInited = false;
/**
* HTTP Transport implementation (pluggable)
*
* @var Apache_Solr_HttpTransport_Interface
*/
protected $_httpTransport = false;
/**
* Escape a value for special query characters such as ':', '(', ')', '*', '?', etc.
*
* NOTE: inside a phrase fewer characters need escaped, use {@link Apache_Solr_Service::escapePhrase()} instead
*
* @param string $value
* @return string
*/
static public function escape($value)
{
//list taken from http://lucene.apache.org/java/docs/queryparsersyntax.html#Escaping%20Special%20Characters
$pattern = '/(\+|-|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';
$replace = '\\\$1';
return preg_replace($pattern, $replace, $value);
}
/**
* Escape a value meant to be contained in a phrase for special query characters
*
* @param string $value
* @return string
*/
static public function escapePhrase($value)
{
$pattern = '/("|\\\)/';
$replace = '\\\$1';
return preg_replace($pattern, $replace, $value);
}
/**
* Convenience function for creating phrase syntax from a value
*
* @param string $value
* @return string
*/
static public function phrase($value)
{
return '"' . self::escapePhrase($value) . '"';
}
/**
* Constructor. All parameters are optional and will take on default values
* if not specified.
*
* @param string $host
* @param string $port
* @param string $path
* @param Apache_Solr_HttpTransport_Interface $httpTransport
*/
public function __construct($host = 'localhost', $port = 8180, $path = '/solr/', $httpTransport = false)
{
$this->setHost($host);
$this->setPort($port);
$this->setPath($path);
$this->_initUrls();
if ($httpTransport)
{
$this->setHttpTransport($httpTransport);
}
// check that our php version is >= 5.1.3 so we can correct for http_build_query behavior later
$this->_queryBracketsEscaped = version_compare(phpversion(), '5.1.3', '>=');
}
/**
* Return a valid http URL given this server's host, port and path and a provided servlet name
*
* @param string $servlet
* @return string
*/
protected function _constructUrl($servlet, $params = array())
{
if (count($params))
{
//escape all parameters appropriately for inclusion in the query string
$escapedParams = array();
foreach ($params as $key => $value)
{
$escapedParams[] = urlencode($key) . '=' . urlencode($value);
}
$queryString = $this->_queryDelimiter . implode($this->_queryStringDelimiter, $escapedParams);
}
else
{
$queryString = '';
}
return 'http://' . $this->_host . ':' . $this->_port . $this->_path . $servlet . $queryString;
}
/**
* Construct the Full URLs for the three servlets we reference
*/
protected function _initUrls()
{
//Initialize our full servlet URLs now that we have server information
$this->_extractUrl = $this->_constructUrl(self::EXTRACT_SERVLET);
$this->_pingUrl = $this->_constructUrl(self::PING_SERVLET);
$this->_searchUrl = $this->_constructUrl(self::SEARCH_SERVLET);
$this->_threadsUrl = $this->_constructUrl(self::THREADS_SERVLET, array('wt' => self::SOLR_WRITER ));
$this->_updateUrl = $this->_constructUrl(self::UPDATE_SERVLET, array('wt' => self::SOLR_WRITER ));
$this->_urlsInited = true;
}
protected function _generateQueryString($params)
{
// use http_build_query to encode our arguments because its faster
// than urlencoding all the parts ourselves in a loop
//
// because http_build_query treats arrays differently than we want to, correct the query
// string by changing foo[#]=bar (# being an actual number) parameter strings to just
// multiple foo=bar strings. This regex should always work since '=' will be urlencoded
// anywhere else the regex isn't expecting it
//
// NOTE: before php 5.1.3 brackets were not url encoded by http_build query - we've checked
// the php version in the constructor and put the results in the instance variable. Also, before
// 5.1.2 the arg_separator parameter was not available, so don't use it
if ($this->_queryBracketsEscaped)
{
$queryString = http_build_query($params, null, $this->_queryStringDelimiter);
return preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $queryString);
}
else
{
$queryString = http_build_query($params);
return preg_replace('/\\[(?:[0-9]|[1-9][0-9]+)\\]=/', '=', $queryString);
}
}
/**
* Central method for making a get operation against this Solr Server
*
* @param string $url
* @param float $timeout Read timeout in seconds
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If a non 200 response status is returned
*/
protected function _sendRawGet($url, $timeout = FALSE)
{
$httpTransport = $this->getHttpTransport();
$httpResponse = $httpTransport->performGetRequest($url, $timeout);
$solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays);
if ($solrResponse->getHttpStatus() != 200)
{
throw new Apache_Solr_HttpTransportException($solrResponse);
}
return $solrResponse;
}
/**
* Central method for making a post operation against this Solr Server
*
* @param string $url
* @param string $rawPost
* @param float $timeout Read timeout in seconds
* @param string $contentType
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If a non 200 response status is returned
*/
protected function _sendRawPost($url, $rawPost, $timeout = FALSE, $contentType = 'text/xml; charset=UTF-8')
{
$httpTransport = $this->getHttpTransport();
$httpResponse = $httpTransport->performPostRequest($url, $rawPost, $contentType, $timeout);
$solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays);
if ($solrResponse->getHttpStatus() != 200)
{
throw new Apache_Solr_HttpTransportException($solrResponse);
}
return $solrResponse;
}
/**
* Returns the set host
*
* @return string
*/
public function getHost()
{
return $this->_host;
}
/**
* Set the host used. If empty will fallback to constants
*
* @param string $host
*
* @throws Apache_Solr_InvalidArgumentException If the host parameter is empty
*/
public function setHost($host)
{
//Use the provided host or use the default
if (empty($host))
{
throw new Apache_Solr_InvalidArgumentException('Host parameter is empty');
}
else
{
$this->_host = $host;
}
if ($this->_urlsInited)
{
$this->_initUrls();
}
}
/**
* Get the set port
*
* @return integer
*/
public function getPort()
{
return $this->_port;
}
/**
* Set the port used. If empty will fallback to constants
*
* @param integer $port
*
* @throws Apache_Solr_InvalidArgumentException If the port parameter is empty
*/
public function setPort($port)
{
//Use the provided port or use the default
$port = (int) $port;
if ($port <= 0)
{
throw new Apache_Solr_InvalidArgumentException('Port is not a valid port number');
}
else
{
$this->_port = $port;
}
if ($this->_urlsInited)
{
$this->_initUrls();
}
}
/**
* Get the set path.
*
* @return string
*/
public function getPath()
{
return $this->_path;
}
/**
* Set the path used. If empty will fallback to constants
*
* @param string $path
*/
public function setPath($path)
{
$path = trim($path, '/');
$this->_path = '/' . $path . '/';
if ($this->_urlsInited)
{
$this->_initUrls();
}
}
/**
* Get the current configured HTTP Transport
*
* @return HttpTransportInterface
*/
public function getHttpTransport()
{
// lazy load a default if one has not be set
if ($this->_httpTransport === false)
{
require_once(dirname(__FILE__) . '/HttpTransport/FileGetContents.php');
$this->_httpTransport = new Apache_Solr_HttpTransport_FileGetContents();
}
return $this->_httpTransport;
}
/**
* Set the HTTP Transport implemenation that will be used for all HTTP requests
*
* @param Apache_Solr_HttpTransport_Interface
*/
public function setHttpTransport(Apache_Solr_HttpTransport_Interface $httpTransport)
{
$this->_httpTransport = $httpTransport;
}
/**
* Set the create documents flag. This determines whether {@link Apache_Solr_Response} objects will
* parse the response and create {@link Apache_Solr_Document} instances in place.
*
* @param boolean $createDocuments
*/
public function setCreateDocuments($createDocuments)
{
$this->_createDocuments = (bool) $createDocuments;
}
/**
* Get the current state of teh create documents flag.
*
* @return boolean
*/
public function getCreateDocuments()
{
return $this->_createDocuments;
}
/**
* Set the collapse single value arrays flag.
*
* @param boolean $collapseSingleValueArrays
*/
public function setCollapseSingleValueArrays($collapseSingleValueArrays)
{
$this->_collapseSingleValueArrays = (bool) $collapseSingleValueArrays;
}
/**
* Get the current state of the collapse single value arrays flag.
*
* @return boolean
*/
public function getCollapseSingleValueArrays()
{
return $this->_collapseSingleValueArrays;
}
/**
* Get the current default timeout setting (initially the default_socket_timeout ini setting)
* in seconds
*
* @return float
*
* @deprecated Use the getDefaultTimeout method on the HTTP transport implementation
*/
public function getDefaultTimeout()
{
return $this->getHttpTransport()->getDefaultTimeout();
}
/**
* Set the default timeout for all calls that aren't passed a specific timeout
*
* @param float $timeout Timeout value in seconds
*
* @deprecated Use the setDefaultTimeout method on the HTTP transport implementation
*/
public function setDefaultTimeout($timeout)
{
$this->getHttpTransport()->setDefaultTimeout($timeout);
}
/**
* Set how NamedLists should be formatted in the response data. This mainly effects
* the facet counts format.
*
* @param string $namedListTreatment
* @throws Apache_Solr_InvalidArgumentException If invalid option is set
*/
public function setNamedListTreatment($namedListTreatment)
{
switch ((string) $namedListTreatment)
{
case Apache_Solr_Service::NAMED_LIST_FLAT:
$this->_namedListTreatment = Apache_Solr_Service::NAMED_LIST_FLAT;
break;
case Apache_Solr_Service::NAMED_LIST_MAP:
$this->_namedListTreatment = Apache_Solr_Service::NAMED_LIST_MAP;
break;
default:
throw new Apache_Solr_InvalidArgumentException('Not a valid named list treatement option');
}
}
/**
* Get the current setting for named list treatment.
*
* @return string
*/
public function getNamedListTreatment()
{
return $this->_namedListTreatment;
}
/**
* Set the string used to separate the path form the query string.
* Defaulted to '?'
*
* @param string $queryDelimiter
*/
public function setQueryDelimiter($queryDelimiter)
{
$this->_queryDelimiter = $queryDelimiter;
}
/**
* Set the string used to separate the parameters in thequery string
* Defaulted to '&'
*
* @param string $queryStringDelimiter
*/
public function setQueryStringDelimiter($queryStringDelimiter)
{
$this->_queryStringDelimiter = $queryStringDelimiter;
}
/**
* Call the /admin/ping servlet, can be used to quickly tell if a connection to the
* server is able to be made.
*
* @param float $timeout maximum time to wait for ping in seconds, -1 for unlimited (default is 2)
* @return float Actual time taken to ping the server, FALSE if timeout or HTTP error status occurs
*/
public function ping($timeout = 2)
{
$start = microtime(true);
$httpTransport = $this->getHttpTransport();
$httpResponse = $httpTransport->performHeadRequest($this->_pingUrl, $timeout);
$solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays);
if ($solrResponse->getHttpStatus() == 200)
{
return microtime(true) - $start;
}
else
{
return false;
}
}
/**
* Call the /admin/threads servlet and retrieve information about all threads in the
* Solr servlet's thread group. Useful for diagnostics.
*
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function threads()
{
return $this->_sendRawGet($this->_threadsUrl);
}
/**
* Raw Add Method. Takes a raw post body and sends it to the update service. Post body
* should be a complete and well formed "add" xml document.
*
* @param string $rawPost
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function add($rawPost)
{
return $this->_sendRawPost($this->_updateUrl, $rawPost);
}
/**
* Add a Solr Document to the index
*
* @param Apache_Solr_Document $document
* @param boolean $allowDups
* @param boolean $overwritePending
* @param boolean $overwriteCommitted
* @param integer $commitWithin The number of milliseconds that a document must be committed within, see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details. If left empty this property will not be set in the request.
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function addDocument(Apache_Solr_Document $document, $allowDups = false, $overwritePending = true, $overwriteCommitted = true, $commitWithin = 0)
{
$dupValue = $allowDups ? 'true' : 'false';
$pendingValue = $overwritePending ? 'true' : 'false';
$committedValue = $overwriteCommitted ? 'true' : 'false';
$commitWithin = (int) $commitWithin;
$commitWithinString = $commitWithin > 0 ? " commitWithin=\"{$commitWithin}\"" : '';
$rawPost = "<add{$commitWithinString}>";
$rawPost .= $this->_documentToXmlFragment($document);
$rawPost .= '</add>';
return $this->add($rawPost);
}
/**
* Add an array of Solr Documents to the index all at once
*
* @param array $documents Should be an array of Apache_Solr_Document instances
* @param boolean $allowDups
* @param boolean $overwritePending
* @param boolean $overwriteCommitted
* @param integer $commitWithin The number of milliseconds that a document must be committed within, see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details. If left empty this property will not be set in the request.
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function addDocuments($documents, $allowDups = false, $overwritePending = true, $overwriteCommitted = true, $commitWithin = 0)
{
$dupValue = $allowDups ? 'true' : 'false';
$pendingValue = $overwritePending ? 'true' : 'false';
$committedValue = $overwriteCommitted ? 'true' : 'false';
$commitWithin = (int) $commitWithin;
$commitWithinString = $commitWithin > 0 ? " commitWithin=\"{$commitWithin}\"" : '';
$rawPost = "<add{$commitWithinString}>";
foreach ($documents as $document)
{
if ($document instanceof Apache_Solr_Document)
{
$rawPost .= $this->_documentToXmlFragment($document);
}
}
$rawPost .= '</add>';
return $this->add($rawPost);
}
/**
* Create an XML fragment from a {@link Apache_Solr_Document} instance appropriate for use inside a Solr add call
*
* @return string
*/
protected function _documentToXmlFragment(Apache_Solr_Document $document)
{
$xml = '<doc';
if ($document->getBoost() !== false)
{
$xml .= ' boost="' . $document->getBoost() . '"';
}
$xml .= '>';
foreach ($document as $key => $value)
{
$key = htmlspecialchars($key, ENT_QUOTES, 'UTF-8');
$fieldBoost = $document->getFieldBoost($key);
if (is_array($value))
{
foreach ($value as $multivalue)
{
$xml .= '<field name="' . $key . '"';
if ($fieldBoost !== false)
{
$xml .= ' boost="' . $fieldBoost . '"';
// only set the boost for the first field in the set
$fieldBoost = false;
}
$multivalue = htmlspecialchars($multivalue, ENT_NOQUOTES, 'UTF-8');
$xml .= '>' . $multivalue . '</field>';
}
}
else
{
$xml .= '<field name="' . $key . '"';
if ($fieldBoost !== false)
{
$xml .= ' boost="' . $fieldBoost . '"';
}
$value = htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8');
$xml .= '>' . $value . '</field>';
}
}
$xml .= '</doc>';
// replace any control characters to avoid Solr XML parser exception
return $this->_stripCtrlChars($xml);
}
/**
* Replace control (non-printable) characters from string that are invalid to Solr's XML parser with a space.
*
* @param string $string
* @return string
*/
protected function _stripCtrlChars($string)
{
// See: http://w3.org/International/questions/qa-forms-utf-8.html
// Printable utf-8 does not include any of these chars below x7F
return preg_replace('@[\x00-\x08\x0B\x0C\x0E-\x1F]@', ' ', $string);
}
/**
* Send a commit command. Will be synchronous unless both wait parameters are set to false.
*
* @param boolean $expungeDeletes Defaults to false, merge segments with deletes away
* @param boolean $waitFlush Defaults to true, block until index changes are flushed to disk
* @param boolean $waitSearcher Defaults to true, block until a new searcher is opened and registered as the main query searcher, making the changes visible
* @param float $timeout Maximum expected duration (in seconds) of the commit operation on the server (otherwise, will throw a communication exception). Defaults to 1 hour
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function commit($expungeDeletes = false, $waitFlush = true, $waitSearcher = true, $timeout = 3600)
{
$expungeValue = $expungeDeletes ? 'true' : 'false';
$flushValue = $waitFlush ? 'true' : 'false';
$searcherValue = $waitSearcher ? 'true' : 'false';
$rawPost = '<commit expungeDeletes="' . $expungeValue . '" waitSearcher="' . $searcherValue . '" />';
return $this->_sendRawPost($this->_updateUrl, $rawPost, $timeout);
}
/**
* Raw Delete Method. Takes a raw post body and sends it to the update service. Body should be
* a complete and well formed "delete" xml document
*
* @param string $rawPost Expected to be utf-8 encoded xml document
* @param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function delete($rawPost, $timeout = 3600)
{
return $this->_sendRawPost($this->_updateUrl, $rawPost, $timeout);
}
/**
* Create a delete document based on document ID
*
* @param string $id Expected to be utf-8 encoded
* @param boolean $fromPending
* @param boolean $fromCommitted
* @param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function deleteById($id, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$pendingValue = $fromPending ? 'true' : 'false';
$committedValue = $fromCommitted ? 'true' : 'false';
//escape special xml characters
$id = htmlspecialchars($id, ENT_NOQUOTES, 'UTF-8');
$rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '"><id>' . $id . '</id></delete>';
return $this->delete($rawPost, $timeout);
}
/**
* Create and post a delete document based on multiple document IDs.
*
* @param array $ids Expected to be utf-8 encoded strings
* @param boolean $fromPending
* @param boolean $fromCommitted
* @param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function deleteByMultipleIds($ids, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$pendingValue = $fromPending ? 'true' : 'false';
$committedValue = $fromCommitted ? 'true' : 'false';
$rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '">';
foreach ($ids as $id)
{
//escape special xml characters
$id = htmlspecialchars($id, ENT_NOQUOTES, 'UTF-8');
$rawPost .= '<id>' . $id . '</id>';
}
$rawPost .= '</delete>';
return $this->delete($rawPost, $timeout);
}
/**
* Create a delete document based on a query and submit it
*
* @param string $rawQuery Expected to be utf-8 encoded
* @param boolean $fromPending
* @param boolean $fromCommitted
* @param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function deleteByQuery($rawQuery, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$pendingValue = $fromPending ? 'true' : 'false';
$committedValue = $fromCommitted ? 'true' : 'false';
// escape special xml characters
$rawQuery = htmlspecialchars($rawQuery, ENT_NOQUOTES, 'UTF-8');
$rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '"><query>' . $rawQuery . '</query></delete>';
return $this->delete($rawPost, $timeout);
}
/**
* Use Solr Cell to extract document contents. See {@link http://wiki.apache.org/solr/ExtractingRequestHandler} for information on how
* to use Solr Cell and what parameters are available.
*
* NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost."
* as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value
* pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also
* pass in a document isntance with an "id" field" - the document's value(s) will take precedence).
*
* @param string $file Path to file to extract data from
* @param array $params optional array of key value pairs that will be sent with the post (see Solr Cell documentation)
* @param Apache_Solr_Document $document optional document that will be used to generate post parameters (literal.* and boost.* params)
* @param string $mimetype optional mimetype specification (for the file being extracted)
*
* @return Apache_Solr_Response
*
* @throws Apache_Solr_InvalidArgumentException if $file, $params, or $document are invalid.
*/
public function extract($file, $params = array(), $document = null, $mimetype = 'application/octet-stream')
{
// check if $params is an array (allow null for default empty array)
if (!is_null($params))
{
if (!is_array($params))
{
throw new Apache_Solr_InvalidArgumentException("\$params must be a valid array or null");
}
}
else
{
$params = array();
}
// if $file is an http request, defer to extractFromUrl instead
if (substr($file, 0, 7) == 'http://' || substr($file, 0, 8) == 'https://')
{
return $this->extractFromUrl($file, $params, $document, $mimetype);
}
// read the contents of the file
$contents = @file_get_contents($file);
if ($contents !== false)
{
// add the resource.name parameter if not specified
if (!isset($params['resource.name']))
{
$params['resource.name'] = basename($file);
}
// delegate the rest to extractFromString
return $this->extractFromString($contents, $params, $document, $mimetype);
}
else
{
throw new Apache_Solr_InvalidArgumentException("File '{$file}' is empty or could not be read");
}
}
/**
* Use Solr Cell to extract document contents. See {@link http://wiki.apache.org/solr/ExtractingRequestHandler} for information on how
* to use Solr Cell and what parameters are available.
*
* NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost."
* as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value
* pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also
* pass in a document isntance with an "id" field" - the document's value(s) will take precedence).
*
* @param string $data Data that will be passed to Solr Cell
* @param array $params optional array of key value pairs that will be sent with the post (see Solr Cell documentation)
* @param Apache_Solr_Document $document optional document that will be used to generate post parameters (literal.* and boost.* params)
* @param string $mimetype optional mimetype specification (for the file being extracted)
*
* @return Apache_Solr_Response
*
* @throws Apache_Solr_InvalidArgumentException if $file, $params, or $document are invalid.
*
* @todo Should be using multipart/form-data to post parameter values, but I could not get my implementation to work. Needs revisisted.
*/
public function extractFromString($data, $params = array(), $document = null, $mimetype = 'application/octet-stream')
{
// check if $params is an array (allow null for default empty array)
if (!is_null($params))
{
if (!is_array($params))
{
throw new Apache_Solr_InvalidArgumentException("\$params must be a valid array or null");
}
}
else
{
$params = array();
}
// make sure we receive our response in JSON and have proper name list treatment
$params['wt'] = self::SOLR_WRITER;
$params['json.nl'] = $this->_namedListTreatment;
// check if $document is an Apache_Solr_Document instance
if (!is_null($document) && $document instanceof Apache_Solr_Document)
{
// iterate document, adding literal.* and boost.* fields to $params as appropriate
foreach ($document as $field => $fieldValue)
{
// check if we need to add a boost.* parameters
$fieldBoost = $document->getFieldBoost($field);
if ($fieldBoost !== false)
{
$params["boost.{$field}"] = $fieldBoost;
}
// add the literal.* parameter
$params["literal.{$field}"] = $fieldValue;
}
}
// params will be sent to SOLR in the QUERY STRING
$queryString = $this->_generateQueryString($params);
// the file contents will be sent to SOLR as the POST BODY - we use application/octect-stream as default mimetype
return $this->_sendRawPost($this->_extractUrl . $this->_queryDelimiter . $queryString, $data, false, $mimetype);
}
/**
* Use Solr Cell to extract document contents. See {@link http://wiki.apache.org/solr/ExtractingRequestHandler} for information on how
* to use Solr Cell and what parameters are available.
*
* NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost."
* as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value
* pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also
* pass in a document isntance with an "id" field" - the document's value(s) will take precedence).
*
* @param string $url URL
* @param array $params optional array of key value pairs that will be sent with the post (see Solr Cell documentation)
* @param Apache_Solr_Document $document optional document that will be used to generate post parameters (literal.* and boost.* params)
* @param string $mimetype optional mimetype specification (for the file being extracted)
*
* @return Apache_Solr_Response
*
* @throws Apache_Solr_InvalidArgumentException if $url, $params, or $document are invalid.
*/
public function extractFromUrl($url, $params = array(), $document = null, $mimetype = 'application/octet-stream')
{
// check if $params is an array (allow null for default empty array)
if (!is_null($params))
{
if (!is_array($params))
{
throw new Apache_Solr_InvalidArgumentException("\$params must be a valid array or null");
}
}
else
{
$params = array();
}
$httpTransport = $this->getHttpTransport();
// read the contents of the URL using our configured Http Transport and default timeout
$httpResponse = $httpTransport->performGetRequest($url);
// check that its a 200 response
if ($httpResponse->getStatusCode() == 200)
{
// add the resource.name parameter if not specified
if (!isset($params['resource.name']))
{
$params['resource.name'] = $url;
}
// delegate the rest to extractFromString
return $this->extractFromString($httpResponse->getBody(), $params, $document, $mimetype);
}
else
{
throw new Apache_Solr_InvalidArgumentException("URL '{$url}' returned non 200 response code");
}
}
/**
* Send an optimize command. Will be synchronous unless both wait parameters are set
* to false.
*
* @param boolean $waitFlush
* @param boolean $waitSearcher
* @param float $timeout Maximum expected duration of the commit operation on the server (otherwise, will throw a communication exception)
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
*/
public function optimize($waitFlush = true, $waitSearcher = true, $timeout = 3600)
{
$flushValue = $waitFlush ? 'true' : 'false';
$searcherValue = $waitSearcher ? 'true' : 'false';
$rawPost = '<optimize waitSearcher="' . $searcherValue . '" />';
return $this->_sendRawPost($this->_updateUrl, $rawPost, $timeout);
}
/**
* Simple Search interface
*
* @param string $query The raw query string
* @param int $offset The starting offset for result documents
* @param int $limit The maximum number of result documents to return
* @param array $params key / value pairs for other query parameters (see Solr documentation), use arrays for parameter keys used more than once (e.g. facet.field)
* @param string $method The HTTP method (Apache_Solr_Service::METHOD_GET or Apache_Solr_Service::METHOD::POST)
* @return Apache_Solr_Response
*
* @throws Apache_Solr_HttpTransportException If an error occurs during the service call
* @throws Apache_Solr_InvalidArgumentException If an invalid HTTP method is used
*/
public function search($query, $offset = 0, $limit = 10, $params = array(), $method = self::METHOD_GET)
{
// ensure params is an array
if (!is_null($params))
{
if (!is_array($params))
{
// params was specified but was not an array - invalid
throw new Apache_Solr_InvalidArgumentException("\$params must be a valid array or null");
}
}
else
{
$params = array();
}
// construct our full parameters
// common parameters in this interface
$params['wt'] = self::SOLR_WRITER;
$params['json.nl'] = $this->_namedListTreatment;
$params['q'] = $query;
$params['start'] = $offset;
$params['rows'] = $limit;
$queryString = $this->_generateQueryString($params);
if ($method == self::METHOD_GET)
{
return $this->_sendRawGet($this->_searchUrl . $this->_queryDelimiter . $queryString);
}
else if ($method == self::METHOD_POST)
{
return $this->_sendRawPost($this->_searchUrl, $queryString, FALSE, 'application/x-www-form-urlencoded; charset=UTF-8');
}
else
{
throw new Apache_Solr_InvalidArgumentException("Unsupported method '$method', please use the Apache_Solr_Service::METHOD_* constants");
}
}
} | ekilfeather/open-storyscope | profiles/storyscope/libraries/SolrPhpClient/Apache/Solr/Service.php | PHP | gpl-2.0 | 39,313 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tesisweb.controller.general;
/**
*
* @author root
*/
/* *******************************************
// Copyright 2010-2012, Anthony Hand
//
// File version date: January 21, 2012
// Update:
// - Moved Windows Phone 7 to the iPhone Tier. WP7.5's IE 9-based browser is good enough now.
// - Added a new variable for 2 versions of the new BlackBerry Bold Touch (9900 and 9930): deviceBBBoldTouch.
// - Updated DetectBlackBerryTouch() to support the 2 versions of the new BlackBerry Bold Touch (9900 and 9930).
// - Updated DetectKindle() to focus on eInk devices only. The Kindle Fire should be detected as a regular Android device.
//
// File version date: August 22, 2011
// Update:
// - Updated DetectAndroidTablet() to fix a bug I introduced in the last fix!
//
// File version date: August 16, 2011
// Update:
// - Updated DetectAndroidTablet() to exclude Opera Mini, which was falsely reporting as running on a tablet device when on a phone.
//
// File version date: August 7, 2011
// Update:
// - The Opera for Android browser doesn't follow Google's recommended useragent string guidelines, so some fixes were needed.
// - Updated DetectAndroidPhone() and DetectAndroidTablet() to properly detect devices running Opera Mobile.
// - Created 2 new methods: DetectOperaAndroidPhone() and DetectOperaAndroidTablet().
// - Updated DetectTierIphone(). Removed the call to DetectMaemoTablet(), an obsolete mobile OS.
//
//
// LICENSE INFORMATION
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
//
//
// ABOUT THIS PROJECT
// Project Owner: Anthony Hand
// Email: anthony.hand@gmail.com
// Web Site: http://www.mobileesp.com
// Source Files: http://code.google.com/p/mobileesp/
//
// Versions of this code are available for:
// PHP, JavaScript, Java, ASP.NET (C#), and Ruby
//
// *******************************************
*/
/**
* The DetectSmartPhone class encapsulates information about
* a browser's connection to your web site.
* You can use it to find out whether the browser asking for
* your site's content is probably running on a mobile device.
* The methods were written so you can be as granular as you want.
* For example, enquiring whether it's as specific as an iPod Touch or
* as general as a smartphone class device.
* The object's methods return true, or false.
*/
public class UserAgentInfo {
// User-Agent and Accept HTTP request headers
private String userAgent = "";
private String httpAccept = "";
// Let's store values for quickly accessing the same info multiple times.
public boolean isIphone = false;
public boolean isAndroidPhone = false;
public boolean isTierTablet = false;
public boolean isTierIphone = false;
public boolean isTierRichCss = false;
public boolean isTierGenericMobile = false;
// Initialize some initial smartphone string variables.
public static final String engineWebKit = "webkit";
public static final String deviceIphone = "iphone";
public static final String deviceIpod = "ipod";
public static final String deviceIpad = "ipad";
public static final String deviceMacPpc = "macintosh"; //Used for disambiguation
public static final String deviceAndroid = "android";
public static final String deviceGoogleTV = "googletv";
public static final String deviceXoom = "xoom"; //Motorola Xoom
public static final String deviceHtcFlyer = "htc_flyer"; //HTC Flyer
public static final String deviceSymbian = "symbian";
public static final String deviceS60 = "series60";
public static final String deviceS70 = "series70";
public static final String deviceS80 = "series80";
public static final String deviceS90 = "series90";
public static final String deviceWinPhone7 = "windows phone os 7";
public static final String deviceWinMob = "windows ce";
public static final String deviceWindows = "windows";
public static final String deviceIeMob = "iemobile";
public static final String devicePpc = "ppc"; //Stands for PocketPC
public static final String enginePie = "wm5 pie"; //An old Windows Mobile
public static final String deviceBB = "blackberry";
public static final String vndRIM = "vnd.rim"; //Detectable when BB devices emulate IE or Firefox
public static final String deviceBBStorm = "blackberry95"; //Storm 1 and 2
public static final String deviceBBBold = "blackberry97"; //Bold 97x0 (non-touch)
public static final String deviceBBBoldTouch = "blackberry 99"; //Bold 99x0 (touchscreen)
public static final String deviceBBTour = "blackberry96"; //Tour
public static final String deviceBBCurve = "blackberry89"; //Curve 2
public static final String deviceBBTorch = "blackberry 98"; //Torch
public static final String deviceBBPlaybook = "playbook"; //PlayBook tablet
public static final String devicePalm = "palm";
public static final String deviceWebOS = "webos"; //For Palm's line of WebOS devices
public static final String deviceWebOShp = "hpwos"; //For HP's line of WebOS devices
public static final String engineBlazer = "blazer"; //Old Palm
public static final String engineXiino = "xiino"; //Another old Palm
public static final String deviceKindle = "kindle"; //Amazon Kindle, eInk one.
public static final String deviceNuvifone = "nuvifone"; //Garmin Nuvifone
//Initialize variables for mobile-specific content.
public static final String vndwap = "vnd.wap";
public static final String wml = "wml";
//Initialize variables for other random devices and mobile browsers.
public static final String deviceTablet = "tablet"; //Generic term for slate and tablet devices
public static final String deviceBrew = "brew";
public static final String deviceDanger = "danger";
public static final String deviceHiptop = "hiptop";
public static final String devicePlaystation = "playstation";
public static final String deviceNintendoDs = "nitro";
public static final String deviceNintendo = "nintendo";
public static final String deviceWii = "wii";
public static final String deviceXbox = "xbox";
public static final String deviceArchos = "archos";
public static final String engineOpera = "opera"; //Popular browser
public static final String engineNetfront = "netfront"; //Common embedded OS browser
public static final String engineUpBrowser = "up.browser"; //common on some phones
public static final String engineOpenWeb = "openweb"; //Transcoding by OpenWave server
public static final String deviceMidp = "midp"; //a mobile Java technology
public static final String uplink = "up.link";
public static final String engineTelecaQ = "teleca q"; //a modern feature phone browser
public static final String devicePda = "pda"; //some devices report themselves as PDAs
public static final String mini = "mini"; //Some mobile browsers put "mini" in their names.
public static final String mobile = "mobile"; //Some mobile browsers put "mobile" in their user agent strings.
public static final String mobi = "mobi"; //Some mobile browsers put "mobi" in their user agent strings.
//Use Maemo, Tablet, and Linux to test for Nokia"s Internet Tablets.
public static final String maemo = "maemo";
public static final String linux = "linux";
public static final String qtembedded = "qt embedded"; //for Sony Mylo
public static final String mylocom2 = "com2"; //for Sony Mylo also
//In some UserAgents, the only clue is the manufacturer.
public static final String manuSonyEricsson = "sonyericsson";
public static final String manuericsson = "ericsson";
public static final String manuSamsung1 = "sec-sgh";
public static final String manuSony = "sony";
public static final String manuHtc = "htc"; //Popular Android and WinMo manufacturer
//In some UserAgents, the only clue is the operator.
public static final String svcDocomo = "docomo";
public static final String svcKddi = "kddi";
public static final String svcVodafone = "vodafone";
//Disambiguation strings.
public static final String disUpdate = "update"; //pda vs. update
/**
* Initialize the userAgent and httpAccept variables
*
* @param userAgent the User-Agent header
* @param httpAccept the Accept header
*/
public UserAgentInfo(String userAgent, String httpAccept) {
if (userAgent != null) {
this.userAgent = userAgent.toLowerCase();
}
if (httpAccept != null) {
this.httpAccept = httpAccept.toLowerCase();
}
//Intialize key stored values.
initDeviceScan();
}
/**
* Is the device is any Mobile Device (in list of course)
* @return
*/
public boolean isMobileDevice(){
if(isIphone || isAndroidPhone || isTierTablet || isTierIphone || isTierRichCss || isTierGenericMobile)
return true;
return false;
}
/**
* Return the lower case HTTP_USER_AGENT
* @return userAgent
*/
public String getUserAgent() {
return userAgent;
}
/**
* Return the lower case HTTP_ACCEPT
* @return httpAccept
*/
public String getHttpAccept() {
return httpAccept;
}
/**
* Return whether the device is an Iphone or iPod Touch
* @return isIphone
*/
public boolean getIsIphone() {
return isIphone;
}
/**
* Return whether the device is in the Tablet Tier.
* @return isTierTablet
*/
public boolean getIsTierTablet() {
return isTierTablet;
}
/**
* Return whether the device is in the Iphone Tier.
* @return isTierIphone
*/
public boolean getIsTierIphone() {
return isTierIphone;
}
/**
* Return whether the device is in the 'Rich CSS' tier of mobile devices.
* @return isTierRichCss
*/
public boolean getIsTierRichCss() {
return isTierRichCss;
}
/**
* Return whether the device is a generic, less-capable mobile device.
* @return isTierGenericMobile
*/
public boolean getIsTierGenericMobile() {
return isTierGenericMobile;
}
/**
* Initialize Key Stored Values.
*/
public void initDeviceScan() {
this.isIphone = detectIphoneOrIpod();
this.isAndroidPhone = detectAndroidPhone();
this.isTierTablet = detectTierTablet();
this.isTierIphone = detectTierIphone();
this.isTierRichCss = detectTierRichCss();
this.isTierGenericMobile = detectTierOtherPhones();
}
/**
* Detects if the current device is an iPhone.
* @return detection of an iPhone
*/
public boolean detectIphone() {
// The iPad and iPod touch say they're an iPhone! So let's disambiguate.
if (userAgent.indexOf(deviceIphone) != -1 &&
!detectIpad() &&
!detectIpod()) {
return true;
}
return false;
}
/**
* Detects if the current device is an iPod Touch.
* @return detection of an iPod Touch
*/
public boolean detectIpod() {
if (userAgent.indexOf(deviceIpod) != -1) {
return true;
}
return false;
}
/**
* Detects if the current device is an iPad tablet.
* @return detection of an iPad
*/
public boolean detectIpad() {
if (userAgent.indexOf(deviceIpad) != -1
&& detectWebkit()) {
return true;
}
return false;
}
/**
* Detects if the current device is an iPhone or iPod Touch.
* @return detection of an iPhone or iPod Touch
*/
public boolean detectIphoneOrIpod() {
//We repeat the searches here because some iPods may report themselves as an iPhone, which would be okay.
if (userAgent.indexOf(deviceIphone) != -1
|| userAgent.indexOf(deviceIpod) != -1) {
return true;
}
return false;
}
/**
* Detects *any* iOS device: iPhone, iPod Touch, iPad.
* @return detection of an Apple iOS device
*/
public boolean detectIos() {
if (detectIphoneOrIpod() || detectIpad()) {
return true;
}
return false;
}
/**
* Detects *any* Android OS-based device: phone, tablet, and multi-media player.
* Also detects Google TV.
* @return detection of an Android device
*/
public boolean detectAndroid() {
if ((userAgent.indexOf(deviceAndroid) != -1) ||
detectGoogleTV())
return true;
//Special check for the HTC Flyer 7" tablet. It should report here.
if (userAgent.indexOf(deviceHtcFlyer) != -1)
return true;
return false;
}
/**
* Detects if the current device is a (small-ish) Android OS-based device
* used for calling and/or multi-media (like a Samsung Galaxy Player).
* Google says these devices will have 'Android' AND 'mobile' in user agent.
* Ignores tablets (Honeycomb and later).
* @return detection of an Android phone
*/
public boolean detectAndroidPhone() {
if (detectAndroid() && (userAgent.indexOf(mobile) != -1))
return true;
//Special check for Android phones with Opera Mobile. They should report here.
if (detectOperaAndroidPhone())
return true;
//Special check for the HTC Flyer 7" tablet. It should report here.
if (userAgent.indexOf(deviceHtcFlyer) != -1)
return true;
return false;
}
/**
* Detects if the current device is a (self-reported) Android tablet.
* Google says these devices will have 'Android' and NOT 'mobile' in their user agent.
* @return detection of an Android tablet
*/
public boolean detectAndroidTablet() {
//First, let's make sure we're on an Android device.
if (!detectAndroid())
return false;
//Special check for Opera Android Phones. They should NOT report here.
if (detectOperaMobile())
return false;
//Special check for the HTC Flyer 7" tablet. It should NOT report here.
if (userAgent.indexOf(deviceHtcFlyer) != -1)
return false;
//Otherwise, if it's Android and does NOT have 'mobile' in it, Google says it's a tablet.
if ((userAgent.indexOf(mobile) > -1))
return false;
else
return true;
}
/**
* Detects if the current device is an Android OS-based device and
* the browser is based on WebKit.
* @return detection of an Android WebKit browser
*/
public boolean detectAndroidWebKit() {
if (detectAndroid() && detectWebkit()) {
return true;
}
return false;
}
/**
* Detects if the current device is a GoogleTV.
* @return detection of GoogleTV
*/
public boolean detectGoogleTV() {
if (userAgent.indexOf(deviceGoogleTV) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is based on WebKit.
* @return detection of a WebKit browser
*/
public boolean detectWebkit() {
if (userAgent.indexOf(engineWebKit) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is the Symbian S60 Open Source Browser.
* @return detection of Symbian S60 Browser
*/
public boolean detectS60OssBrowser() {
//First, test for WebKit, then make sure it's either Symbian or S60.
if (detectWebkit()
&& (userAgent.indexOf(deviceSymbian) != -1
|| userAgent.indexOf(deviceS60) != -1)) {
return true;
}
return false;
}
/**
*
* Detects if the current device is any Symbian OS-based device,
* including older S60, Series 70, Series 80, Series 90, and UIQ,
* or other browsers running on these devices.
* @return detection of SymbianOS
*/
public boolean detectSymbianOS() {
if (userAgent.indexOf(deviceSymbian) != -1
|| userAgent.indexOf(deviceS60) != -1
|| userAgent.indexOf(deviceS70) != -1
|| userAgent.indexOf(deviceS80) != -1
|| userAgent.indexOf(deviceS90) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is a
* Windows Phone 7 device.
* @return detection of Windows Phone 7
*/
public boolean detectWindowsPhone7() {
if (userAgent.indexOf(deviceWinPhone7) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is a Windows Mobile device.
* Excludes Windows Phone 7 devices.
* Focuses on Windows Mobile 6.xx and earlier.
* @return detection of Windows Mobile
*/
public boolean detectWindowsMobile() {
//Exclude new Windows Phone 7.
if (detectWindowsPhone7()) {
return false;
}
//Most devices use 'Windows CE', but some report 'iemobile'
// and some older ones report as 'PIE' for Pocket IE.
// We also look for instances of HTC and Windows for many of their WinMo devices.
if (userAgent.indexOf(deviceWinMob) != -1
|| userAgent.indexOf(deviceWinMob) != -1
|| userAgent.indexOf(deviceIeMob) != -1
|| userAgent.indexOf(enginePie) != -1
|| (userAgent.indexOf(manuHtc) != -1 && userAgent.indexOf(deviceWindows) != -1)
|| (detectWapWml() && userAgent.indexOf(deviceWindows) != -1)) {
return true;
}
//Test for Windows Mobile PPC but not old Macintosh PowerPC.
if (userAgent.indexOf(devicePpc) != -1 &&
!(userAgent.indexOf(deviceMacPpc) != -1))
return true;
return false;
}
/**
* Detects if the current browser is any BlackBerry.
* Includes the PlayBook.
* @return detection of Blackberry
*/
public boolean detectBlackBerry() {
if (userAgent.indexOf(deviceBB) != -1 ||
httpAccept.indexOf(vndRIM) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is on a BlackBerry tablet device.
* Example: PlayBook
* @return detection of a Blackberry Tablet
*/
public boolean detectBlackBerryTablet() {
if (userAgent.indexOf(deviceBBPlaybook) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is a BlackBerry device AND uses a
* WebKit-based browser. These are signatures for the new BlackBerry OS 6.
* Examples: Torch. Includes the Playbook.
* @return detection of a Blackberry device with WebKit browser
*/
public boolean detectBlackBerryWebKit() {
if (detectBlackBerry() &&
userAgent.indexOf(engineWebKit) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is a BlackBerry Touch
* device, such as the Storm, Torch, and Bold Touch. Excludes the Playbook.
* @return detection of a Blackberry touchscreen device
*/
public boolean detectBlackBerryTouch() {
if (detectBlackBerry() &&
(userAgent.indexOf(deviceBBStorm) != -1 ||
userAgent.indexOf(deviceBBTorch) != -1 ||
userAgent.indexOf(deviceBBBoldTouch) != -1)) {
return true;
}
return false;
}
/**
* Detects if the current browser is a BlackBerry device AND
* has a more capable recent browser. Excludes the Playbook.
* Examples, Storm, Bold, Tour, Curve2
* Excludes the new BlackBerry OS 6 and 7 browser!!
* @return detection of a Blackberry device with a better browser
*/
public boolean detectBlackBerryHigh() {
//Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser
if (detectBlackBerryWebKit())
return false;
if (detectBlackBerry()) {
if (detectBlackBerryTouch()
|| userAgent.indexOf(deviceBBBold) != -1
|| userAgent.indexOf(deviceBBTour) != -1
|| userAgent.indexOf(deviceBBCurve) != -1) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Detects if the current browser is a BlackBerry device AND
* has an older, less capable browser.
* Examples: Pearl, 8800, Curve1
* @return detection of a Blackberry device with a poorer browser
*/
public boolean detectBlackBerryLow() {
if (detectBlackBerry()) {
//Assume that if it's not in the High tier, then it's Low
if (detectBlackBerryHigh()
|| detectBlackBerryWebKit()) {
return false;
} else {
return true;
}
} else {
return false;
}
}
/**
* Detects if the current browser is on a PalmOS device.
* @return detection of a PalmOS device
*/
public boolean detectPalmOS() {
//Most devices nowadays report as 'Palm', but some older ones reported as Blazer or Xiino.
if (userAgent.indexOf(devicePalm) != -1
|| userAgent.indexOf(engineBlazer) != -1
|| userAgent.indexOf(engineXiino) != -1) {
//Make sure it's not WebOS first
if (detectPalmWebOS()) {
return false;
} else {
return true;
}
}
return false;
}
/**
* Detects if the current browser is on a Palm device
* running the new WebOS.
* @return detection of a Palm WebOS device
*/
public boolean detectPalmWebOS() {
if (userAgent.indexOf(deviceWebOS) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is on an HP tablet running WebOS.
* @return detection of an HP WebOS tablet
*/
public boolean detectWebOSTablet() {
if (userAgent.indexOf(deviceWebOShp) != -1 &&
userAgent.indexOf(deviceTablet) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is a
* Garmin Nuvifone.
* @return detection of a Garmin Nuvifone
*/
public boolean detectGarminNuvifone() {
if (userAgent.indexOf(deviceNuvifone) != -1) {
return true;
}
return false;
}
/**
* Check to see whether the device is any device
* in the 'smartphone' category.
* @return detection of a general smartphone device
*/
public boolean detectSmartphone() {
return (isIphone
|| isAndroidPhone
|| isTierIphone
|| detectS60OssBrowser()
|| detectSymbianOS()
|| detectWindowsMobile()
|| detectWindowsPhone7()
|| detectBlackBerry()
|| detectPalmWebOS()
|| detectPalmOS()
|| detectGarminNuvifone());
}
/**
* Detects whether the device is a Brew-powered device.
* @return detection of a Brew device
*/
public boolean detectBrewDevice() {
if (userAgent.indexOf(deviceBrew) != -1) {
return true;
}
return false;
}
/**
* Detects the Danger Hiptop device.
* @return detection of a Danger Hiptop
*/
public boolean detectDangerHiptop() {
if (userAgent.indexOf(deviceDanger) != -1
|| userAgent.indexOf(deviceHiptop) != -1) {
return true;
}
return false;
}
/**
* Detects Opera Mobile or Opera Mini.
* @return detection of an Opera browser for a mobile device
*/
public boolean detectOperaMobile() {
if (userAgent.indexOf(engineOpera) != -1
&& (userAgent.indexOf(mini) != -1
|| userAgent.indexOf(mobi) != -1)) {
return true;
}
return false;
}
/**
* Detects Opera Mobile on an Android phone.
* @return detection of an Opera browser on an Android phone
*/
public boolean detectOperaAndroidPhone() {
if (userAgent.indexOf(engineOpera) != -1
&& (userAgent.indexOf(deviceAndroid) != -1
&& userAgent.indexOf(mobi) != -1)) {
return true;
}
return false;
}
/**
* Detects Opera Mobile on an Android tablet.
* @return detection of an Opera browser on an Android tablet
*/
public boolean detectOperaAndroidTablet() {
if (userAgent.indexOf(engineOpera) != -1
&& (userAgent.indexOf(deviceAndroid) != -1
&& userAgent.indexOf(deviceTablet) != -1)) {
return true;
}
return false;
}
/**
* Detects whether the device supports WAP or WML.
* @return detection of a WAP- or WML-capable device
*/
public boolean detectWapWml() {
if (httpAccept.indexOf(vndwap) != -1
|| httpAccept.indexOf(wml) != -1) {
return true;
}
return false;
}
/**
* Detects if the current device is an Amazon Kindle (eInk devices only).
* Note: For the Kindle Fire, use the normal Android methods.
* @return detection of a Kindle
*/
public boolean detectKindle() {
if (userAgent.indexOf(deviceKindle)!= -1 &&
!detectAndroid()) {
return true;
}
return false;
}
/**
* Detects if the current device is a mobile device.
* This method catches most of the popular modern devices.
* Excludes Apple iPads and other modern tablets.
* @return detection of any mobile device using the quicker method
*/
public boolean detectMobileQuick() {
//Let's exclude tablets
if (isTierTablet) {
return false;
}
//Most mobile browsing is done on smartphones
if (detectSmartphone()) {
return true;
}
if (detectWapWml()
|| detectBrewDevice()
|| detectOperaMobile()) {
return true;
}
if ((userAgent.indexOf(engineNetfront) != -1)
|| (userAgent.indexOf(engineUpBrowser) != -1)
|| (userAgent.indexOf(engineOpenWeb) != -1)) {
return true;
}
if (detectDangerHiptop()
|| detectMidpCapable()
|| detectMaemoTablet()
|| detectArchos()) {
return true;
}
if ((userAgent.indexOf(devicePda) != -1) &&
(userAgent.indexOf(disUpdate) < 0)) //no index found
{
return true;
}
if (userAgent.indexOf(mobile) != -1) {
return true;
}
return false;
}
/**
* Detects if the current device is a Sony Playstation.
* @return detection of Sony Playstation
*/
public boolean detectSonyPlaystation() {
if (userAgent.indexOf(devicePlaystation) != -1) {
return true;
}
return false;
}
/**
* Detects if the current device is a Nintendo game device.
* @return detection of Nintendo
*/
public boolean detectNintendo() {
if (userAgent.indexOf(deviceNintendo) != -1
|| userAgent.indexOf(deviceWii) != -1
|| userAgent.indexOf(deviceNintendoDs) != -1) {
return true;
}
return false;
}
/**
* Detects if the current device is a Microsoft Xbox.
* @return detection of Xbox
*/
public boolean detectXbox() {
if (userAgent.indexOf(deviceXbox) != -1) {
return true;
}
return false;
}
/**
* Detects if the current device is an Internet-capable game console.
* @return detection of any Game Console
*/
public boolean detectGameConsole() {
if (detectSonyPlaystation()
|| detectNintendo()
|| detectXbox()) {
return true;
}
return false;
}
/**
* Detects if the current device supports MIDP, a mobile Java technology.
* @return detection of a MIDP mobile Java-capable device
*/
public boolean detectMidpCapable() {
if (userAgent.indexOf(deviceMidp) != -1
|| httpAccept.indexOf(deviceMidp) != -1) {
return true;
}
return false;
}
/**
* Detects if the current device is on one of the Maemo-based Nokia Internet Tablets.
* @return detection of a Maemo OS tablet
*/
public boolean detectMaemoTablet() {
if (userAgent.indexOf(maemo) != -1) {
return true;
} else if (userAgent.indexOf(linux) != -1
&& userAgent.indexOf(deviceTablet) != -1
&& !detectWebOSTablet()
&& !detectAndroid()) {
return true;
}
return false;
}
/**
* Detects if the current device is an Archos media player/Internet tablet.
* @return detection of an Archos media player
*/
public boolean detectArchos() {
if (userAgent.indexOf(deviceArchos) != -1) {
return true;
}
return false;
}
/**
* Detects if the current browser is a Sony Mylo device.
* @return detection of a Sony Mylo device
*/
public boolean detectSonyMylo() {
if (userAgent.indexOf(manuSony) != -1
&& (userAgent.indexOf(qtembedded) != -1
|| userAgent.indexOf(mylocom2) != -1)) {
return true;
}
return false;
}
/**
* The longer and more thorough way to detect for a mobile device.
* Will probably detect most feature phones,
* smartphone-class devices, Internet Tablets,
* Internet-enabled game consoles, etc.
* This ought to catch a lot of the more obscure and older devices, also --
* but no promises on thoroughness!
* @return detection of any mobile device using the more thorough method
*/
public boolean detectMobileLong() {
if (detectMobileQuick()
|| detectGameConsole()
|| detectSonyMylo()) {
return true;
}
//detect older phones from certain manufacturers and operators.
if (userAgent.indexOf(uplink) != -1) {
return true;
}
if (userAgent.indexOf(manuSonyEricsson) != -1) {
return true;
}
if (userAgent.indexOf(manuericsson) != -1) {
return true;
}
if (userAgent.indexOf(manuSamsung1) != -1) {
return true;
}
if (userAgent.indexOf(svcDocomo) != -1) {
return true;
}
if (userAgent.indexOf(svcKddi) != -1) {
return true;
}
if (userAgent.indexOf(svcVodafone) != -1) {
return true;
}
return false;
}
//*****************************
// For Mobile Web Site Design
//*****************************
/**
* The quick way to detect for a tier of devices.
* This method detects for the new generation of
* HTML 5 capable, larger screen tablets.
* Includes iPad, Android (e.g., Xoom), BB Playbook, WebOS, etc.
* @return detection of any device in the Tablet Tier
*/
public boolean detectTierTablet() {
if (detectIpad()
|| detectAndroidTablet()
|| detectBlackBerryTablet()
|| detectWebOSTablet()) {
return true;
}
return false;
}
/**
* The quick way to detect for a tier of devices.
* This method detects for devices which can
* display iPhone-optimized web content.
* Includes iPhone, iPod Touch, Android, Windows Phone 7, Palm WebOS, etc.
* @return detection of any device in the iPhone/Android/WP7/WebOS Tier
*/
public boolean detectTierIphone() {
if (isIphone
|| isAndroidPhone
|| (detectBlackBerryWebKit()
&& detectBlackBerryTouch())
|| detectWindowsPhone7()
|| detectPalmWebOS()
|| detectGarminNuvifone()) {
return true;
}
return false;
}
/**
* The quick way to detect for a tier of devices.
* This method detects for devices which are likely to be capable
* of viewing CSS content optimized for the iPhone,
* but may not necessarily support JavaScript.
* Excludes all iPhone Tier devices.
* @return detection of any device in the 'Rich CSS' Tier
*/
public boolean detectTierRichCss() {
boolean result = false;
//The following devices are explicitly ok.
//Note: 'High' BlackBerry devices ONLY
if (detectMobileQuick()) {
if (!detectTierIphone()) {
//The following devices are explicitly ok.
//Note: 'High' BlackBerry devices ONLY
//Older Windows 'Mobile' isn't good enough for iPhone Tier.
if (detectWebkit()
|| detectS60OssBrowser()
|| detectBlackBerryHigh()
|| detectWindowsMobile()
|| userAgent.indexOf(engineTelecaQ) !=
-1) {
result= true;
} // if detectWebkit()
} //if !detectTierIphone()
} //if detectMobileQuick()
return result;
}
/**
* The quick way to detect for a tier of devices.
* This method detects for all other types of phones,
* but excludes the iPhone and RichCSS Tier devices.
* @return detection of a mobile device in the less capable tier
*/
public boolean detectTierOtherPhones() {
//Exclude devices in the other 2 categories
if (detectMobileLong()
&& !detectTierIphone()
&& !detectTierRichCss()) {
return true;
}
return false;
}
} | ferremarce/TEST_USABILIDAD | src/main/java/tesisweb/controller/general/UserAgentInfo.java | Java | gpl-2.0 | 35,267 |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Reports\Block\Adminhtml\Sales;
/**
* Adminhtml invoiced report page content block
*
* @api
* @author Magento Core Team <core@magentocommerce.com>
* @since 100.0.2
*/
class Invoiced extends \Magento\Backend\Block\Widget\Grid\Container
{
/**
* Template file
*
* @var string
*/
protected $_template = 'Magento_Reports::report/grid/container.phtml';
/**
* {@inheritdoc}
*/
protected function _construct()
{
$this->_blockGroup = 'Magento_Reports';
$this->_controller = 'adminhtml_sales_invoiced';
$this->_headerText = __('Total Invoiced vs. Paid Report');
parent::_construct();
$this->buttonList->remove('add');
$this->addButton(
'filter_form_submit',
['label' => __('Show Report'), 'onclick' => 'filterFormSubmit()', 'class' => 'primary']
);
}
/**
* Get filter URL
*
* @return string
*/
public function getFilterUrl()
{
$this->getRequest()->setParam('filter', null);
return $this->getUrl('*/*/invoiced', ['_current' => true]);
}
}
| kunj1988/Magento2 | app/code/Magento/Reports/Block/Adminhtml/Sales/Invoiced.php | PHP | gpl-2.0 | 1,251 |
<?php
$contents="<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' type='text/javascript' charset='utf-8'></script>
<script src='js/jquery.uniform.min.js' type='text/javascript' charset='utf-8'></script>
<script type='text/javascript' charset='utf-8'>
$(function(){
$('input, textarea, select, button').uniform();
});
</script>
<link rel='stylesheet' href='css/uniform.default.css' type='text/css' media='screen'>
<style type='text/css' media='screen'>
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #666;
padding: 40px;
}
h1 {
margin-top: 0;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
margin-bottom: 20px;
clear: both;
}
label {
font-size: 10px;
font-weight: bold;
text-transform: uppercase;
display: block;
margin-bottom: 3px;
clear: both;
}
</style>
</head>
";
include('../openinviter.php');
$inviter=new OpenInviter();
$oi_services=$inviter->getPlugins();
$pluginContent="";
if (isset($_POST['provider_box']))
{
if (isset($oi_services['email'][$_POST['provider_box']])) $plugType='email';
elseif (isset($oi_services['social'][$_POST['provider_box']])) $plugType='social';
else $plugType='';
if ($plugType) $pluginContent=createPluginContent($_POST['provider_box']);
}
elseif(!empty($_GET['provider_box']))
{
if (isset($oi_services['email'][$_GET['provider_box']])) $plugType='email';
elseif (isset($oi_services['social'][$_GET['provider_box']])) $plugType='social';
else $plugType='';
if($plugType)
{
$_POST['provider_box']=$_GET['provider_box'];
$pluginContent=createPluginContent($_GET['provider_box']);
}
}
else { $plugType = ''; $_POST['provider_box']=''; }
function ers($ers)
{
if (!empty($ers))
{
$contents="<table cellspacing='0' cellpadding='0' style='border:1px solid red;' align='center'><tr><td valign='middle' style='padding:3px' valign='middle'><img src='imgs/ers.gif'></td><td valign='middle' style='color:red;padding:5px;'>";
foreach ($ers as $key=>$error)
$contents.="{$error}<br >";
$contents.="</td></tr></table><br >";
return $contents;
}
}
function oks($oks)
{
if (!empty($oks))
{
$contents="<table border='0' cellspacing='0' cellpadding='10' style='border:1px solid #5897FE;' align='center'><tr><td valign='middle' valign='middle'><img src='imgs/oks.gif' ></td><td valign='middle' style='color:#5897FE;padding:5px;'> ";
foreach ($oks as $key=>$msg)
$contents.="{$msg}<br >";
$contents.="</td></tr></table><br >";
return $contents;
}
}
if (!empty($_POST['step'])) $step=$_POST['step'];
else $step='get_contacts';
$ers=array();$oks=array();$import_ok=false;$done=false;
if ($_SERVER['REQUEST_METHOD']=='POST')
{
if ($step=='get_contacts')
{
if (empty($_POST['email_box']))
$ers['email']="Email missing !";
if (empty($_POST['password_box']))
$ers['password']="Password missing !";
if (empty($_POST['provider_box']))
$ers['provide']='Provider missing!';
if (count($ers)==0)
{
$inviter->startPlugin($_POST['provider_box']);
$internal=$inviter->getInternalError();
if ($internal)
$ers['inviter']=$internal;
elseif (!$inviter->login($_POST['email_box'],$_POST['password_box']))
{
$internal=$inviter->getInternalError();
$ers['login']=($internal?$internal:"Login failed. Please check the email and password you have provided and try again later !");
}
elseif (false===$contacts=$inviter->getMyContacts())
$ers['contacts']="Unable to get contacts !";
else
{
$import_ok=true;
$step='send_invites';
$_POST['oi_session_id']=$inviter->plugin->getSessionID();
$_POST['message_box']='';
}
}
}
elseif ($step=='send_invites')
{
if (empty($_POST['provider_box'])) $ers['provider']='Provider missing !';
else
{
$inviter->startPlugin($_POST['provider_box']);
$internal=$inviter->getInternalError();
if ($internal) $ers['internal']=$internal;
else
{
if (empty($_POST['email_box'])) $ers['inviter']='Inviter information missing !';
if (empty($_POST['oi_session_id'])) $ers['session_id']='No active session !';
if (empty($_POST['message_box'])) $ers['message_body']='Message missing !';
else $_POST['message_box']=strip_tags($_POST['message_box']);
$selected_contacts=array();$contacts=array();
$message=array('subject'=>$inviter->settings['message_subject'],'body'=>$inviter->settings['message_body'],'attachment'=>"\n\rAttached message: \n\r".$_POST['message_box']);
if ($inviter->showContacts())
{
foreach ($_POST as $key=>$val)
if (strpos($key,'check_')!==false)
$selected_contacts[$_POST['email_'.$val]]=$_POST['name_'.$val];
elseif (strpos($key,'email_')!==false)
{
$temp=explode('_',$key);$counter=$temp[1];
if (is_numeric($temp[1])) $contacts[$val]=$_POST['name_'.$temp[1]];
}
if (count($selected_contacts)==0) $ers['contacts']="You haven't selected any contacts to invite !";
}
}
}
if (count($ers)==0)
{
$sendMessage=$inviter->sendMessage($_POST['oi_session_id'],$message,$selected_contacts);
$inviter->logout();
if ($sendMessage===-1)
{
$message_footer="\r\n\r\nThis invite was sent using OpenInviter technology.";
$message_subject=$_POST['email_box'].$message['subject'];
$message_body=$message['body'].$message['attachment'].$message_footer;
$headers="From: {$_POST['email_box']}";
foreach ($selected_contacts as $email=>$name)
mail($email,$message_subject,$message_body,$headers);
$oks['mails']="Mails sent successfully";
}
elseif ($sendMessage===false)
{
$internal=$inviter->getInternalError();
$ers['internal']=($internal?$internal:"There were errors while sending your invites.<br>Please try again later!");
}
else $oks['internal']="Invites sent successfully!";
$done=true;
}
}
}
else
{
$_POST['email_box']='';
$_POST['password_box']='';
}
$contents.="<script type='text/javascript'>
function toggleAll(element)
{
var form = document.forms.openinviter, z = 0;
for(z=0; z<form.length;z++)
{
if(form[z].type == 'checkbox')
form[z].checked = element.checked;
}
}
</script>";
$contents.="<form action='' method='POST' name='openinviter'>".ers($ers).oks($oks);
if (!$done)
{
if ($step=='get_contacts')
{
$contents.="<table align='center' class='thTable' cellspacing='2' cellpadding='0' style='border:none;'>
<tr><td align='right'><label for='email_box'>Email</label></td><td><input type='text' name='email_box' value='{$_POST['email_box']}'></td></tr>
<tr><td align='right'><label for='password_box'>Password</label></td><td><input type='password' name='password_box' value='{$_POST['password_box']}'></td></tr>
<tr><td colspan='2' align='center'><input type='submit' name='import' value='Import Contacts'></td></tr>
</table><input type='hidden' name='provider_box' value='{$_POST['provider_box']}'><input type='hidden' name='step' value='get_contacts'>";
}
else
$contents.="<table class='thTable' cellspacing='0' cellpadding='0' style='border:none;'>
<tr><td align='center' valign='top'><label for='message_box'>Message</label></td><td><textarea rows='5' cols='50' name='message_box' style='width:300px;'>{$_POST['message_box']}</textarea></td></tr>
<tr><td align='center' colspan='2'><input type='submit' name='send' value='Send Invites' ></td></tr>
</table>";
}
$contents.="<center>{$pluginContent}</center>";
if (!$done)
{
if ($step=='send_invites')
{
if ($inviter->showContacts())
{
$contents.="<table align='center' cellspacing='0' cellpadding='0'><tr><td colspan='".($plugType=='email'? "3":"2")."'>Your contacts</td></tr>";
if (count($contacts)==0)
$contents.="<tr><td align='center' style='padding:20px;' colspan='".($plugType=='email'? "3":"2")."'>You do not have any contacts in your address book.</td></tr>";
else
{
$contents.="<tr><td><input type='checkbox' onChange='toggleAll(this)' name='toggle_all' title='Select/Deselect all' checked>Invite?</td><td>Name</td>".($plugType == 'email' ?"<td>E-mail</td>":"")."</tr>";
$counter=0;
foreach ($contacts as $email=>$name)
{
$counter++;
$contents.="<tr><td><input name='check_{$counter}' value='{$counter}' type='checkbox' checked><input type='hidden' name='email_{$counter}' value='{$email}'><input type='hidden' name='name_{$counter}' value='{$name}'></td><td>{$name}</td>".($plugType == 'email' ?"<td>{$email}</td>":"")."</tr>";
}
$contents.="<tr><td colspan='".($plugType=='email'? "3":"2")."' style='padding:3px;'><input type='submit' name='send' value='Send invites'></td></tr>";
}
$contents.="</table>";
}
$contents.="<input type='hidden' name='step' value='send_invites'>
<input type='hidden' name='provider_box' value='{$_POST['provider_box']}'>
<input type='hidden' name='email_box' value='{$_POST['email_box']}'>
<input type='hidden' name='oi_session_id' value='{$_POST['oi_session_id']}'>";
$contents.="<script>self.parent.$.fancybox.resize();</script>";
}
}
$contents.="</form>";
echo $contents;
function createPluginContent($pr)
{
global $oi_services,$plugType;
$a=array_keys($oi_services[$plugType]);
foreach($a as $r=>$sv) if ($sv==$pr) break;
return $contentPlugin="<div style='border:none; display:block; height:60px; margin:0; padding:0; width:130px; background-position: 0px ".(-60*$r)."px; background-image:url(\"imgs/{$plugType}_services.png\");'></div>";
}
?>
| berryjace/www | crm/library/ThirdParty/OpenInviter/more_examples/get_contacts.php | PHP | gpl-2.0 | 9,479 |
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem, NavItem, NavLink } from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCog, faExternalLinkAlt, faSignOutAlt } from '@fortawesome/free-solid-svg-icons';
import { useTranslation } from 'react-i18next';
import Avatar from 'components/Avatar';
import { openSettingsModal } from 'store/actions/settingsActions';
import { logOut } from 'store/actions/userActions';
import './UserDropdown.scss';
export default function UserDropdow() {
const { t } = useTranslation();
const dispatch = useDispatch();
const user = useSelector((state) => state.user);
return (
<React.Fragment>
<UncontrolledDropdown data-cy="UserDropdown" nav inNavbar>
<DropdownToggle nav caret className="ows-dropdown-user">
<Avatar user={user} alt={user.name} size="sm" />
<span className="ows-username" data-cy="UserDropdown-username">
{user.name}
</span>
</DropdownToggle>
<DropdownMenu right>
<DropdownItem href={user.url} target="_blank" rel="noopener" data-cy="UserDropdown-profileLink">
{t('viewProfile')}
<FontAwesomeIcon className="ml-1" color="var(--gray)" icon={faExternalLinkAlt} />
</DropdownItem>
<DropdownItem divider />
<DropdownItem onClick={openSettingsModal(dispatch)}>
<FontAwesomeIcon icon={faCog} />
{t('settings')}
</DropdownItem>
<DropdownItem className="d-none d-md-block" onClick={logOut(dispatch)}>
<FontAwesomeIcon icon={faSignOutAlt} />
{t('logOut')}
</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
<NavItem className="d-block d-md-none">
<NavLink onClick={logOut(dispatch)}>
<FontAwesomeIcon icon={faSignOutAlt} />
{t('logOut')}
</NavLink>
</NavItem>
</React.Fragment>
);
}
| elamperti/OpenWebScrobbler | src/components/Navigation/partials/UserDropdown.js | JavaScript | gpl-2.0 | 2,071 |
/*
* Copyright (C) 2005-2011 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "SpellMgr.h"
#include "ObjectMgr.h"
#include "SpellAuraDefines.h"
#include "ProgressBar.h"
#include "DBCStores.h"
#include "World.h"
#include "Chat.h"
#include "Spell.h"
#include "BattleGroundMgr.h"
#include "MapManager.h"
#include "Unit.h"
SpellMgr::SpellMgr()
{
}
SpellMgr::~SpellMgr()
{
}
SpellMgr& SpellMgr::Instance()
{
static SpellMgr spellMgr;
return spellMgr;
}
int32 GetSpellDuration(SpellEntry const *spellInfo)
{
if(!spellInfo)
return 0;
SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex);
if(!du)
return 0;
return (du->Duration[0] == -1) ? -1 : abs(du->Duration[0]);
}
int32 GetSpellMaxDuration(SpellEntry const *spellInfo)
{
if(!spellInfo)
return 0;
SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex);
if(!du)
return 0;
return (du->Duration[2] == -1) ? -1 : abs(du->Duration[2]);
}
int32 CalculateSpellDuration(SpellEntry const *spellInfo, Unit const* caster)
{
int32 duration = GetSpellDuration(spellInfo);
if (duration != -1 && caster)
{
int32 maxduration = GetSpellMaxDuration(spellInfo);
if (duration != maxduration && caster->GetTypeId() == TYPEID_PLAYER)
duration += int32((maxduration - duration) * ((Player*)caster)->GetComboPoints() / 5);
if (Player* modOwner = caster->GetSpellModOwner())
{
modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_DURATION, duration);
if (duration < 0)
duration = 0;
}
}
return duration;
}
uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell const* spell)
{
if (spell)
{
// some triggered spells have data only usable for client
if (spell->IsTriggeredSpellWithRedundentData())
return 0;
// spell targeted to non-trading trade slot item instant at trade success apply
if (spell->GetCaster()->GetTypeId()==TYPEID_PLAYER)
if (TradeData* my_trade = ((Player*)(spell->GetCaster()))->GetTradeData())
if (Item* nonTrade = my_trade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED))
if (nonTrade == spell->m_targets.getItemTarget())
return 0;
}
SpellCastTimesEntry const *spellCastTimeEntry = sSpellCastTimesStore.LookupEntry(spellInfo->CastingTimeIndex);
// not all spells have cast time index and this is all is pasiive abilities
if (!spellCastTimeEntry)
return 0;
int32 castTime = spellCastTimeEntry->CastTime;
if (spell)
{
if (Player* modOwner = spell->GetCaster()->GetSpellModOwner())
modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, castTime, spell);
if (!(spellInfo->Attributes & (SPELL_ATTR_UNK4|SPELL_ATTR_TRADESPELL)))
castTime = int32(castTime * spell->GetCaster()->GetFloatValue(UNIT_MOD_CAST_SPEED));
else
{
if (spell->IsRangedSpell() && !spell->IsAutoRepeat())
castTime = int32(castTime * spell->GetCaster()->m_modAttackSpeedPct[RANGED_ATTACK]);
}
}
if (spellInfo->Attributes & SPELL_ATTR_RANGED && (!spell || !spell->IsAutoRepeat()))
castTime += 500;
return (castTime > 0) ? uint32(castTime) : 0;
}
uint32 GetSpellCastTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype )
{
uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
if (CastingTime > 7000) CastingTime = 7000;
if (CastingTime < 1500) CastingTime = 1500;
if(damagetype == DOT && !IsChanneledSpell(spellProto))
CastingTime = 3500;
int32 overTime = 0;
uint8 effects = 0;
bool DirectDamage = false;
bool AreaEffect = false;
for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
AreaEffect = true;
for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
switch (spellProto->Effect[i])
{
case SPELL_EFFECT_SCHOOL_DAMAGE:
case SPELL_EFFECT_POWER_DRAIN:
case SPELL_EFFECT_HEALTH_LEECH:
case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
case SPELL_EFFECT_POWER_BURN:
case SPELL_EFFECT_HEAL:
DirectDamage = true;
break;
case SPELL_EFFECT_APPLY_AURA:
switch (spellProto->EffectApplyAuraName[i])
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_PERIODIC_LEECH:
if ( GetSpellDuration(spellProto) )
overTime = GetSpellDuration(spellProto);
break;
// Penalty for additional effects
case SPELL_AURA_DUMMY:
++effects;
break;
case SPELL_AURA_MOD_DECREASE_SPEED:
++effects;
break;
case SPELL_AURA_MOD_CONFUSE:
case SPELL_AURA_MOD_STUN:
case SPELL_AURA_MOD_ROOT:
// -10% per effect
effects += 2;
break;
default:
break;
}
break;
default:
break;
}
}
// Combined Spells with Both Over Time and Direct Damage
if (overTime > 0 && CastingTime > 0 && DirectDamage)
{
// mainly for DoTs which are 3500 here otherwise
uint32 OriginalCastTime = GetSpellCastTime(spellProto);
if (OriginalCastTime > 7000) OriginalCastTime = 7000;
if (OriginalCastTime < 1500) OriginalCastTime = 1500;
// Portion to Over Time
float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
if (damagetype == DOT)
CastingTime = uint32(CastingTime * PtOT);
else if (PtOT < 1.0f)
CastingTime = uint32(CastingTime * (1 - PtOT));
else
CastingTime = 0;
}
// Area Effect Spells receive only half of bonus
if (AreaEffect)
CastingTime /= 2;
// 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
{
if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
(spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH))
{
CastingTime /= 2;
break;
}
}
// -5% of total per any additional effect (multiplicative)
for (int i = 0; i < effects; ++i)
CastingTime *= 0.95f;
return CastingTime;
}
uint16 GetSpellAuraMaxTicks(SpellEntry const* spellInfo)
{
int32 DotDuration = GetSpellDuration(spellInfo);
if(DotDuration == 0)
return 1;
// 200% limit
if(DotDuration > 30000)
DotDuration = 30000;
for (int j = 0; j < MAX_EFFECT_INDEX; ++j)
{
if (spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
spellInfo->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
spellInfo->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_HEAL ||
spellInfo->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
{
if (spellInfo->EffectAmplitude[j] != 0)
return DotDuration / spellInfo->EffectAmplitude[j];
break;
}
}
return 6;
}
uint16 GetSpellAuraMaxTicks(uint32 spellId)
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
{
sLog.outError("GetSpellAuraMaxTicks: Spell %u not exist!", spellId);
return 1;
}
return GetSpellAuraMaxTicks(spellInfo);
}
float CalculateDefaultCoefficient(SpellEntry const *spellProto, DamageEffectType const damagetype)
{
// Damage over Time spells bonus calculation
float DotFactor = 1.0f;
if (damagetype == DOT)
{
if (!IsChanneledSpell(spellProto))
DotFactor = GetSpellDuration(spellProto) / 15000.0f;
if (uint16 DotTicks = GetSpellAuraMaxTicks(spellProto))
DotFactor /= DotTicks;
}
// Distribute Damage over multiple effects, reduce by AoE
float coeff = GetSpellCastTimeForBonus(spellProto, damagetype) / 3500.0f;
return coeff * DotFactor;
}
WeaponAttackType GetWeaponAttackType(SpellEntry const *spellInfo)
{
if(!spellInfo)
return BASE_ATTACK;
switch (spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE:
if (spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
return OFF_ATTACK;
else
return BASE_ATTACK;
break;
case SPELL_DAMAGE_CLASS_RANGED:
return RANGED_ATTACK;
break;
default:
// Wands
if (spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
return RANGED_ATTACK;
else
return BASE_ATTACK;
break;
}
}
bool IsPassiveSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return false;
return IsPassiveSpell(spellInfo);
}
bool IsPassiveSpell(SpellEntry const *spellInfo)
{
return (spellInfo->Attributes & SPELL_ATTR_PASSIVE) != 0;
}
bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 spellId_2)
{
SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
if(!spellInfo_1 || !spellInfo_2) return false;
if(spellInfo_1->Id == spellId_2) return false;
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
for (int32 j = 0; j < MAX_EFFECT_INDEX; ++j)
{
if (spellInfo_1->Effect[i] == spellInfo_2->Effect[j]
&& spellInfo_1->EffectApplyAuraName[i] == spellInfo_2->EffectApplyAuraName[j]
&& spellInfo_1->EffectMiscValue[i] == spellInfo_2->EffectMiscValue[j]
&& spellInfo_1->EffectItemType[i] == spellInfo_2->EffectItemType[j]
&& (spellInfo_1->Effect[i] != 0 || spellInfo_1->EffectApplyAuraName[i] != 0 ||
spellInfo_1->EffectMiscValue[i] != 0 || spellInfo_1->EffectItemType[i] != 0))
return true;
}
}
return false;
}
int32 CompareAuraRanks(uint32 spellId_1, uint32 spellId_2)
{
SpellEntry const*spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
SpellEntry const*spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
if(!spellInfo_1 || !spellInfo_2) return 0;
if (spellId_1 == spellId_2) return 0;
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (spellInfo_1->Effect[i] != 0 && spellInfo_2->Effect[i] != 0 && spellInfo_1->Effect[i] == spellInfo_2->Effect[i])
{
int32 diff = spellInfo_1->EffectBasePoints[i] - spellInfo_2->EffectBasePoints[i];
if (spellInfo_1->CalculateSimpleValue(SpellEffectIndex(i)) < 0 && spellInfo_2->CalculateSimpleValue(SpellEffectIndex(i)) < 0)
return -diff;
else return diff;
}
}
return 0;
}
SpellSpecific GetSpellSpecific(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if(!spellInfo)
return SPELL_NORMAL;
switch(spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
// Food / Drinks (mostly)
if (spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED)
{
bool food = false;
bool drink = false;
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
switch(spellInfo->EffectApplyAuraName[i])
{
// Food
case SPELL_AURA_MOD_REGEN:
case SPELL_AURA_OBS_MOD_HEALTH:
food = true;
break;
// Drink
case SPELL_AURA_MOD_POWER_REGEN:
case SPELL_AURA_OBS_MOD_MANA:
drink = true;
break;
default:
break;
}
}
if (food && drink)
return SPELL_FOOD_AND_DRINK;
else if (food)
return SPELL_FOOD;
else if (drink)
return SPELL_DRINK;
}
else
{
// Well Fed buffs (must be exclusive with Food / Drink replenishment effects, or else Well Fed will cause them to be removed)
// SpellIcon 2560 is Spell 46687, does not have this flag
if ((spellInfo->AttributesEx2 & SPELL_ATTR_EX2_FOOD_BUFF) || spellInfo->SpellIconID == 2560)
return SPELL_WELL_FED;
else if (spellInfo->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_STAT && spellInfo->Attributes & SPELL_ATTR_NOT_SHAPESHIFT &&
spellInfo->SchoolMask & SPELL_SCHOOL_MASK_NATURE && spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
return SPELL_SCROLL;
}
break;
}
case SPELLFAMILY_MAGE:
{
// family flags 18(Molten), 25(Frost/Ice), 28(Mage)
if (spellInfo->SpellFamilyFlags & UI64LIT(0x12040000))
return SPELL_MAGE_ARMOR;
if ((spellInfo->SpellFamilyFlags & UI64LIT(0x1000000)) && spellInfo->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_CONFUSE)
return SPELL_MAGE_POLYMORPH;
break;
}
case SPELLFAMILY_WARRIOR:
{
if (spellInfo->SpellFamilyFlags & UI64LIT(0x00008000010000))
return SPELL_POSITIVE_SHOUT;
break;
}
case SPELLFAMILY_WARLOCK:
{
// only warlock curses have this
if (spellInfo->Dispel == DISPEL_CURSE)
return SPELL_CURSE;
// Warlock (Demon Armor | Demon Skin | Fel Armor)
if (spellInfo->IsFitToFamilyMask(UI64LIT(0x2000002000000000), 0x00000010))
return SPELL_WARLOCK_ARMOR;
// Unstable Affliction | Immolate
if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0000010000000004)))
return SPELL_UA_IMMOLATE;
break;
}
case SPELLFAMILY_PRIEST:
{
// "Well Fed" buff from Blessed Sunfruit, Blessed Sunfruit Juice, Alterac Spring Water
if ((spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_SITTING) &&
(spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_AUTOATTACK) &&
(spellInfo->SpellIconID == 52 || spellInfo->SpellIconID == 79))
return SPELL_WELL_FED;
break;
}
case SPELLFAMILY_HUNTER:
{
// only hunter stings have this
if (spellInfo->Dispel == DISPEL_POISON)
return SPELL_STING;
// only hunter aspects have this
if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0044000000380000), 0x00001010))
return SPELL_ASPECT;
break;
}
case SPELLFAMILY_PALADIN:
{
if (IsSealSpell(spellInfo))
return SPELL_SEAL;
if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000011010002)))
return SPELL_BLESSING;
if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000000002190)))
return SPELL_HAND;
// skip Heart of the Crusader that have also same spell family mask
if (spellInfo->IsFitToFamilyMask(UI64LIT(0x00000820180400)) && (spellInfo->AttributesEx3 & 0x200) && (spellInfo->SpellIconID != 237))
return SPELL_JUDGEMENT;
// only paladin auras have this (for palaldin class family)
if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000000000000), 0x00000020))
return SPELL_AURA;
break;
}
case SPELLFAMILY_SHAMAN:
{
if (IsElementalShield(spellInfo))
return SPELL_ELEMENTAL_SHIELD;
break;
}
case SPELLFAMILY_POTION:
return sSpellMgr.GetSpellElixirSpecific(spellInfo->Id);
case SPELLFAMILY_DEATHKNIGHT:
if (spellInfo->Category == 47)
return SPELL_PRESENCE;
break;
}
// Tracking spells (exclude Well Fed, some other always allowed cases)
if ((IsSpellHaveAura(spellInfo, SPELL_AURA_TRACK_CREATURES) ||
IsSpellHaveAura(spellInfo, SPELL_AURA_TRACK_RESOURCES) ||
IsSpellHaveAura(spellInfo, SPELL_AURA_TRACK_STEALTHED)) &&
((spellInfo->AttributesEx & SPELL_ATTR_EX_UNK17) || (spellInfo->AttributesEx6 & SPELL_ATTR_EX6_UNK12)))
return SPELL_TRACKER;
// elixirs can have different families, but potion most ofc.
if (SpellSpecific sp = sSpellMgr.GetSpellElixirSpecific(spellInfo->Id))
return sp;
return SPELL_NORMAL;
}
// target not allow have more one spell specific from same caster
bool IsSingleFromSpellSpecificPerTargetPerCaster(SpellSpecific spellSpec1,SpellSpecific spellSpec2)
{
switch(spellSpec1)
{
case SPELL_BLESSING:
case SPELL_AURA:
case SPELL_STING:
case SPELL_CURSE:
case SPELL_ASPECT:
case SPELL_POSITIVE_SHOUT:
case SPELL_JUDGEMENT:
case SPELL_HAND:
case SPELL_UA_IMMOLATE:
return spellSpec1==spellSpec2;
default:
return false;
}
}
// target not allow have more one ranks from spell from spell specific per target
bool IsSingleFromSpellSpecificSpellRanksPerTarget(SpellSpecific spellSpec1,SpellSpecific spellSpec2)
{
switch(spellSpec1)
{
case SPELL_BLESSING:
case SPELL_AURA:
case SPELL_CURSE:
case SPELL_ASPECT:
case SPELL_HAND:
return spellSpec1==spellSpec2;
default:
return false;
}
}
// target not allow have more one spell specific per target from any caster
bool IsSingleFromSpellSpecificPerTarget(SpellSpecific spellSpec1,SpellSpecific spellSpec2)
{
switch(spellSpec1)
{
case SPELL_SEAL:
case SPELL_TRACKER:
case SPELL_WARLOCK_ARMOR:
case SPELL_MAGE_ARMOR:
case SPELL_ELEMENTAL_SHIELD:
case SPELL_MAGE_POLYMORPH:
case SPELL_PRESENCE:
case SPELL_WELL_FED:
return spellSpec1==spellSpec2;
case SPELL_BATTLE_ELIXIR:
return spellSpec2==SPELL_BATTLE_ELIXIR
|| spellSpec2==SPELL_FLASK_ELIXIR;
case SPELL_GUARDIAN_ELIXIR:
return spellSpec2==SPELL_GUARDIAN_ELIXIR
|| spellSpec2==SPELL_FLASK_ELIXIR;
case SPELL_FLASK_ELIXIR:
return spellSpec2==SPELL_BATTLE_ELIXIR
|| spellSpec2==SPELL_GUARDIAN_ELIXIR
|| spellSpec2==SPELL_FLASK_ELIXIR;
case SPELL_FOOD:
return spellSpec2==SPELL_FOOD
|| spellSpec2==SPELL_FOOD_AND_DRINK;
case SPELL_DRINK:
return spellSpec2==SPELL_DRINK
|| spellSpec2==SPELL_FOOD_AND_DRINK;
case SPELL_FOOD_AND_DRINK:
return spellSpec2==SPELL_FOOD
|| spellSpec2==SPELL_DRINK
|| spellSpec2==SPELL_FOOD_AND_DRINK;
default:
return false;
}
}
bool IsPositiveTarget(uint32 targetA, uint32 targetB)
{
switch(targetA)
{
// non-positive targets
case TARGET_CHAIN_DAMAGE:
case TARGET_ALL_ENEMY_IN_AREA:
case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
case TARGET_IN_FRONT_OF_CASTER:
case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
case TARGET_CURRENT_ENEMY_COORDINATES:
case TARGET_SINGLE_ENEMY:
case TARGET_IN_FRONT_OF_CASTER_30:
return false;
// positive or dependent
case TARGET_CASTER_COORDINATES:
return (targetB == TARGET_ALL_PARTY || targetB == TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER);
default:
break;
}
if (targetB)
return IsPositiveTarget(targetB, 0);
return true;
}
bool IsExplicitPositiveTarget(uint32 targetA)
{
// positive targets that in target selection code expect target in m_targers, so not that auto-select target by spell data by m_caster and etc
switch(targetA)
{
case TARGET_SINGLE_FRIEND:
case TARGET_SINGLE_PARTY:
case TARGET_CHAIN_HEAL:
case TARGET_SINGLE_FRIEND_2:
case TARGET_AREAEFFECT_PARTY_AND_CLASS:
return true;
default:
break;
}
return false;
}
bool IsExplicitNegativeTarget(uint32 targetA)
{
// non-positive targets that in target selection code expect target in m_targers, so not that auto-select target by spell data by m_caster and etc
switch(targetA)
{
case TARGET_CHAIN_DAMAGE:
case TARGET_CURRENT_ENEMY_COORDINATES:
case TARGET_SINGLE_ENEMY:
return true;
default:
break;
}
return false;
}
bool IsPositiveEffect(SpellEntry const *spellproto, SpellEffectIndex effIndex)
{
// FG: temp fix, that they are not cancelable
switch(spellproto->Id)
{
case 37675: // Chaos Blast
case 36810: // rotting puterescence
case 36809: // overpowering sickness
case 48323: // indisposed
return false;
}
switch(spellproto->Effect[effIndex])
{
case SPELL_EFFECT_DUMMY:
// some explicitly required dummy effect sets
switch(spellproto->Id)
{
case 28441: // AB Effect 000
return false;
case 49634: // Sergeant's Flare
case 54530: // Opening
case 62105: // To'kini's Blowgun
return true;
default:
break;
}
break;
// always positive effects (check before target checks that provided non-positive result in some case for positive effects)
case SPELL_EFFECT_HEAL:
case SPELL_EFFECT_LEARN_SPELL:
case SPELL_EFFECT_SKILL_STEP:
case SPELL_EFFECT_HEAL_PCT:
case SPELL_EFFECT_ENERGIZE_PCT:
return true;
// non-positive aura use
case SPELL_EFFECT_APPLY_AURA:
case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
{
switch(spellproto->EffectApplyAuraName[effIndex])
{
case SPELL_AURA_DUMMY:
{
// dummy aura can be positive or negative dependent from casted spell
switch(spellproto->Id)
{
case 13139: // net-o-matic special effect
case 23445: // evil twin
case 35679: // Protectorate Demolitionist
case 38637: // Nether Exhaustion (red)
case 38638: // Nether Exhaustion (green)
case 38639: // Nether Exhaustion (blue)
case 11196: // Recently Bandaged
case 44689: // Relay Race Accept Hidden Debuff - DND
case 58600: // Restricted Flight Area
return false;
// some spells have unclear target modes for selection, so just make effect positive
case 27184:
case 27190:
case 27191:
case 27201:
case 27202:
case 27203:
return true;
default:
break;
}
} break;
case SPELL_AURA_MOD_DAMAGE_DONE: // dependent from base point sign (negative -> negative)
case SPELL_AURA_MOD_RESISTANCE:
case SPELL_AURA_MOD_STAT:
case SPELL_AURA_MOD_SKILL:
case SPELL_AURA_MOD_DODGE_PERCENT:
case SPELL_AURA_MOD_HEALING_PCT:
case SPELL_AURA_MOD_HEALING_DONE:
if(spellproto->CalculateSimpleValue(effIndex) < 0)
return false;
break;
case SPELL_AURA_MOD_DAMAGE_TAKEN: // dependent from bas point sign (positive -> negative)
if (spellproto->CalculateSimpleValue(effIndex) < 0)
return true;
// let check by target modes (for Amplify Magic cases/etc)
break;
case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
case SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT:
case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE:
if(spellproto->CalculateSimpleValue(effIndex) > 0)
return true; // some expected positive spells have SPELL_ATTR_EX_NEGATIVE or unclear target modes
break;
case SPELL_AURA_ADD_TARGET_TRIGGER:
return true;
case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
if (spellproto->Id != spellproto->EffectTriggerSpell[effIndex])
{
uint32 spellTriggeredId = spellproto->EffectTriggerSpell[effIndex];
SpellEntry const *spellTriggeredProto = sSpellStore.LookupEntry(spellTriggeredId);
if (spellTriggeredProto)
{
// non-positive targets of main spell return early
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
// if non-positive trigger cast targeted to positive target this main cast is non-positive
// this will place this spell auras as debuffs
if (spellTriggeredProto->Effect[i] &&
IsPositiveTarget(spellTriggeredProto->EffectImplicitTargetA[i], spellTriggeredProto->EffectImplicitTargetB[i]) &&
!IsPositiveEffect(spellTriggeredProto, SpellEffectIndex(i)))
return false;
}
}
}
break;
case SPELL_AURA_PROC_TRIGGER_SPELL:
// many positive auras have negative triggered spells at damage for example and this not make it negative (it can be canceled for example)
break;
case SPELL_AURA_MOD_STUN: //have positive and negative spells, we can't sort its correctly at this moment.
if (effIndex == EFFECT_INDEX_0 && spellproto->Effect[EFFECT_INDEX_1] == 0 && spellproto->Effect[EFFECT_INDEX_2] == 0)
return false; // but all single stun aura spells is negative
// Petrification
if(spellproto->Id == 17624)
return false;
break;
case SPELL_AURA_MOD_PACIFY_SILENCE:
switch(spellproto->Id)
{
case 24740: // Wisp Costume
case 47585: // Dispersion
return true;
default: break;
}
return false;
case SPELL_AURA_MOD_ROOT:
case SPELL_AURA_MOD_SILENCE:
case SPELL_AURA_GHOST:
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_MOD_STALKED:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
return false;
case SPELL_AURA_PERIODIC_DAMAGE: // used in positive spells also.
// part of negative spell if casted at self (prevent cancel)
if (spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF ||
spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF2)
return false;
break;
case SPELL_AURA_MOD_DECREASE_SPEED: // used in positive spells also
// part of positive spell if casted at self
if ((spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF ||
spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF2) &&
spellproto->SpellFamilyName == SPELLFAMILY_GENERIC)
return false;
// but not this if this first effect (don't found better check)
if (spellproto->Attributes & 0x4000000 && effIndex == EFFECT_INDEX_0)
return false;
break;
case SPELL_AURA_TRANSFORM:
// some spells negative
switch(spellproto->Id)
{
case 36897: // Transporter Malfunction (race mutation to horde)
case 36899: // Transporter Malfunction (race mutation to alliance)
return false;
}
break;
case SPELL_AURA_MOD_SCALE:
// some spells negative
switch(spellproto->Id)
{
case 802: // Mutate Bug, wrongly negative by target modes
return true;
case 36900: // Soul Split: Evil!
case 36901: // Soul Split: Good
case 36893: // Transporter Malfunction (decrease size case)
case 36895: // Transporter Malfunction (increase size case)
return false;
}
break;
case SPELL_AURA_MECHANIC_IMMUNITY:
{
// non-positive immunities
switch(spellproto->EffectMiscValue[effIndex])
{
case MECHANIC_BANDAGE:
case MECHANIC_SHIELD:
case MECHANIC_MOUNT:
case MECHANIC_INVULNERABILITY:
return false;
default:
break;
}
} break;
case SPELL_AURA_ADD_FLAT_MODIFIER: // mods
case SPELL_AURA_ADD_PCT_MODIFIER:
{
// non-positive mods
switch(spellproto->EffectMiscValue[effIndex])
{
case SPELLMOD_COST: // dependent from bas point sign (negative -> positive)
if(spellproto->CalculateSimpleValue(effIndex) > 0)
return false;
break;
default:
break;
}
} break;
case SPELL_AURA_FORCE_REACTION:
{
switch (spellproto->Id)
{
case 42792: // Recently Dropped Flag (prevent cancel)
case 46221: // Animal Blood
return false;
default:
break;
}
break;
}
default:
break;
}
break;
}
default:
break;
}
// non-positive targets
if(!IsPositiveTarget(spellproto->EffectImplicitTargetA[effIndex],spellproto->EffectImplicitTargetB[effIndex]))
return false;
// AttributesEx check
if(spellproto->AttributesEx & SPELL_ATTR_EX_NEGATIVE)
return false;
// ok, positive
return true;
}
bool IsPositiveSpell(uint32 spellId)
{
SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
if (!spellproto)
return false;
return IsPositiveSpell(spellproto);
}
bool IsPositiveSpell(SpellEntry const *spellproto)
{
// spells with at least one negative effect are considered negative
// some self-applied spells have negative effects but in self casting case negative check ignored.
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
if (spellproto->Effect[i] && !IsPositiveEffect(spellproto, SpellEffectIndex(i)))
return false;
return true;
}
bool IsSingleTargetSpell(SpellEntry const *spellInfo)
{
// all other single target spells have if it has AttributesEx5
if ( spellInfo->AttributesEx5 & SPELL_ATTR_EX5_SINGLE_TARGET_SPELL )
return true;
// TODO - need found Judgements rule
switch(GetSpellSpecific(spellInfo->Id))
{
case SPELL_JUDGEMENT:
return true;
default:
break;
}
// single target triggered spell.
// Not real client side single target spell, but it' not triggered until prev. aura expired.
// This is allow store it in single target spells list for caster for spell proc checking
if(spellInfo->Id==38324) // Regeneration (triggered by 38299 (HoTs on Heals))
return true;
return false;
}
bool IsSingleTargetSpells(SpellEntry const *spellInfo1, SpellEntry const *spellInfo2)
{
// TODO - need better check
// Equal icon and spellfamily
if( spellInfo1->SpellFamilyName == spellInfo2->SpellFamilyName &&
spellInfo1->SpellIconID == spellInfo2->SpellIconID )
return true;
// TODO - need found Judgements rule
SpellSpecific spec1 = GetSpellSpecific(spellInfo1->Id);
// spell with single target specific types
switch(spec1)
{
case SPELL_JUDGEMENT:
case SPELL_MAGE_POLYMORPH:
if(GetSpellSpecific(spellInfo2->Id) == spec1)
return true;
break;
default:
break;
}
return false;
}
SpellCastResult GetErrorAtShapeshiftedCast (SpellEntry const *spellInfo, uint32 form)
{
// talents that learn spells can have stance requirements that need ignore
// (this requirement only for client-side stance show in talent description)
if( GetTalentSpellCost(spellInfo->Id) > 0 &&
(spellInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[EFFECT_INDEX_1] == SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[EFFECT_INDEX_2] == SPELL_EFFECT_LEARN_SPELL) )
return SPELL_CAST_OK;
uint32 stanceMask = (form ? 1 << (form - 1) : 0);
if (stanceMask & spellInfo->StancesNot) // can explicitly not be casted in this stance
return SPELL_FAILED_NOT_SHAPESHIFT;
if (stanceMask & spellInfo->Stances) // can explicitly be casted in this stance
return SPELL_CAST_OK;
bool actAsShifted = false;
if (form > 0)
{
SpellShapeshiftFormEntry const *shapeInfo = sSpellShapeshiftFormStore.LookupEntry(form);
if (!shapeInfo)
{
sLog.outError("GetErrorAtShapeshiftedCast: unknown shapeshift %u", form);
return SPELL_CAST_OK;
}
actAsShifted = !(shapeInfo->flags1 & 1); // shapeshift acts as normal form for spells
}
if(actAsShifted)
{
if (spellInfo->Attributes & SPELL_ATTR_NOT_SHAPESHIFT) // not while shapeshifted
{
//but we must allow cast of Berserk+modifier from any form... where for the hell should we do it?
if (!(spellInfo->SpellIconID == 1680 && (spellInfo->AttributesEx & 0x8000)))
return SPELL_FAILED_NOT_SHAPESHIFT;
}
else if (spellInfo->Stances != 0) // needs other shapeshift
return SPELL_FAILED_ONLY_SHAPESHIFT;
}
else
{
// needs shapeshift
if(!(spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT) && spellInfo->Stances != 0)
return SPELL_FAILED_ONLY_SHAPESHIFT;
}
return SPELL_CAST_OK;
}
void SpellMgr::LoadSpellTargetPositions()
{
mSpellTargetPositions.clear(); // need for reload case
uint32 count = 0;
// 0 1 2 3 4 5
QueryResult *result = WorldDatabase.Query("SELECT id, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM spell_target_position");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> Loaded %u spell target destination coordinates", count);
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 Spell_ID = fields[0].GetUInt32();
SpellTargetPosition st;
st.target_mapId = fields[1].GetUInt32();
st.target_X = fields[2].GetFloat();
st.target_Y = fields[3].GetFloat();
st.target_Z = fields[4].GetFloat();
st.target_Orientation = fields[5].GetFloat();
MapEntry const* mapEntry = sMapStore.LookupEntry(st.target_mapId);
if (!mapEntry)
{
sLog.outErrorDb("Spell (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Spell_ID,st.target_mapId);
continue;
}
if (st.target_X==0 && st.target_Y==0 && st.target_Z==0)
{
sLog.outErrorDb("Spell (ID:%u) target coordinates not provided.",Spell_ID);
continue;
}
SpellEntry const* spellInfo = sSpellStore.LookupEntry(Spell_ID);
if (!spellInfo)
{
sLog.outErrorDb("Spell (ID:%u) listed in `spell_target_position` does not exist.",Spell_ID);
continue;
}
bool found = false;
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (spellInfo->EffectImplicitTargetA[i]==TARGET_TABLE_X_Y_Z_COORDINATES || spellInfo->EffectImplicitTargetB[i]==TARGET_TABLE_X_Y_Z_COORDINATES)
{
// additional requirements
if (spellInfo->Effect[i]==SPELL_EFFECT_BIND && spellInfo->EffectMiscValue[i])
{
uint32 zone_id = sTerrainMgr.GetAreaId(st.target_mapId, st.target_X, st.target_Y, st.target_Z);
if (int32(zone_id) != spellInfo->EffectMiscValue[i])
{
sLog.outErrorDb("Spell (Id: %u) listed in `spell_target_position` expected point to zone %u bit point to zone %u.",Spell_ID, spellInfo->EffectMiscValue[i], zone_id);
break;
}
}
found = true;
break;
}
}
if (!found)
{
sLog.outErrorDb("Spell (Id: %u) listed in `spell_target_position` does not have target TARGET_TABLE_X_Y_Z_COORDINATES (17).",Spell_ID);
continue;
}
mSpellTargetPositions[Spell_ID] = st;
++count;
} while( result->NextRow() );
delete result;
sLog.outString();
sLog.outString(">> Loaded %u spell target destination coordinates", count);
}
template <typename EntryType, typename WorkerType, typename StorageType>
struct SpellRankHelper
{
SpellRankHelper(SpellMgr &_mgr, StorageType &_storage): mgr(_mgr), worker(_storage), customRank(0) {}
void RecordRank(EntryType &entry, uint32 spell_id)
{
const SpellEntry *spell = sSpellStore.LookupEntry(spell_id);
if (!spell)
{
sLog.outErrorDb("Spell %u listed in `%s` does not exist", spell_id, worker.TableName());
return;
}
uint32 first_id = mgr.GetFirstSpellInChain(spell_id);
// most spell ranks expected same data
if(first_id)
{
firstRankSpells.insert(first_id);
if (first_id != spell_id)
{
if (!worker.IsValidCustomRank(entry, spell_id, first_id))
return;
// for later check that first rank also added
else
{
firstRankSpellsWithCustomRanks.insert(first_id);
++customRank;
}
}
}
worker.AddEntry(entry, spell);
}
void FillHigherRanks()
{
// check that first rank added for custom ranks
for (std::set<uint32>::const_iterator itr = firstRankSpellsWithCustomRanks.begin(); itr != firstRankSpellsWithCustomRanks.end(); ++itr)
if (!worker.HasEntry(*itr))
sLog.outErrorDb("Spell %u must be listed in `%s` as first rank for listed custom ranks of spell but not found!", *itr, worker.TableName());
// fill absent non first ranks data base at first rank data
for (std::set<uint32>::const_iterator itr = firstRankSpells.begin(); itr != firstRankSpells.end(); ++itr)
{
if (worker.SetStateToEntry(*itr))
mgr.doForHighRanks(*itr, worker);
}
}
std::set<uint32> firstRankSpells;
std::set<uint32> firstRankSpellsWithCustomRanks;
SpellMgr &mgr;
WorkerType worker;
uint32 customRank;
};
struct DoSpellProcEvent
{
DoSpellProcEvent(SpellProcEventMap& _spe_map) : spe_map(_spe_map), customProc(0), count(0) {}
void operator() (uint32 spell_id)
{
SpellProcEventEntry const& spe = state->second;
// add ranks only for not filled data (some ranks have ppm data different for ranks for example)
SpellProcEventMap::const_iterator spellItr = spe_map.find(spell_id);
if (spellItr == spe_map.end())
spe_map[spell_id] = spe;
// if custom rank data added then it must be same except ppm
else
{
SpellProcEventEntry const& r_spe = spellItr->second;
if (spe.schoolMask != r_spe.schoolMask)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different schoolMask from first rank in chain", spell_id);
if (spe.spellFamilyName != r_spe.spellFamilyName)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different spellFamilyName from first rank in chain", spell_id);
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (spe.spellFamilyMask[i] != r_spe.spellFamilyMask[i])
{
sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different spellFamilyMask/spellFamilyMask2 from first rank in chain", spell_id);
break;
}
}
if (spe.procFlags != r_spe.procFlags)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different procFlags from first rank in chain", spell_id);
if (spe.procEx != r_spe.procEx)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different procEx from first rank in chain", spell_id);
// only ppm allowed has been different from first rank
if (spe.customChance != r_spe.customChance)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different customChance from first rank in chain", spell_id);
if (spe.cooldown != r_spe.cooldown)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different cooldown from first rank in chain", spell_id);
}
}
const char* TableName() { return "spell_proc_event"; }
bool IsValidCustomRank(SpellProcEventEntry const &spe, uint32 entry, uint32 first_id)
{
// let have independent data in table for spells with ppm rates (exist rank dependent ppm rate spells)
if (!spe.ppmRate)
{
sLog.outErrorDb("Spell %u listed in `spell_proc_event` is not first rank (%u) in chain", entry, first_id);
// prevent loading since it won't have an effect anyway
return false;
}
return true;
}
void AddEntry(SpellProcEventEntry const &spe, SpellEntry const *spell)
{
spe_map[spell->Id] = spe;
bool isCustom = false;
if (spe.procFlags == 0)
{
if (spell->procFlags==0)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` probally not triggered spell (no proc flags)", spell->Id);
}
else
{
if (spell->procFlags==spe.procFlags)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` has exactly same proc flags as in spell.dbc, field value redundant", spell->Id);
else
isCustom = true;
}
if (spe.customChance == 0)
{
/* enable for re-check cases, 0 chance ok for some cases because in some cases it set by another spell/talent spellmod)
if (spell->procChance==0 && !spe.ppmRate)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` probally not triggered spell (no chance or ppm)", spell->Id);
*/
}
else
{
if (spell->procChance==spe.customChance)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` has exactly same custom chance as in spell.dbc, field value redundant", spell->Id);
else
isCustom = true;
}
// totally redundant record
if (!spe.schoolMask && !spe.procFlags &&
!spe.procEx && !spe.ppmRate && !spe.customChance && !spe.cooldown)
{
bool empty = !spe.spellFamilyName ? true : false;
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (spe.spellFamilyMask[i])
{
empty = false;
ClassFamilyMask const& mask = spell->GetEffectSpellClassMask(SpellEffectIndex(i));
if (mask == spe.spellFamilyMask[i])
sLog.outErrorDb("Spell %u listed in `spell_proc_event` has same class mask as in Spell.dbc (EffectIndex %u) and doesn't have any other data", spell->Id, i);
}
}
if (empty)
sLog.outErrorDb("Spell %u listed in `spell_proc_event` doesn't have any useful data", spell->Id);
}
if (isCustom)
++customProc;
else
++count;
}
bool HasEntry(uint32 spellId) { return spe_map.count(spellId) > 0; }
bool SetStateToEntry(uint32 spellId) { return (state = spe_map.find(spellId)) != spe_map.end(); }
SpellProcEventMap& spe_map;
SpellProcEventMap::const_iterator state;
uint32 customProc;
uint32 count;
};
void SpellMgr::LoadSpellProcEvents()
{
mSpellProcEventMap.clear(); // need for reload case
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
QueryResult *result = WorldDatabase.Query("SELECT entry, SchoolMask, SpellFamilyName, SpellFamilyMaskA0, SpellFamilyMaskA1, SpellFamilyMaskA2, SpellFamilyMaskB0, SpellFamilyMaskB1, SpellFamilyMaskB2, SpellFamilyMaskC0, SpellFamilyMaskC1, SpellFamilyMaskC2, procFlags, procEx, ppmRate, CustomChance, Cooldown FROM spell_proc_event");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> No spell proc event conditions loaded");
return;
}
SpellRankHelper<SpellProcEventEntry, DoSpellProcEvent, SpellProcEventMap> rankHelper(*this, mSpellProcEventMap);
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 entry = fields[0].GetUInt32();
SpellProcEventEntry spe;
spe.schoolMask = fields[1].GetUInt32();
spe.spellFamilyName = fields[2].GetUInt32();
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
spe.spellFamilyMask[i] = ClassFamilyMask(
(uint64)fields[i+3].GetUInt32() | ((uint64)fields[i+6].GetUInt32()<<32),
fields[i+9].GetUInt32());
}
spe.procFlags = fields[12].GetUInt32();
spe.procEx = fields[13].GetUInt32();
spe.ppmRate = fields[14].GetFloat();
spe.customChance = fields[15].GetFloat();
spe.cooldown = fields[16].GetUInt32();
rankHelper.RecordRank(spe, entry);
} while (result->NextRow());
rankHelper.FillHigherRanks();
delete result;
sLog.outString();
sLog.outString( ">> Loaded %u extra spell proc event conditions +%u custom proc (inc. +%u custom ranks)", rankHelper.worker.count, rankHelper.worker.customProc, rankHelper.customRank);
}
struct DoSpellProcItemEnchant
{
DoSpellProcItemEnchant(SpellProcItemEnchantMap& _procMap, float _ppm) : procMap(_procMap), ppm(_ppm) {}
void operator() (uint32 spell_id) { procMap[spell_id] = ppm; }
SpellProcItemEnchantMap& procMap;
float ppm;
};
void SpellMgr::LoadSpellProcItemEnchant()
{
mSpellProcItemEnchantMap.clear(); // need for reload case
uint32 count = 0;
// 0 1
QueryResult *result = WorldDatabase.Query("SELECT entry, ppmRate FROM spell_proc_item_enchant");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> Loaded %u proc item enchant definitions", count);
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 entry = fields[0].GetUInt32();
float ppmRate = fields[1].GetFloat();
SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry);
if (!spellInfo)
{
sLog.outErrorDb("Spell %u listed in `spell_proc_item_enchant` does not exist", entry);
continue;
}
uint32 first_id = GetFirstSpellInChain(entry);
if ( first_id != entry )
{
sLog.outErrorDb("Spell %u listed in `spell_proc_item_enchant` is not first rank (%u) in chain", entry, first_id);
// prevent loading since it won't have an effect anyway
continue;
}
mSpellProcItemEnchantMap[entry] = ppmRate;
// also add to high ranks
DoSpellProcItemEnchant worker(mSpellProcItemEnchantMap, ppmRate);
doForHighRanks(entry,worker);
++count;
} while( result->NextRow() );
delete result;
sLog.outString();
sLog.outString( ">> Loaded %u proc item enchant definitions", count );
}
struct DoSpellBonuses
{
DoSpellBonuses(SpellBonusMap& _spellBonusMap, SpellBonusEntry const& _spellBonus) : spellBonusMap(_spellBonusMap), spellBonus(_spellBonus) {}
void operator() (uint32 spell_id) { spellBonusMap[spell_id] = spellBonus; }
SpellBonusMap& spellBonusMap;
SpellBonusEntry const& spellBonus;
};
void SpellMgr::LoadSpellBonuses()
{
mSpellBonusMap.clear(); // need for reload case
uint32 count = 0;
// 0 1 2 3
QueryResult *result = WorldDatabase.Query("SELECT entry, direct_bonus, dot_bonus, ap_bonus, ap_dot_bonus FROM spell_bonus_data");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> Loaded %u spell bonus data", count);
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 entry = fields[0].GetUInt32();
SpellEntry const* spell = sSpellStore.LookupEntry(entry);
if (!spell)
{
sLog.outErrorDb("Spell %u listed in `spell_bonus_data` does not exist", entry);
continue;
}
uint32 first_id = GetFirstSpellInChain(entry);
if ( first_id != entry )
{
sLog.outErrorDb("Spell %u listed in `spell_bonus_data` is not first rank (%u) in chain", entry, first_id);
// prevent loading since it won't have an effect anyway
continue;
}
SpellBonusEntry sbe;
sbe.direct_damage = fields[1].GetFloat();
sbe.dot_damage = fields[2].GetFloat();
sbe.ap_bonus = fields[3].GetFloat();
sbe.ap_dot_bonus = fields[4].GetFloat();
bool need_dot = false;
bool need_direct = false;
uint32 x = 0; // count all, including empty, meaning: not all existing effect is DoTs/HoTs
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (!spell->Effect[i])
{
++x;
continue;
}
// DoTs/HoTs
switch(spell->EffectApplyAuraName[i])
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_OBS_MOD_HEALTH:
case SPELL_AURA_PERIODIC_MANA_LEECH:
case SPELL_AURA_OBS_MOD_MANA:
case SPELL_AURA_POWER_BURN_MANA:
need_dot = true;
++x;
break;
default:
break;
}
}
//TODO: maybe add explicit list possible direct damage spell effects...
if (x < MAX_EFFECT_INDEX)
need_direct = true;
// Check if direct_bonus is needed in `spell_bonus_data`
float direct_calc;
float direct_diff = 1000.0f; // for have big diff if no DB field value
if (sbe.direct_damage)
{
bool isHeal = false;
for(int i = 0; i < 3; ++i)
{
// Heals (Also count Mana Shield and Absorb effects as heals)
if (spell->Effect[i] == SPELL_EFFECT_HEAL || spell->Effect[i] == SPELL_EFFECT_HEAL_MAX_HEALTH ||
(spell->Effect[i] == SPELL_EFFECT_APPLY_AURA && (spell->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_ABSORB || spell->EffectApplyAuraName[i] == SPELL_AURA_PERIODIC_HEAL)) )
{
isHeal = true;
break;
}
}
direct_calc = CalculateDefaultCoefficient(spell, SPELL_DIRECT_DAMAGE) * (isHeal ? 1.88f : 1.0f);
direct_diff = std::abs(sbe.direct_damage - direct_calc);
}
// Check if dot_bonus is needed in `spell_bonus_data`
float dot_calc;
float dot_diff = 1000.0f; // for have big diff if no DB field value
if (sbe.dot_damage)
{
bool isHeal = false;
for(int i = 0; i < 3; ++i)
{
// Periodic Heals
if (spell->Effect[i] == SPELL_EFFECT_APPLY_AURA && spell->EffectApplyAuraName[i] == SPELL_AURA_PERIODIC_HEAL)
{
isHeal = true;
break;
}
}
dot_calc = CalculateDefaultCoefficient(spell, DOT) * (isHeal ? 1.88f : 1.0f);
dot_diff = std::abs(sbe.dot_damage - dot_calc);
}
if (direct_diff < 0.02f && !need_dot && !sbe.ap_bonus && !sbe.ap_dot_bonus)
sLog.outErrorDb("`spell_bonus_data` entry for spell %u `direct_bonus` not needed (data from table: %f, calculated %f, difference of %f) and `dot_bonus` also not used",
entry, sbe.direct_damage, direct_calc, direct_diff);
else if (direct_diff < 0.02f && dot_diff < 0.02f && !sbe.ap_bonus && !sbe.ap_dot_bonus)
{
sLog.outErrorDb("`spell_bonus_data` entry for spell %u `direct_bonus` not needed (data from table: %f, calculated %f, difference of %f) and ",
entry, sbe.direct_damage, direct_calc, direct_diff);
sLog.outErrorDb(" ... `dot_bonus` not needed (data from table: %f, calculated %f, difference of %f)",
sbe.dot_damage, dot_calc, dot_diff);
}
else if (!need_direct && dot_diff < 0.02f && !sbe.ap_bonus && !sbe.ap_dot_bonus)
sLog.outErrorDb("`spell_bonus_data` entry for spell %u `dot_bonus` not needed (data from table: %f, calculated %f, difference of %f) and direct also not used",
entry, sbe.dot_damage, dot_calc, dot_diff);
else if (!need_direct && sbe.direct_damage)
sLog.outErrorDb("`spell_bonus_data` entry for spell %u `direct_bonus` not used (spell not have non-periodic affects)", entry);
else if (!need_dot && sbe.dot_damage)
sLog.outErrorDb("`spell_bonus_data` entry for spell %u `dot_bonus` not used (spell not have periodic affects)", entry);
if (!need_direct && sbe.ap_bonus)
sLog.outErrorDb("`spell_bonus_data` entry for spell %u `ap_bonus` not used (spell not have non-periodic affects)", entry);
else if (!need_dot && sbe.ap_dot_bonus)
sLog.outErrorDb("`spell_bonus_data` entry for spell %u `ap_dot_bonus` not used (spell not have periodic affects)", entry);
mSpellBonusMap[entry] = sbe;
// also add to high ranks
DoSpellBonuses worker(mSpellBonusMap, sbe);
doForHighRanks(entry,worker);
++count;
} while( result->NextRow() );
delete result;
sLog.outString();
sLog.outString( ">> Loaded %u extra spell bonus data", count);
}
bool SpellMgr::IsSpellProcEventCanTriggeredBy(SpellProcEventEntry const * spellProcEvent, uint32 EventProcFlag, SpellEntry const * procSpell, uint32 procFlags, uint32 procExtra)
{
// No extra req need
uint32 procEvent_procEx = PROC_EX_NONE;
// check prockFlags for condition
if((procFlags & EventProcFlag) == 0)
return false;
// Always trigger for this
if (EventProcFlag & (PROC_FLAG_KILLED | PROC_FLAG_KILL | PROC_FLAG_ON_TRAP_ACTIVATION | PROC_FLAG_ON_DEATH))
return true;
if (spellProcEvent) // Exist event data
{
// Store extra req
procEvent_procEx = spellProcEvent->procEx;
// For melee triggers
if (procSpell == NULL)
{
// Check (if set) for school (melee attack have Normal school)
if(spellProcEvent->schoolMask && (spellProcEvent->schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0)
return false;
}
else // For spells need check school/spell family/family mask
{
// Check (if set) for school
if(spellProcEvent->schoolMask && (spellProcEvent->schoolMask & procSpell->SchoolMask) == 0)
return false;
// Check (if set) for spellFamilyName
if(spellProcEvent->spellFamilyName && (spellProcEvent->spellFamilyName != procSpell->SpellFamilyName))
return false;
}
}
// Check for extra req (if none) and hit/crit
if (procEvent_procEx == PROC_EX_NONE)
{
// Don't allow proc from periodic heal if no extra requirement is defined
if (EventProcFlag & (PROC_FLAG_ON_DO_PERIODIC | PROC_FLAG_ON_TAKE_PERIODIC) && (procExtra & PROC_EX_PERIODIC_POSITIVE))
return false;
// No extra req, so can trigger for (damage/healing present) and hit/crit
if(procExtra & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT))
return true;
}
else // all spells hits here only if resist/reflect/immune/evade
{
// Exist req for PROC_EX_EX_TRIGGER_ALWAYS
if (procEvent_procEx & PROC_EX_EX_TRIGGER_ALWAYS)
return true;
// Check Extra Requirement like (hit/crit/miss/resist/parry/dodge/block/immune/reflect/absorb and other)
if (procEvent_procEx & procExtra)
return true;
}
return false;
}
void SpellMgr::LoadSpellElixirs()
{
mSpellElixirs.clear(); // need for reload case
uint32 count = 0;
// 0 1
QueryResult *result = WorldDatabase.Query("SELECT entry, mask FROM spell_elixir");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> Loaded %u spell elixir definitions", count);
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 entry = fields[0].GetUInt32();
uint8 mask = fields[1].GetUInt8();
SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry);
if (!spellInfo)
{
sLog.outErrorDb("Spell %u listed in `spell_elixir` does not exist", entry);
continue;
}
mSpellElixirs[entry] = mask;
++count;
} while( result->NextRow() );
delete result;
sLog.outString();
sLog.outString( ">> Loaded %u spell elixir definitions", count );
}
struct DoSpellThreat
{
DoSpellThreat(SpellThreatMap& _threatMap) : threatMap(_threatMap), count(0) {}
void operator() (uint32 spell_id)
{
SpellThreatEntry const &ste = state->second;
// add ranks only for not filled data (spells adding flat threat are usually different for ranks)
SpellThreatMap::const_iterator spellItr = threatMap.find(spell_id);
if (spellItr == threatMap.end())
threatMap[spell_id] = ste;
// just assert that entry is not redundant
else
{
SpellThreatEntry const& r_ste = spellItr->second;
if (ste.threat == r_ste.threat && ste.multiplier == r_ste.multiplier && ste.ap_bonus == r_ste.ap_bonus)
sLog.outErrorDb("Spell %u listed in `spell_threat` as custom rank has same data as Rank 1, so redundant", spell_id);
}
}
const char* TableName() { return "spell_threat"; }
bool IsValidCustomRank(SpellThreatEntry const &ste, uint32 entry, uint32 first_id)
{
if (!ste.threat)
{
sLog.outErrorDb("Spell %u listed in `spell_threat` is not first rank (%u) in chain and has no threat", entry, first_id);
// prevent loading unexpected data
return false;
}
return true;
}
void AddEntry(SpellThreatEntry const &ste, SpellEntry const *spell)
{
threatMap[spell->Id] = ste;
// flat threat bonus and attack power bonus currently only work properly when all
// effects have same targets, otherwise, we'd need to seperate it by effect index
if (ste.threat || ste.ap_bonus != 0.f)
{
const uint32 *targetA = spell->EffectImplicitTargetA;
const uint32 *targetB = spell->EffectImplicitTargetB;
if ((targetA[EFFECT_INDEX_1] && targetA[EFFECT_INDEX_1] != targetA[EFFECT_INDEX_0]) ||
(targetA[EFFECT_INDEX_2] && targetA[EFFECT_INDEX_2] != targetA[EFFECT_INDEX_0]))
sLog.outErrorDb("Spell %u listed in `spell_threat` has effects with different targets, threat may be assigned incorrectly", spell->Id);
}
++count;
}
bool HasEntry(uint32 spellId) { return threatMap.count(spellId) > 0; }
bool SetStateToEntry(uint32 spellId) { return (state = threatMap.find(spellId)) != threatMap.end(); }
SpellThreatMap& threatMap;
SpellThreatMap::const_iterator state;
uint32 count;
};
void SpellMgr::LoadSpellThreats()
{
mSpellThreatMap.clear(); // need for reload case
// 0 1 2 3
QueryResult *result = WorldDatabase.Query("SELECT entry, Threat, multiplier, ap_bonus FROM spell_threat");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> No spell threat entries loaded.");
return;
}
SpellRankHelper<SpellThreatEntry, DoSpellThreat, SpellThreatMap> rankHelper(*this, mSpellThreatMap);
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 entry = fields[0].GetUInt32();
SpellThreatEntry ste;
ste.threat = fields[1].GetUInt16();
ste.multiplier = fields[2].GetFloat();
ste.ap_bonus = fields[3].GetFloat();
rankHelper.RecordRank(ste, entry);
} while( result->NextRow() );
rankHelper.FillHigherRanks();
delete result;
sLog.outString();
sLog.outString( ">> Loaded %u spell threat entries", rankHelper.worker.count );
}
bool SpellMgr::IsRankSpellDueToSpell(SpellEntry const *spellInfo_1,uint32 spellId_2) const
{
SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
if(!spellInfo_1 || !spellInfo_2) return false;
if(spellInfo_1->Id == spellId_2) return false;
return GetFirstSpellInChain(spellInfo_1->Id)==GetFirstSpellInChain(spellId_2);
}
bool SpellMgr::canStackSpellRanksInSpellBook(SpellEntry const *spellInfo) const
{
if (IsPassiveSpell(spellInfo)) // ranked passive spell
return false;
if (spellInfo->powerType != POWER_MANA && spellInfo->powerType != POWER_HEALTH)
return false;
if (IsProfessionOrRidingSpell(spellInfo->Id))
return false;
if (IsSkillBonusSpell(spellInfo->Id))
return false;
// All stance spells. if any better way, change it.
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
switch(spellInfo->SpellFamilyName)
{
case SPELLFAMILY_PALADIN:
// Paladin aura Spell
if (spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AREA_AURA_RAID)
return false;
// Seal of Righteousness, 2 version of same rank
if ((spellInfo->SpellFamilyFlags & UI64LIT(0x0000000008000000)) && spellInfo->SpellIconID == 25)
return false;
break;
case SPELLFAMILY_DRUID:
// Druid form Spell
if (spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AURA &&
spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT)
return false;
break;
case SPELLFAMILY_ROGUE:
// Rogue Stealth
if (spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AURA &&
spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT)
return false;
break;
}
}
return true;
}
bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) const
{
SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
if (!spellInfo_1 || !spellInfo_2)
return false;
if (spellId_1 == spellId_2)
return false;
// Resurrection sickness
if ((spellInfo_1->Id == SPELL_ID_PASSIVE_RESURRECTION_SICKNESS) != (spellInfo_2->Id==SPELL_ID_PASSIVE_RESURRECTION_SICKNESS))
return false;
// Allow stack passive and not passive spells
if ((spellInfo_1->Attributes & SPELL_ATTR_PASSIVE)!=(spellInfo_2->Attributes & SPELL_ATTR_PASSIVE))
return false;
// My rules! :D
if (spellInfo_1->AttributesEx6 & SPELL_ATTR_EX6_UNK26 && spellInfo_2->AttributesEx6 & SPELL_ATTR_EX6_UNK26)
{
// Marks and Gifts of the Wild
if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_2] == SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE &&
spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_2] == SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE)
return true;
// Blessings of Kings and Blessing of Forgotten Kings
if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE &&
spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE)
return true;
}
// Mangle and Trauma
if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_1] == SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT &&
spellInfo_1->EffectMiscValue[EFFECT_INDEX_1] == MECHANIC_BLEED &&
spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT &&
spellInfo_2->EffectMiscValue[EFFECT_INDEX_0] == MECHANIC_BLEED ||
spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_1] == SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT &&
spellInfo_2->EffectMiscValue[EFFECT_INDEX_1] == MECHANIC_BLEED &&
spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT &&
spellInfo_1->EffectMiscValue[EFFECT_INDEX_0] == MECHANIC_BLEED )
return true;
// Specific spell family spells
switch(spellInfo_1->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch(spellInfo_2->SpellFamilyName)
{
case SPELLFAMILY_GENERIC: // same family case
{
// Thunderfury
if ((spellInfo_1->Id == 21992 && spellInfo_2->Id == 27648) ||
(spellInfo_2->Id == 21992 && spellInfo_1->Id == 27648))
return false;
// Lightning Speed (Mongoose) and Fury of the Crashing Waves (Tsunami Talisman)
if ((spellInfo_1->Id == 28093 && spellInfo_2->Id == 42084) ||
(spellInfo_2->Id == 28093 && spellInfo_1->Id == 42084))
return false;
// Soulstone Resurrection and Twisting Nether (resurrector)
if (spellInfo_1->SpellIconID == 92 && spellInfo_2->SpellIconID == 92 && (
(spellInfo_1->SpellVisual[0] == 99 && spellInfo_2->SpellVisual[0] == 0) ||
(spellInfo_2->SpellVisual[0] == 99 && spellInfo_1->SpellVisual[0] == 0)))
return false;
// Heart of the Wild, Agility and various Idol Triggers
if (spellInfo_1->SpellIconID == 240 && spellInfo_2->SpellIconID == 240)
return false;
// Personalized Weather (thunder effect should overwrite rainy aura)
if (spellInfo_1->SpellIconID == 2606 && spellInfo_2->SpellIconID == 2606)
return false;
// Brood Affliction: Bronze
if ((spellInfo_1->Id == 23170 && spellInfo_2->Id == 23171) ||
(spellInfo_2->Id == 23170 && spellInfo_1->Id == 23171))
return false;
// Male Shadowy Disguise
if ((spellInfo_1->Id == 32756 && spellInfo_2->Id == 38080) ||
(spellInfo_2->Id == 32756 && spellInfo_1->Id == 38080))
return false;
// Female Shadowy Disguise
if ((spellInfo_1->Id == 32756 && spellInfo_2->Id == 38081) ||
(spellInfo_2->Id == 32756 && spellInfo_1->Id == 38081))
return false;
// Cool Down (See PeriodicAuraTick())
if ((spellInfo_1->Id == 52441 && spellInfo_2->Id == 52443) ||
(spellInfo_2->Id == 52441 && spellInfo_1->Id == 52443))
return false;
// See Chapel Invisibility and See Noth Invisibility
if ((spellInfo_1->Id == 52950 && spellInfo_2->Id == 52707) ||
(spellInfo_2->Id == 52950 && spellInfo_1->Id == 52707))
return false;
// Regular and Night Elf Ghost
if ((spellInfo_1->Id == 8326 && spellInfo_2->Id == 20584) ||
(spellInfo_2->Id == 8326 && spellInfo_1->Id == 20584))
return false;
// Aura of Despair auras
if ((spellInfo_1->Id == 64848 && spellInfo_2->Id == 62692) ||
(spellInfo_2->Id == 64848 && spellInfo_1->Id == 62692))
return false;
// Blood Fury and Rage of the Unraveller
if (spellInfo_1->SpellIconID == 1662 && spellInfo_2->SpellIconID == 1662)
return false;
// Kindred Spirits
if (spellInfo_1->SpellIconID == 3559 && spellInfo_2->SpellIconID == 3559)
return false;
// Vigilance and Damage Reduction (Vigilance triggered spell)
if (spellInfo_1->SpellIconID == 2834 && spellInfo_2->SpellIconID == 2834)
return false;
// Unstable Sphere Timer and Unstable Sphere Passive
if ((spellInfo_1->Id == 50758 && spellInfo_2->Id == 50756) ||
(spellInfo_2->Id == 50758 && spellInfo_1->Id == 50756))
return false;
break;
}
case SPELLFAMILY_MAGE:
// Arcane Intellect and Insight
if (spellInfo_2->SpellIconID == 125 && spellInfo_1->Id == 18820)
return false;
break;
case SPELLFAMILY_WARRIOR:
{
// Scroll of Protection and Defensive Stance (multi-family check)
if (spellInfo_1->SpellIconID == 276 && spellInfo_1->SpellVisual[0] == 196 && spellInfo_2->Id == 71)
return false;
// Improved Hamstring -> Hamstring (multi-family check)
if ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x2)) && spellInfo_1->Id == 23694)
return false;
// Death Wish and Heart of a Dragon
if (spellInfo_1->Id == 169 && spellInfo_2->SpellIconID == 169)
return false;
break;
}
case SPELLFAMILY_PRIEST:
{
// Berserking/Enrage PvE spells and Mind Trauma
if(spellInfo_1->SpellIconID == 95 && spellInfo_2->Id == 48301)
return false;
break;
// Frenzy (Grand Widow Faerlina) and Mind Trauma
if( spellInfo_1->SpellIconID == 95 && spellInfo_2->SpellFamilyFlags & UI64LIT(0x84000000))
return false;
// Runescroll of Fortitude and Power Word: Fortitude
if( spellInfo_1->Id == 72590 && spellInfo_2->SpellFamilyFlags & UI64LIT(0x8))
return true;
}
case SPELLFAMILY_DRUID:
{
// Scroll of Stamina and Leader of the Pack (multi-family check)
if (spellInfo_1->SpellIconID == 312 && spellInfo_1->SpellVisual[0] == 216 && spellInfo_2->Id == 24932)
return false;
// Dragonmaw Illusion (multi-family check)
if (spellId_1 == 40216 && spellId_2 == 42016)
return false;
// Drums of the Wild and Gift of the Wild
if( spellInfo_1->Id == 72588 && spellInfo_2->SpellFamilyFlags & UI64LIT(0x40000))
return true;
// FG: Gift of the Wild (21849 and ranks) and Gift of the Wild (from Item: Drums of the Wild)
if (spellInfo_1->Id == 72588 && spellInfo_2->SpellIconID == 2435)
return true; // does not stack
break;
}
case SPELLFAMILY_ROGUE:
{
// Garrote-Silence -> Garrote (multi-family check)
if (spellInfo_1->SpellIconID == 498 && spellInfo_1->SpellVisual[0] == 0 && spellInfo_2->SpellIconID == 498)
return false;
// Honor Among Thieves dummy auras (multi-family check)
if (spellId_1 == 51699 && spellId_2 == 52916)
return false;
break;
}
case SPELLFAMILY_HUNTER:
{
// Concussive Shot and Imp. Concussive Shot (multi-family check)
if (spellInfo_1->Id == 19410 && spellInfo_2->Id == 5116)
return false;
// Improved Wing Clip -> Wing Clip (multi-family check)
if ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x40)) && spellInfo_1->Id == 19229)
return false;
break;
}
case SPELLFAMILY_PALADIN:
{
// Unstable Currents and other -> *Sanctity Aura (multi-family check)
if (spellInfo_2->SpellIconID==502 && spellInfo_1->SpellIconID==502 && spellInfo_1->SpellVisual[0]==969)
return false;
// *Band of Eternal Champion and Seal of Command(multi-family check)
if (spellId_1 == 35081 && spellInfo_2->SpellIconID==561 && spellInfo_2->SpellVisual[0]==7992)
return false;
// FG: Frostforged Champion and Seal of Command(multi-family check)
if( spellId_1 == 72412 && spellInfo_2->SpellIconID==561 && spellInfo_2->SpellVisual[0]==7992)
return false;
// Blessing of Sanctuary (multi-family check, some from 16 spell icon spells)
if (spellInfo_1->Id == 67480 && spellInfo_2->Id == 20911)
return false;
// Devotion Aura and Essence if Gossamer
if (spellInfo_1->SpellIconID == 291 && spellInfo_2->SpellIconID == 291)
return false;
// FG: Greater Blessing of Kings and Blessing of Forgotten Kings
if (spellId_1 == 72586 && spellId_2 == 25898)
return true; // does not stack
// Drums of Forgotten Kings and Blessing of Kings
if( spellInfo_1->Id == 72586 && spellInfo_2->SpellFamilyFlags & UI64LIT(0x10000000))
return true;
break;
}
}
// Dragonmaw Illusion, Blood Elf Illusion, Human Illusion, Illidari Agent Illusion, Scarlet Crusade Disguise
if(spellInfo_1->SpellIconID == 1691 && spellInfo_2->SpellIconID == 1691)
return false;
break;
case SPELLFAMILY_MAGE:
if( spellInfo_2->SpellFamilyName == SPELLFAMILY_MAGE )
{
// Blizzard & Chilled (and some other stacked with blizzard spells
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x80)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x100000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x80)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x100000))))
return false;
// Blink & Improved Blink
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x0000000000010000)) && (spellInfo_2->SpellVisual[0] == 72 && spellInfo_2->SpellIconID == 1499)) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x0000000000010000)) && (spellInfo_1->SpellVisual[0] == 72 && spellInfo_1->SpellIconID == 1499)))
return false;
// Fingers of Frost effects
if (spellInfo_1->SpellIconID == 2947 && spellInfo_2->SpellIconID == 2947)
return false;
// Living Bomb & Ignite (Dots)
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x2000000000000)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x8000000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x2000000000000)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x8000000))))
return false;
// Fireball & Pyroblast (Dots)
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x1)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x400000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x1)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x400000))))
return false;
//Focus magic 30min buff and 10s proc
if( (spellInfo_1->SpellIconID == 54648) && (spellInfo_2->SpellIconID == 54646) ||
(spellInfo_2->SpellIconID == 54648) && (spellInfo_1->SpellIconID == 54646) )
return false;
//Improved scorch and Winter's Chill
if( (spellInfo_1->Id == 22959) && (spellInfo_2->Id == 12579) ||
(spellInfo_2->Id == 22959) && (spellInfo_1->Id == 12579) )
return false;
// FG: arcane intelligence, arcane brilliance, dalaran intelligence, dalaran brilliance
if( spellInfo_1->SpellFamilyFlags.Flags == 1024 && spellInfo_2->SpellFamilyFlags.Flags == 1024)
return true; // cant be stacked
}
// Detect Invisibility and Mana Shield (multi-family check)
if (spellInfo_2->Id == 132 && spellInfo_1->SpellIconID == 209 && spellInfo_1->SpellVisual[0] == 968)
return false;
// Combustion and Fire Protection Aura (multi-family check)
if (spellInfo_1->Id == 11129 && spellInfo_2->SpellIconID == 33 && spellInfo_2->SpellVisual[0] == 321)
return false;
// Arcane Intellect and Insight
if (spellInfo_1->SpellIconID == 125 && spellInfo_2->Id == 18820)
return false;
break;
case SPELLFAMILY_WARLOCK:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_WARLOCK)
{
// Siphon Life and Drain Life
if ((spellInfo_1->SpellIconID == 152 && spellInfo_2->SpellIconID == 546) ||
(spellInfo_2->SpellIconID == 152 && spellInfo_1->SpellIconID == 546))
return false;
//Corruption & Seed of corruption
if ((spellInfo_1->SpellIconID == 313 && spellInfo_2->SpellIconID == 1932) ||
(spellInfo_2->SpellIconID == 313 && spellInfo_1->SpellIconID == 1932))
if(spellInfo_1->SpellVisual[0] != 0 && spellInfo_2->SpellVisual[0] != 0)
return true; // can't be stacked
// Corruption and Unstable Affliction
if ((spellInfo_1->SpellIconID == 313 && spellInfo_2->SpellIconID == 2039) ||
(spellInfo_2->SpellIconID == 313 && spellInfo_1->SpellIconID == 2039))
return false;
// (Corruption or Unstable Affliction) and (Curse of Agony or Curse of Doom)
if (((spellInfo_1->SpellIconID == 313 || spellInfo_1->SpellIconID == 2039) && (spellInfo_2->SpellIconID == 544 || spellInfo_2->SpellIconID == 91)) ||
((spellInfo_2->SpellIconID == 313 || spellInfo_2->SpellIconID == 2039) && (spellInfo_1->SpellIconID == 544 || spellInfo_1->SpellIconID == 91)))
return false;
// Shadowflame and Curse of Agony
if( spellInfo_1->SpellIconID == 544 && spellInfo_2->SpellIconID == 3317 ||
spellInfo_2->SpellIconID == 544 && spellInfo_1->SpellIconID == 3317 )
return false;
// Shadowflame and Curse of Doom
if( spellInfo_1->SpellIconID == 91 && spellInfo_2->SpellIconID == 3317 ||
spellInfo_2->SpellIconID == 91 && spellInfo_1->SpellIconID == 3317 )
return false;
// Metamorphosis, diff effects
if (spellInfo_1->SpellIconID == 3314 && spellInfo_2->SpellIconID == 3314)
return false;
// Shadowflame and Corruption
if ( ( (spellInfo_1->SpellFamilyFlags.Flags2 & 0x00000002) && spellInfo_2->SpellIconID == 313 ) ||
( (spellInfo_2->SpellFamilyFlags.Flags2 & 0x00000002) && spellInfo_1->SpellIconID == 313 ) )
return false;
// Shadowflame and Curse of Agony
if ( ( (spellInfo_1->SpellFamilyFlags.Flags2 & 0x00000002) && spellInfo_2->SpellIconID == 544 ) ||
( (spellInfo_2->SpellFamilyFlags.Flags2 & 0x00000002) && spellInfo_1->SpellIconID == 544 ) )
return false;
}
// Detect Invisibility and Mana Shield (multi-family check)
if (spellInfo_1->Id == 132 && spellInfo_2->SpellIconID == 209 && spellInfo_2->SpellVisual[0] == 968)
return false;
break;
case SPELLFAMILY_WARRIOR:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_WARRIOR)
{
// Rend and Deep Wound
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x20)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x1000000000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x20)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x1000000000))))
return false;
// Battle Shout and Rampage
if ((spellInfo_1->SpellIconID == 456 && spellInfo_2->SpellIconID == 2006) ||
(spellInfo_2->SpellIconID == 456 && spellInfo_1->SpellIconID == 2006))
return false;
// Glyph of Revenge (triggered), and Sword and Board (triggered)
if ((spellInfo_1->SpellIconID == 856 && spellInfo_2->SpellIconID == 2780) ||
(spellInfo_2->SpellIconID == 856 && spellInfo_1->SpellIconID == 2780))
return false;
// Defensive/Berserker/Battle stance aura can not stack (needed for dummy auras)
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x800000)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x800000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x800000)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x800000))))
return true;
// Taste of Blood and Sudden Death
if( (spellInfo_1->Id == 52437 && spellInfo_2->Id == 60503) ||
(spellInfo_2->Id == 52437 && spellInfo_1->Id == 60503) )
return false;
}
else if (spellInfo_2->SpellFamilyName == SPELLFAMILY_ROGUE)
{
// Sunder Armor and Expose Armor
if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_RESISTANCE_PCT &&
spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_RESISTANCE_PCT)
return true;
}
// Hamstring -> Improved Hamstring (multi-family check)
if ((spellInfo_1->SpellFamilyFlags & UI64LIT(0x2)) && spellInfo_2->Id == 23694)
return false;
// Defensive Stance and Scroll of Protection (multi-family check)
if (spellInfo_1->Id == 71 && spellInfo_2->SpellIconID == 276 && spellInfo_2->SpellVisual[0] == 196)
return false;
// Bloodlust and Bloodthirst (multi-family check)
if (spellInfo_2->Id == 2825 && spellInfo_1->SpellIconID == 38 && spellInfo_1->SpellVisual[0] == 0)
return false;
// Death Wish and Heart of a Dragon
if (spellInfo_1->Id == 169 && spellInfo_2->SpellIconID == 169 && spellInfo_2->SpellFamilyName == SPELLFAMILY_GENERIC)
return false;
break;
case SPELLFAMILY_PRIEST:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_PRIEST)
{
//Devouring Plague and Shadow Vulnerability
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x2000000)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x800000000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x2000000)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x800000000))))
return false;
//StarShards and Shadow Word: Pain
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x200000)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x8000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x200000)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x8000))))
return false;
// Dispersion
if ((spellInfo_1->Id == 47585 && spellInfo_2->Id == 60069) ||
(spellInfo_2->Id == 47585 && spellInfo_1->Id == 60069))
return false;
// Power Word: Shield and Divine Aegis
if ((spellInfo_1->SpellIconID == 566 && spellInfo_2->SpellIconID == 2820) ||
(spellInfo_2->SpellIconID == 566 && spellInfo_1->SpellIconID == 2820))
return false;
// Inner Fire and Consecration
if (spellInfo_1->SpellIconID == 51 && spellInfo_2->SpellIconID == 51 && spellInfo_2->SpellFamilyName == SPELLFAMILY_PALADIN)
return false;
// Prayer/PW Fortitude && Runescroll of Fortitude
if (spellInfo_1->SpellVisual[0] == 278 && spellInfo_2->Id == 72590)
return true;
}
// Power Word: Fortitude and Runescroll of Fortitude
if( spellInfo_1->SpellFamilyFlags & UI64LIT(0x8) && spellInfo_2->Id == 72590 )
return true;
break;
case SPELLFAMILY_DRUID:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_DRUID)
{
//Omen of Clarity and Blood Frenzy
if (((spellInfo_1->SpellFamilyFlags == UI64LIT(0x0) && spellInfo_1->SpellIconID == 108) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x20000000000000))) ||
((spellInfo_2->SpellFamilyFlags == UI64LIT(0x0) && spellInfo_2->SpellIconID == 108) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x20000000000000))))
return false;
// Tree of Life (Shapeshift) and 34123 Tree of Life (Passive)
if ((spellId_1 == 33891 && spellId_2 == 34123) ||
(spellId_2 == 33891 && spellId_1 == 34123))
return false;
// Lifebloom and Wild Growth
if ((spellInfo_1->SpellIconID == 2101 && spellInfo_2->SpellIconID == 2864) ||
(spellInfo_2->SpellIconID == 2101 && spellInfo_1->SpellIconID == 2864))
return false;
// Innervate and Glyph of Innervate and some other spells
if (spellInfo_1->SpellIconID == 62 && spellInfo_2->SpellIconID == 62)
return false;
// Wrath of Elune and Nature's Grace
if ((spellInfo_1->Id == 16886 && spellInfo_2->Id == 46833) ||
(spellInfo_2->Id == 16886 && spellInfo_1->Id == 46833))
return false;
// Bear Rage (Feral T4 (2)) and Omen of Clarity
if ((spellInfo_1->Id == 16864 && spellInfo_2->Id == 37306) ||
(spellInfo_2->Id == 16864 && spellInfo_1->Id == 37306))
return false;
// Cat Energy (Feral T4 (2)) and Omen of Clarity
if ((spellInfo_1->Id == 16864 && spellInfo_2->Id == 37311) ||
(spellInfo_2->Id == 16864 && spellInfo_1->Id == 37311))
return false;
// Survival Instincts and Survival Instincts
if ((spellInfo_1->Id == 61336 && spellInfo_2->Id == 50322) ||
(spellInfo_2->Id == 61336 && spellInfo_1->Id == 50322))
return false;
// Frenzied Regeneration and Savage Defense
if( spellInfo_1->Id == 22842 && spellInfo_2->Id == 62606 || spellInfo_2->Id == 22842 && spellInfo_1->Id == 62606 )
return false;
// Savage Roar and Savage Roar (triggered)
if (spellInfo_1->SpellIconID == 2865 && spellInfo_2->SpellIconID == 2865)
return false;
// Frenzied Regeneration and Savage Defense
if ((spellInfo_1->Id == 22842 && spellInfo_2->Id == 62606) ||
(spellInfo_2->Id == 22842 && spellInfo_1->Id == 62606))
return false;
// FG: Moonfire and Lacerate
if ((spellInfo_1->SpellIconID == 225 && spellInfo_2->SpellIconID == 2246)
|| (spellInfo_1->SpellIconID == 2246 && spellInfo_2->SpellIconID == 225))
return false;
}
// FG: Gift of the Wild (21849 and ranks) and Gift of the Wild (from Item: Drums of the Wild)
if (spellInfo_1->SpellIconID == 2435 && spellId_2 == 72588)
return true; // does not stack
// Leader of the Pack and Scroll of Stamina (multi-family check)
if (spellInfo_1->Id == 24932 && spellInfo_2->SpellIconID == 312 && spellInfo_2->SpellVisual[0] == 216)
return false;
// Dragonmaw Illusion (multi-family check)
if (spellId_1 == 42016 && spellId_2 == 40216 )
return false;
// Gift of the Wild and Drums of the Wild
if( spellInfo_1->SpellFamilyFlags & UI64LIT(0x40000) && spellInfo_2->Id == 72588)
return true;
break;
case SPELLFAMILY_ROGUE:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_ROGUE)
{
// Master of Subtlety
if ((spellId_1 == 31665 && spellId_2 == 31666) ||
(spellId_1 == 31666 && spellId_2 == 31665))
return false;
// Sprint & Sprint (waterwalk)
if (spellInfo_1->SpellIconID == 516 && spellInfo_2->SpellIconID == 516 &&
((spellInfo_1->Category == 44 && spellInfo_2->Category == 0) ||
(spellInfo_2->Category == 44 && spellInfo_1->Category == 0)))
return false;
}
else if (spellInfo_2->SpellFamilyName == SPELLFAMILY_GENERIC)
{
if (spellInfo_1->SpellIconID == 2903 && spellInfo_2->SpellIconID == 2903)
return false;
// Honor Among Thieves dummy auras (multi-family check)
if (spellId_1 == 52916 && spellId_2 == 51699)
return false;
}
else if (spellInfo_2->SpellFamilyName == SPELLFAMILY_WARRIOR)
{
// Sunder Armor and Expose Armor
if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_RESISTANCE_PCT &&
spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_RESISTANCE_PCT)
return true;
}
//Overkill
if (spellInfo_1->SpellIconID == 2285 && spellInfo_2->SpellIconID == 2285)
return false;
// Garrote -> Garrote-Silence (multi-family check)
if (spellInfo_1->SpellIconID == 498 && spellInfo_2->SpellIconID == 498 && spellInfo_2->SpellVisual[0] == 0)
return false;
break;
case SPELLFAMILY_HUNTER:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_HUNTER)
{
// Rapid Fire & Quick Shots
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x20)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x20000000000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x20)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x20000000000))) )
return false;
// Serpent Sting & (Immolation/Explosive Trap Effect)
if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x4)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x00000004000))) ||
((spellInfo_2->SpellFamilyFlags & UI64LIT(0x4)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x00000004000))))
return false;
// Deterrence
if (spellInfo_1->SpellIconID == 83 && spellInfo_2->SpellIconID == 83)
return false;
// Bestial Wrath
if (spellInfo_1->SpellIconID == 1680 && spellInfo_2->SpellIconID == 1680)
return false;
// Aspect of the Viper & Vicious Viper
if (spellInfo_1->SpellIconID == 2227 && spellInfo_2->SpellIconID == 2227)
return false;
}
// Repentance and Track Humanoids
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_PALADIN && spellInfo_1->SpellIconID == 316 && spellInfo_2->SpellIconID == 316)
return false;
// Wing Clip -> Improved Wing Clip (multi-family check)
if ((spellInfo_1->SpellFamilyFlags & UI64LIT(0x40)) && spellInfo_2->Id == 19229)
return false;
// Concussive Shot and Imp. Concussive Shot (multi-family check)
if (spellInfo_2->Id == 19410 && spellInfo_1->Id == 5116)
return false;
break;
case SPELLFAMILY_PALADIN:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_PALADIN)
{
// Paladin Seals
if (IsSealSpell(spellInfo_1) && IsSealSpell(spellInfo_2))
return true;
//Blood Corruption, Holy Vengeance, Righteous Vengeance
if ((spellInfo_1->SpellIconID == 2292 && spellInfo_2->SpellIconID == 3025) ||
(spellInfo_2->SpellIconID == 2292 && spellInfo_1->SpellIconID == 3025))
return false;
// Swift Retribution / Improved Devotion Aura (talents) and Paladin Auras
if ((spellInfo_1->IsFitToFamilyMask(UI64LIT(0x0), 0x00000020) && (spellInfo_2->SpellIconID == 291 || spellInfo_2->SpellIconID == 3028)) ||
(spellInfo_2->IsFitToFamilyMask(UI64LIT(0x0), 0x00000020) && (spellInfo_1->SpellIconID == 291 || spellInfo_1->SpellIconID == 3028)))
return false;
// Beacon of Light and Light's Beacon
if ((spellInfo_1->SpellIconID == 3032) && (spellInfo_2->SpellIconID == 3032))
return false;
// Concentration Aura and Improved Concentration Aura and Aura Mastery
if ((spellInfo_1->SpellIconID == 1487) && (spellInfo_2->SpellIconID == 1487))
return false;
// Seal of Corruption (caster/target parts stacking allow, other stacking checked by spell specs)
if (spellInfo_1->SpellIconID == 2292 && spellInfo_2->SpellIconID == 2292)
return false;
// Divine Sacrifice and Divine Guardian
if (spellInfo_1->SpellIconID == 3837 && spellInfo_2->SpellIconID == 3837)
return false;
// Blood Corruption, Holy Vengeance, Righteous Vengeance
if ((spellInfo_1->SpellIconID == 2292 && spellInfo_2->SpellIconID == 3025) ||
(spellInfo_2->SpellIconID == 2292 && spellInfo_1->SpellIconID == 3025))
return false;
// Sacred Shield and Blessing of Sanctuary
if ((( spellInfo_1->SpellFamilyFlags & UI64LIT(0x0008000000000000)) &&
(spellInfo_2->Id == 25899 || spellInfo_2->Id == 20911)) ||
(( spellInfo_2->SpellFamilyFlags & UI64LIT(0x0008000000000000))
&& (spellInfo_1->Id == 25899 || spellInfo_1->Id == 20911)))
return false;
// Seal of Corruption/Vengeance DoT and Righteouss Fury
if ((spellInfo_1->SpellIconID == 3025 && spellInfo_2->SpellIconID == 2292) ||
(spellInfo_1->SpellIconID == 2292 && spellInfo_2->SpellIconID == 3025))
return false;
}
// Blessing of Sanctuary (multi-family check, some from 16 spell icon spells)
if (spellInfo_2->Id == 67480 && spellInfo_1->Id == 20911)
return false;
// Combustion and Fire Protection Aura (multi-family check)
if (spellInfo_2->Id == 11129 && spellInfo_1->SpellIconID == 33 && spellInfo_1->SpellVisual[0] == 321)
return false;
// *Sanctity Aura -> Unstable Currents and other (multi-family check)
if (spellInfo_1->SpellIconID==502 && spellInfo_2->SpellFamilyName == SPELLFAMILY_GENERIC && spellInfo_2->SpellIconID==502 && spellInfo_2->SpellVisual[0]==969)
return false;
// *Seal of Command and Band of Eternal Champion (multi-family check)
if (spellInfo_1->SpellIconID==561 && spellInfo_1->SpellVisual[0]==7992 && spellId_2 == 35081)
return false;
// Blessing of Kings and Drums of Forgotten Kings
if( spellInfo_1->SpellFamilyFlags & UI64LIT(0x10000000) && spellInfo_2->Id == 72586)
return true;
break;
// FG: Seal of Command and Frostforged Champion (multi-family check)
if( spellInfo_1->SpellIconID==561 && spellInfo_1->SpellVisual[0]==7992 && spellId_2 == 72412)
return false;
// Devotion Aura and Essence of Gossamer
if (spellInfo_1->SpellIconID == 291 && spellInfo_2->SpellIconID == 291 && spellInfo_2->SpellFamilyName == SPELLFAMILY_GENERIC)
return false;
// Inner Fire and Consecration
if (spellInfo_1->SpellIconID == 51 && spellInfo_2->SpellIconID == 51 && spellInfo_2->SpellFamilyName == SPELLFAMILY_PRIEST)
return false;
// Repentance and Track Humanoids
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_HUNTER && spellInfo_1->SpellIconID == 316 && spellInfo_2->SpellIconID == 316)
return false;
// FG: Greater Blessing of Kings and Blessing of Forgotten Kings
if (spellId_1 == 25898 && spellId_2 == 72586)
return true; // does not stack
break;
case SPELLFAMILY_SHAMAN:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_SHAMAN)
{
// Windfury weapon
if (spellInfo_1->SpellIconID==220 && spellInfo_2->SpellIconID==220 &&
!spellInfo_1->IsFitToFamilyMask(spellInfo_2->SpellFamilyFlags))
return false;
// Ghost Wolf
if (spellInfo_1->SpellIconID == 67 && spellInfo_2->SpellIconID == 67)
return false;
// Totem of Wrath (positive/negative), ranks checked early
if (spellInfo_1->SpellIconID == 2019 && spellInfo_2->SpellIconID == 2019)
return false;
}
// Bloodlust and Bloodthirst (multi-family check)
if (spellInfo_1->Id == 2825 && spellInfo_2->SpellIconID == 38 && spellInfo_2->SpellVisual[0] == 0)
return false;
break;
case SPELLFAMILY_DEATHKNIGHT:
if (spellInfo_2->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT)
{
// Lichborne and Lichborne (triggered)
if (spellInfo_1->SpellIconID == 61 && spellInfo_2->SpellIconID == 61)
return false;
// Frost Presence and Frost Presence (triggered)
if (spellInfo_1->SpellIconID == 2632 && spellInfo_2->SpellIconID == 2632)
return false;
// Unholy Presence and Unholy Presence (triggered)
if (spellInfo_1->SpellIconID == 2633 && spellInfo_2->SpellIconID == 2633)
return false;
// Blood Presence and Blood Presence (triggered)
if (spellInfo_1->SpellIconID == 2636 && spellInfo_2->SpellIconID == 2636)
return false;
}
break;
default:
break;
}
// more generic checks
if (spellInfo_1->SpellIconID == spellInfo_2->SpellIconID &&
spellInfo_1->SpellIconID != 0 && spellInfo_2->SpellIconID != 0)
{
bool isModifier = false;
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (spellInfo_1->EffectApplyAuraName[i] == SPELL_AURA_ADD_FLAT_MODIFIER ||
spellInfo_1->EffectApplyAuraName[i] == SPELL_AURA_ADD_PCT_MODIFIER ||
spellInfo_2->EffectApplyAuraName[i] == SPELL_AURA_ADD_FLAT_MODIFIER ||
spellInfo_2->EffectApplyAuraName[i] == SPELL_AURA_ADD_PCT_MODIFIER )
isModifier = true;
}
if (!isModifier)
return true;
}
if (IsRankSpellDueToSpell(spellInfo_1, spellId_2))
return true;
if (spellInfo_1->SpellFamilyName == 0 || spellInfo_2->SpellFamilyName == 0)
return false;
if (spellInfo_1->SpellFamilyName != spellInfo_2->SpellFamilyName)
return false;
bool dummy_only = true;
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (spellInfo_1->Effect[i] != spellInfo_2->Effect[i] ||
spellInfo_1->EffectItemType[i] != spellInfo_2->EffectItemType[i] ||
spellInfo_1->EffectMiscValue[i] != spellInfo_2->EffectMiscValue[i] ||
spellInfo_1->EffectApplyAuraName[i] != spellInfo_2->EffectApplyAuraName[i])
return false;
// ignore dummy only spells
if (spellInfo_1->Effect[i] && spellInfo_1->Effect[i] != SPELL_EFFECT_DUMMY && spellInfo_1->EffectApplyAuraName[i] != SPELL_AURA_DUMMY)
dummy_only = false;
}
if (dummy_only)
return false;
return true;
}
bool SpellMgr::IsProfessionOrRidingSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if(!spellInfo)
return false;
if (spellInfo->Effect[EFFECT_INDEX_1] != SPELL_EFFECT_SKILL)
return false;
uint32 skill = spellInfo->EffectMiscValue[EFFECT_INDEX_1];
return IsProfessionOrRidingSkill(skill);
}
bool SpellMgr::IsProfessionSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if(!spellInfo)
return false;
if (spellInfo->Effect[EFFECT_INDEX_1] != SPELL_EFFECT_SKILL)
return false;
uint32 skill = spellInfo->EffectMiscValue[EFFECT_INDEX_1];
return IsProfessionSkill(skill);
}
bool SpellMgr::IsPrimaryProfessionSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if(!spellInfo)
return false;
if (spellInfo->Effect[EFFECT_INDEX_1] != SPELL_EFFECT_SKILL)
return false;
uint32 skill = spellInfo->EffectMiscValue[EFFECT_INDEX_1];
return IsPrimaryProfessionSkill(skill);
}
uint32 SpellMgr::GetProfessionSpellMinLevel(uint32 spellId)
{
uint32 s2l[8][3] =
{ // 0 - gather 1 - non-gather 2 - fish
/*0*/ { 0, 5, 5 },
/*1*/ { 0, 5, 5 },
/*2*/ { 0, 10, 10 },
/*3*/ { 10, 20, 10 },
/*4*/ { 25, 35, 10 },
/*5*/ { 40, 50, 10 },
/*6*/ { 55, 65, 10 },
/*7*/ { 75, 75, 10 },
};
uint32 rank = GetSpellRank(spellId);
if (rank >= 8)
return 0;
SkillLineAbilityMapBounds bounds = GetSkillLineAbilityMapBounds(spellId);
if (bounds.first == bounds.second)
return 0;
switch (bounds.first->second->skillId)
{
case SKILL_FISHING:
return s2l[rank][2];
case SKILL_HERBALISM:
case SKILL_MINING:
case SKILL_SKINNING:
return s2l[rank][0];
default:
return s2l[rank][1];
}
}
bool SpellMgr::IsPrimaryProfessionFirstRankSpell(uint32 spellId) const
{
return IsPrimaryProfessionSpell(spellId) && GetSpellRank(spellId)==1;
}
bool SpellMgr::IsSkillBonusSpell(uint32 spellId) const
{
SkillLineAbilityMapBounds bounds = GetSkillLineAbilityMapBounds(spellId);
for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
SkillLineAbilityEntry const *pAbility = _spell_idx->second;
if (!pAbility || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
continue;
if (pAbility->req_skill_value > 0)
return true;
}
return false;
}
SpellEntry const* SpellMgr::SelectAuraRankForLevel(SpellEntry const* spellInfo, uint32 level) const
{
// fast case
if (level + 10 >= spellInfo->spellLevel)
return spellInfo;
// ignore selection for passive spells
if (IsPassiveSpell(spellInfo))
return spellInfo;
bool needRankSelection = false;
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
// for simple aura in check apply to any non caster based targets, in rank search mode to any explicit targets
if (((spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA &&
(IsExplicitPositiveTarget(spellInfo->EffectImplicitTargetA[i]) ||
IsAreaEffectPossitiveTarget(Targets(spellInfo->EffectImplicitTargetA[i])))) ||
spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PARTY ||
spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_RAID) &&
IsPositiveEffect(spellInfo, SpellEffectIndex(i)))
{
needRankSelection = true;
break;
}
}
// not required (rank check more slow so check it here)
if (!needRankSelection || GetSpellRank(spellInfo->Id) == 0)
return spellInfo;
for(uint32 nextSpellId = spellInfo->Id; nextSpellId != 0; nextSpellId = GetPrevSpellInChain(nextSpellId))
{
SpellEntry const *nextSpellInfo = sSpellStore.LookupEntry(nextSpellId);
if (!nextSpellInfo)
break;
// if found appropriate level
if (level + 10 >= spellInfo->spellLevel)
return nextSpellInfo;
// one rank less then
}
// not found
return NULL;
}
typedef UNORDERED_MAP<uint32,uint32> AbilitySpellPrevMap;
static void LoadSpellChains_AbilityHelper(SpellChainMap& chainMap, AbilitySpellPrevMap const& prevRanks, uint32 spell_id, uint32 prev_id, uint32 deep = 30)
{
// spell already listed in chains store
SpellChainMap::const_iterator chain_itr = chainMap.find(spell_id);
if (chain_itr != chainMap.end())
{
MANGOS_ASSERT(chain_itr->second.prev == prev_id && "LoadSpellChains_AbilityHelper: Conflicting data in talents or spell abilities dbc");
return;
}
// prev rank listed in main chain table (can fill correct data directly)
SpellChainMap::const_iterator prev_chain_itr = chainMap.find(prev_id);
if (prev_chain_itr != chainMap.end())
{
SpellChainNode node;
node.prev = prev_id;
node.first = prev_chain_itr->second.first;
node.rank = prev_chain_itr->second.rank+1;
node.req = 0;
chainMap[spell_id] = node;
return;
}
// prev spell not listed in prev ranks store, so it first rank
AbilitySpellPrevMap::const_iterator prev_itr = prevRanks.find(prev_id);
if (prev_itr == prevRanks.end())
{
SpellChainNode prev_node;
prev_node.prev = 0;
prev_node.first = prev_id;
prev_node.rank = 1;
prev_node.req = 0;
chainMap[prev_id] = prev_node;
SpellChainNode node;
node.prev = prev_id;
node.first = prev_id;
node.rank = 2;
node.req = 0;
chainMap[spell_id] = node;
return;
}
if (deep == 0)
{
MANGOS_ASSERT(false && "LoadSpellChains_AbilityHelper: Infinity cycle in spell ability data");
return;
}
// prev rank listed, so process it first
LoadSpellChains_AbilityHelper(chainMap, prevRanks, prev_id, prev_itr->second, deep-1);
// prev rank must be listed now
prev_chain_itr = chainMap.find(prev_id);
if (prev_chain_itr == chainMap.end())
return;
SpellChainNode node;
node.prev = prev_id;
node.first = prev_chain_itr->second.first;
node.rank = prev_chain_itr->second.rank+1;
node.req = 0;
chainMap[spell_id] = node;
}
void SpellMgr::LoadSpellChains()
{
mSpellChains.clear(); // need for reload case
mSpellChainsNext.clear(); // need for reload case
// load known data for talents
for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
{
TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
if (!talentInfo)
continue;
// not add ranks for 1 ranks talents (if exist non ranks spells then it will included in table data)
if (!talentInfo->RankID[1])
continue;
for (int j = 0; j < MAX_TALENT_RANK; j++)
{
uint32 spell_id = talentInfo->RankID[j];
if (!spell_id)
continue;
if (!sSpellStore.LookupEntry(spell_id))
{
//sLog.outErrorDb("Talent %u not exist as spell",spell_id);
continue;
}
SpellChainNode node;
node.prev = (j > 0) ? talentInfo->RankID[j-1] : 0;
node.first = talentInfo->RankID[0];
node.rank = j+1;
node.req = 0;
mSpellChains[spell_id] = node;
}
}
// load known data from spell abilities
{
// we can calculate ranks only after full data generation
AbilitySpellPrevMap prevRanks;
for(SkillLineAbilityMap::const_iterator ab_itr = mSkillLineAbilityMap.begin(); ab_itr != mSkillLineAbilityMap.end(); ++ab_itr)
{
uint32 spell_id = ab_itr->first;
// skip GM/test/internal spells.begin Its not have ranks anyway
if (ab_itr->second->skillId == SKILL_INTERNAL)
continue;
// some forward spells not exist and can be ignored (some outdated data)
SpellEntry const* spell_entry = sSpellStore.LookupEntry(spell_id);
if (!spell_entry) // no cases
continue;
// ignore spell without forwards (non ranked or missing info in skill abilities)
uint32 forward_id = ab_itr->second->forward_spellid;
if (!forward_id)
continue;
// some forward spells not exist and can be ignored (some outdated data)
SpellEntry const* forward_entry = sSpellStore.LookupEntry(forward_id);
if (!forward_entry)
continue;
// some forward spells still exist but excluded from real use as ranks and not listed in skill abilities now
SkillLineAbilityMapBounds bounds = mSkillLineAbilityMap.equal_range(forward_id);
if (bounds.first == bounds.second)
continue;
// spell already listed in chains store
SpellChainMap::const_iterator chain_itr = mSpellChains.find(forward_id);
if (chain_itr != mSpellChains.end())
{
MANGOS_ASSERT(chain_itr->second.prev == spell_id && "Conflicting data in talents or spell abilities dbc");
continue;
}
// spell already listed in prev ranks store
AbilitySpellPrevMap::const_iterator prev_itr = prevRanks.find(forward_id);
if (prev_itr != prevRanks.end())
{
MANGOS_ASSERT(prev_itr->second == spell_id && "Conflicting data in talents or spell abilities dbc");
continue;
}
// prev rank listed in main chain table (can fill correct data directly)
SpellChainMap::const_iterator prev_chain_itr = mSpellChains.find(spell_id);
if (prev_chain_itr != mSpellChains.end())
{
SpellChainNode node;
node.prev = spell_id;
node.first = prev_chain_itr->second.first;
node.rank = prev_chain_itr->second.rank+1;
node.req = 0;
mSpellChains[forward_id] = node;
continue;
}
// need temporary store for later rank calculation
prevRanks[forward_id] = spell_id;
}
while (!prevRanks.empty())
{
uint32 spell_id = prevRanks.begin()->first;
uint32 prev_id = prevRanks.begin()->second;
prevRanks.erase(prevRanks.begin());
LoadSpellChains_AbilityHelper(mSpellChains, prevRanks, spell_id, prev_id);
}
}
// load custom case
QueryResult *result = WorldDatabase.Query("SELECT spell_id, prev_spell, first_spell, rank, req_spell FROM spell_chain");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> Loaded 0 spell chain records");
sLog.outErrorDb("`spell_chains` table is empty!");
return;
}
uint32 dbc_count = mSpellChains.size();
uint32 new_count = 0;
uint32 req_count = 0;
BarGoLink bar(result->GetRowCount());
do
{
bar.step();
Field *fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
SpellChainNode node;
node.prev = fields[1].GetUInt32();
node.first = fields[2].GetUInt32();
node.rank = fields[3].GetUInt8();
node.req = fields[4].GetUInt32();
if (!sSpellStore.LookupEntry(spell_id))
{
sLog.outErrorDb("Spell %u listed in `spell_chain` does not exist",spell_id);
continue;
}
SpellChainMap::iterator chain_itr = mSpellChains.find(spell_id);
if (chain_itr != mSpellChains.end())
{
if (chain_itr->second.rank != node.rank)
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` expected rank %u by DBC data.",
spell_id,node.prev,node.first,node.rank,node.req,chain_itr->second.rank);
continue;
}
if (chain_itr->second.prev != node.prev)
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` expected prev %u by DBC data.",
spell_id,node.prev,node.first,node.rank,node.req,chain_itr->second.prev);
continue;
}
if (chain_itr->second.first != node.first)
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` expected first %u by DBC data.",
spell_id,node.prev,node.first,node.rank,node.req,chain_itr->second.first);
continue;
}
// update req field by table data
if (node.req)
{
chain_itr->second.req = node.req;
++req_count;
continue;
}
// in other case redundant
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) already added (talent or spell ability with forward) and non need in `spell_chain`",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}
if (node.prev != 0 && !sSpellStore.LookupEntry(node.prev))
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has nonexistent previous rank spell.",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}
if(!sSpellStore.LookupEntry(node.first))
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existing first rank spell.",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}
// check basic spell chain data integrity (note: rank can be equal 0 or 1 for first/single spell)
if( (spell_id == node.first) != (node.rank <= 1) ||
(spell_id == node.first) != (node.prev == 0) ||
(node.rank <= 1) != (node.prev == 0) )
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not compatible chain data.",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}
if(node.req!=0 && !sSpellStore.LookupEntry(node.req))
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existing required spell.",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}
// talents not required data in spell chain for work, but must be checked if present for integrity
if(TalentSpellPos const* pos = GetTalentSpellPos(spell_id))
{
if(node.rank!=pos->rank+1)
{
sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong rank.",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}
if(TalentEntry const* talentEntry = sTalentStore.LookupEntry(pos->talent_id))
{
if(node.first!=talentEntry->RankID[0])
{
sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong first rank spell.",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}
if(node.rank > 1 && node.prev != talentEntry->RankID[node.rank-1-1])
{
sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong prev rank spell.",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}
/*if(node.req!=talentEntry->DependsOnSpell)
{
sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong required spell.",
spell_id,node.prev,node.first,node.rank,node.req);
continue;
}*/
}
}
// removed ranks often still listed as forward in skill abilities but not listed as spell in it
if (node.prev)
{
bool skip = false;
// some forward spells still exist but excluded from real use as ranks and not listed in skill abilities now
SkillLineAbilityMapBounds bounds = mSkillLineAbilityMap.equal_range(spell_id);
if (bounds.first == bounds.second)
{
SkillLineAbilityMapBounds prev_bounds = mSkillLineAbilityMap.equal_range(node.prev);
for(SkillLineAbilityMap::const_iterator ab_itr = prev_bounds.first; ab_itr != prev_bounds.second; ++ab_itr)
{
// spell listed as forward and not listed as ability
// this is marker for removed ranks
if (ab_itr->second->forward_spellid == spell_id)
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` is removed rank by DBC data.",
spell_id, node.prev, node.first, node.rank, node.req);
skip = true;
break;
}
}
}
if (skip)
continue;
}
mSpellChains[spell_id] = node;
++new_count;
} while( result->NextRow() );
delete result;
// additional integrity checks
for(SpellChainMap::const_iterator i = mSpellChains.begin(); i != mSpellChains.end(); ++i)
{
if(i->second.prev)
{
SpellChainMap::const_iterator i_prev = mSpellChains.find(i->second.prev);
if(i_prev == mSpellChains.end())
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not found previous rank spell in table.",
i->first,i->second.prev,i->second.first,i->second.rank,i->second.req);
}
else if( i_prev->second.first != i->second.first )
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has different first spell in chain compared to previous rank spell (prev: %u, first: %u, rank: %d, req: %u).",
i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
i_prev->second.prev,i_prev->second.first,i_prev->second.rank,i_prev->second.req);
}
else if( i_prev->second.rank+1 != i->second.rank )
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has different rank compared to previous rank spell (prev: %u, first: %u, rank: %d, req: %u).",
i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
i_prev->second.prev,i_prev->second.first,i_prev->second.rank,i_prev->second.req);
}
}
if(i->second.req)
{
SpellChainMap::const_iterator i_req = mSpellChains.find(i->second.req);
if(i_req == mSpellChains.end())
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not found required rank spell in table.",
i->first,i->second.prev,i->second.first,i->second.rank,i->second.req);
}
else if( i_req->second.first == i->second.first )
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has required rank spell from same spell chain (prev: %u, first: %u, rank: %d, req: %u).",
i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
i_req->second.prev,i_req->second.first,i_req->second.rank,i_req->second.req);
}
else if( i_req->second.req )
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has required rank spell with required spell (prev: %u, first: %u, rank: %d, req: %u).",
i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
i_req->second.prev,i_req->second.first,i_req->second.rank,i_req->second.req);
}
}
}
// fill next rank cache
for(SpellChainMap::const_iterator i = mSpellChains.begin(); i != mSpellChains.end(); ++i)
{
uint32 spell_id = i->first;
SpellChainNode const& node = i->second;
if(node.prev)
mSpellChainsNext.insert(SpellChainMapNext::value_type(node.prev,spell_id));
if(node.req)
mSpellChainsNext.insert(SpellChainMapNext::value_type(node.req,spell_id));
}
// check single rank redundant cases (single rank talents/spell abilities not added by default so this can be only custom cases)
for(SpellChainMap::const_iterator i = mSpellChains.begin(); i != mSpellChains.end(); ++i)
{
// skip non-first ranks, and spells with additional reqs
if (i->second.rank > 1 || i->second.req)
continue;
if (mSpellChainsNext.find(i->first) == mSpellChainsNext.end())
{
sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has single rank data, so redundant.",
i->first,i->second.prev,i->second.first,i->second.rank,i->second.req);
}
}
sLog.outString();
sLog.outString( ">> Loaded %u spell chain records (%u from DBC data with %u req field updates, and %u loaded from table)", dbc_count+new_count, dbc_count, req_count, new_count);
}
void SpellMgr::LoadSpellLearnSkills()
{
mSpellLearnSkills.clear(); // need for reload case
// search auto-learned skills and add its to map also for use in unlearn spells/talents
uint32 dbc_count = 0;
BarGoLink bar(sSpellStore.GetNumRows());
for (uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell)
{
bar.step();
SpellEntry const* entry = sSpellStore.LookupEntry(spell);
if (!entry)
continue;
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (entry->Effect[i] == SPELL_EFFECT_SKILL)
{
SpellLearnSkillNode dbc_node;
dbc_node.skill = entry->EffectMiscValue[i];
dbc_node.step = entry->CalculateSimpleValue(SpellEffectIndex(i));
if (dbc_node.skill != SKILL_RIDING)
dbc_node.value = 1;
else
dbc_node.value = dbc_node.step * 75;
dbc_node.maxvalue = dbc_node.step * 75;
mSpellLearnSkills[spell] = dbc_node;
++dbc_count;
break;
}
}
}
sLog.outString();
sLog.outString(">> Loaded %u Spell Learn Skills from DBC", dbc_count);
}
void SpellMgr::LoadSpellLearnSpells()
{
mSpellLearnSpells.clear(); // need for reload case
// 0 1 2
QueryResult *result = WorldDatabase.Query("SELECT entry, SpellID, Active FROM spell_learn_spell");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> Loaded 0 spell learn spells");
sLog.outErrorDb("`spell_learn_spell` table is empty!");
return;
}
uint32 count = 0;
BarGoLink bar(result->GetRowCount());
do
{
bar.step();
Field *fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
SpellLearnSpellNode node;
node.spell = fields[1].GetUInt32();
node.active = fields[2].GetBool();
node.autoLearned= false;
if (!sSpellStore.LookupEntry(spell_id))
{
sLog.outErrorDb("Spell %u listed in `spell_learn_spell` does not exist",spell_id);
continue;
}
if (!sSpellStore.LookupEntry(node.spell))
{
sLog.outErrorDb("Spell %u listed in `spell_learn_spell` learning nonexistent spell %u",spell_id,node.spell);
continue;
}
if (GetTalentSpellCost(node.spell))
{
sLog.outErrorDb("Spell %u listed in `spell_learn_spell` attempt learning talent spell %u, skipped",spell_id,node.spell);
continue;
}
mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell_id,node));
++count;
} while (result->NextRow());
delete result;
// search auto-learned spells and add its to map also for use in unlearn spells/talents
uint32 dbc_count = 0;
for(uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell)
{
SpellEntry const* entry = sSpellStore.LookupEntry(spell);
if (!entry)
continue;
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if(entry->Effect[i]==SPELL_EFFECT_LEARN_SPELL)
{
SpellLearnSpellNode dbc_node;
dbc_node.spell = entry->EffectTriggerSpell[i];
dbc_node.active = true; // all dbc based learned spells is active (show in spell book or hide by client itself)
// ignore learning nonexistent spells (broken/outdated/or generic learning spell 483
if (!sSpellStore.LookupEntry(dbc_node.spell))
continue;
// talent or passive spells or skill-step spells auto-casted and not need dependent learning,
// pet teaching spells don't must be dependent learning (casted)
// other required explicit dependent learning
dbc_node.autoLearned = entry->EffectImplicitTargetA[i]==TARGET_PET || GetTalentSpellCost(spell) > 0 || IsPassiveSpell(entry) || IsSpellHaveEffect(entry,SPELL_EFFECT_SKILL_STEP);
SpellLearnSpellMapBounds db_node_bounds = GetSpellLearnSpellMapBounds(spell);
bool found = false;
for(SpellLearnSpellMap::const_iterator itr = db_node_bounds.first; itr != db_node_bounds.second; ++itr)
{
if (itr->second.spell == dbc_node.spell)
{
sLog.outErrorDb("Spell %u auto-learn spell %u in spell.dbc then the record in `spell_learn_spell` is redundant, please fix DB.",
spell,dbc_node.spell);
found = true;
break;
}
}
if (!found) // add new spell-spell pair if not found
{
mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell,dbc_node));
++dbc_count;
}
}
}
}
sLog.outString();
sLog.outString( ">> Loaded %u spell learn spells + %u found in DBC", count, dbc_count );
}
void SpellMgr::LoadSpellScriptTarget()
{
mSpellScriptTarget.clear(); // need for reload case
uint32 count = 0;
QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM spell_script_target");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outErrorDb(">> Loaded 0 SpellScriptTarget. DB table `spell_script_target` is empty.");
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 spellId = fields[0].GetUInt32();
uint32 type = fields[1].GetUInt32();
uint32 targetEntry = fields[2].GetUInt32();
SpellEntry const* spellProto = sSpellStore.LookupEntry(spellId);
if (!spellProto)
{
sLog.outErrorDb("Table `spell_script_target`: spellId %u listed for TargetEntry %u does not exist.",spellId,targetEntry);
continue;
}
bool targetfound = false;
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if( spellProto->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
spellProto->EffectImplicitTargetB[i] == TARGET_SCRIPT ||
spellProto->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
spellProto->EffectImplicitTargetB[i] == TARGET_SCRIPT_COORDINATES ||
spellProto->EffectImplicitTargetA[i] == TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT ||
spellProto->EffectImplicitTargetB[i] == TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT ||
spellProto->EffectImplicitTargetA[i] == TARGET_AREAEFFECT_INSTANT ||
spellProto->EffectImplicitTargetB[i] == TARGET_AREAEFFECT_INSTANT ||
spellProto->EffectImplicitTargetA[i] == TARGET_AREAEFFECT_CUSTOM ||
spellProto->EffectImplicitTargetB[i] == TARGET_AREAEFFECT_CUSTOM ||
spellProto->EffectImplicitTargetA[i] == TARGET_AREAEFFECT_GO_AROUND_DEST ||
spellProto->EffectImplicitTargetB[i] == TARGET_AREAEFFECT_GO_AROUND_DEST)
{
targetfound = true;
break;
}
}
if (!targetfound)
{
sLog.outErrorDb("Table `spell_script_target`: spellId %u listed for TargetEntry %u does not have any implicit target TARGET_SCRIPT(38) or TARGET_SCRIPT_COORDINATES (46) or TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT (40).", spellId, targetEntry);
continue;
}
if (type >= MAX_SPELL_TARGET_TYPE)
{
sLog.outErrorDb("Table `spell_script_target`: target type %u for TargetEntry %u is incorrect.",type,targetEntry);
continue;
}
// Checks by target type
switch (type)
{
case SPELL_TARGET_TYPE_GAMEOBJECT:
{
if (!targetEntry)
break;
if (!sGOStorage.LookupEntry<GameObjectInfo>(targetEntry))
{
sLog.outErrorDb("Table `spell_script_target`: gameobject template entry %u does not exist.",targetEntry);
continue;
}
break;
}
default:
if (!targetEntry)
{
sLog.outErrorDb("Table `spell_script_target`: target entry == 0 for not GO target type (%u).",type);
continue;
}
if (const CreatureInfo* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(targetEntry))
{
if (spellId == 30427 && !cInfo->SkinLootId)
{
sLog.outErrorDb("Table `spell_script_target` has creature %u as a target of spellid 30427, but this creature has no skinlootid. Gas extraction will not work!", cInfo->Entry);
continue;
}
}
else
{
sLog.outErrorDb("Table `spell_script_target`: creature template entry %u does not exist.",targetEntry);
continue;
}
break;
}
mSpellScriptTarget.insert(SpellScriptTarget::value_type(spellId,SpellTargetEntry(SpellTargetType(type),targetEntry)));
++count;
} while (result->NextRow());
delete result;
// Check all spells
/* Disabled (lot errors at this moment)
for(uint32 i = 1; i < sSpellStore.nCount; ++i)
{
SpellEntry const * spellInfo = sSpellStore.LookupEntry(i);
if(!spellInfo)
continue;
bool found = false;
for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
{
if( spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT || spellInfo->EffectImplicitTargetA[j] != TARGET_SELF && spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT )
{
SpellScriptTarget::const_iterator lower = GetBeginSpellScriptTarget(spellInfo->Id);
SpellScriptTarget::const_iterator upper = GetEndSpellScriptTarget(spellInfo->Id);
if(lower==upper)
{
sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = %u (TARGET_SCRIPT), but does not have record in `spell_script_target`",spellInfo->Id,TARGET_SCRIPT);
break; // effects of spell
}
}
}
}
*/
sLog.outString();
sLog.outString(">> Loaded %u Spell Script Targets", count);
}
void SpellMgr::LoadSpellPetAuras()
{
mSpellPetAuraMap.clear(); // need for reload case
uint32 count = 0;
// 0 1 2 3
QueryResult *result = WorldDatabase.Query("SELECT spell, effectId, pet, aura FROM spell_pet_auras");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> Loaded %u spell pet auras", count);
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 spell = fields[0].GetUInt32();
SpellEffectIndex eff = SpellEffectIndex(fields[1].GetUInt32());
uint32 pet = fields[2].GetUInt32();
uint32 aura = fields[3].GetUInt32();
if (eff >= MAX_EFFECT_INDEX)
{
sLog.outErrorDb("Spell %u listed in `spell_pet_auras` with wrong spell effect index (%u)", spell, eff);
continue;
}
SpellPetAuraMap::iterator itr = mSpellPetAuraMap.find((spell<<8) + eff);
if(itr != mSpellPetAuraMap.end())
{
itr->second.AddAura(pet, aura);
}
else
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
if (!spellInfo)
{
sLog.outErrorDb("Spell %u listed in `spell_pet_auras` does not exist", spell);
continue;
}
if (spellInfo->Effect[eff] != SPELL_EFFECT_DUMMY &&
(spellInfo->Effect[eff] != SPELL_EFFECT_APPLY_AURA ||
spellInfo->EffectApplyAuraName[eff] != SPELL_AURA_DUMMY))
{
sLog.outError("Spell %u listed in `spell_pet_auras` does not have dummy aura or dummy effect", spell);
continue;
}
SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(aura);
if (!spellInfo2)
{
sLog.outErrorDb("Aura %u listed in `spell_pet_auras` does not exist", aura);
continue;
}
PetAura pa(pet, aura, spellInfo->EffectImplicitTargetA[eff] == TARGET_PET, spellInfo->CalculateSimpleValue(eff));
mSpellPetAuraMap[(spell<<8) + eff] = pa;
}
++count;
} while( result->NextRow() );
delete result;
sLog.outString();
sLog.outString( ">> Loaded %u spell pet auras", count );
}
void SpellMgr::LoadPetLevelupSpellMap()
{
uint32 count = 0;
uint32 family_count = 0;
for (uint32 i = 0; i < sCreatureFamilyStore.GetNumRows(); ++i)
{
CreatureFamilyEntry const *creatureFamily = sCreatureFamilyStore.LookupEntry(i);
if(!creatureFamily) // not exist
continue;
for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
{
SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(j);
if( !skillLine )
continue;
if (skillLine->skillId!=creatureFamily->skillLine[0] &&
(!creatureFamily->skillLine[1] || skillLine->skillId!=creatureFamily->skillLine[1]))
continue;
if(skillLine->learnOnGetSkill != ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL)
continue;
SpellEntry const *spell = sSpellStore.LookupEntry(skillLine->spellId);
if(!spell) // not exist
continue;
PetLevelupSpellSet& spellSet = mPetLevelupSpellMap[creatureFamily->ID];
if(spellSet.empty())
++family_count;
spellSet.insert(PetLevelupSpellSet::value_type(spell->spellLevel,spell->Id));
count++;
}
}
sLog.outString();
sLog.outString( ">> Loaded %u pet levelup and default spells for %u families", count, family_count );
}
bool SpellMgr::LoadPetDefaultSpells_helper(CreatureInfo const* cInfo, PetDefaultSpellsEntry& petDefSpells)
{
// skip empty list;
bool have_spell = false;
for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
{
if(petDefSpells.spellid[j])
{
have_spell = true;
break;
}
}
if(!have_spell)
return false;
// remove duplicates with levelupSpells if any
if(PetLevelupSpellSet const *levelupSpells = cInfo->family ? GetPetLevelupSpellList(cInfo->family) : NULL)
{
for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
{
if(!petDefSpells.spellid[j])
continue;
for(PetLevelupSpellSet::const_iterator itr = levelupSpells->begin(); itr != levelupSpells->end(); ++itr)
{
if (itr->second == petDefSpells.spellid[j])
{
petDefSpells.spellid[j] = 0;
break;
}
}
}
}
// skip empty list;
have_spell = false;
for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
{
if(petDefSpells.spellid[j])
{
have_spell = true;
break;
}
}
return have_spell;
}
void SpellMgr::LoadPetDefaultSpells()
{
MANGOS_ASSERT(MAX_CREATURE_SPELL_DATA_SLOT==CREATURE_MAX_SPELLS);
mPetDefaultSpellsMap.clear();
uint32 countCreature = 0;
uint32 countData = 0;
for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i )
{
CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
if(!cInfo)
continue;
if(!cInfo->PetSpellDataId)
continue;
// for creature with PetSpellDataId get default pet spells from dbc
CreatureSpellDataEntry const* spellDataEntry = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
if(!spellDataEntry)
continue;
int32 petSpellsId = -(int32)cInfo->PetSpellDataId;
PetDefaultSpellsEntry petDefSpells;
for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
petDefSpells.spellid[j] = spellDataEntry->spellId[j];
if(LoadPetDefaultSpells_helper(cInfo, petDefSpells))
{
mPetDefaultSpellsMap[petSpellsId] = petDefSpells;
++countData;
}
}
// different summon spells
for(uint32 i = 0; i < sSpellStore.GetNumRows(); ++i )
{
SpellEntry const* spellEntry = sSpellStore.LookupEntry(i);
if(!spellEntry)
continue;
for(int k = 0; k < MAX_EFFECT_INDEX; ++k)
{
if(spellEntry->Effect[k]==SPELL_EFFECT_SUMMON || spellEntry->Effect[k]==SPELL_EFFECT_SUMMON_PET)
{
uint32 creature_id = spellEntry->EffectMiscValue[k];
CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(creature_id);
if(!cInfo)
continue;
// already loaded
if(cInfo->PetSpellDataId)
continue;
// for creature without PetSpellDataId get default pet spells from creature_template
int32 petSpellsId = cInfo->Entry;
if(mPetDefaultSpellsMap.find(cInfo->Entry) != mPetDefaultSpellsMap.end())
continue;
PetDefaultSpellsEntry petDefSpells;
for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
petDefSpells.spellid[j] = cInfo->spells[j];
if(LoadPetDefaultSpells_helper(cInfo, petDefSpells))
{
mPetDefaultSpellsMap[petSpellsId] = petDefSpells;
++countCreature;
}
}
}
}
sLog.outString();
sLog.outString( ">> Loaded addition spells for %u pet spell data entries and %u summonable creature templates", countData, countCreature );
}
/// Some checks for spells, to prevent adding deprecated/broken spells for trainers, spell book, etc
bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg)
{
// not exist
if(!spellInfo)
return false;
bool need_check_reagents = false;
// check effects
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
switch(spellInfo->Effect[i])
{
case 0:
continue;
// craft spell for crafting nonexistent item (break client recipes list show)
case SPELL_EFFECT_CREATE_ITEM:
case SPELL_EFFECT_CREATE_ITEM_2:
{
if (spellInfo->EffectItemType[i] == 0)
{
// skip auto-loot crafting spells, its not need explicit item info (but have special fake items sometime)
if (!IsLootCraftingSpell(spellInfo))
{
if(msg)
{
if(pl)
ChatHandler(pl).PSendSysMessage("Craft spell %u not have create item entry.",spellInfo->Id);
else
sLog.outErrorDb("Craft spell %u not have create item entry.",spellInfo->Id);
}
return false;
}
}
// also possible IsLootCraftingSpell case but fake item must exist anyway
else if (!ObjectMgr::GetItemPrototype( spellInfo->EffectItemType[i] ))
{
if(msg)
{
if(pl)
ChatHandler(pl).PSendSysMessage("Craft spell %u create item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellInfo->EffectItemType[i]);
else
sLog.outErrorDb("Craft spell %u create item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellInfo->EffectItemType[i]);
}
return false;
}
need_check_reagents = true;
break;
}
case SPELL_EFFECT_LEARN_SPELL:
{
SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(spellInfo->EffectTriggerSpell[i]);
if( !IsSpellValid(spellInfo2,pl,msg) )
{
if(msg)
{
if(pl)
ChatHandler(pl).PSendSysMessage("Spell %u learn to broken spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[i]);
else
sLog.outErrorDb("Spell %u learn to invalid spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[i]);
}
return false;
}
break;
}
}
}
if(need_check_reagents)
{
for(int j = 0; j < MAX_SPELL_REAGENTS; ++j)
{
if(spellInfo->Reagent[j] > 0 && !ObjectMgr::GetItemPrototype( spellInfo->Reagent[j] ))
{
if(msg)
{
if(pl)
ChatHandler(pl).PSendSysMessage("Craft spell %u requires reagent item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellInfo->Reagent[j]);
else
sLog.outErrorDb("Craft spell %u requires reagent item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellInfo->Reagent[j]);
}
return false;
}
}
}
return true;
}
void SpellMgr::LoadSpellAreas()
{
mSpellAreaMap.clear(); // need for reload case
mSpellAreaForQuestMap.clear();
mSpellAreaForActiveQuestMap.clear();
mSpellAreaForQuestEndMap.clear();
mSpellAreaForAuraMap.clear();
uint32 count = 0;
// 0 1 2 3 4 5 6 7 8
QueryResult *result = WorldDatabase.Query("SELECT spell, area, quest_start, quest_start_active, quest_end, aura_spell, racemask, gender, autocast FROM spell_area");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outString(">> Loaded %u spell area requirements", count);
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 spell = fields[0].GetUInt32();
SpellArea spellArea;
spellArea.spellId = spell;
spellArea.areaId = fields[1].GetUInt32();
spellArea.questStart = fields[2].GetUInt32();
spellArea.questStartCanActive = fields[3].GetBool();
spellArea.questEnd = fields[4].GetUInt32();
spellArea.auraSpell = fields[5].GetInt32();
spellArea.raceMask = fields[6].GetUInt32();
spellArea.gender = Gender(fields[7].GetUInt8());
spellArea.autocast = fields[8].GetBool();
if (!sSpellStore.LookupEntry(spell))
{
sLog.outErrorDb("Spell %u listed in `spell_area` does not exist", spell);
continue;
}
{
bool ok = true;
SpellAreaMapBounds sa_bounds = GetSpellAreaMapBounds(spellArea.spellId);
for (SpellAreaMap::const_iterator itr = sa_bounds.first; itr != sa_bounds.second; ++itr)
{
if (spellArea.spellId != itr->second.spellId)
continue;
if (spellArea.areaId != itr->second.areaId)
continue;
if (spellArea.questStart != itr->second.questStart)
continue;
if (spellArea.auraSpell != itr->second.auraSpell)
continue;
if ((spellArea.raceMask & itr->second.raceMask) == 0)
continue;
if (spellArea.gender != itr->second.gender)
continue;
// duplicate by requirements
ok =false;
break;
}
if (!ok)
{
sLog.outErrorDb("Spell %u listed in `spell_area` already listed with similar requirements.", spell);
continue;
}
}
if (spellArea.areaId && !GetAreaEntryByAreaID(spellArea.areaId))
{
sLog.outErrorDb("Spell %u listed in `spell_area` have wrong area (%u) requirement", spell,spellArea.areaId);
continue;
}
if (spellArea.questStart && !sObjectMgr.GetQuestTemplate(spellArea.questStart))
{
sLog.outErrorDb("Spell %u listed in `spell_area` have wrong start quest (%u) requirement", spell,spellArea.questStart);
continue;
}
if (spellArea.questEnd)
{
if (!sObjectMgr.GetQuestTemplate(spellArea.questEnd))
{
sLog.outErrorDb("Spell %u listed in `spell_area` have wrong end quest (%u) requirement", spell,spellArea.questEnd);
continue;
}
if (spellArea.questEnd==spellArea.questStart && !spellArea.questStartCanActive)
{
sLog.outErrorDb("Spell %u listed in `spell_area` have quest (%u) requirement for start and end in same time", spell,spellArea.questEnd);
continue;
}
}
if (spellArea.auraSpell)
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(abs(spellArea.auraSpell));
if (!spellInfo)
{
sLog.outErrorDb("Spell %u listed in `spell_area` have wrong aura spell (%u) requirement", spell,abs(spellArea.auraSpell));
continue;
}
switch (spellInfo->EffectApplyAuraName[EFFECT_INDEX_0])
{
case SPELL_AURA_DUMMY:
case SPELL_AURA_PHASE:
case SPELL_AURA_GHOST:
break;
default:
sLog.outErrorDb("Spell %u listed in `spell_area` have aura spell requirement (%u) without dummy/phase/ghost aura in effect 0", spell,abs(spellArea.auraSpell));
continue;
}
if (uint32(abs(spellArea.auraSpell))==spellArea.spellId)
{
sLog.outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement for itself", spell, abs(spellArea.auraSpell));
continue;
}
// not allow autocast chains by auraSpell field (but allow use as alternative if not present)
if (spellArea.autocast && spellArea.auraSpell > 0)
{
bool chain = false;
SpellAreaForAuraMapBounds saBound = GetSpellAreaForAuraMapBounds(spellArea.spellId);
for (SpellAreaForAuraMap::const_iterator itr = saBound.first; itr != saBound.second; ++itr)
{
if (itr->second->autocast && itr->second->auraSpell > 0)
{
chain = true;
break;
}
}
if (chain)
{
sLog.outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement that itself autocast from aura", spell,spellArea.auraSpell);
continue;
}
SpellAreaMapBounds saBound2 = GetSpellAreaMapBounds(spellArea.auraSpell);
for (SpellAreaMap::const_iterator itr2 = saBound2.first; itr2 != saBound2.second; ++itr2)
{
if (itr2->second.autocast && itr2->second.auraSpell > 0)
{
chain = true;
break;
}
}
if (chain)
{
sLog.outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement that itself autocast from aura", spell,spellArea.auraSpell);
continue;
}
}
}
if (spellArea.raceMask && (spellArea.raceMask & RACEMASK_ALL_PLAYABLE)==0)
{
sLog.outErrorDb("Spell %u listed in `spell_area` have wrong race mask (%u) requirement", spell,spellArea.raceMask);
continue;
}
if (spellArea.gender!=GENDER_NONE && spellArea.gender!=GENDER_FEMALE && spellArea.gender!=GENDER_MALE)
{
sLog.outErrorDb("Spell %u listed in `spell_area` have wrong gender (%u) requirement", spell,spellArea.gender);
continue;
}
SpellArea const* sa = &mSpellAreaMap.insert(SpellAreaMap::value_type(spell,spellArea))->second;
// for search by current zone/subzone at zone/subzone change
if (spellArea.areaId)
mSpellAreaForAreaMap.insert(SpellAreaForAreaMap::value_type(spellArea.areaId,sa));
// for search at quest start/reward
if (spellArea.questStart)
{
if (spellArea.questStartCanActive)
mSpellAreaForActiveQuestMap.insert(SpellAreaForQuestMap::value_type(spellArea.questStart,sa));
else
mSpellAreaForQuestMap.insert(SpellAreaForQuestMap::value_type(spellArea.questStart,sa));
}
// for search at quest start/reward
if (spellArea.questEnd)
mSpellAreaForQuestEndMap.insert(SpellAreaForQuestMap::value_type(spellArea.questEnd,sa));
// for search at aura apply
if (spellArea.auraSpell)
mSpellAreaForAuraMap.insert(SpellAreaForAuraMap::value_type(abs(spellArea.auraSpell),sa));
++count;
} while (result->NextRow());
delete result;
sLog.outString();
sLog.outString(">> Loaded %u spell area requirements", count);
}
SpellCastResult SpellMgr::GetSpellAllowedInLocationError(SpellEntry const *spellInfo, uint32 map_id, uint32 zone_id, uint32 area_id, Player const* player)
{
// normal case
int32 areaGroupId = spellInfo->AreaGroupId;
if (areaGroupId > 0)
{
bool found = false;
AreaGroupEntry const* groupEntry = sAreaGroupStore.LookupEntry(areaGroupId);
while (groupEntry)
{
for (uint32 i=0; i<6; ++i)
if (groupEntry->AreaId[i] == zone_id || groupEntry->AreaId[i] == area_id)
found = true;
if (found || !groupEntry->nextGroup)
break;
// Try search in next group
groupEntry = sAreaGroupStore.LookupEntry(groupEntry->nextGroup);
}
if (!found)
return SPELL_FAILED_INCORRECT_AREA;
}
// continent limitation (virtual continent), ignore for GM
if ((spellInfo->AttributesEx4 & SPELL_ATTR_EX4_CAST_ONLY_IN_OUTLAND) && !(player && player->isGameMaster()))
{
uint32 v_map = GetVirtualMapForMapAndZone(map_id, zone_id);
MapEntry const* mapEntry = sMapStore.LookupEntry(v_map);
if (!mapEntry || mapEntry->addon < 1 || !mapEntry->IsContinent())
return SPELL_FAILED_INCORRECT_AREA;
}
// raid instance limitation
if (spellInfo->AttributesEx6 & SPELL_ATTR_EX6_NOT_IN_RAID_INSTANCE)
{
MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
if (!mapEntry || mapEntry->IsRaid())
return SPELL_FAILED_NOT_IN_RAID_INSTANCE;
}
// DB base check (if non empty then must fit at least single for allow)
SpellAreaMapBounds saBounds = GetSpellAreaMapBounds(spellInfo->Id);
if (saBounds.first != saBounds.second)
{
for(SpellAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
{
if(itr->second.IsFitToRequirements(player,zone_id,area_id))
return SPELL_CAST_OK;
}
return SPELL_FAILED_INCORRECT_AREA;
}
// bg spell checks
// do not allow spells to be cast in arenas
// - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
// - with greater than 10 min CD
if ((spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
(GetSpellRecoveryTime(spellInfo) > 10 * MINUTE * IN_MILLISECONDS && !(spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA)))
if (player && player->InArena())
return SPELL_FAILED_NOT_IN_ARENA;
// Spell casted only on battleground
if ((spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND))
if (!player || !player->InBattleGround())
return SPELL_FAILED_ONLY_BATTLEGROUNDS;
switch(spellInfo->Id)
{
// a trinket in alterac valley allows to teleport to the boss
case 22564: // recall
case 22563: // recall
{
if (!player)
return SPELL_FAILED_REQUIRES_AREA;
BattleGround* bg = player->GetBattleGround();
return map_id == 30 && bg
&& bg->GetStatus() != STATUS_WAIT_JOIN ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
}
case 23333: // Warsong Flag
case 23335: // Silverwing Flag
return map_id == 489 && player && player->InBattleGround() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
case 34976: // Netherstorm Flag
return map_id == 566 && player && player->InBattleGround() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
case 2584: // Waiting to Resurrect
case 42792: // Recently Dropped Flag
case 43681: // Inactive
{
return player && player->InBattleGround() ? SPELL_CAST_OK : SPELL_FAILED_ONLY_BATTLEGROUNDS;
}
case 22011: // Spirit Heal Channel
case 22012: // Spirit Heal
case 24171: // Resurrection Impact Visual
case 44535: // Spirit Heal (mana)
{
MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
if (!mapEntry)
return SPELL_FAILED_INCORRECT_AREA;
return mapEntry->IsBattleGround()? SPELL_CAST_OK : SPELL_FAILED_ONLY_BATTLEGROUNDS;
}
case 44521: // Preparation
{
if (!player)
return SPELL_FAILED_REQUIRES_AREA;
BattleGround* bg = player->GetBattleGround();
return bg && bg->GetStatus()==STATUS_WAIT_JOIN ? SPELL_CAST_OK : SPELL_FAILED_ONLY_BATTLEGROUNDS;
}
case 32724: // Gold Team (Alliance)
case 32725: // Green Team (Alliance)
case 35774: // Gold Team (Horde)
case 35775: // Green Team (Horde)
{
return player && player->InArena() ? SPELL_CAST_OK : SPELL_FAILED_ONLY_IN_ARENA;
}
case 32727: // Arena Preparation
{
if (!player)
return SPELL_FAILED_REQUIRES_AREA;
if (!player->InArena())
return SPELL_FAILED_REQUIRES_AREA;
BattleGround* bg = player->GetBattleGround();
return bg && bg->GetStatus()==STATUS_WAIT_JOIN ? SPELL_CAST_OK : SPELL_FAILED_ONLY_IN_ARENA;
}
case 74410: // Arena - Dampening
return player && player->InArena() ? SPELL_CAST_OK : SPELL_FAILED_ONLY_IN_ARENA;
case 74411: // Battleground - Dampening
{
if (!player)
return SPELL_FAILED_ONLY_BATTLEGROUNDS;
BattleGround* bg = player->GetBattleGround();
return bg && !bg->isArena() ? SPELL_CAST_OK : SPELL_FAILED_ONLY_BATTLEGROUNDS;
}
}
return SPELL_CAST_OK;
}
void SpellMgr::LoadSkillLineAbilityMap()
{
mSkillLineAbilityMap.clear();
BarGoLink bar(sSkillLineAbilityStore.GetNumRows());
uint32 count = 0;
for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
{
bar.step();
SkillLineAbilityEntry const *SkillInfo = sSkillLineAbilityStore.LookupEntry(i);
if(!SkillInfo)
continue;
mSkillLineAbilityMap.insert(SkillLineAbilityMap::value_type(SkillInfo->spellId,SkillInfo));
++count;
}
sLog.outString();
sLog.outString(">> Loaded %u SkillLineAbility MultiMap Data", count);
}
void SpellMgr::LoadSkillRaceClassInfoMap()
{
mSkillRaceClassInfoMap.clear();
BarGoLink bar(sSkillRaceClassInfoStore.GetNumRows());
uint32 count = 0;
for (uint32 i = 0; i < sSkillRaceClassInfoStore.GetNumRows(); ++i)
{
bar.step();
SkillRaceClassInfoEntry const *skillRCInfo = sSkillRaceClassInfoStore.LookupEntry(i);
if (!skillRCInfo)
continue;
// not all skills really listed in ability skills list
if (!sSkillLineStore.LookupEntry(skillRCInfo->skillId))
continue;
mSkillRaceClassInfoMap.insert(SkillRaceClassInfoMap::value_type(skillRCInfo->skillId,skillRCInfo));
++count;
}
sLog.outString();
sLog.outString(">> Loaded %u SkillRaceClassInfo MultiMap Data", count);
}
void SpellMgr::CheckUsedSpells(char const* table)
{
uint32 countSpells = 0;
uint32 countMasks = 0;
// 0 1 2 3 4 5 6 7 8 9 10 11
QueryResult *result = WorldDatabase.PQuery("SELECT spellid,SpellFamilyName,SpellFamilyMaskA,SpellFamilyMaskB,SpellIcon,SpellVisual,SpellCategory,EffectType,EffectAura,EffectIdx,Name,Code FROM %s",table);
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString();
sLog.outErrorDb("`%s` table is empty!",table);
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 spell = fields[0].GetUInt32();
int32 family = fields[1].GetInt32();
uint64 familyMaskA = fields[2].GetUInt64();
uint32 familyMaskB = fields[3].GetUInt32();
int32 spellIcon = fields[4].GetInt32();
int32 spellVisual = fields[5].GetInt32();
int32 category = fields[6].GetInt32();
int32 effectType = fields[7].GetInt32();
int32 auraType = fields[8].GetInt32();
int32 effectIdx = fields[9].GetInt32();
std::string name = fields[10].GetCppString();
std::string code = fields[11].GetCppString();
// checks of correctness requirements itself
if (family < -1 || family > SPELLFAMILY_PET)
{
sLog.outError("Table '%s' for spell %u have wrong SpellFamily value(%u), skipped.",table,spell,family);
continue;
}
// TODO: spellIcon check need dbc loading
if (spellIcon < -1)
{
sLog.outError("Table '%s' for spell %u have wrong SpellIcon value(%u), skipped.",table,spell,spellIcon);
continue;
}
// TODO: spellVisual check need dbc loading
if (spellVisual < -1)
{
sLog.outError("Table '%s' for spell %u have wrong SpellVisual value(%u), skipped.",table,spell,spellVisual);
continue;
}
// TODO: for spellCategory better check need dbc loading
if (category < -1 || (category >=0 && sSpellCategoryStore.find(category) == sSpellCategoryStore.end()))
{
sLog.outError("Table '%s' for spell %u have wrong SpellCategory value(%u), skipped.",table,spell,category);
continue;
}
if (effectType < -1 || effectType >= TOTAL_SPELL_EFFECTS)
{
sLog.outError("Table '%s' for spell %u have wrong SpellEffect type value(%u), skipped.",table,spell,effectType);
continue;
}
if (auraType < -1 || auraType >= TOTAL_AURAS)
{
sLog.outError("Table '%s' for spell %u have wrong SpellAura type value(%u), skipped.",table,spell,auraType);
continue;
}
if (effectIdx < -1 || effectIdx >= 3)
{
sLog.outError("Table '%s' for spell %u have wrong EffectIdx value(%u), skipped.",table,spell,effectIdx);
continue;
}
// now checks of requirements
if(spell)
{
++countSpells;
SpellEntry const* spellEntry = sSpellStore.LookupEntry(spell);
if(!spellEntry)
{
sLog.outError("Spell %u '%s' not exist but used in %s.",spell,name.c_str(),code.c_str());
continue;
}
if (family >= 0 && spellEntry->SpellFamilyName != uint32(family))
{
sLog.outError("Spell %u '%s' family(%u) <> %u but used in %s.",spell,name.c_str(),spellEntry->SpellFamilyName,family,code.c_str());
continue;
}
if(familyMaskA != UI64LIT(0xFFFFFFFFFFFFFFFF) || familyMaskB != 0xFFFFFFFF)
{
if(familyMaskA == UI64LIT(0x0000000000000000) && familyMaskB == 0x00000000)
{
if (spellEntry->SpellFamilyFlags)
{
sLog.outError("Spell %u '%s' not fit to (" I64FMT "," I32FMT ") but used in %s.",
spell, name.c_str(), familyMaskA, familyMaskB, code.c_str());
continue;
}
}
else
{
if (!spellEntry->IsFitToFamilyMask(familyMaskA, familyMaskB))
{
sLog.outError("Spell %u '%s' not fit to (" I64FMT "," I32FMT ") but used in %s.",spell,name.c_str(),familyMaskA,familyMaskB,code.c_str());
continue;
}
}
}
if (spellIcon >= 0 && spellEntry->SpellIconID != uint32(spellIcon))
{
sLog.outError("Spell %u '%s' icon(%u) <> %u but used in %s.",spell,name.c_str(),spellEntry->SpellIconID,spellIcon,code.c_str());
continue;
}
if (spellVisual >= 0 && spellEntry->SpellVisual[0] != uint32(spellVisual))
{
sLog.outError("Spell %u '%s' visual(%u) <> %u but used in %s.",spell,name.c_str(),spellEntry->SpellVisual[0],spellVisual,code.c_str());
continue;
}
if (category >= 0 && spellEntry->Category != uint32(category))
{
sLog.outError("Spell %u '%s' category(%u) <> %u but used in %s.",spell,name.c_str(),spellEntry->Category,category,code.c_str());
continue;
}
if (effectIdx >= EFFECT_INDEX_0)
{
if (effectType >= 0 && spellEntry->Effect[effectIdx] != uint32(effectType))
{
sLog.outError("Spell %u '%s' effect%d <> %u but used in %s.",spell,name.c_str(),effectIdx+1,effectType,code.c_str());
continue;
}
if (auraType >= 0 && spellEntry->EffectApplyAuraName[effectIdx] != uint32(auraType))
{
sLog.outError("Spell %u '%s' aura%d <> %u but used in %s.",spell,name.c_str(),effectIdx+1,auraType,code.c_str());
continue;
}
}
else
{
if (effectType >= 0 && !IsSpellHaveEffect(spellEntry,SpellEffects(effectType)))
{
sLog.outError("Spell %u '%s' not have effect %u but used in %s.",spell,name.c_str(),effectType,code.c_str());
continue;
}
if (auraType >= 0 && !IsSpellHaveAura(spellEntry, AuraType(auraType)))
{
sLog.outError("Spell %u '%s' not have aura %u but used in %s.",spell,name.c_str(),auraType,code.c_str());
continue;
}
}
}
else
{
++countMasks;
bool found = false;
for(uint32 spellId = 1; spellId < sSpellStore.GetNumRows(); ++spellId)
{
SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellId);
if (!spellEntry)
continue;
if (family >=0 && spellEntry->SpellFamilyName != uint32(family))
continue;
if (familyMaskA != UI64LIT(0xFFFFFFFFFFFFFFFF) || familyMaskB != 0xFFFFFFFF)
{
if(familyMaskA == UI64LIT(0x0000000000000000) && familyMaskB == 0x00000000)
{
if (spellEntry->SpellFamilyFlags)
continue;
}
else
{
if (!spellEntry->IsFitToFamilyMask(familyMaskA, familyMaskB))
continue;
}
}
if (spellIcon >= 0 && spellEntry->SpellIconID != uint32(spellIcon))
continue;
if (spellVisual >= 0 && spellEntry->SpellVisual[0] != uint32(spellVisual))
continue;
if (category >= 0 && spellEntry->Category != uint32(category))
continue;
if (effectIdx >= 0)
{
if (effectType >=0 && spellEntry->Effect[effectIdx] != uint32(effectType))
continue;
if (auraType >=0 && spellEntry->EffectApplyAuraName[effectIdx] != uint32(auraType))
continue;
}
else
{
if (effectType >=0 && !IsSpellHaveEffect(spellEntry,SpellEffects(effectType)))
continue;
if (auraType >=0 && !IsSpellHaveAura(spellEntry,AuraType(auraType)))
continue;
}
found = true;
break;
}
if (!found)
{
if (effectIdx >= 0)
sLog.outError("Spells '%s' not found for family %i (" I64FMT "," I32FMT ") icon(%i) visual(%i) category(%i) effect%d(%i) aura%d(%i) but used in %s",
name.c_str(),family,familyMaskA,familyMaskB,spellIcon,spellVisual,category,effectIdx+1,effectType,effectIdx+1,auraType,code.c_str());
else
sLog.outError("Spells '%s' not found for family %i (" I64FMT "," I32FMT ") icon(%i) visual(%i) category(%i) effect(%i) aura(%i) but used in %s",
name.c_str(),family,familyMaskA,familyMaskB,spellIcon,spellVisual,category,effectType,auraType,code.c_str());
continue;
}
}
} while( result->NextRow() );
delete result;
sLog.outString();
sLog.outString( ">> Checked %u spells and %u spell masks", countSpells, countMasks );
}
DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellEntry const* spellproto, bool triggered)
{
// Explicit Diminishing Groups
switch(spellproto->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
// some generic arena related spells have by some strange reason MECHANIC_TURN
if (spellproto->Mechanic == MECHANIC_TURN)
return DIMINISHING_NONE;
break;
case SPELLFAMILY_MAGE:
// Dragon's Breath
if (spellproto->SpellIconID == 1548)
return DIMINISHING_DISORIENT;
break;
case SPELLFAMILY_ROGUE:
{
// Blind
if (spellproto->IsFitToFamilyMask(UI64LIT(0x00001000000)))
return DIMINISHING_FEAR_CHARM_BLIND;
// Cheap Shot
else if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000000400)))
return DIMINISHING_CHEAPSHOT_POUNCE;
// Crippling poison - Limit to 10 seconds in PvP (No SpellFamilyFlags)
else if (spellproto->SpellIconID == 163)
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_HUNTER:
{
// Freezing Trap & Freezing Arrow & Wyvern Sting
if (spellproto->SpellIconID == 180 || spellproto->SpellIconID == 1721)
return DIMINISHING_DISORIENT;
break;
}
case SPELLFAMILY_WARLOCK:
{
// Curses/etc
if (spellproto->IsFitToFamilyMask(UI64LIT(0x00080000000)))
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_PALADIN:
{
// Judgement of Justice - Limit to 10 seconds in PvP
if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000100000)))
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_DRUID:
{
// Cyclone
if (spellproto->IsFitToFamilyMask(UI64LIT(0x02000000000)))
return DIMINISHING_CYCLONE;
// Pounce
else if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000020000)))
return DIMINISHING_CHEAPSHOT_POUNCE;
// Faerie Fire
else if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000000400)))
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_WARRIOR:
{
// Hamstring - limit duration to 10s in PvP
if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000000002)))
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_PRIEST:
{
// Shackle Undead
if (spellproto->SpellIconID == 27)
return DIMINISHING_DISORIENT;
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Hungering Cold (no flags)
if (spellproto->SpellIconID == 2797)
return DIMINISHING_DISORIENT;
break;
}
default:
break;
}
// Get by mechanic
uint32 mechanic = GetAllSpellMechanicMask(spellproto);
if (!mechanic)
return DIMINISHING_NONE;
if (mechanic & ((1<<(MECHANIC_STUN-1))|(1<<(MECHANIC_SHACKLE-1))))
return triggered ? DIMINISHING_TRIGGER_STUN : DIMINISHING_CONTROL_STUN;
if (mechanic & ((1<<(MECHANIC_SLEEP-1))|(1<<(MECHANIC_FREEZE-1))))
return DIMINISHING_FREEZE_SLEEP;
if (mechanic & ((1<<(MECHANIC_KNOCKOUT-1))|(1<<(MECHANIC_POLYMORPH-1))|(1<<(MECHANIC_SAPPED-1))))
return DIMINISHING_DISORIENT;
if (mechanic & (1<<(MECHANIC_ROOT-1)))
return triggered ? DIMINISHING_TRIGGER_ROOT : DIMINISHING_CONTROL_ROOT;
if (mechanic & ((1<<(MECHANIC_FEAR-1))|(1<<(MECHANIC_CHARM-1))|(1<<(MECHANIC_TURN-1))))
return DIMINISHING_FEAR_CHARM_BLIND;
if (mechanic & ((1<<(MECHANIC_SILENCE-1))|(1<<(MECHANIC_INTERRUPT-1))))
return DIMINISHING_SILENCE;
if (mechanic & (1<<(MECHANIC_DISARM-1)))
return DIMINISHING_DISARM;
if (mechanic & (1<<(MECHANIC_BANISH-1)))
return DIMINISHING_BANISH;
if (mechanic & (1<<(MECHANIC_HORROR-1)))
return DIMINISHING_HORROR;
return DIMINISHING_NONE;
}
int32 GetDiminishingReturnsLimitDuration(DiminishingGroup group, SpellEntry const* spellproto)
{
if(!IsDiminishingReturnsGroupDurationLimited(group))
return 0;
// Explicit diminishing duration
switch(spellproto->SpellFamilyName)
{
case SPELLFAMILY_HUNTER:
{
// Wyvern Sting
if (spellproto->SpellFamilyFlags & UI64LIT(0x0000100000000000))
return 6000;
break;
}
case SPELLFAMILY_PALADIN:
{
// Repentance - limit to 6 seconds in PvP
if (spellproto->SpellFamilyFlags & UI64LIT(0x00000000004))
return 6000;
break;
}
case SPELLFAMILY_DRUID:
{
// Faerie Fire - limit to 40 seconds in PvP (3.1)
if (spellproto->SpellFamilyFlags & UI64LIT(0x00000000400))
return 40000;
break;
}
default:
break;
}
return 10000;
}
bool IsDiminishingReturnsGroupDurationLimited(DiminishingGroup group)
{
switch(group)
{
case DIMINISHING_CONTROL_STUN:
case DIMINISHING_TRIGGER_STUN:
case DIMINISHING_CONTROL_ROOT:
case DIMINISHING_TRIGGER_ROOT:
case DIMINISHING_FEAR_CHARM_BLIND:
case DIMINISHING_DISORIENT:
case DIMINISHING_CHEAPSHOT_POUNCE:
case DIMINISHING_FREEZE_SLEEP:
case DIMINISHING_CYCLONE:
case DIMINISHING_BANISH:
case DIMINISHING_LIMITONLY:
return true;
default:
return false;
}
return false;
}
DiminishingReturnsType GetDiminishingReturnsGroupType(DiminishingGroup group)
{
switch(group)
{
case DIMINISHING_CYCLONE:
case DIMINISHING_TRIGGER_STUN:
case DIMINISHING_CONTROL_STUN:
return DRTYPE_ALL;
case DIMINISHING_CONTROL_ROOT:
case DIMINISHING_TRIGGER_ROOT:
case DIMINISHING_FEAR_CHARM_BLIND:
case DIMINISHING_DISORIENT:
case DIMINISHING_SILENCE:
case DIMINISHING_DISARM:
case DIMINISHING_HORROR:
case DIMINISHING_FREEZE_SLEEP:
case DIMINISHING_BANISH:
case DIMINISHING_CHEAPSHOT_POUNCE:
return DRTYPE_PLAYER;
default:
break;
}
return DRTYPE_NONE;
}
bool SpellArea::IsFitToRequirements(Player const* player, uint32 newZone, uint32 newArea) const
{
if(gender!=GENDER_NONE)
{
// not in expected gender
if(!player || gender != player->getGender())
return false;
}
if(raceMask)
{
// not in expected race
if(!player || !(raceMask & player->getRaceMask()))
return false;
}
if(areaId)
{
// not in expected zone
if(newZone!=areaId && newArea!=areaId)
return false;
}
if(questStart)
{
// not in expected required quest state
if(!player || (!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart))
return false;
}
if(questEnd)
{
// not in expected forbidden quest state
if(!player || player->GetQuestRewardStatus(questEnd))
return false;
}
if(auraSpell)
{
// not have expected aura
if(!player)
return false;
if(auraSpell > 0)
// have expected aura
return player->HasAura(auraSpell, EFFECT_INDEX_0);
else
// not have expected aura
return !player->HasAura(-auraSpell, EFFECT_INDEX_0);
}
return true;
}
SpellEntry const* GetSpellEntryByDifficulty(uint32 id, Difficulty difficulty, bool isRaid)
{
SpellDifficultyEntry const* spellDiff = sSpellDifficultyStore.LookupEntry(id);
if (!spellDiff)
return NULL;
for (Difficulty diff = difficulty; diff >= REGULAR_DIFFICULTY; diff = GetPrevDifficulty(diff, isRaid))
{
if (spellDiff->spellId[diff])
return sSpellStore.LookupEntry(spellDiff->spellId[diff]);
}
return NULL;
}
| fgenesis/mangos | src/game/SpellMgr.cpp | C++ | gpl-2.0 | 188,760 |
package mattparks.mods.space.venus.entities;
import mattparks.mods.space.venus.items.GCVenusItems;
import micdoodle8.mods.galacticraft.api.entity.IEntityBreathable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntitySmallFireball;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class GCVenusEntityEvolvedBlaze extends EntityMob implements IEntityBreathable
{
private float heightOffset = 0.5F;
private int heightOffsetUpdateTime;
private int field_70846_g;
public GCVenusEntityEvolvedBlaze(World par1World)
{
super(par1World);
this.isImmuneToFire = true;
this.experienceValue = 10;
}
@Override
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setAttribute(6.0D);
}
@Override
protected void attackEntity(Entity par1Entity, float par2)
{
if (this.attackTime <= 0 && par2 < 2.0F && par1Entity.boundingBox.maxY > this.boundingBox.minY && par1Entity.boundingBox.minY < this.boundingBox.maxY)
{
this.attackTime = 20;
this.attackEntityAsMob(par1Entity);
}
else if (par2 < 30.0F)
{
double d0 = par1Entity.posX - this.posX;
double d1 = par1Entity.boundingBox.minY + par1Entity.height / 2.0F - (this.posY + this.height / 2.0F);
double d2 = par1Entity.posZ - this.posZ;
if (this.attackTime == 0)
{
++this.field_70846_g;
if (this.field_70846_g == 1)
{
this.attackTime = 60;
this.func_70844_e(true);
}
else if (this.field_70846_g <= 4)
{
this.attackTime = 6;
}
else
{
this.attackTime = 100;
this.field_70846_g = 0;
this.func_70844_e(false);
}
if (this.field_70846_g > 1)
{
float f1 = MathHelper.sqrt_float(par2) * 0.5F;
this.worldObj.playAuxSFXAtEntity((EntityPlayer)null, 1009, (int)this.posX, (int)this.posY, (int)this.posZ, 0);
for (int i = 0; i < 1; ++i)
{
EntitySmallFireball entitysmallfireball = new EntitySmallFireball(this.worldObj, this, d0 + this.rand.nextGaussian() * f1, d1, d2 + this.rand.nextGaussian() * f1);
entitysmallfireball.posY = this.posY + this.height / 2.0F + 0.5D;
this.worldObj.spawnEntityInWorld(entitysmallfireball);
}
}
}
this.rotationYaw = (float)(Math.atan2(d2, d0) * 180.0D / Math.PI) - 90.0F;
this.hasAttacked = true;
}
}
@Override
public boolean canBreath()
{
return true;
}
@Override
protected void dropFewItems(boolean par1, int par2)
{
if (par1)
{
int j = this.rand.nextInt(2 + par2);
for (int k = 0; k < j; ++k)
{
this.dropItem(GCVenusItems.venusRod.itemID, 1);
}
}
}
@Override
protected void entityInit()
{
super.entityInit();
this.dataWatcher.addObject(16, new Byte((byte)0));
}
@Override
protected void fall(float par1) {}
public void func_70844_e(boolean par1)
{
byte b0 = this.dataWatcher.getWatchableObjectByte(16);
if (par1)
{
b0 = (byte)(b0 | 1);
}
else
{
b0 &= -2;
}
this.dataWatcher.updateObject(16, Byte.valueOf(b0));
}
public boolean func_70845_n()
{
return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0;
}
@Override
public float getBrightness(float par1)
{
return 1.0F;
}
@Override
@SideOnly(Side.CLIENT)
public int getBrightnessForRender(float par1)
{
return 15728880;
}
@Override
protected String getDeathSound()
{
return "mob.blaze.death";
}
@Override
protected int getDropItemId()
{
return GCVenusItems.venusRod.itemID;
}
@Override
protected String getHurtSound()
{
return "mob.blaze.hit";
}
@Override
protected String getLivingSound()
{
return "mob.blaze.breathe";
}
@Override
public boolean isBurning()
{
return this.func_70845_n();
}
@Override
protected boolean isValidLightLevel()
{
return true;
}
@Override
public void onLivingUpdate()
{
if (!this.worldObj.isRemote)
{
if (this.isWet())
{
this.attackEntityFrom(DamageSource.drown, 1.0F);
}
--this.heightOffsetUpdateTime;
if (this.heightOffsetUpdateTime <= 0)
{
this.heightOffsetUpdateTime = 100;
this.heightOffset = 0.5F + (float)this.rand.nextGaussian() * 3.0F;
}
if (this.getEntityToAttack() != null && this.getEntityToAttack().posY + this.getEntityToAttack().getEyeHeight() > this.posY + this.getEyeHeight() + this.heightOffset)
{
this.motionY += (0.30000001192092896D - this.motionY) * 0.30000001192092896D;
}
}
if (this.rand.nextInt(24) == 0)
{
this.worldObj.playSoundEffect(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.fire", 1.0F + this.rand.nextFloat(), this.rand.nextFloat() * 0.7F + 0.3F);
}
if (!this.onGround && this.motionY < 0.0D)
{
this.motionY *= 0.6D;
}
for (int i = 0; i < 2; ++i)
{
this.worldObj.spawnParticle("largesmoke", this.posX + (this.rand.nextDouble() - 0.5D) * this.width, this.posY + this.rand.nextDouble() * this.height, this.posZ + (this.rand.nextDouble() - 0.5D) * this.width, 0.0D, 0.0D, 0.0D);
}
super.onLivingUpdate();
}
}
| 4Space/4-Space-1.6.4 | common/mattparks/mods/space/venus/entities/GCVenusEntityEvolvedBlaze.java | Java | gpl-2.0 | 6,459 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest15221")
public class BenchmarkTest15221 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getHeader("foo");
String bar = doSomething(param);
try {
float rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextFloat();
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextFloat() - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextFloat() executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar = "safe!";
java.util.HashMap<String,Object> map33682 = new java.util.HashMap<String,Object>();
map33682.put("keyA-33682", "a_Value"); // put some stuff in the collection
map33682.put("keyB-33682", param.toString()); // put it in a collection
map33682.put("keyC", "another_Value"); // put some stuff in the collection
bar = (String)map33682.get("keyB-33682"); // get it back out
bar = (String)map33682.get("keyA-33682"); // get safe value back out
return bar;
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest15221.java | Java | gpl-2.0 | 2,564 |
<?php
require_once dirname(__FILE__) . '/Reviews.php';
class Sabai_Addon_Directory_Controller_UserReviews extends Sabai_Addon_Directory_Controller_Reviews
{
protected function _createQuery(Sabai_Context $context, $sort, Sabai_Addon_Entity_Model_Bundle $bundle = null)
{
return parent::_createQuery($context, $sort, $bundle)
->propertyIs('post_user_id', $context->identity->id);
}
} | ssxenon01/mm | resources/plugins/sabai-directory/lib/Directory/Controller/UserReviews.php | PHP | gpl-2.0 | 418 |
/*
* 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
*/
/*
* ServerMessenger.java
*
* Created on December 11, 2001, 7:43 PM
*/
package games.strategy.net;
import games.strategy.engine.chat.ChatController;
import games.strategy.engine.chat.IChatChannel;
import games.strategy.engine.lobby.server.login.LobbyLoginValidator;
import games.strategy.engine.lobby.server.userDB.MutedIpController;
import games.strategy.engine.lobby.server.userDB.MutedMacController;
import games.strategy.engine.lobby.server.userDB.MutedUsernameController;
import games.strategy.engine.message.HubInvoke;
import games.strategy.engine.message.RemoteMethodCall;
import games.strategy.engine.message.RemoteName;
import games.strategy.engine.message.SpokeInvoke;
import games.strategy.net.nio.NIOSocket;
import games.strategy.net.nio.NIOSocketListener;
import games.strategy.net.nio.QuarantineConversation;
import games.strategy.net.nio.ServerQuarantineConversation;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A Messenger that can have many clients connected to it.
*
* @author Sean Bridges
* @version 1.0
*/
public class ServerMessenger implements IServerMessenger, NIOSocketListener
{
private static Logger s_logger = Logger.getLogger(ServerMessenger.class.getName());
private final Selector m_acceptorSelector;
private final ServerSocketChannel m_socketChannel;
private final Node m_node;
private boolean m_shutdown = false;
private final NIOSocket m_nioSocket;
private final CopyOnWriteArrayList<IMessageListener> m_listeners = new CopyOnWriteArrayList<IMessageListener>();
private final CopyOnWriteArrayList<IMessengerErrorListener> m_errorListeners = new CopyOnWriteArrayList<IMessengerErrorListener>();
private final CopyOnWriteArrayList<IConnectionChangeListener> m_connectionListeners = new CopyOnWriteArrayList<IConnectionChangeListener>();
private boolean m_acceptNewConnection = false;
private ILoginValidator m_loginValidator;
// all our nodes
private final ConcurrentHashMap<INode, SocketChannel> m_nodeToChannel = new ConcurrentHashMap<INode, SocketChannel>();
private final ConcurrentHashMap<SocketChannel, INode> m_channelToNode = new ConcurrentHashMap<SocketChannel, INode>();
// A hack, till I think of something better
public ServerMessenger(final String name, final int portNumber, final IObjectStreamFactory streamFactory) throws IOException
{
m_socketChannel = ServerSocketChannel.open();
m_socketChannel.configureBlocking(false);
m_socketChannel.socket().setReuseAddress(true);
m_socketChannel.socket().bind(new InetSocketAddress(portNumber), 10);
m_nioSocket = new NIOSocket(streamFactory, this, "Server");
m_acceptorSelector = Selector.open();
if (IPFinder.findInetAddress() != null)
m_node = new Node(name, IPFinder.findInetAddress(), portNumber);
else
m_node = new Node(name, InetAddress.getLocalHost(), portNumber);
final Thread t = new Thread(new ConnectionHandler(), "Server Messenger Connection Handler");
t.start();
}
public void setLoginValidator(final ILoginValidator loginValidator)
{
m_loginValidator = loginValidator;
}
public ILoginValidator getLoginValidator()
{
return m_loginValidator;
}
/** Creates new ServerMessenger */
public ServerMessenger(final String name, final int portNumber) throws IOException
{
this(name, portNumber, new DefaultObjectStreamFactory());
}
/*
* @see IMessenger#addMessageListener(Class, IMessageListener)
*/
public void addMessageListener(final IMessageListener listener)
{
m_listeners.add(listener);
}
/*
* @see IMessenger#removeMessageListener(Class, IMessageListener)
*/
public void removeMessageListener(final IMessageListener listener)
{
m_listeners.remove(listener);
}
/**
* Get a list of nodes.
*/
public Set<INode> getNodes()
{
final Set<INode> rVal = new HashSet<INode>(m_nodeToChannel.keySet());
rVal.add(m_node);
return rVal;
}
public synchronized void shutDown()
{
if (!m_shutdown)
{
m_shutdown = true;
m_nioSocket.shutDown();
try
{
m_socketChannel.close();
} catch (final Exception e)
{
// ignore
}
if (m_acceptorSelector != null)
m_acceptorSelector.wakeup();
}
}
public synchronized boolean isShutDown()
{
return m_shutdown;
}
public boolean isConnected()
{
return !m_shutdown;
}
/**
* Send a message to the given node.
*/
public void send(final Serializable msg, final INode to)
{
if (m_shutdown)
return;
if (s_logger.isLoggable(Level.FINEST))
{
s_logger.log(Level.FINEST, "Sending" + msg + " to:" + to);
}
final MessageHeader header = new MessageHeader(to, m_node, msg);
final SocketChannel socketChannel = m_nodeToChannel.get(to);
// the socket was removed
if (socketChannel == null)
{
if (s_logger.isLoggable(Level.FINER))
{
s_logger.log(Level.FINER, "no channel for node:" + to + " dropping message:" + msg);
}
// the socket has not been added yet
return;
}
m_nioSocket.send(socketChannel, header);
}
/**
* Send a message to all nodes.
*/
public void broadcast(final Serializable msg)
{
final MessageHeader header = new MessageHeader(m_node, msg);
forwardBroadcast(header);
}
private boolean isLobby()
{
return m_loginValidator instanceof LobbyLoginValidator;
}
private boolean isGame()
{
return !isLobby();
}
private final Object m_cachedListLock = new Object();
private final HashMap<String, String> m_cachedMacAddresses = new HashMap<String, String>();
public String GetPlayerMac(final String name)
{
synchronized (m_cachedListLock)
{
String mac = m_cachedMacAddresses.get(name);
if (mac == null)
mac = m_playersThatLeftMacs_Last10.get(name);
return mac;
}
}
// We need to cache whether players are muted, because otherwise the database would have to be accessed each time a message was sent, which can be very slow
private final List<String> m_liveMutedUsernames = new ArrayList<String>();
public boolean IsUsernameMuted(final String username)
{
synchronized (m_cachedListLock)
{
return m_liveMutedUsernames.contains(username);
}
}
public void NotifyUsernameMutingOfPlayer(final String username, final Date muteExpires)
{
synchronized (m_cachedListLock)
{
if (!m_liveMutedUsernames.contains(username))
m_liveMutedUsernames.add(username);
if (muteExpires != null)
ScheduleUsernameUnmuteAt(username, muteExpires.getTime());
}
}
private final List<String> m_liveMutedIpAddresses = new ArrayList<String>();
public boolean IsIpMuted(final String ip)
{
synchronized (m_cachedListLock)
{
return m_liveMutedIpAddresses.contains(ip);
}
}
public void NotifyIPMutingOfPlayer(final String ip, final Date muteExpires)
{
synchronized (m_cachedListLock)
{
if (!m_liveMutedIpAddresses.contains(ip))
m_liveMutedIpAddresses.add(ip);
if (muteExpires != null)
ScheduleIpUnmuteAt(ip, muteExpires.getTime());
}
}
private final List<String> m_liveMutedMacAddresses = new ArrayList<String>();
public boolean IsMacMuted(final String mac)
{
synchronized (m_cachedListLock)
{
return m_liveMutedMacAddresses.contains(mac);
}
}
public void NotifyMacMutingOfPlayer(final String mac, final Date muteExpires)
{
synchronized (m_cachedListLock)
{
if (!m_liveMutedMacAddresses.contains(mac))
m_liveMutedMacAddresses.add(mac);
if (muteExpires != null)
ScheduleMacUnmuteAt(mac, muteExpires.getTime());
}
}
private void ScheduleUsernameUnmuteAt(final String username, final long checkTime)
{
final Timer unmuteUsernameTimer = new Timer("Username unmute timer");
unmuteUsernameTimer.schedule(GetUsernameUnmuteTask(username), new Date(checkTime));
}
private void ScheduleIpUnmuteAt(final String ip, final long checkTime)
{
final Timer unmuteIpTimer = new Timer("IP unmute timer");
unmuteIpTimer.schedule(GetIpUnmuteTask(ip), new Date(checkTime));
}
private void ScheduleMacUnmuteAt(final String mac, final long checkTime)
{
final Timer unmuteMacTimer = new Timer("Mac unmute timer");
unmuteMacTimer.schedule(GetMacUnmuteTask(mac), new Date(checkTime));
}
public void NotifyPlayerLogin(final String uniquePlayerName, final String ip, final String mac)
{
synchronized (m_cachedListLock)
{
m_cachedMacAddresses.put(uniquePlayerName, mac);
if (isLobby())
{
final String realName = uniquePlayerName.split(" ")[0];
if (!m_liveMutedUsernames.contains(realName))
{
final long muteTill = new MutedUsernameController().getUsernameUnmuteTime(realName);
if (muteTill != -1 && muteTill <= System.currentTimeMillis())
{
m_liveMutedUsernames.add(realName); // Signal the player as muted
ScheduleUsernameUnmuteAt(realName, muteTill);
}
}
if (!m_liveMutedIpAddresses.contains(ip))
{
final long muteTill = new MutedIpController().getIpUnmuteTime(ip);
if (muteTill != -1 && muteTill <= System.currentTimeMillis())
{
m_liveMutedIpAddresses.add(ip); // Signal the player as muted
ScheduleIpUnmuteAt(ip, muteTill);
}
}
if (!m_liveMutedMacAddresses.contains(mac))
{
final long muteTill = new MutedMacController().getMacUnmuteTime(mac);
if (muteTill != -1 && muteTill <= System.currentTimeMillis())
{
m_liveMutedMacAddresses.add(mac); // Signal the player as muted
ScheduleMacUnmuteAt(mac, muteTill);
}
}
}
}
}
private final HashMap<String, String> m_playersThatLeftMacs_Last10 = new HashMap<String, String>();
public HashMap<String, String> GetPlayersThatLeftMacs_Last10()
{
return m_playersThatLeftMacs_Last10;
}
private void NotifyPlayerRemoval(final INode node)
{
synchronized (m_cachedListLock)
{
m_playersThatLeftMacs_Last10.put(node.getName(), m_cachedMacAddresses.get(node.getName()));
if (m_playersThatLeftMacs_Last10.size() > 10)
m_playersThatLeftMacs_Last10.remove(m_playersThatLeftMacs_Last10.entrySet().iterator().next().toString());
m_cachedMacAddresses.remove(node.getName());
}
}
public static final String YOU_HAVE_BEEN_MUTED_LOBBY = "?YOUR LOBBY CHATTING HAS BEEN TEMPORARILY 'MUTED' BY THE ADMINS, TRY AGAIN LATER"; // Special character to stop spoofing by server
public static final String YOU_HAVE_BEEN_MUTED_GAME = "?YOUR CHATTING IN THIS GAME HAS BEEN 'MUTED' BY THE HOST"; // Special character to stop spoofing by host
public void messageReceived(final MessageHeader msg, final SocketChannel channel)
{
final INode expectedReceive = m_channelToNode.get(channel);
if (!expectedReceive.equals(msg.getFrom()))
{
throw new IllegalStateException("Expected: " + expectedReceive + " not: " + msg.getFrom());
}
if (msg.getMessage() instanceof HubInvoke) // Chat messages are always HubInvoke's
{
if (isLobby() && ((HubInvoke) msg.getMessage()).call.getRemoteName().equals("_ChatCtrl_LOBBY_CHAT"))
{
final String realName = msg.getFrom().getName().split(" ")[0];
if (IsUsernameMuted(realName))
{
bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_LOBBY, msg.getFrom());
return;
}
else if (IsIpMuted(msg.getFrom().getAddress().getHostAddress()))
{
bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_LOBBY, msg.getFrom());
return;
}
else if (IsMacMuted(GetPlayerMac(msg.getFrom().getName())))
{
bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_LOBBY, msg.getFrom());
return;
}
}
else if (isGame() && ((HubInvoke) msg.getMessage()).call.getRemoteName().equals("_ChatCtrlgames.strategy.engine.framework.ui.ServerStartup.CHAT_NAME"))
{
final String realName = msg.getFrom().getName().split(" ")[0];
if (IsUsernameMuted(realName))
{
bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_GAME, msg.getFrom());
return;
}
else if (IsIpMuted(msg.getFrom().getAddress().getHostAddress()))
{
bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_GAME, msg.getFrom());
return;
}
if (IsMacMuted(GetPlayerMac(msg.getFrom().getName())))
{
bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_GAME, msg.getFrom());
return;
}
}
}
if (msg.getFor() == null)
{
forwardBroadcast(msg);
notifyListeners(msg);
}
else if (msg.getFor().equals(m_node))
{
notifyListeners(msg);
}
else
{
forward(msg);
}
}
private void bareBonesSendChatMessage(final String message, final INode to)
{
final List<Object> args = new ArrayList<Object>();
final Class[] argTypes = new Class[1];
args.add(message);
argTypes[0] = args.get(0).getClass();
RemoteName rn;
if (isLobby())
rn = new RemoteName(ChatController.getChatChannelName("_LOBBY_CHAT"), IChatChannel.class);
else
rn = new RemoteName(ChatController.getChatChannelName("games.strategy.engine.framework.ui.ServerStartup.CHAT_NAME"), IChatChannel.class);
final RemoteMethodCall call = new RemoteMethodCall(rn.getName(), "chatOccured", args.toArray(), argTypes, rn.getClazz());
final SpokeInvoke spokeInvoke = new SpokeInvoke(null, false, call, getServerNode());
send(spokeInvoke, to);
}
// The following code is used in hosted lobby games by the host for player mini-banning and mini-muting
private final List<String> m_miniBannedUsernames = new ArrayList<String>();
public boolean IsUsernameMiniBanned(final String username)
{
synchronized (m_cachedListLock)
{
return m_miniBannedUsernames.contains(username);
}
}
public void NotifyUsernameMiniBanningOfPlayer(final String username, final Date expires)
{
synchronized (m_cachedListLock)
{
if (!m_miniBannedUsernames.contains(username))
m_miniBannedUsernames.add(username);
if (expires != null)
{
final Timer unbanUsernameTimer = new Timer("Username unban timer");
unbanUsernameTimer.schedule(new TimerTask()
{
@Override
public void run()
{
synchronized (m_cachedListLock)
{
m_miniBannedUsernames.remove(username);
}
}
}, new Date(expires.getTime()));
}
}
}
private final List<String> m_miniBannedIpAddresses = new ArrayList<String>();
public boolean IsIpMiniBanned(final String ip)
{
synchronized (m_cachedListLock)
{
return m_miniBannedIpAddresses.contains(ip);
}
}
public void NotifyIPMiniBanningOfPlayer(final String ip, final Date expires)
{
synchronized (m_cachedListLock)
{
if (!m_miniBannedIpAddresses.contains(ip))
m_miniBannedIpAddresses.add(ip);
if (expires != null)
{
final Timer unbanIpTimer = new Timer("IP unban timer");
unbanIpTimer.schedule(new TimerTask()
{
@Override
public void run()
{
synchronized (m_cachedListLock)
{
m_miniBannedIpAddresses.remove(ip);
}
}
}, new Date(expires.getTime()));
}
}
}
private final List<String> m_miniBannedMacAddresses = new ArrayList<String>();
public boolean IsMacMiniBanned(final String mac)
{
synchronized (m_cachedListLock)
{
return m_miniBannedMacAddresses.contains(mac);
}
}
public void NotifyMacMiniBanningOfPlayer(final String mac, final Date expires)
{
synchronized (m_cachedListLock)
{
if (!m_miniBannedMacAddresses.contains(mac))
m_miniBannedMacAddresses.add(mac);
if (expires != null)
{
final Timer unbanMacTimer = new Timer("Mac unban timer");
unbanMacTimer.schedule(new TimerTask()
{
@Override
public void run()
{
synchronized (m_cachedListLock)
{
m_miniBannedMacAddresses.remove(mac);
}
}
}, new Date(expires.getTime()));
}
}
}
private void forward(final MessageHeader msg)
{
if (m_shutdown)
return;
final SocketChannel socketChannel = m_nodeToChannel.get(msg.getFor());
if (socketChannel == null)
throw new IllegalStateException("No channel for:" + msg.getFor() + " all channels:" + socketChannel);
m_nioSocket.send(socketChannel, msg);
}
private void forwardBroadcast(final MessageHeader msg)
{
if (m_shutdown)
return;
final SocketChannel fromChannel = m_nodeToChannel.get(msg.getFrom());
final List<SocketChannel> nodes = new ArrayList<SocketChannel>(m_nodeToChannel.values());
if (s_logger.isLoggable(Level.FINEST))
{
s_logger.log(Level.FINEST, "broadcasting to" + nodes);
}
for (final SocketChannel channel : nodes)
{
if (channel != fromChannel)
m_nioSocket.send(channel, msg);
}
}
private boolean isNameTaken(final String nodeName)
{
for (final INode node : getNodes())
{
if (node.getName().equalsIgnoreCase(nodeName))
return true;
}
return false;
}
public String getUniqueName(String currentName)
{
if (currentName.length() > 50)
{
currentName = currentName.substring(0, 50);
}
if (currentName.length() < 2)
{
currentName = "aa" + currentName;
}
synchronized (m_node)
{
if (isNameTaken(currentName))
{
int i = 1;
while (true)
{
final String newName = currentName + " (" + i + ")";
if (!isNameTaken(newName))
{
currentName = newName;
break;
}
i++;
}
}
}
return currentName;
}
private void notifyListeners(final MessageHeader msg)
{
final Iterator<IMessageListener> iter = m_listeners.iterator();
while (iter.hasNext())
{
final IMessageListener listener = iter.next();
listener.messageReceived(msg.getMessage(), msg.getFrom());
}
}
public void addErrorListener(final IMessengerErrorListener listener)
{
m_errorListeners.add(listener);
}
public void removeErrorListener(final IMessengerErrorListener listener)
{
m_errorListeners.remove(listener);
}
public void addConnectionChangeListener(final IConnectionChangeListener listener)
{
m_connectionListeners.add(listener);
}
public void removeConnectionChangeListener(final IConnectionChangeListener listener)
{
m_connectionListeners.remove(listener);
}
private void notifyConnectionsChanged(final boolean added, final INode node)
{
final Iterator<IConnectionChangeListener> iter = m_connectionListeners.iterator();
while (iter.hasNext())
{
if (added)
{
iter.next().connectionAdded(node);
}
else
{
iter.next().connectionRemoved(node);
}
}
}
public void setAcceptNewConnections(final boolean accept)
{
m_acceptNewConnection = accept;
}
public boolean isAcceptNewConnections()
{
return m_acceptNewConnection;
}
/**
* Get the local node
*/
public INode getLocalNode()
{
return m_node;
}
private class ConnectionHandler implements Runnable
{
public void run()
{
try
{
m_socketChannel.register(m_acceptorSelector, SelectionKey.OP_ACCEPT);
} catch (final ClosedChannelException e)
{
s_logger.log(Level.SEVERE, "socket closed", e);
shutDown();
}
while (!m_shutdown)
{
try
{
m_acceptorSelector.select();
} catch (final IOException e)
{
s_logger.log(Level.SEVERE, "Could not accept on server", e);
shutDown();
}
if (m_shutdown)
continue;
final Set<SelectionKey> keys = m_acceptorSelector.selectedKeys();
final Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext())
{
final SelectionKey key = iter.next();
iter.remove();
if (key.isAcceptable() && key.isValid())
{
final ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
// Accept the connection and make it non-blocking
SocketChannel socketChannel = null;
try
{
socketChannel = serverSocketChannel.accept();
if (socketChannel == null)
{
continue;
}
socketChannel.configureBlocking(false);
socketChannel.socket().setKeepAlive(true);
} catch (final IOException e)
{
s_logger.log(Level.FINE, "Could not accept channel", e);
try
{
if (socketChannel != null)
socketChannel.close();
} catch (final IOException e2)
{
s_logger.log(Level.FINE, "Could not close channel", e2);
}
continue;
}
// we are not accepting connections
if (!m_acceptNewConnection)
{
try
{
socketChannel.close();
} catch (final IOException e)
{
s_logger.log(Level.FINE, "Could not close channel", e);
}
continue;
}
final ServerQuarantineConversation conversation = new ServerQuarantineConversation(m_loginValidator, socketChannel, m_nioSocket, ServerMessenger.this);
m_nioSocket.add(socketChannel, conversation);
}
else if (!key.isValid())
{
key.cancel();
}
}
}
}
}
private TimerTask GetUsernameUnmuteTask(final String username)
{
return new TimerTask()
{
@Override
public void run()
{ // lobby has a database we need to check, normal hosted games do not
if ((isLobby() && new MutedUsernameController().getUsernameUnmuteTime(username) == -1) || (isGame())) // If the mute has expired
{
synchronized (m_cachedListLock)
{
m_liveMutedUsernames.remove(username); // Remove the username from the list of live username's muted
}
}
}
};
}
private TimerTask GetIpUnmuteTask(final String ip)
{
return new TimerTask()
{
@Override
public void run()
{ // lobby has a database we need to check, normal hosted games do not
if ((isLobby() && new MutedIpController().getIpUnmuteTime(ip) == -1) || (isGame())) // If the mute has expired
{
synchronized (m_cachedListLock)
{
m_liveMutedIpAddresses.remove(ip); // Remove the ip from the list of live ip's muted
}
}
}
};
}
private TimerTask GetMacUnmuteTask(final String mac)
{
return new TimerTask()
{
@Override
public void run()
{ // lobby has a database we need to check, normal hosted games do not
if ((isLobby() && new MutedMacController().getMacUnmuteTime(mac) == -1) || (isGame())) // If the mute has expired
{
synchronized (m_cachedListLock)
{
m_liveMutedMacAddresses.remove(mac); // Remove the mac from the list of live mac's muted
}
}
}
};
}
public boolean isServer()
{
return true;
}
public void removeConnection(final INode node)
{
if (node.equals(m_node))
throw new IllegalArgumentException("Cant remove ourself!");
NotifyPlayerRemoval(node);
SocketChannel channel = m_nodeToChannel.remove(node);
if (channel == null)
{
channel = m_nodeToChannel.remove(node);
}
if (channel == null)
{
s_logger.info("Could not remove connection to node:" + node);
return;
}
m_channelToNode.remove(channel);
m_nioSocket.close(channel);
notifyConnectionsChanged(false, node);
s_logger.info("Connection removed:" + node);
}
public INode getServerNode()
{
return m_node;
}
public void socketError(final SocketChannel channel, final Exception error)
{
if (channel == null)
throw new IllegalArgumentException("Null channel");
// already closed, dont report it again
final INode node = m_channelToNode.get(channel);
if (node != null)
removeConnection(node);
}
public void socketUnqaurantined(final SocketChannel channel, final QuarantineConversation conversation)
{
final ServerQuarantineConversation con = (ServerQuarantineConversation) conversation;
final INode remote = new Node(con.getRemoteName(), (InetSocketAddress) channel.socket().getRemoteSocketAddress());
if (s_logger.isLoggable(Level.FINER))
{
s_logger.log(Level.FINER, "Unquarntined node:" + remote);
}
m_nodeToChannel.put(remote, channel);
m_channelToNode.put(channel, remote);
notifyConnectionsChanged(true, remote);
s_logger.info("Connection added to:" + remote);
}
public INode getRemoteNode(final SocketChannel channel)
{
return m_channelToNode.get(channel);
}
public InetSocketAddress getRemoteServerSocketAddress()
{
return m_node.getSocketAddress();
}
@Override
public String toString()
{
return "ServerMessenger LocalNode:" + m_node + " ClientNodes:" + m_nodeToChannel.keySet();
}
}
| tea-dragon/triplea | src/main/java/games/strategy/net/ServerMessenger.java | Java | gpl-2.0 | 25,312 |
// This file is part of Agros2D.
//
// Agros2D 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.
//
// Agros2D 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 Agros2D. If not, see <http://www.gnu.org/licenses/>.
//
// hp-FEM group (http://hpfem.org/)
// University of Nevada, Reno (UNR) and University of West Bohemia, Pilsen
// Email: agros2d@googlegroups.com, home page: http://hpfem.org/agros2d/
#include "localvalueview.h"
#include "scene.h"
LocalPointValue::LocalPointValue(Point &point)
{
this->point = point;
PointValue val = pointValue(Util::scene()->sceneSolution()->sln(), point);
value = val.value;
derivative = val.derivative;
labelMarker = val.marker;
}
PointValue LocalPointValue::pointValue(Solution *sln, Point &point)
{
double tmpValue;
Point tmpDerivative;
SceneLabelMarker *tmpLabelMarker = NULL;
if (sln)
{
int index = Util::scene()->sceneSolution()->findTriangleInMesh(Util::scene()->sceneSolution()->meshInitial(), point);
if (index != -1)
{
if ((Util::scene()->problemInfo()->analysisType == AnalysisType_Transient) &&
Util::scene()->sceneSolution()->timeStep() == 0)
// const solution at first time step
tmpValue = Util::scene()->problemInfo()->initialCondition.number;
else
tmpValue = sln->get_pt_value(point.x, point.y, H2D_FN_VAL_0);
if (Util::scene()->problemInfo()->physicField() != PhysicField_Elasticity)
{
tmpDerivative.x = sln->get_pt_value(point.x, point.y, H2D_FN_DX_0);
tmpDerivative.y = sln->get_pt_value(point.x, point.y, H2D_FN_DY_0);
}
// find marker
Element *element = Util::scene()->sceneSolution()->meshInitial()->get_element_fast(index);
tmpLabelMarker = Util::scene()->labels[element->marker]->marker;
}
}
return PointValue(tmpValue, tmpDerivative, tmpLabelMarker);
}
// *************************************************************************************************************************************
LocalPointValueView::LocalPointValueView(QWidget *parent): QDockWidget(tr("Local Values"), parent)
{
QSettings settings;
setMinimumWidth(280);
setObjectName("LocalPointValueView");
createActions();
createMenu();
trvWidget = new QTreeWidget();
trvWidget->setHeaderHidden(false);
trvWidget->setContextMenuPolicy(Qt::CustomContextMenu);
trvWidget->setMouseTracking(true);
trvWidget->setColumnCount(3);
trvWidget->setColumnWidth(0, settings.value("LocalPointValueView/TreeViewColumn0", 150).value<int>());
trvWidget->setColumnWidth(1, settings.value("LocalPointValueView/TreeViewColumn1", 80).value<int>());
trvWidget->setIndentation(12);
QStringList labels;
labels << tr("Label") << tr("Value") << tr("Unit");
trvWidget->setHeaderLabels(labels);
connect(trvWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(doContextMenu(const QPoint &)));
QPushButton *btnPoint = new QPushButton();
btnPoint->setText(actPoint->text());
btnPoint->setIcon(actPoint->icon());
btnPoint->setMaximumSize(btnPoint->sizeHint());
connect(btnPoint, SIGNAL(clicked()), this, SLOT(doPoint()));
// main widget
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(trvWidget);
layout->addWidget(btnPoint);
layout->setContentsMargins(0, 0, 0, 7);
QWidget *widget = new QWidget(this);
widget->setLayout(layout);
setWidget(widget);
}
LocalPointValueView::~LocalPointValueView()
{
QSettings settings;
settings.setValue("LocalPointValueView/TreeViewColumn0", trvWidget->columnWidth(0));
settings.setValue("LocalPointValueView/TreeViewColumn1", trvWidget->columnWidth(1));
}
void LocalPointValueView::createActions()
{
// point
actPoint = new QAction(icon("scene-node"), tr("Local point value"), this);
connect(actPoint, SIGNAL(triggered()), this, SLOT(doPoint()));
// copy value
actCopy = new QAction(icon(""), tr("Copy value"), this);
connect(actCopy, SIGNAL(triggered()), this, SLOT(doCopyValue()));
}
void LocalPointValueView::createMenu()
{
mnuInfo = new QMenu(this);
mnuInfo->addAction(actPoint);
mnuInfo->addAction(actCopy);
}
void LocalPointValueView::doPoint()
{
LocalPointValueDialog localPointValueDialog(point);
if (localPointValueDialog.exec() == QDialog::Accepted)
{
doShowPoint(localPointValueDialog.point());
}
}
void LocalPointValueView::doContextMenu(const QPoint &pos)
{
actCopy->setEnabled(false);
QTreeWidgetItem *item = trvWidget->itemAt(pos);
if (item)
if (!item->text(1).isEmpty())
{
trvWidget->setCurrentItem(item);
actCopy->setEnabled(true);
}
mnuInfo->exec(QCursor::pos());
}
void LocalPointValueView::doShowPoint(const Point &point)
{
// store point
this->point = point;
doShowPoint();
}
void LocalPointValueView::doCopyValue()
{
QTreeWidgetItem *item = trvWidget->currentItem();
if (item)
if (!item->text(1).isEmpty())
QApplication::clipboard()->setText(item->text(1));
}
void LocalPointValueView::doShowPoint()
{
trvWidget->clear();
// point
QTreeWidgetItem *pointNode = new QTreeWidgetItem(trvWidget);
pointNode->setText(0, tr("Point"));
pointNode->setExpanded(true);
addTreeWidgetItemValue(pointNode, Util::scene()->problemInfo()->labelX() + ":", QString("%1").arg(point.x, 0, 'f', 5), tr("m"));
addTreeWidgetItemValue(pointNode, Util::scene()->problemInfo()->labelY() + ":", QString("%1").arg(point.y, 0, 'f', 5), tr("m"));
trvWidget->insertTopLevelItem(0, pointNode);
if (Util::scene()->sceneSolution()->isSolved())
Util::scene()->problemInfo()->hermes()->showLocalValue(trvWidget, Util::scene()->problemInfo()->hermes()->localPointValue(point));
trvWidget->resizeColumnToContents(2);
}
LocalPointValueDialog::LocalPointValueDialog(Point point, QWidget *parent) : QDialog(parent)
{
setWindowIcon(icon("scene-node"));
setWindowTitle(tr("Local point value"));
setModal(true);
txtPointX = new SLineEditValue();
txtPointX->setNumber(point.x);
txtPointY = new SLineEditValue();
txtPointY->setNumber(point.y);
connect(txtPointX, SIGNAL(evaluated(bool)), this, SLOT(evaluated(bool)));
connect(txtPointY, SIGNAL(evaluated(bool)), this, SLOT(evaluated(bool)));
QFormLayout *layoutPoint = new QFormLayout();
layoutPoint->addRow(Util::scene()->problemInfo()->labelX() + " (m):", txtPointX);
layoutPoint->addRow(Util::scene()->problemInfo()->labelY() + " (m):", txtPointY);
// dialog buttons
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
QVBoxLayout *layout = new QVBoxLayout();
layout->addLayout(layoutPoint);
layout->addStretch();
layout->addWidget(buttonBox);
setLayout(layout);
setMinimumSize(sizeHint());
setMaximumSize(sizeHint());
}
LocalPointValueDialog::~LocalPointValueDialog()
{
delete txtPointX;
delete txtPointY;
}
Point LocalPointValueDialog::point()
{
return Point(txtPointX->value().number, txtPointY->value().number);
}
void LocalPointValueDialog::evaluated(bool isError)
{
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!isError);
}
| panek50/agros2d | src/localvalueview.cpp | C++ | gpl-2.0 | 8,032 |
#!/usr/bin/env python
# Copyright (C) 2007--2016 the X-ray Polarimetry Explorer (XPE) team.
#
# For the license terms see the file LICENSE, distributed along with this
# software.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import struct
import numpy
import os
import logging as logger
# python2/3 compatibility fix
try:
xrange
except NameError:
xrange = range
# color core fror creen printout, work only on posix
class ixpeAnsiColors:
HEADER = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#
# Useful constants
#
XPOL_NUM_COLUMNS = 300
XPOL_NUM_ROWS = 352
XPOL_NUM_PIXELS = XPOL_NUM_COLUMNS*XPOL_NUM_ROWS
#
# Class for a windowed event
#
class ixpeEventWindowed:
"""Basic class representing an event aquired in windowed mode.
"""
HEADER_MARKER = 65535
HEADER_LENGTH = 20
def __init__(self, xmin, xmax, ymin, ymax, buffer_id, t1, t2, s1, s2,
adc_values):
"""Constructor.
"""
self.xmin = xmin
self.xmax = xmax
self.ymin = ymin
self.ymax = ymax
self.buffer_id = buffer_id
self.microseconds = (t1 + t2*65534)*0.8
self.adc_values = adc_values
def size(self):
"""Return the total number of bytes in the event.
"""
return self.HEADER_LENGTH + 2*self.num_pixels()
def num_columns(self):
"""Return the number of columns.
"""
return (self.xmax - self.xmin + 1)
def num_rows(self):
"""Return the number of rows.
"""
return (self.ymax - self.ymin + 1)
def num_pixels(self):
"""Return the total number of pixels in the window.
"""
return self.num_rows()*self.num_columns()
def adc_value(self, col, row):
"""Return the pulse height for a given pixel in the window.
"""
return self.adc_values[col, row]
def highest_pixel(self):
"""Return the coordinats of the pixel with the maximum value of
ADC counts.
"""
return numpy.unravel_index(numpy.argmax(self.adc_values),
self.adc_values.shape)
def highest_adc_value(self):
"""Return the maximum value of ADC counts for the pixels in the event.
"""
return self.adc_values.max()
def ascii(self, zero_suppression=5, max_threshold=0.75, width=4,
color=True):
"""Return a pretty-printed ASCII representation of the event.
"""
if os.name != 'posix':
color = False
_fmt = '%%%dd' % width
_max = self.highest_adc_value()
text = ''
text += ' '*(2*width + 2)
for col in xrange(self.num_columns()):
text += _fmt % (col + self.xmin)
text += '\n'
text += ' '*(2*width + 2)
for col in xrange(self.num_columns()):
text += _fmt % col
text += '\n'
text += ' '*(2*width + 1) + '+' + '-'*(width*self.num_columns()) + '\n'
for row in xrange(self.num_rows()):
text += (_fmt % (row + self.ymin)) + ' ' + (_fmt % row) + '|'
for col in xrange(self.num_columns()):
adc = self.adc_value(col, row)
pix = _fmt % adc
if color and adc == _max:
pix = '%s%s%s' %\
(ixpeAnsiColors.RED, pix, ixpeAnsiColors.ENDC)
elif color and adc >= max_threshold*_max:
pix = '%s%s%s' %\
(ixpeAnsiColors.YELLOW, pix, ixpeAnsiColors.ENDC)
elif color and adc > zero_suppression:
pix = '%s%s%s' %\
(ixpeAnsiColors.GREEN, pix, ixpeAnsiColors.ENDC)
text += pix
text += '\n%s|\n' % (' '*(2*width + 1))
return text
def draw_ascii(self, zero_suppression=5):
"""Print the ASCII representation of the event.
"""
print(self.ascii(zero_suppression))
def __str__(self):
"""String representation.
"""
text = 'buffer %5d, w(%3d, %3d)--(%3d, %3d), %d px, t = %d us' %\
(self.buffer_id, self.xmin, self.ymin, self.xmax, self.ymax,
self.num_pixels(), self.microseconds)
return text
#
# Class for a windowed file
#
class ixpeBinaryFileWindowed:
"""Binary file acquired in windowed mode.
"""
def __init__(self, filePath):
"""Constructor.
"""
logger.info('Opening input binary file %s...' % filePath)
self.__file = open(filePath, 'rb')
def seek(self, offset):
""" redefine seek
"""
self.__file.seek(offset)
def read(self, n):
""" redefine read
"""
return self.__file.read(n)
def close(self):
""" redefine
"""
self.__file.close()
def read_word(self):
"""Read and byte-swap a single 2-bytes binary word from file.
Note that struct.unpack returns a tuple even when we read a single
number, and here we're returning the first (and only) element of the
tuple.
"""
return struct.unpack('H', self.read(2))[0]
def read_words(self, num_words):
"""Read and byte-swap a fixed number of 2-bytes binary words from file.
Args
----
num_words : int
The number of words to be read from the input file.
"""
return struct.unpack('%dH' % num_words, self.read(2*num_words))
def read_adc_word(self):
"""Read and byte-swap a single 2-bytes binary word from file.
Same as read word, but adc value are now signed
"""
return struct.unpack('h', self.read(2))[0]
def read_adc_words(self, num_words):
"""Read and byte-swap a fixed number of 2-bytes binary words from file.
Same as read_words, but adc values are now signed.
Args
----
num_words : int
The number of words to be read from the input file.
"""
return struct.unpack('%dh' % num_words, self.read(2*num_words))
def __iter__(self):
"""Basic iterator implementation.
"""
return self
def next(self):
"""Read the next event in the file.
"""
try:
header = self.read_word()
except Exception:
raise StopIteration()
if header != ixpeEventWindowed.HEADER_MARKER:
msg = 'Event header mismatch at byte %d' % self.tell()
msg += ' (expected %s, got %s).' %\
(hex(ixpeEventWindowed.HEADER_MARKER), hex(header))
logger.error(msg)
logger.info('Moving ahead to the next event header...')
while header != ixpeEventWindowed.HEADER_MARKER:
header = self.read_word()
logger.info('Got back in synch at byte %d.' % self.tell())
xmin, xmax, ymin, ymax, buf_id, t1, t2, s1, s2 = self.read_words(9)
num_columns = (xmax - xmin + 1)
num_rows = (ymax - ymin + 1)
data = self.read_adc_words(num_rows*num_columns)
adc = numpy.array(data).reshape((num_rows, num_columns)).T
return ixpeEventWindowed(xmin, xmax, ymin, ymax, buf_id, t1, t2, s1, s2,
adc)
if __name__ == '__main__':
import argparse
formatter = argparse.ArgumentDefaultsHelpFormatter
parser = argparse.ArgumentParser(formatter_class=formatter)
parser.add_argument('infile', type=str,
help='the input binary file')
parser.add_argument('-n', '--num_events', type=int, default=10,
help = 'number of events to be processed')
args = parser.parse_args()
#test_windowed
input_file = ixpeBinaryFileWindowed(args.infile)
for i in xrange(args.num_events):
event = input_file.next()
print (event)
event.draw_ascii()
try:
input("e2g")
except NameError:
raw_input("e2g")
| lucabaldini/xpedaq | scripts/ixpe_evt_lib.py | Python | gpl-2.0 | 7,540 |
/**
* Copyright (c) 2014 Igor Botian
*
* 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
*
* @author Igor Botian <igor.botian@gmail.com>
*/
package ru.spbftu.igorbotian.phdapp.common.impl;
import ru.spbftu.igorbotian.phdapp.common.*;
import java.util.Objects;
import java.util.Set;
/**
* @see ru.spbftu.igorbotian.phdapp.common.impl.AbstractInputDataImpl
* @see ru.spbftu.igorbotian.phdapp.common.PointwiseInputData
* @see ru.spbftu.igorbotian.phdapp.common.InputDataFactory
*/
class PointwiseInputDataImpl extends AbstractInputDataImpl implements PointwiseInputData {
private final PointwiseTrainingSet trainingSet;
public PointwiseInputDataImpl(UnclassifiedData testingSet, PointwiseTrainingSet trainingSet)
throws DataException {
super(testingSet);
this.trainingSet = Objects.requireNonNull(trainingSet);
}
public Set<? extends PointwiseTrainingObject> trainingSet() {
return trainingSet.objects();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), trainingSet);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || !(obj instanceof PointwiseInputDataImpl)) {
return false;
}
PointwiseInputDataImpl other = (PointwiseInputDataImpl) obj;
return super.equals(other) && trainingSet.equals(other.trainingSet);
}
@Override
public String toString() {
return String.join(";", super.toString(), trainingSet.toString());
}
}
| igorbotian/phdapp | input/src/main/java/ru/spbftu/igorbotian/phdapp/common/impl/PointwiseInputDataImpl.java | Java | gpl-2.0 | 2,247 |
using System.Collections.Generic;
using System.IO;
using System.Timers;
namespace DevWilson
{
internal class ImageList : List<ImageFileAttributes>
{
private readonly string filePath;
private readonly object syncRoot = new object();
private Timer saveTimer;
public ImageList(string filePath)
{
this.filePath = filePath;
}
public void Load()
{
if (File.Exists(filePath))
{
lock (syncRoot)
{
if (saveTimer != null)
{
saveTimer.Stop();
saveTimer = null;
}
ImageListToXml.LoadFromXml(filePath, this);
}
}
}
public void Save()
{
lock (syncRoot)
{
if (saveTimer == null || !saveTimer.Enabled)
{
saveTimer = new Timer(5000);
saveTimer.Elapsed += saveTimer_Elapsed;
saveTimer.AutoReset = false;
saveTimer.Start();
}
}
}
public List<ImageFileAttributes> Clone()
{
lock (syncRoot)
{
return new List<ImageFileAttributes>(this);
}
}
private void saveTimer_Elapsed(object sender, ElapsedEventArgs e)
{
string folderPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
lock (syncRoot)
{
ImageListToXml.SaveAsXml(filePath, this);
}
}
}
} | abmv/MetaComic | MetaComics.Client/Code/PDF/PDFImageWorks/ImageList.cs | C# | gpl-2.0 | 1,807 |
<?php
// src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php
namespace FL\CoreBundle\Tests\Utility;
use FL\CoreBundle\Utility\Calculator;
class CalculatorTest extends \PHPUnit_Framework_TestCase
{
public function testAdd()
{
$calc = new Calculator();
$result = $calc->add(30, 12);
// vérifie que votre classe a correctement calculé!
$this->assertEquals(42, $result);
}
} | flabastie/memoword | src/FL/CoreBundle/Tests/Utility/CalculatorTest.php | PHP | gpl-2.0 | 421 |
showWord(["pr.","Lan, anndan. Ti moun yo t ap jwe nan dlo a."
]) | georgejhunt/HaitiDictionary.activity | data/words/nan.js | JavaScript | gpl-2.0 | 64 |
/***************************************************************************
tag: FMTC Tue Mar 11 21:49:27 CET 2008 DataFlowInterface.cpp
DataFlowInterface.cpp - description
-------------------
begin : Tue March 11 2008
copyright : (C) 2008 FMTC
email : peter.soetens@fmtc.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; *
* version 2 of the License. *
* *
* As a special exception, you may use this file as part of a free *
* software library without restriction. Specifically, if other files *
* instantiate templates or use macros or inline functions from this *
* file, or you compile this file and link it with other files to *
* produce an executable, this file does not by itself cause the *
* resulting executable to be covered by the GNU General Public *
* License. This exception does not however invalidate any other *
* reasons why the executable file might be covered by the GNU General *
* Public License. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
#include "DataFlowInterface.hpp"
#include "Logger.hpp"
#include "Service.hpp"
#include "TaskContext.hpp"
namespace RTT
{
using namespace detail;
DataFlowInterface::DataFlowInterface(Service* parent /* = 0 */)
: mservice(parent)
{}
DataFlowInterface::~DataFlowInterface() {
}
TaskContext* DataFlowInterface::getOwner() const {
return mservice ? mservice->getOwner() : 0;
}
PortInterface& DataFlowInterface::addPort(PortInterface& port) {
if ( !chkPtr("addPort", "PortInterface", &port) ) return port;
this->addLocalPort(port);
if (mservice && mservice->hasService( port.getName()) != 0) {
log(Warning) <<"'addPort' "<< port.getName() << ": name already in use as Service. Replacing previous service with new one." <<endlog();
mservice->removeService(port.getName());
}
if (!mservice) {
log(Warning) <<"'addPort' "<< port.getName() << ": DataFlowInterface not given to parent. Not adding Service." <<endlog();
return port;
}
Service::shared_ptr ms( this->createPortObject( port.getName()) );
if ( ms )
mservice->addService( ms );
// END NOTE.
return port;
}
PortInterface& DataFlowInterface::addLocalPort(PortInterface& port) {
for ( Ports::iterator it(mports.begin());
it != mports.end();
++it)
if ( (*it)->getName() == port.getName() ) {
log(Warning) <<"'addPort' "<< port.getName() << ": name already in use. Disconnecting and replacing previous port with new one." <<endlog();
removePort( port.getName() );
break;
}
mports.push_back( &port );
port.setInterface( this );
return port;
}
InputPortInterface& DataFlowInterface::addEventPort(InputPortInterface& port, SlotFunction callback) {
if ( !chkPtr("addEventPort", "PortInterface", &port) ) return port;
this->addLocalEventPort(port, callback);
if (mservice && mservice->hasService( port.getName()) != 0) {
log(Warning) <<"'addPort' "<< port.getName() << ": name already in use as Service. Replacing previous service with new one." <<endlog();
mservice->removeService(port.getName());
}
if (!mservice) {
log(Warning) <<"'addPort' "<< port.getName() << ": DataFlowInterface not given to parent. Not adding Service." <<endlog();
return port;
}
Service::shared_ptr ms( this->createPortObject( port.getName()) );
if ( ms )
mservice->addService( ms );
return port;
}
#ifdef ORO_SIGNALLING_PORTS
void DataFlowInterface::setupHandles() {
for_each(handles.begin(), handles.end(), boost::bind(&Handle::connect, _1));
}
void DataFlowInterface::cleanupHandles() {
for_each(handles.begin(), handles.end(), boost::bind(&Handle::disconnect, _1));
}
#else
void DataFlowInterface::dataOnPort(base::PortInterface* port)
{
if ( mservice && mservice->getOwner() )
mservice->getOwner()->dataOnPort(port);
}
#endif
InputPortInterface& DataFlowInterface::addLocalEventPort(InputPortInterface& port, SlotFunction callback) {
this->addLocalPort(port);
if (mservice == 0 || mservice->getOwner() == 0) {
log(Error) << "addLocalEventPort "<< port.getName() <<": DataFlowInterface not part of a TaskContext. Will not trigger any TaskContext nor register callback." <<endlog();
return port;
}
if (callback)
mservice->getOwner()->dataOnPortCallback(&port,callback); // the handle will be deleted when the port is removed.
port.signalInterface(true);
return port;
}
void DataFlowInterface::removePort(const std::string& name) {
for ( Ports::iterator it(mports.begin());
it != mports.end();
++it)
if ( (*it)->getName() == name ) {
if (mservice) {
mservice->removeService( name );
if (mservice->getOwner())
mservice->getOwner()->dataOnPortRemoved( *it );
}
(*it)->disconnect(); // remove all connections and callbacks.
mports.erase(it);
return;
}
}
DataFlowInterface::Ports DataFlowInterface::getPorts() const {
return mports;
}
DataFlowInterface::PortNames DataFlowInterface::getPortNames() const {
std::vector<std::string> res;
for ( Ports::const_iterator it(mports.begin());
it != mports.end();
++it)
res.push_back( (*it)->getName() );
return res;
}
PortInterface* DataFlowInterface::getPort(const std::string& name) const {
for ( Ports::const_iterator it(mports.begin());
it != mports.end();
++it)
if ( (*it)->getName() == name )
return *it;
return 0;
}
std::string DataFlowInterface::getPortDescription(const std::string& name) const {
for ( Ports::const_iterator it(mports.begin());
it != mports.end();
++it)
if ( (*it)->getName() == name )
return (*it)->getDescription();
return "";
}
bool DataFlowInterface::setPortDescription(const std::string& name, const std::string description) {
Service::shared_ptr srv = mservice->getService(name);
if (srv) {
srv->doc(description);
return true;
}
return false;
}
Service* DataFlowInterface::createPortObject(const std::string& name) {
PortInterface* p = this->getPort(name);
if ( !p )
return 0;
Service* to = p->createPortObject();
if (to) {
std::string d = this->getPortDescription(name);
if ( !d.empty() )
to->doc( d );
else
to->doc("No description set for this Port. Use .doc() to document it.");
}
return to;
}
void DataFlowInterface::clear()
{
// remove TaskObjects:
for ( Ports::iterator it(mports.begin());
it != mports.end();
++it) {
if (mservice)
mservice->removeService( (*it)->getName() );
}
mports.clear();
}
bool DataFlowInterface::chkPtr(const std::string & where, const std::string & name, const void *ptr)
{
if ( ptr == 0) {
log(Error) << "You tried to add a null pointer in '"<< where << "' for the object '" << name << "'. Fix your code !"<< endlog();
return false;
}
return true;
}
}
| jbohren-forks/rtt-smits | rtt/DataFlowInterface.cpp | C++ | gpl-2.0 | 9,316 |
<?php
/*
* Removes core controls
*/
function shoestrap_remove_controls( $wp_customize ){
$wp_customize->remove_control( 'header_textcolor');
}
add_action( 'customize_register', 'shoestrap_remove_controls' );
| westerniowawireless/wiaw.net | wp-content/themes/shoestrap/lib/customizer/functions/remove-controls.php | PHP | gpl-2.0 | 213 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2016 Red Hat, Inc.
#
# Authors:
# Thomas Woerner <twoerner@redhat.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/>.
#
import os.path
import copy
from firewall.core.base import SHORTCUTS, DEFAULT_ZONE_TARGET
from firewall.core.prog import runProg
from firewall.core.logger import log
from firewall.functions import tempFile, readfile, splitArgs, check_mac, portStr, \
check_single_address
from firewall import config
from firewall.errors import FirewallError, INVALID_PASSTHROUGH, INVALID_RULE, UNKNOWN_ERROR
from firewall.core.rich import Rich_Accept, Rich_Reject, Rich_Drop, Rich_Mark, \
Rich_Masquerade, Rich_ForwardPort, Rich_IcmpBlock
import string
BUILT_IN_CHAINS = {
"security": [ "INPUT", "OUTPUT", "FORWARD" ],
"raw": [ "PREROUTING", "OUTPUT" ],
"mangle": [ "PREROUTING", "POSTROUTING", "INPUT", "OUTPUT", "FORWARD" ],
"nat": [ "PREROUTING", "POSTROUTING", "OUTPUT" ],
"filter": [ "INPUT", "OUTPUT", "FORWARD" ],
}
DEFAULT_REJECT_TYPE = {
"ipv4": "icmp-host-prohibited",
"ipv6": "icmp6-adm-prohibited",
}
ICMP = {
"ipv4": "icmp",
"ipv6": "ipv6-icmp",
}
# ipv ebtables also uses this
#
def common_reverse_rule(args):
""" Inverse valid rule """
replace_args = {
# Append
"-A": "-D",
"--append": "--delete",
# Insert
"-I": "-D",
"--insert": "--delete",
# New chain
"-N": "-X",
"--new-chain": "--delete-chain",
}
ret_args = args[:]
for arg in replace_args:
try:
idx = ret_args.index(arg)
except Exception:
continue
if arg in [ "-I", "--insert" ]:
# With insert rulenum, then remove it if it is a number
# Opt at position idx, chain at position idx+1, [rulenum] at
# position idx+2
try:
int(ret_args[idx+2])
except Exception:
pass
else:
ret_args.pop(idx+2)
ret_args[idx] = replace_args[arg]
return ret_args
def common_reverse_passthrough(args):
""" Reverse valid passthough rule """
replace_args = {
# Append
"-A": "-D",
"--append": "--delete",
# Insert
"-I": "-D",
"--insert": "--delete",
# New chain
"-N": "-X",
"--new-chain": "--delete-chain",
}
ret_args = args[:]
for x in replace_args:
try:
idx = ret_args.index(x)
except ValueError:
continue
if x in [ "-I", "--insert" ]:
# With insert rulenum, then remove it if it is a number
# Opt at position idx, chain at position idx+1, [rulenum] at
# position idx+2
try:
int(ret_args[idx+2])
except ValueError:
pass
else:
ret_args.pop(idx+2)
ret_args[idx] = replace_args[x]
return ret_args
raise FirewallError(INVALID_PASSTHROUGH,
"no '-A', '-I' or '-N' arg")
# ipv ebtables also uses this
#
def common_check_passthrough(args):
""" Check if passthough rule is valid (only add, insert and new chain
rules are allowed) """
args = set(args)
not_allowed = set(["-C", "--check", # check rule
"-D", "--delete", # delete rule
"-R", "--replace", # replace rule
"-L", "--list", # list rule
"-S", "--list-rules", # print rules
"-F", "--flush", # flush rules
"-Z", "--zero", # zero rules
"-X", "--delete-chain", # delete chain
"-P", "--policy", # policy
"-E", "--rename-chain"]) # rename chain)
# intersection of args and not_allowed is not empty, i.e.
# something from args is not allowed
if len(args & not_allowed) > 0:
raise FirewallError(INVALID_PASSTHROUGH,
"arg '%s' is not allowed" %
list(args & not_allowed)[0])
# args need to contain one of -A, -I, -N
needed = set(["-A", "--append",
"-I", "--insert",
"-N", "--new-chain"])
# empty intersection of args and needed, i.e.
# none from args contains any needed command
if len(args & needed) == 0:
raise FirewallError(INVALID_PASSTHROUGH,
"no '-A', '-I' or '-N' arg")
class ip4tables(object):
ipv = "ipv4"
name = "ip4tables"
zones_supported = True
def __init__(self, fw):
self._fw = fw
self._command = config.COMMANDS[self.ipv]
self._restore_command = config.COMMANDS["%s-restore" % self.ipv]
self.wait_option = self._detect_wait_option()
self.restore_wait_option = self._detect_restore_wait_option()
self.fill_exists()
self.available_tables = []
self.rich_rule_priority_counts = {}
self.our_chains = {} # chains created by firewalld
def fill_exists(self):
self.command_exists = os.path.exists(self._command)
self.restore_command_exists = os.path.exists(self._restore_command)
def __run(self, args):
# convert to string list
if self.wait_option and self.wait_option not in args:
_args = [self.wait_option] + ["%s" % item for item in args]
else:
_args = ["%s" % item for item in args]
log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
(status, ret) = runProg(self._command, _args)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command,
" ".join(_args), ret))
return ret
def split_value(self, rules, opts=None):
"""Split values combined with commas for options in opts"""
if opts is None:
return rules
out_rules = [ ]
for rule in rules:
processed = False
for opt in opts:
try:
i = rule.index(opt)
except ValueError:
pass
else:
if len(rule) > i and "," in rule[i+1]:
# For all items in the comma separated list in index
# i of the rule, a new rule is created with a single
# item from this list
processed = True
items = rule[i+1].split(",")
for item in items:
_rule = rule[:]
_rule[i+1] = item
out_rules.append(_rule)
if not processed:
out_rules.append(rule)
return out_rules
def _rule_replace(self, rule, pattern, replacement):
try:
i = rule.index(pattern)
except ValueError:
return False
else:
rule[i:i+1] = replacement
return True
def is_chain_builtin(self, ipv, table, chain):
return table in BUILT_IN_CHAINS and \
chain in BUILT_IN_CHAINS[table]
def build_chain_rules(self, add, table, chain):
rule = [ "-t", table ]
if add:
rule.append("-N")
else:
rule.append("-X")
rule.append(chain)
return [rule]
def build_rule(self, add, table, chain, index, args):
rule = [ "-t", table ]
if add:
rule += [ "-I", chain, str(index) ]
else:
rule += [ "-D", chain ]
rule += args
return rule
def reverse_rule(self, args):
return common_reverse_rule(args)
def check_passthrough(self, args):
common_check_passthrough(args)
def reverse_passthrough(self, args):
return common_reverse_passthrough(args)
def passthrough_parse_table_chain(self, args):
table = "filter"
try:
i = args.index("-t")
except ValueError:
pass
else:
if len(args) >= i+1:
table = args[i+1]
chain = None
for opt in [ "-A", "--append",
"-I", "--insert",
"-N", "--new-chain" ]:
try:
i = args.index(opt)
except ValueError:
pass
else:
if len(args) >= i+1:
chain = args[i+1]
return (table, chain)
def _set_rule_replace_rich_rule_priority(self, rule, rich_rule_priority_counts):
"""
Change something like
-t filter -I public_IN %%RICH_RULE_PRIORITY%% 123
or
-t filter -A public_IN %%RICH_RULE_PRIORITY%% 321
into
-t filter -I public_IN 4
or
-t filter -I public_IN
"""
try:
i = rule.index("%%RICH_RULE_PRIORITY%%")
except ValueError:
pass
else:
rule_add = True
insert = False
insert_add_index = -1
rule.pop(i)
priority = rule.pop(i)
if type(priority) != int:
raise FirewallError(INVALID_RULE, "rich rule priority must be followed by a number")
table = "filter"
for opt in [ "-t", "--table" ]:
try:
j = rule.index(opt)
except ValueError:
pass
else:
if len(rule) >= j+1:
table = rule[j+1]
for opt in [ "-A", "--append",
"-I", "--insert",
"-D", "--delete" ]:
try:
insert_add_index = rule.index(opt)
except ValueError:
pass
else:
if len(rule) >= insert_add_index+1:
chain = rule[insert_add_index+1]
if opt in [ "-I", "--insert" ]:
insert = True
if opt in [ "-D", "--delete" ]:
rule_add = False
chain = (table, chain)
# Add the rule to the priority counts. We don't need to store the
# rule, just bump the ref count for the priority value.
if not rule_add:
if chain not in rich_rule_priority_counts or \
priority not in rich_rule_priority_counts[chain] or \
rich_rule_priority_counts[chain][priority] <= 0:
raise FirewallError(UNKNOWN_ERROR, "nonexistent or underflow of rich rule priority count")
rich_rule_priority_counts[chain][priority] -= 1
else:
if chain not in rich_rule_priority_counts:
rich_rule_priority_counts[chain] = {}
if priority not in rich_rule_priority_counts[chain]:
rich_rule_priority_counts[chain][priority] = 0
# calculate index of new rule
index = 1
for p in sorted(rich_rule_priority_counts[chain].keys()):
if p == priority and insert:
break
index += rich_rule_priority_counts[chain][p]
if p == priority:
break
rich_rule_priority_counts[chain][priority] += 1
rule[insert_add_index] = "-I"
rule.insert(insert_add_index+2, "%d" % index)
def set_rules(self, rules, log_denied):
temp_file = tempFile()
table_rules = { }
rich_rule_priority_counts = copy.deepcopy(self.rich_rule_priority_counts)
for _rule in rules:
rule = _rule[:]
# replace %%REJECT%%
self._rule_replace(rule, "%%REJECT%%", \
["REJECT", "--reject-with", DEFAULT_REJECT_TYPE[self.ipv]])
# replace %%ICMP%%
self._rule_replace(rule, "%%ICMP%%", [ICMP[self.ipv]])
# replace %%LOGTYPE%%
try:
i = rule.index("%%LOGTYPE%%")
except ValueError:
pass
else:
if log_denied == "off":
continue
if log_denied in [ "unicast", "broadcast", "multicast" ]:
rule[i:i+1] = [ "-m", "pkttype", "--pkt-type", log_denied ]
else:
rule.pop(i)
self._set_rule_replace_rich_rule_priority(rule, rich_rule_priority_counts)
table = "filter"
# get table form rule
for opt in [ "-t", "--table" ]:
try:
i = rule.index(opt)
except ValueError:
pass
else:
if len(rule) >= i+1:
rule.pop(i)
table = rule.pop(i)
# we can not use joinArgs here, because it would use "'" instead
# of '"' for the start and end of the string, this breaks
# iptables-restore
for i in range(len(rule)):
for c in string.whitespace:
if c in rule[i] and not (rule[i].startswith('"') and
rule[i].endswith('"')):
rule[i] = '"%s"' % rule[i]
table_rules.setdefault(table, []).append(rule)
for table in table_rules:
rules = table_rules[table]
rules = self.split_value(rules, [ "-s", "--source" ])
rules = self.split_value(rules, [ "-d", "--destination" ])
temp_file.write("*%s\n" % table)
for rule in rules:
temp_file.write(" ".join(rule) + "\n")
temp_file.write("COMMIT\n")
temp_file.close()
stat = os.stat(temp_file.name)
log.debug2("%s: %s %s", self.__class__, self._restore_command,
"%s: %d" % (temp_file.name, stat.st_size))
args = [ ]
if self.restore_wait_option:
args.append(self.restore_wait_option)
args.append("-n")
(status, ret) = runProg(self._restore_command, args,
stdin=temp_file.name)
if log.getDebugLogLevel() > 2:
lines = readfile(temp_file.name)
if lines is not None:
i = 1
for line in lines:
log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
if not line.endswith("\n"):
log.debug3("", nofmt=1)
i += 1
os.unlink(temp_file.name)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._restore_command,
" ".join(args), ret))
self.rich_rule_priority_counts = rich_rule_priority_counts
return ret
def set_rule(self, rule, log_denied):
# replace %%REJECT%%
self._rule_replace(rule, "%%REJECT%%", \
["REJECT", "--reject-with", DEFAULT_REJECT_TYPE[self.ipv]])
# replace %%ICMP%%
self._rule_replace(rule, "%%ICMP%%", [ICMP[self.ipv]])
# replace %%LOGTYPE%%
try:
i = rule.index("%%LOGTYPE%%")
except ValueError:
pass
else:
if log_denied == "off":
return ""
if log_denied in [ "unicast", "broadcast", "multicast" ]:
rule[i:i+1] = [ "-m", "pkttype", "--pkt-type", log_denied ]
else:
rule.pop(i)
rich_rule_priority_counts = copy.deepcopy(self.rich_rule_priority_counts)
self._set_rule_replace_rich_rule_priority(rule, self.rich_rule_priority_counts)
output = self.__run(rule)
self.rich_rule_priority_counts = rich_rule_priority_counts
return output
def get_available_tables(self, table=None):
ret = []
tables = [ table ] if table else BUILT_IN_CHAINS.keys()
for table in tables:
if table in self.available_tables:
ret.append(table)
else:
try:
self.__run(["-t", table, "-L", "-n"])
self.available_tables.append(table)
ret.append(table)
except ValueError:
log.debug1("%s table '%s' does not exist (or not enough permission to check)." % (self.ipv, table))
return ret
def _detect_wait_option(self):
wait_option = ""
ret = runProg(self._command, ["-w", "-L", "-n"]) # since iptables-1.4.20
if ret[0] == 0:
wait_option = "-w" # wait for xtables lock
ret = runProg(self._command, ["-w10", "-L", "-n"]) # since iptables > 1.4.21
if ret[0] == 0:
wait_option = "-w10" # wait max 10 seconds
log.debug2("%s: %s will be using %s option.", self.__class__, self._command, wait_option)
return wait_option
def _detect_restore_wait_option(self):
temp_file = tempFile()
temp_file.write("#foo")
temp_file.close()
wait_option = ""
for test_option in ["-w", "--wait=2"]:
ret = runProg(self._restore_command, [test_option], stdin=temp_file.name)
if ret[0] == 0 and "invalid option" not in ret[1] \
and "unrecognized option" not in ret[1]:
wait_option = test_option
break
log.debug2("%s: %s will be using %s option.", self.__class__, self._restore_command, wait_option)
os.unlink(temp_file.name)
return wait_option
def build_flush_rules(self):
self.rich_rule_priority_counts = {}
rules = []
for table in BUILT_IN_CHAINS.keys():
# Flush firewall rules: -F
# Delete firewall chains: -X
# Set counter to zero: -Z
for flag in [ "-F", "-X", "-Z" ]:
rules.append(["-t", table, flag])
return rules
def build_set_policy_rules(self, policy):
rules = []
for table in BUILT_IN_CHAINS.keys():
if table == "nat":
continue
for chain in BUILT_IN_CHAINS[table]:
rules.append(["-t", table, "-P", chain, policy])
return rules
def supported_icmp_types(self):
"""Return ICMP types that are supported by the iptables/ip6tables command and kernel"""
ret = [ ]
output = ""
try:
output = self.__run(["-p",
"icmp" if self.ipv == "ipv4" else "ipv6-icmp",
"--help"])
except ValueError as ex:
if self.ipv == "ipv4":
log.debug1("iptables error: %s" % ex)
else:
log.debug1("ip6tables error: %s" % ex)
lines = output.splitlines()
in_types = False
for line in lines:
#print(line)
if in_types:
line = line.strip().lower()
splits = line.split()
for split in splits:
if split.startswith("(") and split.endswith(")"):
x = split[1:-1]
else:
x = split
if x not in ret:
ret.append(x)
if self.ipv == "ipv4" and line.startswith("Valid ICMP Types:") or \
self.ipv == "ipv6" and line.startswith("Valid ICMPv6 Types:"):
in_types = True
return ret
def build_default_tables(self):
# nothing to do, they always exist
return []
def build_default_rules(self, log_denied="off"):
default_rules = {}
default_rules["security"] = [ ]
self.our_chains["security"] = set()
for chain in BUILT_IN_CHAINS["security"]:
default_rules["security"].append("-N %s_direct" % chain)
default_rules["security"].append("-A %s -j %s_direct" % (chain, chain))
self.our_chains["security"].add("%s_direct" % chain)
default_rules["raw"] = [ ]
self.our_chains["raw"] = set()
for chain in BUILT_IN_CHAINS["raw"]:
default_rules["raw"].append("-N %s_direct" % chain)
default_rules["raw"].append("-A %s -j %s_direct" % (chain, chain))
self.our_chains["raw"].add("%s_direct" % chain)
if chain == "PREROUTING":
default_rules["raw"].append("-N %s_ZONES_SOURCE" % chain)
default_rules["raw"].append("-N %s_ZONES" % chain)
default_rules["raw"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain))
default_rules["raw"].append("-A %s -j %s_ZONES" % (chain, chain))
self.our_chains["raw"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain]))
default_rules["mangle"] = [ ]
self.our_chains["mangle"] = set()
for chain in BUILT_IN_CHAINS["mangle"]:
default_rules["mangle"].append("-N %s_direct" % chain)
default_rules["mangle"].append("-A %s -j %s_direct" % (chain, chain))
self.our_chains["mangle"].add("%s_direct" % chain)
if chain == "PREROUTING":
default_rules["mangle"].append("-N %s_ZONES_SOURCE" % chain)
default_rules["mangle"].append("-N %s_ZONES" % chain)
default_rules["mangle"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain))
default_rules["mangle"].append("-A %s -j %s_ZONES" % (chain, chain))
self.our_chains["mangle"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain]))
default_rules["nat"] = [ ]
self.our_chains["nat"] = set()
for chain in BUILT_IN_CHAINS["nat"]:
default_rules["nat"].append("-N %s_direct" % chain)
default_rules["nat"].append("-A %s -j %s_direct" % (chain, chain))
self.our_chains["nat"].add("%s_direct" % chain)
if chain in [ "PREROUTING", "POSTROUTING" ]:
default_rules["nat"].append("-N %s_ZONES_SOURCE" % chain)
default_rules["nat"].append("-N %s_ZONES" % chain)
default_rules["nat"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain))
default_rules["nat"].append("-A %s -j %s_ZONES" % (chain, chain))
self.our_chains["nat"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain]))
default_rules["filter"] = [
"-N INPUT_direct",
"-N INPUT_ZONES_SOURCE",
"-N INPUT_ZONES",
"-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT",
"-A INPUT -i lo -j ACCEPT",
"-A INPUT -j INPUT_direct",
"-A INPUT -j INPUT_ZONES_SOURCE",
"-A INPUT -j INPUT_ZONES",
]
if log_denied != "off":
default_rules["filter"].append("-A INPUT -m conntrack --ctstate INVALID %%LOGTYPE%% -j LOG --log-prefix 'STATE_INVALID_DROP: '")
default_rules["filter"].append("-A INPUT -m conntrack --ctstate INVALID -j DROP")
if log_denied != "off":
default_rules["filter"].append("-A INPUT %%LOGTYPE%% -j LOG --log-prefix 'FINAL_REJECT: '")
default_rules["filter"].append("-A INPUT -j %%REJECT%%")
default_rules["filter"] += [
"-N FORWARD_direct",
"-N FORWARD_IN_ZONES_SOURCE",
"-N FORWARD_IN_ZONES",
"-N FORWARD_OUT_ZONES_SOURCE",
"-N FORWARD_OUT_ZONES",
"-A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT",
"-A FORWARD -i lo -j ACCEPT",
"-A FORWARD -j FORWARD_direct",
"-A FORWARD -j FORWARD_IN_ZONES_SOURCE",
"-A FORWARD -j FORWARD_IN_ZONES",
"-A FORWARD -j FORWARD_OUT_ZONES_SOURCE",
"-A FORWARD -j FORWARD_OUT_ZONES",
]
if log_denied != "off":
default_rules["filter"].append("-A FORWARD -m conntrack --ctstate INVALID %%LOGTYPE%% -j LOG --log-prefix 'STATE_INVALID_DROP: '")
default_rules["filter"].append("-A FORWARD -m conntrack --ctstate INVALID -j DROP")
if log_denied != "off":
default_rules["filter"].append("-A FORWARD %%LOGTYPE%% -j LOG --log-prefix 'FINAL_REJECT: '")
default_rules["filter"].append("-A FORWARD -j %%REJECT%%")
default_rules["filter"] += [
"-N OUTPUT_direct",
"-A OUTPUT -o lo -j ACCEPT",
"-A OUTPUT -j OUTPUT_direct",
]
self.our_chains["filter"] = set(["INPUT_direct", "INPUT_ZONES_SOURCE", "INPUT_ZONES",
"FORWARD_direct", "FORWARD_IN_ZONES_SOURCE",
"FORWARD_IN_ZONES", "FORWARD_OUT_ZONES_SOURCE",
"FORWARD_OUT_ZONES", "OUTPUT_direct"])
final_default_rules = []
for table in default_rules:
if table not in self.get_available_tables():
continue
for rule in default_rules[table]:
final_default_rules.append(["-t", table] + splitArgs(rule))
return final_default_rules
def get_zone_table_chains(self, table):
if table == "filter":
return { "INPUT", "FORWARD_IN", "FORWARD_OUT" }
if table == "mangle":
if "mangle" in self.get_available_tables() and \
"nat" in self.get_available_tables():
return { "PREROUTING" }
if table == "nat":
if "nat" in self.get_available_tables():
return { "PREROUTING", "POSTROUTING" }
if table == "raw":
if "raw" in self.get_available_tables():
return { "PREROUTING" }
return {}
def build_zone_source_interface_rules(self, enable, zone, zone_target,
interface, table, chain,
append=False):
# handle all zones in the same way here, now
# trust and block zone targets are handled now in __chain
opt = {
"PREROUTING": "-i",
"POSTROUTING": "-o",
"INPUT": "-i",
"FORWARD_IN": "-i",
"FORWARD_OUT": "-o",
"OUTPUT": "-o",
}[chain]
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone)
if zone_target == DEFAULT_ZONE_TARGET:
action = "-g"
else:
action = "-j"
if enable and not append:
rule = [ "-I", "%s_ZONES" % chain, "1" ]
elif enable:
rule = [ "-A", "%s_ZONES" % chain ]
else:
rule = [ "-D", "%s_ZONES" % chain ]
rule += [ "-t", table, opt, interface, action, target ]
return [rule]
def build_zone_source_address_rules(self, enable, zone, zone_target,
address, table, chain):
add_del = { True: "-A", False: "-D" }[enable]
opt = {
"PREROUTING": "-s",
"POSTROUTING": "-d",
"INPUT": "-s",
"FORWARD_IN": "-s",
"FORWARD_OUT": "-d",
"OUTPUT": "-d",
}[chain]
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone)
if zone_target == DEFAULT_ZONE_TARGET:
action = "-g"
else:
action = "-j"
if address.startswith("ipset:"):
name = address[6:]
if opt == "-d":
opt = "dst"
else:
opt = "src"
flags = ",".join([opt] * self._fw.ipset.get_dimension(name))
rule = [ add_del,
"%s_ZONES_SOURCE" % chain, "-t", table,
"-m", "set", "--match-set", name,
flags, action, target ]
else:
if check_mac(address):
# outgoing can not be set
if opt == "-d":
return ""
rule = [ add_del,
"%s_ZONES_SOURCE" % chain, "-t", table,
"-m", "mac", "--mac-source", address.upper(),
action, target ]
else:
rule = [ add_del,
"%s_ZONES_SOURCE" % chain, "-t", table,
opt, address, action, target ]
return [rule]
def build_zone_chain_rules(self, zone, table, chain):
_zone = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone)
self.our_chains[table].update(set([_zone,
"%s_log" % _zone,
"%s_deny" % _zone,
"%s_pre" % _zone,
"%s_post" % _zone,
"%s_allow" % _zone]))
rules = []
rules.append([ "-N", _zone, "-t", table ])
rules.append([ "-N", "%s_pre" % _zone, "-t", table ])
rules.append([ "-N", "%s_log" % _zone, "-t", table ])
rules.append([ "-N", "%s_deny" % _zone, "-t", table ])
rules.append([ "-N", "%s_allow" % _zone, "-t", table ])
rules.append([ "-N", "%s_post" % _zone, "-t", table ])
rules.append([ "-A", _zone, "-t", table, "-j", "%s_pre" % _zone ])
rules.append([ "-A", _zone, "-t", table, "-j", "%s_log" % _zone ])
rules.append([ "-A", _zone, "-t", table, "-j", "%s_deny" % _zone ])
rules.append([ "-A", _zone, "-t", table, "-j", "%s_allow" % _zone ])
rules.append([ "-A", _zone, "-t", table, "-j", "%s_post" % _zone ])
target = self._fw.zone._zones[zone].target
if self._fw.get_log_denied() != "off":
if table == "filter" and \
chain in [ "INPUT", "FORWARD_IN", "FORWARD_OUT", "OUTPUT" ]:
if target in [ "REJECT", "%%REJECT%%" ]:
rules.append([ "-A", _zone, "-t", table, "%%LOGTYPE%%",
"-j", "LOG", "--log-prefix",
"\"%s_REJECT: \"" % _zone ])
if target == "DROP":
rules.append([ "-A", _zone, "-t", table, "%%LOGTYPE%%",
"-j", "LOG", "--log-prefix",
"\"%s_DROP: \"" % _zone ])
# Handle trust, block and drop zones:
# Add an additional rule with the zone target (accept, reject
# or drop) to the base zone only in the filter table.
# Otherwise it is not be possible to have a zone with drop
# target, that is allowing traffic that is locally initiated
# or that adds additional rules. (RHBZ#1055190)
if table == "filter" and \
target in [ "ACCEPT", "REJECT", "%%REJECT%%", "DROP" ] and \
chain in [ "INPUT", "FORWARD_IN", "FORWARD_OUT", "OUTPUT" ]:
rules.append([ "-A", _zone, "-t", table, "-j", target ])
return rules
def _rule_limit(self, limit):
if limit:
return [ "-m", "limit", "--limit", limit.value ]
return []
def _rich_rule_chain_suffix(self, rich_rule):
if type(rich_rule.element) in [Rich_Masquerade, Rich_ForwardPort, Rich_IcmpBlock]:
# These are special and don't have an explicit action
pass
elif rich_rule.action:
if type(rich_rule.action) not in [Rich_Accept, Rich_Reject, Rich_Drop, Rich_Mark]:
raise FirewallError(INVALID_RULE, "Unknown action %s" % type(rich_rule.action))
else:
raise FirewallError(INVALID_RULE, "No rule action specified.")
if rich_rule.priority == 0:
if type(rich_rule.element) in [Rich_Masquerade, Rich_ForwardPort] or \
type(rich_rule.action) in [Rich_Accept, Rich_Mark]:
return "allow"
elif type(rich_rule.element) in [Rich_IcmpBlock] or \
type(rich_rule.action) in [Rich_Reject, Rich_Drop]:
return "deny"
elif rich_rule.priority < 0:
return "pre"
else:
return "post"
def _rich_rule_chain_suffix_from_log(self, rich_rule):
if not rich_rule.log and not rich_rule.audit:
raise FirewallError(INVALID_RULE, "Not log or audit")
if rich_rule.priority == 0:
return "log"
elif rich_rule.priority < 0:
return "pre"
else:
return "post"
def _rich_rule_priority_fragment(self, rich_rule):
if rich_rule.priority == 0:
return []
return ["%%RICH_RULE_PRIORITY%%", rich_rule.priority]
def _rich_rule_log(self, rich_rule, enable, table, target, rule_fragment):
if not rich_rule.log:
return []
add_del = { True: "-A", False: "-D" }[enable]
chain_suffix = self._rich_rule_chain_suffix_from_log(rich_rule)
rule = ["-t", table, add_del, "%s_%s" % (target, chain_suffix)]
rule += self._rich_rule_priority_fragment(rich_rule)
rule += rule_fragment + [ "-j", "LOG" ]
if rich_rule.log.prefix:
rule += [ "--log-prefix", "'%s'" % rich_rule.log.prefix ]
if rich_rule.log.level:
rule += [ "--log-level", "%s" % rich_rule.log.level ]
rule += self._rule_limit(rich_rule.log.limit)
return rule
def _rich_rule_audit(self, rich_rule, enable, table, target, rule_fragment):
if not rich_rule.audit:
return []
add_del = { True: "-A", False: "-D" }[enable]
chain_suffix = self._rich_rule_chain_suffix_from_log(rich_rule)
rule = ["-t", table, add_del, "%s_%s" % (target, chain_suffix)]
rule += self._rich_rule_priority_fragment(rich_rule)
rule += rule_fragment
if type(rich_rule.action) == Rich_Accept:
_type = "accept"
elif type(rich_rule.action) == Rich_Reject:
_type = "reject"
elif type(rich_rule.action) == Rich_Drop:
_type = "drop"
else:
_type = "unknown"
rule += [ "-j", "AUDIT", "--type", _type ]
rule += self._rule_limit(rich_rule.audit.limit)
return rule
def _rich_rule_action(self, zone, rich_rule, enable, table, target, rule_fragment):
if not rich_rule.action:
return []
add_del = { True: "-A", False: "-D" }[enable]
chain_suffix = self._rich_rule_chain_suffix(rich_rule)
chain = "%s_%s" % (target, chain_suffix)
if type(rich_rule.action) == Rich_Accept:
rule_action = [ "-j", "ACCEPT" ]
elif type(rich_rule.action) == Rich_Reject:
rule_action = [ "-j", "REJECT" ]
if rich_rule.action.type:
rule_action += [ "--reject-with", rich_rule.action.type ]
elif type(rich_rule.action) == Rich_Drop:
rule_action = [ "-j", "DROP" ]
elif type(rich_rule.action) == Rich_Mark:
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"],
zone=zone)
table = "mangle"
chain = "%s_%s" % (target, chain_suffix)
rule_action = [ "-j", "MARK", "--set-xmark", rich_rule.action.set ]
else:
raise FirewallError(INVALID_RULE,
"Unknown action %s" % type(rich_rule.action))
rule = ["-t", table, add_del, chain]
rule += self._rich_rule_priority_fragment(rich_rule)
rule += rule_fragment + rule_action
rule += self._rule_limit(rich_rule.action.limit)
return rule
def _rich_rule_destination_fragment(self, rich_dest):
if not rich_dest:
return []
rule_fragment = []
if rich_dest.invert:
rule_fragment.append("!")
rule_fragment += [ "-d", rich_dest.addr ]
return rule_fragment
def _rich_rule_source_fragment(self, rich_source):
if not rich_source:
return []
rule_fragment = []
if rich_source.addr:
if rich_source.invert:
rule_fragment.append("!")
rule_fragment += [ "-s", rich_source.addr ]
elif hasattr(rich_source, "mac") and rich_source.mac:
rule_fragment += [ "-m", "mac" ]
if rich_source.invert:
rule_fragment.append("!")
rule_fragment += [ "--mac-source", rich_source.mac ]
elif hasattr(rich_source, "ipset") and rich_source.ipset:
rule_fragment += [ "-m", "set" ]
if rich_source.invert:
rule_fragment.append("!")
flags = self._fw.zone._ipset_match_flags(rich_source.ipset, "src")
rule_fragment += [ "--match-set", rich_source.ipset, flags ]
return rule_fragment
def build_zone_ports_rules(self, enable, zone, proto, port, destination=None, rich_rule=None):
add_del = { True: "-A", False: "-D" }[enable]
table = "filter"
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"],
zone=zone)
rule_fragment = [ "-p", proto ]
if port:
rule_fragment += [ "--dport", "%s" % portStr(port) ]
if destination:
rule_fragment += [ "-d", destination ]
if rich_rule:
rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination)
rule_fragment += self._rich_rule_source_fragment(rich_rule.source)
if not rich_rule or rich_rule.action != Rich_Mark:
rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ]
rules = []
if rich_rule:
rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment))
else:
rules.append([add_del, "%s_allow" % (target), "-t", table] +
rule_fragment + [ "-j", "ACCEPT" ])
return rules
def build_zone_protocol_rules(self, enable, zone, protocol, destination=None, rich_rule=None):
add_del = { True: "-A", False: "-D" }[enable]
table = "filter"
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone)
rule_fragment = [ "-p", protocol ]
if destination:
rule_fragment += [ "-d", destination ]
if rich_rule:
rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination)
rule_fragment += self._rich_rule_source_fragment(rich_rule.source)
if not rich_rule or rich_rule.action != Rich_Mark:
rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ]
rules = []
if rich_rule:
rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment))
else:
rules.append([add_del, "%s_allow" % (target), "-t", table] +
rule_fragment + [ "-j", "ACCEPT" ])
return rules
def build_zone_source_ports_rules(self, enable, zone, proto, port,
destination=None, rich_rule=None):
add_del = { True: "-A", False: "-D" }[enable]
table = "filter"
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone)
rule_fragment = [ "-p", proto ]
if port:
rule_fragment += [ "--sport", "%s" % portStr(port) ]
if destination:
rule_fragment += [ "-d", destination ]
if rich_rule:
rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination)
rule_fragment += self._rich_rule_source_fragment(rich_rule.source)
if not rich_rule or rich_rule.action != Rich_Mark:
rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ]
rules = []
if rich_rule:
rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment))
else:
rules.append([add_del, "%s_allow" % (target), "-t", table] +
rule_fragment + [ "-j", "ACCEPT" ])
return rules
def build_zone_helper_ports_rules(self, enable, zone, proto, port,
destination, helper_name):
add_del = { True: "-A", False: "-D" }[enable]
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"],
zone=zone)
rule = [ add_del, "%s_allow" % (target), "-t", "raw", "-p", proto ]
if port:
rule += [ "--dport", "%s" % portStr(port) ]
if destination:
rule += [ "-d", destination ]
rule += [ "-j", "CT", "--helper", helper_name ]
return [rule]
def build_zone_masquerade_rules(self, enable, zone, rich_rule=None):
add_del = { True: "-A", False: "-D" }[enable]
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["POSTROUTING"],
zone=zone)
rule_fragment = []
if rich_rule:
chain_suffix = self._rich_rule_chain_suffix(rich_rule)
rule_fragment += self._rich_rule_priority_fragment(rich_rule)
rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination)
rule_fragment += self._rich_rule_source_fragment(rich_rule.source)
else:
chain_suffix = "allow"
rules = []
rules.append(["-t", "nat", add_del, "%s_%s" % (target, chain_suffix)]
+ rule_fragment +
[ "!", "-o", "lo", "-j", "MASQUERADE" ])
# FORWARD_OUT
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["FORWARD_OUT"],
zone=zone)
rule_fragment = []
if rich_rule:
chain_suffix = self._rich_rule_chain_suffix(rich_rule)
rule_fragment += self._rich_rule_priority_fragment(rich_rule)
rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination)
rule_fragment += self._rich_rule_source_fragment(rich_rule.source)
else:
chain_suffix = "allow"
rules.append(["-t", "filter", add_del, "%s_%s" % (target, chain_suffix)]
+ rule_fragment +
["-m", "conntrack", "--ctstate", "NEW,UNTRACKED", "-j", "ACCEPT" ])
return rules
def build_zone_forward_port_rules(self, enable, zone, filter_chain, port,
protocol, toport, toaddr, mark_id, rich_rule=None):
add_del = { True: "-A", False: "-D" }[enable]
mark_str = "0x%x" % mark_id
mark = [ "-m", "mark", "--mark", mark_str ]
to = ""
if toaddr:
if check_single_address("ipv6", toaddr):
to += "[%s]" % toaddr
else:
to += toaddr
if toport and toport != "":
to += ":%s" % portStr(toport, "-")
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"],
zone=zone)
rule_fragment = [ "-p", protocol, "--dport", portStr(port) ]
rich_rule_priority_fragment = []
if rich_rule:
chain_suffix = self._rich_rule_chain_suffix(rich_rule)
rich_rule_priority_fragment = self._rich_rule_priority_fragment(rich_rule)
rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination)
rule_fragment += self._rich_rule_source_fragment(rich_rule.source)
else:
chain_suffix = "allow"
rules = []
if rich_rule:
rules.append(self._rich_rule_log(rich_rule, enable, "mangle", target, rule_fragment))
rules.append(["-t", "mangle", add_del, "%s_%s" % (target, chain_suffix)]
+ rich_rule_priority_fragment + rule_fragment +
[ "-j", "MARK", "--set-mark", mark_str ])
# local and remote
rules.append(["-t", "nat", add_del, "%s_%s" % (target, chain_suffix)]
+ rich_rule_priority_fragment +
["-p", protocol ] + mark +
[ "-j", "DNAT", "--to-destination", to ])
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[filter_chain],
zone=zone)
rules.append(["-t", "filter", add_del, "%s_%s" % (target, chain_suffix)]
+ rich_rule_priority_fragment +
["-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ]
+ mark +
[ "-j", "ACCEPT" ])
return rules
def build_zone_icmp_block_rules(self, enable, zone, ict, rich_rule=None):
table = "filter"
add_del = { True: "-A", False: "-D" }[enable]
if self.ipv == "ipv4":
proto = [ "-p", "icmp" ]
match = [ "-m", "icmp", "--icmp-type", ict.name ]
else:
proto = [ "-p", "ipv6-icmp" ]
match = [ "-m", "icmp6", "--icmpv6-type", ict.name ]
rules = []
for chain in ["INPUT", "FORWARD_IN"]:
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain],
zone=zone)
if self._fw.zone.query_icmp_block_inversion(zone):
final_chain = "%s_allow" % target
final_target = "ACCEPT"
else:
final_chain = "%s_deny" % target
final_target = "%%REJECT%%"
rule_fragment = []
if rich_rule:
rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination)
rule_fragment += self._rich_rule_source_fragment(rich_rule.source)
rule_fragment += proto + match
if rich_rule:
rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment))
if rich_rule.action:
rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment))
else:
chain_suffix = self._rich_rule_chain_suffix(rich_rule)
rules.append(["-t", table, add_del, "%s_%s" % (target, chain_suffix)]
+ self._rich_rule_priority_fragment(rich_rule)
+ rule_fragment +
[ "-j", "%%REJECT%%" ])
else:
if self._fw.get_log_denied() != "off" and final_target != "ACCEPT":
rules.append([ add_del, final_chain, "-t", table ]
+ rule_fragment +
[ "%%LOGTYPE%%", "-j", "LOG",
"--log-prefix", "\"%s_ICMP_BLOCK: \"" % zone ])
rules.append([ add_del, final_chain, "-t", table ]
+ rule_fragment +
[ "-j", final_target ])
return rules
def build_zone_icmp_block_inversion_rules(self, enable, zone):
table = "filter"
rules = []
for chain in [ "INPUT", "FORWARD_IN" ]:
rule_idx = 6
_zone = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain],
zone=zone)
if self._fw.zone.query_icmp_block_inversion(zone):
ibi_target = "%%REJECT%%"
if self._fw.get_log_denied() != "off":
if enable:
rule = [ "-I", _zone, str(rule_idx) ]
else:
rule = [ "-D", _zone ]
rule = rule + [ "-t", table, "-p", "%%ICMP%%",
"%%LOGTYPE%%",
"-j", "LOG", "--log-prefix",
"\"%s_ICMP_BLOCK: \"" % _zone ]
rules.append(rule)
rule_idx += 1
else:
ibi_target = "ACCEPT"
if enable:
rule = [ "-I", _zone, str(rule_idx) ]
else:
rule = [ "-D", _zone ]
rule = rule + [ "-t", table, "-p", "%%ICMP%%", "-j", ibi_target ]
rules.append(rule)
return rules
def build_zone_rich_source_destination_rules(self, enable, zone, rich_rule):
table = "filter"
target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"],
zone=zone)
rule_fragment = []
rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination)
rule_fragment += self._rich_rule_source_fragment(rich_rule.source)
rules = []
rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment))
rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment))
return rules
def is_ipv_supported(self, ipv):
return ipv == self.ipv
class ip6tables(ip4tables):
ipv = "ipv6"
name = "ip6tables"
def build_rpfilter_rules(self, log_denied=False):
rules = []
rules.append([ "-I", "PREROUTING", "-t", "raw",
"-m", "rpfilter", "--invert", "-j", "DROP" ])
if log_denied != "off":
rules.append([ "-I", "PREROUTING", "-t", "raw",
"-m", "rpfilter", "--invert",
"-j", "LOG",
"--log-prefix", "rpfilter_DROP: " ])
rules.append([ "-I", "PREROUTING", "-t", "raw",
"-p", "ipv6-icmp",
"--icmpv6-type=neighbour-solicitation",
"-j", "ACCEPT" ]) # RHBZ#1575431, kernel bug in 4.16-4.17
rules.append([ "-I", "PREROUTING", "-t", "raw",
"-p", "ipv6-icmp",
"--icmpv6-type=router-advertisement",
"-j", "ACCEPT" ]) # RHBZ#1058505
return rules
def build_rfc3964_ipv4_rules(self):
daddr_list = [
"::0.0.0.0/96", # IPv4 compatible
"::ffff:0.0.0.0/96", # IPv4 mapped
"2002:0000::/24", # 0.0.0.0/8 (the system has no address assigned yet)
"2002:0a00::/24", # 10.0.0.0/8 (private)
"2002:7f00::/24", # 127.0.0.0/8 (loopback)
"2002:ac10::/28", # 172.16.0.0/12 (private)
"2002:c0a8::/32", # 192.168.0.0/16 (private)
"2002:a9fe::/32", # 169.254.0.0/16 (IANA Assigned DHCP link-local)
"2002:e000::/19", # 224.0.0.0/4 (multicast), 240.0.0.0/4 (reserved and broadcast)
]
chain_name = "RFC3964_IPv4"
self.our_chains["filter"].add(chain_name)
rules = []
rules.append(["-t", "filter", "-N", chain_name])
for daddr in daddr_list:
rules.append(["-t", "filter", "-I", chain_name,
"-d", daddr, "-j", "REJECT", "--reject-with",
"addr-unreach"])
if self._fw._log_denied in ["unicast", "all"]:
rules.append(["-t", "filter", "-I", chain_name,
"-d", daddr, "-j", "LOG",
"--log-prefix", "\"RFC3964_IPv4_REJECT: \""])
# Inject into FORWARD and OUTPUT chains
rules.append(["-t", "filter", "-I", "OUTPUT", "3",
"-j", chain_name])
rules.append(["-t", "filter", "-I", "FORWARD", "4",
"-j", chain_name])
return rules
| hos7ein/firewalld | src/firewall/core/ipXtables.py | Python | gpl-2.0 | 53,449 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009, 2013 Zuza Software Foundation
#
# This file is part of Pootle.
#
# 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/>.
import json
import time
from translate.storage import factory, statsdb
from pootle.tests import PootleTestCase
from pootle_store.models import Store, Unit
class UnitTests(PootleTestCase):
def setUp(self):
super(UnitTests, self).setUp()
self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po")
def _update_translation(self, item, newvalues):
unit = self.store.getitem(item)
time.sleep(1)
if 'target' in newvalues:
unit.target = newvalues['target']
if 'fuzzy' in newvalues:
unit.markfuzzy(newvalues['fuzzy'])
if 'translator_comment' in newvalues:
unit.translator_comment = newvalues['translator_comment']
unit.save()
self.store.sync(update_translation=True)
return self.store.getitem(item)
def test_getorig(self):
for dbunit in self.store.units.iterator():
storeunit = dbunit.getorig()
self.assertEqual(dbunit.getid(), storeunit.getid())
def test_convert(self):
for dbunit in self.store.units.iterator():
if dbunit.hasplural() and not dbunit.istranslated():
# skip untranslated plural units, they will always look different
continue
storeunit = dbunit.getorig()
newunit = dbunit.convert(self.store.file.store.UnitClass)
self.assertEqual(str(newunit), str(storeunit))
def test_update_target(self):
dbunit = self._update_translation(0, {'target': u'samaka'})
storeunit = dbunit.getorig()
self.assertEqual(dbunit.target, u'samaka')
self.assertEqual(dbunit.target, storeunit.target)
pofile = factory.getobject(self.store.file.path)
self.assertEqual(dbunit.target, pofile.units[dbunit.index].target)
def test_empty_plural_target(self):
"""test we don't delete empty plural targets"""
dbunit = self._update_translation(2, {'target': [u'samaka']})
storeunit = dbunit.getorig()
self.assertEqual(len(storeunit.target.strings), 2)
dbunit = self._update_translation(2, {'target': u''})
self.assertEqual(len(storeunit.target.strings), 2)
def test_update_plural_target(self):
dbunit = self._update_translation(2, {'target': [u'samaka', u'samak']})
storeunit = dbunit.getorig()
self.assertEqual(dbunit.target.strings, [u'samaka', u'samak'])
self.assertEqual(dbunit.target.strings, storeunit.target.strings)
pofile = factory.getobject(self.store.file.path)
self.assertEqual(dbunit.target.strings, pofile.units[dbunit.index].target.strings)
self.assertEqual(dbunit.target, u'samaka')
self.assertEqual(dbunit.target, storeunit.target)
self.assertEqual(dbunit.target, pofile.units[dbunit.index].target)
def test_update_plural_target_dict(self):
dbunit = self._update_translation(2, {'target': {0: u'samaka', 1: u'samak'}})
storeunit = dbunit.getorig()
self.assertEqual(dbunit.target.strings, [u'samaka', u'samak'])
self.assertEqual(dbunit.target.strings, storeunit.target.strings)
pofile = factory.getobject(self.store.file.path)
self.assertEqual(dbunit.target.strings, pofile.units[dbunit.index].target.strings)
self.assertEqual(dbunit.target, u'samaka')
self.assertEqual(dbunit.target, storeunit.target)
self.assertEqual(dbunit.target, pofile.units[dbunit.index].target)
def test_update_fuzzy(self):
dbunit = self._update_translation(0, {'target': u'samaka', 'fuzzy': True})
storeunit = dbunit.getorig()
self.assertTrue(dbunit.isfuzzy())
self.assertEqual(dbunit.isfuzzy(), storeunit.isfuzzy())
pofile = factory.getobject(self.store.file.path)
self.assertEqual(dbunit.isfuzzy(), pofile.units[dbunit.index].isfuzzy())
time.sleep(1)
dbunit = self._update_translation(0, {'fuzzy': False})
storeunit = dbunit.getorig()
self.assertFalse(dbunit.isfuzzy())
self.assertEqual(dbunit.isfuzzy(), storeunit.isfuzzy())
pofile = factory.getobject(self.store.file.path)
self.assertEqual(dbunit.isfuzzy(), pofile.units[dbunit.index].isfuzzy())
def test_update_comment(self):
dbunit = self._update_translation(0, {'translator_comment': u'7amada'})
storeunit = dbunit.getorig()
self.assertEqual(dbunit.getnotes(origin="translator"), u'7amada')
self.assertEqual(dbunit.getnotes(origin="translator"), storeunit.getnotes(origin="translator"))
pofile = factory.getobject(self.store.file.path)
self.assertEqual(dbunit.getnotes(origin="translator"), pofile.units[dbunit.index].getnotes(origin="translator"))
class SuggestionTests(PootleTestCase):
def setUp(self):
super(SuggestionTests, self).setUp()
self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po")
def test_hash(self):
unit = self.store.getitem(0)
suggestion = unit.add_suggestion("gras")
first_hash = suggestion.target_hash
suggestion.translator_comment = "my nice comment"
second_hash = suggestion.target_hash
assert first_hash != second_hash
suggestion.target = "gras++"
assert first_hash != second_hash != suggestion.target_hash
class StoreTests(PootleTestCase):
def setUp(self):
super(StoreTests, self).setUp()
self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po")
def test_quickstats(self):
statscache = statsdb.StatsCache()
dbstats = self.store.getquickstats()
filestats = statscache.filetotals(self.store.file.path)
self.assertEqual(dbstats['total'], filestats['total'])
self.assertEqual(dbstats['totalsourcewords'], filestats['totalsourcewords'])
self.assertEqual(dbstats['untranslated'], filestats['untranslated'])
self.assertEqual(dbstats['untranslatedsourcewords'], filestats['untranslatedsourcewords'])
self.assertEqual(dbstats['fuzzy'], filestats['fuzzy'])
self.assertEqual(dbstats['fuzzysourcewords'], filestats['fuzzysourcewords'])
self.assertEqual(dbstats['translated'], filestats['translated'])
self.assertEqual(dbstats['translatedsourcewords'], filestats['translatedsourcewords'])
self.assertEqual(dbstats['translatedtargetwords'], filestats['translatedtargetwords'])
class XHRTestAnonymous(PootleTestCase):
"""
Base class for testing the XHR views.
"""
def setUp(self):
# FIXME: We should test on a bigger dataset (with a fixture maybe)
super(XHRTestAnonymous, self).setUp()
self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po")
self.unit = self.store.units[0]
self.uid = self.unit.id
self.bad_uid = 69696969
self.path = self.store.pootle_path
self.bad_path = "/foo/bar/baz.po"
self.post_data = {'id': self.uid,
'index': 1,
'path': self.path,
'pootle_path': self.path,
'store': self.path,
'source_f_0': 'fish',
'target_f_0': 'arraina'}
#
# Tests for the get_view_units() view.
#
def test_get_view_units_response_ok(self):
"""AJAX request, should return HTTP 200."""
r = self.client.get("%(pootle_path)s/view" %\
{'pootle_path': self.path},
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
def test_get_view_units_bad_store(self):
"""Checks for store correctness when passing an invalid path."""
r = self.client.get("%(pootle_path)s/view" %\
{'pootle_path': self.bad_path},
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 404)
#
# Tests for the get_more_context() view.
#
def test_get_more_context_response_ok(self):
"""AJAX request, should return HTTP 200."""
r = self.client.get("/unit/context/%s" % self.uid,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
def test_get_more_context_bad_unit(self):
"""Checks for store correctness when passing an invalid uid."""
r = self.client.get("/unit/context/%s" % self.bad_uid,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 404)
def test_get_more_context_bad_store_unit(self):
"""Checks for store/unit correctness when passing an invalid path/uid."""
r = self.client.get("/unit/context/%s" % self.bad_uid,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 404)
#
# Tests for the get_edit_unit() view.
#
def test_get_edit_unit_response_ok(self):
"""AJAX request, should return HTTP 200."""
r = self.client.get("/unit/edit/%s" % self.uid,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
def test_get_edit_unit_bad_unit(self):
"""Checks for unit correctness when passing an invalid uid."""
r = self.client.get("/unit/edit/%s" % self.bad_uid,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 404)
def test_get_edit_unit_bad_store_unit(self):
"""Checks for store/unit correctness when passing an invalid path/uid."""
r = self.client.get("/unit/edit/%s" % self.bad_uid,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 404)
def test_get_edit_unit_good_response(self):
"""Checks for returned data correctness."""
r = self.client.get("/unit/edit/%s" % self.uid,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
self.assertTemplateUsed(r, 'unit/edit.html')
#
# Tests for the get_failing_checks() view.
#
def test_get_failing_checks_response_ok(self):
"""AJAX request, should return HTTP 200."""
r = self.client.get("%(pootle_path)s/checks/" %\
{'pootle_path': self.path},
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
def test_get_failing_checks_bad_store(self):
"""Checks for store correctness when passing an invalid path."""
r = self.client.get("%(pootle_path)s/checks/" %\
{'pootle_path': self.bad_path},
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 404)
#
# Tests for the process_submit() view.
#
def test_process_submit_response_ok(self):
"""AJAX request, should return HTTP 200."""
for m in ("submission", "suggestion"):
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.uid, 'method': m},
self.post_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
def test_process_submit_bad_unit(self):
"""Checks for unit correctness when passing an invalid uid."""
for m in ("submission", "suggestion"):
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.bad_uid, 'method': m},
self.post_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
j = json.loads(r.content)
self.assertTrue('captcha' in j.keys())
def test_process_submit_bad_store_unit(self):
"""Checks for store/unit correctness when passing an invalid path/uid."""
for m in ("submission", "suggestion"):
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.bad_uid, 'method': m},
self.post_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
j = json.loads(r.content)
self.assertTrue('captcha' in j.keys())
def test_process_submit_bad_form(self):
"""Checks for form correctness when bad POST data is passed."""
form_data = self.post_data
del(form_data['index'])
for m in ("submission", "suggestion"):
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.uid, 'method': m},
form_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
j = json.loads(r.content)
self.assertTrue('captcha' in j.keys())
def test_process_submit_good_response(self):
"""Checks for returned data correctness."""
for m in ("submission", "suggestion"):
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.uid, 'method': m},
self.post_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
j = json.loads(r.content)
self.assertTrue('captcha' in j.keys())
class XHRTestNobody(XHRTestAnonymous):
"""
Tests the XHR views as a non-privileged user.
"""
username = 'nonpriv'
password = 'nonpriv'
def setUp(self):
super(XHRTestNobody, self).setUp()
self.client.login(username=self.username, password=self.password)
def test_process_submit_bad_unit(self):
"""Checks for unit correctness when passing an invalid uid."""
for m in ("submission", "suggestion"):
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.bad_uid, 'method': m},
self.post_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 404)
def test_process_submit_bad_store_unit(self):
"""Checks for store/unit correctness when passing an invalid path/uid."""
for m in ("submission", "suggestion"):
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.bad_uid, 'method': m},
self.post_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 404)
def test_process_submit_bad_form(self):
"""Checks for form correctness when bad POST data is passed."""
form_data = self.post_data
del(form_data['index'])
for m in ("submission", "suggestion"):
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.uid, 'method': m},
form_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 400)
def test_process_submit_good_response(self):
"""Checks for returned data correctness."""
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.uid, 'method': "suggestion"}, self.post_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
unit = Unit.objects.get(id=self.uid)
sugg = unit.get_suggestions()[0]
self.assertEqual(sugg.target, self.post_data['target_f_0'])
r = self.client.post("/unit/process/%(uid)s/%(method)s" %\
{'uid': self.uid, 'method': "submission"}, self.post_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(r.status_code, 200)
unit = Unit.objects.get(id=self.uid)
self.assertEqual(unit.target, self.post_data['target_f_0'])
class XHRTestAdmin(XHRTestNobody):
"""
Tests the XHR views as admin user.
"""
username = 'admin'
password = 'admin'
| arky/pootle-dev | pootle/apps/pootle_store/tests.py | Python | gpl-2.0 | 17,327 |
<?php
/*------------------------------------------------------------------------
# com_localise - Localise
# ------------------------------------------------------------------------
# author Mohammad Hasani Eghtedar <m.h.eghtedar@gmail.com>
# copyright Copyright (C) 2010 http://joomlacode.org/gf/project/com_localise/. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://joomlacode.org/gf/project/com_localise/
# Technical Support: Forum - http://joomlacode.org/gf/project/com_localise/forum/
-------------------------------------------------------------------------*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
$document = & JFactory::getDocument();
$document->setTitle(JText::_('COM_LOCALISE_LOCALISE') . " - " . JText::_('COM_LOCALISE_PACKAGE'));
| bcnu/aptopnews | administrator/components/com_localise/views/package/tmpl/default_document.php | PHP | gpl-2.0 | 834 |
/**
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
import classNames from "classnames";
import React from "react";
import { useSection, withSection } from "@library/layout/LayoutContext";
import { ILayoutContainer } from "@library/layout/components/interface.layoutContainer";
export function Panel(props: ILayoutContainer) {
const Tag = (props.tag as "div") || "div";
return (
<Tag
className={classNames(useSection().classes.panel, props.className)}
aria-hidden={props.ariaHidden}
ref={props.innerRef}
>
{props.children}
</Tag>
);
}
export default withSection(Panel);
| vanilla/vanilla | library/src/scripts/layout/components/Panel.tsx | TypeScript | gpl-2.0 | 682 |
<?php defined('SYSPATH') or die('No direct script access.');
/**
* SwiftMailer driver, used with the email helper.
*
* @see http://www.swiftmailer.org/wikidocs/v3/connections/nativemail
* @see http://www.swiftmailer.org/wikidocs/v3/connections/sendmail
* @see http://www.swiftmailer.org/wikidocs/v3/connections/smtp
*
* Valid drivers are: native, sendmail, smtp
*/
$config['driver'] = 'native';
/**
* To use secure connections with SMTP, set "port" to 465 instead of 25.
* To enable TLS, set "encryption" to "tls".
*
* Driver options:
* @param null native: no options
* @param string sendmail: executable path, with -bs or equivalent attached
* @param array smtp: hostname, (username), (password), (port), (auth), (encryption)
*/
$config['options'] = NULL;
| boudewijnrempt/HyvesDesktop | 3rdparty/socorro/webapp-php/system/config/email.php | PHP | gpl-2.0 | 786 |
<?php
namespace estoque\Http\Controllers;
use Illuminate\Http\Request;
use estoque\Http\Requests;
use estoque\Http\Controllers\Controller;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
return view('home');
}
}
| Thiago-Cardoso/treinamento-Laravel5.1 | app/Http/Controllers/HomeController.php | PHP | gpl-2.0 | 456 |
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import java.util.Map;
import java.util.Iterator;
import SimpleOpenNI.*;
import java.util.Random;
import java.net.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class masterB extends PApplet {
SimpleOpenNI context;
OPC opc;
float dx, dy;
int test = 0;
int numSketches = 4;
int numPixels = 60; //per ring
float angleOfFirst = PI;
//For Spinning Pixels
int[] spinHue;
int backgroundBright = 0;
int backgroundSat = 0;
int backgroundSpinHue = 0;
int numSpinners = 30;
int spinCounter = 0;
int spinSat = 100;
int shapeCounter[];
int randomPixel[];
int speed = 1;
int numInThreshold1 = 0;
int numInThreshold2 = 0;
int numInThreshold3 = 0;
PVector[] spinCircle = new PVector[numSpinners];
shapeClass[][] spinningDots;
PVector[] spinDot = new PVector[numSpinners];
//
//For fading circles
boolean personOnLeft = false;
boolean personOnRight = false;
boolean leftChanged = false;
boolean rightChanged = false;
int numFaders = 30;
shapeClass[][] fadingDots;
PVector[] fadeCircle = new PVector[numFaders];
PVector[] fadeDot = new PVector[numFaders];
int[] fadeHue = new int[numFaders];
int[] fadeSat = new int[numFaders];
int[] faderBrightnesses = new int[numFaders];
boolean[] increaseBrightnesses = new boolean[numFaders];
int initIncBright = 0;
int[] oldHue = new int[numFaders];
int faderBrightness = 1;
boolean increaseBrightness = true;
//
//For depthThreshold
PImage display;
PImage flipped;
int depthHue = 0;
int depthSat = 100;
int depthBri = 100;
int backgroundHue = 50;//
int hue = 0;
int brightness = 0;
boolean backwards = false;
int numShapes = 1;
int counter = 0;
boolean firstPass = true;
Random randomGenerator = new Random();
char direction;
PVector circle = new PVector();
PVector circle2 = new PVector();
shapeClass[] dots;
shapeClass[] dots2;
shapeClass[][][] dotsArray = new shapeClass[8][8][numPixels];
int pixelCounter = 0;
PVector dot = new PVector();
PVector dot2 = new PVector();
float radius;
PVector blank;
public void setup()
{
context = new SimpleOpenNI(0, this);
context.enableDepth();
blank = new PVector();
blank.x = 0;
blank.y = 0;
//Use height for width and height to draw square window
size(240, 240);
// Connect to the local instance of fcserver
opc = new OPC(this, "127.0.0.1", 7891);
// Map an 8x8 grid of rings of LEDs to the center of the window
int numPixelsPerRing = numPixels;
opc.ledRingGrid(width, height, numPixelsPerRing);
colorMode(HSB, 100);
background(0, 0, 0);
///Fading initialization
fadingDots = new shapeClass[numFaders][numPixels];
for (int i=0; i<numFaders; i++)
{
fadeCircle[i] = new PVector();
fadeCircle[i].x = width/16 + (width/8 * (int)random(8));
fadeCircle[i].y = height/16 + (height/8 * (int)random(8));
fadeDot[i] = new PVector();
fadeHue[i] = (int)random(100);
oldHue[i] = fadeHue[i];
fadeSat[i] = 100;
faderBrightnesses[i] = (int)random(100);
initIncBright = (int)random(1);
if (initIncBright == 1)
increaseBrightnesses[i] = true;
else
increaseBrightnesses[i] = false;
for (int j=0; j<numPixels; j++)
fadingDots[i][j] = new shapeClass(color(0, 0, 0), blank);
}
///
////Spinner initialization
spinHue = new int[numSpinners];
shapeCounter = new int[numSpinners];
randomPixel = new int[numSpinners];
spinningDots = new shapeClass[numSpinners][numPixels];
for (int i=0; i<numSpinners; i++)
{
spinCircle[i] = new PVector();
spinCircle[i].x = width/16 + (width/8 * (int)random(8));
spinCircle[i].y = height/16 + (height/8 * (int)random(8));
spinDot[i] = new PVector();
randomPixel[i] = (int)random(numPixels);
spinHue[i] = (int)random(100);
for (int j=0; j<numPixels; j++)
{
spinningDots[i][j] = new shapeClass(color(0, 0, 0), blank);
}
}
////
opc.setStatusLed(false);
radius = ((width + height) / 2) / 20;
}
float noiseScale=0.02f;
public float fractalNoise(float x, float y, float z) {
float r = 0;
float amp = 1.0f;
for (int octave = 0; octave < 4; octave++) {
r += noise(x, y, z) * amp;
amp /= 2;
x *= 2;
y *= 2;
z *= 2;
}
return r;
}
public void draw()
{
if (hour() >= 5 && hour() < 23)
{
//Fading Circles
if (minute() % 15 >= 10)
// if(test == 1)
{
background(0, 0, 0);
context.update();
for (int x = 0; x < context.depthWidth (); x++) {
for (int y = 0; y < context.depthHeight (); y++) {
// mirroring image
int offset = x + y * context.depthWidth();
int[] depthValues = context.depthMap();
int rawDepth = depthValues[offset];
//only get the pixel corresponding to a certain depth
int depthmin=0;
int depthmax=3000;
if (rawDepth < depthmax && rawDepth > depthmin) {
if ((x % 640) < 320)
personOnLeft = true;
if ((x % 640) > 320)
personOnRight = true;
}
}
}
for (int i=0; i<numFaders; i++)
{
if (faderBrightnesses[i] >= 100)
increaseBrightnesses[i] = false;
else if (faderBrightnesses[i] <= 0)
increaseBrightnesses[i] = true;
if (increaseBrightnesses[i] == true)
faderBrightnesses[i]+=5;
else if (increaseBrightnesses[i] == false)
faderBrightnesses[i]-=5;
}
for (int i=0; i<numFaders; i++)
{
for (int j=0; j<numPixels; j++)
{
float a = angleOfFirst + j * 2 * PI / numPixels;
fadeDot[i].x = (int)(fadeCircle[i].x - radius * cos(a) + 0.5f);
fadeDot[i].y = (int)(fadeCircle[i].y - radius * sin(a) + 0.5f);
if (personOnLeft == true)
{
if (fadeCircle[i].x < width/2)
{
fadeHue[i] = (int)random(100);
leftChanged = true;
}
}
if (personOnLeft == false && leftChanged == true)
{
fadeHue[i] = oldHue[i];
if (i == numFaders)
leftChanged = false;
}
if (personOnRight == true)
{
if (fadeCircle[i].x > width/2)
{
fadeHue[i] = (int)random(100);
rightChanged = true;
}
}
if (personOnRight == false && rightChanged == true && leftChanged == false)
{
fadeHue[i] = oldHue[i];
if (i == numFaders)
rightChanged = false;
}
fadingDots[i][j] = new shapeClass(color(fadeHue[i], fadeSat[i], faderBrightnesses[i]), fadeDot[i]);
fadingDots[i][j].display();
}
}
for (int i=0; i<numFaders; i++)
{
if (faderBrightnesses[i] == 0)
{
fadeCircle[i].x = width/16 + (width/8 * (int)random(8));
fadeCircle[i].y = height/16 + (height/8 * (int)random(8));
fadeHue[i] = (int)random(100);
oldHue[i] = fadeHue[i];
fadeSat[i] = 100;
for (int k=0; k<numFaders; k++)
{
if (k != i)
{
while ( (fadeCircle[i].x == fadeCircle[k].x) && (fadeCircle[i].y == fadeCircle[k].y))
{
fadeCircle[i].x = width/16 + (width/8 * (int)random(8));
fadeCircle[i].y = height/16 + (height/8 * (int)random(8));
}
}
}
}
}
personOnLeft = false;
personOnRight = false;
}
//Clouds
if (minute() % 15 <= 5) {
// if(test == 1) {
long now = millis();
float speed = 0.002f;
float angle = sin(now * 0.001f);
float z = now * 0.00008f;
float hue = now * 0.01f;
float scale = 0.005f;
int brightnessScale = 100;
context.update();
for (int x = 0; x < context.depthHeight (); x++) {
for (int y = 0; y < context.depthHeight (); y++) {
// mirroring image
int offset = context.depthWidth()-x-1+y*context.depthWidth();
int[] depthValues = context.depthMap();
int rawDepth = depthValues[offset];
int pix = x + y * context.depthWidth();
//only get the pixel corresponding to a certain depth
int depthmin1 = 0;
int depthmax1 = 2000;
if (rawDepth < depthmax1 && rawDepth > depthmin1)
speed = 0.005f;
int depthmin2=2000;
int depthmax2=3000;
if (rawDepth < depthmax2 && rawDepth > depthmin2)
speed = 0.004f;
int depthmin3 = 3000;
int depthmax3 = 3500;
if (rawDepth < depthmax3 && rawDepth > depthmin3)
speed = 0.003f;
}
}
dx += cos(angle) * speed;
dy += sin(angle) * speed;
loadPixels();
for (int x=0; x < width; x++) {
for (int y=0; y < height; y++) {
float n = fractalNoise(dx + x*scale, dy + y*scale, z) - 0.75f;
float m = fractalNoise(dx + x*scale, dy + y*scale, z + 10.0f) - 0.75f;
int c = color(
(hue + 80.0f * m) % 100.0f,
100 - 100 * constrain(pow(3.0f * n, 3.5f), 0, 0.9f),
brightnessScale * constrain(pow(3.0f * n, 1.5f), 0, 0.9f)
);
pixels[x + width*y] = c;
}
}
updatePixels();
}
//Xtion Depth Threshold
if ((minute() % 15) >= 5 && (minute() % 15) < 10)
// if(test == 0)
{
context.update();
display = context.depthImage();
display.loadPixels();
flipped = createImage(display.width, display.height, HSB);
flipped.loadPixels();
//loop to select a depthzone
for (int x = 0; x < context.depthWidth (); x++) {
for (int y = 0; y < context.depthHeight (); y++) {
// mirroring image
int offset = context.depthWidth()-x-1+y*context.depthWidth();
int[] depthValues = context.depthMap();
int rawDepth = depthValues[offset];
int pix = x + y * context.depthWidth();
//only get the pixel corresponding to a certain depth
int depthmin=0;
int depthmax=3530;
if (rawDepth < depthmax && rawDepth > depthmin) {
display.pixels[pix] = color(depthHue, depthSat, depthBri);
/* hue+=10;
bri+=1;
if(hue>=100) {
hue=0;
}
if(bri>=100)
bri=50;
*/
} else
display.pixels[pix] = color(backgroundHue, 50, 50);
}
}
for(int x = 0; x < context.depthWidth(); x++)
{
for(int y = 0; y < context.depthHeight(); y++)
{
int pix = x + y * context.depthWidth();
int pixInv = (context.depthWidth() - x - 1) + (context.depthHeight() - y - 1) * context.depthWidth();
flipped.pixels[pixInv] = display.pixels[pix];
}
}
image(flipped, 0, 0, width*1.333333333f, height);
depthHue++;
if (depthHue==100)
depthHue=0;
backgroundHue++;
if (backgroundHue==100)
backgroundHue=0;
}
/*
//Spinning Dots
if ((minute() % 20 >= 15) && (minute() % 20 < 20))
if(test == 0)
{
background(backgroundSpinHue, backgroundSat, backgroundBright);
context.update();
display = context.depthImage();
display.loadPixels();
for (int x = 0; x < context.depthHeight (); x++) {
for (int y = 0; y < context.depthHeight (); y++) {
// mirroring image
int offset = context.depthWidth()-x-1+y*context.depthWidth();
int[] depthValues = context.depthMap();
int rawDepth = depthValues[offset];
int pix = x + y * context.depthWidth();
//only get the pixel corresponding to a certain depth
int depthmin2=2000;
int depthmax2=3000;
if (rawDepth < depthmax2 && rawDepth > depthmin2) {
// display.pixels[pix] = color(depthHue%100, depthSat, depthBri);
numInThreshold2++;
} else
display.pixels[pix] = color(0);
int depthmin1 = 0;
int depthmax1 = 2000;
if (rawDepth < depthmax1 && rawDepth > depthmin1)
numInThreshold1++;
int depthmin3 = 3000;
int depthmax3 = 3500;
if (rawDepth < depthmax3 && rawDepth > depthmin3)
numInThreshold3++;
}
}
// display.updatePixels();
// image(display, 0, 0, width*1.333333, height);
depthHue++;
if (numInThreshold1 < 10000 && numInThreshold2 < 10000 && numInThreshold3 < 35000)
speed=1;
if (numInThreshold3 > 35000 && numInThreshold3 > numInThreshold2 && numInThreshold3 > numInThreshold1)
speed=2;
if (numInThreshold2 > 10000 && numInThreshold2 > numInThreshold1 && numInThreshold2 > numInThreshold3)
speed=3;
if (numInThreshold1 > 10000 && numInThreshold1 > numInThreshold2 && numInThreshold1 > numInThreshold2)
speed=4;
//assign idividual dot positions from circle center point position
for (int i=0; i<numSpinners; i++)
{
shapeCounter[i]++;
float a = angleOfFirst + ((spinCounter + randomPixel[i]) % numPixels) * 2 * PI / numPixels * speed;
spinDot[i].x = (int)(spinCircle[i].x - radius * cos(a) + 0.5);
spinDot[i].y = (int)(spinCircle[i].y - radius * sin(a) + 0.5);
}
//create the dots from positions
for (int i=0; i<numSpinners; i++)
spinningDots[i][spinCounter%numPixels] = new shapeClass(color(spinHue[i], spinSat, 100), spinDot[i]);
//display all dots
for (int i=0; i<numSpinners; i++)
{
for (int j=0; j<numPixels; j++)
spinningDots[i][j].display();
}
if (spinCounter%5==0) {
for (int i=0; i<numSpinners; i++) {
spinHue[i]++;
if (spinHue[i] == 100)
spinHue[i] = 0;
}
}
spinCounter++;
if (spinCounter == numPixels*4)
spinCounter = 0;
for (int i=0; i<numSpinners; i++)
{
if (shapeCounter[i]%5 == (int)random(5) && spinCounter%numPixels == 0)
{
spinCircle[i].x = width/16 + (width/8 * (int)random(8));
spinCircle[i].y = height/16 + (height/8 * (int)random(8));
randomPixel[i] = (int)random(numPixels);
//check to make sure dots aren't on top of each other
for (int k=0; k<numSpinners; k++)
{
if (k != i)
{
while ( (spinCircle[i].x == spinCircle[k].x) && (spinCircle[i].y == spinCircle[k].y))
{
spinCircle[i].x = width/16 + (width/8 * (int)random(8));
spinCircle[i].y = height/16 + (height/8 * (int)random(8));
}
}
}
for (int j=0; j<numPixels; j++)
{
float a = angleOfFirst + j * 2 * PI / numPixels;
spinDot[i].x = (int)(spinCircle[i].x - radius * cos(a) + 0.5);
spinDot[i].y = (int)(spinCircle[i].y - radius * sin(a) + 0.5);
}
}
}
numInThreshold1 = 0;
numInThreshold2 = 0;
numInThreshold3 = 0;
}
*/
} else
background(0, 0, 0);
}
class shapeClass
{
int colour;
PVector pos;
shapeClass(int colour, PVector pos)
{
this.colour = colour;
this.pos = pos;
}
public void display()
{
smooth();
fill(colour);
strokeWeight(0);
ellipseMode(CENTER);
// ellipse(pos.x - 40, pos.y - 40, 50, 50);
// println("shape.x: " + pos.x);
// println("shape.y: " + pos.y);
ellipse(pos.x, pos.y, 3, 3);
}
}
/*
* Simple Open Pixel Control client for Processing,
* designed to sample each LED's color from some point on the canvas.
*
* Micah Elizabeth Scott, 2013
* This file is released into the public domain.
*/
public class OPC
{
Socket socket;
OutputStream output;
String host;
int port;
int[] pixelLocations;
byte[] packetData;
byte firmwareConfig;
String colorCorrection;
boolean enableShowLocations;
OPC(PApplet parent, String host, int port)
{
this.host = host;
this.port = port;
this.enableShowLocations = true;
parent.registerDraw(this);
}
// Set the location of a single LED
public void led(int index, int x, int y)
{
// For convenience, automatically grow the pixelLocations array. We do want this to be an array,
// instead of a HashMap, to keep draw() as fast as it can be.
if (pixelLocations == null) {
pixelLocations = new int[index + 1];
} else if (index >= pixelLocations.length) {
pixelLocations = Arrays.copyOf(pixelLocations, index + 1);
}
pixelLocations[index] = x + width * y;
}
// Set the locations of a ring of LEDs. The center of the ring is at (x, y),
// with "radius" pixels between the center and each LED. The first LED is at
// the indicated angle, in radians, measured clockwise from +X.
public void ledRing(int index, int count, float x, float y, float radius, float angle, boolean inverted)
{
float pi = PI;
if(inverted == true)
pi *= -1;
for (int i = 0; i < count; i++) {
float a = angle + i * 2 * pi / count;
led(index + i, (int)(x - radius * cos(a) + 0.5f),
(int)(y - radius * sin(a) + 0.5f));
}
}
//Draws an 8x8 grid of pixel rings.
//Grid is drawn column by column, starting at the bottom left,
//and is relative to screen size.
public void ledRingGrid(int screenWidth, int screenHeight, int numPixels)
{
int xPosition = screenWidth / 16;
int index = 0;
float radius = ((screenWidth + screenHeight) / 2) / 20;
float angleOfFirstPixel = PI;
boolean inverted = false;
if(numPixels == 16)
inverted = true;
for(int x = 0; x < 8; x++)
{
int yPosition = screenHeight - (screenHeight / 16);
for(int y = 0; y < 8; y++)
{
ledRing(index, numPixels, xPosition, yPosition, radius, angleOfFirstPixel, inverted);
yPosition -= screenHeight / 8;
index += numPixels;
}
xPosition += screenHeight / 8;
}
}
// Should the pixel sampling locations be visible? This helps with debugging.
// Showing locations is enabled by default. You might need to disable it if our drawing
// is interfering with your processing sketch, or if you'd simply like the screen to be
// less cluttered.
public void showLocations(boolean enabled)
{
enableShowLocations = enabled;
}
// Enable or disable dithering. Dithering avoids the "stair-stepping" artifact and increases color
// resolution by quickly jittering between adjacent 8-bit brightness levels about 400 times a second.
// Dithering is on by default.
public void setDithering(boolean enabled)
{
if (enabled)
firmwareConfig &= ~0x01;
else
firmwareConfig |= 0x01;
sendFirmwareConfigPacket();
}
// Enable or disable frame interpolation. Interpolation automatically blends between consecutive frames
// in hardware, and it does so with 16-bit per channel resolution. Combined with dithering, this helps make
// fades very smooth. Interpolation is on by default.
public void setInterpolation(boolean enabled)
{
if (enabled)
firmwareConfig &= ~0x02;
else
firmwareConfig |= 0x02;
sendFirmwareConfigPacket();
}
// Put the Fadecandy onboard LED under automatic control. It blinks any time the firmware processes a packet.
// This is the default configuration for the LED.
public void statusLedAuto()
{
firmwareConfig &= 0x0C;
sendFirmwareConfigPacket();
}
// Manually turn the Fadecandy onboard LED on or off. This disables automatic LED control.
public void setStatusLed(boolean on)
{
firmwareConfig |= 0x04; // Manual LED control
if (on)
firmwareConfig |= 0x08;
else
firmwareConfig &= ~0x08;
sendFirmwareConfigPacket();
}
// Set the color correction parameters
public void setColorCorrection(float gamma, float red, float green, float blue)
{
colorCorrection = "{ \"gamma\": " + gamma + ", \"whitepoint\": [" + red + "," + green + "," + blue + "]}";
sendColorCorrectionPacket();
}
// Set custom color correction parameters from a string
public void setColorCorrection(String s)
{
colorCorrection = s;
sendColorCorrectionPacket();
}
// Send a packet with the current firmware configuration settings
public void sendFirmwareConfigPacket()
{
if (output == null) {
// We'll do this when we reconnect
return;
}
byte[] packet = new byte[9];
packet[0] = 0; // Channel (reserved)
packet[1] = (byte)0xFF; // Command (System Exclusive)
packet[2] = 0; // Length high byte
packet[3] = 5; // Length low byte
packet[4] = 0x00; // System ID high byte
packet[5] = 0x01; // System ID low byte
packet[6] = 0x00; // Command ID high byte
packet[7] = 0x02; // Command ID low byte
packet[8] = firmwareConfig;
try {
output.write(packet);
} catch (Exception e) {
dispose();
}
}
// Send a packet with the current color correction settings
public void sendColorCorrectionPacket()
{
if (colorCorrection == null) {
// No color correction defined
return;
}
if (output == null) {
// We'll do this when we reconnect
return;
}
byte[] content = colorCorrection.getBytes();
int packetLen = content.length + 4;
byte[] header = new byte[8];
header[0] = 0; // Channel (reserved)
header[1] = (byte)0xFF; // Command (System Exclusive)
header[2] = (byte)(packetLen >> 8);
header[3] = (byte)(packetLen & 0xFF);
header[4] = 0x00; // System ID high byte
header[5] = 0x01; // System ID low byte
header[6] = 0x00; // Command ID high byte
header[7] = 0x01; // Command ID low byte
try {
output.write(header);
output.write(content);
} catch (Exception e) {
dispose();
}
}
// Automatically called at the end of each draw().
// This handles the automatic Pixel to LED mapping.
// If you aren't using that mapping, this function has no effect.
// In that case, you can call setPixelCount(), setPixel(), and writePixels()
// separately.
public void draw()
{
if (pixelLocations == null) {
// No pixels defined yet
return;
}
if (output == null) {
// Try to (re)connect
connect();
}
if (output == null) {
return;
}
int numPixels = pixelLocations.length;
int ledAddress = 4;
setPixelCount(numPixels);
loadPixels();
for (int i = 0; i < numPixels; i++) {
int pixelLocation = pixelLocations[i];
int pixel = pixels[pixelLocation];
packetData[ledAddress] = (byte)(pixel >> 16);
packetData[ledAddress + 1] = (byte)(pixel >> 8);
packetData[ledAddress + 2] = (byte)pixel;
ledAddress += 3;
if (enableShowLocations) {
pixels[pixelLocation] = 0xFFFFFF ^ pixel;
}
}
writePixels();
if (enableShowLocations) {
updatePixels();
}
}
// Change the number of pixels in our output packet.
// This is normally not needed; the output packet is automatically sized
// by draw() and by setPixel().
public void setPixelCount(int numPixels)
{
int numBytes = 3 * numPixels;
int packetLen = 4 + numBytes;
if (packetData == null || packetData.length != packetLen) {
// Set up our packet buffer
packetData = new byte[packetLen];
packetData[0] = 0; // Channel
packetData[1] = 0; // Command (Set pixel colors)
packetData[2] = (byte)(numBytes >> 8);
packetData[3] = (byte)(numBytes & 0xFF);
}
}
// Directly manipulate a pixel in the output buffer. This isn't needed
// for pixels that are mapped to the screen.
public void setPixel(int number, int c)
{
int offset = 4 + number * 3;
if (packetData == null || packetData.length < offset + 3) {
setPixelCount(number + 1);
}
packetData[offset] = (byte) (c >> 16);
packetData[offset + 1] = (byte) (c >> 8);
packetData[offset + 2] = (byte) c;
}
// Read a pixel from the output buffer. If the pixel was mapped to the display,
// this returns the value we captured on the previous frame.
public int getPixel(int number)
{
int offset = 4 + number * 3;
if (packetData == null || packetData.length < offset + 3) {
return 0;
}
return (packetData[offset] << 16) | (packetData[offset + 1] << 8) | packetData[offset + 2];
}
// Transmit our current buffer of pixel values to the OPC server. This is handled
// automatically in draw() if any pixels are mapped to the screen, but if you haven't
// mapped any pixels to the screen you'll want to call this directly.
public void writePixels()
{
if (packetData == null || packetData.length == 0) {
// No pixel buffer
return;
}
if (output == null) {
// Try to (re)connect
connect();
}
if (output == null) {
return;
}
try {
output.write(packetData);
} catch (Exception e) {
dispose();
}
}
public void dispose()
{
// Destroy the socket. Called internally when we've disconnected.
if (output != null) {
println("Disconnected from OPC server");
}
socket = null;
output = null;
}
public void connect()
{
// Try to connect to the OPC server. This normally happens automatically in draw()
try {
socket = new Socket(host, port);
socket.setTcpNoDelay(true);
output = socket.getOutputStream();
println("Connected to OPC server");
} catch (ConnectException e) {
dispose();
} catch (IOException e) {
dispose();
}
sendColorCorrectionPacket();
sendFirmwareConfigPacket();
}
}
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "masterB" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
| Signal-to-Noise-Media-Labs/open_windows | sketches/masterB/application.linux64/source/masterB.java | Java | gpl-2.0 | 26,791 |
<?php
/**
* @package HikaShop for Joomla!
* @version 4.4.0
* @author hikashop.com
* @copyright (C) 2010-2020 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?> <table class="admintable" width="100%">
<tr>
<td class="key">
<?php echo JText::_( 'HIKA_NAME' ); ?>
</td>
<td>
<?php
$systemOrderStatuses = array('created', 'confirmed', 'cancelled', 'refunded', 'shipped');
if(!empty($this->element->category_id) && in_array($this->element->category_name, $systemOrderStatuses) && !@$this->translation && @$this->element->category_type=='status'){ ?>
<input id="category_name" type="hidden" size="80" name="<?php echo $this->category_name_input; ?>" value="<?php echo $this->escape(@$this->element->category_name); ?>" /><?php echo $this->escape(@$this->element->category_name); ?>
<?php }else{ ?>
<input id="category_name" type="text" size="80" name="<?php echo $this->category_name_input; ?>" value="<?php echo $this->escape(@$this->element->category_name); ?>" />
<?php }
if(isset($this->category_name_published)){
$publishedid = 'published-'.$this->category_name_id;
?>
<span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_name_published,'translation') ?></span>
<?php } ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_( 'CATEGORY_DESCRIPTION' ); ?>
</td>
<td width="100%"></td>
</tr>
<tr>
<td colspan="2" width="100%">
<?php if(isset($this->category_description_published)){
$publishedid = 'published-'.$this->category_description_id;
?>
<span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_description_published,'translation') ?></span>
<br/>
<?php }
$this->editor->height = 150;
$this->editor->content = @$this->element->category_description;
echo $this->editor->display();
?>
</td>
</tr>
<?php if(empty($this->element->category_type) || in_array($this->element->category_type,array('product','manufacturer'))){ ?>
<tr>
<td class="key">
<?php echo JText::_( 'CATEGORY_META_DESCRIPTION' ); ?>
</td>
<td>
<textarea id="category_meta_description" cols="46" rows="2" name="<?php echo $this->category_meta_description_input; ?>"><?php echo $this->escape(@$this->element->category_meta_description); ?></textarea>
<?php if(isset($this->category_meta_description_published)){
$publishedid = 'published-'.$this->category_meta_description_id;
?>
<span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_meta_description_published,'translation') ?></span>
<?php } ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_( 'CATEGORY_KEYWORDS' ); ?>
</td>
<td>
<textarea id="category_keywords" cols="46" rows="1" name="<?php echo $this->category_keywords_input; ?>"><?php echo $this->escape(@$this->element->category_keywords); ?></textarea>
<?php if(isset($this->category_keywords_published)){
$publishedid = 'published-'.$this->category_keywords_id;
?>
<span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_keywords_published,'translation') ?></span>
<?php } ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_( 'PAGE_TITLE' ); ?>
</td>
<td>
<textarea id="category_page_title" cols="46" rows="2" name="<?php echo $this->category_page_title_input; ?>"><?php if(!isset($this->element->category_page_title)) $this->element->category_page_title=''; echo $this->escape(@$this->element->category_page_title); ?></textarea>
<?php if(isset($this->category_page_title_published)){
$publishedid = 'published-'.$this->category_page_title_id;
?>
<span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_page_title_published,'translation') ?></span>
<?php } ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_( 'HIKA_ALIAS' ); ?>
</td>
<td>
<textarea id="category_alias" cols="46" rows="2" name="<?php echo $this->category_alias_input; ?>"><?php if(!isset($this->element->category_alias))$this->element->category_alias=''; echo $this->escape(@$this->element->category_alias); ?></textarea>
<?php if(isset($this->category_alias_published)){
$publishedid = 'published-'.$this->category_alias_id;
?>
<span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_alias_published,'translation') ?></span>
<?php } ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_( 'PRODUCT_CANONICAL' ); ?>
</td>
<td>
<input type="text" id="category_canonical" name="<?php echo $this->category_canonical_input; ?>" value="<?php if(!isset($this->element->category_alias))$this->element->category_alias=''; echo $this->escape(@$this->element->category_canonical); ?>"/>
<?php if(isset($this->category_canonical_published)){
$publishedid = 'published-'.$this->category_canonical_id;
?>
<span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_canonical_published,'translation') ?></span>
<?php } ?>
</td>
</tr>
<?php } ?>
</table>
| emundus/v6 | administrator/components/com_hikashop/views/category/tmpl/normal.php | PHP | gpl-2.0 | 6,147 |
<?PHP
require_once "nxheader.inc.php";
// Get the Google Maps API-Key
$apikey = $cds->content->get("Google-API-Key");
// Create the Maps-API. The apikey is passed as parameter.
$maps = $cds->plugins->getApi("Google Maps API", $apikey);
$cds->layout->addToHeader($maps->printGoogleJS());
require_once $cds->path."inc/header.php";
$headline = $cds->content->get("Headline");
$body = $cds->content->get("Body");
if ($headline != "") {
echo '<h1>'.$headline.'</h1>';
br();
}
if ($body !="") {
echo $cds->content->get("Body");
br();
}
br();
if ($sma != 1) {
// add a point to the map
$maps->addAddress($cds->content->get("Address"), $cds->content->get("Address Description"));
// setup width and height and zoom factor (0-17)
$maps->setWidth(600);
$maps->setHeight(450);
$maps->zoomLevel = 2;
// setup controls
$maps->showControl = $cds->content->get("ShowControls");
// draw the map.
$maps->showMap();
} else {
echo "Address: ".$cds->content->get("Address");
br();
echo "Address Description: ".$cds->content->get("Address Description");
}
require_once $cds->path."inc/footer.php";
require_once "nxfooter.inc.php";
?> | sweih/nxr | wwwdev/map.php | PHP | gpl-2.0 | 1,192 |
<?php
/**
* @package Joomla
* @subpackage com_morfeoshow
* @copyright Copyright (C) Vamba & Matthew Thomson. All rights reserved.
* @license GNU/GPL.
* @author Vamba (.joomlaitalia.com) & Matthew Thomson (ignitejoomlaextensions.com)
* @based on com_morfeoshow
* @author Matthew Thomson (ignitejoomlaextensions.com)
* Joomla! and com_morfeoshow are free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed they include or
* are derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
defined( '_JEXEC' ) or die( 'Restricted access' );
?>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<fieldset class="adminform">
<legend><?php echo JText::_( 'Edit images description' ); ?></legend>
<table class="admintable" cellpadding="5" cellspacing="0" border="0" ">
<tr>
<td>
</td>
<td>
<img src="../images/morfeoshow/<?php echo $row->folder . '/thumbs/' . $img_row->filename; ?>" />
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<?php echo JText::_( 'Title' ); ?>
</td>
<td>
<input class="text_area" type="text" name="title" id="title" size="40"
value="<?php echo htmlspecialchars($img_row->title, ENT_QUOTES, 'UTF-8'); ?>" />
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<?php echo JText::_( 'Date' ); ?>
</td>
<td><?php echo JHTML::_('calendar', $img_row->imgdate, 'imgdate', 'imgdate', '%Y-%m-%d ', array('class'=>'inputbox', 'size'=>'25', 'maxlength'=>'19')); ?></td>
</tr>
<td width="100" align="right" class="key">
<?php echo JText::_( 'Description' ); ?>
</td>
<td>
<?php echo $editor->display( 'html', $img_row->html ,'100%',
'150', '40', '5', array('pagebreak', 'readmore', 'image') );?>
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<?php echo JText::_( 'Creator' ); ?>
</td>
<td>
<input class="text_area" type="text" name="creator" id="creator" size="40"
value="<?php echo $img_row->creator ?>" />
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<?php echo JText::_( 'Web Site Link' ); ?>
</td>
<td>
<input class="text_area" type="text" name="link" id="link" size="80"
value="<?php echo $img_row->link ?>" />
</td>
</tr>
</table>
</fieldset>
<input type="hidden" name="folder" value="<?php echo $row->folder; ?>" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="option" value="<?php echo $option ?>" />
<input type="hidden" name="cid" value="<?php echo $id ?>" />
<input type="hidden" name="id" value="<?php echo $img_row->id; ?>" />
</form> | jcorrego/graduarte | administrator/components/com_morfeoshow/view/editphoto.php | PHP | gpl-2.0 | 2,901 |
<?php
/*
** ZABBIX
** Copyright (C) 2000-2005 SIA Zabbix
**
** 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.
**/
?>
<?php
class CTriggersInfo extends CTable
{
/*
var $style;
var $show_header;
var $nodeid;*/
function CTriggersInfo($style = STYLE_HORISONTAL)
{
$this->style = null;
parent::CTable(NULL,"triggers_info");
$this->SetOrientation($style);
$this->show_header = true;
$this->nodeid = get_current_nodeid();
}
function SetOrientation($value)
{
if($value != STYLE_HORISONTAL && $value != STYLE_VERTICAL)
return $this->error("Incorrect value for SetOrientation [$value]");
$this->style = $value;
}
function SetNodeid($nodeid)
{
$this->nodeid = (int)$nodeid;
}
function HideHeader()
{
$this->show_header = false;
}
function BodyToString()
{
global $USER_DETAILS;
$this->CleanItems();
$ok = $uncn = $info = $warn = $avg = $high = $dis = 0;
$db_priority = DBselect("select t.priority,t.value,count(*) as cnt from triggers t,hosts h,hosts_groups hg,items i,functions f".
" where t.status=".TRIGGER_STATUS_ENABLED." and f.itemid=i.itemid ".
" and h.hostid=i.hostid and h.status=".HOST_STATUS_MONITORED." and t.triggerid=f.triggerid ".
" and i.status=".ITEM_STATUS_ACTIVE.
' and hg.hostid=h.hostid and hg.groupid in ('.get_accessible_groups_by_user($USER_DETAILS,PERM_READ_ONLY,
null, null, $this->nodeid).') '.
" group by priority,t.value");
while($row=DBfetch($db_priority))
{
switch($row["value"])
{
case TRIGGER_VALUE_TRUE:
switch($row["priority"])
{
case 1: $info += $row["cnt"]; break;
case 2: $warn += $row["cnt"]; break;
case 3: $avg += $row["cnt"]; break;
case 4: $high += $row["cnt"]; break;
case 5: $dis += $row["cnt"]; break;
default:
$uncn += $row["cnt"]; break;
}
break;
case TRIGGER_VALUE_FALSE:
$ok += $row["cnt"]; break;
default:
$uncn += $row["cnt"]; break;
}
}
if($this->show_header)
{
$header = new CCol(S_TRIGGERS_INFO,"header");
if($this->style == STYLE_HORISONTAL)
$header->SetColspan(7);
$this->AddRow($header);
}
$trok = new CCol($ok.SPACE.S_OK, "normal");
$uncn = new CCol($uncn.SPACE.S_NOT_CLASSIFIED,"unknown");
$info = new CCol($info.SPACE.S_INFORMATION, "information");
$warn = new CCol($warn.SPACE.S_WARNING, "warning");
$avg = new CCol($avg.SPACE.S_AVERAGE, "average");
$high = new CCol($high.SPACE.S_HIGH, "high");
$dis = new CCol($dis.SPACE.S_DISASTER, "disaster");
if($this->style == STYLE_HORISONTAL)
{
$this->AddRow(array($trok, $uncn, $info, $warn, $avg, $high, $dis));
}
else
{
$this->AddRow($trok);
$this->AddRow($uncn);
$this->AddRow($info);
$this->AddRow($warn);
$this->AddRow($avg);
$this->AddRow($high);
$this->AddRow($dis);
}
return parent::BodyToString();
}
}
?>
| Shmuma/z | frontends/php/include/classes/ctriggerinfo.mod.php | PHP | gpl-2.0 | 3,613 |
import java.util.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;
import java.awt.geom.*;
public class SimpleWordGame
{
public int points(String[] player, String[] dictionary)
{
Set<String> wrds = new HashSet<String>();
Set<String> dict = new HashSet<String>();
for(int i = 0; i < player.length; i++)
wrds.add(player[i]);
for(int i = 0; i < dictionary.length; i++)
dict.add(dictionary[i]);
int ans = 0;
Iterator<String> iterator = wrds.iterator();
while(iterator.hasNext()) {
String ele = iterator.next();
if(dict.contains(ele))
ans += ele.length() * ele.length();
}
return ans;
}
public static void main(String[] args)
{
long time;
int answer;
boolean errors = false;
int desiredAnswer;
time = System.currentTimeMillis();
answer = new SimpleWordGame().points(new String[]{ "apple", "orange", "strawberry" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" });
System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds");
desiredAnswer = 136;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer)
{
errors = true;
System.out.println("DOESN'T MATCH!!!!");
}
else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new SimpleWordGame().points(new String[]{ "apple" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" });
System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds");
desiredAnswer = 0;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer)
{
errors = true;
System.out.println("DOESN'T MATCH!!!!");
}
else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new SimpleWordGame().points(new String[]{ "orange", "orange" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" });
System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds");
desiredAnswer = 36;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer)
{
errors = true;
System.out.println("DOESN'T MATCH!!!!");
}
else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new SimpleWordGame().points(new String[]{ "lidi", "o", "lidi", "gnbewjzb", "kten", "ebnelff", "gptsvqx", "rkauxq", "rkauxq", "kfkcdn"}, new String[]{ "nava", "wk", "kfkcdn", "lidi", "gptsvqx", "ebnelff", "hgsppdezet", "ulf", "rkauxq", "wcicx"});
System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds");
desiredAnswer = 186;
System.out.println("Your answer:");
System.out.println("\t" + answer);
System.out.println("Desired answer:");
System.out.println("\t" + desiredAnswer);
if (answer != desiredAnswer)
{
errors = true;
System.out.println("DOESN'T MATCH!!!!");
}
else
System.out.println("Match :-)");
System.out.println();
if (errors)
System.out.println("Some of the test cases had errors :-(");
else
System.out.println("You're a stud (at least on the test data)! :-D ");
}
}
//Powered by [KawigiEdit] 2.0!
| venkatesh551/TopCoder | older/SimpleWordGame.java | Java | gpl-2.0 | 3,588 |
<?php
//--------------------------------------------------------------------
//- File : contact/mailing_lists.php
//- Project : FVWM Home Page
//- Programmer : Uwe Pross
//--------------------------------------------------------------------
if(!isset($rel_path)) $rel_path = "./..";
//--------------------------------------------------------------------
// load some global definitions
//--------------------------------------------------------------------
if(!isset($navigation_check)) include_once($rel_path.'/definitions.inc');
//--------------------------------------------------------------------
// Site definitions
//--------------------------------------------------------------------
$title = "FVWM - Mailing Lists";
$heading = "FVWM - Mailing Lists";
$link_name = "Mailing Lists";
$link_picture = "pictures/icons/contact_mailing_list";
$parent_site = "top";
$child_sites = array();
$requested_file = basename(my_get_global("PHP_SELF", "SERVER"));
$this_site = "mailing_lists";
//--------------------------------------------------------------------
// check if we should stop here
//--------------------------------------------------------------------
if(isset($navigation_check)) return;
//--------------------------------------------------------------------
// load the layout file
//--------------------------------------------------------------------
if(!isset($site_has_been_loaded)) {
$site_has_been_loaded = "true";
include_once(sec_filename("$layout_file"));
exit();
}
decoration_window_start("Mailing lists");
?>
<p>
PLEASE ASK QUESTIONS RELATED TO XMMS ON THE XMMS MAILING LIST.
See <a href="http://xmms.org/">http://xmms.org/</a>.
</p>
<h4>The mailing list addresses are:</h4>
<ul>
<li><a href="mailto:fvwm@fvwm.org">fvwm@fvwm.org</a> (Discussion and questions list)</li>
<li><a href="mailto:fvwm-announce@fvwm.org">fvwm-announce@fvwm.org</a> (Announcement only list)</li>
<li><a href="mailto:fvwm-workers@fvwm.org">fvwm-workers@fvwm.org</a> (Beta testers and contributors list)</li>
</ul>
<p>
Please help us managing incoming mail by following a few rules
when you write to any of the fvwm related mailing list:
<ul>
<li> When quoting previous mails in a discussion, please put
your replies below the quoted portions of the text.</li>
<li> Quote all relevant parts of the original mail in a
reply.
<li> Type about 66 to 72 characters per line.</li>
<li> Insert line breaks manually, even if your email program
does it for you.</li>
<li> Always specify the fvwm version you use when asking
questions or reporting problems.</li>
</ul>
</p>
<p>
They are maintained by Jason Tibbitts, and are Majordomo based mailing
lists. To subscribe to a list, send "<code>subscribe</code>"
in the body of a message to the appropriate <code>*-request</code>
address.
</p>
<p>
To unsubscribe from the list, send "<code>unsubscribe</code>" in the
body of a message to the appropriate <code>*-request</code> address.
</p>
<h4>*-request addresses are:</h4>
<p>
<ul>
<li> <a href="mailto:fvwm-request@fvwm.org">fvwm-request@fvwm.org</a></li>
<li> <a href="mailto:fvwm-announce-request@fvwm.org">fvwm-announce-request@fvwm.org</a></li>
<li> <a href="mailto:fvwm-workers-request@fvwm.org">fvwm-workers-request@fvwm.org</a></li>
</ul>
</p>
<p>
<strong>Subscription requests sent to the list will be ignored!</strong><br>
Please follow the above instructions for subscribing properly.
</p>
<p>
To report problems with any of the mailing lists, send mail to
<a href="mailto:fvwm-owner@fvwm.org">fvwm-owner@fvwm.org</a>.
</p>
<p>
Also the mailing lists are archived:
<a href="http://www.mail-archive.com/fvwm@lists.math.uh.edu/">fvwm</a>,
<a href="http://www.mail-archive.com/fvwm-workers@lists.math.uh.edu/">fvwm-workers</a>.
</p>
<p>
<form method="GET" action="http://www.mail-archive.com/search">
<b>Search the fvwm mail archive: </b>
<input type="text" value="" name="q" size="30">
<input type="hidden" name="num" value="100">
<input type="hidden" name="l" value="fvwm@lists.math.uh.edu">
<input type="submit" name="btnG" value="Search Archives">
</form>
<p>
<form method="GET" action="http://www.mail-archive.com/search">
<b>Search the fvwm workers mail archive: </b>
<input type="text" value="" name="q" size="30">
<input type="hidden" name="num" value="100">
<input type="hidden" name="l" value="fvwm-workers@lists.math.uh.edu">
<input type="submit" name="btnG" value="Search Archives">
</form>
<h4>IRC Channels</h4>
<p>
Several IRC channels are also available to discuss fvwm related
topics or to get help. They are not official in a sense that the
fvwm developers maintain them, but there is a chance to meet some
of the developers there:
</p>
<ul>
<li> #fvwm on freenode</li>
<li> +fvwm.de on IRCnet (German channel)</li>
</ul>
<?php decoration_window_end(); ?>
| ThomasAdam/fvwm-web | contact/index.php | PHP | gpl-2.0 | 5,170 |
/* $Id: tstMvWnd.cpp 44529 2013-02-04 15:54:15Z vboxsync $ */
/*
* Copyright (C) 2010-2011 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <windows.h>
#define Assert(_m) do {} while (0)
#define vboxVDbgPrint(_m) do {} while (0)
static LRESULT CALLBACK WindowProc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
if(uMsg == WM_DESTROY)
{
PostQuitMessage(0);
return 0;
}
// switch(uMsg)
// {
// case WM_CLOSE:
// vboxVDbgPrint((__FUNCTION__": got WM_CLOSE for hwnd(0x%x)", hwnd));
// return 0;
// case WM_DESTROY:
// vboxVDbgPrint((__FUNCTION__": got WM_DESTROY for hwnd(0x%x)", hwnd));
// return 0;
// case WM_NCHITTEST:
// vboxVDbgPrint((__FUNCTION__": got WM_NCHITTEST for hwnd(0x%x)\n", hwnd));
// return HTNOWHERE;
// }
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
#define VBOXDISPWND_NAME L"tstMvWnd"
HRESULT tstMvWndCreate(DWORD w, DWORD h, HWND *phWnd)
{
HRESULT hr = S_OK;
HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);
/* Register the Window Class. */
WNDCLASS wc;
if (!GetClassInfo(hInstance, VBOXDISPWND_NAME, &wc))
{
wc.style = CS_OWNDC;
wc.lpfnWndProc = WindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = NULL;
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = VBOXDISPWND_NAME;
if (!RegisterClass(&wc))
{
DWORD winErr = GetLastError();
vboxVDbgPrint((__FUNCTION__": RegisterClass failed, winErr(%d)\n", winErr));
hr = E_FAIL;
}
}
if (hr == S_OK)
{
HWND hWnd = CreateWindowEx (0 /*WS_EX_CLIENTEDGE*/,
VBOXDISPWND_NAME, VBOXDISPWND_NAME,
WS_OVERLAPPEDWINDOW,
0, 0,
w, h,
GetDesktopWindow() /* hWndParent */,
NULL /* hMenu */,
hInstance,
NULL /* lpParam */);
Assert(hWnd);
if (hWnd)
{
*phWnd = hWnd;
}
else
{
DWORD winErr = GetLastError();
vboxVDbgPrint((__FUNCTION__": CreateWindowEx failed, winErr(%d)\n", winErr));
hr = E_FAIL;
}
}
return hr;
}
static int g_Width = 400;
static int g_Height = 300;
static DWORD WINAPI tstMvWndThread(void *pvUser)
{
HWND hWnd = (HWND)pvUser;
RECT Rect;
BOOL bRc = GetWindowRect(hWnd, &Rect);
Assert(bRc);
if (bRc)
{
bRc = SetWindowPos(hWnd, HWND_TOPMOST,
0, /* int X */
0, /* int Y */
g_Width, //Rect.left - Rect.right,
g_Height, //Rect.bottom - Rect.top,
SWP_SHOWWINDOW);
Assert(bRc);
if (bRc)
{
int dX = 10, dY = 10;
int xMin = 5, xMax = 300;
int yMin = 5, yMax = 300;
int x = dX, y = dY;
do
{
bRc = SetWindowPos(hWnd, HWND_TOPMOST,
x, /* int X */
y, /* int Y */
g_Width, //Rect.left - Rect.right,
g_Height, //Rect.bottom - Rect.top,
SWP_SHOWWINDOW);
x += dX;
if (x > xMax)
x = xMin;
y += dY;
if (y > yMax)
y = yMin;
Sleep(5);
} while(1);
}
}
return 0;
}
int main(int argc, char **argv, char **envp)
{
HWND hWnd;
HRESULT hr = tstMvWndCreate(200, 200, &hWnd);
Assert(hr == S_OK);
if (hr == S_OK)
{
HANDLE hThread = CreateThread(
NULL /* LPSECURITY_ATTRIBUTES lpThreadAttributes */,
0 /* SIZE_T dwStackSize */,
tstMvWndThread,
hWnd,
0 /* DWORD dwCreationFlags */,
NULL /* pThreadId */);
Assert(hThread);
if (hThread)
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
DestroyWindow (hWnd);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow);
return main(__argc, __argv, environ);
}
| carmark/vbox | src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/dbg/tstMvWnd.cpp | C++ | gpl-2.0 | 5,327 |
<?php
/**
* Logique des tâches
*
* PHP versions 5
*
* LODEL - Logiciel d'Edition ELectronique.
*
* Home page: http://www.lodel.org
* E-Mail: lodel@lodel.org
*
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* @package lodel/logic
* @author Ghislain Picard
* @author Jean Lamy
* @author Pierre-Alain Mignot
* @copyright 2001-2002, Ghislain Picard, Marin Dacos
* @copyright 2003, Ghislain Picard, Marin Dacos, Luc Santeramo, Nicolas Nutten, Anne Gentil-Beccot
* @copyright 2004, Ghislain Picard, Marin Dacos, Luc Santeramo, Anne Gentil-Beccot, Bruno Cénou
* @copyright 2005, Ghislain Picard, Marin Dacos, Luc Santeramo, Gautier Poupeau, Jean Lamy, Bruno Cénou
* @copyright 2006, Marin Dacos, Luc Santeramo, Bruno Cénou, Jean Lamy, Mikaël Cixous, Sophie Malafosse
* @copyright 2007, Marin Dacos, Bruno Cénou, Sophie Malafosse, Pierre-Alain Mignot
* @copyright 2008, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière
* @copyright 2009, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière
* @licence http://www.gnu.org/copyleft/gpl.html
* @since Fichier ajouté depuis la version 0.8
* @version CVS:$Id$
*/
/**
* Classe de logique des tâches
*
* @package lodel/logic
* @author Ghislain Picard
* @author Jean Lamy
* @copyright 2001-2002, Ghislain Picard, Marin Dacos
* @copyright 2003, Ghislain Picard, Marin Dacos, Luc Santeramo, Nicolas Nutten, Anne Gentil-Beccot
* @copyright 2004, Ghislain Picard, Marin Dacos, Luc Santeramo, Anne Gentil-Beccot, Bruno Cénou
* @copyright 2005, Ghislain Picard, Marin Dacos, Luc Santeramo, Gautier Poupeau, Jean Lamy, Bruno Cénou
* @copyright 2006, Marin Dacos, Luc Santeramo, Bruno Cénou, Jean Lamy, Mikaël Cixous, Sophie Malafosse
* @copyright 2007, Marin Dacos, Bruno Cénou, Sophie Malafosse, Pierre-Alain Mignot
* @copyright 2008, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière
* @copyright 2009, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière
* @licence http://www.gnu.org/copyleft/gpl.html
* @since Classe ajouté depuis la version 0.8
* @see logic.php
*/
class TasksLogic extends Logic {
/**
* generic equivalent assoc array
*/
public $g_name;
/** Constructor
*/
public function __construct() {
parent::__construct("tasks");
}
/**
* Affichage d'un objet
*
* @param array &$context le contexte passé par référence
* @param array &$error le tableau des erreurs éventuelles passé par référence
*/
public function viewAction(&$context,&$error)
{
trigger_error("TasksLogic::viewAction", E_USER_ERROR);
}
/**
* Changement du rang d'un objet
*
* @param array &$context le contexte passé par référence
* @param array &$error le tableau des erreurs éventuelles passé par référence
*/
public function changeRankAction(&$context, &$error, $groupfields = "", $status = "status>0")
{
trigger_error("TasksLogic::changeRankAction", E_USER_ERROR);
}
/**
* add/edit Action
*/
public function editAction(&$context,&$error, $clean=false)
{ trigger_error("TasksLogic::editAction", E_USER_ERROR); }
/*---------------------------------------------------------------*/
//! Private or protected from this point
/**
* @private
*/
/**
* Indique si un objet est protégé en suppression
*
* Cette méthode indique si un objet, identifié par son identifiant numérique et
* éventuellement son status, ne peut pas être supprimé. Dans le cas où un objet ne serait
* pas supprimable un message est retourné indiquant la cause. Sinon la méthode renvoit le
* booleen false.
*
* @param integer $id identifiant de l'objet
* @param integer $status status de l'objet
* @return false si l'objet n'est pas protégé en suppression, un message sinon
*/
public function isdeletelocked($id,$status=0)
{
$id = (int)$id;
// basic check. Should be more advanced because of the potential conflict between
// adminlodel adn othe rusers
$vo=$this->_getMainTableDAO()->find("id='".$id."' AND user='".C::get('id', 'lodeluser')."'","id");
return $vo->id ? false : true ;
}
// begin{publicfields} automatic generation //
/**
* Retourne la liste des champs publics
* @access private
*/
protected function _publicfields()
{
return array();
}
// end{publicfields} automatic generation //
// begin{uniquefields} automatic generation //
// end{uniquefields} automatic generation //
} // class | charlycoste/lodel-old | lodel/scripts/logic/class.tasks.php | PHP | gpl-2.0 | 5,266 |
<?php
namespace PaLogic\Bundle\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class PaLogicUserBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle'; // Name of parent bundle
}
}
| 71m024/palogic | src/PaLogic/Bundle/UserBundle/PaLogicUserBundle.php | PHP | gpl-2.0 | 238 |
/*
* Copyright (C) 2006, 2008 Thomas Zander <zander@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "GroupShape.h"
#include <KoShapeFactory.h>
#include <KoCreateShapesTool.h>
#include <QDomElement>
GroupShape::GroupShape(KoShapeFactory *shapeFactory)
: IconShape(shapeFactory->icon())
{
m_shapeFactory = shapeFactory;
}
void GroupShape::visit(KoCreateShapesTool *tool) {
tool->setShapeId(m_shapeFactory->id());
tool->setShapeProperties(0);
}
QString GroupShape::toolTip() {
return m_shapeFactory->toolTip();
}
QString GroupShape::groupId() const {
return m_shapeFactory->id();
}
void GroupShape::save(QDomElement &root)
{
Q_UNUSED(root);
}
| JeremiasE/KFormula | plugins/dockers/shapeselector/GroupShape.cpp | C++ | gpl-2.0 | 1,427 |
<?php
//======================================================
// Copyright (C) 2006 Claudio Redaelli, All Rights Reserved
//
// This file is part of the Unit Command Climate
// Assessment and Survey System (UCCASS)
//
// UCCASS is free software; you can redistribute it and/or
// modify it under the terms of the Affero General Public License as
// published by Affero, Inc.; either version 1 of the License, or
// (at your option) any later version.
//
// http://www.affero.org/oagpl.html
//
// UCCASS 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
// Affero General Public License for more details.
//======================================================
include('classes/main.class.php');
include('classes/special_results.class.php');
include('classes/spss_results.class.php');
$survey = new UCCASS_SPSS_Results(@$_REQUEST['sid'], @$_REQUEST['sep'], @$_REQUEST['del'], @$_REQUEST['altdel'], @$_REQUEST['text'], @$_REQUEST['altcr'], @$_REQUEST['order']);
echo $survey->getData();
?> | nishad/uccass | results_spss.php | PHP | gpl-2.0 | 1,125 |
import data from './data.json';
import * as F2 from '../../../../src/index';
// 兼容之前的pinch和pan
import '../../../../src/interaction/index';
import Pan from '../../../../src/interaction/pan';
import Pinch from '../../../../src/interaction/pinch';
const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
const chart = new F2.Chart({
el: canvas,
pixelRatio: window.devicePixelRatio
});
chart.source(data, {
reportDate: {
type: 'timeCat',
tickCount: 3,
range: [ 0, 1 ],
mask: 'YYYY-MM-DD'
},
rate: {
tickCount: 5
}
});
chart.line()
.position('reportDate*rate')
.color('name');
describe('Interaction', () => {
it('contructor compatible', () => {
expect(F2.Chart._Interactions.pan).toBe(Pan);
expect(F2.Chart._Interactions.pinch).toBe(Pinch);
});
it('instance compatible', () => {
chart.interaction('pan');
chart.interaction('pinch');
chart.render();
expect(chart._interactions.pan).toBeInstanceOf(Pan);
expect(chart._interactions.pinch).toBeInstanceOf(Pinch);
});
});
| antvis/g2-mobile | test/unit/interaction/new/compatible-spec.js | JavaScript | gpl-2.0 | 1,124 |
#-*- coding: utf-8 -*-
from openerp.osv import fields, osv
class partner_add_contact(osv.osv_memory):
_name = "partner.add.contact"
_columns = {
"name": fields.char("Nom", size=128, required=True),
"partner_id": fields.many2one("res.partner", u"Partenaire associé"),
"firstname": fields.char("Prénom", size=128, required=True),
"phone": fields.char(u"Numéro de téléphone", size=30),
"mobile": fields.char(u"Téléphone portable"),
"email": fields.char("Email", size=128),
"position": fields.char(u"Fonction dans l'entreprise", size=128),
'civilite': fields.selection([('mr', 'Monsieur'),('mme', 'Madame'),('mlle','Mademoiselle')], u'Civilité'),
}
def set_contact(self, cr, uid, ids, context=None):
obj = self.browse(cr, uid, ids[0], context=context)
vals = {
"name": obj.name,
"partner_id": obj.partner_id.id,
"firstname": obj.firstname,
"phone": obj.phone,
"mobile": obj.mobile,
"email": obj.email,
"position": obj.position,
"civilite": obj.civilite
}
return self.pool.get('magellanes.contact').create(cr, uid, vals, context)
| ATSTI/administra | open_corretora/brokerage/wizard/partner_add_contact.py | Python | gpl-2.0 | 1,249 |
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file sound.cpp Handling of playing sounds. */
#include "stdafx.h"
#include "landscape.h"
#include "mixer.h"
#include "newgrf_sound.h"
#include "fios.h"
#include "window_gui.h"
#include "vehicle_base.h"
/* The type of set we're replacing */
#define SET_TYPE "sounds"
#include "base_media_func.h"
static SoundEntry _original_sounds[ORIGINAL_SAMPLE_COUNT];
static void OpenBankFile(const char *filename)
{
memset(_original_sounds, 0, sizeof(_original_sounds));
/* If there is no sound file (nosound set), don't load anything */
if (filename == NULL) return;
FioOpenFile(SOUND_SLOT, filename);
size_t pos = FioGetPos();
uint count = FioReadDword();
/* The new format has the highest bit always set */
bool new_format = HasBit(count, 31);
ClrBit(count, 31);
count /= 8;
/* Simple check for the correct number of original sounds. */
if (count != ORIGINAL_SAMPLE_COUNT) {
/* Corrupt sample data? Just leave the allocated memory as those tell
* there is no sound to play (size = 0 due to calloc). Not allocating
* the memory disables valid NewGRFs that replace sounds. */
DEBUG(misc, 6, "Incorrect number of sounds in '%s', ignoring.", filename);
return;
}
FioSeekTo(pos, SEEK_SET);
for (uint i = 0; i != ORIGINAL_SAMPLE_COUNT; i++) {
_original_sounds[i].file_slot = SOUND_SLOT;
_original_sounds[i].file_offset = GB(FioReadDword(), 0, 31) + pos;
_original_sounds[i].file_size = FioReadDword();
}
for (uint i = 0; i != ORIGINAL_SAMPLE_COUNT; i++) {
SoundEntry *sound = &_original_sounds[i];
char name[255];
FioSeekTo(sound->file_offset, SEEK_SET);
/* Check for special case, see else case */
FioReadBlock(name, FioReadByte()); // Read the name of the sound
if (new_format || strcmp(name, "Corrupt sound") != 0) {
FioSeekTo(12, SEEK_CUR); // Skip past RIFF header
/* Read riff tags */
for (;;) {
uint32 tag = FioReadDword();
uint32 size = FioReadDword();
if (tag == ' tmf') {
FioReadWord(); // wFormatTag
sound->channels = FioReadWord(); // wChannels
sound->rate = FioReadDword(); // samples per second
if (!new_format) sound->rate = 11025; // seems like all old samples should be played at this rate.
FioReadDword(); // avg bytes per second
FioReadWord(); // alignment
sound->bits_per_sample = FioReadByte(); // bits per sample
FioSeekTo(size - (2 + 2 + 4 + 4 + 2 + 1), SEEK_CUR);
} else if (tag == 'atad') {
sound->file_size = size;
sound->file_slot = SOUND_SLOT;
sound->file_offset = FioGetPos();
break;
} else {
sound->file_size = 0;
break;
}
}
} else {
/*
* Special case for the jackhammer sound
* (name in sample.cat is "Corrupt sound")
* It's no RIFF file, but raw PCM data
*/
sound->channels = 1;
sound->rate = 11025;
sound->bits_per_sample = 8;
sound->file_slot = SOUND_SLOT;
sound->file_offset = FioGetPos();
}
}
}
static bool SetBankSource(MixerChannel *mc, const SoundEntry *sound)
{
assert(sound != NULL);
if (sound->file_size == 0) return false;
int8 *mem = MallocT<int8>(sound->file_size + 2);
/* Add two extra bytes so rate conversion can read these
* without reading out of its input buffer. */
mem[sound->file_size ] = 0;
mem[sound->file_size + 1] = 0;
FioSeekToFile(sound->file_slot, sound->file_offset);
FioReadBlock(mem, sound->file_size);
/* 16-bit PCM WAV files should be signed by default */
if (sound->bits_per_sample == 8) {
for (uint i = 0; i != sound->file_size; i++) {
mem[i] += -128; // Convert unsigned sound data to signed
}
}
#if TTD_ENDIAN == TTD_BIG_ENDIAN
if (sound->bits_per_sample == 16) {
uint num_samples = sound->file_size / 2;
int16 *samples = (int16 *)mem;
for (uint i = 0; i < num_samples; i++) {
samples[i] = BSWAP16(samples[i]);
}
}
#endif
assert(sound->bits_per_sample == 8 || sound->bits_per_sample == 16);
assert(sound->channels == 1);
assert(sound->file_size != 0 && sound->rate != 0);
MxSetChannelRawSrc(mc, mem, sound->file_size, sound->rate, sound->bits_per_sample == 16);
return true;
}
void InitializeSound()
{
DEBUG(misc, 1, "Loading sound effects...");
OpenBankFile(BaseSounds::GetUsedSet()->files->filename);
}
/* Low level sound player */
static void StartSound(SoundID sound_id, float pan, uint volume)
{
if (volume == 0) return;
const SoundEntry *sound = GetSound(sound_id);
if (sound == NULL) return;
/* Empty sound? */
if (sound->rate == 0) return;
MixerChannel *mc = MxAllocateChannel();
if (mc == NULL) return;
if (!SetBankSource(mc, sound)) return;
/* Apply the sound effect's own volume. */
volume = sound->volume * volume;
MxSetChannelVolume(mc, volume, pan);
MxActivateChannel(mc);
}
static const byte _vol_factor_by_zoom[] = {255, 190, 134, 87};
assert_compile(lengthof(_vol_factor_by_zoom) == ZOOM_LVL_COUNT);
static const byte _sound_base_vol[] = {
128, 90, 128, 128, 128, 128, 128, 128,
128, 90, 90, 128, 128, 128, 128, 128,
128, 128, 128, 80, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 90, 90, 90, 128, 90, 128,
128, 90, 128, 128, 128, 90, 128, 128,
128, 128, 128, 128, 90, 128, 128, 128,
128, 90, 128, 128, 128, 128, 128, 128,
128, 128, 90, 90, 90, 128, 128, 128,
90,
};
static const byte _sound_idx[] = {
2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 0,
1, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71,
72,
};
void SndCopyToPool()
{
for (uint i = 0; i < ORIGINAL_SAMPLE_COUNT; i++) {
SoundEntry *sound = AllocateSound();
*sound = _original_sounds[_sound_idx[i]];
sound->volume = _sound_base_vol[i];
sound->priority = 0;
}
}
/**
* Decide 'where' (between left and right speaker) to play the sound effect.
* @param sound Sound effect to play
* @param left Left edge of virtual coordinates where the sound is produced
* @param right Right edge of virtual coordinates where the sound is produced
* @param top Top edge of virtual coordinates where the sound is produced
* @param bottom Bottom edge of virtual coordinates where the sound is produced
*/
static void SndPlayScreenCoordFx(SoundID sound, int left, int right, int top, int bottom)
{
if (_settings_client.music.effect_vol == 0) return;
const Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
const ViewPort *vp = w->viewport;
if (vp != NULL &&
left < vp->virtual_left + vp->virtual_width && right > vp->virtual_left &&
top < vp->virtual_top + vp->virtual_height && bottom > vp->virtual_top) {
int screen_x = (left + right) / 2 - vp->virtual_left;
int width = (vp->virtual_width == 0 ? 1 : vp->virtual_width);
float panning = (float)screen_x / width;
StartSound(
sound,
panning,
(_settings_client.music.effect_vol * _vol_factor_by_zoom[vp->zoom - ZOOM_LVL_BEGIN]) / 256
);
return;
}
}
}
void SndPlayTileFx(SoundID sound, TileIndex tile)
{
/* emits sound from center of the tile */
int x = min(MapMaxX() - 1, TileX(tile)) * TILE_SIZE + TILE_SIZE / 2;
int y = min(MapMaxY() - 1, TileY(tile)) * TILE_SIZE - TILE_SIZE / 2;
uint z = (y < 0 ? 0 : GetSlopeZ(x, y));
Point pt = RemapCoords(x, y, z);
y += 2 * TILE_SIZE;
Point pt2 = RemapCoords(x, y, GetSlopeZ(x, y));
SndPlayScreenCoordFx(sound, pt.x, pt2.x, pt.y, pt2.y);
}
void SndPlayVehicleFx(SoundID sound, const Vehicle *v)
{
SndPlayScreenCoordFx(sound,
v->coord.left, v->coord.right,
v->coord.top, v->coord.bottom
);
}
void SndPlayFx(SoundID sound)
{
StartSound(sound, 0.5, _settings_client.music.effect_vol);
}
INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia<SoundsSet>, SoundsSet)
/** Names corresponding to the sound set's files */
static const char * const _sound_file_names[] = { "samples" };
template <class T, size_t Tnum_files, Subdirectory Tsubdir>
/* static */ const char * const *BaseSet<T, Tnum_files, Tsubdir>::file_names = _sound_file_names;
template <class Tbase_set>
/* static */ const char *BaseMedia<Tbase_set>::GetExtension()
{
return ".obs"; // OpenTTD Base Sounds
}
template <class Tbase_set>
/* static */ bool BaseMedia<Tbase_set>::DetermineBestSet()
{
if (BaseMedia<Tbase_set>::used_set != NULL) return true;
const Tbase_set *best = NULL;
for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != NULL; c = c->next) {
/* Skip unuseable sets */
if (c->GetNumMissing() != 0) continue;
if (best == NULL ||
(best->fallback && !c->fallback) ||
best->valid_files < c->valid_files ||
(best->valid_files == c->valid_files &&
(best->shortname == c->shortname && best->version < c->version))) {
best = c;
}
}
BaseMedia<Tbase_set>::used_set = best;
return BaseMedia<Tbase_set>::used_set != NULL;
}
| koreapyj/openttd-yacd | src/sound.cpp | C++ | gpl-2.0 | 9,517 |
/*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos 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.
Cyclos 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 Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.controls.members.references;
import java.util.Calendar;
import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import nl.strohalm.cyclos.annotations.Inject;
import nl.strohalm.cyclos.controls.ActionContext;
import nl.strohalm.cyclos.controls.BaseQueryAction;
import nl.strohalm.cyclos.entities.accounts.AccountType;
import nl.strohalm.cyclos.entities.accounts.transactions.Payment;
import nl.strohalm.cyclos.entities.accounts.transactions.TransferType;
import nl.strohalm.cyclos.entities.members.Element;
import nl.strohalm.cyclos.entities.members.Member;
import nl.strohalm.cyclos.entities.members.Reference;
import nl.strohalm.cyclos.entities.members.Reference.Level;
import nl.strohalm.cyclos.entities.members.Reference.Nature;
import nl.strohalm.cyclos.entities.members.ReferenceQuery;
import nl.strohalm.cyclos.entities.members.TransactionFeedback;
import nl.strohalm.cyclos.entities.settings.LocalSettings;
import nl.strohalm.cyclos.services.elements.ReferenceService;
import nl.strohalm.cyclos.entities.utils.Period;
import nl.strohalm.cyclos.utils.RelationshipHelper;
import nl.strohalm.cyclos.utils.RequestHelper;
import nl.strohalm.cyclos.entities.utils.TimePeriod;
import nl.strohalm.cyclos.utils.binding.BeanBinder;
import nl.strohalm.cyclos.utils.binding.DataBinder;
import nl.strohalm.cyclos.utils.binding.DataBinderHelper;
import nl.strohalm.cyclos.utils.conversion.CoercionHelper;
import nl.strohalm.cyclos.utils.query.QueryParameters;
import nl.strohalm.cyclos.utils.validation.ValidationException;
/**
* Action used to view a member's references and edit the reference to that member
* @author luis
*/
public class MemberReferencesAction extends BaseQueryAction {
/**
* Represents the direction we're searching
* @author luis
*/
public static enum Direction {
RECEIVED, GIVEN
}
private DataBinder<ReferenceQuery> dataBinder;
private ReferenceService referenceService;
@Inject
public void setReferenceService(final ReferenceService referenceService) {
this.referenceService = referenceService;
}
@SuppressWarnings("unchecked")
@Override
protected void executeQuery(final ActionContext context, final QueryParameters queryParameters) {
final HttpServletRequest request = context.getRequest();
final MemberReferencesForm form = context.getForm();
final Direction direction = CoercionHelper.coerce(Direction.class, form.getDirection());
final Member member = (Member) request.getAttribute("member");
final ReferenceQuery query = (ReferenceQuery) queryParameters;
if (member != null) {
form.setMemberId(member.getId());
}
// Retrieve both summaries for all time and last 30 days
final Map<Level, Integer> allTime = referenceService.countReferencesByLevel(query.getNature(), member, direction == Direction.RECEIVED);
request.setAttribute("summaryAllTime", allTime);
final Period period30 = new TimePeriod(30, TimePeriod.Field.DAYS).periodEndingAt(Calendar.getInstance());
final Map<Level, Integer> last30Days = referenceService.countReferencesHistoryByLevel(query.getNature(), member, period30, direction == Direction.RECEIVED);
request.setAttribute("summaryLast30Days", last30Days);
// Calculate the score
int totalAllTime = 0;
int total30Days = 0;
int scoreAllTime = 0;
int score30Days = 0;
final Collection<Level> levels = (Collection<Level>) request.getAttribute("levels");
int nonNeutralCountAllTime = 0;
int positiveCountAllTime = 0;
int nonNeutralCount30Days = 0;
int positiveCount30Days = 0;
for (final Level level : levels) {
final int value = level.getValue();
final int allTimeCount = CoercionHelper.coerce(Integer.TYPE, allTime.get(level));
final int last30DaysCount = CoercionHelper.coerce(Integer.TYPE, last30Days.get(level));
// Calculate the total
totalAllTime += allTimeCount;
total30Days += last30DaysCount;
// Calculate the score (sum of count * value)
scoreAllTime += allTimeCount * value;
score30Days += last30DaysCount * value;
// Calculate the data for positive percentage
if (value != 0) {
nonNeutralCountAllTime += allTimeCount;
nonNeutralCount30Days += last30DaysCount;
if (value > 0) {
positiveCountAllTime += allTimeCount;
positiveCount30Days += last30DaysCount;
}
}
}
// Calculate the positive percentage
final int percentAllTime = nonNeutralCountAllTime == 0 ? 0 : Math.round((float) positiveCountAllTime / nonNeutralCountAllTime * 100F);
final int percentLast30Days = nonNeutralCount30Days == 0 ? 0 : Math.round((float) positiveCount30Days / nonNeutralCount30Days * 100F);
// Store calculated data on request
request.setAttribute("totalAllTime", totalAllTime);
request.setAttribute("total30Days", total30Days);
request.setAttribute("scoreAllTime", scoreAllTime);
request.setAttribute("score30Days", score30Days);
request.setAttribute("percentAllTime", percentAllTime);
request.setAttribute("percent30Days", percentLast30Days);
// Get the references list
request.setAttribute("references", referenceService.search(query));
}
@Override
protected QueryParameters prepareForm(final ActionContext context) {
final MemberReferencesForm form = context.getForm();
final HttpServletRequest request = context.getRequest();
final ReferenceQuery query = getDataBinder().readFromString(form.getQuery());
query.setNature(CoercionHelper.coerce(Nature.class, form.getNature()));
if (query.getNature() == null) {
query.setNature(Nature.GENERAL);
}
// Find out the member
Member member;
try {
member = (Member) (form.getMemberId() <= 0L ? context.getAccountOwner() : elementService.load(form.getMemberId(), Element.Relationships.GROUP));
} catch (final Exception e) {
throw new ValidationException();
}
final boolean myReferences = member.equals(context.getAccountOwner());
// Retrieve the direction we're looking at
Direction direction = CoercionHelper.coerce(Direction.class, form.getDirection());
if (direction == null) {
direction = Direction.RECEIVED;
form.setDirection(direction.name());
}
final boolean isGiven = direction == Direction.GIVEN;
if (isGiven) {
query.setFrom(member);
} else {
query.setTo(member);
}
final boolean isGeneral = query.getNature() == Reference.Nature.GENERAL;
if (!isGeneral) {
query.fetch(RelationshipHelper.nested(TransactionFeedback.Relationships.TRANSFER, Payment.Relationships.TYPE, TransferType.Relationships.FROM, AccountType.Relationships.CURRENCY));
}
// When it's a member (or operator) viewing of other member's received general references, he can set his own too
final boolean canSetReference = isGeneral && referenceService.canGiveGeneralReference(member);
// Check whether the logged user can manage references on the list
final boolean canManage = isGeneral && (myReferences && isGiven || !myReferences) && referenceService.canManageGeneralReference(member);
// Bind the form and store the request attributes
final LocalSettings localSettings = settingsService.getLocalSettings();
getDataBinder().writeAsString(form.getQuery(), query);
request.setAttribute("member", member);
request.setAttribute("canManage", canManage);
request.setAttribute("myReferences", myReferences);
request.setAttribute("isGiven", isGiven);
request.setAttribute("isGeneral", isGeneral);
request.setAttribute("levels", localSettings.getReferenceLevelList());
request.setAttribute("canSetReference", canSetReference);
RequestHelper.storeEnum(request, Direction.class, "directions");
if (!isGeneral) {
final boolean showAmount = context.isAdmin() || context.getAccountOwner().equals(member);
request.setAttribute("showAmount", showAmount);
}
return query;
}
@Override
protected boolean willExecuteQuery(final ActionContext context, final QueryParameters queryParameters) throws Exception {
return true;
}
private DataBinder<ReferenceQuery> getDataBinder() {
if (dataBinder == null) {
final BeanBinder<ReferenceQuery> binder = BeanBinder.instance(ReferenceQuery.class);
binder.registerBinder("pageParameters", DataBinderHelper.pageBinder());
dataBinder = binder;
}
return dataBinder;
}
}
| mateli/OpenCyclos | src/main/java/nl/strohalm/cyclos/controls/members/references/MemberReferencesAction.java | Java | gpl-2.0 | 9,953 |
using System;
using System.Collections.Generic;
namespace LeetCode
{
public partial class Solution {
public int LengthOfLongestSubstring(string s)
{
//TODO 以下算法虽然思路是对的,但是写法有问题,无法通过长字符串的测试,不应该递归
#region Bad performance
// IList<char> dic=new List<char>();
// for (var i = 0; i < s.Length; i++)
// {
// char c = s [i];
// if (dic.Contains (c))
// {
// var sub = s.Substring (s.IndexOf (c) + 1);
//
// return Math.Max (i, LengthOfLongestSubstring (sub));
// }
// dic.Add (c);
//
// }
// return s.Length;
#endregion
//IList<char> dic=new List<char>();
const int ARRAY_LEN=255;
int[] dic=new int[ARRAY_LEN];
for (var i = 0; i < ARRAY_LEN; i++)
{
dic [i] = -1;
}
int start = 0;
int max = 0;
for (var i = 0; i < s.Length; i++)
{
var c = s [i];
if (dic[c]>=start)//也就是说dic里面不是-1,已经被赋值过,而且这个值在start位置之后出现,判断为重复
{
int len = i - start;
max = Math.Max (max, len);
start = dic [c] + 1;
}
dic [c] = i;
}
max = Math.Max (max, s.Length - start);
return max;
}
}
}
| studyzy/Leetcode | CSharp/LeetCode/LongestSubstringWithoutRepeatingCharacters.cs | C# | gpl-2.0 | 1,226 |
/****************************************************************************
The Sire build utility 'sire'.
Copyright (C) 1999, 2000, 2002, 2003 David W Orchard (davido@errol.org.uk)
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
*****************************************************************************
File : machine.cpp
Class : None
Desc : A description
AMENDMENTS
EDIT 001 21-Nov-97 davido
Check the root directory as well.
EDIT 002 13-Jan-99 davido
Support SuSe Linux file positions.
EDIT 003 14-Aug-99 davido
Support Linux Fortran 77
EDIT 004 19-May-00 davido
Take out the platform specific dependency.
EDIT 005 15-Nov-02 davido
Remove support for infrequently used options
EDIT 006 10-Jan-03 davido
Remove getPython, getMachine() and getPlatform(). Now redundant.
*****************************************************************************/
/************* INCLUDE ******************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "sys.h"
#include "env.h"
#include "machine.h"
#include "build_v.h"
/************* FUNCTIONS ****************************************************/
static char const *findName(char **list)
{
static char buff1[256];
static char buff2[256];
int len1;
int len2;
for (char **p = list; (NULL != *p); p++)
{
strcpy(buff1, (char*)Tenv::appExpand(*p));
strcpy(buff2, (char*)Tenv::appGet("ROOTDIR")); // 004
strcat(buff2, buff1);
len1 = strlen(buff1);
len2 = strlen(buff2);
for (char const * const *q = getExeList(); (NULL != *q); q++)
{
strcpy(buff1 +len1, *q);
strcpy(buff2 +len2, *q);
if (!access(buff1, X_OK)) // Check the given path
return (buff1);
if (!access(buff2, X_OK)) // Check against the file system root
return (buff2);
}
}
return (*list);
}
char const *getCCP()
{
// C++ Compiler
static char *list[] =
{
"/bin/CC",
"/bin/ccp",
"/usr/bin/CC",
"/usr/bin/ccp",
"/usr/ucb/CC",
"/usr/ucb/ccp",
"/usr/lang/CC",
"/usr/lang/ccp",
"/opt/SUNWspro/bin/CC",
"/opt/SUNWspro/bin/ccp",
"${RELEASE}/SC1.0/CC",
"${RELEASE}/SC1.0/ccp",
"/usr/local/bin/gcc",
"${Init}/bin/cl",
"/usr/bin/g++", // 002
NULL
};
return(findName(list));
}
char const *getCPP()
{
// C Preprocessor
static char *list[] =
{
"/bin/cpp",
"/usr/bin/cpp",
"/usr/ucb/cpp",
"/usr/lang/cpp",
"/opt/SUNWspro/bin/cpp",
"${RELEASE}/SC1.0/cpp",
NULL
};
return(findName(list));
}
char const *getCC()
{
// C Compiler
static char *list[] =
{
"/bin/cc",
"/usr/ucb/cc",
"/usr/bin/cc",
"/usr/lang/cc",
"/opt/SUNWspro/bin/cc",
"${RELEASE}/SC1.0/cc",
"${Init}/bin/cl",
"/usr/bin/gcc", // 002
NULL
};
return(findName(list));
}
char const *getJava()
{
// C Compiler
static char *list[] =
{
"/usr/bin/javac",
"javac",
NULL
};
return(findName(list));
}
char const *getSH()
{
// C Compiler
static char *list[] =
{
"/bin/sh",
NULL
};
return(findName(list));
}
char const *getCSH()
{
// C Compiler
static char *list[] =
{
"/bin/csh",
NULL
};
return(findName(list));
}
char const *getTmpDir()
{
const char *path = "/tmp"; // UNIX - default
#if defined (INTEL_NT) || defined (INTEL_9X)
if (NULL != (path = Tenv::appGet("TMP")))
{
if (access((char*)path, F_OK) || !isDir(path))
{
// Does not exist
path = NULL;
}
}
if ((NULL == path) && (NULL != (path = Tenv::appGet("TEMP"))))
{
if (access((char*)path, F_OK) || !isDir(path))
{
// Does not exist
path = NULL;
}
}
if (NULL == path)
{
// PC - default
char buff[512];
sprintf(buff, "%s/tmp", Tenv::appGet("ROOTDIR"));
path = buff;
}
#endif
return(path);
}
/************* END OF FILE **************************************************/
| LaMaisonOrchard/Sire | sire/machine.cpp | C++ | gpl-2.0 | 4,814 |
require 'rails_helper'
RSpec.shared_context 'some assigned reviews and some unassigned reviews' do
let!(:user) { create(:user) }
let!(:review_assigned1) { create(:review, by_user: user.login) }
let!(:review_assigned2) { create(:review, by_user: user.login) }
let!(:review_unassigned1) { create(:review, by_user: user.login) }
let!(:review_unassigned2) { create(:review, by_user: user.login) }
let!(:history_element1) do
create(:history_element_review_assigned, op_object_id: review_assigned1.id, user_id: user.id)
end
let!(:history_element2) do
create(:history_element_review_assigned, op_object_id: review_assigned2.id, user_id: user.id)
end
let!(:history_element3) do
create(:history_element_review_accepted, op_object_id: review_assigned2.id, user_id: user.id)
end
let!(:history_element4) do
create(:history_element_review_accepted, op_object_id: review_unassigned1.id, user_id: user.id)
end
end
RSpec.describe Review do
let(:project) { create(:project_with_package, name: 'Apache', package_name: 'apache2') }
let(:package) { project.packages.first }
let(:user) { create(:user, login: 'King') }
let(:group) { create(:group, title: 'Staff') }
it { is_expected.to belong_to(:bs_request).touch(true) }
describe 'validations' do
it 'is not allowed to specify by_user and any other reviewable' do
[:by_group, :by_project, :by_package].each do |reviewable|
review = Review.create(:by_user => user.login, reviewable => 'not-existent-reviewable')
expect(review.errors.messages[:base]).
to eq(['it is not allowed to have more than one reviewer entity: by_user, by_group, by_project, by_package'])
end
end
it 'is not allowed to specify by_group and any other reviewable' do
[:by_project, :by_package].each do |reviewable|
review = Review.create(:by_group => group.title, reviewable => 'not-existent-reviewable')
expect(review.errors.messages[:base]).
to eq(['it is not allowed to have more than one reviewer entity: by_user, by_group, by_project, by_package'])
end
end
end
describe '.assigned' do
include_context 'some assigned reviews and some unassigned reviews'
subject { Review.assigned }
it { is_expected.to match_array([review_assigned1, review_assigned2]) }
end
describe '.unassigned' do
include_context 'some assigned reviews and some unassigned reviews'
subject { Review.unassigned }
it { is_expected.to match_array([review_unassigned1, review_unassigned2]) }
end
describe '.set_associations' do
context 'with valid attributes' do
it 'sets user association when by_user object exists' do
review = create(:review, by_user: user.login)
expect(review.user).to eq(user)
expect(review.by_user).to eq(user.login)
end
it 'sets group association when by_group object exists' do
review = create(:review, by_group: group.title)
expect(review.group).to eq(group)
expect(review.by_group).to eq(group.title)
end
it 'sets project association when by_project object exists' do
review = create(:review, by_project: project.name)
expect(review.project).to eq(project)
expect(review.by_project).to eq(project.name)
end
it 'sets package and project associations when by_package and by_project object exists' do
review = create(:review, by_project: project.name, by_package: package.name)
expect(review.package).to eq(package)
expect(review.by_package).to eq(package.name)
expect(review.project).to eq(project)
expect(review.by_project).to eq(project.name)
end
end
context 'with invalid attributes' do
let!(:nobody) { create(:user_nobody) }
it 'does not set user association when by_user object does not exist' do
review = Review.new(by_user: 'not-existent')
expect(review.user).to eq(nil)
expect(review.valid?).to eq(false)
end
it 'does not set user association when by_user object is _nobody_' do
review = Review.new(by_user: nobody)
expect(review.user).to eq(nil)
expect(review.valid?).to eq(false)
expect(review.errors.messages[:base]).
to eq(["Couldn't find user #{nobody.login}"])
end
it 'does not set group association when by_group object does not exist' do
review = Review.new(by_group: 'not-existent')
expect(review.group).to eq(nil)
expect(review.valid?).to eq(false)
end
it 'does not set project association when by_project object does not exist' do
review = Review.new(by_project: 'not-existent')
expect(review.project).to eq(nil)
expect(review.valid?).to eq(false)
end
it 'does not set project and package associations when by_project and by_package object does not exist' do
review = Review.new(by_project: 'not-existent', by_package: 'not-existent')
expect(review.package).to eq(nil)
expect(review.valid?).to eq(false)
end
it 'does not set package association when by_project parameter is missing' do
review = Review.new(by_package: package.name)
expect(review.package).to eq(nil)
expect(review.valid?).to eq(false)
end
end
end
describe '#accepted_at' do
let!(:user) { create(:user) }
let(:review_state) { :accepted }
let!(:review) do
create(
:review,
by_user: user.login,
state: review_state
)
end
let!(:history_element_review_accepted) do
create(
:history_element_review_accepted,
review: review,
user: user,
created_at: Faker::Time.forward(1)
)
end
context 'with a review assigned to and assigned to state = accepted' do
let!(:review2) do
create(
:review,
by_user: user.login,
review_id: review.id,
state: :accepted
)
end
let!(:history_element_review_accepted2) do
create(
:history_element_review_accepted,
review: review2,
user: user,
created_at: Faker::Time.forward(2)
)
end
subject { review.accepted_at }
it { is_expected.to eq(history_element_review_accepted2.created_at) }
end
context 'with a review assigned to and assigned to state != accepted' do
let!(:review2) do
create(
:review,
by_user: user.login,
review_id: review.id,
updated_at: Faker::Time.forward(2),
state: :new
)
end
subject { review.accepted_at }
it { is_expected.to eq(nil) }
end
context 'with no reviewed assigned to and state = accepted' do
subject { review.accepted_at }
it { is_expected.to eq(history_element_review_accepted.created_at) }
end
context 'with no reviewed assigned to and state != accepted' do
let(:review_state) { :new }
subject { review.accepted_at }
it { is_expected.to eq(nil) }
end
end
describe '#declined_at' do
let!(:user) { create(:user) }
let(:review_state) { :declined }
let!(:review) do
create(
:review,
by_user: user.login,
state: review_state
)
end
let!(:history_element_review_declined) do
create(
:history_element_review_declined,
review: review,
user: user,
created_at: Faker::Time.forward(1)
)
end
context 'with a review assigned to and assigned to state = declined' do
let!(:review2) do
create(
:review,
by_user: user.login,
review_id: review.id,
state: :declined
)
end
let!(:history_element_review_declined2) do
create(
:history_element_review_declined,
review: review2,
user: user,
created_at: Faker::Time.forward(2)
)
end
subject { review.declined_at }
it { is_expected.to eq(history_element_review_declined2.created_at) }
end
context 'with a review assigned to and assigned to state != declined' do
let!(:review2) do
create(
:review,
by_user: user.login,
review_id: review.id,
updated_at: Faker::Time.forward(2),
state: :new
)
end
subject { review.declined_at }
it { is_expected.to eq(nil) }
end
context 'with no reviewed assigned to and state = declined' do
subject { review.declined_at }
it { is_expected.to eq(history_element_review_declined.created_at) }
end
context 'with no reviewed assigned to and state != declined' do
let(:review_state) { :new }
subject { review.declined_at }
it { is_expected.to eq(nil) }
end
end
describe '#validate_not_self_assigned' do
let!(:user) { create(:user) }
let!(:review) { create(:review, by_user: user.login) }
context 'assigned to itself' do
before { review.review_id = review.id }
subject! { review.valid? }
it { expect(review.errors[:review_id].count).to eq(1) }
end
context 'assigned to a different review' do
let!(:review2) { create(:review, by_user: user.login) }
before { review.review_id = review2.id }
subject! { review.valid? }
it { expect(review.errors[:review_id].count).to eq(0) }
end
end
describe '#validate_non_symmetric_assignment' do
let!(:user) { create(:user) }
let!(:review) { create(:review, by_user: user.login) }
let!(:review2) { create(:review, by_user: user.login, review_id: review.id) }
context 'review1 is assigned to review2 which is already assigned to review1' do
before { review.review_id = review2.id }
subject! { review.valid? }
it { expect(review.errors[:review_id].count).to eq(1) }
end
context 'review1 is assigned to review3' do
let!(:review3) { create(:review, by_user: user.login) }
before { review.review_id = review3.id }
subject! { review.valid? }
it { expect(review.errors[:review_id].count).to eq(0) }
end
end
describe '#update_caches' do
RSpec.shared_examples "the subject's cache is reset when it's review changes" do
before do
Timecop.travel(1.minute)
@cache_key = subject.cache_key
review.state = :accepted
review.save
subject.reload
end
it { expect(subject.cache_key).not_to eq(@cache_key) }
end
context 'by_user' do
let!(:review) { create(:user_review) }
subject { review.user }
it_should_behave_like "the subject's cache is reset when it's review changes"
end
context 'by_group' do
let(:groups_user) { create(:groups_user) }
let(:group) { groups_user.group }
let(:user) { groups_user.user }
let!(:review) { create(:review, by_group: group) }
it_should_behave_like "the subject's cache is reset when it's review changes" do
subject { user }
end
it_should_behave_like "the subject's cache is reset when it's review changes" do
subject { group }
end
end
context 'by_package with a direct relationship' do
let(:relationship_package_user) { create(:relationship_package_user) }
let(:package) { relationship_package_user.package }
let!(:review) { create(:review, by_package: package, by_project: package.project) }
subject { relationship_package_user.user }
it_should_behave_like "the subject's cache is reset when it's review changes"
end
context 'by_package with a group relationship' do
let(:relationship_package_group) { create(:relationship_package_group) }
let(:package) { relationship_package_group.package }
let(:group) { relationship_package_group.group }
let(:groups_user) { create(:groups_user, group: group) }
let!(:user) { groups_user.user }
let!(:review) { create(:review, by_package: package, by_project: package.project) }
it_should_behave_like "the subject's cache is reset when it's review changes" do
subject { user }
end
it_should_behave_like "the subject's cache is reset when it's review changes" do
subject { group }
end
end
context 'by_project with a direct relationship' do
let(:relationship_project_user) { create(:relationship_project_user) }
let(:project) { relationship_project_user.project }
let!(:review) { create(:review, by_project: project) }
subject { relationship_project_user.user }
it_should_behave_like "the subject's cache is reset when it's review changes"
end
context 'by_project with a group relationship' do
let(:relationship_project_group) { create(:relationship_project_group) }
let(:project) { relationship_project_group.project }
let(:group) { relationship_project_group.group }
let(:groups_user) { create(:groups_user, group: group) }
let!(:user) { groups_user.user }
let!(:review) { create(:review, by_project: project) }
it_should_behave_like "the subject's cache is reset when it's review changes" do
subject { user }
end
it_should_behave_like "the subject's cache is reset when it's review changes" do
subject { group }
end
end
end
describe '#reviewable_by?' do
let(:other_user) { create(:user, login: 'bob') }
let(:other_group) { create(:group, title: 'my_group') }
let(:other_project) { create(:project_with_package, name: 'doc:things', package_name: 'less') }
let(:other_package) { other_project.packages.first }
let(:other_package_with_same_name) { create(:package, name: package.name) }
let(:review_by_user) { create(:review, by_user: user.login) }
let(:review_by_group) { create(:review, by_group: group.title) }
let(:review_by_project) { create(:review, by_project: project.name) }
let(:review_by_package) { create(:review, by_project: project.name, by_package: package.name) }
it 'returns true if review configuration matches provided hash' do
expect(review_by_user.reviewable_by?(by_user: user.login)).to be(true)
expect(review_by_group.reviewable_by?(by_group: group.title)).to be(true)
expect(review_by_project.reviewable_by?(by_project: project.name)).to be(true)
expect(review_by_package.reviewable_by?(by_package: package.name, by_project: package.project.name)).to be(true)
end
it 'returns false if review configuration does not match provided hash' do
expect(review_by_user.reviewable_by?(by_user: other_user.login)).to be_falsy
expect(review_by_group.reviewable_by?(by_group: other_group.title)).to be_falsy
expect(review_by_project.reviewable_by?(by_project: other_project.name)).to be_falsy
expect(review_by_package.reviewable_by?(by_package: other_package.name, by_project: other_package.project.name)).to be_falsy
expect(review_by_package.reviewable_by?(by_package: other_package_with_same_name.name, by_project: other_package_with_same_name.project.name)).to be_falsy
end
end
describe '.new_from_xml_hash' do
let(:request_xml) do
"<request>
<review state='accepted' by_user='#{user}'/>
</request>"
end
let(:request_hash) { Xmlhash.parse(request_xml) }
let(:review_hash) { request_hash['review'] }
subject { Review.new_from_xml_hash(review_hash) }
it 'initalizes the review in state :new' do
expect(subject.state).to eq(:new)
end
end
end
| Ana06/open-build-service | src/api/spec/models/review_spec.rb | Ruby | gpl-2.0 | 15,667 |
#include "\z\ifa3_comp_ace\addons\cannon\script_component.hpp" | bux/IFA3_ACE_COMPAT | addons/cannon/functions/script_component.hpp | C++ | gpl-2.0 | 62 |
using System;
using Server;
using Server.Items;
namespace Server.Items
{
public abstract class BaseSpear : BaseMeleeWeapon
{
public override int DefHitSound{ get{ return 0x23C; } }
public override int DefMissSound{ get{ return 0x238; } }
public override SkillName DefSkill{ get{ return SkillName.Fencing; } }
public override WeaponType DefType{ get{ return WeaponType.Piercing; } }
public override WeaponAnimation DefAnimation{ get{ return WeaponAnimation.Pierce2H; } }
public BaseSpear( int itemID ) : base( itemID )
{
}
public BaseSpear( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */reader.ReadInt();
}
public override void OnHit( Mobile attacker, Mobile defender )
{
base.OnHit( attacker, defender );
if ( !Core.AOS && Layer == Layer.TwoHanded && (attacker.Skills[SkillName.Anatomy].Value / 400.0) >= Utility.RandomDouble() )
{
defender.SendMessage( "You receive a paralyzing blow!" ); // Is this not localized?
defender.Freeze( TimeSpan.FromSeconds( 2.0 ) );
attacker.SendMessage( "You deliver a paralyzing blow!" ); // Is this not localized?
attacker.PlaySound( 0x11C );
}
if ( !Core.AOS && Poison != null && PoisonCharges > 0 )
{
--PoisonCharges;
if ( Utility.RandomDouble() >= 0.5 ) // 50% chance to poison
defender.ApplyPoison( attacker, Poison );
}
}
}
} | brodock/sunuo | scripts/legacy/Items/Weapons/SpearsAndForks/BaseSpear.cs | C# | gpl-2.0 | 1,599 |
package it.giacomos.android.wwwsapp.locationUtils;
public class Constants {
public static final long LOCATION_UPDATE_INTERVAL = 25000L;
public static final long LOCATION_FASTEST_UPDATE_INTERVAL = 20000L;
public static final long LOCATION_UPDATES_GPS_MIN_TIME = 12000l;
public static final float LOCATION_UPDATES_NETWORK_MIN_DIST = 80f;
public static final float LOCATION_UPDATES_GPS_MIN_DIST = 20f;
// public static final long LOCATION_UPDATES_PASSIVE_MIN_TIME = 5000l;
// public static final float LOCATION_UPDATES_PASSIVE_MIN_DIST = 10f;
public static final int LOCATION_COMPARER_INTERVAL = 1000 * 60;
public static final int LOCATION_COMPARER_ACCURACY = 200;
}
| delleceste/wwwsapp | src/it/giacomos/android/wwwsapp/locationUtils/Constants.java | Java | gpl-2.0 | 688 |
<?php
require_once("include/bittorrent.php");
dbconn();
$langid = 0 + $_GET['sitelanguage'];
if ($langid)
{
$lang_folder = validlang($langid);
if(get_langfolder_cookie() != $lang_folder)
{
set_langfolder_cookie($lang_folder);
header("Location: " . $_SERVER['PHP_SELF']);
}
}
require_once(get_langfile_path("", false, $CURLANGDIR));
failedloginscheck ();
cur_user_check () ;
stdhead($lang_login['head_login']);
$s = "<select name=\"sitelanguage\" onchange='submit()'>\n";
$langs = langlist("site_lang");
foreach ($langs as $row)
{
if ($row["site_lang_folder"] == get_langfolder_cookie()) $se = "selected=\"selected\""; else $se = "";
$s .= "<option value=\"". $row["id"] ."\" ". $se. ">" . htmlspecialchars($row["lang_name"]) . "</option>\n";
}
$s .= "\n</select>";
?>
<?php
unset($returnto);
if (!empty($_GET["returnto"])) {
$returnto = $_GET["returnto"];
if (!$_GET["nowarn"]) {
print("<h1>" . $lang_login['h1_not_logged_in']. "</h1>\n");
print("<p><b>" . $lang_login['p_error']. "</b> " . $lang_login['p_after_logged_in']. "</p>\n");
}
}
?>
<iframe id="loginframe" name="loginframe" style="display:none;height:1px;width:1px;"></iframe>
<form name="formlogin" method="post" target="loginframe">
<p><?php echo $lang_login['p_need_cookies_enables']?><br /> [<b><?php echo $maxloginattempts;?></b>] <?php echo $lang_login['p_fail_ban']?></p>
<p><?php echo $lang_login['p_you_have']?> <b><?php echo remaining ();?></b> <?php echo $lang_login['p_remaining_tries']?></p>
<p><font color=blue><b>注意:</b></font>登录前请确认您的帐号在西北望BBS已经激活!并注意帐号大小写!</p>
<table border="0" cellpadding="5">
<tr><td class="rowhead"><?php echo $lang_login['rowhead_username']?></td><td class="rowfollow" align="left"><input type="text" name="username" style="width: 180px; border: 1px solid gray" /></td></tr>
<tr><td class="rowhead"><?php echo $lang_login['rowhead_password']?></td><td class="rowfollow" align="left"><input type="password" name="password" style="width: 180px; border: 1px solid gray"/></td></tr>
<tr><td class="toolbox" colspan="2" align="right"><input type="submit" value="<?php echo $lang_login['button_login']?>" class="btn" onClick="LoginbyBBS()" > <input type="reset" value="<?php echo $lang_login['button_reset']?>" class="btn" /></td></tr>
</table>
<?php
if (isset($returnto))
print("<input type=\"hidden\" name=\"returnto\" value=\"" . htmlspecialchars($returnto) . "\" />\n");
?>
</form>
<p><?php echo $lang_login['p_no_account_signup']?></p>
<?php
if ($smtptype != 'none'){
?>
<p><?php echo $lang_login['p_forget_pass_recover']?></p>
<p><?php echo $lang_login['p_tishi']?></p>
<?php
}
if ($showhelpbox_main != 'no'){?>
<table width="700" class="main" border="0" cellspacing="0" cellpadding="0"><tr><td class="embedded">
<h2><?php echo $lang_login['text_helpbox'] ?><font class="small"> - <?php echo $lang_login['text_helpbox_note'] ?><font id= "waittime" color="red"></font></h2>
<?php
print("<table width='100%' border='1' cellspacing='0' cellpadding='1'><tr><td class=\"text\">\n");
print("<iframe src='" . get_protocol_prefix() . $BASEURL . "/shoutbox.php?type=helpbox' width='650' height='180' frameborder='0' name='sbox' marginwidth='0' marginheight='0'></iframe><br /><br />\n");
print("<form action='" . get_protocol_prefix() . $BASEURL . "/shoutbox.php' id='helpbox' method='get' target='sbox' name='shbox'>\n");
print($lang_login['text_message']."<input type='text' id=\"hbtext\" name='shbox_text' autocomplete='off' style='width: 500px; border: 1px solid gray' ><input type='submit' id='hbsubmit' class='btn' name='shout' value=\"".$lang_login['sumbit_shout']."\" /><input type='reset' class='btn' value=".$lang_login['submit_clear']." /> <input type='hidden' name='sent' value='yes'><input type='hidden' name='type' value='helpbox' />\n");
print("<div id=sbword style=\"display: none\">".$lang_login['sumbit_shout']."</div>");
print(smile_row("shbox","shbox_text"));
print("</td></tr></table></form></td></tr></table>");
}
stdfoot();
| lzuhzy/xbwpt | xbwpt/login.php | PHP | gpl-2.0 | 4,030 |
<?php
/********************************************************************
PhPeace - Portal Management System
Copyright notice
(C) 2003-2019 Francesco Iannuzzelli <francesco@phpeace.org>
All rights reserved
This script is part of PhPeace.
PhPeace 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.
PhPeace 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.
The GNU General Public License (GPL) is available at
http://www.gnu.org/copyleft/gpl.html.
A copy can be found in the file COPYING distributed with
these scripts.
This copyright notice MUST APPEAR in all copies of the script!
********************************************************************/
if (!defined('SERVER_ROOT'))
define('SERVER_ROOT',$_SERVER['DOCUMENT_ROOT']);
include_once(SERVER_ROOT."/include/header.php");
$phpeace = new Phpeace;
$title[] = array('licence','');
echo $hh->ShowTitle($title);
?>
<pre>
<strong><a href="http://www.phpeace.org" target="_blank" title="PhPeace website - Link to external site - Opens in new browser window">PhPeace</a> - Portal Management System</strong>
Copyright (C) 2003-2018 Francesco Iannuzzelli <<a href="mailto:francesco@phpeace.org">francesco@phpeace.org</a>>
All rights reserved
PhPeace 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.
PhPeace 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.
The GNU General Public License (GPL) is available at
<a href="http://www.gnu.org/copyleft/gpl.html" target="_blank" title="GNU/GPL website - Link to external site - Opens in new browser window">http://www.gnu.org/copyleft/gpl.html</a>.
For your convenience a copy is reported below.
<hr>
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
</pre>
<?php
include_once(SERVER_ROOT."/include/footer.php");
?>
| fra967/phpeace | admin/gate/licence.php | PHP | gpl-2.0 | 17,635 |
using System;
using MonoDevelop.Projects;
using System.Xml;
using MonoDevelop.Core.Assemblies;
namespace MonoDevelop.MonoGame
{
public static class MonoGameBuildAction
{
public static readonly string Shader;
public static bool IsMonoGameBuildAction(string action){
return action == Shader;
}
static MonoGameBuildAction(){
Shader = "MonoGameShader";
}
}
public static class MonoGameProject : DotNetAssemblyProject
{
public MonoGameProject ()
{
Init ();
}
public MonoGameProject (string languageName)
: base (languageName)
{
Init ();
}
public MonoGameProject(string languageName, ProjectCreateInformation info, XmlElement projectOptions)
:base(languageName, info, projectOptions)
{
Init ();
}
private void Init(){
}
public override SolutionItemConfiguration CreateConfiguration(string name)
{
var conf = new MonoGameProjectConfiguration (name);
conf.CopyFrom (base.CreateConfiguration (name));
return conf;
}
public override bool SupportsFormat (FileFormat format)
{
return format.Id == "MSBuild10";
}
public override TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (FileFormat format)
{
return new TargetFrameworkMoniker("4.0");
}
public override bool SupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework)
{
if (framework.Id != (MonoDevelop.Core.Assemblies.TargetFrameworkMoniker.NET_4_0))
return false;
else
return base.SupportsFramework (framework);
}
protected override System.Collections.Generic.IList<string> GetCommonBuildActions ()
{
var actions = new System.Collections.Generic.List<string> (base.GetCommonBuildActions ());
actions.Add (MonoGameBuildAction.Shader);
return actions;
}
public override string GetDefaultBuildAction (string fileName)
{
if (System.IO.Path.GetExtension (fileName) == ".fx") {
return MonoGameBuildAction.Shader;
}
return base.GetDefaultBuildAction (fileName);
}
protected override void PopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration)
{
base.PopulateSupportFileList (list, configuration);
foreach(var projectReference in References){
if (projectReference != null && projectReference.Package.Name == "monogame") {
if (projectReference.ReferenceType == ReferenceType.Gac) {
foreach (var assem in projectReference.Package.Assemblies) {
list.Add (assem.Location);
var cfg = (MonoGameProjectConfiguration)configuration.GetConfiguration (this);
if (cfg.DebugMode) {
var mdbFile = TargetRuntime.GetAssemblyDebugInfoFile (assem.Location);
if (System.IO.File.Equals(mdbFile)){
list.Add(mdbFile);
}
}
}
}
break;
}
}
}
}
public class MonoGameBuildExtension : ProjectServiceExtension{
protected override BuildResult Build (MonoDevelop.Core.IProgressMonitor monitor, IBuildTarget item, ConfigurationSelector configuration)
{
try {
return base.Build(monitor, item, configuration);
} finally {
}
}
protected override BuildResult Compile (MonoDevelop.Core.IProgressMonitor monitor, SolutionEntityItem item, BuildData buildData)
{
try {
var proj = item as MonoGameProject;
if (proj == null){
return base.Compile (monitor, item, buildData);
}
var results = new System.Collections.Generic.List<BuildResult>();
foreach (var file in proj.Files) {
if (MonoGameBuildAction.IsMonoGameBuildAction(file.BuildAction)){
buildData.Items.Add(file);
var buildresults = MonoGameContentProcessor.Compile(file, monitor,buildData);
results.Add(buildresults);
}
}
return base.Compile(monitor, item, buildData).Append(results);
} finally {
}
}
}
public class MonoGameProjectBinding : IProjectBinding{
public Project CreateProject(ProjectCreateInformation info, System.Xml.XmlElement projectOptions){
string lang = projectOptions.GetAttribute ("language");
return new MonoGameProject (lang, info, projectOptions);
}
public Project CreateSingleFileproject(string sourceFile){
throw new InvalidOperationException ();
}
public Project CanCreateSingleFileProject(string sourceFile){
return false;
}
public string Name{
get{return "MonoGame"; }
}
}
public class MonoGameProjectConfiguration : DotNetProjectConfiguration{
public MonoGameProjectConfiguration () : base (){
}
public MonoGameProjectConfiguration (string name): base(name){
}
public override void CopyFrom (ItemConfiguration configuration)
{
base.CopyFrom (configuration);
}
}
public class MonoGameContentProcessor {
public static BuildResult Compile( ProjectFile file, MonoDevelop.Core.IProgressMonitor monitor, BuildData buildData){
switch (file.BuildAction) {
case "MonoGameShader":
{
var results = new BuildResult ();
monitor.Log.WriteLine ("Compiling Shader");
monitor.Log.WriteLine ("Shader : " + buildData.Configuration.OutputDirectory);
monitor.Log.WriteLine ("Shader : " + file.FilePath);
monitor.Log.WriteLine ("Shader : " + file.ToString ());
return results;
}
default:
return new BuildResult ();
}
}
}
}
| stebyrne04/Monogame_templates | Properties/MonoGameProject.cs | C# | gpl-2.0 | 5,230 |
package com.example.review;
public class SwitchStringStatement {
public static void main(String args[]){
String color = "Blue";
String shirt = " Shirt";
switch (color){
case "Blue":
shirt = "Blue" + shirt;
break;
case "Red":
shirt = "Red" + shirt;
break;
default:
shirt = "White" + shirt;
}
System.out.println("Shirt type: " + shirt);
}
}
| amzaso/Java_servef | 02-Review/examples/ReviewExamples/src/com/example/review/SwitchStringStatement.java | Java | gpl-2.0 | 536 |
<?php
// Form override fo theme settings
function saa_basic_form_system_theme_settings_alter(&$form, $form_state) {
$form['options_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Theme Specific Settings'),
'#collapsible' => FALSE,
'#collapsed' => FALSE
);
$form['options_settings']['saa_basic_tabs'] = array(
'#type' => 'checkbox',
'#title' => t('Use the ZEN tabs'),
'#description' => t('Check this if you wish to replace the default tabs by the ZEN tabs'),
'#default_value' => theme_get_setting('saa_basic_tabs'),
);
$form['options_settings']['saa_basic_breadcrumb'] = array(
'#type' => 'fieldset',
'#title' => t('Breadcrumb settings'),
'#attributes' => array('id' => 'basic-breadcrumb'),
);
$form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb'] = array(
'#type' => 'select',
'#title' => t('Display breadcrumb'),
'#default_value' => theme_get_setting('saa_basic_breadcrumb'),
'#options' => array(
'yes' => t('Yes'),
'admin' => t('Only in admin section'),
'no' => t('No'),
),
);
$form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_separator'] = array(
'#type' => 'textfield',
'#title' => t('Breadcrumb separator'),
'#description' => t('Text only. Don’t forget to include spaces.'),
'#default_value' => theme_get_setting('saa_basic_breadcrumb_separator'),
'#size' => 5,
'#maxlength' => 10,
'#prefix' => '<div id="div-basic-breadcrumb-collapse">', // jquery hook to show/hide optional widgets
);
$form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_home'] = array(
'#type' => 'checkbox',
'#title' => t('Show home page link in breadcrumb'),
'#default_value' => theme_get_setting('saa_basic_breadcrumb_home'),
);
$form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_trailing'] = array(
'#type' => 'checkbox',
'#title' => t('Append a separator to the end of the breadcrumb'),
'#default_value' => theme_get_setting('saa_basic_breadcrumb_trailing'),
'#description' => t('Useful when the breadcrumb is placed just before the title.'),
);
$form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_title'] = array(
'#type' => 'checkbox',
'#title' => t('Append the content title to the end of the breadcrumb'),
'#default_value' => theme_get_setting('saa_basic_breadcrumb_title'),
'#description' => t('Useful when the breadcrumb is not placed just before the title.'),
'#suffix' => '</div>', // #div-basic-breadcrumb-collapse"
);
//IE specific settings.
$form['options_settings']['saa_basic_ie'] = array(
'#type' => 'fieldset',
'#title' => t('Internet Explorer Stylesheets'),
'#attributes' => array('id' => 'basic-ie'),
);
$form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Enable Internet Explorer stylesheets in theme'),
'#default_value' => theme_get_setting('saa_basic_ie_enabled'),
'#description' => t('If you check this box you can choose which IE stylesheets in theme get rendered on display.'),
);
$form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled_css'] = array(
'#type' => 'fieldset',
'#title' => t('Check which IE versions you want to enable additional .css stylesheets for.'),
'#states' => array(
'visible' => array(
':input[name="saa_basic_ie_enabled"]' => array('checked' => TRUE),
),
),
);
$form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled_css']['saa_basic_ie_enabled_versions'] = array(
'#type' => 'checkboxes',
'#options' => array(
'ie8' => t('Internet Explorer 8'),
'ie9' => t('Internet Explorer 9'),
'ie10' => t('Internet Explorer 10'),
),
'#default_value' => theme_get_setting('saa_basic_ie_enabled_versions'),
);
$form['options_settings']['clear_registry'] = array(
'#type' => 'checkbox',
'#title' => t('Rebuild theme registry on every page.'),
'#description' =>t('During theme development, it can be very useful to continuously <a href="!link">rebuild the theme registry</a>. WARNING: this is a huge performance penalty and must be turned off on production websites.', array('!link' => 'http://drupal.org/node/173880#theme-registry')),
'#default_value' => theme_get_setting('clear_registry'),
);
}
| saaphx-dev/saa | sites/all/themes/saa-basic/theme-settings.php | PHP | gpl-2.0 | 4,665 |
<?
/**************************************************************************************************
* Archivo: StoreConsultaDetalleUbicacion.php
* ------------------------------------------------------------------------------------------------
* Version: 1.0
* Descripcion:
* Modificaciones:
* -
*
* Nota: Registrar en este encabezado todas las modificaciones hechas al archivo.
**************************************************************************************************/
require_once ('template.php');
require_once ('Sysgran/Core/Red/Encoder.php');
require_once ('Sysgran/Core/Listados/FiltroNumerico.php');
require_once ('Sysgran/Core/Php/StoreCustom.php');
class StoreConsultaDetalleUbicacion extends StoreCustom {
function StoreConsultaDetalleUbicacion ($paginado = false) {
parent::__construct ($paginado);
$this->AgregarFiltro (new FiltroNumerico ('ubicacion', 'ubic'));
$this->AgregarFiltro (new FiltroNumerico ('producto', 'prod'));
$this->AgregarFiltro (new FiltroNumerico ('almacen', 'alm'));
}
function ArmarQuery () {
$fubic = $this->GetFiltro ('ubicacion');
$fprod = $this->GetFiltro ('producto');
$falm = $this->GetFiltro ('almacen');
$where = '';
if ($fubic->EsActivo ()) {
$where .= " AND d.iUbicacionAlmacenId = " . $fubic->GetValor ();
}
if ($fprod->EsActivo ()) {
$where .= " AND p.iProductoId = " . $fprod->GetValor ();
}
if ($falm->EsActivo ()) {
$where .= " AND u.iAlmacenId = " . $falm->GetValor ();
}
$query = "SELECT d.iDetalleUbicacionAlmacenId, d.iNroDeDetalle, d.fCantidad, um.cCodigo AS cod_um, p.cCodigo AS cod_producto, d.iNroDeDetalle
FROM DetalleUbicacionAlmacen d
JOIN UbicacionAlmacen u ON u.iUbicacionAlmacenId = d.iUbicacionAlmacenId
JOIN Producto p ON p.iProductoId = d.iProductoId
JOIN UnidadDeMedida um ON um.iUnidadDeMedidaId = p.iUnidadDeMedidaStockId
WHERE
u.bActivo = " . DB::ToBoolean (true) . " AND
d.fCantidad > 0
$where
ORDER BY u.cCodigo, d.iDetalleubicacionAlmacenId ASC";
return $query;
}
function CargarItem ($rs) {
$ret['id'] = $rs->Fields ('iDetalleUbicacionAlmacenId');
$ret['nroDeDetalle'] = $rs->Fields ('iNroDeDetalle');
$ret['codigoProducto'] = $rs->Fields ('cod_producto');
$ret['cantidad'] = $rs->Fields ('fCantidad');
$ret['codigoUnidadDeMedida'] = $rs->Fields ('cod_um');
return $ret;
}
} | marcelinoar/FrameworkWeb | src/base/servidor/Sysgran/Aplicacion/Modulos/Produccion/Store/StoreConsultaDetalleUbicacion.php | PHP | gpl-2.0 | 2,477 |
<?php
/**
* Module: Intro Text
*
* @author SpyroSol
* @category BuilderModules
* @package Spyropress
*/
class Spyropress_Module_Intro_Text extends SpyropressBuilderModule {
public function __construct() {
global $spyropress;
// Widget variable settings
$this->cssclass = '';
$this->description = __( 'A lightweight component for introduction text.', 'spyropress' );
$this->idbase = 'spyropress_intro_text';
$this->name = __( 'Introduction Text', 'spyropress' );
$this->templates['centered'] = array(
'label' => 'Text Centered',
'class' => 'twelve columns offset-by-two'
);
$this->templates['style2'] = array(
'label' => 'Text Centered 2',
'class' => 'fourteen columns marginTop offset-by-one'
);
// Fields
$this->fields = array(
array(
'label' => __( 'Styles', 'spyropress' ),
'id' => 'template',
'type' => 'select',
'options' => $this->get_option_templates()
),
array(
'label' => __('Content', 'spyropress' ),
'id' => 'content',
'type' => 'editor'
)
);
$this->create_widget();
}
function widget( $args, $instance ) {
// extracting info
extract($args);
extract( spyropress_clean_array( $instance ) );
// get view to render
include $this->get_view();
}
}
spyropress_builder_register_module( 'Spyropress_Module_Intro_Text' );
?> | jamesshannonwd/meesha | wp-content/themes/cutting-edge/framework/builder/modules/intro-text/intro-text.php | PHP | gpl-2.0 | 1,765 |
<?php
$vortex_like_dislike = get_option("vortex_like_dislike");
function vortex_system_add_dislike_class_buddypress($id){
$vortex_like_dislike = get_option("vortex_like_dislike");
if(is_user_logged_in()){
$current_user_id = get_current_user_id();
$user_key = 'vortex_system_user_'.$current_user_id;
}elseif(!is_user_logged_in() && $vortex_like_dislike['v-switch-anon']){
$user_ip = sanitize_text_field($_SERVER['REMOTE_ADDR']);
$user_key = 'vortex_system_user_'.$user_ip;
};
if(is_user_logged_in() || (!is_user_logged_in() && $vortex_like_dislike['v-switch-anon'])){
if(!get_post_meta($id,$user_key,true) == ''){
$current_user = get_post_meta($id,$user_key,true);
$current_user_disliked = $current_user['disliked'];
}
if($current_user_disliked == 'nodisliked'){
return 'vortex-p-dislike-active';
}elseif(vortex_ra_read_cookie('dislikepost',$id) == 'found' && $current_user_disliked !== 'disliked'){
return 'vortex-p-dislike-active';
}
}
}
function vortex_system_get_total_dislikes_buddypress($id){
$dislikes = get_post_meta($id,'vortex_system_dislikes',true);
if(empty($dislikes)){
return 0;
}elseif(!$dislikes == ''){
return $dislikes = get_post_meta($id,'vortex_system_dislikes',true);
}
}
function vortex_system_dislike_counter_buddypress($id){
$vortex_like_dislike = get_option("vortex_like_dislike");
if ($vortex_like_dislike['v_custom_text_post_keep'] && vortex_system_add_dislike_class_buddypress($id) == 'vortex-p-dislike-active'){
if(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){
return '<span class="vortex-p-dislike-counter '.$id. '">'.$vortex_like_dislike['v_custom_text_post_dislike'].'</span>';
}
}elseif(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){
return '<span class="vortex-p-dislike-counter '.$id. '">'. vortex_system_get_total_dislikes_buddypress($id).'</span>';
}
}
function vortex_system_render_dislike_button_buddypress($id){
/*dev use the same as below
return '<div class="vortex-container-dislike">
<input type="hidden" value="'.get_the_ID().'" ></input>
<div class="vortex-p-dislike '.get_the_ID().' '. vortex_system_add_dislike_class() .' '.vortex_system_get_dislike_icon().'">
'.vortex_system_dislike_counter().'
</div>
</div>';
*/
return '<div class="vortex-container-dislike"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-dislike '.$id.' '. vortex_system_add_dislike_class_buddypress($id) .' '.vortex_system_get_dislike_icon().'">'.vortex_system_dislike_counter_buddypress($id).'</div></div>';
}
function vortex_system_add_like_class_buddypress($id){
$vortex_like_dislike = get_option("vortex_like_dislike");
if(is_user_logged_in()){
$current_user_id = get_current_user_id();
$user_key = 'vortex_system_user_'.$current_user_id;
}elseif(!is_user_logged_in() && $vortex_like_dislike['v-switch-anon']){
$user_ip = sanitize_text_field($_SERVER['REMOTE_ADDR']);
$user_key = 'vortex_system_user_'.$user_ip;
};
if(is_user_logged_in() || (!is_user_logged_in() && $vortex_like_dislike['v-switch-anon'])){
if(!get_post_meta($id,$user_key,true) == ''){
$current_user = get_post_meta($id,$user_key,true);
$current_user_liked = $current_user['liked'];
}
if($current_user_liked == 'noliked'){
return 'vortex-p-like-active';
}elseif(vortex_ra_read_cookie('likepost',$id) == 'found' && $current_user_liked !== 'liked'){
return 'vortex-p-like-active';
}
}
}
function vortex_system_get_total_likes_buddypress($id){
$likes = get_post_meta($id,'vortex_system_likes',true);
if(empty($likes)){
return 0;
}elseif(!$likes == ''){
return $dislikes = get_post_meta($id,'vortex_system_likes',true);
}
}
function vortex_system_like_counter_buddypress($id){
$vortex_like_dislike = get_option("vortex_like_dislike");
if ($vortex_like_dislike['v_custom_text_post_keep'] && vortex_system_add_like_class_buddypress($id) == 'vortex-p-like-active'){
if(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){
return '<span class="vortex-p-like-counter '. $id.'">'.$vortex_like_dislike['v_custom_text_post_like'].'</span>';
}
}elseif(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){
return '<span class="vortex-p-like-counter '. $id.'">'.vortex_system_get_total_likes_buddypress($id).'</span>';
}
}
function vortex_buddypress_render($id){
$vortex_like_dislike = get_option("vortex_like_dislike");
if(!$vortex_like_dislike['v-switch-dislike']){
/*
this is for dev the same as below
$buttons = '
<div class="vortex-container-vote '.vortex_button_align().'">
<div class="vortex-container-like">
<input type="hidden" value="'.get_the_ID().'" ></input>
<div class="vortex-p-like '.get_the_ID().' '.vortex_system_add_like_class().' '.vortex_system_get_like_icon().'">
'.vortex_system_like_counter().'
</div>
</div>
'.vortex_system_render_dislike_button().'
</div>
';*/
//leave it inline, bbPress adds p tags for unkown reasons
$buttons = '<div class="vortex-container-vote '.vortex_button_align().'"><div class="vortex-container-like"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-like '.$id.' '.vortex_system_add_like_class_buddypress($id).' '.vortex_system_get_like_icon().'">'.vortex_system_like_counter_buddypress($id).'</div></div>'.vortex_system_render_dislike_button_buddypress($id).'</div>';
return $buttons;
}else {
/* this is for dev the same as below
$buttons = '
<div class="vortex-container-vote '.vortex_button_align().'">
<div class="vortex-container-like">
<input type="hidden" value="'.get_the_ID().'" ></input>
<div class="vortex-p-like '.get_the_ID().' '.vortex_system_add_like_class().' '.vortex_system_get_like_icon().'">
'.vortex_system_like_counter().'
</div>
</div>
</div>
';
*/
$buttons = '<div class="vortex-container-vote '.vortex_button_align().'"><div class="vortex-container-like"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-like '.$id.' '.vortex_system_add_like_class_buddypress($id).' '.vortex_system_get_like_icon().'">'.vortex_system_like_counter_buddypress($id).'</div></div></div>';
return $buttons;
}
}
function vortex_buddypress_after($content){
return $content.vortex_buddypress_render(bp_get_activity_id());
}
function vortex_buddypress_before($content){
return vortex_buddypress_render(bp_get_activity_id()).$content;
}
$vortex_like_dislike = get_option("vortex_like_dislike");
if($vortex_like_dislike['v_button_visibility'][1] && $vortex_like_dislike['v_button_visibility'][2] ){
add_filter('bp_get_activity_content_body','vortex_buddypress_after');
add_filter('bp_get_activity_content_body','vortex_buddypress_before');
}elseif($vortex_like_dislike['v_button_visibility'][1]){
add_filter('bp_get_activity_content_body','vortex_buddypress_before');
}elseif($vortex_like_dislike['v_button_visibility'][2]){
add_filter('bp_get_activity_content_body','vortex_buddypress_after');
}
| jackhutson03/Exashare | wp-content/plugins/rating-system/buddypress.php | PHP | gpl-2.0 | 7,404 |
/*
* java-gnome, a UI library for writing GTK and GNOME programs from Java!
*
* Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others
*
* The code in this file, and the program it is a part of, is made available
* to you by its authors as open source software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License version
* 2 ("GPL") as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details.
*
* You should have received a copy of the GPL along with this program. If not,
* see http://www.gnu.org/licenses/. The authors of this program may be
* contacted through http://java-gnome.sourceforge.net/.
*
* Linking this library statically or dynamically with other modules is making
* a combined work based on this library. Thus, the terms and conditions of
* the GPL cover the whole combination. As a special exception (the
* "Claspath Exception"), the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library. If
* you modify this library, you may extend the Classpath Exception to your
* version of the library, but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version.
*/
package org.gnome.atk;
/*
* THIS FILE IS GENERATED CODE!
*
* To modify its contents or behaviour, either update the generation program,
* change the information in the source defs file, or implement an override for
* this class.
*/
import org.gnome.atk.Plumbing;
final class AtkLayer extends Plumbing
{
private AtkLayer() {}
static final int INVALID = 0;
static final int BACKGROUND = 1;
static final int CANVAS = 2;
static final int WIDGET = 3;
static final int MDI = 4;
static final int POPUP = 5;
static final int OVERLAY = 6;
}
| cyberpython/java-gnome | generated/bindings/org/gnome/atk/AtkLayer.java | Java | gpl-2.0 | 2,440 |
<?php
/**
* @version 1.0.0 jp logs $
* @package jplogs
* @copyright Copyright © 2010 - All rights reserved.
* @license GNU/GPL
* @author kim
* @author mail administracion@joomlanetprojects.com
* @website http://www.joomlanetprojects.com
*
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import the Joomla modellist library
jimport('joomla.application.component.modellist');
class jplogsModelLogs extends JModelList
{
/**
* Constructor.
*
* @param array An optional associative array of configuration settings.
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields'])) {
$config['filter_fields'] = array(
'title', 'title',
);
}
parent::__construct($config);
}
/**
* Method to get all the log files.
* @return array
* @since 1.6
*/
public function getItems()
{
jimport('joomla.filesystem.file');
$main = 'error_log';
$folder = JPATH_ROOT.DS.'logs';
$items = JFolder::files($folder, $filter = '.', true, false , array('index.html'));
if(file_exists(JPATH_ROOT.DS.$main)) { array_push($items, $main); }
return $items;
}
/**
* Method to get the file lenght.
* @return file
* @since 1.6
*/
public function getLenght($file)
{
$file == 'error_log' ? $path = JPATH_ROOT.DS : $path = JPATH_ROOT.DS.'logs'.DS;
return filesize($path.$file).' Kb';
}
} | nishijieone/Webinar_joomla25 | administrator/components/com_jplogs/models/logs.php | PHP | gpl-2.0 | 1,544 |
class AddRegisteredByToCredittypes < ActiveRecord::Migration
def self.up
if column_exists? :credittypes, :moduser_id
rename_column :credittypes, :moduser_id, :registered_by_id
else
add_column :credittypes, :registered_by_id, :integer
end
add_column :credittypes, :modified_by_id, :integer
end
def self.down
rename_column :credittypes, :registered_by_id, :moduser_id
remove_column :credittypes, :modified_by_id
end
end
| ifunam/salva | db/migrate/20101117233353_add_registered_by_to_credittypes.rb | Ruby | gpl-2.0 | 465 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Scores</title>
<style type="text/css">
html { font-family: Arial; }
table { empty-cells: hide; border-collapse: collapse; background-color: white; border: 2px solid black; }
th, td { padding: 3px 1.5ex; border: 1px solid black; border-top: 1px dotted black; border-bottom: 1px dotted black; }
td.score { text-align: right; }
th { background-color: rgb(208,208,191); border-bottom: 2px solid black; }
tr.fini td { background-color: rgb(251,249,238); border-bottom: 2px solid black; }
tr.fini td.date { background-color: white; }
tr.suite td.date { border-top: hidden; }
tr:hover,
tr.fini:hover td { background-color: rgb(238,234,221); }
</style>
</head>
<body>
<h1>Tableau des scores</h1>
<h2>Exercice Hotpotatoes : <em><?php echo $oSousActiv->oHotpotatoes->retTitre(); ?></em></h2>
<h3>Etudiant : <em><?php echo $oEtudiant->retNomComplet(); ?></em></h3>
<?php
if (empty($oHotpotScores)) {
echo "<p>Aucun score Hotpotatoes.</p>";
} else {
?>
<table border="1">
<thead>
<tr><th>Date de début de l'exercice</th><th>Durée</th><th>Score</th></tr>
</thead>
<tbody>
<?php
$derDate = 0;
foreach ($oHotpotScores as $oScore) {
$suite = ($oScore->retDateDebut()===$derDate ? true : false);
echo '<tr>'
.'<td class="date">'.( $suite ? '' : date('d/m/Y H:i',$oScore->retDateInitiale()) ).'</td>'
.'<td>'.$oScore->retDuree().'</td>'
.'<td class="score">'.$oScore->retScore().' %</td>'
.'</tr>';
$derDate = $oScore->retDateDebut();
}
?>
</tbody>
<?php } ?>
</table>
</body>
</html>
| Ced-le-pingouin/esprit-mirror | src/sousactiv/hotpotatoes/scores.tpl.php | PHP | gpl-2.0 | 1,680 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.telegram.messenger.exoplayer2.source;
import android.util.Pair;
import org.telegram.messenger.exoplayer2.C;
import org.telegram.messenger.exoplayer2.ExoPlayer;
import org.telegram.messenger.exoplayer2.Timeline;
import org.telegram.messenger.exoplayer2.upstream.Allocator;
import org.telegram.messenger.exoplayer2.util.Assertions;
import org.telegram.messenger.exoplayer2.util.Util;
import java.io.IOException;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Concatenates multiple {@link MediaSource}s. It is valid for the same {@link MediaSource} instance
* to be present more than once in the concatenation.
*/
public final class ConcatenatingMediaSource implements MediaSource {
private final MediaSource[] mediaSources;
private final Timeline[] timelines;
private final Object[] manifests;
private final Map<MediaPeriod, Integer> sourceIndexByMediaPeriod;
private final boolean[] duplicateFlags;
private Listener listener;
private ConcatenatedTimeline timeline;
/**
* @param mediaSources The {@link MediaSource}s to concatenate. It is valid for the same
* {@link MediaSource} instance to be present more than once in the array.
*/
public ConcatenatingMediaSource(MediaSource... mediaSources) {
this.mediaSources = mediaSources;
timelines = new Timeline[mediaSources.length];
manifests = new Object[mediaSources.length];
sourceIndexByMediaPeriod = new HashMap<>();
duplicateFlags = buildDuplicateFlags(mediaSources);
}
@Override
public void prepareSource(ExoPlayer player, boolean isTopLevelSource, Listener listener) {
this.listener = listener;
for (int i = 0; i < mediaSources.length; i++) {
if (!duplicateFlags[i]) {
final int index = i;
mediaSources[i].prepareSource(player, false, new Listener() {
@Override
public void onSourceInfoRefreshed(Timeline timeline, Object manifest) {
handleSourceInfoRefreshed(index, timeline, manifest);
}
});
}
}
}
@Override
public void maybeThrowSourceInfoRefreshError() throws IOException {
for (int i = 0; i < mediaSources.length; i++) {
if (!duplicateFlags[i]) {
mediaSources[i].maybeThrowSourceInfoRefreshError();
}
}
}
@Override
public MediaPeriod createPeriod(int index, Allocator allocator, long positionUs) {
int sourceIndex = timeline.getSourceIndexForPeriod(index);
int periodIndexInSource = index - timeline.getFirstPeriodIndexInSource(sourceIndex);
MediaPeriod mediaPeriod = mediaSources[sourceIndex].createPeriod(periodIndexInSource, allocator,
positionUs);
sourceIndexByMediaPeriod.put(mediaPeriod, sourceIndex);
return mediaPeriod;
}
@Override
public void releasePeriod(MediaPeriod mediaPeriod) {
int sourceIndex = sourceIndexByMediaPeriod.get(mediaPeriod);
sourceIndexByMediaPeriod.remove(mediaPeriod);
mediaSources[sourceIndex].releasePeriod(mediaPeriod);
}
@Override
public void releaseSource() {
for (int i = 0; i < mediaSources.length; i++) {
if (!duplicateFlags[i]) {
mediaSources[i].releaseSource();
}
}
}
private void handleSourceInfoRefreshed(int sourceFirstIndex, Timeline sourceTimeline,
Object sourceManifest) {
// Set the timeline and manifest.
timelines[sourceFirstIndex] = sourceTimeline;
manifests[sourceFirstIndex] = sourceManifest;
// Also set the timeline and manifest for any duplicate entries of the same source.
for (int i = sourceFirstIndex + 1; i < mediaSources.length; i++) {
if (mediaSources[i] == mediaSources[sourceFirstIndex]) {
timelines[i] = sourceTimeline;
manifests[i] = sourceManifest;
}
}
for (Timeline timeline : timelines) {
if (timeline == null) {
// Don't invoke the listener until all sources have timelines.
return;
}
}
timeline = new ConcatenatedTimeline(timelines.clone());
listener.onSourceInfoRefreshed(timeline, manifests.clone());
}
private static boolean[] buildDuplicateFlags(MediaSource[] mediaSources) {
boolean[] duplicateFlags = new boolean[mediaSources.length];
IdentityHashMap<MediaSource, Void> sources = new IdentityHashMap<>(mediaSources.length);
for (int i = 0; i < mediaSources.length; i++) {
MediaSource source = mediaSources[i];
if (!sources.containsKey(source)) {
sources.put(source, null);
} else {
duplicateFlags[i] = true;
}
}
return duplicateFlags;
}
/**
* A {@link Timeline} that is the concatenation of one or more {@link Timeline}s.
*/
private static final class ConcatenatedTimeline extends Timeline {
private final Timeline[] timelines;
private final int[] sourcePeriodOffsets;
private final int[] sourceWindowOffsets;
public ConcatenatedTimeline(Timeline[] timelines) {
int[] sourcePeriodOffsets = new int[timelines.length];
int[] sourceWindowOffsets = new int[timelines.length];
long periodCount = 0;
int windowCount = 0;
for (int i = 0; i < timelines.length; i++) {
Timeline timeline = timelines[i];
periodCount += timeline.getPeriodCount();
Assertions.checkState(periodCount <= Integer.MAX_VALUE,
"ConcatenatingMediaSource children contain too many periods");
sourcePeriodOffsets[i] = (int) periodCount;
windowCount += timeline.getWindowCount();
sourceWindowOffsets[i] = windowCount;
}
this.timelines = timelines;
this.sourcePeriodOffsets = sourcePeriodOffsets;
this.sourceWindowOffsets = sourceWindowOffsets;
}
@Override
public int getWindowCount() {
return sourceWindowOffsets[sourceWindowOffsets.length - 1];
}
@Override
public Window getWindow(int windowIndex, Window window, boolean setIds,
long defaultPositionProjectionUs) {
int sourceIndex = getSourceIndexForWindow(windowIndex);
int firstWindowIndexInSource = getFirstWindowIndexInSource(sourceIndex);
int firstPeriodIndexInSource = getFirstPeriodIndexInSource(sourceIndex);
timelines[sourceIndex].getWindow(windowIndex - firstWindowIndexInSource, window, setIds,
defaultPositionProjectionUs);
window.firstPeriodIndex += firstPeriodIndexInSource;
window.lastPeriodIndex += firstPeriodIndexInSource;
return window;
}
@Override
public int getPeriodCount() {
return sourcePeriodOffsets[sourcePeriodOffsets.length - 1];
}
@Override
public Period getPeriod(int periodIndex, Period period, boolean setIds) {
int sourceIndex = getSourceIndexForPeriod(periodIndex);
int firstWindowIndexInSource = getFirstWindowIndexInSource(sourceIndex);
int firstPeriodIndexInSource = getFirstPeriodIndexInSource(sourceIndex);
timelines[sourceIndex].getPeriod(periodIndex - firstPeriodIndexInSource, period, setIds);
period.windowIndex += firstWindowIndexInSource;
if (setIds) {
period.uid = Pair.create(sourceIndex, period.uid);
}
return period;
}
@Override
public int getIndexOfPeriod(Object uid) {
if (!(uid instanceof Pair)) {
return C.INDEX_UNSET;
}
Pair<?, ?> sourceIndexAndPeriodId = (Pair<?, ?>) uid;
if (!(sourceIndexAndPeriodId.first instanceof Integer)) {
return C.INDEX_UNSET;
}
int sourceIndex = (Integer) sourceIndexAndPeriodId.first;
Object periodId = sourceIndexAndPeriodId.second;
if (sourceIndex < 0 || sourceIndex >= timelines.length) {
return C.INDEX_UNSET;
}
int periodIndexInSource = timelines[sourceIndex].getIndexOfPeriod(periodId);
return periodIndexInSource == C.INDEX_UNSET ? C.INDEX_UNSET
: getFirstPeriodIndexInSource(sourceIndex) + periodIndexInSource;
}
private int getSourceIndexForPeriod(int periodIndex) {
return Util.binarySearchFloor(sourcePeriodOffsets, periodIndex, true, false) + 1;
}
private int getFirstPeriodIndexInSource(int sourceIndex) {
return sourceIndex == 0 ? 0 : sourcePeriodOffsets[sourceIndex - 1];
}
private int getSourceIndexForWindow(int windowIndex) {
return Util.binarySearchFloor(sourceWindowOffsets, windowIndex, true, false) + 1;
}
private int getFirstWindowIndexInSource(int sourceIndex) {
return sourceIndex == 0 ? 0 : sourceWindowOffsets[sourceIndex - 1];
}
}
}
| JungleTian/Telegram | TMessagesProj/src/main/java/org/telegram/messenger/exoplayer2/source/ConcatenatingMediaSource.java | Java | gpl-2.0 | 9,121 |
<?php
/**
*
* Adapted from Edward McIntyre's wp_bootstrap_navwalker class.
* Removed support for glyphicon and added support for Font Awesome
*
*/
/**
* Class Name: wp_bootstrap_navwalker
* GitHub URI: https://github.com/twittem/wp-bootstrap-navwalker
* Description: A custom WordPress nav walker class to implement the Bootstrap 3 navigation style in a custom theme using the WordPress built in menu manager.
* Version: 2.0.4
* Author: Edward McIntyre - @twittem
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/
//exit if accessed directly
if(!defined('ABSPATH')) exit;
class cronista_navwalker extends Walker_Nav_Menu {
/**
* @see Walker::start_lvl()
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of page. Used for padding.
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "\n$indent<ul role=\"menu\" class=\" dropdown-menu\">\n";
}
/**
* @see Walker::start_el()
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param int $current_page Menu item ID.
* @param object $args
*/
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
/**
* Dividers, Headers or Disabled
* =============================
* Determine whether the item is a Divider, Header, Disabled or regular
* menu item. To prevent errors we use the strcasecmp() function to so a
* comparison that is not case sensitive. The strcasecmp() function returns
* a 0 if the strings are equal.
*/
if ( strcasecmp( $item->attr_title, 'divider' ) == 0 && $depth === 1 ) {
$output .= $indent . '<li role="presentation" class="divider">';
} else if ( strcasecmp( $item->title, 'divider') == 0 && $depth === 1 ) {
$output .= $indent . '<li role="presentation" class="divider">';
} else if ( strcasecmp( $item->attr_title, 'dropdown-header') == 0 && $depth === 1 ) {
$output .= $indent . '<li role="presentation" class="dropdown-header">' . esc_attr( $item->title );
} else if ( strcasecmp($item->attr_title, 'disabled' ) == 0 ) {
$output .= $indent . '<li role="presentation" class="disabled"><a href="#">' . esc_attr( $item->title ) . '</a>';
} else {
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
/*
if ( $args->has_children )
$class_names .= ' dropdown';
*/
if($args->has_children && $depth === 0) { $class_names .= ' dropdown'; } elseif($args->has_children && $depth > 0) { $class_names .= ' dropdown-submenu'; }
if ( in_array( 'current-menu-item', $classes ) )
$class_names .= ' active';
// remove Font Awesome icon from classes array and save the icon
// we will add the icon back in via a <span> below so it aligns with
// the menu item
if ( in_array('fa', $classes)) {
$key = array_search('fa', $classes);
$icon = $classes[$key + 1];
$class_names = str_replace($classes[$key+1], '', $class_names);
$class_names = str_replace($classes[$key], '', $class_names);
}
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$atts = array();
$atts['title'] = ! empty( $item->title ) ? $item->title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
// If item has_children add atts to a.
// if ( $args->has_children && $depth === 0 ) {
if ( $args->has_children ) {
$atts['href'] = '#';
$atts['data-toggle'] = 'dropdown';
$atts['class'] = 'dropdown-toggle';
} else {
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
}
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
// Font Awesome icons
if ( ! empty( $icon ) )
$item_output .= '<a'. $attributes .'><span class="fa ' . esc_attr( $icon ) . '"></span> ';
else
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= ( $args->has_children && 0 === $depth ) ? ' <span class="caret"></span></a>' : '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
/**
* Traverse elements to create list from elements.
*
* Display one element if the element doesn't have any children otherwise,
* display the element and its children. Will only traverse up to the max
* depth and no ignore elements under that depth.
*
* This method shouldn't be called directly, use the walk() method instead.
*
* @see Walker::start_el()
* @since 2.5.0
*
* @param object $element Data object
* @param array $children_elements List of elements to continue traversing.
* @param int $max_depth Max depth to traverse.
* @param int $depth Depth of current element.
* @param array $args
* @param string $output Passed by reference. Used to append additional content.
* @return null Null on failure with no changes to parameters.
*/
public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
if ( ! $element )
return;
$id_field = $this->db_fields['id'];
// Display this element.
if ( is_object( $args[0] ) )
$args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] );
parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
/**
* Menu Fallback
* =============
* If this function is assigned to the wp_nav_menu's fallback_cb variable
* and a manu has not been assigned to the theme location in the WordPress
* menu manager the function with display nothing to a non-logged in user,
* and will add a link to the WordPress menu manager if logged in as an admin.
*
* @param array $args passed from the wp_nav_menu function.
*
*/
public static function fallback( $args ) {
if ( current_user_can( 'manage_options' ) ) {
extract( $args );
$fb_output = null;
if ( $container ) {
$fb_output = '<' . $container;
if ( $container_id )
$fb_output .= ' id="' . $container_id . '"';
if ( $container_class )
$fb_output .= ' class="' . $container_class . '"';
$fb_output .= '>';
}
$fb_output .= '<ul';
if ( $menu_id )
$fb_output .= ' id="' . $menu_id . '"';
if ( $menu_class )
$fb_output .= ' class="' . $menu_class . '"';
$fb_output .= '>';
$fb_output .= '<li><a href="' . esc_url(admin_url( 'nav-menus.php' )) . '">'.__('Asigna un menu','cronista').'</a></li>';
$fb_output .= '</ul>';
if ( $container )
$fb_output .= '</' . $container . '>';
echo $fb_output;
}
}
} | ttthanhDC/ProjectTeamWP | wp-content/themes/cronista/assets/functions/cronista_navwalker.php | PHP | gpl-2.0 | 7,699 |
<?php
namespace TYPO3\Fluid\Tests\Unit\ViewHelpers;
/* *
* This script belongs to the TYPO3 Flow package "TYPO3.Fluid". *
* *
* It is free software; you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License, either version 3 *
* of the License, or (at your option) any later version. *
* *
* The TYPO3 project - inspiring people to share! *
* */
require_once(__DIR__ . '/ViewHelperBaseTestcase.php');
/**
* Test for the Form view helper
*/
class FormViewHelperTest extends \TYPO3\Fluid\ViewHelpers\ViewHelperBaseTestcase {
/**
* @var \TYPO3\Flow\Security\Cryptography\HashService
*/
protected $hashService;
/**
* @var \TYPO3\Flow\Security\Context
*/
protected $securityContext;
/**
* Set up test dependencies
*/
public function setUp() {
parent::setUp();
$this->arguments['action'] = '';
$this->arguments['arguments'] = array();
$this->arguments['controller'] = '';
$this->arguments['package'] = '';
$this->arguments['subpackage'] = '';
$this->arguments['method'] = '';
$this->arguments['object'] = NULL;
$this->arguments['section'] = '';
$this->arguments['absolute'] = FALSE;
$this->arguments['addQueryString'] = FALSE;
$this->arguments['format'] = '';
$this->arguments['additionalParams'] = array();
$this->arguments['argumentsToBeExcludedFromQueryString'] = array();
$this->arguments['useParentRequest'] = FALSE;
}
/**
* @param \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper $viewHelper
*/
protected function injectDependenciesIntoViewHelper(\TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper $viewHelper) {
$this->hashService = $this->getMock('TYPO3\Flow\Security\Cryptography\HashService');
$this->inject($viewHelper, 'hashService', $this->hashService);
$this->mvcPropertyMappingConfigurationService = $this->getMock('TYPO3\Flow\Mvc\Controller\MvcPropertyMappingConfigurationService');
$this->inject($viewHelper, 'mvcPropertyMappingConfigurationService', $this->mvcPropertyMappingConfigurationService);
$this->securityContext = $this->getMock('TYPO3\Flow\Security\Context');
$this->inject($viewHelper, 'securityContext', $this->securityContext);
parent::injectDependenciesIntoViewHelper($viewHelper);
}
/**
* @test
*/
public function renderAddsObjectToViewHelperVariableContainer() {
$formObject = new \stdClass();
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderAdditionalIdentityFields', 'renderHiddenReferrerFields', 'addFormObjectNameToViewHelperVariableContainer', 'addFieldNamePrefixToViewHelperVariableContainer', 'removeFormObjectNameFromViewHelperVariableContainer', 'removeFieldNamePrefixFromViewHelperVariableContainer', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$this->arguments['object'] = $formObject;
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$this->viewHelperVariableContainer->expects($this->at(0))->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObject', $formObject);
$this->viewHelperVariableContainer->expects($this->at(1))->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'additionalIdentityProperties', array());
$this->viewHelperVariableContainer->expects($this->at(2))->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'emptyHiddenFieldNames', array());
$this->viewHelperVariableContainer->expects($this->at(3))->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObject');
$this->viewHelperVariableContainer->expects($this->at(4))->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'additionalIdentityProperties');
$this->viewHelperVariableContainer->expects($this->at(5))->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'emptyHiddenFieldNames');
$viewHelper->render('index');
}
/**
* @test
*/
public function renderAddsObjectNameToTemplateVariableContainer() {
$objectName = 'someObjectName';
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormObjectToViewHelperVariableContainer', 'addFieldNamePrefixToViewHelperVariableContainer', 'removeFormObjectFromViewHelperVariableContainer', 'removeFieldNamePrefixFromViewHelperVariableContainer', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$this->arguments['name'] = $objectName;
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObjectName', $objectName);
$this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObjectName');
$viewHelper->render('index');
}
/**
* @test
*/
public function formObjectNameArgumentOverrulesNameArgument() {
$objectName = 'someObjectName';
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormObjectToViewHelperVariableContainer', 'addFieldNamePrefixToViewHelperVariableContainer', 'removeFormObjectFromViewHelperVariableContainer', 'removeFieldNamePrefixFromViewHelperVariableContainer', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$this->arguments['name'] = 'formName';
$this->arguments['objectName'] = $objectName;
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObjectName', $objectName);
$this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObjectName');
$viewHelper->render('index');
}
/**
* @test
*/
public function renderCallsRenderHiddenReferrerFields() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenReferrerFields', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$viewHelper->expects($this->once())->method('renderHiddenReferrerFields');
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$viewHelper->render('index');
}
/**
* @test
*/
public function renderCallsRenderHiddenIdentityField() {
$object = new \stdClass();
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'getFormObjectName'), array(), '', FALSE);
$this->arguments['object'] = $object;
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$viewHelper->expects($this->atLeastOnce())->method('getFormObjectName')->will($this->returnValue('MyName'));
$viewHelper->expects($this->once())->method('renderHiddenIdentityField')->with($object, 'MyName');
$viewHelper->render('index');
}
/**
* @test
*/
public function renderWithMethodGetAddsActionUriQueryAsHiddenFields() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE);
$this->arguments['method'] = 'GET';
$this->arguments['actionUri'] = 'http://localhost/fluid/test?foo=bar%20baz';
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$viewHelper->expects($this->any())->method('renderChildren')->will($this->returnValue('formContent'));
$expectedResult = chr(10) .
'<div style="display: none">' . chr(10) .
'<input type="hidden" name="foo" value="bar baz" />' . chr(10) .
'<input type="hidden" name="__referrer[@package]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[@subpackage]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[@controller]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[@action]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[arguments]" value="" />' . chr(10) .
'<input type="hidden" name="__trustedProperties" value="" />' . chr(10) . chr(10) .
'</div>' . chr(10) .
'formContent';
$this->tagBuilder->expects($this->once())->method('setContent')->with($expectedResult);
$viewHelper->render('index');
}
/**
* @test
*/
public function renderWithMethodGetDoesNotBreakInRenderHiddenActionUriQueryParametersIfNoQueryStringExists() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE);
$this->arguments['method'] = 'GET';
$this->arguments['actionUri'] = 'http://localhost/fluid/test';
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$viewHelper->expects($this->any())->method('renderChildren')->will($this->returnValue('formContent'));
$expectedResult = chr(10) .
'<div style="display: none">' . chr(10) .
'<input type="hidden" name="__referrer[@package]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[@subpackage]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[@controller]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[@action]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[arguments]" value="" />' . chr(10) .
'<input type="hidden" name="__trustedProperties" value="" />' . chr(10) . chr(10) .
'</div>' . chr(10) .
'formContent';
$this->tagBuilder->expects($this->once())->method('setContent')->with($expectedResult);
$viewHelper->render('index');
}
/**
* @test
*/
public function renderCallsRenderAdditionalIdentityFields() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderAdditionalIdentityFields'), array(), '', FALSE);
$viewHelper->expects($this->once())->method('renderAdditionalIdentityFields');
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$viewHelper->render('index');
}
/**
* @test
*/
public function renderWrapsHiddenFieldsWithDivForXhtmlCompatibility() {
$viewHelper = $this->getMock($this->buildAccessibleProxy('TYPO3\Fluid\ViewHelpers\FormViewHelper'), array('renderChildren', 'renderHiddenIdentityField', 'renderAdditionalIdentityFields', 'renderHiddenReferrerFields', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$viewHelper->expects($this->once())->method('renderHiddenIdentityField')->will($this->returnValue('hiddenIdentityField'));
$viewHelper->expects($this->once())->method('renderAdditionalIdentityFields')->will($this->returnValue('additionalIdentityFields'));
$viewHelper->expects($this->once())->method('renderHiddenReferrerFields')->will($this->returnValue('hiddenReferrerFields'));
$viewHelper->expects($this->once())->method('renderChildren')->will($this->returnValue('formContent'));
$viewHelper->expects($this->once())->method('renderEmptyHiddenFields')->will($this->returnValue('emptyHiddenFields'));
$viewHelper->expects($this->once())->method('renderTrustedPropertiesField')->will($this->returnValue('trustedPropertiesField'));
$expectedResult = chr(10) . '<div style="display: none">hiddenIdentityFieldadditionalIdentityFieldshiddenReferrerFieldsemptyHiddenFieldstrustedPropertiesField' . chr(10) . '</div>' . chr(10) . 'formContent';
$this->tagBuilder->expects($this->once())->method('setContent')->with($expectedResult);
$viewHelper->render('index');
}
/**
* @test
*/
public function renderAdditionalIdentityFieldsFetchesTheFieldsFromViewHelperVariableContainerAndBuildsHiddenFieldsForThem() {
$identityProperties = array(
'object1[object2]' => '<input type="hidden" name="object1[object2][__identity]" value="42" />',
'object1[object2][subobject]' => '<input type="hidden" name="object1[object2][subobject][__identity]" value="21" />'
);
$this->viewHelperVariableContainer->expects($this->once())->method('exists')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'additionalIdentityProperties')->will($this->returnValue(TRUE));
$this->viewHelperVariableContainer->expects($this->once())->method('get')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'additionalIdentityProperties')->will($this->returnValue($identityProperties));
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$expected = chr(10) . '<input type="hidden" name="object1[object2][__identity]" value="42" />' . chr(10) .
'<input type="hidden" name="object1[object2][subobject][__identity]" value="21" />';
$actual = $viewHelper->_call('renderAdditionalIdentityFields');
$this->assertEquals($expected, $actual);
}
/**
* @test
*/
public function renderHiddenReferrerFieldsAddCurrentControllerAndActionAsHiddenFields() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('dummy'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$this->request->expects($this->atLeastOnce())->method('getControllerPackageKey')->will($this->returnValue('packageKey'));
$this->request->expects($this->atLeastOnce())->method('getControllerSubpackageKey')->will($this->returnValue('subpackageKey'));
$this->request->expects($this->atLeastOnce())->method('getControllerName')->will($this->returnValue('controllerName'));
$this->request->expects($this->atLeastOnce())->method('getControllerActionName')->will($this->returnValue('controllerActionName'));
$hiddenFields = $viewHelper->_call('renderHiddenReferrerFields');
$expectedResult = chr(10) . '<input type="hidden" name="__referrer[@package]" value="packageKey" />' . chr(10) .
'<input type="hidden" name="__referrer[@subpackage]" value="subpackageKey" />' . chr(10) .
'<input type="hidden" name="__referrer[@controller]" value="controllerName" />' . chr(10) .
'<input type="hidden" name="__referrer[@action]" value="controllerActionName" />' . chr(10) .
'<input type="hidden" name="__referrer[arguments]" value="" />' . chr(10);
$this->assertEquals($expectedResult, $hiddenFields);
}
/**
* @test
*/
public function renderHiddenReferrerFieldsAddCurrentControllerAndActionOfParentAndSubRequestAsHiddenFields() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('dummy'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$mockSubRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), 'Foo', FALSE);
$mockSubRequest->expects($this->atLeastOnce())->method('isMainRequest')->will($this->returnValue(FALSE));
$mockSubRequest->expects($this->atLeastOnce())->method('getControllerPackageKey')->will($this->returnValue('subRequestPackageKey'));
$mockSubRequest->expects($this->atLeastOnce())->method('getControllerSubpackageKey')->will($this->returnValue('subRequestSubpackageKey'));
$mockSubRequest->expects($this->atLeastOnce())->method('getControllerName')->will($this->returnValue('subRequestControllerName'));
$mockSubRequest->expects($this->atLeastOnce())->method('getControllerActionName')->will($this->returnValue('subRequestControllerActionName'));
$mockSubRequest->expects($this->atLeastOnce())->method('getParentRequest')->will($this->returnValue($this->request));
$mockSubRequest->expects($this->atLeastOnce())->method('getArgumentNamespace')->will($this->returnValue('subRequestArgumentNamespace'));
$this->request->expects($this->atLeastOnce())->method('getControllerPackageKey')->will($this->returnValue('packageKey'));
$this->request->expects($this->atLeastOnce())->method('getControllerSubpackageKey')->will($this->returnValue('subpackageKey'));
$this->request->expects($this->atLeastOnce())->method('getControllerName')->will($this->returnValue('controllerName'));
$this->request->expects($this->atLeastOnce())->method('getControllerActionName')->will($this->returnValue('controllerActionName'));
$this->controllerContext = $this->getMock('TYPO3\Flow\Mvc\Controller\ControllerContext', array(), array(), '', FALSE);
$this->controllerContext->expects($this->atLeastOnce())->method('getRequest')->will($this->returnValue($mockSubRequest));
$this->renderingContext->setControllerContext($this->controllerContext);
$this->injectDependenciesIntoViewHelper($viewHelper);
$hiddenFields = $viewHelper->_call('renderHiddenReferrerFields');
$expectedResult = chr(10) . '<input type="hidden" name="subRequestArgumentNamespace[__referrer][@package]" value="subRequestPackageKey" />' . chr(10) .
'<input type="hidden" name="subRequestArgumentNamespace[__referrer][@subpackage]" value="subRequestSubpackageKey" />' . chr(10) .
'<input type="hidden" name="subRequestArgumentNamespace[__referrer][@controller]" value="subRequestControllerName" />' . chr(10) .
'<input type="hidden" name="subRequestArgumentNamespace[__referrer][@action]" value="subRequestControllerActionName" />' . chr(10) .
'<input type="hidden" name="subRequestArgumentNamespace[__referrer][arguments]" value="" />' . chr(10) .
'<input type="hidden" name="__referrer[@package]" value="packageKey" />' . chr(10) .
'<input type="hidden" name="__referrer[@subpackage]" value="subpackageKey" />' . chr(10) .
'<input type="hidden" name="__referrer[@controller]" value="controllerName" />' . chr(10) .
'<input type="hidden" name="__referrer[@action]" value="controllerActionName" />' . chr(10) .
'<input type="hidden" name="__referrer[arguments]" value="" />' . chr(10);
$this->assertEquals($expectedResult, $hiddenFields);
}
/**
* @test
*/
public function renderAddsSpecifiedPrefixToTemplateVariableContainer() {
$prefix = 'somePrefix';
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$this->arguments['fieldNamePrefix'] = $prefix;
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix', $prefix);
$this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix');
$viewHelper->render('index');
}
/**
* @test
*/
public function renderAddsNoFieldNamePrefixToTemplateVariableContainerIfNoPrefixIsSpecified() {
$expectedPrefix = '';
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix', $expectedPrefix);
$this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix');
$viewHelper->render('index');
}
/**
* @test
*/
public function renderAddsDefaultFieldNamePrefixToTemplateVariableContainerIfNoPrefixIsSpecifiedAndRequestIsASubRequest() {
$expectedPrefix = 'someArgumentPrefix';
$mockSubRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE);
$mockSubRequest->expects($this->once())->method('getArgumentNamespace')->will($this->returnValue($expectedPrefix));
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('getFormActionUri', 'renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$this->controllerContext = $this->getMock('TYPO3\Flow\Mvc\Controller\ControllerContext', array(), array(), '', FALSE);
$this->controllerContext->expects($this->any())->method('getRequest')->will($this->returnValue($mockSubRequest));
$this->renderingContext->setControllerContext($this->controllerContext);
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix', $expectedPrefix);
$this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix');
$viewHelper->render('index');
}
/**
* @test
*/
public function renderAddsDefaultFieldNamePrefixToTemplateVariableContainerIfNoPrefixIsSpecifiedAndUseParentRequestArgumentIsSet() {
$expectedPrefix = 'parentRequestsPrefix';
$mockParentRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE);
$mockParentRequest->expects($this->once())->method('getArgumentNamespace')->will($this->returnValue($expectedPrefix));
$mockSubRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE);
$mockSubRequest->expects($this->once())->method('getParentRequest')->will($this->returnValue($mockParentRequest));
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('getFormActionUri', 'renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE);
$this->arguments['useParentRequest'] = TRUE;
$this->controllerContext = $this->getMock('TYPO3\Flow\Mvc\Controller\ControllerContext', array(), array(), '', FALSE);
$this->controllerContext->expects($this->once())->method('getRequest')->will($this->returnValue($mockSubRequest));
$this->renderingContext->setControllerContext($this->controllerContext);
$this->injectDependenciesIntoViewHelper($viewHelper);
$this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE));
$this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix', $expectedPrefix);
$viewHelper->render('index');
}
/**
* @test
*/
public function renderEmptyHiddenFieldsRendersEmptyStringByDefault() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$expected = '';
$actual = $viewHelper->_call('renderEmptyHiddenFields');
$this->assertEquals($expected, $actual);
}
/**
* @test
*/
public function renderEmptyHiddenFieldsRendersOneHiddenFieldPerEntry() {
$emptyHiddenFieldNames = array('fieldName1', 'fieldName2');
$this->viewHelperVariableContainer->expects($this->once())->method('exists')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'emptyHiddenFieldNames')->will($this->returnValue(TRUE));
$this->viewHelperVariableContainer->expects($this->once())->method('get')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'emptyHiddenFieldNames')->will($this->returnValue($emptyHiddenFieldNames));
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$expected = '<input type="hidden" name="fieldName1" value="" />' . chr(10) . '<input type="hidden" name="fieldName2" value="" />' . chr(10);
$actual = $viewHelper->_call('renderEmptyHiddenFields');
$this->assertEquals($expected, $actual);
}
/**
* @test
*/
public function renderResetsFormActionUri() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$viewHelper->_set('formActionUri', 'someUri');
$viewHelper->render('index');
$this->assertNull($viewHelper->_get('formActionUri'));
}
/**
* @test
* @expectedException \TYPO3\Fluid\Core\ViewHelper\Exception
*/
public function renderThrowsExceptionIfNeitherActionNorActionUriArgumentIsSpecified() {
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE);
$this->injectDependenciesIntoViewHelper($viewHelper);
$viewHelper->render();
}
/**
* @test
*/
public function renderThrowsExceptionIfUseParentRequestIsSetAndTheCurrentRequestHasNoParentRequest() {
$this->setExpectedException('TYPO3\Fluid\Core\ViewHelper\Exception', '', 1361354942);
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE);
$this->arguments['useParentRequest'] = TRUE;
$this->injectDependenciesIntoViewHelper($viewHelper);
$viewHelper->render('index');
}
/**
* @test
*/
public function renderUsesParentRequestIfUseParentRequestIsSet() {
$mockParentRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE);
$mockSubRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE);
$mockSubRequest->expects($this->once())->method('isMainRequest')->will($this->returnValue(FALSE));
$mockSubRequest->expects($this->once())->method('getParentRequest')->will($this->returnValue($mockParentRequest));
$this->uriBuilder->expects($this->once())->method('setRequest')->with($mockParentRequest);
$viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('dummy'), array(), '', FALSE);
$this->arguments['useParentRequest'] = TRUE;
$this->controllerContext = $this->getMock('TYPO3\Flow\Mvc\Controller\ControllerContext', array(), array(), '', FALSE);
$this->controllerContext->expects($this->once())->method('getRequest')->will($this->returnValue($mockSubRequest));
$this->controllerContext->expects($this->once())->method('getUriBuilder')->will($this->returnValue($this->uriBuilder));
$this->renderingContext->setControllerContext($this->controllerContext);
$this->injectDependenciesIntoViewHelper($viewHelper);
$viewHelper->_call('getFormActionUri');
}
}
| garvitdelhi/emulate | Packages/Framework/TYPO3.Fluid/Tests/Unit/ViewHelpers/FormViewHelperTest.php | PHP | gpl-2.0 | 29,478 |
<?php
namespace TYPO3\Flow\Persistence\Doctrine\Proxies\__CG__\project\emulate\Domain\Model;
/**
* THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
*/
class UserAccount extends \project\emulate\Domain\Model\UserAccount implements \Doctrine\ORM\Proxy\Proxy
{
private $_entityPersister;
private $_identifier;
public $__isInitialized__ = false;
public function __construct($entityPersister, $identifier)
{
$this->_entityPersister = $entityPersister;
$this->_identifier = $identifier;
}
/** @private */
public function __load()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
if (method_exists($this, "__wakeup")) {
// call this after __isInitialized__to avoid infinite recursion
// but before loading to emulate what ClassMetadata::newInstance()
// provides.
$this->__wakeup();
}
if ($this->_entityPersister->load($this->_identifier, $this) === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
unset($this->_entityPersister, $this->_identifier);
}
}
/** @private */
public function __isInitialized()
{
return $this->__isInitialized__;
}
public function __wakeup()
{
$this->__load();
return parent::__wakeup();
}
public function Flow_Aop_Proxy_fixMethodsAndAdvicesArrayForDoctrineProxies()
{
$this->__load();
return parent::Flow_Aop_Proxy_fixMethodsAndAdvicesArrayForDoctrineProxies();
}
public function Flow_Aop_Proxy_fixInjectedPropertiesForDoctrineProxies()
{
$this->__load();
return parent::Flow_Aop_Proxy_fixInjectedPropertiesForDoctrineProxies();
}
public function Flow_Aop_Proxy_invokeJoinPoint(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint)
{
$this->__load();
return parent::Flow_Aop_Proxy_invokeJoinPoint($joinPoint);
}
public function getName()
{
$this->__load();
return parent::getName();
}
public function setName($name)
{
$this->__load();
return parent::setName($name);
}
public function getgender()
{
$this->__load();
return parent::getgender();
}
public function setgender($gender)
{
$this->__load();
return parent::setgender($gender);
}
public function getUsername()
{
$this->__load();
return parent::getUsername();
}
public function setUsername($username)
{
$this->__load();
return parent::setUsername($username);
}
public function getPassword()
{
$this->__load();
return parent::getPassword();
}
public function setPassword($password)
{
$this->__load();
return parent::setPassword($password);
}
public function getEmail()
{
$this->__load();
return parent::getEmail();
}
public function setEmail($email)
{
$this->__load();
return parent::setEmail($email);
}
public function getProfilePic()
{
$this->__load();
return parent::getProfilePic();
}
public function setProfilePic($profilePic)
{
$this->__load();
return parent::setProfilePic($profilePic);
}
public function getEmulatorPreference()
{
$this->__load();
return parent::getEmulatorPreference();
}
public function setEmulatorPreference($emulatorPreference)
{
$this->__load();
return parent::setEmulatorPreference($emulatorPreference);
}
public function getEmulatorMode()
{
$this->__load();
return parent::getEmulatorMode();
}
public function setEmulatorMode($emulatorMode)
{
$this->__load();
return parent::setEmulatorMode($emulatorMode);
}
public function Validate($userAccountRepository, $user)
{
$this->__load();
return parent::Validate($userAccountRepository, $user);
}
public function __sleep()
{
return array_merge(array('__isInitialized__'), parent::__sleep());
}
public function __clone()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
$class = $this->_entityPersister->getClassMetadata();
$original = $this->_entityPersister->load($this->_identifier);
if ($original === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
foreach ($class->reflFields as $field => $reflProperty) {
$reflProperty->setValue($this, $reflProperty->getValue($original));
}
unset($this->_entityPersister, $this->_identifier);
}
parent::__clone();
}
} | garvitdelhi/emulate | Data/Temporary/Development/Doctrine/Proxies/__CG__projectemulateDomainModelUserAccount.php | PHP | gpl-2.0 | 4,993 |
from settings import *
import pymysql
def getconn():
conn = pymysql.connect( charset = 'utf8',
host = DATABASES['default']['HOST'],
port = DATABASES['default']['PORT'],
user = DATABASES['default']['USER'],
passwd = DATABASES['default']['PASSWORD'],
db = DATABASES['default']['NAME'])
return conn
def loadSqlScript(sqlScript):
f = open(sqlScript)
query = ''
for line in f:
query = query + line
return query
| kassine/caparis2mysql | sqlTools.py | Python | gpl-2.0 | 602 |
/****************************************************************************
** $Id: qpngio.cpp 2 2005-11-16 15:49:26Z dmik $
**
** Implementation of PNG QImage IOHandler
**
** Created : 970521
**
** Copyright (C) 1992-2003 Trolltech AS. All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "qpngio.h"
#ifndef QT_NO_IMAGEIO_PNG
#include "qasyncimageio.h"
#include "qiodevice.h"
#include <png.h>
#ifdef Q_OS_TEMP
#define CALLBACK_CALL_TYPE __cdecl
#else
#define CALLBACK_CALL_TYPE
#endif
/*
All PNG files load to the minimal QImage equivalent.
All QImage formats output to reasonably efficient PNG equivalents.
Never to grayscale.
*/
#if defined(Q_C_CALLBACKS)
extern "C" {
#endif
static
void CALLBACK_CALL_TYPE iod_read_fn(png_structp png_ptr, png_bytep data, png_size_t length)
{
QImageIO* iio = (QImageIO*)png_get_io_ptr(png_ptr);
QIODevice* in = iio->ioDevice();
while (length) {
int nr = in->readBlock((char*)data, length);
if (nr <= 0) {
png_error(png_ptr, "Read Error");
return;
}
length -= nr;
}
}
static
void CALLBACK_CALL_TYPE qpiw_write_fn( png_structp png_ptr, png_bytep data, png_size_t length )
{
QPNGImageWriter* qpiw = (QPNGImageWriter*)png_get_io_ptr( png_ptr );
QIODevice* out = qpiw->device();
uint nr = out->writeBlock( (char*)data, length );
if ( nr != length ) {
png_error( png_ptr, "Write Error" );
return;
}
}
static
void CALLBACK_CALL_TYPE qpiw_flush_fn( png_structp png_ptr )
{
QPNGImageWriter* qpiw = (QPNGImageWriter*)png_get_io_ptr( png_ptr );
QIODevice* out = qpiw->device();
out->flush();
}
#if defined(Q_C_CALLBACKS)
}
#endif
static
void setup_qt( QImage& image, png_structp png_ptr, png_infop info_ptr, float screen_gamma=0.0 )
{
if ( screen_gamma != 0.0 && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) ) {
double file_gamma;
png_get_gAMA(png_ptr, info_ptr, &file_gamma);
png_set_gamma( png_ptr, screen_gamma, file_gamma );
}
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
0, 0, 0);
if ( color_type == PNG_COLOR_TYPE_GRAY ) {
// Black & White or 8-bit grayscale
if ( bit_depth == 1 && info_ptr->channels == 1 ) {
png_set_invert_mono( png_ptr );
png_read_update_info( png_ptr, info_ptr );
if (!image.create( width, height, 1, 2, QImage::BigEndian ))
return;
image.setColor( 1, qRgb(0,0,0) );
image.setColor( 0, qRgb(255,255,255) );
} else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_expand(png_ptr);
png_set_strip_16(png_ptr);
png_set_gray_to_rgb(png_ptr);
if (!image.create(width, height, 32))
return;
image.setAlphaBuffer(TRUE);
if (QImage::systemByteOrder() == QImage::BigEndian)
png_set_swap_alpha(png_ptr);
png_read_update_info(png_ptr, info_ptr);
} else {
if ( bit_depth == 16 )
png_set_strip_16(png_ptr);
else if ( bit_depth < 8 )
png_set_packing(png_ptr);
int ncols = bit_depth < 8 ? 1 << bit_depth : 256;
png_read_update_info(png_ptr, info_ptr);
if (!image.create(width, height, 8, ncols))
return;
for (int i=0; i<ncols; i++) {
int c = i*255/(ncols-1);
image.setColor( i, qRgba(c,c,c,0xff) );
}
if ( png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ) {
const int g = info_ptr->trans_values.gray;
if (g < ncols) {
image.setAlphaBuffer(TRUE);
image.setColor(g, image.color(g) & RGB_MASK);
}
}
}
} else if ( color_type == PNG_COLOR_TYPE_PALETTE
&& png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE)
&& info_ptr->num_palette <= 256 )
{
// 1-bit and 8-bit color
if ( bit_depth != 1 )
png_set_packing( png_ptr );
png_read_update_info( png_ptr, info_ptr );
png_get_IHDR(png_ptr, info_ptr,
&width, &height, &bit_depth, &color_type, 0, 0, 0);
if (!image.create(width, height, bit_depth, info_ptr->num_palette,
QImage::BigEndian))
return;
int i = 0;
if ( png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ) {
image.setAlphaBuffer( TRUE );
while ( i < info_ptr->num_trans ) {
image.setColor(i, qRgba(
info_ptr->palette[i].red,
info_ptr->palette[i].green,
info_ptr->palette[i].blue,
info_ptr->trans[i]
)
);
i++;
}
}
while ( i < info_ptr->num_palette ) {
image.setColor(i, qRgba(
info_ptr->palette[i].red,
info_ptr->palette[i].green,
info_ptr->palette[i].blue,
0xff
)
);
i++;
}
} else {
// 32-bit
if ( bit_depth == 16 )
png_set_strip_16(png_ptr);
png_set_expand(png_ptr);
if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA )
png_set_gray_to_rgb(png_ptr);
if (!image.create(width, height, 32))
return;
// Only add filler if no alpha, or we can get 5 channel data.
if (!(color_type & PNG_COLOR_MASK_ALPHA)
&& !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_filler(png_ptr, 0xff,
QImage::systemByteOrder() == QImage::BigEndian ?
PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
// We want 4 bytes, but it isn't an alpha channel
} else {
image.setAlphaBuffer(TRUE);
}
if ( QImage::systemByteOrder() == QImage::BigEndian ) {
png_set_swap_alpha(png_ptr);
}
png_read_update_info(png_ptr, info_ptr);
}
// Qt==ARGB==Big(ARGB)==Little(BGRA)
if ( QImage::systemByteOrder() == QImage::LittleEndian ) {
png_set_bgr(png_ptr);
}
}
#if defined(Q_C_CALLBACKS)
extern "C" {
#endif
static void CALLBACK_CALL_TYPE qt_png_warning(png_structp /*png_ptr*/, png_const_charp message)
{
qWarning("libpng warning: %s", message);
}
#if defined(Q_C_CALLBACKS)
}
#endif
static
void read_png_image(QImageIO* iio)
{
png_structp png_ptr;
png_infop info_ptr;
png_infop end_info;
png_bytep* row_pointers;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0);
if (!png_ptr) {
iio->setStatus(-1);
return;
}
png_set_error_fn(png_ptr, 0, 0, qt_png_warning);
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, 0, 0);
iio->setStatus(-2);
return;
}
end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
iio->setStatus(-3);
return;
}
if (setjmp(png_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
iio->setStatus(-4);
return;
}
png_set_read_fn(png_ptr, (void*)iio, iod_read_fn);
png_read_info(png_ptr, info_ptr);
QImage image;
setup_qt(image, png_ptr, info_ptr, iio->gamma());
if (image.isNull()) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
iio->setStatus(-5);
return;
}
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
0, 0, 0);
uchar** jt = image.jumpTable();
row_pointers=new png_bytep[height];
for (uint y=0; y<height; y++) {
row_pointers[y]=jt[y];
}
png_read_image(png_ptr, row_pointers);
#if 0 // libpng takes care of this.
png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)
if (image.depth()==32 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
QRgb trans = 0xFF000000 | qRgb(
(info_ptr->trans_values.red << 8 >> bit_depth)&0xff,
(info_ptr->trans_values.green << 8 >> bit_depth)&0xff,
(info_ptr->trans_values.blue << 8 >> bit_depth)&0xff);
for (uint y=0; y<height; y++) {
for (uint x=0; x<info_ptr->width; x++) {
if (((uint**)jt)[y][x] == trans) {
((uint**)jt)[y][x] &= 0x00FFFFFF;
} else {
}
}
}
}
#endif
image.setDotsPerMeterX(png_get_x_pixels_per_meter(png_ptr,info_ptr));
image.setDotsPerMeterY(png_get_y_pixels_per_meter(png_ptr,info_ptr));
#ifndef QT_NO_IMAGE_TEXT
png_textp text_ptr;
int num_text=0;
png_get_text(png_ptr,info_ptr,&text_ptr,&num_text);
while (num_text--) {
image.setText(text_ptr->key,0,text_ptr->text);
text_ptr++;
}
#endif
delete [] row_pointers;
if ( image.hasAlphaBuffer() ) {
// Many PNG files lie (eg. from PhotoShop). Fortunately this loop will
// usually be quick to find those that tell the truth.
QRgb* c;
int n;
if (image.depth()==32) {
c = (QRgb*)image.bits();
n = image.bytesPerLine() * image.height() / 4;
} else {
c = image.colorTable();
n = image.numColors();
}
while ( n-- && qAlpha(*c++)==0xff )
;
if ( n<0 ) // LIAR!
image.setAlphaBuffer(FALSE);
}
iio->setImage(image);
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
iio->setStatus(0);
}
QPNGImageWriter::QPNGImageWriter(QIODevice* iod) :
dev(iod),
frames_written(0),
disposal(Unspecified),
looping(-1),
ms_delay(-1),
gamma(0.0)
{
}
QPNGImageWriter::~QPNGImageWriter()
{
}
void QPNGImageWriter::setDisposalMethod(DisposalMethod dm)
{
disposal = dm;
}
void QPNGImageWriter::setLooping(int loops)
{
looping = loops;
}
void QPNGImageWriter::setFrameDelay(int msecs)
{
ms_delay = msecs;
}
void QPNGImageWriter::setGamma(float g)
{
gamma = g;
}
#ifndef QT_NO_IMAGE_TEXT
static void set_text(const QImage& image, png_structp png_ptr, png_infop info_ptr, bool short_not_long)
{
QValueList<QImageTextKeyLang> keys = image.textList();
if ( keys.count() ) {
png_textp text_ptr = new png_text[keys.count()];
int i=0;
for (QValueList<QImageTextKeyLang>::Iterator it=keys.begin();
it != keys.end(); ++it)
{
QString t = image.text(*it);
if ( (t.length() <= 200) == short_not_long ) {
if ( t.length() < 40 )
text_ptr[i].compression = PNG_TEXT_COMPRESSION_NONE;
else
text_ptr[i].compression = PNG_TEXT_COMPRESSION_zTXt;
text_ptr[i].key = (png_charp)(*it).key.data();
text_ptr[i].text = (png_charp)t.latin1();
//text_ptr[i].text = qstrdup(t.latin1());
i++;
}
}
png_set_text(png_ptr, info_ptr, text_ptr, i);
//for (int j=0; j<i; j++)
//free(text_ptr[i].text);
delete [] text_ptr;
}
}
#endif
bool QPNGImageWriter::writeImage(const QImage& image, int off_x, int off_y)
{
return writeImage(image, -1, off_x, off_y);
}
bool QPNGImageWriter::writeImage(const QImage& image, int quality_in, int off_x_in, int off_y_in)
{
QPoint offset = image.offset();
int off_x = off_x_in + offset.x();
int off_y = off_y_in + offset.y();
png_structp png_ptr;
png_infop info_ptr;
png_bytep* row_pointers;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,0,0,0);
if (!png_ptr) {
return FALSE;
}
png_set_error_fn(png_ptr, 0, 0, qt_png_warning);
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, 0);
return FALSE;
}
if (setjmp(png_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return FALSE;
}
int quality = quality_in;
if (quality >= 0) {
if (quality > 9) {
#if defined(QT_CHECK_RANGE)
qWarning( "PNG: Quality %d out of range", quality );
#endif
quality = 9;
}
png_set_compression_level(png_ptr, quality);
}
if (gamma != 0.0) {
png_set_gAMA(png_ptr, info_ptr, 1.0/gamma);
}
png_set_write_fn(png_ptr, (void*)this, qpiw_write_fn, qpiw_flush_fn);
info_ptr->channels =
(image.depth() == 32)
? (image.hasAlphaBuffer() ? 4 : 3)
: 1;
png_set_IHDR(png_ptr, info_ptr, image.width(), image.height(),
image.depth() == 1 ? 1 : 8 /* per channel */,
image.depth() == 32
? image.hasAlphaBuffer()
? PNG_COLOR_TYPE_RGB_ALPHA
: PNG_COLOR_TYPE_RGB
: PNG_COLOR_TYPE_PALETTE, 0, 0, 0);
//png_set_sBIT(png_ptr, info_ptr, 8);
info_ptr->sig_bit.red = 8;
info_ptr->sig_bit.green = 8;
info_ptr->sig_bit.blue = 8;
if (image.depth() == 1 && image.bitOrder() == QImage::LittleEndian)
png_set_packswap(png_ptr);
png_colorp palette = 0;
png_bytep copy_trans = 0;
if (image.numColors()) {
// Paletted
int num_palette = image.numColors();
palette = new png_color[num_palette];
png_set_PLTE(png_ptr, info_ptr, palette, num_palette);
int* trans = new int[num_palette];
int num_trans = 0;
for (int i=0; i<num_palette; i++) {
QRgb rgb=image.color(i);
info_ptr->palette[i].red = qRed(rgb);
info_ptr->palette[i].green = qGreen(rgb);
info_ptr->palette[i].blue = qBlue(rgb);
if (image.hasAlphaBuffer()) {
trans[i] = rgb >> 24;
if (trans[i] < 255) {
num_trans = i+1;
}
}
}
if (num_trans) {
copy_trans = new png_byte[num_trans];
for (int i=0; i<num_trans; i++)
copy_trans[i] = trans[i];
png_set_tRNS(png_ptr, info_ptr, copy_trans, num_trans, 0);
}
delete [] trans;
}
if ( image.hasAlphaBuffer() ) {
info_ptr->sig_bit.alpha = 8;
}
// Swap ARGB to RGBA (normal PNG format) before saving on
// BigEndian machines
if ( QImage::systemByteOrder() == QImage::BigEndian ) {
png_set_swap_alpha(png_ptr);
}
// Qt==ARGB==Big(ARGB)==Little(BGRA)
if ( QImage::systemByteOrder() == QImage::LittleEndian ) {
png_set_bgr(png_ptr);
}
if (off_x || off_y) {
png_set_oFFs(png_ptr, info_ptr, off_x, off_y, PNG_OFFSET_PIXEL);
}
if ( frames_written > 0 )
png_set_sig_bytes(png_ptr, 8);
if ( image.dotsPerMeterX() > 0 || image.dotsPerMeterY() > 0 ) {
png_set_pHYs(png_ptr, info_ptr,
image.dotsPerMeterX(), image.dotsPerMeterY(),
PNG_RESOLUTION_METER);
}
#ifndef QT_NO_IMAGE_TEXT
// Write short texts early.
set_text(image,png_ptr,info_ptr,TRUE);
#endif
png_write_info(png_ptr, info_ptr);
#ifndef QT_NO_IMAGE_TEXT
// Write long texts later.
set_text(image,png_ptr,info_ptr,FALSE);
#endif
if ( image.depth() != 1 )
png_set_packing(png_ptr);
if ( image.depth() == 32 && !image.hasAlphaBuffer() )
png_set_filler(png_ptr, 0,
QImage::systemByteOrder() == QImage::BigEndian ?
PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
if ( looping >= 0 && frames_written == 0 ) {
uchar data[13] = "NETSCAPE2.0";
// 0123456789aBC
data[0xB] = looping%0x100;
data[0xC] = looping/0x100;
png_write_chunk(png_ptr, (png_byte*)"gIFx", data, 13);
}
if ( ms_delay >= 0 || disposal!=Unspecified ) {
uchar data[4];
data[0] = disposal;
data[1] = 0;
data[2] = (ms_delay/10)/0x100; // hundredths
data[3] = (ms_delay/10)%0x100;
png_write_chunk(png_ptr, (png_byte*)"gIFg", data, 4);
}
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
0, 0, 0);
uchar** jt = image.jumpTable();
row_pointers=new png_bytep[height];
uint y;
for (y=0; y<height; y++) {
row_pointers[y]=jt[y];
}
png_write_image(png_ptr, row_pointers);
delete [] row_pointers;
png_write_end(png_ptr, info_ptr);
frames_written++;
if ( palette )
delete [] palette;
if ( copy_trans )
delete [] copy_trans;
png_destroy_write_struct(&png_ptr, &info_ptr);
return TRUE;
}
static
void write_png_image(QImageIO* iio)
{
QPNGImageWriter writer(iio->ioDevice());
int quality = iio->quality();
if ( quality >= 0 ) {
quality = QMIN( quality, 100 );
quality = (100-quality) * 9 / 91; // map [0,100] -> [9,0]
}
writer.setGamma(iio->gamma());
bool ok = writer.writeImage( iio->image(), quality );
iio->setStatus( ok ? 0 : -1 );
}
/*!
\class QPNGImagePacker qpngio.h
\brief The QPNGImagePacker class creates well-compressed PNG animations.
\ingroup images
\ingroup graphics
By using transparency, QPNGImagePacker allows you to build a PNG
image from a sequence of QImages.
Images are added using packImage().
*/
/*!
Creates an image packer that writes PNG data to IO device \a iod
using a \a storage_depth bit encoding (use 8 or 32, depending on
the desired quality and compression requirements).
If the image needs to be modified to fit in a lower-resolution
result (e.g. converting from 32-bit to 8-bit), use the \a
conversionflags to specify how you'd prefer this to happen.
\sa Qt::ImageConversionFlags
*/
QPNGImagePacker::QPNGImagePacker(QIODevice* iod, int storage_depth,
int conversionflags) :
QPNGImageWriter(iod),
depth(storage_depth),
convflags(conversionflags),
alignx(1)
{
}
/*!
Aligns pixel differences to \a x pixels. For example, using 8 can
improve playback on certain hardware. Normally the default of
1-pixel alignment (i.e. no alignment) gives better compression and
performance.
*/
void QPNGImagePacker::setPixelAlignment(int x)
{
alignx = x;
}
/*!
Adds the image \a img to the PNG animation, analyzing the
differences between this and the previous image to improve
compression.
*/
bool QPNGImagePacker::packImage(const QImage& img)
{
QImage image = img.convertDepth(32);
if ( previous.isNull() ) {
// First image
writeImage(image.convertDepth(depth,convflags));
} else {
bool done;
int minx, maxx, miny, maxy;
int w = image.width();
int h = image.height();
QRgb** jt = (QRgb**)image.jumpTable();
QRgb** pjt = (QRgb**)previous.jumpTable();
// Find left edge of change
done = FALSE;
for (minx = 0; minx < w && !done; minx++) {
for (int ty = 0; ty < h; ty++) {
if ( jt[ty][minx] != pjt[ty][minx] ) {
done = TRUE;
break;
}
}
}
minx--;
// Find right edge of change
done = FALSE;
for (maxx = w-1; maxx >= 0 && !done; maxx--) {
for (int ty = 0; ty < h; ty++) {
if ( jt[ty][maxx] != pjt[ty][maxx] ) {
done = TRUE;
break;
}
}
}
maxx++;
// Find top edge of change
done = FALSE;
for (miny = 0; miny < h && !done; miny++) {
for (int tx = 0; tx < w; tx++) {
if ( jt[miny][tx] != pjt[miny][tx] ) {
done = TRUE;
break;
}
}
}
miny--;
// Find right edge of change
done = FALSE;
for (maxy = h-1; maxy >= 0 && !done; maxy--) {
for (int tx = 0; tx < w; tx++) {
if ( jt[maxy][tx] != pjt[maxy][tx] ) {
done = TRUE;
break;
}
}
}
maxy++;
if ( minx > maxx ) minx=maxx=0;
if ( miny > maxy ) miny=maxy=0;
if ( alignx > 1 ) {
minx -= minx % alignx;
maxx = maxx - maxx % alignx + alignx - 1;
}
int dw = maxx-minx+1;
int dh = maxy-miny+1;
QImage diff(dw, dh, 32);
diff.setAlphaBuffer(TRUE);
int x, y;
if ( alignx < 1 )
alignx = 1;
for (y = 0; y < dh; y++) {
QRgb* li = (QRgb*)image.scanLine(y+miny)+minx;
QRgb* lp = (QRgb*)previous.scanLine(y+miny)+minx;
QRgb* ld = (QRgb*)diff.scanLine(y);
if ( alignx ) {
for (x = 0; x < dw; x+=alignx) {
int i;
for (i=0; i<alignx; i++) {
if ( li[x+i] != lp[x+i] )
break;
}
if ( i == alignx ) {
// All the same
for (i=0; i<alignx; i++) {
ld[x+i] = qRgba(0,0,0,0);
}
} else {
// Some different
for (i=0; i<alignx; i++) {
ld[x+i] = 0xff000000 | li[x+i];
}
}
}
} else {
for (x = 0; x < dw; x++) {
if ( li[x] != lp[x] )
ld[x] = 0xff000000 | li[x];
else
ld[x] = qRgba(0,0,0,0);
}
}
}
diff = diff.convertDepth(depth,convflags);
if ( !writeImage(diff, minx, miny) )
return FALSE;
}
previous = image;
return TRUE;
}
#ifndef QT_NO_ASYNC_IMAGE_IO
class QPNGFormat : public QImageFormat {
public:
QPNGFormat();
virtual ~QPNGFormat();
int decode(QImage& img, QImageConsumer* consumer,
const uchar* buffer, int length);
void info(png_structp png_ptr, png_infop info);
void row(png_structp png_ptr, png_bytep new_row,
png_uint_32 row_num, int pass);
void end(png_structp png_ptr, png_infop info);
#ifdef PNG_USER_CHUNKS_SUPPORTED
int user_chunk(png_structp png_ptr,
png_bytep data, png_uint_32 length);
#endif
private:
// Animation-level information
enum { MovieStart, FrameStart, Inside, End } state;
int first_frame;
int base_offx;
int base_offy;
// Image-level information
png_structp png_ptr;
png_infop info_ptr;
// Temporary locals during single data-chunk processing
QImageConsumer* consumer;
QImage* image;
int unused_data;
};
class QPNGFormatType : public QImageFormatType
{
QImageFormat* decoderFor(const uchar* buffer, int length);
const char* formatName() const;
};
/*
\class QPNGFormat qpngio.h
\brief The QPNGFormat class provides an incremental image decoder for PNG
image format.
\ingroup images
\ingroup graphics
This subclass of QImageFormat decodes PNG format images,
including animated PNGs.
Animated PNG images are standard PNG images. The PNG standard
defines two extension chunks that are useful for animations:
\list
\i gIFg - GIF-like Graphic Control Extension.
This includes frame disposal, user input flag (we ignore this),
and inter-frame delay.
\i gIFx - GIF-like Application Extension.
This is multi-purpose, but we just use the Netscape extension
which specifies looping.
\endlist
The subimages usually contain a offset chunk (oFFs) but need not.
The first image defines the "screen" size. Any subsequent image that
doesn't fit is clipped.
*/
/* ###TODO: decide on this point. gIFg gives disposal types, so it can be done.
All images paste (\e not composite, just place all-channel copying)
over the previous image to produce a subsequent frame.
*/
/*
\class QPNGFormatType qasyncimageio.h
\brief The QPNGFormatType class provides an incremental image decoder
for PNG image format.
\ingroup images
\ingroup graphics
\ingroup io
This subclass of QImageFormatType recognizes PNG format images, creating
a QPNGFormat when required. An instance of this class is created
automatically before any other factories, so you should have no need for
such objects.
*/
QImageFormat* QPNGFormatType::decoderFor(
const uchar* buffer, int length)
{
if (length < 8) return 0;
if (buffer[0]==137
&& buffer[1]=='P'
&& buffer[2]=='N'
&& buffer[3]=='G'
&& buffer[4]==13
&& buffer[5]==10
&& buffer[6]==26
&& buffer[7]==10)
return new QPNGFormat;
return 0;
}
const char* QPNGFormatType::formatName() const
{
return "PNG";
}
#if defined(Q_C_CALLBACKS)
extern "C" {
#endif
static void
CALLBACK_CALL_TYPE info_callback(png_structp png_ptr, png_infop info)
{
QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr);
that->info(png_ptr,info);
}
static void
CALLBACK_CALL_TYPE row_callback(png_structp png_ptr, png_bytep new_row,
png_uint_32 row_num, int pass)
{
QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr);
that->row(png_ptr,new_row,row_num,pass);
}
static void
CALLBACK_CALL_TYPE end_callback(png_structp png_ptr, png_infop info)
{
QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr);
that->end(png_ptr,info);
}
#if 0
#ifdef PNG_USER_CHUNKS_SUPPORTED
static int
CALLBACK_CALL_TYPE user_chunk_callback(png_structp png_ptr,
png_unknown_chunkp chunk)
{
QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr);
return that->user_chunk(png_ptr,chunk->data,chunk->size);
}
#endif
#endif
#if defined(Q_C_CALLBACKS)
}
#endif
/*!
Constructs a QPNGFormat object.
*/
QPNGFormat::QPNGFormat()
{
state = MovieStart;
first_frame = 1;
base_offx = 0;
base_offy = 0;
png_ptr = 0;
info_ptr = 0;
}
/*!
Destroys a QPNGFormat object.
*/
QPNGFormat::~QPNGFormat()
{
if ( png_ptr )
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
}
/*!
This function decodes some data into image changes.
Returns the number of bytes consumed.
*/
int QPNGFormat::decode(QImage& img, QImageConsumer* cons,
const uchar* buffer, int length)
{
consumer = cons;
image = &img;
if ( state != Inside ) {
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
if (!png_ptr) {
info_ptr = 0;
image = 0;
return -1;
}
png_set_error_fn(png_ptr, 0, 0, qt_png_warning);
png_set_compression_level(png_ptr, 9);
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
image = 0;
return -1;
}
if (setjmp((png_ptr)->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
image = 0;
return -1;
}
png_set_progressive_read_fn(png_ptr, (void *)this,
info_callback, row_callback, end_callback);
#ifdef PNG_USER_CHUNKS_SUPPORTED
// Can't do this yet. libpng has a crash bug with unknown (user) chunks.
// Warwick has sent them a patch.
// png_set_read_user_chunk_fn(png_ptr, 0, user_chunk_callback);
// png_set_keep_unknown_chunks(png_ptr, 2/*HANDLE_CHUNK_IF_SAFE*/, 0, 0);
#endif
if ( state != MovieStart && *buffer != 0211 ) {
// Good, no signature - the preferred way to concat PNG images.
// Skip them.
png_set_sig_bytes(png_ptr, 8);
}
state = Inside;
}
if ( !png_ptr ) return 0;
if (setjmp(png_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
image = 0;
state = MovieStart;
return -1;
}
unused_data = 0;
png_process_data(png_ptr, info_ptr, (png_bytep)buffer, length);
int l = length - unused_data;
// TODO: send incremental stuff to consumer (optional)
if ( state != Inside ) {
if ( png_ptr )
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
}
image = 0;
return l;
}
void QPNGFormat::info(png_structp png, png_infop)
{
png_set_interlace_handling(png);
setup_qt(*image, png, info_ptr);
}
void QPNGFormat::row(png_structp png, png_bytep new_row,
png_uint_32 row_num, int)
{
uchar* old_row = image->scanLine(row_num);
png_progressive_combine_row(png, old_row, new_row);
}
void QPNGFormat::end(png_structp png, png_infop info)
{
int offx = png_get_x_offset_pixels(png,info) - base_offx;
int offy = png_get_y_offset_pixels(png,info) - base_offy;
if ( first_frame ) {
base_offx = offx;
base_offy = offy;
first_frame = 0;
}
image->setOffset(QPoint(offx,offy));
image->setDotsPerMeterX(png_get_x_pixels_per_meter(png,info));
image->setDotsPerMeterY(png_get_y_pixels_per_meter(png,info));
#ifndef QT_NO_IMAGE_TEXT
png_textp text_ptr;
int num_text=0;
png_get_text(png,info,&text_ptr,&num_text);
while (num_text--) {
image->setText(text_ptr->key,0,text_ptr->text);
text_ptr++;
}
#endif
QRect r(0,0,image->width(),image->height());
consumer->frameDone(QPoint(offx,offy),r);
consumer->end();
state = FrameStart;
unused_data = (int)png->buffer_size; // Since libpng doesn't tell us
}
#ifdef PNG_USER_CHUNKS_SUPPORTED
/*
#ifndef QT_NO_IMAGE_TEXT
static bool skip(png_uint_32& max, png_bytep& data)
{
while (*data) {
if ( !max ) return FALSE;
max--;
data++;
}
if ( !max ) return FALSE;
max--;
data++; // skip to after NUL
return TRUE;
}
#endif
*/
int QPNGFormat::user_chunk(png_structp png,
png_bytep data, png_uint_32 length)
{
#if 0 // NOT SUPPORTED: experimental PNG animation.
// qDebug("Got %ld-byte %s chunk", length, png->chunk_name);
if ( 0==qstrcmp((char*)png->chunk_name, "gIFg")
&& length == 4 ) {
//QPNGImageWriter::DisposalMethod disposal =
// (QPNGImageWriter::DisposalMethod)data[0];
// ### TODO: use the disposal method
int ms_delay = ((data[2] << 8) | data[3])*10;
consumer->setFramePeriod(ms_delay);
return 1;
} else if ( 0==qstrcmp((char*)png->chunk_name, "gIFx")
&& length == 13 ) {
if ( qstrncmp((char*)data,"NETSCAPE2.0",11)==0 ) {
int looping = (data[0xC]<<8)|data[0xB];
consumer->setLooping(looping);
return 1;
}
}
#else
Q_UNUSED( png )
Q_UNUSED( data )
Q_UNUSED( length )
#endif
#ifndef QT_NO_IMAGE_TEXT
/*
libpng now supports this chunk.
if ( 0==qstrcmp((char*)png->chunk_name, "iTXt") && length>=6 ) {
const char* keyword = (const char*)data;
if ( !skip(length,data) ) return 0;
if ( length >= 4 ) {
char compression_flag = *data++;
char compression_method = *data++;
if ( compression_flag == compression_method ) {
// fool the compiler into thinking they're used
}
const char* lang = (const char*)data;
if ( !skip(length,data) ) return 0;
// const char* keyword_utf8 = (const char*)data;
if ( !skip(length,data) ) return 0;
const char* text_utf8 = (const char*)data;
if ( !skip(length,data) ) return 0;
QString text = QString::fromUtf8(text_utf8);
image->setText(keyword,lang[0] ? lang : 0,text);
return 1;
}
}
*/
#endif
return 0;
}
#endif
static QPNGFormatType* globalPngFormatTypeObject = 0;
#endif // QT_NO_ASYNC_IMAGE_IO
static bool done = FALSE;
void qCleanupPngIO()
{
#ifndef QT_NO_ASYNC_IMAGE_IO
if ( globalPngFormatTypeObject ) {
delete globalPngFormatTypeObject;
globalPngFormatTypeObject = 0;
}
#endif
done = FALSE;
}
void qInitPngIO()
{
if ( !done ) {
done = TRUE;
QImageIO::defineIOHandler( "PNG", "^.PNG\r", 0, read_png_image,
write_png_image);
#ifndef QT_NO_ASYNC_IMAGE_IO
globalPngFormatTypeObject = new QPNGFormatType;
#endif
qAddPostRoutine( qCleanupPngIO );
}
}
void qt_zlib_compression_hack()
{
compress(0,0,0,0);
uncompress(0,0,0,0);
}
#endif // QT_NO_IMAGEIO_PNG
| OS2World/LIB-QT3_Toolkit_Vbox | src/kernel/qpngio.cpp | C++ | gpl-2.0 | 30,630 |
#!/usr/bin/env python
#Mercurial extension to robustly integrate prompts with other processes
#Copyright (C) 2010-2011 Willem Verstraeten
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import urllib2
from mercurial import ui, util
import struct, socket
from mercurial.i18n import _
try:
from mercurial.url import passwordmgr
except:
from mercurial.httprepo import passwordmgr
def sendInt( client, number):
length = struct.pack('>L', number)
client.sendall( length )
def send( client, data ):
if data is None:
sendInt(client, 0)
else:
sendInt(client, len(data))
client.sendall( data )
def receiveIntWithMessage(client, message):
requiredLength = struct.calcsize('>L')
buffer = ''
while len(buffer)<requiredLength:
chunk = client.recv(requiredLength-len(buffer))
if chunk == '':
raise util.Abort( message )
buffer = buffer + chunk
# struct.unpack always returns a tuple, even if that tuple only contains a single
# item. The trailing , is to destructure the tuple into its first element.
intToReturn, = struct.unpack('>L', buffer)
return intToReturn
def receiveInt(client):
return receiveIntWithMessage(client, "could not get information from server")
def receive( client ):
receiveWithMessage(client, "could not get information from server")
def receiveWithMessage( client, message ):
length = receiveIntWithMessage(client, message)
buffer = ''
while len(buffer) < length :
chunk = client.recv(length - len(buffer))
if chunk == '':
raise util.Abort( message)
buffer = buffer+chunk
return buffer
# decorator to cleanly monkey patch methods in mercurial
def monkeypatch_method(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
def sendchoicestoidea(ui, msg, choices, default):
port = int(ui.config( 'hg4ideaprompt', 'port', None, True))
if not port:
raise util.Abort("No port was specified")
numOfChoices = len(choices)
if not numOfChoices:
return default
client = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
try:
client.connect( ('127.0.0.1', port) )
send( client, msg )
sendInt( client, numOfChoices )
for choice in choices:
send( client, choice )
sendInt( client, default )
answer = receiveInt( client )
if answer == -1:
raise util.Abort("User cancelled")
else:
return answer
except:
raise
# determine which method to monkey patch :
# in Mercurial 1.4 the prompt method was renamed to promptchoice
if getattr(ui.ui, 'promptchoice', None):
@monkeypatch_method(ui.ui)
def promptchoice(self, msg, choices=None, default=0):
return sendchoicestoidea(self, msg, choices, default)
else:
@monkeypatch_method(ui.ui)
def prompt(self, msg, choices=None, default="y"):
resps = [s[s.index('&')+1].lower() for s in choices]
defaultIndex = resps.index( default )
responseIndex = sendchoicestoidea( self, msg, choices, defaultIndex)
return resps[responseIndex]
original_warn = ui.ui.warn
@monkeypatch_method(ui.ui)
def warn(self, *msg):
original_warn(self, *msg)
port = int(self.config( 'hg4ideawarn', 'port', None, True))
if not port:
raise util.Abort("No port was specified")
self.debug( "hg4idea prompt server waiting on port %s" % port )
client = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.debug( "connecting ..." )
client.connect( ('127.0.0.1', port) )
self.debug( "connected, sending data ..." )
sendInt( client, len(msg) )
for message in msg:
send( client, message )
def retrieve_pass_from_server(ui, uri,path, proposed_user):
port = int(ui.config('hg4ideapass', 'port', None, True))
if port is None:
raise util.Abort("No port was specified")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ui.debug("connecting ...")
client.connect(('127.0.0.1', port))
ui.debug("connected, sending data ...")
send(client, "getpass")
send(client, uri)
send(client, path)
send(client, proposed_user)
user = receiveWithMessage(client, "http authorization required")
password = receiveWithMessage(client, "http authorization required")
return user, password
original_retrievepass=passwordmgr.find_user_password
@monkeypatch_method(passwordmgr)
def find_user_password(self, realm, authuri):
try:
return original_retrievepass(self, realm, authuri)
except util.Abort:
# In mercurial 1.8 the readauthtoken method was replaced with
# the readauthforuri method, which has different semantics
if getattr(self, 'readauthtoken', None):
def read_hgrc_authtoken(ui, authuri):
return self.readauthtoken(authuri)
else:
def read_hgrc_authtoken(ui, authuri):
# hg 1.8
from mercurial.url import readauthforuri
res = readauthforuri(self.ui, authuri)
if res:
group, auth = res
return auth
else:
return None
user, password = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(self, realm, authuri)
if user is None:
auth = read_hgrc_authtoken(self.ui, authuri)
if auth:
user = auth.get("username")
reduced_uri, path= self.reduce_uri(authuri, False)
retrievedPass = retrieve_pass_from_server(self.ui, reduced_uri, path, user)
if retrievedPass is None:
raise util.Abort(_('http authorization required'))
user, passwd = retrievedPass
self.add_password(realm, authuri, user, passwd)
return retrievedPass | willemv/mercurial_prompthooks | prompthooks.py | Python | gpl-2.0 | 6,665 |
/*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
Thread::Thread (const String& threadName_)
: threadName (threadName_),
threadHandle (nullptr),
threadId (0),
threadPriority (5),
affinityMask (0),
shouldExit (false)
{
}
Thread::~Thread()
{
/* If your thread class's destructor has been called without first stopping the thread, that
means that this partially destructed object is still performing some work - and that's
probably a Bad Thing!
To avoid this type of nastiness, always make sure you call stopThread() before or during
your subclass's destructor.
*/
jassert (! isThreadRunning());
stopThread (100);
}
//==============================================================================
// Use a ref-counted object to hold this shared data, so that it can outlive its static
// shared pointer when threads are still running during static shutdown.
struct CurrentThreadHolder : public ReferenceCountedObject
{
CurrentThreadHolder() noexcept {}
typedef ReferenceCountedObjectPtr <CurrentThreadHolder> Ptr;
ThreadLocalValue<Thread*> value;
JUCE_DECLARE_NON_COPYABLE (CurrentThreadHolder)
};
static char currentThreadHolderLock [sizeof (SpinLock)]; // (statically initialised to zeros).
static CurrentThreadHolder::Ptr getCurrentThreadHolder()
{
static CurrentThreadHolder::Ptr currentThreadHolder;
SpinLock::ScopedLockType lock (*reinterpret_cast <SpinLock*> (currentThreadHolderLock));
if (currentThreadHolder == nullptr)
currentThreadHolder = new CurrentThreadHolder();
return currentThreadHolder;
}
void Thread::threadEntryPoint()
{
const CurrentThreadHolder::Ptr currentThreadHolder (getCurrentThreadHolder());
currentThreadHolder->value = this;
JUCE_TRY
{
if (threadName.isNotEmpty())
setCurrentThreadName (threadName);
if (startSuspensionEvent.wait (10000))
{
jassert (getCurrentThreadId() == threadId);
if (affinityMask != 0)
setCurrentThreadAffinityMask (affinityMask);
run();
}
}
JUCE_CATCH_ALL_ASSERT
currentThreadHolder->value.releaseCurrentThreadStorage();
closeThreadHandle();
}
// used to wrap the incoming call from the platform-specific code
void JUCE_API juce_threadEntryPoint (void* userData)
{
static_cast <Thread*> (userData)->threadEntryPoint();
}
//==============================================================================
void Thread::startThread()
{
const ScopedLock sl (startStopLock);
shouldExit = false;
if (threadHandle == nullptr)
{
launchThread();
setThreadPriority (threadHandle, threadPriority);
startSuspensionEvent.signal();
}
}
void Thread::startThread (const int priority)
{
const ScopedLock sl (startStopLock);
if (threadHandle == nullptr)
{
threadPriority = priority;
startThread();
}
else
{
setPriority (priority);
}
}
bool Thread::isThreadRunning() const
{
return threadHandle != nullptr;
}
Thread* Thread::getCurrentThread()
{
return getCurrentThreadHolder()->value.get();
}
//==============================================================================
void Thread::signalThreadShouldExit()
{
shouldExit = true;
}
bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
{
// Doh! So how exactly do you expect this thread to wait for itself to stop??
jassert (getThreadId() != getCurrentThreadId() || getCurrentThreadId() == 0);
const uint32 timeoutEnd = Time::getMillisecondCounter() + (uint32) timeOutMilliseconds;
while (isThreadRunning())
{
if (timeOutMilliseconds >= 0 && Time::getMillisecondCounter() > timeoutEnd)
return false;
sleep (2);
}
return true;
}
void Thread::stopThread (const int timeOutMilliseconds)
{
// agh! You can't stop the thread that's calling this method! How on earth
// would that work??
jassert (getCurrentThreadId() != getThreadId());
const ScopedLock sl (startStopLock);
if (isThreadRunning())
{
signalThreadShouldExit();
notify();
if (timeOutMilliseconds != 0)
waitForThreadToExit (timeOutMilliseconds);
if (isThreadRunning())
{
// very bad karma if this point is reached, as there are bound to be
// locks and events left in silly states when a thread is killed by force..
jassertfalse;
Logger::writeToLog ("!! killing thread by force !!");
killThread();
threadHandle = nullptr;
threadId = 0;
}
}
}
//==============================================================================
bool Thread::setPriority (const int newPriority)
{
// NB: deadlock possible if you try to set the thread prio from the thread itself,
// so using setCurrentThreadPriority instead in that case.
if (getCurrentThreadId() == getThreadId())
return setCurrentThreadPriority (newPriority);
const ScopedLock sl (startStopLock);
if (setThreadPriority (threadHandle, newPriority))
{
threadPriority = newPriority;
return true;
}
return false;
}
bool Thread::setCurrentThreadPriority (const int newPriority)
{
return setThreadPriority (0, newPriority);
}
void Thread::setAffinityMask (const uint32 newAffinityMask)
{
affinityMask = newAffinityMask;
}
//==============================================================================
bool Thread::wait (const int timeOutMilliseconds) const
{
return defaultEvent.wait (timeOutMilliseconds);
}
void Thread::notify() const
{
defaultEvent.signal();
}
//==============================================================================
void SpinLock::enter() const noexcept
{
if (! tryEnter())
{
for (int i = 20; --i >= 0;)
if (tryEnter())
return;
while (! tryEnter())
Thread::yield();
}
}
//==============================================================================
#if JUCE_UNIT_TESTS
class AtomicTests : public UnitTest
{
public:
AtomicTests() : UnitTest ("Atomics") {}
void runTest()
{
beginTest ("Misc");
char a1[7];
expect (numElementsInArray(a1) == 7);
int a2[3];
expect (numElementsInArray(a2) == 3);
expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
beginTest ("Atomic int");
AtomicTester <int>::testInteger (*this);
beginTest ("Atomic unsigned int");
AtomicTester <unsigned int>::testInteger (*this);
beginTest ("Atomic int32");
AtomicTester <int32>::testInteger (*this);
beginTest ("Atomic uint32");
AtomicTester <uint32>::testInteger (*this);
beginTest ("Atomic long");
AtomicTester <long>::testInteger (*this);
beginTest ("Atomic void*");
AtomicTester <void*>::testInteger (*this);
beginTest ("Atomic int*");
AtomicTester <int*>::testInteger (*this);
beginTest ("Atomic float");
AtomicTester <float>::testFloat (*this);
#if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
beginTest ("Atomic int64");
AtomicTester <int64>::testInteger (*this);
beginTest ("Atomic uint64");
AtomicTester <uint64>::testInteger (*this);
beginTest ("Atomic double");
AtomicTester <double>::testFloat (*this);
#endif
}
template <typename Type>
class AtomicTester
{
public:
AtomicTester() {}
static void testInteger (UnitTest& test)
{
Atomic<Type> a, b;
a.set ((Type) 10);
test.expect (a.value == (Type) 10);
test.expect (a.get() == (Type) 10);
a += (Type) 15;
test.expect (a.get() == (Type) 25);
a.memoryBarrier();
a -= (Type) 5;
test.expect (a.get() == (Type) 20);
test.expect (++a == (Type) 21);
++a;
test.expect (--a == (Type) 21);
test.expect (a.get() == (Type) 21);
a.memoryBarrier();
testFloat (test);
}
static void testFloat (UnitTest& test)
{
Atomic<Type> a, b;
a = (Type) 21;
a.memoryBarrier();
/* These are some simple test cases to check the atomics - let me know
if any of these assertions fail on your system!
*/
test.expect (a.get() == (Type) 21);
test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
test.expect (a.get() == (Type) 21);
test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
test.expect (a.get() == (Type) 101);
test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
test.expect (a.get() == (Type) 101);
test.expect (a.compareAndSetBool ((Type) 200, a.get()));
test.expect (a.get() == (Type) 200);
test.expect (a.exchange ((Type) 300) == (Type) 200);
test.expect (a.get() == (Type) 300);
b = a;
test.expect (b.get() == a.get());
}
};
};
static AtomicTests atomicUnitTests;
#endif
| teragonaudio/Arooo | JuceLibraryCode/modules/juce_core/threads/juce_Thread.cpp | C++ | gpl-2.0 | 11,061 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Core functions used all over the scripts.
* This script is distinct from libraries/common.inc.php because this
* script is called from /test.
*
* @package PhpMyAdmin
*/
use PMA\libraries\Message;
use PMA\libraries\URL;
use PMA\libraries\Sanitize;
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* String handling (security)
*/
require_once 'libraries/string.lib.php';
/**
* checks given $var and returns it if valid, or $default of not valid
* given $var is also checked for type being 'similar' as $default
* or against any other type if $type is provided
*
* <code>
* // $_REQUEST['db'] not set
* echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
* // $_REQUEST['sql_query'] not set
* echo PMA_ifSetOr($_REQUEST['sql_query']); // null
* // $cfg['EnableFoo'] not set
* echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
* echo PMA_ifSetOr($cfg['EnableFoo']); // null
* // $cfg['EnableFoo'] set to 1
* echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
* echo PMA_ifSetOr($cfg['EnableFoo'], false, 'similar'); // 1
* echo PMA_ifSetOr($cfg['EnableFoo'], false); // 1
* // $cfg['EnableFoo'] set to true
* echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // true
* </code>
*
* @param mixed &$var param to check
* @param mixed $default default value
* @param mixed $type var type or array of values to check against $var
*
* @return mixed $var or $default
*
* @see PMA_isValid()
*/
function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
{
if (! PMA_isValid($var, $type, $default)) {
return $default;
}
return $var;
}
/**
* checks given $var against $type or $compare
*
* $type can be:
* - false : no type checking
* - 'scalar' : whether type of $var is integer, float, string or boolean
* - 'numeric' : whether type of $var is any number representation
* - 'length' : whether type of $var is scalar with a string length > 0
* - 'similar' : whether type of $var is similar to type of $compare
* - 'equal' : whether type of $var is identical to type of $compare
* - 'identical' : whether $var is identical to $compare, not only the type!
* - or any other valid PHP variable type
*
* <code>
* // $_REQUEST['doit'] = true;
* PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
* // $_REQUEST['doit'] = 'true';
* PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
* </code>
*
* NOTE: call-by-reference is used to not get NOTICE on undefined vars,
* but the var is not altered inside this function, also after checking a var
* this var exists nut is not set, example:
* <code>
* // $var is not set
* isset($var); // false
* functionCallByReference($var); // false
* isset($var); // true
* functionCallByReference($var); // true
* </code>
*
* to avoid this we set this var to null if not isset
*
* @param mixed &$var variable to check
* @param mixed $type var type or array of valid values to check against $var
* @param mixed $compare var to compare with $var
*
* @return boolean whether valid or not
*
* @todo add some more var types like hex, bin, ...?
* @see http://php.net/gettype
*/
function PMA_isValid(&$var, $type = 'length', $compare = null)
{
if (! isset($var)) {
// var is not even set
return false;
}
if ($type === false) {
// no vartype requested
return true;
}
if (is_array($type)) {
return in_array($var, $type);
}
// allow some aliases of var types
$type = strtolower($type);
switch ($type) {
case 'identic' :
$type = 'identical';
break;
case 'len' :
$type = 'length';
break;
case 'bool' :
$type = 'boolean';
break;
case 'float' :
$type = 'double';
break;
case 'int' :
$type = 'integer';
break;
case 'null' :
$type = 'NULL';
break;
}
if ($type === 'identical') {
return $var === $compare;
}
// whether we should check against given $compare
if ($type === 'similar') {
switch (gettype($compare)) {
case 'string':
case 'boolean':
$type = 'scalar';
break;
case 'integer':
case 'double':
$type = 'numeric';
break;
default:
$type = gettype($compare);
}
} elseif ($type === 'equal') {
$type = gettype($compare);
}
// do the check
if ($type === 'length' || $type === 'scalar') {
$is_scalar = is_scalar($var);
if ($is_scalar && $type === 'length') {
return (bool) mb_strlen($var);
}
return $is_scalar;
}
if ($type === 'numeric') {
return is_numeric($var);
}
if (gettype($var) === $type) {
return true;
}
return false;
}
/**
* Removes insecure parts in a path; used before include() or
* require() when a part of the path comes from an insecure source
* like a cookie or form.
*
* @param string $path The path to check
*
* @return string The secured path
*
* @access public
*/
function PMA_securePath($path)
{
// change .. to .
$path = preg_replace('@\.\.*@', '.', $path);
return $path;
} // end function
/**
* displays the given error message on phpMyAdmin error page in foreign language,
* ends script execution and closes session
*
* loads language file if not loaded already
*
* @param string $error_message the error message or named error message
* @param string|array $message_args arguments applied to $error_message
* @param boolean $delete_session whether to delete session cookie
*
* @return void
*/
function PMA_fatalError(
$error_message, $message_args = null, $delete_session = true
) {
/* Use format string if applicable */
if (is_string($message_args)) {
$error_message = sprintf($error_message, $message_args);
} elseif (is_array($message_args)) {
$error_message = vsprintf($error_message, $message_args);
}
if (! empty($GLOBALS['is_ajax_request']) && $GLOBALS['is_ajax_request']) {
$response = PMA\libraries\Response::getInstance();
$response->setRequestStatus(false);
$response->addJSON('message', PMA\libraries\Message::error($error_message));
} else {
$error_message = strtr($error_message, array('<br />' => '[br]'));
// these variables are used in the included file libraries/error.inc.php
//first check if php-mbstring is available
if (function_exists('mb_detect_encoding')) {
//If present use gettext
$error_header = __('Error');
} else {
$error_header = 'Error';
}
$lang = $GLOBALS['lang'];
$dir = $GLOBALS['text_dir'];
// on fatal errors it cannot hurt to always delete the current session
if ($delete_session
&& isset($GLOBALS['session_name'])
&& isset($_COOKIE[$GLOBALS['session_name']])
) {
$GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
}
// Displays the error message
include './libraries/error.inc.php';
}
if (! defined('TESTSUITE')) {
exit;
}
}
/**
* Returns a link to the PHP documentation
*
* @param string $target anchor in documentation
*
* @return string the URL
*
* @access public
*/
function PMA_getPHPDocLink($target)
{
/* List of PHP documentation translations */
$php_doc_languages = array(
'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
);
$lang = 'en';
if (in_array($GLOBALS['lang'], $php_doc_languages)) {
$lang = $GLOBALS['lang'];
}
return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target);
}
/**
* Warn or fail on missing extension.
*
* @param string $extension Extension name
* @param bool $fatal Whether the error is fatal.
* @param string $extra Extra string to append to message.
*
* @return void
*/
function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
{
/* Gettext does not have to be loaded yet here */
if (function_exists('__')) {
$message = __(
'The %s extension is missing. Please check your PHP configuration.'
);
} else {
$message
= 'The %s extension is missing. Please check your PHP configuration.';
}
$doclink = PMA_getPHPDocLink('book.' . $extension . '.php');
$message = sprintf(
$message,
'[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
);
if ($extra != '') {
$message .= ' ' . $extra;
}
if ($fatal) {
PMA_fatalError($message);
return;
}
$GLOBALS['error_handler']->addError(
$message,
E_USER_WARNING,
'',
'',
false
);
}
/**
* returns count of tables in given db
*
* @param string $db database to count tables for
*
* @return integer count of tables in $db
*/
function PMA_getTableCount($db)
{
$tables = $GLOBALS['dbi']->tryQuery(
'SHOW TABLES FROM ' . PMA\libraries\Util::backquote($db) . ';',
null, PMA\libraries\DatabaseInterface::QUERY_STORE
);
if ($tables) {
$num_tables = $GLOBALS['dbi']->numRows($tables);
$GLOBALS['dbi']->freeResult($tables);
} else {
$num_tables = 0;
}
return $num_tables;
}
/**
* Converts numbers like 10M into bytes
* Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
* (renamed with PMA prefix to avoid double definition when embedded
* in Moodle)
*
* @param string|int $size size (Default = 0)
*
* @return integer $size
*/
function PMA_getRealSize($size = 0)
{
if (! $size) {
return 0;
}
$scan = array(
'gb' => 1073741824, //1024 * 1024 * 1024,
'g' => 1073741824, //1024 * 1024 * 1024,
'mb' => 1048576,
'm' => 1048576,
'kb' => 1024,
'k' => 1024,
'b' => 1,
);
foreach ($scan as $unit => $factor) {
$sizeLength = strlen($size);
$unitLength = strlen($unit);
if ($sizeLength > $unitLength
&& strtolower(
substr(
$size,
$sizeLength - $unitLength
)
) == $unit
) {
return substr(
$size,
0,
$sizeLength - $unitLength
) * $factor;
}
}
return $size;
} // end function PMA_getRealSize()
/**
* boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
*
* checks given $page against given $whitelist and returns true if valid
* it optionally ignores query parameters in $page (script.php?ignored)
*
* @param string &$page page to check
* @param array $whitelist whitelist to check page against
*
* @return boolean whether $page is valid or not (in $whitelist or not)
*/
function PMA_checkPageValidity(&$page, $whitelist)
{
if (! isset($page) || !is_string($page)) {
return false;
}
if (in_array($page, $whitelist)) {
return true;
}
$_page = mb_substr(
$page,
0,
mb_strpos($page . '?', '?')
);
if (in_array($_page, $whitelist)) {
return true;
}
$_page = urldecode($page);
$_page = mb_substr(
$_page,
0,
mb_strpos($_page . '?', '?')
);
if (in_array($_page, $whitelist)) {
return true;
}
return false;
}
/**
* tries to find the value for the given environment variable name
*
* searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
* in this order
*
* @param string $var_name variable name
*
* @return string value of $var or empty string
*/
function PMA_getenv($var_name)
{
if (isset($_SERVER[$var_name])) {
return $_SERVER[$var_name];
}
if (isset($_ENV[$var_name])) {
return $_ENV[$var_name];
}
if (getenv($var_name)) {
return getenv($var_name);
}
if (function_exists('apache_getenv')
&& apache_getenv($var_name, true)
) {
return apache_getenv($var_name, true);
}
return '';
}
/**
* Send HTTP header, taking IIS limits into account (600 seems ok)
*
* @param string $uri the header to send
* @param bool $use_refresh whether to use Refresh: header when running on IIS
*
* @return void
*/
function PMA_sendHeaderLocation($uri, $use_refresh = false)
{
if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && mb_strlen($uri) > 600) {
PMA\libraries\Response::getInstance()->disable();
echo PMA\libraries\Template::get('header_location')
->render(array('uri' => $uri));
return;
}
$response = PMA\libraries\Response::getInstance();
if (SID) {
if (mb_strpos($uri, '?') === false) {
$response->header('Location: ' . $uri . '?' . SID);
} else {
$separator = URL::getArgSeparator();
$response->header('Location: ' . $uri . $separator . SID);
}
return;
}
session_write_close();
if ($response->headersSent()) {
if (function_exists('debug_print_backtrace')) {
echo '<pre>';
debug_print_backtrace();
echo '</pre>';
}
trigger_error(
'PMA_sendHeaderLocation called when headers are already sent!',
E_USER_ERROR
);
}
// bug #1523784: IE6 does not like 'Refresh: 0', it
// results in a blank page
// but we need it when coming from the cookie login panel)
if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && $use_refresh) {
$response->header('Refresh: 0; ' . $uri);
} else {
$response->header('Location: ' . $uri);
}
}
/**
* Outputs application/json headers. This includes no caching.
*
* @return void
*/
function PMA_headerJSON()
{
if (defined('TESTSUITE') && ! defined('PMA_TEST_HEADERS')) {
return;
}
// No caching
PMA_noCacheHeader();
// MIME type
header('Content-Type: application/json; charset=UTF-8');
// Disable content sniffing in browser
// This is needed in case we include HTML in JSON, browser might assume it's
// html to display
header('X-Content-Type-Options: nosniff');
}
/**
* Outputs headers to prevent caching in browser (and on the way).
*
* @return void
*/
function PMA_noCacheHeader()
{
if (defined('TESTSUITE') && ! defined('PMA_TEST_HEADERS')) {
return;
}
// rfc2616 - Section 14.21
header('Expires: ' . date(DATE_RFC1123));
// HTTP/1.1
header(
'Cache-Control: no-store, no-cache, must-revalidate,'
. ' pre-check=0, post-check=0, max-age=0'
);
header('Pragma: no-cache'); // HTTP/1.0
// test case: exporting a database into a .gz file with Safari
// would produce files not having the current time
// (added this header for Safari but should not harm other browsers)
header('Last-Modified: ' . date(DATE_RFC1123));
}
/**
* Sends header indicating file download.
*
* @param string $filename Filename to include in headers if empty,
* none Content-Disposition header will be sent.
* @param string $mimetype MIME type to include in headers.
* @param int $length Length of content (optional)
* @param bool $no_cache Whether to include no-caching headers.
*
* @return void
*/
function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
{
if ($no_cache) {
PMA_noCacheHeader();
}
/* Replace all possibly dangerous chars in filename */
$filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
if (!empty($filename)) {
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
header('Content-Type: ' . $mimetype);
// inform the server that compression has been done,
// to avoid a double compression (for example with Apache + mod_deflate)
$notChromeOrLessThan43 = PMA_USR_BROWSER_AGENT != 'CHROME' // see bug #4942
|| (PMA_USR_BROWSER_AGENT == 'CHROME' && PMA_USR_BROWSER_VER < 43);
if (strpos($mimetype, 'gzip') !== false && $notChromeOrLessThan43) {
header('Content-Encoding: gzip');
}
header('Content-Transfer-Encoding: binary');
if ($length > 0) {
header('Content-Length: ' . $length);
}
}
/**
* Returns value of an element in $array given by $path.
* $path is a string describing position of an element in an associative array,
* eg. Servers/1/host refers to $array[Servers][1][host]
*
* @param string $path path in the array
* @param array $array the array
* @param mixed $default default value
*
* @return mixed array element or $default
*/
function PMA_arrayRead($path, $array, $default = null)
{
$keys = explode('/', $path);
$value =& $array;
foreach ($keys as $key) {
if (! isset($value[$key])) {
return $default;
}
$value =& $value[$key];
}
return $value;
}
/**
* Stores value in an array
*
* @param string $path path in the array
* @param array &$array the array
* @param mixed $value value to store
*
* @return void
*/
function PMA_arrayWrite($path, &$array, $value)
{
$keys = explode('/', $path);
$last_key = array_pop($keys);
$a =& $array;
foreach ($keys as $key) {
if (! isset($a[$key])) {
$a[$key] = array();
}
$a =& $a[$key];
}
$a[$last_key] = $value;
}
/**
* Removes value from an array
*
* @param string $path path in the array
* @param array &$array the array
*
* @return void
*/
function PMA_arrayRemove($path, &$array)
{
$keys = explode('/', $path);
$keys_last = array_pop($keys);
$path = array();
$depth = 0;
$path[0] =& $array;
$found = true;
// go as deep as required or possible
foreach ($keys as $key) {
if (! isset($path[$depth][$key])) {
$found = false;
break;
}
$depth++;
$path[$depth] =& $path[$depth - 1][$key];
}
// if element found, remove it
if ($found) {
unset($path[$depth][$keys_last]);
$depth--;
}
// remove empty nested arrays
for (; $depth >= 0; $depth--) {
if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
unset($path[$depth][$keys[$depth]]);
} else {
break;
}
}
}
/**
* Returns link to (possibly) external site using defined redirector.
*
* @param string $url URL where to go.
*
* @return string URL for a link.
*/
function PMA_linkURL($url)
{
if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
return $url;
}
$params = array();
$params['url'] = $url;
$url = URL::getCommon($params);
//strip off token and such sensitive information. Just keep url.
$arr = parse_url($url);
parse_str($arr["query"], $vars);
$query = http_build_query(array("url" => $vars["url"]));
$url = './url.php?' . $query;
return $url;
}
/**
* Checks whether domain of URL is whitelisted domain or not.
* Use only for URLs of external sites.
*
* @param string $url URL of external site.
*
* @return boolean True: if domain of $url is allowed domain,
* False: otherwise.
*/
function PMA_isAllowedDomain($url)
{
$arr = parse_url($url);
$domain = $arr["host"];
$domainWhiteList = array(
/* Include current domain */
$_SERVER['SERVER_NAME'],
/* phpMyAdmin domains */
'wiki.phpmyadmin.net', 'www.phpmyadmin.net', 'phpmyadmin.net',
'docs.phpmyadmin.net',
/* mysql.com domains */
'dev.mysql.com','bugs.mysql.com',
/* mariadb domains */
'mariadb.org',
/* php.net domains */
'php.net',
/* Github domains*/
'github.com','www.github.com',
/* Following are doubtful ones. */
'www.primebase.com',
'pbxt.blogspot.com',
'www.percona.com',
'mysqldatabaseadministration.blogspot.com',
'ronaldbradford.com',
'xaprb.com',
);
if (in_array(mb_strtolower($domain), $domainWhiteList)) {
return true;
}
return false;
}
/**
* Adds JS code snippets to be displayed by the PMA\libraries\Response class.
* Adds a newline to each snippet.
*
* @param string $str Js code to be added (e.g. "token=1234;")
*
* @return void
*/
function PMA_addJSCode($str)
{
$response = PMA\libraries\Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addCode($str);
}
/**
* Adds JS code snippet for variable assignment
* to be displayed by the PMA\libraries\Response class.
*
* @param string $key Name of value to set
* @param mixed $value Value to set, can be either string or array of strings
* @param bool $escape Whether to escape value or keep it as it is
* (for inclusion of js code)
*
* @return void
*/
function PMA_addJSVar($key, $value, $escape = true)
{
PMA_addJSCode(Sanitize::getJsValue($key, $value, $escape));
}
/**
* Replace some html-unfriendly stuff
*
* @param string $buffer String to process
*
* @return string Escaped and cleaned up text suitable for html
*/
function PMA_mimeDefaultFunction($buffer)
{
$buffer = htmlspecialchars($buffer);
$buffer = str_replace(' ', ' ', $buffer);
$buffer = preg_replace("@((\015\012)|(\015)|(\012))@", '<br />' . "\n", $buffer);
return $buffer;
}
/**
* Displays SQL query before executing.
*
* @param array|string $query_data Array containing queries or query itself
*
* @return void
*/
function PMA_previewSQL($query_data)
{
$retval = '<div class="preview_sql">';
if (empty($query_data)) {
$retval .= __('No change');
} elseif (is_array($query_data)) {
foreach ($query_data as $query) {
$retval .= PMA\libraries\Util::formatSql($query);
}
} else {
$retval .= PMA\libraries\Util::formatSql($query_data);
}
$retval .= '</div>';
$response = PMA\libraries\Response::getInstance();
$response->addJSON('sql_data', $retval);
exit;
}
/**
* recursively check if variable is empty
*
* @param mixed $value the variable
*
* @return bool true if empty
*/
function PMA_emptyRecursive($value)
{
$empty = true;
if (is_array($value)) {
array_walk_recursive(
$value,
function ($item) use (&$empty) {
$empty = $empty && empty($item);
}
);
} else {
$empty = empty($value);
}
return $empty;
}
/**
* Creates some globals from $_POST variables matching a pattern
*
* @param array $post_patterns The patterns to search for
*
* @return void
*/
function PMA_setPostAsGlobal($post_patterns)
{
foreach (array_keys($_POST) as $post_key) {
foreach ($post_patterns as $one_post_pattern) {
if (preg_match($one_post_pattern, $post_key)) {
$GLOBALS[$post_key] = $_POST[$post_key];
}
}
}
}
/**
* Creates some globals from $_REQUEST
*
* @param string $param db|table
*
* @return void
*/
function PMA_setGlobalDbOrTable($param)
{
$GLOBALS[$param] = '';
if (PMA_isValid($_REQUEST[$param])) {
// can we strip tags from this?
// only \ and / is not allowed in db names for MySQL
$GLOBALS[$param] = $_REQUEST[$param];
$GLOBALS['url_params'][$param] = $GLOBALS[$param];
}
}
/**
* PATH_INFO could be compromised if set, so remove it from PHP_SELF
* and provide a clean PHP_SELF here
*
* @return void
*/
function PMA_cleanupPathInfo()
{
global $PMA_PHP_SELF, $_PATH_INFO;
$PMA_PHP_SELF = PMA_getenv('PHP_SELF');
$_PATH_INFO = PMA_getenv('PATH_INFO');
if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) {
$path_info_pos = mb_strrpos($PMA_PHP_SELF, $_PATH_INFO);
$pathLength = $path_info_pos + mb_strlen($_PATH_INFO);
if ($pathLength === mb_strlen($PMA_PHP_SELF)) {
$PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $path_info_pos);
}
}
$PMA_PHP_SELF = htmlspecialchars($PMA_PHP_SELF);
}
/**
* Checks that required PHP extensions are there.
* @return void
*/
function PMA_checkExtensions()
{
/**
* Warning about mbstring.
*/
if (! function_exists('mb_detect_encoding')) {
PMA_warnMissingExtension('mbstring', true);
}
/**
* We really need this one!
*/
if (! function_exists('preg_replace')) {
PMA_warnMissingExtension('pcre', true);
}
/**
* JSON is required in several places.
*/
if (! function_exists('json_encode')) {
PMA_warnMissingExtension('json', true);
}
}
/* Compatibility with PHP < 5.6 */
if(! function_exists('hash_equals')) {
/**
* Timing attack safe string comparison
*
* @param string $a first string
* @param string $b second string
*
* @return boolean whether they are equal
*/
function hash_equals($a, $b) {
$ret = strlen($a) ^ strlen($b);
$ret |= array_sum(unpack("C*", $a ^ $b));
return ! $ret;
}
}
| zixtor/phpmyadmin | libraries/core.lib.php | PHP | gpl-2.0 | 25,508 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Meta.Net.Objects;
namespace Meta.Net.Metadata.Factories
{
internal class CheckConstraintFactory
{
private int SchemaNameOrdinal { get; set; }
private int TableNameOrdinal { get; set; }
private int ColumnNameOrdinal { get; set; }
private int ObjectNameOrdinal { get; set; }
private int DefinitionOrdinal { get; set; }
private int IsTableConstraintOrdinal { get; set; }
private int IsDisabledOrdinal { get; set; }
private int IsNotForReplicationOrdinal { get; set; }
private int IsNotTrustedOrdinal { get; set; }
private int IsSystemNamedOrdinal { get; set; }
public CheckConstraintFactory(IDataRecord reader)
{
SchemaNameOrdinal = reader.GetOrdinal("SchemaName");
TableNameOrdinal = reader.GetOrdinal("TableName");
ColumnNameOrdinal = reader.GetOrdinal("ColumnName");
ObjectNameOrdinal = reader.GetOrdinal("ObjectName");
DefinitionOrdinal = reader.GetOrdinal("Definition");
IsTableConstraintOrdinal = reader.GetOrdinal("IsTableConstraint");
IsDisabledOrdinal = reader.GetOrdinal("IsDisabled");
IsNotForReplicationOrdinal = reader.GetOrdinal("IsNotForReplication");
IsNotTrustedOrdinal = reader.GetOrdinal("IsNotTrusted");
IsSystemNamedOrdinal = reader.GetOrdinal("IsSystemNamed");
}
public void CreateCheckConstraint(
Dictionary<string, UserTable> userTables,
IDataReader reader)
{
var schemaName = Convert.ToString(reader[SchemaNameOrdinal]);
var tableName = Convert.ToString(reader[TableNameOrdinal]);
var userTableNamespaceBuilder = new StringBuilder(schemaName.Length + tableName.Length + 1);
userTableNamespaceBuilder.Append(schemaName).
Append(Constants.Dot).
Append(tableName);
var userTableNamespace = userTableNamespaceBuilder.ToString();
if (!userTables.ContainsKey(userTableNamespace))
return;
var userTable = userTables[userTableNamespace];
if (userTable == null)
return;
var checkConstraint = new CheckConstraint
{
UserTable = userTable,
ColumnName = Convert.ToString(reader[ColumnNameOrdinal]),
ObjectName = Convert.ToString(reader[ObjectNameOrdinal]),
Definition = Convert.ToString(reader[DefinitionOrdinal]),
IsTableConstraint = Convert.ToBoolean(reader[IsTableConstraintOrdinal]),
IsDisabled = Convert.ToBoolean(reader[IsDisabledOrdinal]),
IsNotForReplication = Convert.ToBoolean(reader[IsNotForReplicationOrdinal]),
IsNotTrusted = Convert.ToBoolean(reader[IsNotTrustedOrdinal]),
IsSystemNamed = Convert.ToBoolean(reader[IsSystemNamedOrdinal])
};
userTable.CheckConstraints.Add(checkConstraint);
}
}
}
| OhRyanOh/Meta.Net | Meta.Net/Metadata/Factories/CheckConstraintFactory.cs | C# | gpl-2.0 | 3,157 |
// ---------------------------------------------------------------------- //
// //
// Copyright (c) 2007-2014 //
// Digital Beacon, LLC //
// //
// ---------------------------------------------------------------------- //
using System;
using System.Collections;
namespace DigitalBeacon.Model
{
/// This is the interface for all business objects that have a code property
/// </summary>
public interface ICodedEntity : IBaseEntity
{
/// <summary>
/// The code property
/// </summary>
string Code { get; set; }
}
}
| digitalbeacon/sitebase | Model/ICodedEntity.cs | C# | gpl-2.0 | 790 |
var FabrikModalRepeat = new Class({
initialize: function (el, names, field) {
this.names = names;
this.field = field;
this.content = false;
this.setup = false;
this.elid = el;
this.win = {};
this.el = {};
this.field = {};
// If the parent field is inserted via js then we delay the loading untill the html is present
if (!this.ready()) {
this.timer = this.testReady.periodical(500, this);
} else {
this.setUp();
}
},
ready: function () {
return typeOf(document.id(this.elid)) === 'null' ? false : true;
},
testReady: function () {
if (!this.ready()) {
return;
}
if (this.timer) {
clearInterval(this.timer);
}
this.setUp();
},
setUp: function () {
this.button = document.id(this.elid + '_button');
if (this.mask) {
this.mask.destroy();
}
this.mask = new Mask(document.body, {style: {'background-color': '#000', 'opacity': 0.4, 'z-index': 9998}});
document.addEvent('click:relay(*[data-modal=' + this.elid + '])', function (e, target) {
var tbl;
// Correct when in repeating group
var id = target.getNext('input').id;
this.field[id] = target.getNext('input');
var c = target.getParent('li');
this.origContainer = c;
tbl = c.getElement('table');
if (typeOf(tbl) !== 'null') {
this.el[id] = tbl;
}
this.openWindow(id);
}.bind(this));
},
openWindow: function (target) {
var makeWin = false;
if (!this.win[target]) {
makeWin = true;
this.makeTarget(target);
}
this.el[target].inject(this.win[target], 'top');
this.el[target].show();
if (!this.win[target] || makeWin) {
this.makeWin(target);
}
// Testing moviing out of makeWin
//this.build(target);
this.win[target].show();
this.win[target].position();
this.resizeWin(true, target);
this.win[target].position();
this.mask.show();
},
makeTarget: function (target) {
this.win[target] = new Element('div', {'data-modal-content': target, 'styles': {'padding': '5px', 'background-color': '#fff', 'display': 'none', 'z-index': 9999}}).inject(document.body);
},
makeWin: function (target) {
// Testing adopting in.out on show/hide
//this.win[target].adopt(this.el[target]);
var close = new Element('button.btn.button').set('text', 'close');
close.addEvent('click', function (e) {
e.stop();
this.store(target);
this.el[target].hide();
this.el[target].inject(this.origContainer);
this.close();
}.bind(this));
var controls = new Element('div.controls', {'styles': {'text-align': 'right'}}).adopt(close);
this.win[target].adopt(controls);
this.win[target].position();
this.content = this.el[target];
this.build(target);
this.watchButtons(this.win[target], target);
},
resizeWin: function (setup, target) {
console.log(target);
Object.each(this.win, function (win, key) {
var size = this.el[key].getDimensions(true);
var wsize = win.getDimensions(true);
var y = setup ? wsize.y : size.y + 30;
win.setStyles({'width': size.x + 'px', 'height': (y) + 'px'});
}.bind(this));
},
close: function () {
Object.each(this.win, function (win, key) {
win.hide();
});
this.mask.hide();
},
_getRadioValues: function (target) {
var radiovals = [];
this.getTrs(target).each(function (tr) {
var v = (sel = tr.getElement('input[type=radio]:checked')) ? sel.get('value') : v = '';
radiovals.push(v);
});
return radiovals;
},
_setRadioValues: function (radiovals, target) {
// Reapply radio button selections
this.getTrs(target).each(function (tr, i) {
if (r = tr.getElement('input[type=radio][value=' + radiovals[i] + ']')) {
r.checked = 'checked';
}
});
},
watchButtons: function (win, target) {
win.addEvent('click:relay(a.add)', function (e) {
if (tr = this.findTr(e)) {
// Store radio button selections
var radiovals = this._getRadioValues(target);
var body = tr.getParent('table').getElement('tbody');
this.tmpl.clone(true, true).inject(body);
/*if (tr.getChildren('th').length !== 0) {
var body = tr.getParent('table').getElement('tbody');
this.tmpl.clone(true, true).inject(body);
} else {
tr.clone(true, true).inject(tr, 'after');
}*/
this.stripe(target);
// Reapply values as renaming radio buttons
this._setRadioValues(radiovals, target);
this.resizeWin(false, target);
}
win.position();
e.stop();
}.bind(this));
win.addEvent('click:relay(a.remove)', function (e) {
// If only one row -don't remove
var rows = this.content.getElements('tbody tr');
if (rows.length <= 1) {
// return;
}
if (tr = this.findTr(e)) {
tr.dispose();
}
this.resizeWin(false, target);
win.position();
e.stop();
}.bind(this));
},
getTrs: function (target) {
return this.win[target].getElement('tbody').getElements('tr');
},
stripe: function (target) {
trs = this.getTrs(target);
for (var i = 0; i < trs.length; i ++) {
trs[i].removeClass('row1').removeClass('row0');
trs[i].addClass('row' + i % 2);
var chx = trs[i].getElements('input[type=radio]');
chx.each(function (r) {
r.name = r.name.replace(/\[([0-9])\]/, '[' + i + ']');
});
}
},
build: function (target) {
if (!this.win[target]) {
this.makeWin(target);
}
var a = JSON.decode(this.field[target].get('value'));
if (typeOf(a) === 'null') {
a = {};
}
var tr = this.win[target].getElement('tbody').getElement('tr');
var keys = Object.keys(a);
var newrow = keys.length === 0 || a[keys[0]].length === 0 ? true : false;
var rowcount = newrow ? 1 : a[keys[0]].length;
// Build the rows from the json object
for (var i = 1; i < rowcount; i ++) {
tr.clone().inject(tr, 'after');
}
this.stripe(target);
var trs = this.getTrs(target);
// Populate the cloned fields with the json values
for (i = 0; i < rowcount; i++) {
keys.each(function (k) {
trs[i].getElements('*[name*=' + k + ']').each(function (f) {
if (f.get('type') === 'radio') {
if (f.value === a[k][i]) {
f.checked = true;
}
} else {
// Works for input,select and textareas
f.value = a[k][i];
}
});
});
}
this.tmpl = tr;
if (newrow) {
tr.dispose();
}
},
findTr: function (e) {
var tr = e.target.getParents().filter(function (p) {
return p.get('tag') === 'tr';
});
return (tr.length === 0) ? false : tr[0];
},
store: function (target) {
var c = this.content;
c = this.el[target];
// Get the current values
var json = {};
for (var i = 0; i < this.names.length; i++) {
var n = this.names[i];
var fields = c.getElements('*[name*=' + n + ']');
json[n] = [];
fields.each(function (field) {
if (field.get('type') === 'radio') {
if (field.get('checked') === true) {
json[n].push(field.get('value'));
}
} else {
json[n].push(field.get('value'));
}
}.bind(this));
}
// Store them in the parent field.
this.field[target].value = JSON.encode(json);
return true;
}
}); | emundus/v5 | administrator/components/com_fabrik/models/fields/fabrikmodalrepeat.js | JavaScript | gpl-2.0 | 7,061 |
<?php
function _appthemes_localize_scripts() {
// jQuery Validate
wp_register_script( 'validate-lang', APP_FRAMEWORK_URI . '/js/validate/jquery.validate-lang.js', array( 'validate' ) );
wp_localize_script( 'validate-lang', 'validateL10n', array(
'required' => __( 'This field is required.', APP_TD ),
'remote' => __( 'Please fix this field.', APP_TD ),
'email' => __( 'Please enter a valid email address.', APP_TD ),
'url' => __( 'Please enter a valid URL.', APP_TD ),
'date' => __( 'Please enter a valid date.', APP_TD ),
'dateISO' => __( 'Please enter a valid date (ISO).', APP_TD ),
'number' => __( 'Please enter a valid number.', APP_TD ),
'digits' => __( 'Please enter only digits.', APP_TD ),
'creditcard' => __( 'Please enter a valid credit card number.', APP_TD ),
'equalTo' => __( 'Please enter the same value again.', APP_TD ),
'maxlength' => __( 'Please enter no more than {0} characters.', APP_TD ),
'minlength' => __( 'Please enter at least {0} characters.', APP_TD ),
'rangelength' => __( 'Please enter a value between {0} and {1} characters long.', APP_TD ),
'range' => __( 'Please enter a value between {0} and {1}.', APP_TD ),
'max' => __( 'Please enter a value less than or equal to {0}.', APP_TD ),
'min' => __( 'Please enter a value greater than or equal to {0}.', APP_TD ),
) );
// jQuery Colorbox
wp_register_script( 'colorbox-lang', APP_FRAMEWORK_URI . '/js/colorbox/jquery.colorbox-lang.js', array( 'colorbox' ) );
wp_localize_script( 'colorbox-lang', 'colorboxL10n', array(
'current' => __( 'image {current} of {total}', APP_TD ),
'previous' => __( 'previous', APP_TD ),
'next' => __( 'next', APP_TD ),
'close' => __( 'close', APP_TD ),
'xhrError' => __( 'This content failed to load.', APP_TD ),
'imgError' => __( 'This image failed to load.', APP_TD ),
'slideshowStart' => __( 'start slideshow', APP_TD ),
'slideshowStop' => __( 'stop slideshow', APP_TD ),
) );
}
| dakshatechnologies/renovize | wp-content/themes/renovizenew/framework/js/localization.php | PHP | gpl-2.0 | 2,069 |
package com.swayam.jmh.algos;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import com.swayam.practice.algos.strings.IntegerArrayMatcher;
import com.swayam.practice.algos.strings.IntegerArrayMatcherSimpleStringImpl;
public class IntegerArrayMatcherSimpleStringImplBenchmark {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void testContains_positive() {
// given
IntegerArrayMatcher testClass = new IntegerArrayMatcherSimpleStringImpl(
new int[] { 84, 112, 93, 104, 82, 61, 96, 102, 93, 104, 87, 110 });
// when
@SuppressWarnings("unused")
boolean result = testClass.contains(104);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void testContains_negative_1() {
// given
IntegerArrayMatcher testClass = new IntegerArrayMatcherSimpleStringImpl(
new int[] { 84, 112, 93, 104, 82, 61, 96, 102, 93, 104, 87, 110 });
// when
@SuppressWarnings("unused")
boolean result = testClass.contains(826);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void testContains_negative_2() {
// given
IntegerArrayMatcher testClass = new IntegerArrayMatcherSimpleStringImpl(
new int[] { 84, 112, 93, 104, 82, 61, 96, 102, 93, 104, 87, 110 });
// when
@SuppressWarnings("unused")
boolean result = testClass.contains(9);
}
}
| paawak/blog | code/algos-jmh/src/main/java/com/swayam/jmh/algos/IntegerArrayMatcherSimpleStringImplBenchmark.java | Java | gpl-2.0 | 1,581 |
/*
* Copyright (c) 2007 Henrique Pinto <henrique.pinto@kdemail.net>
* Copyright (c) 2008-2009 Harald Hvaal <haraldhv@stud.ntnu.no>
* Copyright (c) 2010 Raphael Kubo da Costa <rakuco@FreeBSD.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "readonlylibarchiveplugin.h"
#include "ark_debug.h"
#include <KPluginFactory>
K_PLUGIN_FACTORY_WITH_JSON(ReadOnlyLibarchivePluginFactory, "kerfuffle_libarchive_readonly.json", registerPlugin<ReadOnlyLibarchivePlugin>();)
ReadOnlyLibarchivePlugin::ReadOnlyLibarchivePlugin(QObject *parent, const QVariantList & args)
: LibarchivePlugin(parent, args)
{
qCDebug(ARK) << "Loaded libarchive read-only plugin";
}
ReadOnlyLibarchivePlugin::~ReadOnlyLibarchivePlugin()
{
}
#include "readonlylibarchiveplugin.moc"
| mvlabat/ark | plugins/libarchive/readonlylibarchiveplugin.cpp | C++ | gpl-2.0 | 1,989 |
<?php $atts = array_map('contact_do_shortcode', (array) $atts);
extract(shortcode_atts(array('filter' => ''), $atts));
$form_id = $GLOBALS['contact_form_id'];
$prefix = $GLOBALS['contact_form_prefix'];
$content = explode('[other]', do_shortcode($content));
if (!isset($_POST[$prefix.'submit'])) { $n = 2; }
elseif ((isset($GLOBALS['form_error'])) && ($GLOBALS['form_error'] == 'yes')) { $n = 1; }
else { $n = 0; }
if (!isset($content[$n])) { $content[$n] = ''; }
$content = contact_filter_data($filter, $content[$n]); | patricerandria/ccmgr-wp | ccmgr/wp-content/plugins/contact-manager/includes/forms/validation-content.php | PHP | gpl-2.0 | 526 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddShortnameProjects extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('projects', function(Blueprint $table)
{
//
$table->string('shortname');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('projects', function(Blueprint $table)
{
//
$table->dropColumn('shortname');
});
}
} | elconejito/Graphics-Library | app/database/migrations/2014_03_17_173453_add_shortname_projects.php | PHP | gpl-2.0 | 547 |
<?php //$Id$
/**
* CLAROLINE
* @version 1.9 $Revision$
*
* @copyright (c) 2001-2007 Universite catholique de Louvain (UCL)
*
* @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE
*
* @package ADMIN
*
* @author Guillaume Lederer <lederer@claroline.net>
*/
$cidReset = TRUE; $gidReset = TRUE; $tidReset = TRUE;
require '../inc/claro_init_global.inc.php';
$userPerPage = get_conf('userPerPage',20); // numbers of user to display on the same page
// Security check
if ( ! claro_is_user_authenticated() ) claro_disp_auth_form();
if ( ! claro_is_platform_admin() ) claro_die(get_lang('Not allowed'));
require_once get_path('incRepositorySys') . '/lib/pager.lib.php';
require_once get_path('incRepositorySys') . '/lib/admin.lib.inc.php';
require_once get_path('incRepositorySys') . '/lib/user.lib.php';
// CHECK INCOMING DATAS
if ((isset($_REQUEST['cidToEdit'])) && ($_REQUEST['cidToEdit']=='')) {unset($_REQUEST['cidToEdit']);}
$validCmdList = array('delete');
$cmd = (isset($_REQUEST['cmd']) && in_array($_REQUEST['cmd'],$validCmdList)? $_REQUEST['cmd'] : null);
$userIdReq = (int) (isset($_REQUEST['user_id']) ? $_REQUEST['user_id']: null);
// USED SESSION VARIABLES
// clean session if needed
if (isset($_REQUEST['newsearch']) && $_REQUEST['newsearch'] == 'yes')
{
unset($_SESSION['admin_user_search' ]);
unset($_SESSION['admin_user_firstName']);
unset($_SESSION['admin_user_lastName' ]);
unset($_SESSION['admin_user_userName' ]);
unset($_SESSION['admin_user_officialCode' ]);
unset($_SESSION['admin_user_mail' ]);
unset($_SESSION['admin_user_action' ]);
unset($_SESSION['admin_order_crit' ]);
}
// deal with session variables for search criteria, it depends where we come from :
// 1 ) we must be able to get back to the list that concerned the criteria we previously used (with out re entering them)
// 2 ) we must be able to arrive with new critera for a new search.
if (isset($_REQUEST['search' ])) $_SESSION['admin_user_search' ] = trim($_REQUEST['search' ]);
if (isset($_REQUEST['firstName' ])) $_SESSION['admin_user_firstName' ] = trim($_REQUEST['firstName' ]);
if (isset($_REQUEST['lastName' ])) $_SESSION['admin_user_lastName' ] = trim($_REQUEST['lastName' ]);
if (isset($_REQUEST['userName' ])) $_SESSION['admin_user_userName' ] = trim($_REQUEST['userName' ]);
if (isset($_REQUEST['officialCode' ])) $_SESSION['admin_user_officialCode' ] = trim($_REQUEST['officialCode' ]);
if (isset($_REQUEST['mail' ])) $_SESSION['admin_user_mail' ] = trim($_REQUEST['mail' ]);
if (isset($_REQUEST['action' ])) $_SESSION['admin_user_action' ] = trim($_REQUEST['action' ]);
if (isset($_REQUEST['order_crit'])) $_SESSION['admin_user_order_crit'] = trim($_REQUEST['order_crit']);
if (isset($_REQUEST['dir' ])) $_SESSION['admin_user_dir' ] = ($_REQUEST['dir'] == 'DESC' ? 'DESC' : 'ASC' );
$addToURL = ( isset($_REQUEST['addToURL']) ? $_REQUEST['addToURL'] : '');
//TABLES
//declare needed tables
// Deal with interbredcrumps
ClaroBreadCrumbs::getInstance()->prepend( get_lang('Administration'), get_path('rootAdminWeb') );
$nameTools = get_lang('User list');
//TABLES
//------------------------------------
// Execute COMMAND section
//------------------------------------
switch ( $cmd )
{
case 'delete' :
{
$dialogBox = ( user_delete($userIdReq) ? get_lang('Deletion of the user was done sucessfully') : get_lang('You can not change your own settings!'));
} break;
}
$searchInfo = prepare_search();
$isSearched = $searchInfo['isSearched'];
$addtoAdvanced = $searchInfo['addtoAdvanced'];
if(count($searchInfo['isSearched']) )
{
$isSearched = array_map( 'strip_tags', $isSearched );
$isSearchedHTML = implode('<br />', $isSearched);
}
else
{
$isSearchedHTML = '';
}
//get the search keyword, if any
$search = (isset($_REQUEST['search']) ? $_REQUEST['search'] : '');
$sql = get_sql_filtered_user_list();
$offset = isset($_REQUEST['offset']) ? $_REQUEST['offset'] : 0 ;
$myPager = new claro_sql_pager($sql, $offset, $userPerPage);
if ( array_key_exists( 'sort', $_GET ) )
{
$dir = array_key_exists( 'dir', $_GET ) && $_GET['dir'] == SORT_DESC
? SORT_DESC
: SORT_ASC
;
$sortKey = strip_tags( $_GET['sort'] );
$myPager->add_sort_key( $sortKey, $dir );
}
$defaultSortKeyList = array ('isPlatformAdmin' => SORT_DESC,
'name' => SORT_ASC,
'firstName' => SORT_ASC);
foreach($defaultSortKeyList as $thisSortKey => $thisSortDir)
{
$myPager->add_sort_key( $thisSortKey, $thisSortDir);
}
$userList = $myPager->get_result_list();
if (is_array($userList))
{
$tbl_mdb_names = claro_sql_get_main_tbl();
foreach ($userList as $userKey => $user)
{
$sql ="SELECT count(DISTINCT code_cours) AS qty_course
FROM `" . $tbl_mdb_names['rel_course_user'] . "`
WHERE user_id = '". (int) $user['user_id'] ."'
GROUP BY user_id";
$userList[$userKey]['qty_course'] = (int) claro_sql_query_get_single_value($sql);
}
}
$userGrid = array();
if (is_array($userList))
foreach ($userList as $userKey => $user)
{
$userGrid[$userKey]['user_id'] = $user['user_id'];
$userGrid[$userKey]['name'] = $user['name'];
$userGrid[$userKey]['firstname'] = $user['firstname'];
$userEmailLabel=null;
if ( !empty($_SESSION['admin_user_search']) )
{
$bold_search = str_replace('*','.*',$_SESSION['admin_user_search']);
$userGrid[$userKey]['name'] = eregi_replace('(' . $bold_search . ')' , '<b>\\1</b>', $user['name']);
$userGrid[$userKey]['firstname'] = eregi_replace('(' . $bold_search . ')' , '<b>\\1</b>', $user['firstname']);
$userEmailLabel = eregi_replace('(' . $bold_search . ')', '<b>\\1</b>' , $user['email']);
}
$userGrid[$userKey]['officialCode'] = empty($user['officialCode']) ? ' - ' : $user['officialCode'];
$userGrid[$userKey]['email'] = claro_html_mailTo($user['email'], $userEmailLabel);
$userGrid[$userKey]['isCourseCreator'] = ( $user['isCourseCreator']?get_lang('Course creator'):get_lang('User'));
if ( $user['isPlatformAdmin'] )
{
$userGrid[$userKey]['isCourseCreator'] .= '<br /><span class="highlight">' . get_lang('Administrator').'</span>';
}
$userGrid[$userKey]['settings'] = '<a href="adminprofile.php'
. '?uidToEdit=' . $user['user_id']
. '&cfrom=ulist' . $addToURL . '">'
. '<img src="' . get_icon_url('usersetting') . '" alt="' . get_lang('User settings') . '" />'
. '</a>';
$userGrid[$userKey]['qty_course'] = '<a href="adminusercourses.php?uidToEdit=' . $user['user_id']
. '&cfrom=ulist' . $addToURL . '">' . "\n"
. get_lang('%nb course(s)', array('%nb' => $user['qty_course'])) . "\n"
. '</a>' . "\n"
;
$userGrid[$userKey]['delete'] = '<a href="' . $_SERVER['PHP_SELF']
. '?cmd=delete&user_id=' . $user['user_id']
. '&offset=' . $offset . $addToURL . '" '
. ' onclick="return confirmation(\'' . clean_str_for_javascript(' ' . $user['firstname'] . ' ' . $user['name']).'\');">' . "\n"
. '<img src="' . get_icon_url('deluser') . '" alt="' . get_lang('Delete') . '" />' . "\n"
. '</a> '."\n"
;
}
$sortUrlList = $myPager->get_sort_url_list($_SERVER['PHP_SELF']);
$userDataGrid = new claro_datagrid();
$userDataGrid->set_grid($userGrid);
$userDataGrid->set_colHead('name') ;
$userDataGrid->set_colTitleList(array (
'user_id'=>'<a href="' . $sortUrlList['user_id'] . '">' . get_lang('Numero') . '</a>'
,'name'=>'<a href="' . $sortUrlList['name'] . '">' . get_lang('Last name') . '</a>'
,'firstname'=>'<a href="' . $sortUrlList['firstname'] . '">' . get_lang('First name') . '</a>'
,'officialCode'=>'<a href="' . $sortUrlList['officialCode'] . '">' . get_lang('Administrative code') . '</a>'
,'email'=>'<a href="' . $sortUrlList['email'] . '">' . get_lang('Email') . '</a>'
,'isCourseCreator'=>'<a href="' . $sortUrlList['isCourseCreator'] . '">' . get_lang('Status') . '</a>'
,'settings'=> get_lang('User settings')
,'qty_course' => get_lang('Courses')
,'delete'=>get_lang('Delete') ));
if ( count($userGrid)==0 )
{
$userDataGrid->set_noRowMessage( '<center>'.get_lang('No user to display') . "\n"
. '<br />' . "\n"
. '<a href="advancedUserSearch.php' . $addtoAdvanced . '">' . get_lang('Search again (advanced)') . '</a></center>' . "\n"
);
}
else
{
$userDataGrid->set_colAttributeList(array ( 'user_id' => array ('align' => 'center')
, 'officialCode' => array ('align' => 'center')
, 'settings' => array ('align' => 'center')
, 'delete' => array ('align' => 'center')
));
}
//---------
// DISPLAY
//---------
//PREPARE
// javascript confirm pop up declaration
$htmlHeadXtra[] =
'<script type="text/javascript">
function confirmation (name)
{
if (confirm("'.clean_str_for_javascript(get_lang('Are you sure to delete')).'" + name + "? "))
{return true;}
else
{return false;}
}'
."\n".'</script>'."\n";
//Header
include get_path('incRepositorySys') . '/claro_init_header.inc.php';
// Display tool title
echo claro_html_tool_title($nameTools) . "\n\n";
//Display Forms or dialog box(if needed)
if( isset($dialogBox) ) echo claro_html_message_box($dialogBox);
//Display selectbox and advanced search link
//TOOL LINKS
//Display search form
if ( !empty($isSearchedHTML) )
{
echo claro_html_message_box ('<b>' . get_lang('Search on') . '</b> : <small>' . $isSearchedHTML . '</small>') ;
}
echo '<table width="100%">' . "\n"
. '<tr>' . "\n"
. '<td>' . '<a class="claroCmd" href="adminaddnewuser.php">'
. '<img src="' . get_icon_url('user') . '" alt="" />'
. get_lang('Create user')
. '</a>'
. '</td>' . "\n"
. '<td>' . ''
. '<td align="right">' . "\n"
. '<form action="' . $_SERVER['PHP_SELF'] . '">' . "\n"
. '<label for="search">' . get_lang('Make new search') . ' </label>' . "\n"
. '<input type="text" value="' . htmlspecialchars($search).'" name="search" id="search" />' . "\n"
. '<input type="submit" value=" ' . get_lang('Ok') . ' " />' . "\n"
. '<input type="hidden" name="newsearch" value="yes" />' . "\n"
. ' [<a class="claroCmd" href="advancedUserSearch.php' . $addtoAdvanced . '" >' . get_lang('Advanced') . '</a>]' . "\n"
. '</form>' . "\n"
. '</td>' . "\n"
. '</tr>' . "\n"
. '</table>' . "\n\n"
;
if ( count($userGrid) > 0 ) echo $myPager->disp_pager_tool_bar($_SERVER['PHP_SELF']);
echo $userDataGrid->render();
if ( count($userGrid) > 0 ) echo $myPager->disp_pager_tool_bar($_SERVER['PHP_SELF']);
include get_path('incRepositorySys') . '/claro_init_footer.inc.php';
/**
*
* @todo: the name would be review befor move to a lib
* @todo: eject usage in function of $_SESSION
*
* @return sql statements
*/
function get_sql_filtered_user_list()
{
if ( isset($_SESSION['admin_user_action']) )
{
switch ($_SESSION['admin_user_action'])
{
case 'plateformadmin' :
{
$filterOnStatus = 'plateformadmin';
} break;
case 'createcourse' :
{
$filterOnStatus= 'createcourse';
} break;
case 'followcourse' :
{
$filterOnStatus='followcourse';
} break;
case 'all' :
{
$filterOnStatus='';
} break;
default:
{
trigger_error('admin_user_action value unknow : '.var_export($_SESSION['admin_user_action'],1),E_USER_NOTICE);
$filterOnStatus='followcourse';
}
}
}
else $filterOnStatus='';
$tbl_mdb_names = claro_sql_get_main_tbl();
$sql = "SELECT U.user_id AS user_id,
U.nom AS name,
U.prenom AS firstname,
U.authSource AS authSource,
U.email AS email,
U.officialCode AS officialCode,
U.phoneNumber AS phoneNumber,
U.pictureUri AS pictureUri,
U.creatorId AS creator_id,
U.isCourseCreator ,
U.isPlatformAdmin AS isPlatformAdmin
FROM `" . $tbl_mdb_names['user'] . "` AS U
WHERE 1=1 ";
//deal with admin user search only
if ($filterOnStatus=='plateformadmin')
{
$sql .= " AND U.isPlatformAdmin = 1";
}
//deal with KEY WORDS classification call
if (isset($_SESSION['admin_user_search']))
{
$sql .= " AND (U.nom LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."%'
OR U.prenom LIKE '%".claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."%' ";
$sql .= " OR U.email LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."%'";
$sql .= " OR U.username LIKE '". claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."%'";
$sql .= " OR U.officialCode = '". claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."')";
}
//deal with ADVANCED SEARCH parameters call
if ( isset($_SESSION['admin_user_firstName']) && !empty($_SESSION['admin_user_firstname']) )
{
$sql .= " AND (U.prenom LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_firstName'])) ."%') ";
}
if ( isset($_SESSION['admin_user_lastName']) && !empty($_SESSION['admin_user_lastName']) )
{
$sql .= " AND (U.nom LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_lastName']))."%') ";
}
if ( isset($_SESSION['admin_user_userName']) && !empty($_SESSION['admin_user_userName']) )
{
$sql.= " AND (U.username LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_userName'])) ."%') ";
}
if ( isset($_SESSION['admin_user_officialCode']) && !empty($_SESSION['admin_user_officialCode']) )
{
$sql.= " AND (U.officialCode LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_officialCode'])) ."%') ";
}
if ( isset($_SESSION['admin_user_mail']) && !empty($_SESSION['admin_user_mail']) )
{
$sql.= " AND (U.email LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_mail'])) ."%') ";
}
if ($filterOnStatus== 'createcourse' )
{
$sql.=" AND (U.isCourseCreator=1)";
}
elseif ($filterOnStatus=='followcourse' )
{
$sql.=" AND (U.isCourseCreator=0)";
}
return $sql;
}
function prepare_search()
{
$queryStringElementList = array();
$isSearched = array();
if ( !empty($_SESSION['admin_user_search']) )
{
$isSearched[] = $_SESSION['admin_user_search'];
}
if ( !empty($_SESSION['admin_user_firstName']) )
{
$isSearched[] = get_lang('First name') . '=' . $_SESSION['admin_user_firstName'];
$queryStringElementList [] = 'firstName=' . urlencode($_SESSION['admin_user_firstName']);
}
if ( !empty($_SESSION['admin_user_lastName']) )
{
$isSearched[] = get_lang('Last name') . '=' . $_SESSION['admin_user_lastName'];
$queryStringElementList[] = 'lastName=' . urlencode($_SESSION['admin_user_lastName']);
}
if ( !empty($_SESSION['admin_user_userName']) )
{
$isSearched[] = get_lang('Username') . '=' . $_SESSION['admin_user_userName'];
$queryStringElementList[] = 'userName=' . urlencode($_SESSION['admin_user_userName']);
}
if ( !empty($_SESSION['admin_user_officialCode']) )
{
$isSearched[] = get_lang('Official code') . '=' . $_SESSION['admin_user_officialCode'];
$queryStringElementList[] = 'userName=' . urlencode($_SESSION['admin_user_officialCode']);
}
if ( !empty($_SESSION['admin_user_mail']) )
{
$isSearched[] = get_lang('Email') . '=' . $_SESSION['admin_user_mail'];
$queryStringElementList[] = 'mail=' . urlencode($_SESSION['admin_user_mail']);
}
if ( !empty($_SESSION['admin_user_action']) && ($_SESSION['admin_user_action'] == 'followcourse'))
{
$isSearched[] = '<b>' . get_lang('Follow courses') . '</b>';
$queryStringElementList[] = 'action=' . urlencode($_SESSION['admin_user_action']);
}
elseif ( !empty($_SESSION['admin_user_action']) && ($_SESSION['admin_user_action'] == 'createcourse'))
{
$isSearched[] = '<b>' . get_lang('Course creator') . '</b>';
$queryStringElementList[] = 'action=' . urlencode($_SESSION['admin_user_action']);
}
elseif (isset($_SESSION['admin_user_action']) && ($_SESSION['admin_user_action']=='plateformadmin'))
{
$isSearched[] = '<b>' . get_lang('Platform administrator') . ' </b> ';
$queryStringElementList[] = 'action=' . urlencode($_SESSION['admin_user_action']);
}
else $queryStringElementList[] = 'action=all';
if ( count($queryStringElementList) > 0 ) $queryString = '?' . implode('&',$queryStringElementList);
else $queryString = '';
$searchInfo['isSearched'] = $isSearched;
$searchInfo['addtoAdvanced'] = $queryString;
return $searchInfo;
}
?> | yannhos115/claroline-exercice | claroline/admin/adminusers.php | PHP | gpl-2.0 | 18,212 |
//
// Copyright 2002 Sony Corporation
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
#include <OPENR/OPENRAPI.h>
#include <OPENR/OSyslog.h>
#include "MoNetAgentManager.h"
#include "MoNetAgent.h"
MoNetAgentManager::MoNetAgentManager() : activeMoNetAgent(0),
activeAgentCommand(),
moNetAgentList(),
effectorSubject(0)
{
for (int i = 0; i < NUM_JOINTS; i++) primitiveID[i] = oprimitiveID_UNDEF;
for (int i = 0; i < NUM_COMMAND_VECTOR; i++) commandRegions[i] = 0;
}
void
MoNetAgentManager::Init()
{
OSYSDEBUG(("MoNetAgentManager::Init()\n"));
OpenPrimitives();
NewCommandVectorData();
list<MoNetAgent*>::iterator iter = moNetAgentList.begin();
list<MoNetAgent*>::iterator last = moNetAgentList.end();
while (iter != last) {
(*iter)->Init();
++iter;
}
}
void
MoNetAgentManager::Start(OSubject* effector)
{
OSYSDEBUG(("MoNetAgentManager::Start()\n"));
effectorSubject = effector;
}
void
MoNetAgentManager::RegisterMoNetAgent(MoNetAgent* m)
{
OSYSDEBUG(("MoNetAgentManager::RegisterMoNetAgent()\n"));
moNetAgentList.push_back(m);
m->SetMoNetAgentManager(this);
}
void
MoNetAgentManager::NotifyCommand(const ONotifyEvent& event,
MoNetAgentResult* result)
{
MoNetAgentCommand* cmd = (MoNetAgentCommand*)event.Data(0);
if (activeMoNetAgent != 0) {
// BUSY
result->agent = cmd->agent;
result->index = cmd->index;
result->status = monetBUSY;
result->endPosture = monetpostureUNDEF;
return;
}
list<MoNetAgent*>::iterator iter = moNetAgentList.begin();
list<MoNetAgent*>::iterator last = moNetAgentList.end();
while (iter != last) {
if ((*iter)->AreYou(cmd->agent) == true) {
(*iter)->NotifyCommand(*cmd, result);
if (result->status != monetSUCCESS) return;
activeMoNetAgent = *iter;
activeAgentCommand = *cmd;
return;
}
++iter;
}
// INVALID_ARG
result->agent = cmd->agent;
result->index = cmd->index;
result->status = monetINVALID_ARG;
result->endPosture = monetpostureUNDEF;
}
void
MoNetAgentManager::ReadyEffector(const OReadyEvent& event,
MoNetAgentResult* result)
{
if (activeMoNetAgent == 0) {
result->agent = monetagentUNDEF;
result->index = -1;
result->status = monetSUCCESS;
result->endPosture = monetpostureUNDEF;
return;
}
activeMoNetAgent->ReadyEffector(activeAgentCommand, result);
if (result->status != monetSUCCESS) {
activeMoNetAgent = 0;
activeAgentCommand.Clear();
}
}
void
MoNetAgentManager::OpenPrimitives()
{
OSYSDEBUG(("MoNetAgentManager::OpenPrimitives()\n"));
OStatus result;
for (int i = 0; i < NUM_JOINTS; i++) {
result = OPENR::OpenPrimitive(JOINT_LOCATOR[i], &primitiveID[i]);
if (result != oSUCCESS) {
OSYSLOG1((osyslogERROR, "%s : %s %d",
"MoNetAgentManager::OpenPrimitives()",
"OPENR::OpenPrimitive() FAILED", result));
}
}
}
void
MoNetAgentManager::NewCommandVectorData()
{
OSYSDEBUG(("MoNetAgentManager::NewCommandVectorData()\n"));
OStatus result;
MemoryRegionID cmdVecDataID;
OCommandVectorData* cmdVecData;
OCommandInfo* info;
for (int i = 0; i < NUM_COMMAND_VECTOR; i++) {
result = OPENR::NewCommandVectorData(NUM_JOINTS,
&cmdVecDataID, &cmdVecData);
if (result != oSUCCESS) {
OSYSLOG1((osyslogERROR, "%s : %s %d",
"MoNetAgentManager::NewCommandVectorData()",
"OPENR::NewCommandVectorData() FAILED", result));
}
commandRegions[i] = new RCRegion(cmdVecData->vectorInfo.memRegionID,
cmdVecData->vectorInfo.offset,
(void*)cmdVecData,
cmdVecData->vectorInfo.totalSize);
cmdVecData->SetNumData(NUM_JOINTS);
for (int j = 0; j < NUM_JOINTS; j++) {
info = cmdVecData->GetInfo(j);
info->Set(odataJOINT_COMMAND2, primitiveID[j], NUM_FRAMES);
}
}
}
RCRegion*
MoNetAgentManager::FindFreeCommandRegion()
{
for (int i = 0; i < NUM_COMMAND_VECTOR; i++) {
if (commandRegions[i]->NumberOfReference() == 1) {
return commandRegions[i];
}
}
OSYSPRINT(("err\n"));
OSYSLOG1((osyslogERROR, "%s : %s %d",
"MoNetAgentManager::FindFreeCommandRegion()",
"FAILED", 0));
return 0;
}
int
MoNetAgentManager::GetIndexFromJointName( const char *jointName )
{
for ( int i = 0; i < NUM_JOINTS; i ++ ) {
if ( !strcmp( JOINT_LOCATOR[ i ], jointName ) ) {
return i;
}
}
OSYSLOG1((osyslogERROR, "%s : %s",
"MoNetAgentManager::GetIndexFromJointName()",
"invalid joint name"));
return 0;
}
void
MoNetAgentManager::NotifyPose(const ONotifyEvent& event)
{
PoseData* data = (PoseData*)event.Data(0);
list<MoNetAgent*>::iterator iter = moNetAgentList.begin();
list<MoNetAgent*>::iterator last = moNetAgentList.end();
while (iter != last) {
if ((*iter)->AreYou(monetagentANY) == true) {
(*iter)->SetPose(data);
return;
}
++iter;
}
}
| EiichiroIto/scratch-aibo | MotionAgents/MoNetAgentManager.cc | C++ | gpl-2.0 | 5,877 |
<?php
/*
Plugin Name: Калькулятор цен
Plugin URI: none
Description: Плагин загрузки цен на услуги СТО для калькулятора цен на сайте Автодоктор
Version: 3.1.5
Author: WebUniverse
Author URI: http://webuniverse.com.ua/
*/
define( 'prices_calculator_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'prices_calculator_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( str_replace(chr(92), '/', ABSPATH) . 'wp-admin/includes/file.php' );
}
require_once( str_replace(chr(92), '/', ABSPATH) . 'wp-includes/pluggable.php');
require_once('php_excel/Classes/PHPExcel.php');
function addAdminPagePricesCalculator(){
add_menu_page('Система анализа загруженного .xls файла и его разбор для Калькулятора цен',
'Калькулятор цен',
8,
'prices_calculator',
'pricesCalculatorOptionsPage');
}
function pricesCalculatorOptionsPage(){
global $wpdb;
echo '<h2>Система анализа загруженного .xls файла и его разбор для Калькулятора цен</h2>';
if($_FILES['file']){
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
echo "Успешно загруженный файл, файл: ";
echo $movefile['file'] . "<br><br>";
readXLSXDocument($wpdb, $movefile['file']);
//var_dump( $movefile);
} else {
echo "Ошибка: ";
echo $movefile['error'];
}
}
if($_POST['delete']){
$results = json_decode(json_encode($wpdb->get_results( 'SELECT pc_services.* FROM pc_services
WHERE pc_services.id_service = ' . $_POST['delete'] . ' LIMIT 1; ' )),true);
$id_category = $results[0]['id_category'];
$wpdb->query(
"DELETE FROM pc_services WHERE id_service = '" . $_POST['delete'] . "'"
);
$results = json_decode(json_encode($wpdb->get_results( 'SELECT pc_services.* FROM pc_services
WHERE pc_services.id_category = ' . $id_category . ' LIMIT 1; ' )),true);
if(!$results){
$wpdb->query(
"DELETE FROM pc_categories WHERE id_category = '" . $id_category . "'"
);
}
echo "Успешно удалено!<br><br><br>";
}
echo '<h3>Загрузите Excel файл для его разбора системой:</h3><br>
<form method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "file"><br><br><br>
<input type = "submit" value = "Отправить">
</form><br><br>';
echo "<h3>Имеющиейся данные:</h3><br>";
$results = json_decode(json_encode($wpdb->get_results( 'SELECT pc_services.*, pc_categories.* FROM pc_services
INNER JOIN pc_categories
ON pc_services.id_category = pc_categories.id_category' )),true);
if($results){
echo '<table border = "1" cellspacing="2" cellpadding="10">
<tr>
<td><strong>Категория</strong></td>
<td><strong>Услуга</strong></td>
<td><strong>Стоимость</strong></td>
<td><strong>Удалить</strong></td>
</tr>';
foreach ($results as $data) {
echo '<tr>
<td>' . $data['category'] . '</td>
<td>' . $data['service'] . '</td>
<td>' . $data['price'] . '</td>
<td>
<form method = "POST">
<input type = "hidden" name = "delete" value = "' . $data['id_service'] . '">
<input type = "submit" value = "Удалить">
</form>
</td>
</tr>';
}
echo '</table>';
}
}
function readXLSXDocument($wpdb, $file_name){
$inputFileName = $file_name;
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' . $e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
if($rowData[0]){
echo 'Были произведены действия:<br>';
foreach($rowData[0] as $k=>$v){
if($k == 0){
$service_category = $v;
}else if($k == 1){
$service = $v;
}else if($k == 2){
$service_price = $v;
if(addPrices($wpdb, $service_category, $service, $service_price)){
echo "Добавлено - Категория: " . $service_category . ". Услуга: " . $service . ". Стоимость = " . $service_price . "<br/>";
}else{
echo "Обновлено - Категория: " . $service_category . ". Услуга: " . $service . ". Стоимость = " . $service_price . "<br/>";
}
}
}
}
}
}
function addPrices($wpdb, $category, $service, $price){
$added = false;
$results = json_decode(json_encode($wpdb->get_results( 'SELECT * FROM pc_categories WHERE category = "' . $category . '"' )),true);
if(!$results){
$wpdb->insert(
'pc_categories',
array(
'category' => $category
)
);
$id = $wpdb->insert_id;
}else{
$id = $results[0]['id_category'];
}
$results = json_decode(json_encode($wpdb->get_results( 'SELECT * FROM pc_services WHERE id_category = "' . $id . '" AND
service = "' . $service . '"' )), true);
if(!$results){
$wpdb->insert(
'pc_services',
array(
'id_category' => $id,
'service' => $service,
'price' => $price
)
);
$added = true;
}else{
$wpdb->update(
'pc_services',
array(
'price' => $price
),
array( 'id_service' => $results[0]['id_service'] )
);
}
return $added;
}
add_action('admin_menu', 'addAdminPagePricesCalculator');
| PapaPsih/Avtodoctor | wp-content/plugins/prices_calculator/prices_calculator.php | PHP | gpl-2.0 | 6,459 |
import testlib.flowexpression.qual.FlowExp;
public class Canonicalization {
class LockExample {
protected final Object myLock = new Object();
protected @FlowExp("myLock") Object locked;
protected @FlowExp("this.myLock") Object locked2;
public @FlowExp("myLock") Object getLocked() {
return locked;
}
}
class Use {
final LockExample lockExample1 = new LockExample();
final Object myLock = new Object();
@FlowExp("lockExample1.myLock") Object o1 = lockExample1.locked;
@FlowExp("lockExample1.myLock") Object o2 = lockExample1.locked2;
@FlowExp("myLock")
//:: error: (assignment.type.incompatible)
Object o3 = lockExample1.locked;
@FlowExp("this.myLock")
//:: error: (assignment.type.incompatible)
Object o4 = lockExample1.locked2;
@FlowExp("lockExample1.myLock") Object oM1 = lockExample1.getLocked();
@FlowExp("myLock")
//:: error: (assignment.type.incompatible)
Object oM2 = lockExample1.getLocked();
@FlowExp("this.myLock")
//:: error: (assignment.type.incompatible)
Object oM3 = lockExample1.getLocked();
}
}
| CharlesZ-Chen/checker-framework | framework/tests/flowexpression/Canonicalization.java | Java | gpl-2.0 | 1,226 |
/******************************************************************************
*
* Metodología de la Programación
* Grado en Ingeniería Informática
*
* 2014 - Ernesto Serrano Collado
* ------------------------------
*
* Supongamos que para definir matrices bidimensionales dinamicas usamos una
* estructura como la que aparece en la figura 4(tipo Matriz2D-1). En los apuntes
* de clase se detalla como crear y liberar esta estructura.
* Nota: Recuerde que los modulos que procesan estructuras de este tipo necesitan
* recibir como parametros el numero de filas y columnas de la matriz.
*
* a) Construir un modulo que lea del teclado fils×cols valores y los copie en la
* matriz.
* b) Construir un modulo que muestre los valores guardados en la matriz.
* c) Construir un modulo que reciba una matriz de ese tipo, cree y devuelva una
* copia.
* d) Construir un modulo que extraiga una submatriz de una matriz bidimensional
* Matriz2D-1. Como argumento de la funcion se introduce desde que fila y
* columna y hasta que fila y columna se debe realizar la copia de la matriz
* original. La submatriz devuelta es una nueva matriz.
* e) Construir un modulo que elimine una fila de una matriz bidimensional
* Matriz2D-1. Obviamente, no se permiten “huecos” (filas vacias). El modulo
* devuelve una nueva matriz.
* f) Construir un modulo como el anterior,pero que en vez de eliminar una fila,
* elimine una columna. El modulo devuelve una nueva matriz.
* g) Construir un modulo que devuelva la traspuesta de una matriz. La matriz
* devuelta es una nueva matriz.
* h) Construir un modulo que reciba una matriz y la modifique, de tal manera
* que “invierta” las filas: la primera sera la ultima, la segunda la
* penultima, y asi sucesivamente. El modulo devuelve una nueva matriz.
*
******************************************************************************/
#include <iostream> //Inclusión de los recursos de E/S
#include <iomanip>
#include "Matriz2D_1.h"
using namespace std;
/*****************************************************************************/
//Programa Principal
int main(){
Matriz2D_1 m1; // "m1" matriz dinamicas 2D.
int filas, cols;
// Leer num. de filas y columnas
cout << "Numero de filas : ";
cin >> filas;
cout << "Numero de columnas : ";
cin >> cols;
// Crear matrices dinamicas
cout << "Creando Matriz ("<< filas << "X"<< cols << ")" << endl;
m1 = CreaMatriz2D_1 (filas, cols);
//Llena la matriz y muestra su contenido
m1 = LlenarMatriz2D_1(m1, filas, cols);
cout << endl << "Matriz Original:" << endl;
PintaMatriz2D_1 (m1, filas, cols);
//Copia la matriz y muestra su contenido
Matriz2D_1 copia_m1 = CopiaMatriz2D_1(m1, filas, cols);
cout << endl << "Copia Matriz:" << endl;
PintaMatriz2D_1 (copia_m1, filas, cols);
LiberaMatriz2D_1 (copia_m1, filas, cols);
int desde = 0, hasta = 2;
if (filas >= hasta && cols >= hasta) {
//Crea una submatriz y muestra su contenido
Matriz2D_1 sub_m1 = SubMatriz2D_1(m1, desde, desde, hasta, hasta);
cout << endl << "Sub Matriz:" << endl;
PintaMatriz2D_1 (sub_m1, hasta - desde, hasta - desde);
LiberaMatriz2D_1 (sub_m1, hasta - desde, hasta - desde);
}
//Elimina una fila de la matriz y muestra su contenido
Matriz2D_1 delf_m1 = EliminaFilaMatriz2D_1(m1, filas, cols, 0);
cout << endl << "Matriz con fila eliminada:" << endl;
PintaMatriz2D_1 (delf_m1, filas - 1, cols);
LiberaMatriz2D_1 (delf_m1, filas - 1, cols);
//Elimina una columna de la matriz y muestra su contenido
Matriz2D_1 delc_m1 = EliminaColumnaMatriz2D_1(m1, filas, cols, 0);
cout << endl << "Matriz con columna eliminada:" << endl;
PintaMatriz2D_1 (delc_m1, filas, cols - 1);
LiberaMatriz2D_1 (delc_m1, filas, cols - 1);
//Obtiene la traspuesta de la matriz y muestra su contenido
Matriz2D_1 tras_m1 = TraspuestaMatriz2D_1(m1, filas, cols);
cout << endl << "Traspuesta Matriz:" << endl;
PintaMatriz2D_1 (tras_m1, cols, filas);
LiberaMatriz2D_1 (tras_m1, cols, filas);
//Obtiene la inversa de la matriz y muestra su contenido
Matriz2D_1 inv_m1 = InvierteMatriz2D_1(m1, filas, cols);
cout << endl << "Matriz invertida:" << endl;
PintaMatriz2D_1 (inv_m1, filas, cols);
LiberaMatriz2D_1 (inv_m1, filas, cols);
// Liberar la memoria ocupada
cout << endl << "Liberando matriz" << endl;
LiberaMatriz2D_1 (m1, filas, cols);
return (0);
} | erseco/ugr_metodologia_programacion | Practica_5/src/ejercicio8.cpp | C++ | gpl-2.0 | 4,558 |
# -*- coding: utf-8 -*-
#
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.conf import settings
from django.utils.translation import gettext_lazy as _
def jumpserver_processor(request):
# Setting default pk
context = {
'DEFAULT_PK': '00000000-0000-0000-0000-000000000000',
'LOGO_URL': static('img/logo.png'),
'LOGO_TEXT_URL': static('img/logo_text.png'),
'LOGIN_IMAGE_URL': static('img/login_image.png'),
'FAVICON_URL': static('img/facio.ico'),
'JMS_TITLE': 'Jumpserver',
'VERSION': settings.VERSION,
'COPYRIGHT': 'FIT2CLOUD 飞致云' + ' © 2014-2019',
'SECURITY_COMMAND_EXECUTION': settings.SECURITY_COMMAND_EXECUTION,
'SECURITY_MFA_VERIFY_TTL': settings.SECURITY_MFA_VERIFY_TTL,
}
return context
| eli261/jumpserver | apps/jumpserver/context_processor.py | Python | gpl-2.0 | 835 |