repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
TRCIMPLAN/PEM | lib/Configuracion/PlantillaConfig.php | 2558 | <?php
/*
* SMIbeta - Plantilla Configuración
*
* Copyright (C) 2014 IMPLAN Torreó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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Namespace
namespace Configuracion;
/**
* Clase PlantillaConfig
*/
class PlantillaConfig {
public $sitio_titulo = 'Plan Estratégico Metropolitano | IMPLAN Torreón';
public $sitio_url = 'http://trcimplan.github.io/PEM';
public $rss = 'rss.xml';
public $favicon = 'imagenes/favicon.png';
public $propio_css = 'css/trcimplan.css';
public $en_raiz = false; // Si es verdadero los vínculos serán para un archivo en la raíz del sitio
public $para_compartir = false; // Si es verdadero pondrá los metas para tarjetas en Twitter/Facebook
public $autor = 'TrcIMPLAN'; // Autor por defecto
public $mensaje_oculto = <<<FINAL
<!-- ========================================================================================
Instituto Municipal de Planeación y Competitividad de Torreón.
Todos los Derechos Reservados. © 2014.
Este sistema fue elaborado por personal del IMPLAN Torreón.
Es publicado como Software Libre bajo la licencia GPL versión 3.
Descargue, estudie y colabore con el IMPLAN Torreón por medio de GitHub:
GitHub https://github.com/TRCIMPLAN
Agradecemos y compartimos las tecnologías abiertas sobre las que se basa:
Twitter Bootstrap http://getbootstrap.com
StartBootStrap http://startbootstrap.com
Morris.js http://www.oesmith.co.uk/morris.js
LeafLet http://leafletjs.com
======================================================================================== -->
FINAL;
public $pie = ' <p>Todos los Derechos Reservados. Instituto Municipal de Planeación y Competitividad de Torreón © 2014</p>';
} // Clase PlantillaConfig
?>
| gpl-3.0 |
petebrew/tellervo | src/main/java/org/tellervo/desktop/gis/GraphicsCapability.java | 77 | package org.tellervo.desktop.gis;
public class GraphicsCapability {
}
| gpl-3.0 |
vpenso/libvirt-shell-functions | _config/chef_knife.rb | 442 | log_level :info
log_location STDOUT
node_name 'devops'
client_key '/srv/vms/instances/lxcm01.devops.test/chef/devops.pem'
validation_client_name 'chef-validator'
chef_server_url 'http://10.1.1.3:4000'
cache_type 'BasicFile'
cache_options( :path => '/tmp/chef/devops/checksums' )
cookbook_path [ "~/chef/cookbooks","~/chef/site-cookbooks" ]
| gpl-3.0 |
lipki/TFCNT | src/Common/com/bioxx/tfc/Containers/ContainerPlayerTFC.java | 7641 | package com.bioxx.tfc.Containers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.ContainerPlayer;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import com.bioxx.tfc.Containers.Slots.SlotArmorTFC;
import com.bioxx.tfc.Core.Player.PlayerInventory;
import com.bioxx.tfc.Handlers.CraftingHandler;
import com.bioxx.tfc.Handlers.FoodCraftingHandler;
import com.bioxx.tfc.Items.ItemTFCArmor;
import com.bioxx.tfc.api.Interfaces.IFood;
public class ContainerPlayerTFC extends ContainerPlayer
{
private final EntityPlayer thePlayer;
public ContainerPlayerTFC(InventoryPlayer playerInv, boolean par2, EntityPlayer player)
{
super(playerInv, par2, player);
this.craftMatrix = new InventoryCrafting(this, 3, 3);
this.inventorySlots.clear();
this.inventoryItemStacks.clear();
this.thePlayer = player;
this.addSlotToContainer(new SlotCrafting(player, craftMatrix, craftResult, 0, 152, 36));
int x;
int y;
for (x = 0; x < 2; ++x)
{
for (y = 0; y < 2; ++y)
this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18, 18 + x * 18));
}
for (x = 0; x < playerInv.armorInventory.length; ++x)
{
int index = playerInv.getSizeInventory() - 1 - x;
this.addSlotToContainer(new SlotArmorTFC(this, playerInv, index, 8, 8 + x * 18, x));
}
PlayerInventory.buildInventoryLayout(this, playerInv, 8, 90, false, true);
//Manually built the remaining crafting slots because of an order issue. These have to be created after the default slots
if(player.getEntityData().hasKey("craftingTable") || !player.worldObj.isRemote)
{
x = 2; y = 0; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18, 18 + x * 18));
x = 2; y = 1; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18, 18 + x * 18));
x = 0; y = 2; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18, 18 + x * 18));
x = 1; y = 2; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18, 18 + x * 18));
x = 2; y = 2; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18, 18 + x * 18));
}
else
{
//Have to create some dummy slots
x = 2; y = 0; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18-50000, 18 + x * 18));
x = 2; y = 1; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18-50000, 18 + x * 18));
x = 0; y = 2; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18-50000, 18 + x * 18));
x = 1; y = 2; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18-50000, 18 + x * 18));
x = 2; y = 2; this.addSlotToContainer(new Slot(craftMatrix, y + x * 3, 82 + y * 18-50000, 18 + x * 18));
}
PlayerInventory.addExtraEquipables(this, playerInv, 8, 90, false);
this.onCraftMatrixChanged(this.craftMatrix);
}
@Override
public void onContainerClosed(EntityPlayer player)
{
if(!player.worldObj.isRemote)
{
super.onContainerClosed(player);
for (int i = 0; i < 9; ++i)
{
ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i);
if (itemstack != null)
player.dropPlayerItemWithRandomChoice(itemstack, false);
}
this.craftResult.setInventorySlotContents(0, (ItemStack)null);
}
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int par2)
{
ItemStack origStack = null;
Slot slot = (Slot)this.inventorySlots.get(par2);
if (slot != null && slot.getHasStack())
{
ItemStack slotStack = slot.getStack();
origStack = slotStack.copy();
if (par2 == 0)
{
FoodCraftingHandler.preCraft(player, slotStack, craftMatrix);
CraftingHandler.preCraft(player, slotStack, craftMatrix);
if (!this.mergeItemStack(slotStack, 9, 45, true))
return null;
slot.onSlotChange(slotStack, origStack);
}
else if ((par2 >= 1 && par2 < 5) || (player.getEntityData().hasKey("craftingTable") && (par2 >= 45 && par2 < 50)))
{
if (!this.mergeItemStack(slotStack, 9, 45, false))
return null;
}
else if (par2 >= 5 && par2 < 9 || par2 == 50)
{
if (!this.mergeItemStack(slotStack, 9, 45, false))
return null;
}
else if (origStack.getItem() instanceof ItemArmor)
{
if(origStack.getItem() instanceof ItemTFCArmor &&
((!((Slot)this.inventorySlots.get(5 + ((ItemTFCArmor)origStack.getItem()).getUnadjustedArmorType())).getHasStack() && ((ItemTFCArmor)origStack.getItem()).getUnadjustedArmorType() != 4)||
(!((Slot)this.inventorySlots.get(50)).getHasStack())))
{
int j = ((ItemTFCArmor)origStack.getItem()).getUnadjustedArmorType() != 4 ? 5 + ((ItemTFCArmor)origStack.getItem()).getUnadjustedArmorType() : 50;
if (!this.mergeItemStack(slotStack, j, j + 1, false))
return null;
}
else if(((!((Slot)this.inventorySlots.get(5 + ((ItemArmor)origStack.getItem()).armorType)).getHasStack() && ((ItemArmor)origStack.getItem()).armorType != 4)||
(!((Slot)this.inventorySlots.get(50)).getHasStack())))
{
int j = ((ItemArmor)origStack.getItem()).armorType != 4 ? 5 + ((ItemArmor)origStack.getItem()).armorType : 50;
if (!this.mergeItemStack(slotStack, j, j + 1, false))
return null;
}
}
else if (par2 >= 9 && par2 < 45 && origStack.getItem() instanceof IFood && !isCraftingGridFull())
{
if (!this.mergeItemStack(slotStack, 1, 5, false) && slotStack.stackSize == 0)
return null;
else if (slotStack.stackSize > 0 && player.getEntityData().hasKey("craftingTable") && !this.mergeItemStack(slotStack, 45, 50, false))
return null;
else if (slotStack.stackSize > 0 && par2 >= 9 && par2 < 36)
{
if (!this.mergeItemStack(slotStack, 36, 45, false))
return null;
}
else if (slotStack.stackSize > 0 && par2 >= 36 && par2 < 45)
{
if (!this.mergeItemStack(slotStack, 9, 36, false))
return null;
}
}
else if (par2 >= 9 && par2 < 36)
{
if (!this.mergeItemStack(slotStack, 36, 45, false))
return null;
}
else if (par2 >= 36 && par2 < 45)
{
if (!this.mergeItemStack(slotStack, 9, 36, false))
return null;
}
else if (!this.mergeItemStack(slotStack, 9, 45, false))
return null;
if (slotStack.stackSize == 0)
slot.putStack((ItemStack)null);
else
slot.onSlotChanged();
if (slotStack.stackSize == origStack.stackSize)
return null;
slot.onPickupFromSlot(player, slotStack);
}
return origStack;
}
@Override
public ItemStack slotClick(int sourceSlotID, int destSlotID, int clickType, EntityPlayer p)
{
if (clickType == 7 && sourceSlotID >= 9 && sourceSlotID < 45)
{
Slot sourceSlot = (Slot)this.inventorySlots.get(sourceSlotID);
if (sourceSlot != null && sourceSlot.canTakeStack(p))
{
Slot destSlot = (Slot)this.inventorySlots.get(destSlotID);
destSlot.putStack(sourceSlot.getStack());
sourceSlot.putStack(null);
return null;
}
}
return super.slotClick(sourceSlotID, destSlotID, clickType, p);
}
protected boolean isCraftingGridFull()
{
for(int i = 0; i < this.craftMatrix.getSizeInventory(); i++)
{
if(this.craftMatrix.getStackInSlot(i) == null)
return false;
}
return true;
}
public EntityPlayer getPlayer()
{
return this.thePlayer;
}
}
| gpl-3.0 |
jerabekjak/smoderp | main_src/io_functions/__init__.py | 66 | __all__ = ["hydrographs", "prt", "progress_bar", "post_proc"]
| gpl-3.0 |
Traderain/Wolven-kit | CP77.CR2W/Types/cp77/PachinkoMachineController.cs | 254 | using CP77.CR2W.Reflection;
namespace CP77.CR2W.Types
{
[REDMeta]
public class PachinkoMachineController : ArcadeMachineController
{
public PachinkoMachineController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| gpl-3.0 |
Dark1revan/chat1 | js/base/screen.js | 5206 | /**
* This file is part of "PCPIN Chat 6".
*
* "PCPIN Chat 6" is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* "PCPIN Chat 6" 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/>.
*/
/**
* Screen width, in pixels.
* @var int
*/
var winWidth=getWinWidth();
/**
* Screen height, in pixels.
* @var int
*/
var winHeight=getWinHeight();
/**
* Obtain the width in pixels of the given window
* @param object wh Window handler. Default: current window
* @return int Window width in pixels
*/
function getWinWidth(wh) {
var winWidth=-1;
if (typeof(wh)=='undefined') {
wh=window;
}
if (typeof(wh.innerWidth)=='number') {
// Non-IE browser
winWidth=wh.innerWidth;
} else if (wh.document.documentElement && (wh.document.documentElement.clientWidth || wh.document.documentElement.clientHeight)) {
// IE 6+ browser in 'standards compliant mode'
winWidth=wh.document.documentElement.clientWidth;
} else if (wh.document.body && (wh.document.body.clientWidth || wh.document.body.clientHeight)) {
// IE 4 compatible browser
winWidth=wh.document.body.clientWidth;
}
return winWidth;
}
/**
* Obtain the height in pixels of the given window
* @param object wh Window handler. Default: current window
* @return int Window height in pixels
*/
function getWinHeight(wh) {
var winHeight=-1;
if (typeof(wh)=='undefined') {
wh=window;
}
if (typeof(wh.innerHeight)=='number') {
// Non-IE browser
winHeight=wh.innerHeight;
} else if (wh.document.documentElement && (wh.document.documentElement.clientHeight || wh.document.documentElement.clientHeight)) {
// IE 6+ browser in 'standards compliant mode'
winHeight=wh.document.documentElement.clientHeight;
} else if (wh.document.body && (wh.document.body.clientHeight || wh.document.body.clientHeight)) {
// IE 4 compatible browser
winHeight=wh.document.body.clientHeight;
}
return winHeight;
}
/**
* Obtain the width of the document in the given window
* @param object wh Window handler. Default: current window
* @return int Document width
*/
function getUsedWidth(wh) {
var usedWidth=-1;
if (typeof(wh)=='undefined') {
wh=window;
}
try {
usedWidth=wh.document.documentElement.scrollWidth;
} catch (e) {}
return usedWidth;
}
/**
* Obtain the height of the document in the given window
* @param object wh Window handler. Default: current window
* @return int Document height
*/
function getUsedHeight(wh) {
var usedHeight=-1;
if (typeof(wh)=='undefined') {
wh=window;
}
try {
usedHeight=wh.document.documentElement.scrollHeight;
} catch (e) {}
return usedHeight;
}
/**
* Get absolute top position of static-positioned element
* @param object tgt_element Element
* @return int
*/
function getTopPos(tgt_element) {
var pos=0;
if (typeof(tgt_element)=='object' && tgt_element && tgt_element.offsetParent) {
pos=tgt_element.offsetTop;
while (tgt_element=tgt_element.offsetParent) {
pos+=tgt_element.offsetTop;
}
if (typeof(pos)!='number') pos=0;
}
return pos;
}
/**
* Get absolute top position of static-positioned element
* @param object tgt_element Element
* @return int
*/
function getLeftPos(tgt_element) {
var pos=0;
if (typeof(tgt_element)=='object' && tgt_element && tgt_element.offsetParent) {
pos=tgt_element.offsetLeft;
while (tgt_element=tgt_element.offsetParent) {
pos+=tgt_element.offsetLeft;
}
if (typeof(pos)!='number') pos=0;
}
return pos;
}
/**
* Resize window to fit the document
* @param int add Optional. If not empty, then this value will be added to window width
* @param boolean allow_reduce Optional. If not TRUE window height will be reduced, if needed
*/
function resizeForDocumentHeight(add, allow_reduce) {
if (typeof(add)!='number') add=0;
if (typeof(allow_reduce)!='boolean') allow_reduce=true;
var used_height=getUsedHeight(document.body);
var resize_by=0;
if (used_height>0) {
if (allow_reduce|| used_height>getWinHeight()) {
resize_by=used_height-getWinHeight()+add;
}
} else {
$('last_element_dummy').style.display='';
used_height=getTopPos($('last_element_dummy'));
$('last_element_dummy').style.display='none';
if (allow_reduce || used_height>getWinHeight()) {
resize_by=used_height-getWinHeight()+add;
}
}
try {
if (resize_by+getWinHeight()>window.opener.getWinHeight()-10) {
resize_by=window.opener.getWinHeight()-getWinHeight()-10;
}
} catch (e) {}
if (resize_by>0) {
window.resizeBy(0, resize_by);
}
} | gpl-3.0 |
norris-zhang/venus | parent/common/src/main/java/com/xinxilanr/venus/common/CodeUtil.java | 1501 | /**
*
*/
package com.xinxilanr.venus.common;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.UUID;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
/**
* @author norris
*
*/
public class CodeUtil {
private static final char[] LETTER_NUMBER = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
public static String sha256(String src) {
try {
return sha256(src, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String sha256(String src, String charsetName) throws UnsupportedEncodingException {
MessageDigest sha256Digest = DigestUtils.getSha256Digest();
byte[] digest = sha256Digest.digest(src.getBytes(charsetName));
String hexString = Hex.encodeHexString(digest);
return hexString;
}
public static String randomString(int length) {
SecureRandom random = new SecureRandom();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int nextInt = random.nextInt(LETTER_NUMBER.length);
sb.append(LETTER_NUMBER[nextInt]);
}
return sb.toString();
}
public static String randomUUID() {
return UUID.randomUUID().toString();
}
public static String generateToken() {
return randomUUID();
}
}
| gpl-3.0 |
theyosh/TerrariumPI | hardware/relay/kasa_relay.py | 3715 | import terrariumLogging
logger = terrariumLogging.logging.getLogger(__name__)
import asyncio
from . import terrariumRelay
from terrariumUtils import terrariumUtils, terrariumAsync, terrariumCache
# pip install python-kasa
from kasa import Discover, SmartStrip, SmartPlug
class terrariumRelayTPLinkKasa(terrariumRelay):
HARDWARE = 'tplinkkasa'
NAME = 'Kasa Smart'
URL = '^\d{1,3}\.\d{1,3}\.\d{1,3}(,\d{1,3})?$'
def _load_hardware(self):
# Input format should be either:
# - [IP],[POWER_SWITCH_NR]
# Use an internal caching for speeding things up.
self.__state_cache = terrariumCache()
self._async = terrariumAsync()
address = self._address
if len(address) == 1:
self._device['device'] = SmartPlug(address[0])
self._device['switch'] = 0
else:
self._device['device'] = SmartStrip(address[0])
self._device['switch'] = int(address[1])-1
return self._device['device']
def _set_hardware_value(self, state):
async def __set_hardware_state(state):
await self.device.update()
plug = self.device if len(self._address) == 1 else self.device.children[self._device['switch']]
if state != 0.0:
await plug.turn_on()
else:
await plug.turn_off()
return state
data = self.__state_cache.get_data(self._address[0])
if data is not None and terrariumUtils.is_true(data[self._device['switch']]) == (state != 0.0):
return True
toggle = asyncio.run_coroutine_threadsafe(__set_hardware_state(state), self._async.async_loop)
data = toggle.result()
return data == state
def _get_hardware_value(self):
async def __get_hardware_state():
data = []
await self.device.update()
plugs = [self.device] if len(self._address) == 1 else self.device.children
for plug in plugs:
data.append(plug.is_on)
return data
try:
data = self.__state_cache.get_data(self._address[0])
if data is None:
toggle = asyncio.run_coroutine_threadsafe(__get_hardware_state(), self._async.async_loop)
data = toggle.result()
self.__state_cache.set_data(self._address[0],data,cache_timeout=20)
return self.ON if len(data) >= self._device['switch'] and terrariumUtils.is_true(data[self._device['switch']]) else self.OFF
except RuntimeError as err:
logger.exception(err)
except Exception as ex:
logger.exception(ex)
return None
@staticmethod
def _scan_relays(callback=None):
async def __scan():
found_devices = []
devices = await Discover.discover()
for ip_address in devices:
device = devices[ip_address]
await device.update()
if device.is_strip:
for counter in range(1,len(device.children)+1):
found_devices.append(
terrariumRelay(None,
terrariumRelayTPLinkKasa.HARDWARE,
'{},{}'.format(device.host,counter),
f'Channel {device.children[counter-1].alias}',
None,
callback)
)
else:
found_devices.append(
terrariumRelay(None,
terrariumRelayTPLinkKasa.HARDWARE,
f'{device.host}',
f'Channel {device.alias}',
None,
callback)
)
return found_devices
found_devices = []
_async_loop = terrariumAsync()
data = asyncio.run_coroutine_threadsafe(__scan(), _async_loop.async_loop)
found_devices = data.result()
for device in found_devices:
yield device | gpl-3.0 |
gerddie/mia | mia/2d/transform/translate.hh | 3114 | /* -*- mia-c++ -*-
*
* This file is part of MIA - a toolbox for medical image analysis
* Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny
*
* MIA is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MIA; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef mia_2d_affinetransform_hh
#define mia_2d_affinetransform_hh
#include <iterator>
#include <mia/2d/transform.hh>
NS_MIA_BEGIN
class C2DTranslateTransformation;
class EXPORT_2D C2DTranslateTransformation : public C2DTransformation
{
public:
C2DTranslateTransformation(const C2DBounds& size, const C2DInterpolatorFactory& ipf);
C2DTranslateTransformation(const C2DBounds& size, const C2DFVector& transform, const C2DInterpolatorFactory& ipf);
void translate(float x, float y);
C2DFVector get_displacement_at(const C2DFVector& x) const;
class EXPORT_2D iterator_impl: public C2DTransformation::iterator_impl
{
public:
iterator_impl(const C2DBounds& pos, const C2DBounds& size, const C2DFVector& m_value);
private:
virtual C2DTransformation::iterator_impl *clone() const;
virtual const C2DFVector& do_get_value()const;
virtual void do_x_increment();
virtual void do_y_increment();
C2DFVector m_translate;
C2DFVector m_value;
};
C2DTransformation::const_iterator begin() const;
C2DTransformation::const_iterator end() const;
virtual const C2DBounds& get_size() const;
virtual C2DTransformation *invert() const;
virtual P2DTransformation do_upscale(const C2DBounds& size) const;
virtual void translate(const C2DFVectorfield& gradient, CDoubleVector& params) const;
virtual size_t degrees_of_freedom() const;
virtual void update(float step, const C2DFVectorfield& a);
virtual C2DFMatrix derivative_at(const C2DFVector& x) const;
virtual C2DFMatrix derivative_at(int x, int y) const;
virtual CDoubleVector get_parameters() const;
virtual void set_parameters(const CDoubleVector& params);
virtual void set_identity();
virtual float get_max_transform() const;
virtual float pertuberate(C2DFVectorfield& v) const;
virtual C2DFVector operator () (const C2DFVector& x) const;
virtual float get_jacobian(const C2DFVectorfield& v, float delta) const;
C2DFVector transform(const C2DFVector& x)const;
private:
virtual C2DTransformation *do_clone() const;
C2DFVector m_transform;
C2DBounds m_size;
};
NS_MIA_END
#endif
| gpl-3.0 |
bufutda/Monorail | api/endpoints/route/all.js | 432 | "use strict";
var Endpoint = require(__rootname + "/Endpoint");
module.exports.hand = function (request, response, url, endpoint) {
db.query("SELECT * FROM mrdb.Route;", function (err, rows, fields) {
if (err) {
db.e.emit("error", err);
return;
}
endpoint.data = rows;
Endpoint.end(response, endpoint);
return;
});
};
module.exports.desc = "Get all routes";
| gpl-3.0 |
greeduomacro/xrunuo | Server/Network/GenericPacket.cs | 1517 | //
// X-RunUO - Ultima Online Server Emulator
// Copyright (C) 2015 Pedro Pardal
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Collections.Generic;
namespace Server.Network
{
public class GenericPacket : Packet
{
private static Stack<GenericPacket> m_Stack = new Stack<GenericPacket>();
public static GenericPacket Instantiate( int id, int len )
{
GenericPacket p = null;
lock ( m_Stack )
if ( m_Stack.Count > 0 )
p = m_Stack.Pop();
if ( p == null )
p = new GenericPacket();
p.Initialize( id, len );
return p;
}
public static void Release( GenericPacket p )
{
lock ( m_Stack )
if ( !m_Stack.Contains( p ) )
m_Stack.Push( p );
}
protected override void Free()
{
base.Free();
Release( this );
}
public GenericPacket()
{
}
}
}
| gpl-3.0 |
srejbi/APDuinOS_library | src/APDLogWriter.cpp | 2379 | /* APDuinOS Library
* Copyright (C) 2012 by Gyorgy Schreiber
*
* This file is part of the APDuinOS Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the APDuinOS Library. If not, see
* <http://www.gnu.org/licenses/>.
*
* APDLogWriter.cpp
*
* Created on: Oct 15, 2012
* Author: George Schreiber
*/
#include "APDLogWriter.h"
char APDLogWriter::szlogfname[13] = "";
// start the debug log functionality
void APDLogWriter::begin() {
strcpy_P(szlogfname,PSTR("APDDEBUG.LOG"));
// todo should allocate filename iso static, and copy szFileName
APDStorage::rotate_file(szlogfname,0);
delay(200);
if (APDStorage::ready()) {
APDDebugLog::setlogwriter(&(APDLogWriter::log_writer_function));
}
}
// enables synchronous log writing
// this should be called whenever it's certain that no conflicting SD operations may occur
// when enabled, messages pushed to the debug log buffer get written 'immediately' to SD
// otherwise they are buffered up (as long as possible)
void APDLogWriter::enable_sync_writes() {
if (APDStorage::ready()) {
APDDebugLog::setlogwriter(&(APDLogWriter::log_writer_function));
APDDebugLog::enable_sync_writes();
}
}
// disable synchronous log writing
// this should be called before SD access (avoid multiple file opens at a time)
void APDLogWriter::disable_sync_writes() {
APDDebugLog::disable_sync_writes();
}
// writes (using the log writer callback) all buffered log messages
void APDLogWriter::write_debug_log() {
while (!APDDebugLog::is_empty()) {
APDDebugLog::shifttowriter(&(APDLogWriter::log_writer_function));
}
}
// writes a line to the debug log (using APDStorage::write_log_line)
void APDLogWriter::log_writer_function(const char *pszLog) {
APDStorage::write_log_line(szlogfname,pszLog);
}
| gpl-3.0 |
grim210/defimulator | defimulator/ui/cheat-editor.cpp | 11312 | #include <ui/cheat-editor.h>
CheatEditor cheatEditor;
void CheatEditor::load(string filename)
{
SNES::cheat.reset();
cheatList.reset();
for (unsigned i = 0; i < 128; i++) {
cheatList.addItem("");
cheatText[i][CheatSlot] = decimal<3, ' '>(i + 1);
cheatText[i][CheatCode] = "";
cheatText[i][CheatDesc] = "";
}
unsigned n = 0;
string data;
data.readfile(string(filename, ".cht"));
xml_element document = xml_parse(data);
nall_foreach (head, document.element) {
if (head.name == "cartridge") {
nall_foreach (node, head.element) {
if (node.name == "cheat") {
bool enabled = false;
string description;
string code;
nall_foreach (attribute, node.attribute) {
if (attribute.name == "enabled") {
enabled = (attribute.parse() == "true");
}
}
nall_foreach (element, node.element) {
if (element.name == "description") {
description = element.parse();
} else if (element.name == "code") {
code.append(string(element.parse(), "+"));
}
}
code.rtrim("+");
SNES::cheat[n].enabled = enabled;
SNES::cheat[n] = code;
cheatText[n][CheatCode] = code;
cheatText[n][CheatDesc] = description;
if (++n >= 128) {
break;
}
}
}
}
}
refresh();
synchronize();
}
void CheatEditor::save(string filename)
{
signed lastSave = -1;
for (signed i = 127; i >= 0; i--) {
if (cheatText[i][CheatCode] != "" || cheatText[i][CheatDesc] != "") {
lastSave = i;
break;
}
}
if (lastSave == -1) {
unlink(string(filename, ".cht"));
return;
}
file fp;
if (fp.open(string(filename, ".cht"), file::mode::write)) {
fp.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fp.print(string("<cartridge sha256=\"",
SNES::cartridge.sha256(), "\">\n"));
for (unsigned i = 0; i <= lastSave; i++) {
fp.print(string(" <cheat enabled=\"",
cheatList.checked(i), "\">\n"));
fp.print(string(" <description><![CDATA[",
cheatText[i][CheatDesc], "]]></description>\n"));
lstring list;
list.split("+", cheatText[i][CheatCode]);
nall_foreach (code, list) {
fp.print(string(" <code>", code, "</code>\n"));
}
fp.print(string(" </cheat>\n"));
}
fp.print("</cartridge>\n");
fp.close();
}
cheatList.reset();
cheatList.resizeColumnsToContent();
}
void CheatEditor::create(void)
{
Window::create(0, 0, 256, 256, "Cheat Editor");
application.addWindow(this, "CheatEditor", "160,160");
unsigned x = 5;
unsigned y = 5;
unsigned height = Style::ButtonHeight;
cheatList.create(*this, x, y, 500, 250, "Slot\tCode\tDescription");
y += 255;
cheatList.setHeaderVisible();
cheatList.setCheckable();
codeLabel.create(*this, x, y, 80, Style::TextBoxHeight, "Code(s):");
codeEdit.create (*this, x + 80, y, 420, Style::TextBoxHeight);
y += Style::TextBoxHeight + 5;
descLabel.create(*this, x, y, 80, Style::TextBoxHeight, "Description:");
descEdit.create (*this, x + 80, y, 420, Style::TextBoxHeight);
y+= Style::TextBoxHeight + 5;
findButton.create(*this, x, y, 100, height, "Find Codes ...");
clearAllButton.create(*this, x + 505 - 85 - 85, y, 80,
height, "Clear All");
clearButton.create(*this, x + 505 - 85, y, 80, height, "Clear");
y += height + 5;
setGeometry(0, 0, 510, y);
synchronize();
cheatList.onChange = { &CheatEditor::synchronize, this };
cheatList.onTick = { &CheatEditor::toggle, this };
codeEdit.onChange = descEdit.onChange = { &CheatEditor::bind, this };
findButton.onTick = { &CheatEditor::findCodes, this };
clearAllButton.onTick = { &CheatEditor::clearAll, this };
clearButton.onTick = { &CheatEditor::clear, this };
onClose = []() {
cheatEditor.databaseWindow.setVisible(false);
return true;
};
/* databaseWindow */
databaseWindow.create(0, 0, 256, 256);
application.addWindow(&databaseWindow, "CheatDatabase", "192,192");
x = 5, y = 5;
databaseList.create(databaseWindow, x, y, 600, 360); y += 365;
databaseList.setCheckable(true);
databaseSelectAll.create(databaseWindow, x, y, 100,
height, "Select All");
databaseUnselectAll.create(databaseWindow, x + 105, y, 100,
height, "Unselect All");
databaseOk.create(databaseWindow, 605 - 80, y, 80, height, "Ok");
y += height + 5;
databaseWindow.setGeometry(0, 0, 610, y);
databaseSelectAll.onTick = []() {
for (unsigned i = 0; i < cheatEditor.databaseCode.size(); i++) {
cheatEditor.databaseList.setChecked(i, true);
}
};
databaseUnselectAll.onTick = []() {
for (unsigned i = 0; i < cheatEditor.databaseCode.size(); i++) {
cheatEditor.databaseList.setChecked(i, false);
}
};
databaseOk.onTick = { &CheatEditor::addDatabaseCodes, this };
}
void CheatEditor::synchronize(void)
{
findButton.setEnabled(SNES::cartridge.loaded());
clearAllButton.setEnabled(SNES::cartridge.loaded());
if (auto position = cheatList.selection()) {
codeEdit.setText(cheatText[position()][1]);
descEdit.setText(cheatText[position()][2]);
codeEdit.setEnabled(true);
descEdit.setEnabled(true);
clearButton.setEnabled(true);
} else {
codeEdit.setText("");
descEdit.setText("");
codeEdit.setEnabled(false);
descEdit.setEnabled(false);
clearButton.setEnabled(false);
}
}
void CheatEditor::refresh(void)
{
SNES::cheat.synchronize();
for (unsigned i = 0; i < 128; i++) {
lstring list;
list.split("+", cheatText[i][CheatCode]);
string cheatCode = list[0];
if (list.size() > 1) {
cheatCode.append("...");
}
cheatList.setChecked(i, SNES::cheat[i].enabled);
cheatList.setItem(i, {
cheatText[i][CheatSlot], "\t", cheatCode, "\t",
cheatText[i][CheatDesc]
});
}
cheatList.resizeColumnsToContent();
}
void CheatEditor::toggle(unsigned row)
{
SNES::cheat[row].enabled = cheatList.checked(row);
refresh();
}
void CheatEditor::bind(void)
{
if (auto position = cheatList.selection()) {
cheatText[position()][CheatCode] = codeEdit.text();
cheatText[position()][CheatDesc] = descEdit.text();
SNES::cheat[position()] = cheatText[position()][CheatCode];
refresh();
}
}
void CheatEditor::findCodes(void)
{
string data;
data.readfile(string(config.path.user, "cheats.xml"));
if (data == "") {
data.readfile(string(config.path.base, "cheats.xml"));
}
if (auto position = strpos(data, SNES::cartridge.sha256())) {
auto startPosition = strpos((const char*)data + position(), ">");
auto endPosition = strpos((const char*)data + position(),
"</cartridge>");
string xmlData = {
"<cartridge>\n", substr((const char*)data + position() + 1,
startPosition(), endPosition() - startPosition() - 1),
"</cartridge>\n"
};
databaseWindow.setTitle("");
databaseList.reset();
databaseCode.reset();
xml_element document = xml_parse(xmlData);
nall_foreach (root, document.element) {
if (root.name == "cartridge") {
nall_foreach(node, root.element) {
if (node.name == "name") {
databaseWindow.setTitle(node.parse());
} else if(node.name == "cheat") {
string description, code;
nall_foreach (element, node.element) {
if (element.name == "description") {
description = element.parse();
} else if (element.name == "code") {
code.append(string(element.parse(), "+"));
}
}
code.rtrim<1>("+");
code.append("\t");
code.append(description);
databaseList.addItem(description);
databaseCode.append(code);
}
}
}
}
databaseWindow.setVisible(true);
} else {
MessageWindow::information(cheatEditor,
"Sorry, no cheat codes found for this cartridge.");
}
}
optional<unsigned> CheatEditor::findUnusedSlot()
{
for (unsigned i = 0; i < 128; i++) {
if (cheatText[i][CheatCode] == "" && cheatText[i][CheatDesc] == "") {
return { true, i };
}
}
return { false, 0 };
}
void CheatEditor::addDatabaseCodes(void)
{
for (unsigned n = 0; n < databaseCode.size(); n++) {
if (databaseList.checked(n)) {
if (auto position = findUnusedSlot()) {
lstring part;
part.split("\t", databaseCode[n]);
SNES::cheat[position()].enabled = false;
SNES::cheat[position()] = part[0];
cheatList.setChecked(position(), false);
cheatText[position()][CheatCode] = part[0];
cheatText[position()][CheatDesc] = part[1];
} else {
MessageWindow::warning(databaseWindow,
"Ran out of empty slots for cheat codes.\n"
"Not all cheat codes were added.");
break;
}
}
}
databaseWindow.setVisible(false);
refresh();
synchronize();
}
void CheatEditor::clearAll(void)
{
if (MessageWindow::question(cheatEditor,
"Permanently erase all entered cheat codes?",
MessageWindow::Buttons::YesNo) == MessageWindow::Response::Yes) {
for (unsigned i = 0; i < 128; i++) {
SNES::cheat[i].enabled = false;
SNES::cheat[i] = "";
cheatList.setChecked(i, false);
cheatText[i][CheatCode] = "";
cheatText[i][CheatDesc] = "";
}
SNES::cheat.synchronize();
refresh();
codeEdit.setText("");
descEdit.setText("");
}
}
void CheatEditor::clear(void)
{
if (auto position = cheatList.selection()) {
SNES::cheat[position()].enabled = false;
SNES::cheat[position()] = "";
cheatList.setChecked(position(), false);
cheatText[position()][CheatCode] = "";
cheatText[position()][CheatDesc] = "";
SNES::cheat.synchronize();
refresh();
codeEdit.setText("");
descEdit.setText("");
}
}
| gpl-3.0 |
Y-P-/data-processing-binding | XX3/obsolete/core/test/Print.scala | 4354 | package loader.core.test
import loader.core._
import loader.core.callbacks._
object o extends Core.Impl {
type Kind = String
type Ret = Unit
type Parser = ParserBuilder#Impl
def parsClass = classOf[Parser]
def kindClass = classOf[Kind]
def apply(pr: utils.ParamReader,userCtx:loader.core.UserContext[loader.core.test.o.Element]):Impl = throw new IllegalStateException
}
class Print extends o.Motor {
val userCtx:UserContext[Element] = null
type Element = o.Element
type Result = Unit
protected def onName(e:Element,name: String):Core.Status = { println("creating "+name); new Core.Status(name) }
protected def onBeg(e:Element): Unit = println(e.name+" = {")
protected def onVal(e:Element,v: String): o.Ret = println(" -> "+v)
protected def onEnd(e:Element): o.Ret = println("}")
protected def onChild(e:Element,child: Element, r: o.Ret): Unit = println(e.name+" receiving "+child.name)
protected def onInit():Unit = println("start")
protected def onExit():Unit = println("finished")
}
class Print1 extends Print {
override protected def onBeg(e:Element): Unit = println(e.name+" = ||{")
}
class Print2 extends Print1 {
import o._
class Elt0(parser:Parser, name:String, parent:Element, childBuilder:Bld) extends super.ElementBase(parser,name,parent,childBuilder) with Processor {
override protected def onBeg(): Unit = println(name+" = |{")
}
class ElementCbks(parser:Parser,name:String, parent:Element, childBuilder:Bld, val cbks:Cbks*) extends Elt0(parser,name,parent,childBuilder) with WithCallbacks
class ElementCbk (parser:Parser,name:String, parent:Element, childBuilder:Bld, val cb:Cbk, cbks:Cbks*) extends ElementCbks(parser,name,parent,childBuilder,cbks:_*) with WithCallback {
override def onChild(child:Element,r:Ret):Unit = super[WithCallback].onChild(child,r)
}
override val builder:Bld = new Bld {
def apply(parser:Parser, parent: Element, c: Status, childBuilder:Bld) = new Elt0(parser,c.name,parent,childBuilder)
def apply(parser:Parser, parent: Element, c: Status, childBuilder:Bld, cbks: Cbks*) = new ElementCbks(parser,c.name,parent,childBuilder,cbks:_*)
def apply(parser:Parser, parent: Element, c: Status, childBuilder:Bld, cb:Cbk, cbks: Cbks*) = new ElementCbk(parser,c.name,parent,childBuilder,cb,cbks:_*)
}
}
class Print3 extends o.Motor {
val userCtx:UserContext[o.Element] = null
import o._
type Result = Unit
protected def onName(e:Element,name: String):Core.Status = null
protected def onBeg(e:Element): Unit = ()
protected def onVal(e:Element,v: String): o.Ret = ()
protected def onEnd(e:Element): o.Ret = ()
protected def onChild(e:Element,child: Element, r: o.Ret): Unit = ()
protected def onInit():Unit = ()
protected def onExit():Unit = ()
class Elt0(val parser:Parser, val name:String, val parent:Element, val childBuilder:Bld) extends o.Element {
protected def parser_=(parser:Parser):Unit = ()
def userCtx = Print3.this.userCtx
protected def onName(name: String): Status = { println("creating "+name); new Core.Status(name) }
protected def onBeg(): Unit = println(name+" = (")
protected def onVal(v: String): Ret = println(" => "+v)
protected def onEnd(): Ret = println(")")
protected def onChild(child: Element, r: Ret): Unit = println(name+" receiving "+child.name)
}
class ElementCbks(parser:Parser, name:String, parent:Element, childBuilder:Bld, val cbks:Cbks*) extends Elt0(parser,name,parent,childBuilder) with WithCallbacks
class ElementCbk (parser:Parser, name:String, parent:Element, childBuilder:Bld, val cb:Cbk, cbks:Cbks*) extends ElementCbks(parser,name,parent,childBuilder,cbks:_*) with WithCallback
override val builder:Bld = new Bld {
def apply(parser:Parser, parent: Element, c: Status, childBuilder:Bld) = new Elt0(parser,c.name,parent,childBuilder)
def apply(parser:Parser, parent: Element, c: Status, childBuilder:Bld, cbks: Cbks*) = new ElementCbks(parser,c.name,parent,childBuilder,cbks:_*)
def apply(parser:Parser, parent: Element, c: Status, childBuilder:Bld, cb:Cbk, cbks: Cbks*) = new ElementCbk(parser,c.name,parent,childBuilder,cb,cbks:_*)
}
}
| gpl-3.0 |
iVovolk/dotplant2 | application/commands/YmlController.php | 6221 | <?php
namespace app\commands;
use app\backend\models\Yml;
use app\modules\shop\models\Category;
use app\modules\shop\models\Product;
use yii\helpers\Url;
class YmlController extends \yii\console\Controller
{
private function getByYmlParam($yml, $name, $model, $default = '')
{
$param = $yml->$name;
if ('field' === $param['type']) {
$field = $param['key'];
$result = $model->$field;
} elseif ('relation' === $param['type']) {
$rel = call_user_func([$model, $param['key']]);
$attr = $param['value'];
$rel = $rel->one();
if (!empty($rel)) {
$result = $rel->$attr;
}
}
if (!empty($result)) {
return $result;
}
return $default;
}
private function wrapByYmlParam($yml, $name, $model, $tpl)
{
$result = $this->getByYmlParam($yml, $name, $model);
if ($tpl instanceof \Closure) {
$result = call_user_func($tpl, $result);
} else {
$result = htmlspecialchars(trim(strip_tags($result)));
$result = sprintf($tpl, $result);
}
if (!empty($result)) {
return $result;
}
return '';
}
public function actionGenerate()
{
$ymlConfig = new Yml();
if (!$ymlConfig->loadConfig()) {
return false;
}
\Yii::$app->urlManager->setHostInfo($ymlConfig->shop_url);
$tpl = <<< 'TPL'
<name>%s</name>
<company>%s</company>
<url>%s</url>
<currencies>
<currency id="%s" rate="1" plus="0"/>
</currencies>
<categories>
%s
</categories>
<store>%s</store>
<pickup>%s</pickup>
<delivery>%s</delivery>
<local_delivery_cost>%s</local_delivery_cost>
<adult>%s</adult>
TPL;
$section_categories = '';
$categories = Category::find()->where(['active' => 1, 'is_deleted' => 0])->asArray();
/** @var Category $row */
foreach ($categories->each(500) as $row) {
$section_categories .= '<category id="'.$row['id'].'" '.(0 != $row['parent_id'] ? 'parentId="'.$row['parent_id'].'"' : '').'>'.htmlspecialchars(trim(strip_tags($row['name']))).'</category>' . PHP_EOL;
}
unset($row, $categories);
$section_shop = sprintf($tpl,
$ymlConfig->shop_name,
$ymlConfig->shop_company,
$ymlConfig->shop_url,
$ymlConfig->currency_id,
$section_categories,
1 == $ymlConfig->shop_store ? 'true' : 'false',
1 == $ymlConfig->shop_pickup ? 'true' : 'false',
1 == $ymlConfig->shop_delivery ? 'true' : 'false',
$ymlConfig->shop_local_delivery_cost,
1 == $ymlConfig->shop_adult ? 'true' : 'false'
);
$section_offers = '';
// $offer_type = ('simplified' === $ymlConfig->general_yml_type) ? '' : 'type="'.$ymlConfig->general_yml_type.'"';
$offer_type = ''; // временно, пока не будет окончательно дописан механизм для разных типов
$products = Product::find()->where(['active' => 1, 'is_deleted' => 0]);
/** @var Product $row */
foreach ($products->each(100) as $row) {
$price = $this->getByYmlParam($ymlConfig, 'offer_price', $row, 0);
$price = intval($price);
if ($price <= 0 || $price >= 1000000000) {
continue;
}
$offer = '<offer id="'.$row->id.'" '.$offer_type.' available="true">' . PHP_EOL;
$offer .= '<url>'.Url::to(['/shop/product/show', 'model' => $row, 'category_group_id' => 1], true).'</url>' . PHP_EOL;
$offer .= $this->wrapByYmlParam($ymlConfig, 'offer_price', $row, '<price>%s</price>'. PHP_EOL);
$offer .= '<currencyId>'.$ymlConfig->currency_id.'</currencyId>' . PHP_EOL;
$offer .= $this->wrapByYmlParam($ymlConfig, 'offer_category', $row, '<categoryId>%s</categoryId>' . PHP_EOL);
$offer .= $this->wrapByYmlParam($ymlConfig, 'offer_picture', $row,
function($value) use ($ymlConfig)
{
$value = urlencode($value);
$value = '<picture>'.rtrim($ymlConfig->shop_url, '/').$value.'</picture>' . PHP_EOL;
return $value;
}
);
$offer .= $this->wrapByYmlParam($ymlConfig, 'offer_name', $row,
function($value) use ($ymlConfig)
{
if (mb_strlen($value) > 120) {
$value = mb_substr($value, 0, 120);
$value = mb_substr($value, 0, mb_strrpos($value, ' '));
}
$value = '<name>'.htmlspecialchars(trim(strip_tags($value))).'</name>'. PHP_EOL;
return $value;
}
);
$offer .= $this->wrapByYmlParam($ymlConfig, 'offer_description', $row,
function($value) use ($ymlConfig)
{
if (mb_strlen($value) > 175) {
$value = mb_substr($value, 0, 175);
$value = mb_substr($value, 0, mb_strrpos($value, ' '));
}
$value = '<description>'.htmlspecialchars(trim(strip_tags($value))).'</description>'. PHP_EOL;
return $value;
}
);
$offer .= '</offer>';
$section_offers .= $offer . PHP_EOL;
}
unset($row, $products);
$ymlFileTpl = <<< 'TPL'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE yml_catalog SYSTEM "shops.dtd">
<yml_catalog date="%s">
<shop>
%s
<offers>
%s
</offers>
</shop>
</yml_catalog>
TPL;
file_put_contents(
\Yii::getAlias('@webroot').'/'.$ymlConfig->general_yml_filename,
sprintf($ymlFileTpl,
date('Y-m-d H:i'),
$section_shop,
$section_offers
)
);
}
}
?> | gpl-3.0 |
fbanfi90/PasswordKeeper | PasswordKeeper/AccessForm.Designer.cs | 4039 | namespace PasswordKeeper
{
partial class AccessForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AccessForm));
this.okButton = new System.Windows.Forms.Button();
this.keyTextBox = new System.Windows.Forms.TextBox();
this.showCheckBox = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// okButton
//
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.Location = new System.Drawing.Point(108, 38);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 1;
this.okButton.Text = "OK";
this.okButton.UseVisualStyleBackColor = true;
this.okButton.Click += new System.EventHandler(this.OkButtonClick);
//
// keyTextBox
//
this.keyTextBox.Location = new System.Drawing.Point(12, 12);
this.keyTextBox.Name = "keyTextBox";
this.keyTextBox.Size = new System.Drawing.Size(171, 20);
this.keyTextBox.TabIndex = 0;
this.keyTextBox.UseSystemPasswordChar = true;
//
// showCheckBox
//
this.showCheckBox.AutoSize = true;
this.showCheckBox.Location = new System.Drawing.Point(12, 42);
this.showCheckBox.Name = "showCheckBox";
this.showCheckBox.Size = new System.Drawing.Size(73, 17);
this.showCheckBox.TabIndex = 2;
this.showCheckBox.Text = "Show key";
this.showCheckBox.UseVisualStyleBackColor = true;
this.showCheckBox.CheckedChanged += new System.EventHandler(this.ShowCheckBoxCheckedChanged);
//
// AccessForm
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(195, 73);
this.Controls.Add(this.showCheckBox);
this.Controls.Add(this.keyTextBox);
this.Controls.Add(this.okButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AccessForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Password Keeper";
this.TopMost = true;
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button okButton;
public System.Windows.Forms.TextBox keyTextBox;
private System.Windows.Forms.CheckBox showCheckBox;
}
} | gpl-3.0 |
MadMarty/madsonic-server-5.1 | madsonic-main/src/main/java/org/madsonic/lastfm/cache/DatabaseCache.java | 7395 | /*
* Copyright (c) 2012, the Last.fm Java Project and Committers
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.madsonic.lastfm.cache;
import java.io.*;
import java.sql.*;
/**
* <p>Generic class for caching into a database. Its constructor takes a {@link Connection} instance, which must be opened and closed by the
* client. SQL code used in this class should work with all common databases (which support the varchar, timestamp and text
* datatypes).</p>
* For more specialized versions of this class for different databases one may extend this class and override methods as needed. In
* most cases overriding {@link #createTable()} will be sufficient.<br/>
* The following databases are supported and tested with this class:
* <ul>
* <li>MySQL 5</li>
* <li>H2 1.3</li>
* </ul>
* Not supported by this base class:
* <ul>
* <li>Apache Derby/JavaDB - a long varchar in Derby can only hold up to 32700 characters of text, which is too little for some requests</li>
* <li>HSQLDB - does not support the text datatype</li>
* </ul>
*
* @author Janni Kovacs
*/
public class DatabaseCache extends Cache {
protected static final String DEFAULT_TABLE_NAME = "LASTFM_CACHE";
protected String tableName;
protected Connection connection;
public DatabaseCache(Connection connection) throws SQLException {
this(connection, DEFAULT_TABLE_NAME);
}
/**
* Creates a new <code>DatabaseCache</code> with the supplied database {@link Connection} and the specified table name. A new table with
* <code>tableName</code> will be created in the constructor, if none exists. Note that <code>tableName</code> will <b>not</b> be
* sanitized for usage in SQL, so in the rare case you're using user input for a table name make sure to sanitize the input before
* passing it on to prevent SQL injections.
*
* @param connection The database connection
* @param tableName the name for the database table to use
* @throws SQLException When initializing/creating the table fails
* @see #createTable()
*/
public DatabaseCache(Connection connection, String tableName) throws SQLException {
this.connection = connection;
this.tableName = tableName;
// We need this, because some databases do not support CREATE TABLE IF NOT EXISTS, which is a non standard addition
ResultSet tables = this.connection.getMetaData().getTables(null, null, tableName, null);
if (!tables.next()) {
createTable();
}
}
/**
* This internal method creates a new table in the database for storing XML responses. You can override this method in a subclass if this
* generic method does not work with the database server you are using, given that the following table columns are present:
* <ul>
* <li><code>id</code> - The primary key, which is used to identify cache entries (see {@link Cache#createCacheEntryName}</li>
* <li><code>expiration_date</code> - A timestamp field for this cache entry's expiration date</li>
* <li><code>response</code> - The actual response XML</li>
* </ul>
*
* If you choose to use a different schema in your table you'll most likely have to override the other methods in this class, too.
*
* @throws SQLException When the generic SQL code in this method is not compatible with the database
*/
protected void createTable() throws SQLException {
PreparedStatement stmt = connection.prepareStatement(
"CREATE TABLE " + tableName + " (id VARCHAR(200) PRIMARY KEY, expiration_date TIMESTAMP, response TEXT)");
stmt.execute();
stmt.close();
}
public boolean contains(String cacheEntryName) {
try {
PreparedStatement stmt = connection.prepareStatement("SELECT id FROM " + tableName + " WHERE id = ?");
stmt.setString(1, cacheEntryName);
ResultSet result = stmt.executeQuery();
boolean b = result.next();
stmt.close();
return b;
} catch (SQLException e) {
return false;
}
}
public InputStream load(String cacheEntryName) {
try {
PreparedStatement stmt = connection.prepareStatement("SELECT response FROM " + tableName + " WHERE id = ?");
stmt.setString(1, cacheEntryName);
ResultSet result = stmt.executeQuery();
if (result.next()) {
String s = result.getString("response");
stmt.close();
return new ByteArrayInputStream(s.getBytes("UTF-8"));
}
stmt.close();
} catch (SQLException e) {
// ignore
} catch (UnsupportedEncodingException e) {
// won't happen
}
return null;
}
public void remove(String cacheEntryName) {
try {
PreparedStatement stmt = connection.prepareStatement("DELETE FROM " + tableName + " WHERE id = ?");
stmt.setString(1, cacheEntryName);
stmt.execute();
stmt.close();
} catch (SQLException e) {
// ignore
}
}
public void store(String cacheEntryName, InputStream inputStream, long expirationDate) {
try {
PreparedStatement stmt = connection.prepareStatement(
"INSERT INTO " + tableName + " (id, expiration_date, response) VALUES(?, ?, ?)");
stmt.setString(1, cacheEntryName);
stmt.setTimestamp(2, new Timestamp(expirationDate));
stmt.setCharacterStream(3, new InputStreamReader(inputStream, "UTF-8"), -1);
stmt.execute();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
// ignore
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// won't happen
}
}
public boolean isExpired(String cacheEntryName) {
try {
PreparedStatement stmt = connection.prepareStatement("SELECT expiration_date FROM " + tableName + " WHERE id = ?");
stmt.setString(1, cacheEntryName);
ResultSet result = stmt.executeQuery();
if (result.next()) {
Timestamp timestamp = result.getTimestamp("expiration_date");
long expirationDate = timestamp.getTime();
stmt.close();
return expirationDate < System.currentTimeMillis();
}
} catch (SQLException e) {
// ignore
}
return false;
}
public void clear() {
try {
PreparedStatement stmt = connection.prepareStatement("DELETE FROM " + tableName);
stmt.execute();
stmt.close();
} catch (SQLException e) {
// ignore
}
}
}
| gpl-3.0 |
syn2cat/syndilights | open-lighting-architecture/ola-0.8.4/olad/InternalRDMController.cpp | 10159 | /*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* InternalRDMController.cpp
* Manager internally generated RDM requests
* Copyright (C) 2010 Simon Newton
*/
#include <deque>
#include <map>
#include <string>
#include <vector>
#include "ola/StringUtils.h"
#include "olad/InternalRDMController.h"
namespace ola {
using ola::rdm::RDMCommand;
const char InternalRDMController::MISMATCHED_RDM_RESPONSE_VAR[] =
"rdm-mismatched-responses";
const char InternalRDMController::EXPIRED_RDM_REQUESTS_VAR[] =
"rdm-expired-requests";
const char InternalRDMController::BROADCAST_RDM_REQUESTS_VAR[] =
"rdm-broadcast-requests";
const char InternalRDMController::FAILED_RDM_REQUESTS_VAR[] =
"rdm-failed-requests";
/*
* Create a new OutstandingRDMRequest
*/
OutstandingRDMRequest::OutstandingRDMRequest(
const RDMRequest *request,
rdm_controller_callback *callback):
m_source_uid(request->SourceUID()),
m_sub_device(request->SubDevice()),
m_transaction_number(request->TransactionNumber()),
m_command_class(request->CommandClass()),
m_expires(),
m_callback(callback) {
Clock::CurrentTime(&m_expires);
m_expires += ola::TimeInterval(EXPIRY_TIMEOUT_S, 0);
}
/*
* Returns true if this response matches this request
*/
bool OutstandingRDMRequest::Matches(const RDMResponse *response) {
if (!response)
return false;
if (response->DestinationUID() == m_source_uid &&
response->TransactionNumber() == m_transaction_number &&
response->SubDevice() == m_sub_device) {
if (response->CommandClass() == RDMCommand::GET_COMMAND_RESPONSE &&
m_command_class == RDMCommand::GET_COMMAND)
return true;
if (response->CommandClass() == RDMCommand::SET_COMMAND_RESPONSE &&
m_command_class == RDMCommand::SET_COMMAND)
return true;
}
return false;
}
/*
* Return true if this request has expired
*/
bool OutstandingRDMRequest::HasExpired(const TimeStamp &now) {
return now > m_expires;
}
/*
* Run the callback for this request
*/
void OutstandingRDMRequest::RunCallback(const rdm_response_data &data) {
if (m_callback)
m_callback->Run(data);
m_callback = NULL;
}
InternalRDMController::InternalRDMController(const UID &default_uid,
PortManager *port_manager,
class ExportMap *export_map):
m_default_uid(default_uid),
m_port_manager(port_manager),
m_export_map(export_map) {
m_export_map->GetUIntMapVar(MISMATCHED_RDM_RESPONSE_VAR);
m_export_map->GetUIntMapVar(EXPIRED_RDM_REQUESTS_VAR);
m_export_map->GetUIntMapVar(BROADCAST_RDM_REQUESTS_VAR);
m_export_map->GetUIntMapVar(FAILED_RDM_REQUESTS_VAR);
}
/*
* Tear down this InternalRDMController
*/
InternalRDMController::~InternalRDMController() {
// delete all ports
map<unsigned int, InternalInputPort*>::iterator port_iter;
for (port_iter = m_input_ports.begin(); port_iter != m_input_ports.end();
++port_iter) {
m_port_manager->UnPatchPort(port_iter->second);
delete port_iter->second;
}
m_input_ports.clear();
// delete out OutstandingRDMRequests
map<unsigned int, deque<OutstandingRDMRequest*> >::iterator iter;
deque<OutstandingRDMRequest*>::iterator request_iter;
rdm_response_data data = {RDM_RESPONSE_TIMED_OUT, NULL};
for (iter = m_outstanding_requests.begin();
iter != m_outstanding_requests.end(); ++iter) {
for (request_iter = iter->second.begin();
request_iter != iter->second.end(); ++request_iter) {
(*request_iter)->RunCallback(data);
delete *request_iter;
}
}
m_transaction_numbers.clear();
}
/*
* Send an RDMRequest, this may run the callback immediately if the send failed
*/
bool InternalRDMController::SendRDMRequest(
Universe *universe,
const UID &destination,
uint8_t sub_device,
uint16_t param_id,
const string &data,
bool is_set,
rdm_controller_callback *callback,
const UID *source) {
map<unsigned int, InternalInputPort*>::iterator port_iter =
m_input_ports.find(universe->UniverseId());
if (port_iter == m_input_ports.end()) {
// create a new InternalInputPort for this universe
InternalInputPort *input_port = new InternalInputPort(
universe->UniverseId(),
this);
if (!m_port_manager->PatchPort(input_port, universe->UniverseId())) {
OLA_WARN << "Failed to patch internal input port to universe " <<
universe->UniverseId() << ", aborting RDM request";
delete callback;
return false;
}
port_iter = m_input_ports.insert(pair<unsigned int, InternalInputPort*>(
universe->UniverseId(),
input_port)).first;
}
UID source_uid = m_default_uid;
if (source)
source_uid = *source;
// lookup transaction number
uint8_t transaction_number = 0;
pair<unsigned int, const UID> transaction_key(universe->UniverseId(),
source_uid);
map<pair<unsigned int, const UID>, uint8_t>::iterator transaction_iter =
m_transaction_numbers.find(transaction_key);
if (transaction_iter == m_transaction_numbers.end())
m_transaction_numbers[transaction_key] = 0;
else
transaction_number = ++transaction_iter->second;
ola::rdm::RDMRequest *request = NULL;
if (is_set) {
request = new ola::rdm::RDMSetRequest(
source_uid,
destination,
transaction_number,
1, // port id
0, // message count
sub_device,
param_id,
reinterpret_cast<const uint8_t*>(data.data()),
data.size());
} else {
request = new ola::rdm::RDMGetRequest(
source_uid,
destination,
transaction_number,
1, // port id
0, // message count
sub_device,
param_id,
reinterpret_cast<const uint8_t*>(data.data()),
data.size());
}
// this has to be done before the request is deleted below
OutstandingRDMRequest *outstanding_request =
new OutstandingRDMRequest(request, callback);
// We need to push this on now, because HandleRDMResponse could be called
// immediately
deque<OutstandingRDMRequest*> &request_list =
m_outstanding_requests[universe->UniverseId()];
if (!destination.IsBroadcast())
request_list.push_back(outstanding_request);
if (port_iter->second->HandleRDMRequest(request)) {
if (destination.IsBroadcast()) {
(*m_export_map->GetUIntMapVar(BROADCAST_RDM_REQUESTS_VAR))[
IntToString(universe->UniverseId())]++;
rdm_response_data data = {RDM_RESPONSE_BROADCAST, NULL};
callback->Run(data);
delete outstanding_request;
return true;
} else {
return true;
}
}
// the request failed, remove it from the request queue
request_list.pop_back();
(*m_export_map->GetUIntMapVar(FAILED_RDM_REQUESTS_VAR))[
IntToString(universe->UniverseId())]++;
delete outstanding_request;
return false;
}
/*
* Handle RDM responses
*/
bool InternalRDMController::HandleRDMResponse(
unsigned int universe,
const ola::rdm::RDMResponse *response) {
// try to locate a match
OutstandingRDMRequest *request = NULL;
map<unsigned int, deque<OutstandingRDMRequest*> >::iterator iter =
m_outstanding_requests.find(universe);
if (iter == m_outstanding_requests.end()) {
// things have gone horibly wrong
OLA_WARN << "Got a RDMResponse but can't find universe " << universe;
delete response;
return false;
}
deque<OutstandingRDMRequest*>::iterator request_iter;
for (request_iter = iter->second.begin();
request_iter != iter->second.end(); ++request_iter) {
if ((*request_iter)->Matches(response)) {
request = *request_iter;
iter->second.erase(request_iter);
break;
}
}
if (!request) {
OLA_WARN << "Unable to locate a matching request for RDM response";
(*m_export_map->GetUIntMapVar(MISMATCHED_RDM_RESPONSE_VAR))[
IntToString(universe)]++;
delete response;
return false;
}
rdm_response_data data = {RDM_RESPONSE_OK, response};
request->RunCallback(data);
delete request;
delete response;
return true;
}
/*
* Check for any exprired requests
* @param now the current time
*/
void InternalRDMController::CheckTimeouts(const TimeStamp &now) {
vector<pair<unsigned int, OutstandingRDMRequest*> > expired_requests;
map<unsigned int, deque<OutstandingRDMRequest*> >::iterator iter;
deque<OutstandingRDMRequest*>::iterator request_iter;
vector<pair<unsigned int, OutstandingRDMRequest*> >::iterator expired_iter;
for (iter = m_outstanding_requests.begin();
iter != m_outstanding_requests.end(); ++iter) {
for (request_iter = iter->second.begin();
request_iter != iter->second.end();) {
if ((*request_iter)->HasExpired(now)) {
expired_requests.push_back(
pair<unsigned int, OutstandingRDMRequest*>(iter->first,
*request_iter));
request_iter = iter->second.erase(request_iter);
} else {
request_iter++;
}
}
}
rdm_response_data data = {RDM_RESPONSE_TIMED_OUT, NULL};
for (expired_iter = expired_requests.begin();
expired_iter != expired_requests.end(); ++expired_iter) {
(*m_export_map->GetUIntMapVar(EXPIRED_RDM_REQUESTS_VAR))[
IntToString(expired_iter->first)]++;
expired_iter->second->RunCallback(data);
delete expired_iter->second;
}
expired_requests.clear();
}
} // ola
| gpl-3.0 |
a-dilla/Valentina | src/app/tablewindow.cpp | 23150 | /************************************************************************
**
** @file tablewindow.cpp
** @author Roman Telezhynskyi <dismine(at)gmail.com>
** @date November 15, 2013
**
** @brief
** @copyright
** This source code is part of the Valentine project, a pattern making
** program, whose allow create and modeling patterns of clothing.
** Copyright (C) 2013 Valentina project
** <https://bitbucket.org/dismine/valentina> All Rights Reserved.
**
** Valentina is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Valentina 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 Valentina. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include "tablewindow.h"
#include "ui_tablewindow.h"
#include "widgets/vtablegraphicsview.h"
#include <QtSvg>
#include <QPrinter>
#include "core/vapplication.h"
#include <QtCore/qmath.h>
#ifdef Q_OS_WIN
# define PDFTOPS "pdftops.exe"
#else
# define PDFTOPS "pdftops"
#endif
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief TableWindow constructor.
* @param parent parent widget.
*/
TableWindow::TableWindow(QWidget *parent)
:QMainWindow(parent), numberDetal(nullptr), colission(nullptr), ui(new Ui::TableWindow),
listDetails(QVector<VItem*>()), outItems(false), collidingItems(false), tableScene(nullptr),
paper(nullptr), shadowPaper(nullptr), listOutItems(nullptr), listCollidingItems(QList<QGraphicsItem*>()),
indexDetail(0), sceneRect(QRectF()), fileName(QString()), description(QString())
{
ui->setupUi(this);
numberDetal = new QLabel(tr("0 details left."), this);
colission = new QLabel(tr("Collisions not found."), this);
ui->statusBar->addWidget(numberDetal);
ui->statusBar->addWidget(colission);
outItems = collidingItems = false;
sceneRect = QRectF(0, 0, qApp->toPixel(823, Unit::Mm), qApp->toPixel(1171, Unit::Mm));
tableScene = new QGraphicsScene(sceneRect);
QBrush brush;
brush.setStyle( Qt::SolidPattern );
brush.setColor( QColor( Qt::gray ) );
tableScene->setBackgroundBrush( brush );
ui->view->setScene(tableScene);
ui->view->fitInView(ui->view->scene()->sceneRect(), Qt::KeepAspectRatio);
ui->horizontalLayout->addWidget(ui->view);
connect(tableScene, &QGraphicsScene::selectionChanged, ui->view, &VTableGraphicsView::selectionChanged);
connect(ui->actionTurn, &QAction::triggered, ui->view, &VTableGraphicsView::rotateItems);
connect(ui->actionMirror, &QAction::triggered, ui->view, &VTableGraphicsView::MirrorItem);
connect(ui->actionZoomIn, &QAction::triggered, ui->view, &VTableGraphicsView::ZoomIn);
connect(ui->actionZoomOut, &QAction::triggered, ui->view, &VTableGraphicsView::ZoomOut);
connect(ui->actionStop, &QAction::triggered, this, &TableWindow::StopTable);
connect(ui->actionSave, &QAction::triggered, this, &TableWindow::saveScene);
connect(ui->actionNext, &QAction::triggered, this, &TableWindow::GetNextDetail);
connect(ui->actionAdd, &QAction::triggered, this, &TableWindow::AddLength);
connect(ui->actionRemove, &QAction::triggered, this, &TableWindow::RemoveLength);
connect(ui->view, &VTableGraphicsView::itemChect, this, &TableWindow::itemChect);
}
//---------------------------------------------------------------------------------------------------------------------
TableWindow::~TableWindow()
{
delete tableScene;
delete ui;
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief AddPaper add to the scene paper and shadow.
*/
void TableWindow::AddPaper()
{
qreal x1, y1, x2, y2;
sceneRect.getCoords(&x1, &y1, &x2, &y2);
shadowPaper = new QGraphicsRectItem(QRectF(x1+4, y1+4, x2+4, y2+4));
shadowPaper->setBrush(QBrush(Qt::black));
tableScene->addItem(shadowPaper);
paper = new QGraphicsRectItem(QRectF(x1, y1, x2, y2));
paper->setPen(QPen(Qt::black, qApp->toPixel(qApp->widthMainLine())));
paper->setBrush(QBrush(Qt::white));
tableScene->addItem(paper);
qDebug()<<paper->rect().size().toSize();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief AddDetail show on scene next detail.
*/
void TableWindow::AddDetail()
{
if (indexDetail<listDetails.count())
{
tableScene->clearSelection();
VItem* Detail = listDetails[indexDetail];
SCASSERT(Detail != nullptr);
connect(Detail, &VItem::itemOut, this, &TableWindow::itemOut);
connect(Detail, &VItem::itemColliding, this, &TableWindow::itemColliding);
connect(this, &TableWindow::LengthChanged, Detail, &VItem::LengthChanged);
Detail->setPen(QPen(Qt::black, 1));
Detail->setBrush(QBrush(Qt::white));
Detail->setPos(paper->boundingRect().center());
Detail->setFlag(QGraphicsItem::ItemIsMovable, true);
Detail->setFlag(QGraphicsItem::ItemIsSelectable, true);
Detail->setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
Detail->setPaper(paper);
tableScene->addItem(Detail);
Detail->setSelected(true);
indexDetail++;
if (indexDetail==listDetails.count())
{
ui->actionSave->setEnabled(true);
}
}
numberDetal->setText(QString(tr("%1 details left.")).arg(listDetails.count()-indexDetail));
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief ModelChosen show window when user want create new layout.
* @param listDetails list of details.
* @param description pattern description.
*/
/*
* Get details for creation layout.
*/
void TableWindow::ModelChosen(QVector<VItem*> listDetails, const QString &fileName, const QString &description)
{
this->description = description;
QString file;
if (fileName.isEmpty())
{
file = tr("untitled");
}
else
{
file = fileName;
}
QFileInfo fi( file );
this->fileName = fi.baseName();
this->listDetails = listDetails;
listOutItems = new QBitArray(this->listDetails.count());
AddPaper();
indexDetail = 0;
AddDetail();
show();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief closeEvent handle after close window.
* @param event close event.
*/
void TableWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
StopTable();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief moveToCenter move screen to the center of window.
*/
void TableWindow::moveToCenter()
{
QRect rect = frameGeometry();
rect.moveCenter(QDesktopWidget().availableGeometry().center());
move(rect.topLeft());
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief showEvent handle after show window.
* @param event show event.
*/
void TableWindow::showEvent ( QShowEvent * event )
{
QMainWindow::showEvent(event);
moveToCenter();
ui->view->fitInView(ui->view->scene()->sceneRect(), Qt::KeepAspectRatio);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief StopTable stop creation layout.
*/
void TableWindow::StopTable()
{
hide();
tableScene->clear();
delete listOutItems;
listDetails.clear();
sceneRect = QRectF(0, 0, qApp->toPixel(823, Unit::Mm), qApp->toPixel(1171, Unit::Mm));
tableScene->setSceneRect(sceneRect);
emit closed();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief saveScene save created layout.
*/
void TableWindow::saveScene()
{
QMap<QString, QString> extByMessage;
extByMessage[ tr("Svg files (*.svg)") ] = ".svg";
extByMessage[ tr("PDF files (*.pdf)") ] = ".pdf";
extByMessage[ tr("Images (*.png)") ] = ".png";
QProcess proc;
proc.start(PDFTOPS);
if (proc.waitForFinished(15000))
{
extByMessage[ tr("PS files (*.ps)") ] = ".ps";
extByMessage[ tr("EPS files (*.eps)") ] = ".eps";
}
else
{
qWarning()<<PDFTOPS<<"error"<<proc.error()<<proc.errorString();
}
QString saveMessage;
QMapIterator<QString, QString> i(extByMessage);
while (i.hasNext())
{
i.next();
saveMessage += i.key();
if (i.hasNext())
{
saveMessage += ";;";
}
}
QString sf;
// the save function
QString dir = QDir::homePath()+"/"+fileName;
QString name = QFileDialog::getSaveFileName(this, tr("Save layout"), dir, saveMessage, &sf);
if (name.isEmpty())
{
return;
}
// what if the user did not specify a suffix...?
QString suf = extByMessage.value(sf);
suf.replace(".", "");
QFileInfo f( name );
if (f.suffix().isEmpty() || f.suffix() != suf)
{
name += extByMessage.value(sf);
}
QBrush *brush = new QBrush();
brush->setColor( QColor( Qt::white ) );
tableScene->setBackgroundBrush( *brush );
tableScene->clearSelection(); // Selections would also render to the file, so need delete them
shadowPaper->setVisible(false);
paper->setPen(QPen(Qt::white, 0.1, Qt::NoPen));
QFileInfo fi( name );
QStringList suffix = QStringList() << "svg" << "png" << "pdf" << "eps" << "ps";
switch (suffix.indexOf(fi.suffix()))
{
case 0: //svg
paper->setVisible(false);
SvgFile(name);
paper->setVisible(true);
break;
case 1: //png
PngFile(name);
break;
case 2: //pdf
PdfFile(name);
break;
case 3: //eps
EpsFile(name);
break;
case 4: //ps
PsFile(name);
break;
default:
qDebug() << "Can't recognize file suffix. File file "<<name<<Q_FUNC_INFO;
break;
}
paper->setPen(QPen(Qt::black, qApp->toPixel(qApp->widthMainLine())));
brush->setColor( QColor( Qt::gray ) );
brush->setStyle( Qt::SolidPattern );
tableScene->setBackgroundBrush( *brush );
shadowPaper->setVisible(true);
delete brush;
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief itemChect turn off rotation button if don't selected detail.
* @param flag true - enable button.
*/
void TableWindow::itemChect(bool flag)
{
ui->actionTurn->setDisabled(flag);
ui->actionMirror->setDisabled(flag);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief checkNext disable next detail button if exist colission or out details.
*/
void TableWindow::checkNext()
{
if (outItems == true && collidingItems == true)
{
colission->setText(tr("Collisions not found."));
if (indexDetail==listDetails.count())
{
ui->actionSave->setEnabled(true);
ui->actionNext->setDisabled(true);
}
else
{
ui->actionNext->setDisabled(false);
ui->actionSave->setEnabled(false);
}
}
else
{
colission->setText(tr("Collisions found."));
ui->actionNext->setDisabled(true);
ui->actionSave->setEnabled(false);
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief itemOut handled if detail moved out paper sheet.
* @param number Number detail in list.
* @param flag set state of detail. True if detail moved out paper sheet.
*/
void TableWindow::itemOut(int number, bool flag)
{
listOutItems->setBit(number, flag);
for ( int i = 0; i < listOutItems->count(); ++i )
{
if (listOutItems->at(i)==true)
{
outItems=false;
qDebug()<<"itemOut::outItems="<<outItems<<"&& collidingItems"<<collidingItems;
checkNext();
return;
}
}
outItems=true;
checkNext();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief itemColliding handled if we have colission details.
* @param list list of colission details.
* @param number 0 - include to list of colission dcetails, 1 - exclude from list.
*/
void TableWindow::itemColliding(QList<QGraphicsItem *> list, int number)
{
//qDebug()<<"number="<<number;
if (number==0)
{
if (listCollidingItems.isEmpty()==false)
{
if (listCollidingItems.contains(list.at(0))==true)
{
listCollidingItems.removeAt(listCollidingItems.indexOf(list.at(0)));
if (listCollidingItems.size()>1)
{
for ( int i = 0; i < listCollidingItems.count(); ++i )
{
QList<QGraphicsItem *> lis = listCollidingItems.at(i)->collidingItems();
if (lis.size()-2 <= 0)
{
VItem * bitem = qgraphicsitem_cast<VItem *> ( listCollidingItems.at(i) );
SCASSERT(bitem != nullptr);
bitem->setPen(QPen(Qt::black, qApp->toPixel(qApp->widthMainLine())));
listCollidingItems.removeAt(i);
}
}
}
else if (listCollidingItems.size()==1)
{
VItem * bitem = qgraphicsitem_cast<VItem *> ( listCollidingItems.at(0) );
SCASSERT(bitem != nullptr);
bitem->setPen(QPen(Qt::black, qApp->toPixel(qApp->widthMainLine())));
listCollidingItems.clear();
collidingItems = true;
}
}
else
{
collidingItems = true;
}
}
else
{
collidingItems = true;
}
}
else if (number==1)
{
if (list.contains(paper)==true)
{
list.removeAt(list.indexOf(paper));
}
if (list.contains(shadowPaper)==true)
{
list.removeAt(list.indexOf(shadowPaper));
}
for ( int i = 0; i < list.count(); ++i )
{
if (listCollidingItems.contains(list.at(i))==false)
{
listCollidingItems.append(list.at(i));
}
}
collidingItems = false;
}
qDebug()<<"itemColliding::outItems="<<outItems<<"&& collidingItems"<<collidingItems;
checkNext();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief GetNextDetail put next detail on table.
*/
void TableWindow::GetNextDetail()
{
AddDetail();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief AddLength Add length paper sheet.Збільшує довжину листа на певне значення за один раз.
*/
void TableWindow::AddLength()
{
QRectF rect = tableScene->sceneRect();
rect.setHeight(rect.height()+qApp->toPixel(279, Unit::Mm));
tableScene->setSceneRect(rect);
rect = shadowPaper->rect();
rect.setHeight(rect.height()+qApp->toPixel(279, Unit::Mm));
shadowPaper->setRect(rect);
rect = paper->rect();
rect.setHeight(rect.height()+qApp->toPixel(279, Unit::Mm));
paper->setRect(rect);
ui->actionRemove->setEnabled(true);
emit LengthChanged();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief RemoveLength reduce the length of paper sheet. You can reduce to the minimal value only.
*/
void TableWindow::RemoveLength()
{
if (sceneRect.height() <= tableScene->sceneRect().height() - 100)
{
QRectF rect = tableScene->sceneRect();
rect.setHeight(rect.height()-qApp->toPixel(279, Unit::Mm));
tableScene->setSceneRect(rect);
rect = shadowPaper->rect();
rect.setHeight(rect.height()-qApp->toPixel(279, Unit::Mm));
shadowPaper->setRect(rect);
rect = paper->rect();
rect.setHeight(rect.height()-qApp->toPixel(279, Unit::Mm));
paper->setRect(rect);
if (fabs(sceneRect.height() - tableScene->sceneRect().height()) < 0.01)
{
ui->actionRemove->setDisabled(true);
}
emit LengthChanged();
}
else
{
ui->actionRemove->setDisabled(true);
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief keyPressEvent handle key press events.
* @param event key event.
*/
void TableWindow::keyPressEvent ( QKeyEvent * event )
{
if ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )
{
if (ui->actionNext->isEnabled() == true )
{
AddDetail();
qDebug()<<"Added detail.";
}
}
QMainWindow::keyPressEvent ( event );
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief SvgFile save layout to svg file.
* @param name name layout file.
*/
void TableWindow::SvgFile(const QString &name) const
{
QSvgGenerator generator;
generator.setFileName(name);
generator.setSize(paper->rect().size().toSize());
generator.setViewBox(paper->rect());
generator.setTitle("Valentina pattern");
generator.setDescription(description);
generator.setResolution(static_cast<int>(qApp->PrintDPI));
QPainter painter;
painter.begin(&generator);
painter.setFont( QFont( "Arial", 8, QFont::Normal ) );
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, qApp->toPixel(qApp->widthHairLine()), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter.setBrush ( QBrush ( Qt::NoBrush ) );
tableScene->render(&painter);
painter.end();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief PngFile save layout to png file.
* @param name name layout file.
*/
void TableWindow::PngFile(const QString &name) const
{
QRectF r = paper->rect();
qreal x=0, y=0, w=0, h=0;
r.getRect(&x, &y, &w, &h);// Re-shrink the scene to it's bounding contents
// Create the image with the exact size of the shrunk scene
QImage image(QSize(static_cast<qint32>(w), static_cast<qint32>(h)), QImage::Format_ARGB32);
image.fill(Qt::transparent); // Start all pixels transparent
QPainter painter(&image);
painter.setFont( QFont( "Arial", 8, QFont::Normal ) );
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, qApp->toPixel(qApp->widthMainLine()), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter.setBrush ( QBrush ( Qt::NoBrush ) );
tableScene->render(&painter);
image.save(name);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief PdfFile save layout to pdf file.
* @param name name layout file.
*/
void TableWindow::PdfFile(const QString &name) const
{
QPrinter printer;
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(name);
QRectF r = paper->rect();
qreal x=0, y=0, w=0, h=0;
r.getRect(&x, &y, &w, &h);// Re-shrink the scene to it's bounding contents
printer.setResolution(static_cast<int>(qApp->PrintDPI));
printer.setPaperSize ( QSizeF(qApp->fromPixel(w, Unit::Mm), qApp->fromPixel(h, Unit::Mm)), QPrinter::Millimeter );
QPainter painter;
if (painter.begin( &printer ) == false)
{ // failed to open file
qCritical("Can't open printer %s", qPrintable(name));
return;
}
painter.setFont( QFont( "Arial", 8, QFont::Normal ) );
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, qApp->toPixel(qApp->widthMainLine()), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter.setBrush ( QBrush ( Qt::NoBrush ) );
tableScene->render(&painter);
painter.end();
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief EpsFile save layout to eps file.
* @param name name layout file.
*/
void TableWindow::EpsFile(const QString &name) const
{
QTemporaryFile tmp;
if (tmp.open())
{
PdfFile(tmp.fileName());
QStringList params = QStringList() << "-eps" << tmp.fileName() << name;
PdfToPs(params);
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief PsFile save layout to ps file.
* @param name name layout file.
*/
void TableWindow::PsFile(const QString &name) const
{
QTemporaryFile tmp;
if (tmp.open())
{
PdfFile(tmp.fileName());
QStringList params = QStringList() << tmp.fileName() << name;
PdfToPs(params);
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief PdfToPs use external tool "pdftops" for converting pdf too eps or ps format.
* @param params string with parameter for tool. Parameters have format: "-eps input_file out_file". Use -eps when
* need create eps file.
*/
void TableWindow::PdfToPs(const QStringList ¶ms) const
{
#ifndef QT_NO_CURSOR
QApplication::setOverrideCursor(Qt::WaitCursor);
#endif
QProcess proc;
proc.start(PDFTOPS, params);
proc.waitForFinished(15000);
#ifndef QT_NO_CURSOR
QApplication::restoreOverrideCursor();
#endif
QFile f(params.last());
if (f.exists() == false)
{
QString msg = QString(tr("Creating file '%1' failed! %2")).arg(params.last()).arg(proc.errorString());
QMessageBox msgBox(QMessageBox::Critical, tr("Critical error!"), msg, QMessageBox::Ok | QMessageBox::Default);
msgBox.exec();
}
}
| gpl-3.0 |
MeteorAdminz/dnSpy | dnSpy/dnSpy/Documents/Tabs/EntryPointCommands.cs | 5654 | /*
Copyright (C) 2014-2016 de4dot@gmail.com
This file is part of dnSpy
dnSpy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.ComponentModel.Composition;
using System.Linq;
using dnlib.DotNet;
using dnSpy.Contracts.Documents.Tabs;
using dnSpy.Contracts.Documents.TreeView;
using dnSpy.Contracts.Images;
using dnSpy.Contracts.Menus;
using dnSpy.Contracts.TreeView;
namespace dnSpy.Documents.Tabs {
static class GoToEntryPointCommand {
internal static ModuleDef GetCurrentModule(IDocumentTabService documentTabService) {
var tab = documentTabService.ActiveTab;
if (tab == null)
return null;
return tab.Content.Nodes.FirstOrDefault().GetModule();
}
[ExportMenuItem(Header = "res:GoToEntryPointCommand", Icon = DsImagesAttribute.EntryPoint, Group = MenuConstants.GROUP_CTX_DOCVIEWER_TOKENS, Order = 0)]
sealed class CodeCommand : MenuItemBase {
readonly IDocumentTabService documentTabService;
[ImportingConstructor]
CodeCommand(IDocumentTabService documentTabService) {
this.documentTabService = documentTabService;
}
public override bool IsVisible(IMenuItemContext context) => GetEntryPoint(documentTabService, context) != null;
static MethodDef GetEntryPoint(IDocumentTabService documentTabService, IMenuItemContext context) {
if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID))
return null;
var module = GetCurrentModule(documentTabService);
return module == null ? null : module.EntryPoint as MethodDef;
}
public override void Execute(IMenuItemContext context) {
var ep = GetEntryPoint(documentTabService, context);
if (ep != null)
documentTabService.FollowReference(ep);
}
}
[ExportMenuItem(Header = "res:GoToEntryPointCommand", Icon = DsImagesAttribute.EntryPoint, Group = MenuConstants.GROUP_CTX_DOCUMENTS_TOKENS, Order = 0)]
sealed class DocumentsCommand : MenuItemBase {
readonly IDocumentTabService documentTabService;
[ImportingConstructor]
DocumentsCommand(IDocumentTabService documentTabService) {
this.documentTabService = documentTabService;
}
public override bool IsVisible(IMenuItemContext context) => GetEntryPoint(context) != null;
static MethodDef GetEntryPoint(IMenuItemContext context) {
if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID))
return null;
var nodes = context.Find<TreeNodeData[]>();
var node = nodes == null || nodes.Length == 0 ? null : nodes[0];
var module = node.GetModule();
return module == null ? null : module.EntryPoint as MethodDef;
}
public override void Execute(IMenuItemContext context) {
var ep = GetEntryPoint(context);
if (ep != null)
documentTabService.FollowReference(ep);
}
}
}
static class GoToGlobalTypeCctorCommand {
[ExportMenuItem(Header = "res:GoToGlobalCctorCommand", Group = MenuConstants.GROUP_CTX_DOCVIEWER_TOKENS, Order = 10)]
sealed class CodeCommand : MenuItemBase {
readonly IDocumentTabService documentTabService;
[ImportingConstructor]
CodeCommand(IDocumentTabService documentTabService) {
this.documentTabService = documentTabService;
}
public override bool IsVisible(IMenuItemContext context) => GetModuleCctor(documentTabService, context) != null;
static MethodDef GetModuleCctor(IDocumentTabService documentTabService, IMenuItemContext context) {
if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID))
return null;
var module = GoToEntryPointCommand.GetCurrentModule(documentTabService);
if (module == null)
return null;
var gt = module.GlobalType;
return gt == null ? null : gt.FindStaticConstructor();
}
public override void Execute(IMenuItemContext context) {
var ep = GetModuleCctor(documentTabService, context);
if (ep != null)
documentTabService.FollowReference(ep);
}
}
[ExportMenuItem(Header = "res:GoToGlobalCctorCommand", Group = MenuConstants.GROUP_CTX_DOCUMENTS_TOKENS, Order = 10)]
sealed class DocumentsCommand : MenuItemBase {
readonly IDocumentTabService documentTabService;
[ImportingConstructor]
DocumentsCommand(IDocumentTabService documentTabService) {
this.documentTabService = documentTabService;
}
public override bool IsVisible(IMenuItemContext context) => GetModuleCctor(context) != null;
static MethodDef GetModuleCctor(IMenuItemContext context) {
if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID))
return null;
var nodes = context.Find<TreeNodeData[]>();
var node = nodes == null || nodes.Length == 0 ? null : nodes[0];
var module = node.GetModule();
if (module == null)
return null;
var gt = module.GlobalType;
return gt == null ? null : gt.FindStaticConstructor();
}
public override void Execute(IMenuItemContext context) {
var ep = GetModuleCctor(context);
if (ep != null)
documentTabService.FollowReference(ep);
}
}
}
}
| gpl-3.0 |
snmgian/yew | lib/yew.rb | 2100 | require 'yaml'
module Yew
# Creates an object tree based on a given list of yml files.
#
# @param [*String] Yaml source files
#
# @return [Yew::Tree]
def self.load(*yml_files)
env_hash = yml_files.inject({}) do |memo, yml|
memo.merge!(YAML.load(File.read(yml)))
end
Tree.new(env_hash)
end
# The object tree. Allows root-to-leave navigation in the form of ordinary method calls.
class Tree < BasicObject
# @param [Hash] env
# @param root Tree's root. Used for notifying a not found entry at an exact path point.
def initialize(env, root = nil)
@env = env
@root = root
end
# Fetches a branch or leaf.
#
# If no key is received, returns the underlying Hash.
#
# @param key Node's name.
#
# @return [Yew::Tree] When the request node is still a tree.
# @return [Hash] Underlying Hash.
# @return [Object] When the requested node is a leaf.
def [](*key)
if key.any?
key = key.first
Utils.fetch(key, @env, @root)
else
@env
end
end
def method_missing(m, *attrs, &block)
Utils.fetch(m, @env, @root)
end
def inspect
if $YEW_DEBUG
"<Yew::Env:#{__id__} -> #@env>"
else
super
end
end
def to_s
if $YEW_DEBUG
"Env -> #@env"
else
super
end
end
end
module Utils
# Fetches the key's value.
#
# Returns a tree if the value is a hash. Otherwise it returns the raw value.
#
# @return [Yew::Tree]
# @return [Object]
def self.fetch(key, env, root)
value = raw_fetch(key, env, root)
if value.is_a?(Hash)
path = key
path = "#{root}.#{path}" if root
Tree.new(value, path)
else
value
end
end
# Fetches a value from the env.
#
# @raise [RuntimeError] When key not found.
def self.raw_fetch(key, env, root)
env.fetch(key) do
env.fetch(key.to_s) do
raise "Attribute #{key} not found at /#{root}"
end
end
end
end
end
| gpl-3.0 |
jeromeetienne/neoip | src/neoip_nunit/suite/neoip_nunit_suite.hpp | 2337 | /*! \file
\brief Header of the nunit_testclass_t
*/
#ifndef __NEOIP_NUNIT_SUITE_HPP__
#define __NEOIP_NUNIT_SUITE_HPP__
/* system include */
#include <string>
#include <vector>
/* local include */
#include "neoip_nunit_tester_api.hpp"
#include "neoip_nunit_event_cb.hpp"
#include "neoip_nunit_path.hpp"
#include "neoip_zerotimer.hpp"
#include "neoip_log.hpp"
#include "neoip_copy_ctor_checker.hpp"
#include "neoip_namespace.hpp"
NEOIP_NAMESPACE_BEGIN;
/** \brief class to store and run nunit_test_api_t implementation
*/
class nunit_suite_t : public nunit_tester_api_t, private nunit_event_cb_t, private zerotimer_cb_t
, NEOIP_COPY_CTOR_DENY {
private:
nunit_path_t local_testname; //!< the name of this suite
std::vector<nunit_tester_api_t *> subtest_db; //!< all the nunit_tester_api_t of this nunit_tester_api_t
bool neoip_nunit_event_cb(void *userptr, const nunit_path_t &subtest_path
, const nunit_event_t &nunit_event) throw();
/*************** zerotimer stuff to avoid notifying in nunit_tester_begin() *******/
zerotimer_t zerotimer;
bool neoip_zerotimer_expire_cb(zerotimer_t &cb_zerotimer, void *userptr) throw();
/**************** variable used ONLY during testing ***************/
nunit_event_cb_t * callback; //!< the event_cb to which report the nunit_event_t
void * userptr; //!< the userptr associated with the above callback
nunit_path_t path_pattern; //!< the pattern of the name to run
size_t cur_test_idx; //!< the current test idx
bool test_inprogress; //!< true if a test is currently in progress, false otherwise
public:
/**************** ctor/dtor ***************************************/
nunit_suite_t(const nunit_path_t &local_testname) throw();
~nunit_suite_t() throw();
void append(nunit_tester_api_t *tester_api) throw();
/**************** nunit_tester_api_t implementation ***************/
void nunit_tester_begin(const nunit_path_t &path_pattern
, nunit_event_cb_t *callback, void *userptr) throw();
void nunit_tester_end() throw();
void nunit_tester_get_allname(const nunit_path_t &path_prefix, const nunit_path_t &path_pattern
, std::list<nunit_path_t> &testname_db) const throw();
const nunit_path_t &nunit_tester_get_testname() const throw();
};
NEOIP_NAMESPACE_END
#endif /* __NEOIP_NUNIT_SUITE_HPP__ */
| gpl-3.0 |
oliveiraped/Reportula | vendor/orchestra/support/src/Orchestra/Support/Ftp/ServerException.php | 99 | <?php namespace Orchestra\Support\Ftp;
class ServerException extends \RuntimeException
{
//
}
| gpl-3.0 |
tung/tea | doc/example/smile_move_2.rb | 1684 | # Move the Smiley with the arrow keys, and press Esc to exit. Identical to
# smile_move.rb, but uses Tea::Event::Dispatch in a controlling class to handle
# events.
require 'tea'
class Smile
def initialize
@bitmap = Tea::Bitmap.new('smile.png')
@x = (Tea::Screen.w - @bitmap.w) / 2
@y = (Tea::Screen.h - @bitmap.h) / 2
@dx = @dy = 0
end
def n(move) @dy += move ? -1 : 1 end
def s(move) @dy += move ? 1 : -1 end
def e(move) @dx += move ? 1 : -1 end
def w(move) @dx += move ? -1 : 1 end
def stopped?; @dx == 0 && @dy == 0; end
def update
@x += @dx
@y += @dy
end
def draw
Tea::Screen.blit @bitmap, @x, @y
end
end
class SmileControllingState
def initialize
@player = Smile.new
@done = false
end
def done?; @done; end
def update; @player.update; end
def need_update?; !@player.stopped?; end
def draw
Tea::Screen.clear
@player.draw
end
include Tea::Event::Dispatch
def kbd_down(e)
case e.key
when Tea::Kbd::UP then @player.n true
when Tea::Kbd::DOWN then @player.s true
when Tea::Kbd::LEFT then @player.w true
when Tea::Kbd::RIGHT then @player.e true
when Tea::Kbd::ESCAPE then @done = true
end
end
def kbd_up(e)
case e.key
when Tea::Kbd::UP then @player.n false
when Tea::Kbd::DOWN then @player.s false
when Tea::Kbd::LEFT then @player.w false
when Tea::Kbd::RIGHT then @player.e false
end
end
end
Tea.init
Tea::Screen.set_mode 640, 480
state = SmileControllingState.new
until state.done?
state.update
state.draw
Tea::Screen.update
if e = Tea::Event.get(!state.need_update?)
state.dispatch_event e
end
end
| gpl-3.0 |
HiSPARC/publicdb | examples/datastore-xmlrpc-server.py | 1743 | #!/usr/bin/python
""" Simple XML-RPC Server to run on the datastore server.
This daemon should be run on HiSPARC's datastore server. It will
handle the cluster layouts and station passwords. When an update is
necessary, it will reload the HTTP daemon.
The basis for this code was ripped from the python SimpleXMLRPCServer
library documentation and extended.
"""
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import urllib2
import hashlib
import subprocess
HASH = '/tmp/hash_datastore'
DATASTORE_CFG = '/tmp/station_list.csv'
CFG_URL = 'http://data.hisparc.nl/config/datastore'
def reload_datastore():
"""Load datastore config and reload datastore, if necessary"""
datastore_cfg = urllib2.urlopen(CFG_URL).read()
new_hash = hashlib.sha1(datastore_cfg).hexdigest()
try:
with open(HASH, 'r') as file:
old_hash = file.readline()
except IOError:
old_hash = None
if new_hash == old_hash:
return True
else:
with open(DATASTORE_CFG, 'w') as file:
file.write(datastore_cfg)
subprocess.check_call(['/sbin/service', 'httpd', 'reload'])
with open(HASH, 'w') as file:
file.write(new_hash)
return True
if __name__ == '__main__':
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("localhost", 8001),
requestHandler=RequestHandler)
server.register_introspection_functions()
server.register_function(reload_datastore)
# Run the server's main loop
server.serve_forever()
| gpl-3.0 |
anooprh/GNU-Octave | libinterp/corefcn/graphics.cc | 282640 | /*
Copyright (C) 2007-2013 John W. Eaton
This file is part of Octave.
Octave is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
Octave 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 Octave; see the file COPYING. If not, see
<http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cctype>
#include <cfloat>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <list>
#include <map>
#include <set>
#include <string>
#include <sstream>
#include "cmd-edit.h"
#include "file-ops.h"
#include "file-stat.h"
#include "oct-locbuf.h"
#include "singleton-cleanup.h"
#include "builtins.h"
#include "cutils.h"
#include "defun.h"
#include "display.h"
#include "error.h"
#include "graphics.h"
#include "input.h"
#include "ov.h"
#include "oct-obj.h"
#include "oct-map.h"
#include "ov-fcn-handle.h"
#include "pager.h"
#include "parse.h"
#include "toplev.h"
#include "txt-eng-ft.h"
#include "unwind-prot.h"
// forward declarations
static octave_value xget (const graphics_handle& h, const caseless_str& name);
static void
gripe_set_invalid (const std::string& pname)
{
error ("set: invalid value for %s property", pname.c_str ());
}
// Check to see that PNAME matches just one of PNAMES uniquely.
// Return the full name of the match, or an empty caseless_str object
// if there is no match, or the match is ambiguous.
static caseless_str
validate_property_name (const std::string& who, const std::string& what,
const std::set<std::string>& pnames,
const caseless_str& pname)
{
size_t len = pname.length ();
std::set<std::string> matches;
for (std::set<std::string>::const_iterator p = pnames.begin ();
p != pnames.end (); p++)
{
if (pname.compare (*p, len))
{
if (len == p->length ())
{
// Exact match.
return pname;
}
matches.insert (*p);
}
}
size_t num_matches = matches.size ();
if (num_matches == 0)
{
error ("%s: unknown %s property %s",
who.c_str (), what.c_str (), pname.c_str ());
}
else if (num_matches > 1)
{
string_vector sv (matches);
std::ostringstream os;
sv.list_in_columns (os);
std::string match_list = os.str ();
error ("%s: ambiguous %s property name %s; possible matches:\n\n%s",
who.c_str (), what.c_str (), pname.c_str (), match_list.c_str ());
}
else if (num_matches == 1)
{
// Exact match was handled above.
std::string possible_match = *(matches.begin ());
warning_with_id ("Octave:abbreviated-property-match",
"%s: allowing %s to match %s property %s",
who.c_str (), pname.c_str (), what.c_str (),
possible_match.c_str ());
return possible_match;
}
return caseless_str ();
}
static Matrix
jet_colormap (void)
{
Matrix cmap (64, 3, 0.0);
// Produce X in the same manner as linspace so that
// jet_colormap and jet.m produce *exactly* the same result.
double delta = 1.0 / 63.0;
for (octave_idx_type i = 0; i < 64; i++)
{
// This is the jet colormap. It would be nice to be able
// to feval the jet function but since there is a static
// property object that includes a colormap_property
// object, we need to initialize this before main is even
// called, so calling an interpreted function is not
// possible.
double x = i*delta;
if (x >= 3.0/8.0 && x < 5.0/8.0)
cmap(i,0) = 4.0 * x - 3.0/2.0;
else if (x >= 5.0/8.0 && x < 7.0/8.0)
cmap(i,0) = 1.0;
else if (x >= 7.0/8.0)
cmap(i,0) = -4.0 * x + 9.0/2.0;
if (x >= 1.0/8.0 && x < 3.0/8.0)
cmap(i,1) = 4.0 * x - 1.0/2.0;
else if (x >= 3.0/8.0 && x < 5.0/8.0)
cmap(i,1) = 1.0;
else if (x >= 5.0/8.0 && x < 7.0/8.0)
cmap(i,1) = -4.0 * x + 7.0/2.0;
if (x < 1.0/8.0)
cmap(i,2) = 4.0 * x + 1.0/2.0;
else if (x >= 1.0/8.0 && x < 3.0/8.0)
cmap(i,2) = 1.0;
else if (x >= 3.0/8.0 && x < 5.0/8.0)
cmap(i,2) = -4.0 * x + 5.0/2.0;
}
return cmap;
}
static double
default_screendepth (void)
{
return display_info::depth ();
}
static Matrix
default_screensize (void)
{
Matrix retval (1, 4, 1.0);
retval(2) = display_info::width ();
retval(3) = display_info::height ();
return retval;
}
static double
default_screenpixelsperinch (void)
{
return (display_info::x_dpi () + display_info::y_dpi ()) / 2;
}
static Matrix
default_colororder (void)
{
Matrix retval (7, 3, 0.0);
retval(0,2) = 1.0;
retval(1,1) = 0.5;
retval(2,0) = 1.0;
retval(3,1) = 0.75;
retval(3,2) = 0.75;
retval(4,0) = 0.75;
retval(4,2) = 0.75;
retval(5,0) = 0.75;
retval(5,1) = 0.75;
retval(6,0) = 0.25;
retval(6,1) = 0.25;
retval(6,2) = 0.25;
return retval;
}
static Matrix
default_lim (bool logscale = false)
{
Matrix m (1, 2, 0);
if (logscale)
{
m(0) = 0.1;
m(1) = 1.0;
}
else
m(1) = 1;
return m;
}
static Matrix
default_data (void)
{
Matrix retval (1, 2);
retval(0) = 0;
retval(1) = 1;
return retval;
}
static Matrix
default_axes_position (void)
{
Matrix m (1, 4, 0.0);
m(0) = 0.13;
m(1) = 0.11;
m(2) = 0.775;
m(3) = 0.815;
return m;
}
static Matrix
default_axes_outerposition (void)
{
Matrix m (1, 4, 0.0);
m(2) = m(3) = 1.0;
return m;
}
static Matrix
default_axes_tick (void)
{
Matrix m (1, 6, 0.0);
m(0) = 0.0;
m(1) = 0.2;
m(2) = 0.4;
m(3) = 0.6;
m(4) = 0.8;
m(5) = 1.0;
return m;
}
static Matrix
default_axes_ticklength (void)
{
Matrix m (1, 2, 0.0);
m(0) = 0.01;
m(1) = 0.025;
return m;
}
static Matrix
default_figure_position (void)
{
Matrix m (1, 4, 0.0);
m(0) = 300;
m(1) = 200;
m(2) = 560;
m(3) = 420;
return m;
}
static Matrix
default_figure_papersize (void)
{
Matrix m (1, 2, 0.0);
m(0) = 8.5;
m(1) = 11.0;
return m;
}
static Matrix
default_figure_paperposition (void)
{
Matrix m (1, 4, 0.0);
m(0) = 0.25;
m(1) = 2.50;
m(2) = 8.00;
m(3) = 6.00;
return m;
}
static Matrix
default_control_position (void)
{
Matrix retval (1, 4, 0.0);
retval(0) = 0;
retval(1) = 0;
retval(2) = 80;
retval(3) = 30;
return retval;
}
static Matrix
default_control_sliderstep (void)
{
Matrix retval (1, 2, 0.0);
retval(0) = 0.01;
retval(1) = 0.1;
return retval;
}
static Matrix
default_panel_position (void)
{
Matrix retval (1, 4, 0.0);
retval(0) = 0;
retval(1) = 0;
retval(2) = 0.5;
retval(3) = 0.5;
return retval;
}
static double
convert_font_size (double font_size, const caseless_str& from_units,
const caseless_str& to_units, double parent_height = 0)
{
// Simple case where from_units == to_units
if (from_units.compare (to_units))
return font_size;
// Converts the given fontsize using the following transformation:
// <old_font_size> => points => <new_font_size>
double points_size = 0;
double res = 0;
if (from_units.compare ("points"))
points_size = font_size;
else
{
res = xget (0, "screenpixelsperinch").double_value ();
if (from_units.compare ("pixels"))
points_size = font_size * 72.0 / res;
else if (from_units.compare ("inches"))
points_size = font_size * 72.0;
else if (from_units.compare ("centimeters"))
points_size = font_size * 72.0 / 2.54;
else if (from_units.compare ("normalized"))
points_size = font_size * parent_height * 72.0 / res;
}
double new_font_size = 0;
if (to_units.compare ("points"))
new_font_size = points_size;
else
{
if (res <= 0)
res = xget (0, "screenpixelsperinch").double_value ();
if (to_units.compare ("pixels"))
new_font_size = points_size * res / 72.0;
else if (to_units.compare ("inches"))
new_font_size = points_size / 72.0;
else if (to_units.compare ("centimeters"))
new_font_size = points_size * 2.54 / 72.0;
else if (to_units.compare ("normalized"))
{
// Avoid setting font size to (0/0) = NaN
if (parent_height > 0)
new_font_size = points_size * res / (parent_height * 72.0);
}
}
return new_font_size;
}
static Matrix
convert_position (const Matrix& pos, const caseless_str& from_units,
const caseless_str& to_units, const Matrix& parent_dim)
{
Matrix retval (1, pos.numel ());
double res = 0;
bool is_rectangle = (pos.numel () == 4);
bool is_2d = (pos.numel () == 2);
if (from_units.compare ("pixels"))
retval = pos;
else if (from_units.compare ("normalized"))
{
retval(0) = pos(0) * parent_dim(0) + 1;
retval(1) = pos(1) * parent_dim(1) + 1;
if (is_rectangle)
{
retval(2) = pos(2) * parent_dim(0);
retval(3) = pos(3) * parent_dim(1);
}
else if (! is_2d)
retval(2) = 0;
}
else if (from_units.compare ("characters"))
{
if (res <= 0)
res = xget (0, "screenpixelsperinch").double_value ();
double f = 0.0;
// FIXME: this assumes the system font is Helvetica 10pt
// (for which "x" requires 6x12 pixels at 74.951 pixels/inch)
f = 12.0 * res / 74.951;
if (f > 0)
{
retval(0) = 0.5 * pos(0) * f;
retval(1) = pos(1) * f;
if (is_rectangle)
{
retval(2) = 0.5 * pos(2) * f;
retval(3) = pos(3) * f;
}
else if (! is_2d)
retval(2) = 0;
}
}
else
{
if (res <= 0)
res = xget (0, "screenpixelsperinch").double_value ();
double f = 0.0;
if (from_units.compare ("points"))
f = res / 72.0;
else if (from_units.compare ("inches"))
f = res;
else if (from_units.compare ("centimeters"))
f = res / 2.54;
if (f > 0)
{
retval(0) = pos(0) * f + 1;
retval(1) = pos(1) * f + 1;
if (is_rectangle)
{
retval(2) = pos(2) * f;
retval(3) = pos(3) * f;
}
else if (! is_2d)
retval(2) = 0;
}
}
if (! to_units.compare ("pixels"))
{
if (to_units.compare ("normalized"))
{
retval(0) = (retval(0) - 1) / parent_dim(0);
retval(1) = (retval(1) - 1) / parent_dim(1);
if (is_rectangle)
{
retval(2) /= parent_dim(0);
retval(3) /= parent_dim(1);
}
else if (! is_2d)
retval(2) = 0;
}
else if (to_units.compare ("characters"))
{
if (res <= 0)
res = xget (0, "screenpixelsperinch").double_value ();
double f = 0.0;
f = 12.0 * res / 74.951;
if (f > 0)
{
retval(0) = 2 * retval(0) / f;
retval(1) = retval(1) / f;
if (is_rectangle)
{
retval(2) = 2 * retval(2) / f;
retval(3) = retval(3) / f;
}
else if (! is_2d)
retval(2) = 0;
}
}
else
{
if (res <= 0)
res = xget (0, "screenpixelsperinch").double_value ();
double f = 0.0;
if (to_units.compare ("points"))
f = res / 72.0;
else if (to_units.compare ("inches"))
f = res;
else if (to_units.compare ("centimeters"))
f = res / 2.54;
if (f > 0)
{
retval(0) = (retval(0) - 1) / f;
retval(1) = (retval(1) - 1) / f;
if (is_rectangle)
{
retval(2) /= f;
retval(3) /= f;
}
else if (! is_2d)
retval(2) = 0;
}
}
}
else if (! is_rectangle && ! is_2d)
retval(2) = 0;
return retval;
}
static Matrix
convert_text_position (const Matrix& pos, const text::properties& props,
const caseless_str& from_units,
const caseless_str& to_units)
{
graphics_object go = gh_manager::get_object (props.get___myhandle__ ());
graphics_object ax = go.get_ancestor ("axes");
Matrix retval;
if (ax.valid_object ())
{
const axes::properties& ax_props =
dynamic_cast<const axes::properties&> (ax.get_properties ());
graphics_xform ax_xform = ax_props.get_transform ();
bool is_rectangle = (pos.numel () == 4);
Matrix ax_bbox = ax_props.get_boundingbox (true),
ax_size = ax_bbox.extract_n (0, 2, 1, 2);
if (from_units.compare ("data"))
{
if (is_rectangle)
{
ColumnVector v1 = ax_xform.transform (pos(0), pos(1), 0),
v2 = ax_xform.transform (pos(0) + pos(2),
pos(1) + pos(3), 0);
retval.resize (1, 4);
retval(0) = v1(0) - ax_bbox(0) + 1;
retval(1) = ax_bbox(1) + ax_bbox(3) - v1(1) + 1;
retval(2) = v2(0) - v1(0);
retval(3) = v1(1) - v2(1);
}
else
{
ColumnVector v = ax_xform.transform (pos(0), pos(1), pos(2));
retval.resize (1, 3);
retval(0) = v(0) - ax_bbox(0) + 1;
retval(1) = ax_bbox(1) + ax_bbox(3) - v(1) + 1;
retval(2) = 0;
}
}
else
retval = convert_position (pos, from_units, "pixels", ax_size);
if (! to_units.compare ("pixels"))
{
if (to_units.compare ("data"))
{
if (is_rectangle)
{
ColumnVector v1, v2;
v1 = ax_xform.untransform (
retval(0) + ax_bbox(0) - 1,
ax_bbox(1) + ax_bbox(3) - retval(1) + 1);
v2 = ax_xform.untransform (
retval(0) + retval(2) + ax_bbox(0) - 1,
ax_bbox(1) + ax_bbox(3) - (retval(1) + retval(3)) + 1);
retval.resize (1, 4);
retval(0) = v1(0);
retval(1) = v1(1);
retval(2) = v2(0) - v1(0);
retval(3) = v2(1) - v1(1);
}
else
{
ColumnVector v;
v = ax_xform.untransform (
retval(0) + ax_bbox(0) - 1,
ax_bbox(1) + ax_bbox(3) - retval(1) + 1);
retval.resize (1, 3);
retval(0) = v(0);
retval(1) = v(1);
retval(2) = v(2);
}
}
else
retval = convert_position (retval, "pixels", to_units, ax_size);
}
}
return retval;
}
// This function always returns the screensize in pixels
static Matrix
screen_size_pixels (void)
{
graphics_object obj = gh_manager::get_object (0);
Matrix sz = obj.get ("screensize").matrix_value ();
return convert_position (sz, obj.get ("units").string_value (), "pixels",
sz.extract_n (0, 2, 1, 2)).extract_n (0, 2, 1, 2);
}
static void
convert_cdata_2 (bool is_scaled, double clim_0, double clim_1,
const double *cmapv, double x, octave_idx_type lda,
octave_idx_type nc, octave_idx_type i, double *av)
{
if (is_scaled)
x = xround ((nc - 1) * (x - clim_0) / (clim_1 - clim_0));
else
x = xround (x - 1);
if (xisnan (x))
{
av[i] = x;
av[i+lda] = x;
av[i+2*lda] = x;
}
else
{
if (x < 0)
x = 0;
else if (x >= nc)
x = (nc - 1);
octave_idx_type idx = static_cast<octave_idx_type> (x);
av[i] = cmapv[idx];
av[i+lda] = cmapv[idx+nc];
av[i+2*lda] = cmapv[idx+2*nc];
}
}
template <class T>
void
convert_cdata_1 (bool is_scaled, double clim_0, double clim_1,
const double *cmapv, const T *cv, octave_idx_type lda,
octave_idx_type nc, double *av)
{
for (octave_idx_type i = 0; i < lda; i++)
convert_cdata_2 (is_scaled, clim_0, clim_1, cmapv, cv[i], lda, nc, i, av);
}
static octave_value
convert_cdata (const base_properties& props, const octave_value& cdata,
bool is_scaled, int cdim)
{
dim_vector dv (cdata.dims ());
if (dv.length () == cdim && dv(cdim-1) == 3)
return cdata;
Matrix cmap (1, 3, 0.0);
Matrix clim (1, 2, 0.0);
graphics_object go = gh_manager::get_object (props.get___myhandle__ ());
graphics_object fig = go.get_ancestor ("figure");
if (fig.valid_object ())
{
Matrix _cmap = fig.get (caseless_str ("colormap")).matrix_value ();
if (! error_state)
cmap = _cmap;
}
if (is_scaled)
{
graphics_object ax = go.get_ancestor ("axes");
if (ax.valid_object ())
{
Matrix _clim = ax.get (caseless_str ("clim")).matrix_value ();
if (! error_state)
clim = _clim;
}
}
dv.resize (cdim);
dv(cdim-1) = 3;
NDArray a (dv);
octave_idx_type lda = a.numel () / static_cast<octave_idx_type> (3);
octave_idx_type nc = cmap.rows ();
double *av = a.fortran_vec ();
const double *cmapv = cmap.data ();
double clim_0 = clim(0);
double clim_1 = clim(1);
#define CONVERT_CDATA_1(ARRAY_T, VAL_FN) \
do \
{ \
ARRAY_T tmp = cdata. VAL_FN ## array_value (); \
\
convert_cdata_1 (is_scaled, clim_0, clim_1, cmapv, \
tmp.data (), lda, nc, av); \
} \
while (0)
if (cdata.is_uint8_type ())
CONVERT_CDATA_1 (uint8NDArray, uint8_);
else if (cdata.is_single_type ())
CONVERT_CDATA_1 (FloatNDArray, float_);
else if (cdata.is_double_type ())
CONVERT_CDATA_1 (NDArray, );
else
error ("unsupported type for cdata (= %s)", cdata.type_name ().c_str ());
#undef CONVERT_CDATA_1
return octave_value (a);
}
template<class T>
static void
get_array_limits (const Array<T>& m, double& emin, double& emax,
double& eminp, double& emaxp)
{
const T *data = m.data ();
octave_idx_type n = m.numel ();
for (octave_idx_type i = 0; i < n; i++)
{
double e = double (data[i]);
// Don't need to test for NaN here as NaN>x and NaN<x is always false
if (! xisinf (e))
{
if (e < emin)
emin = e;
if (e > emax)
emax = e;
if (e > 0 && e < eminp)
eminp = e;
if (e < 0 && e > emaxp)
emaxp = e;
}
}
}
static bool
lookup_object_name (const caseless_str& name, caseless_str& go_name,
caseless_str& rest)
{
int len = name.length ();
int offset = 0;
bool result = false;
if (len >= 4)
{
caseless_str pfx = name.substr (0, 4);
if (pfx.compare ("axes") || pfx.compare ("line")
|| pfx.compare ("text"))
offset = 4;
else if (len >= 5)
{
pfx = name.substr (0, 5);
if (pfx.compare ("image") || pfx.compare ("patch"))
offset = 5;
else if (len >= 6)
{
pfx = name.substr (0, 6);
if (pfx.compare ("figure") || pfx.compare ("uimenu"))
offset = 6;
else if (len >= 7)
{
pfx = name.substr (0, 7);
if (pfx.compare ("surface") || pfx.compare ("hggroup")
|| pfx.compare ("uipanel"))
offset = 7;
else if (len >= 9)
{
pfx = name.substr (0, 9);
if (pfx.compare ("uicontrol")
|| pfx.compare ("uitoolbar"))
offset = 9;
else if (len >= 10)
{
pfx = name.substr (0, 10);
if (pfx.compare ("uipushtool"))
offset = 10;
else if (len >= 12)
{
pfx = name.substr (0, 12);
if (pfx.compare ("uitoggletool"))
offset = 12;
else if (len >= 13)
{
pfx = name.substr (0, 13);
if (pfx.compare ("uicontextmenu"))
offset = 13;
}
}
}
}
}
}
}
if (offset > 0)
{
go_name = pfx;
rest = name.substr (offset);
result = true;
}
}
return result;
}
static base_graphics_object*
make_graphics_object_from_type (const caseless_str& type,
const graphics_handle& h = graphics_handle (),
const graphics_handle& p = graphics_handle ())
{
base_graphics_object *go = 0;
if (type.compare ("figure"))
go = new figure (h, p);
else if (type.compare ("axes"))
go = new axes (h, p);
else if (type.compare ("line"))
go = new line (h, p);
else if (type.compare ("text"))
go = new text (h, p);
else if (type.compare ("image"))
go = new image (h, p);
else if (type.compare ("patch"))
go = new patch (h, p);
else if (type.compare ("surface"))
go = new surface (h, p);
else if (type.compare ("hggroup"))
go = new hggroup (h, p);
else if (type.compare ("uimenu"))
go = new uimenu (h, p);
else if (type.compare ("uicontrol"))
go = new uicontrol (h, p);
else if (type.compare ("uipanel"))
go = new uipanel (h, p);
else if (type.compare ("uicontextmenu"))
go = new uicontextmenu (h, p);
else if (type.compare ("uitoolbar"))
go = new uitoolbar (h, p);
else if (type.compare ("uipushtool"))
go = new uipushtool (h, p);
else if (type.compare ("uitoggletool"))
go = new uitoggletool (h, p);
return go;
}
// ---------------------------------------------------------------------
bool
base_property::set (const octave_value& v, bool do_run, bool do_notify_toolkit)
{
if (do_set (v))
{
// Notify graphics toolkit.
if (id >= 0 && do_notify_toolkit)
{
graphics_object go = gh_manager::get_object (parent);
if (go)
go.update (id);
}
// run listeners
if (do_run && ! error_state)
run_listeners (POSTSET);
return true;
}
return false;
}
void
base_property::run_listeners (listener_mode mode)
{
const octave_value_list& l = listeners[mode];
for (int i = 0; i < l.length (); i++)
{
gh_manager::execute_listener (parent, l(i));
if (error_state)
break;
}
}
radio_values::radio_values (const std::string& opt_string)
: default_val (), possible_vals ()
{
size_t beg = 0;
size_t len = opt_string.length ();
bool done = len == 0;
while (! done)
{
size_t end = opt_string.find ('|', beg);
if (end == std::string::npos)
{
end = len;
done = true;
}
std::string t = opt_string.substr (beg, end-beg);
// Might want more error checking here...
if (t[0] == '{')
{
t = t.substr (1, t.length () - 2);
default_val = t;
}
else if (beg == 0) // ensure default value
default_val = t;
possible_vals.insert (t);
beg = end + 1;
}
}
std::string
radio_values::values_as_string (void) const
{
std::string retval;
for (std::set<caseless_str>::const_iterator it = possible_vals.begin ();
it != possible_vals.end (); it++)
{
if (retval == "")
{
if (*it == default_value ())
retval = "{" + *it + "}";
else
retval = *it;
}
else
{
if (*it == default_value ())
retval += " | {" + *it + "}";
else
retval += " | " + *it;
}
}
if (retval != "")
retval = "[ " + retval + " ]";
return retval;
}
Cell
radio_values::values_as_cell (void) const
{
octave_idx_type i = 0;
Cell retval (nelem (), 1);
for (std::set<caseless_str>::const_iterator it = possible_vals.begin ();
it != possible_vals.end (); it++)
retval(i++) = std::string (*it);
return retval;
}
bool
color_values::str2rgb (std::string str)
{
double tmp_rgb[3] = {0, 0, 0};
bool retval = true;
unsigned int len = str.length ();
std::transform (str.begin (), str.end (), str.begin (), tolower);
if (str.compare (0, len, "blue", 0, len) == 0)
tmp_rgb[2] = 1;
else if (str.compare (0, len, "black", 0, len) == 0
|| str.compare (0, len, "k", 0, len) == 0)
tmp_rgb[0] = tmp_rgb[1] = tmp_rgb[2] = 0;
else if (str.compare (0, len, "red", 0, len) == 0)
tmp_rgb[0] = 1;
else if (str.compare (0, len, "green", 0, len) == 0)
tmp_rgb[1] = 1;
else if (str.compare (0, len, "yellow", 0, len) == 0)
tmp_rgb[0] = tmp_rgb[1] = 1;
else if (str.compare (0, len, "magenta", 0, len) == 0)
tmp_rgb[0] = tmp_rgb[2] = 1;
else if (str.compare (0, len, "cyan", 0, len) == 0)
tmp_rgb[1] = tmp_rgb[2] = 1;
else if (str.compare (0, len, "white", 0, len) == 0
|| str.compare (0, len, "w", 0, len) == 0)
tmp_rgb[0] = tmp_rgb[1] = tmp_rgb[2] = 1;
else
retval = false;
if (retval)
{
for (int i = 0; i < 3; i++)
xrgb(i) = tmp_rgb[i];
}
return retval;
}
bool
color_property::do_set (const octave_value& val)
{
if (val.is_string ())
{
std::string s = val.string_value ();
if (! s.empty ())
{
std::string match;
if (radio_val.contains (s, match))
{
if (current_type != radio_t || match != current_val)
{
if (s.length () != match.length ())
warning_with_id ("Octave:abbreviated-property-match",
"%s: allowing %s to match %s value %s",
"set", s.c_str (), get_name ().c_str (),
match.c_str ());
current_val = match;
current_type = radio_t;
return true;
}
}
else
{
color_values col (s);
if (! error_state)
{
if (current_type != color_t || col != color_val)
{
color_val = col;
current_type = color_t;
return true;
}
}
else
error ("invalid value for color property \"%s\" (value = %s)",
get_name ().c_str (), s.c_str ());
}
}
else
error ("invalid value for color property \"%s\"",
get_name ().c_str ());
}
else if (val.is_numeric_type ())
{
Matrix m = val.matrix_value ();
if (m.numel () == 3)
{
color_values col (m(0), m(1), m(2));
if (! error_state)
{
if (current_type != color_t || col != color_val)
{
color_val = col;
current_type = color_t;
return true;
}
}
}
else
error ("invalid value for color property \"%s\"",
get_name ().c_str ());
}
else
error ("invalid value for color property \"%s\"",
get_name ().c_str ());
return false;
}
bool
double_radio_property::do_set (const octave_value& val)
{
if (val.is_string ())
{
std::string s = val.string_value ();
std::string match;
if (! s.empty () && radio_val.contains (s, match))
{
if (current_type != radio_t || match != current_val)
{
if (s.length () != match.length ())
warning_with_id ("Octave:abbreviated-property-match",
"%s: allowing %s to match %s value %s",
"set", s.c_str (), get_name ().c_str (),
match.c_str ());
current_val = match;
current_type = radio_t;
return true;
}
}
else
error ("invalid value for double_radio property \"%s\"",
get_name ().c_str ());
}
else if (val.is_scalar_type () && val.is_real_type ())
{
double new_dval = val.double_value ();
if (current_type != double_t || new_dval != dval)
{
dval = new_dval;
current_type = double_t;
return true;
}
}
else
error ("invalid value for double_radio property \"%s\"",
get_name ().c_str ());
return false;
}
bool
array_property::validate (const octave_value& v)
{
bool xok = false;
// check value type
if (type_constraints.size () > 0)
{
if (type_constraints.find (v.class_name ()) != type_constraints.end ())
xok = true;
// check if complex is allowed (it's also of class "double", so
// checking that alone is not enough to ensure real type)
if (type_constraints.find ("real") != type_constraints.end ()
&& v.is_complex_type ())
xok = false;
}
else
xok = v.is_numeric_type ();
if (xok)
{
if (size_constraints.size () == 0)
return true;
dim_vector vdims = v.dims ();
int vlen = vdims.length ();
xok = false;
// check dimensional size constraints until a match is found
for (std::list<dim_vector>::const_iterator it = size_constraints.begin ();
! xok && it != size_constraints.end (); ++it)
{
dim_vector itdims = (*it);
if (itdims.length () == vlen)
{
xok = true;
for (int i = 0; xok && i < vlen; i++)
{
if (itdims(i) > 0)
{
if (itdims(i) != vdims(i))
xok = false;
}
else if (v.is_empty ())
break;
}
}
}
}
return xok;
}
bool
array_property::is_equal (const octave_value& v) const
{
if (data.type_name () == v.type_name ())
{
if (data.dims () == v.dims ())
{
#define CHECK_ARRAY_EQUAL(T,F,A) \
{ \
if (data.numel () == 1) \
return data.F ## scalar_value () == \
v.F ## scalar_value (); \
else \
{ \
/* Keep copy of array_value to allow sparse/bool arrays */ \
/* that are converted, to not be deallocated early */ \
const A m1 = data.F ## array_value (); \
const T* d1 = m1.data (); \
const A m2 = v.F ## array_value (); \
const T* d2 = m2.data ();\
\
bool flag = true; \
\
for (int i = 0; flag && i < data.numel (); i++) \
if (d1[i] != d2[i]) \
flag = false; \
\
return flag; \
} \
}
if (data.is_double_type () || data.is_bool_type ())
CHECK_ARRAY_EQUAL (double, , NDArray)
else if (data.is_single_type ())
CHECK_ARRAY_EQUAL (float, float_, FloatNDArray)
else if (data.is_int8_type ())
CHECK_ARRAY_EQUAL (octave_int8, int8_, int8NDArray)
else if (data.is_int16_type ())
CHECK_ARRAY_EQUAL (octave_int16, int16_, int16NDArray)
else if (data.is_int32_type ())
CHECK_ARRAY_EQUAL (octave_int32, int32_, int32NDArray)
else if (data.is_int64_type ())
CHECK_ARRAY_EQUAL (octave_int64, int64_, int64NDArray)
else if (data.is_uint8_type ())
CHECK_ARRAY_EQUAL (octave_uint8, uint8_, uint8NDArray)
else if (data.is_uint16_type ())
CHECK_ARRAY_EQUAL (octave_uint16, uint16_, uint16NDArray)
else if (data.is_uint32_type ())
CHECK_ARRAY_EQUAL (octave_uint32, uint32_, uint32NDArray)
else if (data.is_uint64_type ())
CHECK_ARRAY_EQUAL (octave_uint64, uint64_, uint64NDArray)
}
}
return false;
}
void
array_property::get_data_limits (void)
{
xmin = xminp = octave_Inf;
xmax = xmaxp = -octave_Inf;
if (! data.is_empty ())
{
if (data.is_integer_type ())
{
if (data.is_int8_type ())
get_array_limits (data.int8_array_value (),
xmin, xmax, xminp, xmaxp);
else if (data.is_uint8_type ())
get_array_limits (data.uint8_array_value (),
xmin, xmax, xminp, xmaxp);
else if (data.is_int16_type ())
get_array_limits (data.int16_array_value (),
xmin, xmax, xminp, xmaxp);
else if (data.is_uint16_type ())
get_array_limits (data.uint16_array_value (),
xmin, xmax, xminp, xmaxp);
else if (data.is_int32_type ())
get_array_limits (data.int32_array_value (),
xmin, xmax, xminp, xmaxp);
else if (data.is_uint32_type ())
get_array_limits (data.uint32_array_value (),
xmin, xmax, xminp, xmaxp);
else if (data.is_int64_type ())
get_array_limits (data.int64_array_value (),
xmin, xmax, xminp, xmaxp);
else if (data.is_uint64_type ())
get_array_limits (data.uint64_array_value (),
xmin, xmax, xminp, xmaxp);
}
else
get_array_limits (data.array_value (), xmin, xmax, xminp, xmaxp);
}
}
bool
handle_property::do_set (const octave_value& v)
{
double dv = v.double_value ();
if (! error_state)
{
graphics_handle gh = gh_manager::lookup (dv);
if (xisnan (gh.value ()) || gh.ok ())
{
if (current_val != gh)
{
current_val = gh;
return true;
}
}
else
error ("set: invalid graphics handle (= %g) for property \"%s\"",
dv, get_name ().c_str ());
}
else
error ("set: invalid graphics handle for property \"%s\"",
get_name ().c_str ());
return false;
}
Matrix
children_property::do_get_children (bool return_hidden) const
{
Matrix retval (children_list.size (), 1);
octave_idx_type k = 0;
graphics_object go = gh_manager::get_object (0);
root_figure::properties& props =
dynamic_cast<root_figure::properties&> (go.get_properties ());
if (! props.is_showhiddenhandles ())
{
for (const_children_list_iterator p = children_list.begin ();
p != children_list.end (); p++)
{
graphics_handle kid = *p;
if (gh_manager::is_handle_visible (kid))
{
if (! return_hidden)
retval(k++) = *p;
}
else if (return_hidden)
retval(k++) = *p;
}
retval.resize (k, 1);
}
else
{
for (const_children_list_iterator p = children_list.begin ();
p != children_list.end (); p++)
retval(k++) = *p;
}
return retval;
}
void
children_property::do_delete_children (bool clear)
{
for (children_list_iterator p = children_list.begin ();
p != children_list.end (); p++)
{
graphics_object go = gh_manager::get_object (*p);
if (go.valid_object ())
gh_manager::free (*p);
}
if (clear)
children_list.clear ();
}
bool
callback_property::validate (const octave_value& v) const
{
// case 1: function handle
// case 2: cell array with first element being a function handle
// case 3: string corresponding to known function name
// case 4: evaluatable string
// case 5: empty matrix
if (v.is_function_handle ())
return true;
else if (v.is_string ())
// complete validation will be done at execution-time
return true;
else if (v.is_cell () && v.length () > 0
&& (v.rows () == 1 || v.columns () == 1)
&& v.cell_value ()(0).is_function_handle ())
return true;
else if (v.is_empty ())
return true;
return false;
}
// If TRUE, we are executing any callback function, or the functions it
// calls. Used to determine handle visibility inside callback
// functions.
static bool executing_callback = false;
void
callback_property::execute (const octave_value& data) const
{
unwind_protect frame;
// We are executing the callback function associated with this
// callback property. When set to true, we avoid recursive calls to
// callback routines.
frame.protect_var (executing);
// We are executing a callback function, so allow handles that have
// their handlevisibility property set to "callback" to be visible.
frame.protect_var (executing_callback);
if (! executing)
{
executing = true;
executing_callback = true;
if (callback.is_defined () && ! callback.is_empty ())
gh_manager::execute_callback (get_parent (), callback, data);
}
}
// Used to cache dummy graphics objects from which dynamic
// properties can be cloned.
static std::map<caseless_str, graphics_object> dprop_obj_map;
property
property::create (const std::string& name, const graphics_handle& h,
const caseless_str& type, const octave_value_list& args)
{
property retval;
if (type.compare ("string"))
{
std::string val = (args.length () > 0 ? args(0).string_value () : "");
if (! error_state)
retval = property (new string_property (name, h, val));
}
else if (type.compare ("any"))
{
octave_value val = args.length () > 0 ? args(0)
: octave_value (Matrix ());
retval = property (new any_property (name, h, val));
}
else if (type.compare ("radio"))
{
if (args.length () > 0)
{
std::string vals = args(0).string_value ();
if (! error_state)
{
retval = property (new radio_property (name, h, vals));
if (args.length () > 1)
retval.set (args(1));
}
else
error ("addproperty: invalid argument for radio property, expected a string value");
}
else
error ("addproperty: missing possible values for radio property");
}
else if (type.compare ("double"))
{
double d = (args.length () > 0 ? args(0).double_value () : 0);
if (! error_state)
retval = property (new double_property (name, h, d));
}
else if (type.compare ("handle"))
{
double hh = (args.length () > 0 ? args(0).double_value () : octave_NaN);
if (! error_state)
{
graphics_handle gh (hh);
retval = property (new handle_property (name, h, gh));
}
}
else if (type.compare ("boolean"))
{
retval = property (new bool_property (name, h, false));
if (args.length () > 0)
retval.set (args(0));
}
else if (type.compare ("data"))
{
retval = property (new array_property (name, h, Matrix ()));
if (args.length () > 0)
{
retval.set (args(0));
// FIXME: additional argument could define constraints,
// but is this really useful?
}
}
else if (type.compare ("color"))
{
color_values cv (0, 0, 0);
radio_values rv;
if (args.length () > 1)
rv = radio_values (args(1).string_value ());
if (! error_state)
{
retval = property (new color_property (name, h, cv, rv));
if (! error_state)
{
if (args.length () > 0 && ! args(0).is_empty ())
retval.set (args(0));
else
retval.set (rv.default_value ());
}
}
}
else
{
caseless_str go_name, go_rest;
if (lookup_object_name (type, go_name, go_rest))
{
graphics_object go;
std::map<caseless_str, graphics_object>::const_iterator it =
dprop_obj_map.find (go_name);
if (it == dprop_obj_map.end ())
{
base_graphics_object *bgo =
make_graphics_object_from_type (go_name);
if (bgo)
{
go = graphics_object (bgo);
dprop_obj_map[go_name] = go;
}
}
else
go = it->second;
if (go.valid_object ())
{
property prop = go.get_properties ().get_property (go_rest);
if (! error_state)
{
retval = prop.clone ();
retval.set_parent (h);
retval.set_name (name);
if (args.length () > 0)
retval.set (args(0));
}
}
else
error ("addproperty: invalid object type (= %s)",
go_name.c_str ());
}
else
error ("addproperty: unsupported type for dynamic property (= %s)",
type.c_str ());
}
return retval;
}
static void
finalize_r (const graphics_handle& h)
{
graphics_object go = gh_manager::get_object (h);
if (go)
{
Matrix children = go.get_properties ().get_all_children ();
for (int k = 0; k < children.numel (); k++)
finalize_r (children(k));
go.finalize ();
}
}
static void
initialize_r (const graphics_handle& h)
{
graphics_object go = gh_manager::get_object (h);
if (go)
{
Matrix children = go.get_properties ().get_all_children ();
go.initialize ();
for (int k = 0; k < children.numel (); k++)
initialize_r (children(k));
}
}
void
figure::properties::set_toolkit (const graphics_toolkit& b)
{
if (toolkit)
finalize_r (get___myhandle__ ());
toolkit = b;
__graphics_toolkit__ = b.get_name ();
__plot_stream__ = Matrix ();
if (toolkit)
initialize_r (get___myhandle__ ());
mark_modified ();
}
// ---------------------------------------------------------------------
void
property_list::set (const caseless_str& name, const octave_value& val)
{
size_t offset = 0;
size_t len = name.length ();
if (len > 4)
{
caseless_str pfx = name.substr (0, 4);
if (pfx.compare ("axes") || pfx.compare ("line")
|| pfx.compare ("text"))
offset = 4;
else if (len > 5)
{
pfx = name.substr (0, 5);
if (pfx.compare ("image") || pfx.compare ("patch"))
offset = 5;
else if (len > 6)
{
pfx = name.substr (0, 6);
if (pfx.compare ("figure") || pfx.compare ("uimenu"))
offset = 6;
else if (len > 7)
{
pfx = name.substr (0, 7);
if (pfx.compare ("surface") || pfx.compare ("hggroup")
|| pfx.compare ("uipanel"))
offset = 7;
else if (len > 9)
{
pfx = name.substr (0, 9);
if (pfx.compare ("uicontrol")
|| pfx.compare ("uitoolbar"))
offset = 9;
else if (len > 10)
{
pfx = name.substr (0, 10);
if (pfx.compare ("uipushtool"))
offset = 10;
else if (len > 12)
{
pfx = name.substr (0, 12);
if (pfx.compare ("uitoogletool"))
offset = 12;
else if (len > 13)
{
pfx = name.substr (0, 13);
if (pfx.compare ("uicontextmenu"))
offset = 13;
}
}
}
}
}
}
}
if (offset > 0)
{
// FIXME: should we validate property names and values here?
std::string pname = name.substr (offset);
std::transform (pfx.begin (), pfx.end (), pfx.begin (), tolower);
std::transform (pname.begin (), pname.end (), pname.begin (),
tolower);
bool has_property = false;
if (pfx == "axes")
has_property = axes::properties::has_core_property (pname);
else if (pfx == "line")
has_property = line::properties::has_core_property (pname);
else if (pfx == "text")
has_property = text::properties::has_core_property (pname);
else if (pfx == "image")
has_property = image::properties::has_core_property (pname);
else if (pfx == "patch")
has_property = patch::properties::has_core_property (pname);
else if (pfx == "figure")
has_property = figure::properties::has_core_property (pname);
else if (pfx == "surface")
has_property = surface::properties::has_core_property (pname);
else if (pfx == "hggroup")
has_property = hggroup::properties::has_core_property (pname);
else if (pfx == "uimenu")
has_property = uimenu::properties::has_core_property (pname);
else if (pfx == "uicontrol")
has_property = uicontrol::properties::has_core_property (pname);
else if (pfx == "uipanel")
has_property = uipanel::properties::has_core_property (pname);
else if (pfx == "uicontextmenu")
has_property = uicontextmenu::properties::has_core_property (pname);
else if (pfx == "uitoolbar")
has_property = uitoolbar::properties::has_core_property (pname);
else if (pfx == "uipushtool")
has_property = uipushtool::properties::has_core_property (pname);
if (has_property)
{
bool remove = false;
if (val.is_string ())
{
std::string tval = val.string_value ();
remove = (tval.compare ("remove") == 0);
}
pval_map_type& pval_map = plist_map[pfx];
if (remove)
{
pval_map_iterator p = pval_map.find (pname);
if (p != pval_map.end ())
pval_map.erase (p);
}
else
pval_map[pname] = val;
}
else
error ("invalid %s property '%s'", pfx.c_str (), pname.c_str ());
}
}
if (! error_state && offset == 0)
error ("invalid default property specification");
}
octave_value
property_list::lookup (const caseless_str& name) const
{
octave_value retval;
size_t offset = 0;
size_t len = name.length ();
if (len > 4)
{
caseless_str pfx = name.substr (0, 4);
if (pfx.compare ("axes") || pfx.compare ("line")
|| pfx.compare ("text"))
offset = 4;
else if (len > 5)
{
pfx = name.substr (0, 5);
if (pfx.compare ("image") || pfx.compare ("patch"))
offset = 5;
else if (len > 6)
{
pfx = name.substr (0, 6);
if (pfx.compare ("figure") || pfx.compare ("uimenu"))
offset = 6;
else if (len > 7)
{
pfx = name.substr (0, 7);
if (pfx.compare ("surface") || pfx.compare ("hggroup")
|| pfx.compare ("uipanel"))
offset = 7;
else if (len > 9)
{
pfx = name.substr (0, 9);
if (pfx.compare ("uicontrol")
|| pfx.compare ("uitoolbar"))
offset = 9;
else if (len > 10)
{
pfx = name.substr (0, 10);
if (pfx.compare ("uipushtool"))
offset = 10;
else if (len > 12)
{
pfx = name.substr (0, 12);
if (pfx.compare ("uitoggletool"))
offset = 12;
else if (len > 13)
{
pfx = name.substr (0, 13);
if (pfx.compare ("uicontextmenu"))
offset = 13;
}
}
}
}
}
}
}
if (offset > 0)
{
std::string pname = name.substr (offset);
std::transform (pfx.begin (), pfx.end (), pfx.begin (), tolower);
std::transform (pname.begin (), pname.end (), pname.begin (),
tolower);
plist_map_const_iterator p = find (pfx);
if (p != end ())
{
const pval_map_type& pval_map = p->second;
pval_map_const_iterator q = pval_map.find (pname);
if (q != pval_map.end ())
retval = q->second;
}
}
}
return retval;
}
octave_scalar_map
property_list::as_struct (const std::string& prefix_arg) const
{
octave_scalar_map m;
for (plist_map_const_iterator p = begin (); p != end (); p++)
{
std::string prefix = prefix_arg + p->first;
const pval_map_type pval_map = p->second;
for (pval_map_const_iterator q = pval_map.begin ();
q != pval_map.end ();
q++)
m.assign (prefix + q->first, q->second);
}
return m;
}
// Set properties given as a cs-list of name, value pairs.
void
graphics_object::set (const octave_value_list& args)
{
int nargin = args.length ();
if (nargin == 0)
error ("graphics_object::set: Nothing to set");
else if (nargin % 2 == 0)
{
for (int i = 0; i < nargin; i += 2)
{
caseless_str name = args(i).string_value ();
if (! error_state)
{
octave_value val = args(i+1);
set_value_or_default (name, val);
if (error_state)
break;
}
else
error ("set: expecting argument %d to be a property name", i);
}
}
else
error ("set: invalid number of arguments");
}
/*
## test set with name, value pairs
%!test
%! hf = figure ("visible", "off");
%! h = plot (1:10, 10:-1:1);
%! set (h, "linewidth", 10, "marker", "x");
%! lw = get (h, "linewidth");
%! mk = get (h, "marker");
%! close (hf);
%! assert (lw, 10);
%! assert (mk, "x");
*/
// Set properties given in two cell arrays containing names and values.
void
graphics_object::set (const Array<std::string>& names,
const Cell& values, octave_idx_type row)
{
if (names.numel () != values.columns ())
{
error ("set: number of names must match number of value columns (%d != %d)",
names.numel (), values.columns ());
}
octave_idx_type k = names.columns ();
for (octave_idx_type column = 0; column < k; column++)
{
caseless_str name = names(column);
octave_value val = values(row, column);
set_value_or_default (name, val);
if (error_state)
break;
}
}
/*
## test set with cell array arguments
%!test
%! hf = figure ("visible", "off");
%! h = plot (1:10, 10:-1:1);
%! set (h, {"linewidth", "marker"}, {10, "x"});
%! lw = get (h, "linewidth");
%! mk = get (h, "marker");
%! close (hf);
%! assert (lw, 10);
%! assert (mk, "x");
## test set with multiple handles and cell array arguments
%!test
%! hf = figure ("visible", "off");
%! unwind_protect
%! h = plot (1:10, 10:-1:1, 1:10, 1:10);
%! set (h, {"linewidth", "marker"}, {10, "x"; 5, "o"});
%! assert (get (h, "linewidth"), {10; 5});
%! assert (get (h, "marker"), {"x"; "o"});
%! set (h, {"linewidth", "marker"}, {10, "x"});
%! assert (get (h, "linewidth"), {10; 10});
%! assert (get (h, "marker"), {"x"; "x"});
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect;
%!error <set: number of graphics handles must match number of value rows>
%! hf = figure ("visible", "off");
%! unwind_protect
%! h = plot (1:10, 10:-1:1, 1:10, 1:10);
%! set (h, {"linewidth", "marker"}, {10, "x"; 5, "o"; 7, "."});
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
%!error <set: number of names must match number of value columns>
%! hf = figure ("visible", "off");
%! unwind_protect
%! h = plot (1:10, 10:-1:1, 1:10, 1:10);
%! set (h, {"linewidth"}, {10, "x"; 5, "o"});
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
*/
// Set properties given in a struct array
void
graphics_object::set (const octave_map& m)
{
for (octave_idx_type p = 0; p < m.nfields (); p++)
{
caseless_str name = m.keys ()[p];
octave_value val = octave_value (m.contents (name).elem (m.numel () - 1));
set_value_or_default (name, val);
if (error_state)
break;
}
}
/*
## test set ticklabels for compatibility
%!test
%! hf = figure ("visible", "off");
%! set (gca (), "xticklabel", [0, 0.2, 0.4, 0.6, 0.8, 1]);
%! xticklabel = get (gca (), "xticklabel");
%! close (hf);
%! assert (class (xticklabel), "char");
%! assert (size (xticklabel), [6, 3]);
%!test
%! hf = figure ("visible", "off");
%! set (gca (), "xticklabel", "0|0.2|0.4|0.6|0.8|1");
%! xticklabel = get (gca (), "xticklabel");
%! close (hf);
%! assert (class (xticklabel), "char");
%! assert (size (xticklabel), [6, 3]);
%!test
%! hf = figure ("visible", "off");
%! set (gca (), "xticklabel", ["0 "; "0.2"; "0.4"; "0.6"; "0.8"; "1 "]);
%! xticklabel = get (gca (), "xticklabel");
%! close (hf);
%! assert (class (xticklabel), "char");
%! assert (size (xticklabel), [6, 3]);
%!test
%! hf = figure ("visible", "off");
%! set (gca (), "xticklabel", {"0", "0.2", "0.4", "0.6", "0.8", "1"});
%! xticklabel = get (gca (), "xticklabel");
%! close (hf);
%! assert (class (xticklabel), "cell");
%! assert (size (xticklabel), [6, 1]);
*/
/*
## test set with struct arguments
%!test
%! hf = figure ("visible", "off");
%! unwind_protect
%! h = plot (1:10, 10:-1:1);
%! set (h, struct ("linewidth", 10, "marker", "x"));
%! assert (get (h, "linewidth"), 10);
%! assert (get (h, "marker"), "x");
%! h = plot (1:10, 10:-1:1, 1:10, 1:10);
%! set (h, struct ("linewidth", {5, 10}));
%! assert (get (h, "linewidth"), {10; 10});
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
## test ordering
%!test
%! markchanged = @(h, foobar, name) set (h, "userdata", [get(h,"userdata"); {name}]);
%! hf = figure ("visible", "off");
%! unwind_protect
%! h = line ();
%! set (h, "userdata", {});
%! addlistener (h, "color", {markchanged, "color"});
%! addlistener (h, "linewidth", {markchanged, "linewidth"});
%! ## "linewidth" first
%! props.linewidth = 2;
%! props.color = "r";
%! set (h, props);
%! assert (get (h, "userdata"), fieldnames (props));
%! clear props;
%! clf ();
%! h = line ();
%! set (h, "userdata", {});
%! addlistener (h, "color", {markchanged, "color"});
%! addlistener (h, "linewidth", {markchanged, "linewidth"});
%! ## "color" first
%! props.color = "r";
%! props.linewidth = 2;
%! set (h, props);
%! assert (get (h, "userdata"), fieldnames (props));
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
*/
// Set a property to a value or to its (factory) default value.
void
graphics_object::set_value_or_default (const caseless_str& name,
const octave_value& val)
{
if (val.is_string ())
{
std::string tval = val.string_value ();
octave_value default_val;
if (tval.compare ("default") == 0)
{
default_val = get_default (name);
if (error_state)
return;
rep->set (name, default_val);
}
else if (tval.compare ("factory") == 0)
{
default_val = get_factory_default (name);
if (error_state)
return;
rep->set (name, default_val);
}
else
{
// Matlab specifically uses "\default" to escape string setting
if (tval.compare ("\\default") == 0)
rep->set (name, "default");
else if (tval.compare ("\\factory") == 0)
rep->set (name, "factory");
else
rep->set (name, val);
}
}
else
rep->set (name, val);
}
/*
## test setting of default values
%!test
%! old_lw = get (0, "defaultlinelinewidth");
%! unwind_protect
%! hf = figure ("visible", "off");
%! h = plot (1:10, 10:-1:1);
%! set (0, "defaultlinelinewidth", 20);
%! set (h, "linewidth", "default");
%! assert (get (h, "linewidth"), 20);
%! set (h, "linewidth", "factory");
%! assert (get (h, "linewidth"), 0.5);
%! unwind_protect_cleanup
%! close (hf);
%! set (0, "defaultlinelinewidth", old_lw);
%! end_unwind_protect
*/
static double
make_handle_fraction (void)
{
static double maxrand = RAND_MAX + 2.0;
return (rand () + 1.0) / maxrand;
}
graphics_handle
gh_manager::do_get_handle (bool integer_figure_handle)
{
graphics_handle retval;
if (integer_figure_handle)
{
// Figure handles are positive integers corresponding to the
// figure number.
// We always want the lowest unused figure number.
retval = 1;
while (handle_map.find (retval) != handle_map.end ())
retval++;
}
else
{
// Other graphics handles are negative integers plus some random
// fractional part. To avoid running out of integers, we
// recycle the integer part but tack on a new random part each
// time.
free_list_iterator p = handle_free_list.begin ();
if (p != handle_free_list.end ())
{
retval = *p;
handle_free_list.erase (p);
}
else
{
retval = graphics_handle (next_handle);
next_handle = std::ceil (next_handle) - 1.0 - make_handle_fraction ();
}
}
return retval;
}
void
gh_manager::do_free (const graphics_handle& h)
{
if (h.ok ())
{
if (h.value () != 0)
{
iterator p = handle_map.find (h);
if (p != handle_map.end ())
{
base_properties& bp = p->second.get_properties ();
bp.set_beingdeleted (true);
bp.delete_children ();
octave_value val = bp.get_deletefcn ();
bp.execute_deletefcn ();
// Notify graphics toolkit.
p->second.finalize ();
// Note: this will be valid only for first explicitly
// deleted object. All its children will then have an
// unknown graphics toolkit.
// Graphics handles for non-figure objects are negative
// integers plus some random fractional part. To avoid
// running out of integers, we recycle the integer part
// but tack on a new random part each time.
handle_map.erase (p);
if (h.value () < 0)
handle_free_list.insert
(std::ceil (h.value ()) - make_handle_fraction ());
}
else
error ("graphics_handle::free: invalid object %g", h.value ());
}
else
error ("graphics_handle::free: can't delete root figure");
}
}
void
gh_manager::do_renumber_figure (const graphics_handle& old_gh,
const graphics_handle& new_gh)
{
iterator p = handle_map.find (old_gh);
if (p != handle_map.end ())
{
graphics_object go = p->second;
handle_map.erase (p);
handle_map[new_gh] = go;
if (old_gh.value () < 0)
handle_free_list.insert (std::ceil (old_gh.value ())
- make_handle_fraction ());
}
else
error ("graphics_handle::free: invalid object %g", old_gh.value ());
for (figure_list_iterator q = figure_list.begin ();
q != figure_list.end (); q++)
{
if (*q == old_gh)
{
*q = new_gh;
break;
}
}
}
gh_manager *gh_manager::instance = 0;
static void
xset (const graphics_handle& h, const caseless_str& name,
const octave_value& val)
{
graphics_object obj = gh_manager::get_object (h);
obj.set (name, val);
}
static void
xset (const graphics_handle& h, const octave_value_list& args)
{
if (args.length () > 0)
{
graphics_object obj = gh_manager::get_object (h);
obj.set (args);
}
}
static octave_value
xget (const graphics_handle& h, const caseless_str& name)
{
graphics_object obj = gh_manager::get_object (h);
return obj.get (name);
}
static graphics_handle
reparent (const octave_value& ov, const std::string& who,
const std::string& property, const graphics_handle& new_parent,
bool adopt = true)
{
graphics_handle h = octave_NaN;
double val = ov.double_value ();
if (! error_state)
{
h = gh_manager::lookup (val);
if (h.ok ())
{
graphics_object obj = gh_manager::get_object (h);
graphics_handle parent_h = obj.get_parent ();
graphics_object parent_obj = gh_manager::get_object (parent_h);
parent_obj.remove_child (h);
if (adopt)
obj.set ("parent", new_parent.value ());
else
obj.reparent (new_parent);
}
else
error ("%s: invalid graphics handle (= %g) for %s",
who.c_str (), val, property.c_str ());
}
else
error ("%s: expecting %s to be a graphics handle",
who.c_str (), property.c_str ());
return h;
}
// This function is NOT equivalent to the scripting language function gcf.
graphics_handle
gcf (void)
{
octave_value val = xget (0, "currentfigure");
return val.is_empty () ? octave_NaN : val.double_value ();
}
// This function is NOT equivalent to the scripting language function gca.
graphics_handle
gca (void)
{
octave_value val = xget (gcf (), "currentaxes");
return val.is_empty () ? octave_NaN : val.double_value ();
}
static void
delete_graphics_object (const graphics_handle& h)
{
if (h.ok ())
{
graphics_object obj = gh_manager::get_object (h);
// Don't do recursive deleting, due to callbacks
if (! obj.get_properties ().is_beingdeleted ())
{
graphics_handle parent_h = obj.get_parent ();
graphics_object parent_obj =
gh_manager::get_object (parent_h);
// NOTE: free the handle before removing it from its
// parent's children, such that the object's
// state is correct when the deletefcn callback
// is executed
gh_manager::free (h);
// A callback function might have already deleted
// the parent
if (parent_obj.valid_object ())
parent_obj.remove_child (h);
Vdrawnow_requested = true;
}
}
}
static void
delete_graphics_object (double val)
{
delete_graphics_object (gh_manager::lookup (val));
}
static void
delete_graphics_objects (const NDArray vals)
{
for (octave_idx_type i = 0; i < vals.numel (); i++)
delete_graphics_object (vals.elem (i));
}
static void
close_figure (const graphics_handle& handle)
{
octave_value closerequestfcn = xget (handle, "closerequestfcn");
OCTAVE_SAFE_CALL (gh_manager::execute_callback, (handle, closerequestfcn));
}
static void
force_close_figure (const graphics_handle& handle)
{
// Remove the deletefcn and closerequestfcn callbacks and delete the
// object directly.
xset (handle, "deletefcn", Matrix ());
xset (handle, "closerequestfcn", Matrix ());
delete_graphics_object (handle);
}
void
gh_manager::do_close_all_figures (void)
{
// FIXME: should we process or discard pending events?
event_queue.clear ();
// Don't use figure_list_iterator because we'll be removing elements
// from the list elsewhere.
Matrix hlist = do_figure_handle_list (true);
for (octave_idx_type i = 0; i < hlist.numel (); i++)
{
graphics_handle h = gh_manager::lookup (hlist(i));
if (h.ok ())
close_figure (h);
}
// They should all be closed now. If not, force them to close.
hlist = do_figure_handle_list (true);
for (octave_idx_type i = 0; i < hlist.numel (); i++)
{
graphics_handle h = gh_manager::lookup (hlist(i));
if (h.ok ())
force_close_figure (h);
}
// None left now, right?
hlist = do_figure_handle_list (true);
assert (hlist.numel () == 0);
// Clear all callback objects from our list.
callback_objects.clear ();
}
static void
adopt (const graphics_handle& p, const graphics_handle& h)
{
graphics_object parent_obj = gh_manager::get_object (p);
parent_obj.adopt (h);
}
static bool
is_handle (const graphics_handle& h)
{
return h.ok ();
}
static bool
is_handle (double val)
{
graphics_handle h = gh_manager::lookup (val);
return h.ok ();
}
static octave_value
is_handle (const octave_value& val)
{
octave_value retval = false;
if (val.is_real_scalar () && is_handle (val.double_value ()))
retval = true;
else if (val.is_numeric_type () && val.is_real_type ())
{
const NDArray handles = val.array_value ();
if (! error_state)
{
boolNDArray result (handles.dims ());
for (octave_idx_type i = 0; i < handles.numel (); i++)
result.xelem (i) = is_handle (handles (i));
retval = result;
}
}
return retval;
}
static bool
is_figure (double val)
{
graphics_object obj = gh_manager::get_object (val);
return obj && obj.isa ("figure");
}
static void
xcreatefcn (const graphics_handle& h)
{
graphics_object obj = gh_manager::get_object (h);
obj.get_properties ().execute_createfcn ();
}
static void
xinitialize (const graphics_handle& h)
{
graphics_object go = gh_manager::get_object (h);
if (go)
go.initialize ();
}
// ---------------------------------------------------------------------
void
base_graphics_toolkit::update (const graphics_handle& h, int id)
{
graphics_object go = gh_manager::get_object (h);
update (go, id);
}
bool
base_graphics_toolkit::initialize (const graphics_handle& h)
{
graphics_object go = gh_manager::get_object (h);
return initialize (go);
}
void
base_graphics_toolkit::finalize (const graphics_handle& h)
{
graphics_object go = gh_manager::get_object (h);
finalize (go);
}
// ---------------------------------------------------------------------
void
base_properties::set_from_list (base_graphics_object& obj,
property_list& defaults)
{
std::string go_name = graphics_object_name ();
property_list::plist_map_const_iterator p = defaults.find (go_name);
if (p != defaults.end ())
{
const property_list::pval_map_type pval_map = p->second;
for (property_list::pval_map_const_iterator q = pval_map.begin ();
q != pval_map.end ();
q++)
{
std::string pname = q->first;
obj.set (pname, q->second);
if (error_state)
{
error ("error setting default property %s", pname.c_str ());
break;
}
}
}
}
octave_value
base_properties::get_dynamic (const caseless_str& name) const
{
octave_value retval;
std::map<caseless_str, property, cmp_caseless_str>::const_iterator it =
all_props.find (name);
if (it != all_props.end ())
retval = it->second.get ();
else
error ("get: unknown property \"%s\"", name.c_str ());
return retval;
}
octave_value
base_properties::get_dynamic (bool all) const
{
octave_scalar_map m;
for (std::map<caseless_str, property, cmp_caseless_str>::const_iterator
it = all_props.begin (); it != all_props.end (); ++it)
if (all || ! it->second.is_hidden ())
m.assign (it->second.get_name (), it->second.get ());
return m;
}
std::set<std::string>
base_properties::dynamic_property_names (void) const
{
return dynamic_properties;
}
bool
base_properties::has_dynamic_property (const std::string& pname)
{
const std::set<std::string>& dynprops = dynamic_property_names ();
if (dynprops.find (pname) != dynprops.end ())
return true;
else
return all_props.find (pname) != all_props.end ();
}
void
base_properties::set_dynamic (const caseless_str& pname,
const octave_value& val)
{
std::map<caseless_str, property, cmp_caseless_str>::iterator it =
all_props.find (pname);
if (it != all_props.end ())
it->second.set (val);
else
error ("set: unknown property \"%s\"", pname.c_str ());
if (! error_state)
{
dynamic_properties.insert (pname);
mark_modified ();
}
}
property
base_properties::get_property_dynamic (const caseless_str& name)
{
std::map<caseless_str, property, cmp_caseless_str>::const_iterator it =
all_props.find (name);
if (it == all_props.end ())
{
error ("get_property: unknown property \"%s\"", name.c_str ());
return property ();
}
else
return it->second;
}
void
base_properties::set_parent (const octave_value& val)
{
double hnp = val.double_value ();
graphics_handle new_parent = octave_NaN;
if (! error_state)
{
if (hnp == __myhandle__)
error ("set: can not set object parent to be object itself");
else
{
new_parent = gh_manager::lookup (hnp);
if (new_parent.ok ())
{
// Remove child from current parent
graphics_object old_parent_obj;
old_parent_obj = gh_manager::get_object (get_parent ());
old_parent_obj.remove_child (__myhandle__);
// Check new parent's parent is not this child to avoid recursion
graphics_object new_parent_obj;
new_parent_obj = gh_manager::get_object (new_parent);
if (new_parent_obj.get_parent () == __myhandle__)
{
// new parent's parent gets child's original parent
new_parent_obj.get_properties ().set_parent (get_parent ().as_octave_value ());
}
// Set parent property to new_parent and do adoption
parent = new_parent.as_octave_value ();
::adopt (parent.handle_value (), __myhandle__);
}
else
error ("set: invalid graphics handle (= %g) for parent", hnp);
}
}
else
error ("set: expecting parent to be a graphics handle");
}
void
base_properties::mark_modified (void)
{
__modified__ = "on";
graphics_object parent_obj = gh_manager::get_object (get_parent ());
if (parent_obj)
parent_obj.mark_modified ();
}
void
base_properties::override_defaults (base_graphics_object& obj)
{
graphics_object parent_obj = gh_manager::get_object (get_parent ());
if (parent_obj)
parent_obj.override_defaults (obj);
}
void
base_properties::update_axis_limits (const std::string& axis_type) const
{
graphics_object obj = gh_manager::get_object (__myhandle__);
if (obj)
obj.update_axis_limits (axis_type);
}
void
base_properties::update_axis_limits (const std::string& axis_type,
const graphics_handle& h) const
{
graphics_object obj = gh_manager::get_object (__myhandle__);
if (obj)
obj.update_axis_limits (axis_type, h);
}
bool
base_properties::is_handle_visible (void) const
{
return (handlevisibility.is ("on")
|| (executing_callback && ! handlevisibility.is ("off")));
}
graphics_toolkit
base_properties::get_toolkit (void) const
{
graphics_object go = gh_manager::get_object (get_parent ());
if (go)
return go.get_toolkit ();
else
return graphics_toolkit ();
}
void
base_properties::update_boundingbox (void)
{
Matrix kids = get_children ();
for (int i = 0; i < kids.numel (); i++)
{
graphics_object go = gh_manager::get_object (kids(i));
if (go.valid_object ())
go.get_properties ().update_boundingbox ();
}
}
void
base_properties::update_autopos (const std::string& elem_type)
{
graphics_object parent_obj = gh_manager::get_object (get_parent ());
if (parent_obj.valid_object ())
parent_obj.get_properties ().update_autopos (elem_type);
}
void
base_properties::add_listener (const caseless_str& nm, const octave_value& v,
listener_mode mode)
{
property p = get_property (nm);
if (! error_state && p.ok ())
p.add_listener (v, mode);
}
void
base_properties::delete_listener (const caseless_str& nm,
const octave_value& v, listener_mode mode)
{
property p = get_property (nm);
if (! error_state && p.ok ())
p.delete_listener (v, mode);
}
// ---------------------------------------------------------------------
void
base_graphics_object::update_axis_limits (const std::string& axis_type)
{
if (valid_object ())
{
graphics_object parent_obj = gh_manager::get_object (get_parent ());
if (parent_obj)
parent_obj.update_axis_limits (axis_type);
}
else
error ("base_graphics_object::update_axis_limits: invalid graphics object");
}
void
base_graphics_object::update_axis_limits (const std::string& axis_type,
const graphics_handle& h)
{
if (valid_object ())
{
graphics_object parent_obj = gh_manager::get_object (get_parent ());
if (parent_obj)
parent_obj.update_axis_limits (axis_type, h);
}
else
error ("base_graphics_object::update_axis_limits: invalid graphics object");
}
void
base_graphics_object::remove_all_listeners (void)
{
octave_map m = get (true).map_value ();
for (octave_map::const_iterator pa = m.begin (); pa != m.end (); pa++)
{
// FIXME: there has to be a better way. I think we want to
// ask whether it is OK to delete the listener for the given
// property. How can we know in advance that it will be OK?
unwind_protect frame;
frame.protect_var (error_state);
frame.protect_var (discard_error_messages);
frame.protect_var (Vdebug_on_error);
frame.protect_var (Vdebug_on_warning);
discard_error_messages = true;
Vdebug_on_error = false;
Vdebug_on_warning = false;
property p = get_properties ().get_property (pa->first);
if (! error_state && p.ok ())
p.delete_listener ();
}
}
std::string
base_graphics_object::values_as_string (void)
{
std::string retval;
if (valid_object ())
{
octave_map m = get ().map_value ();
for (octave_map::const_iterator pa = m.begin (); pa != m.end (); pa++)
{
if (pa->first != "children")
{
property p = get_properties ().get_property (pa->first);
if (p.ok () && ! p.is_hidden ())
{
retval += "\n\t" + std::string (pa->first) + ": ";
if (p.is_radio ())
retval += p.values_as_string ();
}
}
}
if (retval != "")
retval += "\n";
}
else
error ("base_graphics_object::values_as_string: invalid graphics object");
return retval;
}
octave_scalar_map
base_graphics_object::values_as_struct (void)
{
octave_scalar_map retval;
if (valid_object ())
{
octave_scalar_map m = get ().scalar_map_value ();
for (octave_scalar_map::const_iterator pa = m.begin ();
pa != m.end (); pa++)
{
if (pa->first != "children")
{
property p = get_properties ().get_property (pa->first);
if (p.ok () && ! p.is_hidden ())
{
if (p.is_radio ())
retval.assign (p.get_name (), p.values_as_cell ());
else
retval.assign (p.get_name (), Cell ());
}
}
}
}
else
error ("base_graphics_object::values_as_struct: invalid graphics object");
return retval;
}
graphics_object
graphics_object::get_ancestor (const std::string& obj_type) const
{
if (valid_object ())
{
if (isa (obj_type))
return *this;
else
return gh_manager::get_object (get_parent ()).get_ancestor (obj_type);
}
else
return graphics_object ();
}
// ---------------------------------------------------------------------
#include "graphics-props.cc"
// ---------------------------------------------------------------------
void
root_figure::properties::set_currentfigure (const octave_value& v)
{
graphics_handle val (v);
if (error_state)
return;
if (xisnan (val.value ()) || is_handle (val))
{
currentfigure = val;
if (val.ok ())
gh_manager::push_figure (val);
}
else
gripe_set_invalid ("currentfigure");
}
void
root_figure::properties::set_callbackobject (const octave_value& v)
{
graphics_handle val (v);
if (error_state)
return;
if (xisnan (val.value ()))
{
if (! cbo_stack.empty ())
{
val = cbo_stack.front ();
cbo_stack.pop_front ();
}
callbackobject = val;
}
else if (is_handle (val))
{
if (get_callbackobject ().ok ())
cbo_stack.push_front (get_callbackobject ());
callbackobject = val;
}
else
gripe_set_invalid ("callbackobject");
}
void
figure::properties::set_integerhandle (const octave_value& val)
{
if (! error_state)
{
if (integerhandle.set (val, true))
{
bool int_fig_handle = integerhandle.is_on ();
graphics_object this_go = gh_manager::get_object (__myhandle__);
graphics_handle old_myhandle = __myhandle__;
__myhandle__ = gh_manager::get_handle (int_fig_handle);
gh_manager::renumber_figure (old_myhandle, __myhandle__);
graphics_object parent_go = gh_manager::get_object (get_parent ());
base_properties& props = parent_go.get_properties ();
props.renumber_child (old_myhandle, __myhandle__);
Matrix kids = get_children ();
for (octave_idx_type i = 0; i < kids.numel (); i++)
{
graphics_object kid = gh_manager::get_object (kids(i));
kid.get_properties ().renumber_parent (__myhandle__);
}
graphics_handle cf = gh_manager::current_figure ();
if (__myhandle__ == cf)
xset (0, "currentfigure", __myhandle__.value ());
this_go.update (integerhandle.get_id ());
mark_modified ();
}
}
}
// FIXME: This should update monitorpositions and pointerlocation, but
// as these properties are yet used, and so it doesn't matter that they
// aren't set yet.
void
root_figure::properties::update_units (void)
{
caseless_str xunits = get_units ();
Matrix ss = default_screensize ();
double dpi = get_screenpixelsperinch ();
if (xunits.compare ("inches"))
{
ss(0) = 0;
ss(1) = 0;
ss(2) /= dpi;
ss(3) /= dpi;
}
else if (xunits.compare ("centimeters"))
{
ss(0) = 0;
ss(1) = 0;
ss(2) *= 2.54 / dpi;
ss(3) *= 2.54 / dpi;
}
else if (xunits.compare ("normalized"))
{
ss = Matrix (1, 4, 1.0);
ss(0) = 0;
ss(1) = 0;
}
else if (xunits.compare ("points"))
{
ss(0) = 0;
ss(1) = 0;
ss(2) *= 72 / dpi;
ss(3) *= 72 / dpi;
}
set_screensize (ss);
}
Matrix
root_figure::properties::get_boundingbox (bool, const Matrix&) const
{
Matrix screen_size = screen_size_pixels ();
Matrix pos = Matrix (1, 4, 0);
pos(2) = screen_size(0);
pos(3) = screen_size(1);
return pos;
}
/*
%!test
%! old_units = get (0, "units");
%! unwind_protect
%! set (0, "units", "pixels");
%! sz = get (0, "screensize") - [1, 1, 0, 0];
%! dpi = get (0, "screenpixelsperinch");
%! set (0, "units", "inches");
%! assert (get (0, "screensize"), sz / dpi, 0.5 / dpi);
%! set (0, "units", "centimeters");
%! assert (get (0, "screensize"), sz / dpi * 2.54, 0.5 / dpi * 2.54);
%! set (0, "units", "points");
%! assert (get (0, "screensize"), sz / dpi * 72, 0.5 / dpi * 72);
%! set (0, "units", "normalized");
%! assert (get (0, "screensize"), [0.0, 0.0, 1.0, 1.0]);
%! set (0, "units", "pixels");
%! assert (get (0, "screensize"), sz + [1, 1, 0, 0]);
%! unwind_protect_cleanup
%! set (0, "units", old_units);
%! end_unwind_protect
*/
void
root_figure::properties::remove_child (const graphics_handle& gh)
{
gh_manager::pop_figure (gh);
graphics_handle cf = gh_manager::current_figure ();
xset (0, "currentfigure", cf.value ());
base_properties::remove_child (gh);
}
property_list
root_figure::factory_properties = root_figure::init_factory_properties ();
static void
reset_default_properties (property_list& default_properties)
{
property_list new_defaults;
for (property_list::plist_map_const_iterator p = default_properties.begin ();
p != default_properties.end (); p++)
{
const property_list::pval_map_type pval_map = p->second;
std::string prefix = p->first;
for (property_list::pval_map_const_iterator q = pval_map.begin ();
q != pval_map.end ();
q++)
{
std::string s = q->first;
if (prefix == "axes" && (s == "position" || s == "units"))
new_defaults.set (prefix + s, q->second);
else if (prefix == "figure" && (s == "position" || s == "units"
|| s == "windowstyle"
|| s == "paperunits"))
new_defaults.set (prefix + s, q->second);
}
}
default_properties = new_defaults;
}
void
root_figure::reset_default_properties (void)
{
::reset_default_properties (default_properties);
}
// ---------------------------------------------------------------------
void
figure::properties::set_currentaxes (const octave_value& v)
{
graphics_handle val (v);
if (error_state)
return;
if (xisnan (val.value ()) || is_handle (val))
currentaxes = val;
else
gripe_set_invalid ("currentaxes");
}
void
figure::properties::remove_child (const graphics_handle& gh)
{
base_properties::remove_child (gh);
if (gh == currentaxes.handle_value ())
{
graphics_handle new_currentaxes;
Matrix kids = get_children ();
for (octave_idx_type i = 0; i < kids.numel (); i++)
{
graphics_handle kid = kids(i);
graphics_object go = gh_manager::get_object (kid);
if (go.isa ("axes"))
{
new_currentaxes = kid;
break;
}
}
currentaxes = new_currentaxes;
}
}
void
figure::properties::set_visible (const octave_value& val)
{
std::string s = val.string_value ();
if (! error_state)
{
if (s == "on")
xset (0, "currentfigure", __myhandle__.value ());
visible = val;
}
}
Matrix
figure::properties::get_boundingbox (bool internal, const Matrix&) const
{
Matrix screen_size = screen_size_pixels ();
Matrix pos = (internal ?
get_position ().matrix_value () :
get_outerposition ().matrix_value ());
pos = convert_position (pos, get_units (), "pixels", screen_size);
pos(0)--;
pos(1)--;
pos(1) = screen_size(1) - pos(1) - pos(3);
return pos;
}
void
figure::properties::set_boundingbox (const Matrix& bb, bool internal,
bool do_notify_toolkit)
{
Matrix screen_size = screen_size_pixels ();
Matrix pos = bb;
pos(1) = screen_size(1) - pos(1) - pos(3);
pos(1)++;
pos(0)++;
pos = convert_position (pos, "pixels", get_units (), screen_size);
if (internal)
set_position (pos, do_notify_toolkit);
else
set_outerposition (pos, do_notify_toolkit);
}
Matrix
figure::properties::map_from_boundingbox (double x, double y) const
{
Matrix bb = get_boundingbox (true);
Matrix pos (1, 2, 0);
pos(0) = x;
pos(1) = y;
pos(1) = bb(3) - pos(1);
pos(0)++;
pos = convert_position (pos, "pixels", get_units (),
bb.extract_n (0, 2, 1, 2));
return pos;
}
Matrix
figure::properties::map_to_boundingbox (double x, double y) const
{
Matrix bb = get_boundingbox (true);
Matrix pos (1, 2, 0);
pos(0) = x;
pos(1) = y;
pos = convert_position (pos, get_units (), "pixels",
bb.extract_n (0, 2, 1, 2));
pos(0)--;
pos(1) = bb(3) - pos(1);
return pos;
}
void
figure::properties::set_position (const octave_value& v,
bool do_notify_toolkit)
{
if (! error_state)
{
Matrix old_bb, new_bb;
bool modified = false;
old_bb = get_boundingbox (true);
modified = position.set (v, false, do_notify_toolkit);
new_bb = get_boundingbox (true);
if (old_bb != new_bb)
{
if (old_bb(2) != new_bb(2) || old_bb(3) != new_bb(3))
{
execute_resizefcn ();
update_boundingbox ();
}
}
if (modified)
{
position.run_listeners (POSTSET);
mark_modified ();
}
}
}
void
figure::properties::set_outerposition (const octave_value& v,
bool do_notify_toolkit)
{
if (! error_state)
{
if (outerposition.set (v, true, do_notify_toolkit))
{
mark_modified ();
}
}
}
void
figure::properties::set_paperunits (const octave_value& v)
{
if (! error_state)
{
caseless_str typ = get_papertype ();
caseless_str punits = v.string_value ();
if (! error_state)
{
if (punits.compare ("normalized") && typ.compare ("<custom>"))
error ("set: can't set the paperunits to normalized when the papertype is custom");
else
{
caseless_str old_paperunits = get_paperunits ();
if (paperunits.set (v, true))
{
update_paperunits (old_paperunits);
mark_modified ();
}
}
}
}
}
void
figure::properties::set_papertype (const octave_value& v)
{
if (! error_state)
{
caseless_str typ = v.string_value ();
caseless_str punits = get_paperunits ();
if (! error_state)
{
if (punits.compare ("normalized") && typ.compare ("<custom>"))
error ("set: can't set the paperunits to normalized when the papertype is custom");
else
{
if (papertype.set (v, true))
{
update_papertype ();
mark_modified ();
}
}
}
}
}
static Matrix
papersize_from_type (const caseless_str punits, const caseless_str typ)
{
Matrix ret (1, 2, 1.0);
if (! punits.compare ("normalized"))
{
double in2units;
double mm2units;
if (punits.compare ("inches"))
{
in2units = 1.0;
mm2units = 1 / 25.4 ;
}
else if (punits.compare ("centimeters"))
{
in2units = 2.54;
mm2units = 1 / 10.0;
}
else // points
{
in2units = 72.0;
mm2units = 72.0 / 25.4;
}
if (typ.compare ("usletter"))
{
ret (0) = 8.5 * in2units;
ret (1) = 11.0 * in2units;
}
else if (typ.compare ("uslegal"))
{
ret (0) = 8.5 * in2units;
ret (1) = 14.0 * in2units;
}
else if (typ.compare ("tabloid"))
{
ret (0) = 11.0 * in2units;
ret (1) = 17.0 * in2units;
}
else if (typ.compare ("a0"))
{
ret (0) = 841.0 * mm2units;
ret (1) = 1189.0 * mm2units;
}
else if (typ.compare ("a1"))
{
ret (0) = 594.0 * mm2units;
ret (1) = 841.0 * mm2units;
}
else if (typ.compare ("a2"))
{
ret (0) = 420.0 * mm2units;
ret (1) = 594.0 * mm2units;
}
else if (typ.compare ("a3"))
{
ret (0) = 297.0 * mm2units;
ret (1) = 420.0 * mm2units;
}
else if (typ.compare ("a4"))
{
ret (0) = 210.0 * mm2units;
ret (1) = 297.0 * mm2units;
}
else if (typ.compare ("a5"))
{
ret (0) = 148.0 * mm2units;
ret (1) = 210.0 * mm2units;
}
else if (typ.compare ("b0"))
{
ret (0) = 1029.0 * mm2units;
ret (1) = 1456.0 * mm2units;
}
else if (typ.compare ("b1"))
{
ret (0) = 728.0 * mm2units;
ret (1) = 1028.0 * mm2units;
}
else if (typ.compare ("b2"))
{
ret (0) = 514.0 * mm2units;
ret (1) = 728.0 * mm2units;
}
else if (typ.compare ("b3"))
{
ret (0) = 364.0 * mm2units;
ret (1) = 514.0 * mm2units;
}
else if (typ.compare ("b4"))
{
ret (0) = 257.0 * mm2units;
ret (1) = 364.0 * mm2units;
}
else if (typ.compare ("b5"))
{
ret (0) = 182.0 * mm2units;
ret (1) = 257.0 * mm2units;
}
else if (typ.compare ("arch-a"))
{
ret (0) = 9.0 * in2units;
ret (1) = 12.0 * in2units;
}
else if (typ.compare ("arch-b"))
{
ret (0) = 12.0 * in2units;
ret (1) = 18.0 * in2units;
}
else if (typ.compare ("arch-c"))
{
ret (0) = 18.0 * in2units;
ret (1) = 24.0 * in2units;
}
else if (typ.compare ("arch-d"))
{
ret (0) = 24.0 * in2units;
ret (1) = 36.0 * in2units;
}
else if (typ.compare ("arch-e"))
{
ret (0) = 36.0 * in2units;
ret (1) = 48.0 * in2units;
}
else if (typ.compare ("a"))
{
ret (0) = 8.5 * in2units;
ret (1) = 11.0 * in2units;
}
else if (typ.compare ("b"))
{
ret (0) = 11.0 * in2units;
ret (1) = 17.0 * in2units;
}
else if (typ.compare ("c"))
{
ret (0) = 17.0 * in2units;
ret (1) = 22.0 * in2units;
}
else if (typ.compare ("d"))
{
ret (0) = 22.0 * in2units;
ret (1) = 34.0 * in2units;
}
else if (typ.compare ("e"))
{
ret (0) = 34.0 * in2units;
ret (1) = 43.0 * in2units;
}
}
return ret;
}
void
figure::properties::update_paperunits (const caseless_str& old_paperunits)
{
Matrix pos = get_paperposition ().matrix_value ();
Matrix sz = get_papersize ().matrix_value ();
pos(0) /= sz(0);
pos(1) /= sz(1);
pos(2) /= sz(0);
pos(3) /= sz(1);
std::string porient = get_paperorientation ();
caseless_str punits = get_paperunits ();
caseless_str typ = get_papertype ();
if (typ.compare ("<custom>"))
{
if (old_paperunits.compare ("centimeters"))
{
sz(0) /= 2.54;
sz(1) /= 2.54;
}
else if (old_paperunits.compare ("points"))
{
sz(0) /= 72.0;
sz(1) /= 72.0;
}
if (punits.compare ("centimeters"))
{
sz(0) *= 2.54;
sz(1) *= 2.54;
}
else if (punits.compare ("points"))
{
sz(0) *= 72.0;
sz(1) *= 72.0;
}
}
else
{
sz = papersize_from_type (punits, typ);
if (porient == "landscape")
std::swap (sz(0), sz(1));
}
pos(0) *= sz(0);
pos(1) *= sz(1);
pos(2) *= sz(0);
pos(3) *= sz(1);
papersize.set (octave_value (sz));
paperposition.set (octave_value (pos));
}
void
figure::properties::update_papertype (void)
{
caseless_str typ = get_papertype ();
if (! typ.compare ("<custom>"))
{
Matrix sz = papersize_from_type (get_paperunits (), typ);
if (get_paperorientation () == "landscape")
std::swap (sz(0), sz(1));
// Call papersize.set rather than set_papersize to avoid loops
// between update_papersize and update_papertype
papersize.set (octave_value (sz));
}
}
void
figure::properties::update_papersize (void)
{
Matrix sz = get_papersize ().matrix_value ();
if (sz(0) > sz(1))
{
std::swap (sz(0), sz(1));
papersize.set (octave_value (sz));
paperorientation.set (octave_value ("landscape"));
}
else
{
paperorientation.set ("portrait");
}
std::string punits = get_paperunits ();
if (punits == "centimeters")
{
sz(0) /= 2.54;
sz(1) /= 2.54;
}
else if (punits == "points")
{
sz(0) /= 72.0;
sz(1) /= 72.0;
}
if (punits == "normalized")
{
caseless_str typ = get_papertype ();
if (get_papertype () == "<custom>")
error ("set: can't set the papertype to <custom> when the paperunits is normalized");
}
else
{
// TODO - the papersizes info is also in papersize_from_type().
// Both should be rewritten to avoid the duplication.
std::string typ = "<custom>";
const double mm2in = 1.0 / 25.4;
const double tol = 0.01;
if (std::abs (sz(0) - 8.5) + std::abs (sz(1) - 11.0) < tol)
typ = "usletter";
else if (std::abs (sz(0) - 8.5) + std::abs (sz(1) - 14.0) < tol)
typ = "uslegal";
else if (std::abs (sz(0) - 11.0) + std::abs (sz(1) - 17.0) < tol)
typ = "tabloid";
else if (std::abs (sz(0) - 841.0 * mm2in)
+ std::abs (sz(1) - 1198.0 * mm2in) < tol)
typ = "a0";
else if (std::abs (sz(0) - 594.0 * mm2in)
+ std::abs (sz(1) - 841.0 * mm2in) < tol)
typ = "a1";
else if (std::abs (sz(0) - 420.0 * mm2in)
+ std::abs (sz(1) - 594.0 * mm2in) < tol)
typ = "a2";
else if (std::abs (sz(0) - 297.0 * mm2in)
+ std::abs (sz(1) - 420.0 * mm2in) < tol)
typ = "a3";
else if (std::abs (sz(0) - 210.0 * mm2in)
+ std::abs (sz(1) - 297.0 * mm2in) < tol)
typ = "a4";
else if (std::abs (sz(0) - 148.0 * mm2in)
+ std::abs (sz(1) - 210.0 * mm2in) < tol)
typ = "a5";
else if (std::abs (sz(0) - 1029.0 * mm2in)
+ std::abs (sz(1) - 1456.0 * mm2in) < tol)
typ = "b0";
else if (std::abs (sz(0) - 728.0 * mm2in)
+ std::abs (sz(1) - 1028.0 * mm2in) < tol)
typ = "b1";
else if (std::abs (sz(0) - 514.0 * mm2in)
+ std::abs (sz(1) - 728.0 * mm2in) < tol)
typ = "b2";
else if (std::abs (sz(0) - 364.0 * mm2in)
+ std::abs (sz(1) - 514.0 * mm2in) < tol)
typ = "b3";
else if (std::abs (sz(0) - 257.0 * mm2in)
+ std::abs (sz(1) - 364.0 * mm2in) < tol)
typ = "b4";
else if (std::abs (sz(0) - 182.0 * mm2in)
+ std::abs (sz(1) - 257.0 * mm2in) < tol)
typ = "b5";
else if (std::abs (sz(0) - 9.0)
+ std::abs (sz(1) - 12.0) < tol)
typ = "arch-a";
else if (std::abs (sz(0) - 12.0)
+ std::abs (sz(1) - 18.0) < tol)
typ = "arch-b";
else if (std::abs (sz(0) - 18.0)
+ std::abs (sz(1) - 24.0) < tol)
typ = "arch-c";
else if (std::abs (sz(0) - 24.0)
+ std::abs (sz(1) - 36.0) < tol)
typ = "arch-d";
else if (std::abs (sz(0) - 36.0)
+ std::abs (sz(1) - 48.0) < tol)
typ = "arch-e";
else if (std::abs (sz(0) - 8.5)
+ std::abs (sz(1) - 11.0) < tol)
typ = "a";
else if (std::abs (sz(0) - 11.0)
+ std::abs (sz(1) - 17.0) < tol)
typ = "b";
else if (std::abs (sz(0) - 17.0)
+ std::abs (sz(1) - 22.0) < tol)
typ = "c";
else if (std::abs (sz(0) - 22.0)
+ std::abs (sz(1) - 34.0) < tol)
typ = "d";
else if (std::abs (sz(0) - 34.0)
+ std::abs (sz(1) - 43.0) < tol)
typ = "e";
// Call papertype.set rather than set_papertype to avoid loops between
// update_papersize and update_papertype
papertype.set (typ);
}
if (punits == "centimeters")
{
sz(0) *= 2.54;
sz(1) *= 2.54;
}
else if (punits == "points")
{
sz(0) *= 72.0;
sz(1) *= 72.0;
}
if (get_paperorientation () == "landscape")
{
std::swap (sz(0), sz(1));
papersize.set (octave_value (sz));
}
}
/*
%!test
%! hf = figure ("visible", "off");
%! unwind_protect
%! set (hf, "paperunits", "inches");
%! set (hf, "papersize", [5, 4]);
%! set (hf, "paperunits", "points");
%! assert (get (hf, "papersize"), [5, 4] * 72, 1);
%! papersize = get (hf, "papersize");
%! set (hf, "papersize", papersize + 1);
%! set (hf, "papersize", papersize);
%! assert (get (hf, "papersize"), [5, 4] * 72, 1);
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
%!test
%! hf = figure ("visible", "off");
%! unwind_protect
%! set (hf, "paperunits", "inches");
%! set (hf, "papersize", [5, 4]);
%! set (hf, "paperunits", "centimeters");
%! assert (get (hf, "papersize"), [5, 4] * 2.54, 2.54/72);
%! papersize = get (hf, "papersize");
%! set (hf, "papersize", papersize + 1);
%! set (hf, "papersize", papersize);
%! assert (get (hf, "papersize"), [5, 4] * 2.54, 2.54/72);
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
*/
void
figure::properties::update_paperorientation (void)
{
std::string porient = get_paperorientation ();
Matrix sz = get_papersize ().matrix_value ();
Matrix pos = get_paperposition ().matrix_value ();
if ((sz(0) > sz(1) && porient == "portrait")
|| (sz(0) < sz(1) && porient == "landscape"))
{
std::swap (sz(0), sz(1));
std::swap (pos(0), pos(1));
std::swap (pos(2), pos(3));
// Call papertype.set rather than set_papertype to avoid loops
// between update_papersize and update_papertype
papersize.set (octave_value (sz));
paperposition.set (octave_value (pos));
}
}
/*
%!test
%! hf = figure ("visible", "off");
%! unwind_protect
%! tol = 100 * eps ();
%! ## UPPER case and MiXed case is part of test and should not be changed.
%! set (hf, "paperorientation", "PORTRAIT");
%! set (hf, "paperunits", "inches");
%! set (hf, "papertype", "USletter");
%! assert (get (hf, "papersize"), [8.5, 11.0], tol);
%! set (hf, "paperorientation", "Landscape");
%! assert (get (hf, "papersize"), [11.0, 8.5], tol);
%! set (hf, "paperunits", "centimeters");
%! assert (get (hf, "papersize"), [11.0, 8.5] * 2.54, tol);
%! set (hf, "papertype", "a4");
%! assert (get (hf, "papersize"), [29.7, 21.0], tol);
%! set (hf, "paperunits", "inches", "papersize", [8.5, 11.0]);
%! assert (get (hf, "papertype"), "usletter");
%! assert (get (hf, "paperorientation"), "portrait");
%! set (hf, "papersize", [11.0, 8.5]);
%! assert (get (hf, "papertype"), "usletter");
%! assert (get (hf, "paperorientation"), "landscape");
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
*/
void
figure::properties::set_units (const octave_value& v)
{
if (! error_state)
{
caseless_str old_units = get_units ();
if (units.set (v, true))
{
update_units (old_units);
mark_modified ();
}
}
}
void
figure::properties::update_units (const caseless_str& old_units)
{
position.set (convert_position (get_position ().matrix_value (), old_units,
get_units (), screen_size_pixels ()), false);
}
/*
%!test
%! hf = figure ("visible", "off");
%! old_units = get (0, "units");
%! unwind_protect
%! set (0, "units", "pixels");
%! rsz = get (0, "screensize");
%! set (gcf (), "units", "pixels");
%! fsz = get (gcf (), "position");
%! set (gcf (), "units", "normalized");
%! pos = get (gcf (), "position");
%! assert (pos, (fsz - [1, 1, 0, 0]) ./ rsz([3, 4, 3, 4]));
%! unwind_protect_cleanup
%! close (hf);
%! set (0, "units", old_units);
%! end_unwind_protect
*/
std::string
figure::properties::get_title (void) const
{
if (is_numbertitle ())
{
std::ostringstream os;
std::string nm = get_name ();
os << "Figure " << __myhandle__.value ();
if (! nm.empty ())
os << ": " << get_name ();
return os.str ();
}
else
return get_name ();
}
octave_value
figure::get_default (const caseless_str& name) const
{
octave_value retval = default_properties.lookup (name);
if (retval.is_undefined ())
{
graphics_handle parent = get_parent ();
graphics_object parent_obj = gh_manager::get_object (parent);
retval = parent_obj.get_default (name);
}
return retval;
}
void
figure::reset_default_properties (void)
{
::reset_default_properties (default_properties);
}
// ---------------------------------------------------------------------
void
axes::properties::init (void)
{
position.add_constraint (dim_vector (1, 4));
outerposition.add_constraint (dim_vector (1, 4));
tightinset.add_constraint (dim_vector (1, 4));
looseinset.add_constraint (dim_vector (1, 4));
colororder.add_constraint (dim_vector (-1, 3));
dataaspectratio.add_constraint (dim_vector (1, 3));
plotboxaspectratio.add_constraint (dim_vector (1, 3));
alim.add_constraint (2);
clim.add_constraint (2);
xlim.add_constraint (2);
ylim.add_constraint (2);
zlim.add_constraint (2);
xtick.add_constraint (dim_vector (1, -1));
ytick.add_constraint (dim_vector (1, -1));
ztick.add_constraint (dim_vector (1, -1));
ticklength.add_constraint (dim_vector (1, 2));
Matrix vw (1, 2, 0);
vw(1) = 90;
view = vw;
view.add_constraint (dim_vector (1, 2));
cameraposition.add_constraint (dim_vector (1, 3));
cameratarget.add_constraint (dim_vector (1, 3));
Matrix upv (1, 3, 0.0);
upv(2) = 1.0;
cameraupvector = upv;
cameraupvector.add_constraint (dim_vector (1, 3));
currentpoint.add_constraint (dim_vector (2, 3));
// No constraints for hidden transform properties
update_font ();
x_zlim.resize (1, 2);
sx = "linear";
sy = "linear";
sz = "linear";
calc_ticklabels (xtick, xticklabel, xscale.is ("log"));
calc_ticklabels (ytick, yticklabel, yscale.is ("log"));
calc_ticklabels (ztick, zticklabel, zscale.is ("log"));
xset (xlabel.handle_value (), "handlevisibility", "off");
xset (ylabel.handle_value (), "handlevisibility", "off");
xset (zlabel.handle_value (), "handlevisibility", "off");
xset (title.handle_value (), "handlevisibility", "off");
xset (xlabel.handle_value (), "horizontalalignment", "center");
xset (xlabel.handle_value (), "horizontalalignmentmode", "auto");
xset (ylabel.handle_value (), "horizontalalignment", "center");
xset (ylabel.handle_value (), "horizontalalignmentmode", "auto");
xset (zlabel.handle_value (), "horizontalalignment", "right");
xset (zlabel.handle_value (), "horizontalalignmentmode", "auto");
xset (title.handle_value (), "horizontalalignment", "center");
xset (title.handle_value (), "horizontalalignmentmode", "auto");
xset (xlabel.handle_value (), "verticalalignment", "top");
xset (xlabel.handle_value (), "verticalalignmentmode", "auto");
xset (ylabel.handle_value (), "verticalalignment", "bottom");
xset (ylabel.handle_value (), "verticalalignmentmode", "auto");
xset (title.handle_value (), "verticalalignment", "bottom");
xset (title.handle_value (), "verticalalignmentmode", "auto");
xset (ylabel.handle_value (), "rotation", 90.0);
xset (ylabel.handle_value (), "rotationmode", "auto");
xset (zlabel.handle_value (), "visible", "off");
xset (xlabel.handle_value (), "clipping", "off");
xset (ylabel.handle_value (), "clipping", "off");
xset (zlabel.handle_value (), "clipping", "off");
xset (title.handle_value (), "clipping", "off");
xset (xlabel.handle_value (), "autopos_tag", "xlabel");
xset (ylabel.handle_value (), "autopos_tag", "ylabel");
xset (zlabel.handle_value (), "autopos_tag", "zlabel");
xset (title.handle_value (), "autopos_tag", "title");
adopt (xlabel.handle_value ());
adopt (ylabel.handle_value ());
adopt (zlabel.handle_value ());
adopt (title.handle_value ());
Matrix tlooseinset = default_axes_position ();
tlooseinset(2) = 1-tlooseinset(0)-tlooseinset(2);
tlooseinset(3) = 1-tlooseinset(1)-tlooseinset(3);
looseinset = tlooseinset;
}
Matrix
axes::properties::calc_tightbox (const Matrix& init_pos)
{
Matrix pos = init_pos;
graphics_object obj = gh_manager::get_object (get_parent ());
Matrix parent_bb = obj.get_properties ().get_boundingbox (true);
Matrix ext = get_extent (true, true);
ext(1) = parent_bb(3) - ext(1) - ext(3);
ext(0)++;
ext(1)++;
ext = convert_position (ext, "pixels", get_units (),
parent_bb.extract_n (0, 2, 1, 2));
if (ext(0) < pos(0))
{
pos(2) += pos(0)-ext(0);
pos(0) = ext(0);
}
if (ext(0)+ext(2) > pos(0)+pos(2))
pos(2) = ext(0)+ext(2)-pos(0);
if (ext(1) < pos(1))
{
pos(3) += pos(1)-ext(1);
pos(1) = ext(1);
}
if (ext(1)+ext(3) > pos(1)+pos(3))
pos(3) = ext(1)+ext(3)-pos(1);
return pos;
}
void
axes::properties::sync_positions (void)
{
// First part is equivalent to `update_tightinset ()'
if (activepositionproperty.is ("position"))
update_position ();
else
update_outerposition ();
caseless_str old_units = get_units ();
set_units ("normalized");
Matrix pos = position.get ().matrix_value ();
Matrix outpos = outerposition.get ().matrix_value ();
Matrix tightpos = calc_tightbox (pos);
Matrix tinset (1, 4, 1.0);
tinset(0) = pos(0)-tightpos(0);
tinset(1) = pos(1)-tightpos(1);
tinset(2) = tightpos(0)+tightpos(2)-pos(0)-pos(2);
tinset(3) = tightpos(1)+tightpos(3)-pos(1)-pos(3);
tightinset = tinset;
set_units (old_units);
update_transform ();
if (activepositionproperty.is ("position"))
update_position ();
else
update_outerposition ();
}
/*
%!testif HAVE_FLTK
%! hf = figure ("visible", "off");
%! graphics_toolkit (hf, "fltk");
%! unwind_protect
%! subplot(2,1,1); plot(rand(10,1)); subplot(2,1,2); plot(rand(10,1));
%! hax = findall (gcf (), "type", "axes");
%! positions = cell2mat (get (hax, "position"));
%! outerpositions = cell2mat (get (hax, "outerposition"));
%! looseinsets = cell2mat (get (hax, "looseinset"));
%! tightinsets = cell2mat (get (hax, "tightinset"));
%! subplot(2,1,1); plot(rand(10,1)); subplot(2,1,2); plot(rand(10,1));
%! hax = findall (gcf (), "type", "axes");
%! assert (cell2mat (get (hax, "position")), positions, 1e-4);
%! assert (cell2mat (get (hax, "outerposition")), outerpositions, 1e-4);
%! assert (cell2mat (get (hax, "looseinset")), looseinsets, 1e-4);
%! assert (cell2mat (get (hax, "tightinset")), tightinsets, 1e-4);
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
%!testif HAVE_FLTK
%! hf = figure ("visible", "off");
%! graphics_toolkit (hf, "fltk");
%! fpos = get (hf, "position");
%! unwind_protect
%! plot (rand (3))
%! position = get (gca, "position");
%! outerposition = get (gca, "outerposition");
%! looseinset = get (gca, "looseinset");
%! tightinset = get (gca, "tightinset");
%! set (hf, "position", [fpos(1:2), 2*fpos(3:4)])
%! set (hf, "position", fpos);
%! assert (get (gca, "outerposition"), outerposition, 0.001)
%! assert (get (gca, "position"), position, 0.001)
%! assert (get (gca, "looseinset"), looseinset, 0.001)
%! assert (get (gca, "tightinset"), tightinset, 0.001)
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
%!testif HAVE_FLTK
%! hf = figure ("visible", "off");
%! graphics_toolkit (hf, "fltk");
%! fpos = get (hf, "position");
%! set (gca, "activepositionproperty", "position")
%! unwind_protect
%! plot (rand (3))
%! position = get (gca, "position");
%! outerposition = get (gca, "outerposition");
%! looseinset = get (gca, "looseinset");
%! tightinset = get (gca, "tightinset");
%! set (hf, "position", [fpos(1:2), 2*fpos(3:4)])
%! set (hf, "position", fpos);
%! assert (get (gca, "position"), position, 0.001)
%! assert (get (gca, "outerposition"), outerposition, 0.001)
%! assert (get (gca, "looseinset"), looseinset, 0.001)
%! assert (get (gca, "tightinset"), tightinset, 0.001)
%! unwind_protect_cleanup
%! close (hf);
%! end_unwind_protect
*/
void
axes::properties::set_text_child (handle_property& hp,
const std::string& who,
const octave_value& v)
{
graphics_handle val;
if (v.is_string ())
{
val = gh_manager::make_graphics_handle ("text", __myhandle__,
false, false);
xset (val, "string", v);
}
else
{
graphics_object go = gh_manager::get_object (gh_manager::lookup (v));
if (go.isa ("text"))
val = ::reparent (v, "set", who, __myhandle__, false);
else
{
std::string cname = v.class_name ();
error ("set: expecting text graphics object or character string for %s property, found %s",
who.c_str (), cname.c_str ());
}
}
if (! error_state)
{
xset (val, "handlevisibility", "off");
gh_manager::free (hp.handle_value ());
base_properties::remove_child (hp.handle_value ());
hp = val;
adopt (hp.handle_value ());
}
}
void
axes::properties::set_xlabel (const octave_value& v)
{
set_text_child (xlabel, "xlabel", v);
xset (xlabel.handle_value (), "positionmode", "auto");
xset (xlabel.handle_value (), "rotationmode", "auto");
xset (xlabel.handle_value (), "horizontalalignmentmode", "auto");
xset (xlabel.handle_value (), "verticalalignmentmode", "auto");
xset (xlabel.handle_value (), "clipping", "off");
xset (xlabel.handle_value (), "color", get_xcolor ());
xset (xlabel.handle_value (), "autopos_tag", "xlabel");
update_xlabel_position ();
}
void
axes::properties::set_ylabel (const octave_value& v)
{
set_text_child (ylabel, "ylabel", v);
xset (ylabel.handle_value (), "positionmode", "auto");
xset (ylabel.handle_value (), "rotationmode", "auto");
xset (ylabel.handle_value (), "horizontalalignmentmode", "auto");
xset (ylabel.handle_value (), "verticalalignmentmode", "auto");
xset (ylabel.handle_value (), "clipping", "off");
xset (ylabel.handle_value (), "color", get_ycolor ());
xset (ylabel.handle_value (), "autopos_tag", "ylabel");
update_ylabel_position ();
}
void
axes::properties::set_zlabel (const octave_value& v)
{
set_text_child (zlabel, "zlabel", v);
xset (zlabel.handle_value (), "positionmode", "auto");
xset (zlabel.handle_value (), "rotationmode", "auto");
xset (zlabel.handle_value (), "horizontalalignmentmode", "auto");
xset (zlabel.handle_value (), "verticalalignmentmode", "auto");
xset (zlabel.handle_value (), "clipping", "off");
xset (zlabel.handle_value (), "color", get_zcolor ());
xset (zlabel.handle_value (), "autopos_tag", "zlabel");
update_zlabel_position ();
}
void
axes::properties::set_title (const octave_value& v)
{
set_text_child (title, "title", v);
xset (title.handle_value (), "positionmode", "auto");
xset (title.handle_value (), "horizontalalignment", "center");
xset (title.handle_value (), "horizontalalignmentmode", "auto");
xset (title.handle_value (), "verticalalignment", "bottom");
xset (title.handle_value (), "verticalalignmentmode", "auto");
xset (title.handle_value (), "clipping", "off");
xset (title.handle_value (), "autopos_tag", "title");
update_title_position ();
}
void
axes::properties::set_defaults (base_graphics_object& obj,
const std::string& mode)
{
box = "on";
colororder = default_colororder ();
// Note: dataspectratio will be set through update_aspectratios
dataaspectratiomode = "auto";
layer = "bottom";
Matrix tlim (1, 2, 0.0);
tlim(1) = 1;
xlim = tlim;
ylim = tlim;
zlim = tlim;
Matrix cl (1, 2, 0);
cl(1) = 1;
clim = cl;
alim = tlim;
xlimmode = "auto";
ylimmode = "auto";
zlimmode = "auto";
climmode = "auto";
alimmode = "auto";
xgrid = "off";
ygrid = "off";
zgrid = "off";
xminorgrid = "off";
yminorgrid = "off";
zminorgrid = "off";
xtick = Matrix ();
ytick = Matrix ();
ztick = Matrix ();
xtickmode = "auto";
ytickmode = "auto";
ztickmode = "auto";
xminortick = "off";
yminortick = "off";
zminortick = "off";
xticklabel = "";
yticklabel = "";
zticklabel = "";
xticklabelmode = "auto";
yticklabelmode = "auto";
zticklabelmode = "auto";
interpreter = "none";
color = color_values ("white");
xcolor = color_values ("black");
ycolor = color_values ("black");
zcolor = color_values ("black");
xscale = "linear";
yscale = "linear";
zscale = "linear";
xdir = "normal";
ydir = "normal";
zdir = "normal";
yaxislocation = "left";
xaxislocation = "bottom";
Matrix tview (1, 2, 0.0);
tview(1) = 90;
view = tview;
__hold_all__ = "off";
nextplot = "replace";
ambientlightcolor = Matrix (1, 3, 1.0);
// Note: camera properties (not mode) will be set in update_transform
camerapositionmode = "auto";
cameratargetmode = "auto";
cameraupvectormode = "auto";
cameraviewanglemode = "auto";
drawmode = "normal";
fontangle = "normal";
fontname = OCTAVE_DEFAULT_FONTNAME;
fontsize = 10;
fontunits = "points";
fontweight = "normal";
gridlinestyle = ":";
linestyleorder = "-";
linewidth = 0.5;
minorgridlinestyle = ":";
// Note: plotboxaspectratio will be set through update_aspectratios
plotboxaspectratiomode = "auto";
projection = "orthographic";
tickdir = "in";
tickdirmode = "auto";
ticklength = default_axes_ticklength ();
tightinset = Matrix (1, 4, 0.0);
sx = "linear";
sy = "linear";
sz = "linear";
visible = "on";
// Replace preserves Position and Units properties
if (mode != "replace")
{
outerposition = default_axes_outerposition ();
position = default_axes_position ();
activepositionproperty = "outerposition";
}
delete_children (true);
xlabel = gh_manager::make_graphics_handle ("text", __myhandle__,
false, false);
ylabel = gh_manager::make_graphics_handle ("text", __myhandle__,
false, false);
zlabel = gh_manager::make_graphics_handle ("text", __myhandle__,
false, false);
title = gh_manager::make_graphics_handle ("text", __myhandle__,
false, false);
xset (xlabel.handle_value (), "handlevisibility", "off");
xset (ylabel.handle_value (), "handlevisibility", "off");
xset (zlabel.handle_value (), "handlevisibility", "off");
xset (title.handle_value (), "handlevisibility", "off");
xset (xlabel.handle_value (), "horizontalalignment", "center");
xset (xlabel.handle_value (), "horizontalalignmentmode", "auto");
xset (ylabel.handle_value (), "horizontalalignment", "center");
xset (ylabel.handle_value (), "horizontalalignmentmode", "auto");
xset (zlabel.handle_value (), "horizontalalignment", "right");
xset (zlabel.handle_value (), "horizontalalignmentmode", "auto");
xset (title.handle_value (), "horizontalalignment", "center");
xset (title.handle_value (), "horizontalalignmentmode", "auto");
xset (xlabel.handle_value (), "verticalalignment", "top");
xset (xlabel.handle_value (), "verticalalignmentmode", "auto");
xset (ylabel.handle_value (), "verticalalignment", "bottom");
xset (ylabel.handle_value (), "verticalalignmentmode", "auto");
xset (title.handle_value (), "verticalalignment", "bottom");
xset (title.handle_value (), "verticalalignmentmode", "auto");
xset (ylabel.handle_value (), "rotation", 90.0);
xset (ylabel.handle_value (), "rotationmode", "auto");
xset (zlabel.handle_value (), "visible", "off");
xset (xlabel.handle_value (), "clipping", "off");
xset (ylabel.handle_value (), "clipping", "off");
xset (zlabel.handle_value (), "clipping", "off");
xset (title.handle_value (), "clipping", "off");
xset (xlabel.handle_value (), "autopos_tag", "xlabel");
xset (ylabel.handle_value (), "autopos_tag", "ylabel");
xset (zlabel.handle_value (), "autopos_tag", "zlabel");
xset (title.handle_value (), "autopos_tag", "title");
adopt (xlabel.handle_value ());
adopt (ylabel.handle_value ());
adopt (zlabel.handle_value ());
adopt (title.handle_value ());
update_transform ();
sync_positions ();
override_defaults (obj);
}
void
axes::properties::delete_text_child (handle_property& hp)
{
graphics_handle h = hp.handle_value ();
if (h.ok ())
{
graphics_object go = gh_manager::get_object (h);
if (go.valid_object ())
gh_manager::free (h);
base_properties::remove_child (h);
}
// FIXME: is it necessary to check whether the axes object is
// being deleted now? I think this function is only called when an
// individual child object is delete and not when the parent axes
// object is deleted.
if (! is_beingdeleted ())
{
hp = gh_manager::make_graphics_handle ("text", __myhandle__,
false, false);
xset (hp.handle_value (), "handlevisibility", "off");
adopt (hp.handle_value ());
}
}
void
axes::properties::remove_child (const graphics_handle& h)
{
if (xlabel.handle_value ().ok () && h == xlabel.handle_value ())
delete_text_child (xlabel);
else if (ylabel.handle_value ().ok () && h == ylabel.handle_value ())
delete_text_child (ylabel);
else if (zlabel.handle_value ().ok () && h == zlabel.handle_value ())
delete_text_child (zlabel);
else if (title.handle_value ().ok () && h == title.handle_value ())
delete_text_child (title);
else
base_properties::remove_child (h);
}
inline Matrix
xform_matrix (void)
{
Matrix m (4, 4, 0.0);
for (int i = 0; i < 4; i++)
m(i,i) = 1;
return m;
}
inline ColumnVector
xform_vector (void)
{
ColumnVector v (4, 0.0);
v(3) = 1;
return v;
}
inline ColumnVector
xform_vector (double x, double y, double z)
{
ColumnVector v (4, 1.0);
v(0) = x; v(1) = y; v(2) = z;
return v;
}
inline ColumnVector
transform (const Matrix& m, double x, double y, double z)
{
return (m * xform_vector (x, y, z));
}
inline Matrix
xform_scale (double x, double y, double z)
{
Matrix m (4, 4, 0.0);
m(0,0) = x; m(1,1) = y; m(2,2) = z; m(3,3) = 1;
return m;
}
inline Matrix
xform_translate (double x, double y, double z)
{
Matrix m = xform_matrix ();
m(0,3) = x; m(1,3) = y; m(2,3) = z; m(3,3) = 1;
return m;
}
inline void
scale (Matrix& m, double x, double y, double z)
{
m = m * xform_scale (x, y, z);
}
inline void
translate (Matrix& m, double x, double y, double z)
{
m = m * xform_translate (x, y, z);
}
inline void
xform (ColumnVector& v, const Matrix& m)
{
v = m*v;
}
inline void
scale (ColumnVector& v, double x, double y, double z)
{
v(0) *= x;
v(1) *= y;
v(2) *= z;
}
inline void
translate (ColumnVector& v, double x, double y, double z)
{
v(0) += x;
v(1) += y;
v(2) += z;
}
inline void
normalize (ColumnVector& v)
{
double fact = 1.0 / sqrt (v(0)*v(0)+v(1)*v(1)+v(2)*v(2));
scale (v, fact, fact, fact);
}
inline double
dot (const ColumnVector& v1, const ColumnVector& v2)
{
return (v1(0)*v2(0)+v1(1)*v2(1)+v1(2)*v2(2));
}
inline double
norm (const ColumnVector& v)
{
return sqrt (dot (v, v));
}
inline ColumnVector
cross (const ColumnVector& v1, const ColumnVector& v2)
{
ColumnVector r = xform_vector ();
r(0) = v1(1)*v2(2)-v1(2)*v2(1);
r(1) = v1(2)*v2(0)-v1(0)*v2(2);
r(2) = v1(0)*v2(1)-v1(1)*v2(0);
return r;
}
inline Matrix
unit_cube (void)
{
static double data[32] =
{
0,0,0,1,
1,0,0,1,
0,1,0,1,
0,0,1,1,
1,1,0,1,
1,0,1,1,
0,1,1,1,
1,1,1,1
};
Matrix m (4, 8);
memcpy (m.fortran_vec (), data, sizeof (double)*32);
return m;
}
inline ColumnVector
cam2xform (const Array<double>& m)
{
ColumnVector retval (4, 1.0);
memcpy (retval.fortran_vec (), m.fortran_vec (), sizeof (double)*3);
return retval;
}
inline RowVector
xform2cam (const ColumnVector& v)
{
return v.extract_n (0, 3).transpose ();
}
void
axes::properties::update_camera (void)
{
double xd = (xdir_is ("normal") ? 1 : -1);
double yd = (ydir_is ("normal") ? 1 : -1);
double zd = (zdir_is ("normal") ? 1 : -1);
Matrix xlimits = sx.scale (get_xlim ().matrix_value ());
Matrix ylimits = sy.scale (get_ylim ().matrix_value ());
Matrix zlimits = sz.scale (get_zlim ().matrix_value ());
double xo = xlimits(xd > 0 ? 0 : 1);
double yo = ylimits(yd > 0 ? 0 : 1);
double zo = zlimits(zd > 0 ? 0 : 1);
Matrix pb = get_plotboxaspectratio ().matrix_value ();
bool autocam = (camerapositionmode_is ("auto")
&& cameratargetmode_is ("auto")
&& cameraupvectormode_is ("auto")
&& cameraviewanglemode_is ("auto"));
bool dowarp = (autocam && dataaspectratiomode_is ("auto")
&& plotboxaspectratiomode_is ("auto"));
ColumnVector c_eye (xform_vector ());
ColumnVector c_center (xform_vector ());
ColumnVector c_upv (xform_vector ());
if (cameratargetmode_is ("auto"))
{
c_center(0) = (xlimits(0)+xlimits(1))/2;
c_center(1) = (ylimits(0)+ylimits(1))/2;
c_center(2) = (zlimits(0)+zlimits(1))/2;
cameratarget = xform2cam (c_center);
}
else
c_center = cam2xform (get_cameratarget ().matrix_value ());
if (camerapositionmode_is ("auto"))
{
Matrix tview = get_view ().matrix_value ();
double az = tview(0), el = tview(1);
double d = 5 * sqrt (pb(0)*pb(0)+pb(1)*pb(1)+pb(2)*pb(2));
if (el == 90 || el == -90)
c_eye(2) = d*signum (el);
else
{
az *= M_PI/180.0;
el *= M_PI/180.0;
c_eye(0) = d * cos (el) * sin (az);
c_eye(1) = -d* cos (el) * cos (az);
c_eye(2) = d * sin (el);
}
c_eye(0) = c_eye(0)*(xlimits(1)-xlimits(0))/(xd*pb(0))+c_center(0);
c_eye(1) = c_eye(1)*(ylimits(1)-ylimits(0))/(yd*pb(1))+c_center(1);
c_eye(2) = c_eye(2)*(zlimits(1)-zlimits(0))/(zd*pb(2))+c_center(2);
cameraposition = xform2cam (c_eye);
}
else
c_eye = cam2xform (get_cameraposition ().matrix_value ());
if (cameraupvectormode_is ("auto"))
{
Matrix tview = get_view ().matrix_value ();
double az = tview(0), el = tview(1);
if (el == 90 || el == -90)
{
c_upv(0) =
-signum (el) *sin (az*M_PI/180.0)*(xlimits(1)-xlimits(0))/pb(0);
c_upv(1) =
signum (el) * cos (az*M_PI/180.0)*(ylimits(1)-ylimits(0))/pb(1);
}
else
c_upv(2) = 1;
cameraupvector = xform2cam (c_upv);
}
else
c_upv = cam2xform (get_cameraupvector ().matrix_value ());
Matrix x_view = xform_matrix ();
Matrix x_projection = xform_matrix ();
Matrix x_viewport = xform_matrix ();
Matrix x_normrender = xform_matrix ();
Matrix x_pre = xform_matrix ();
x_render = xform_matrix ();
x_render_inv = xform_matrix ();
scale (x_pre, pb(0), pb(1), pb(2));
translate (x_pre, -0.5, -0.5, -0.5);
scale (x_pre, xd/(xlimits(1)-xlimits(0)), yd/(ylimits(1)-ylimits(0)),
zd/(zlimits(1)-zlimits(0)));
translate (x_pre, -xo, -yo, -zo);
xform (c_eye, x_pre);
xform (c_center, x_pre);
scale (c_upv, pb(0)/(xlimits(1)-xlimits(0)), pb(1)/(ylimits(1)-ylimits(0)),
pb(2)/(zlimits(1)-zlimits(0)));
translate (c_center, -c_eye(0), -c_eye(1), -c_eye(2));
ColumnVector F (c_center), f (F), UP (c_upv);
normalize (f);
normalize (UP);
if (std::abs (dot (f, UP)) > 1e-15)
{
double fa = 1 / sqrt(1-f(2)*f(2));
scale (UP, fa, fa, fa);
}
ColumnVector s = cross (f, UP);
ColumnVector u = cross (s, f);
scale (x_view, 1, 1, -1);
Matrix l = xform_matrix ();
l(0,0) = s(0); l(0,1) = s(1); l(0,2) = s(2);
l(1,0) = u(0); l(1,1) = u(1); l(1,2) = u(2);
l(2,0) = -f(0); l(2,1) = -f(1); l(2,2) = -f(2);
x_view = x_view * l;
translate (x_view, -c_eye(0), -c_eye(1), -c_eye(2));
scale (x_view, pb(0), pb(1), pb(2));
translate (x_view, -0.5, -0.5, -0.5);
Matrix x_cube = x_view * unit_cube ();
ColumnVector cmin = x_cube.row_min (), cmax = x_cube.row_max ();
double xM = cmax(0)-cmin(0);
double yM = cmax(1)-cmin(1);
Matrix bb = get_boundingbox (true);
double v_angle;
if (cameraviewanglemode_is ("auto"))
{
double af;
// FIXME: was this really needed? When compared to Matlab, it
// does not seem to be required. Need investigation with concrete
// graphics toolkit to see results visually.
if (false && dowarp)
af = 1.0 / (xM > yM ? xM : yM);
else
{
if ((bb(2)/bb(3)) > (xM/yM))
af = 1.0 / yM;
else
af = 1.0 / xM;
}
v_angle = 2 * (180.0 / M_PI) * atan (1 / (2 * af * norm (F)));
cameraviewangle = v_angle;
}
else
v_angle = get_cameraviewangle ();
double pf = 1 / (2 * tan ((v_angle / 2) * M_PI / 180.0) * norm (F));
scale (x_projection, pf, pf, 1);
if (dowarp)
{
xM *= pf;
yM *= pf;
translate (x_viewport, bb(0)+bb(2)/2, bb(1)+bb(3)/2, 0);
scale (x_viewport, bb(2)/xM, -bb(3)/yM, 1);
}
else
{
double pix = 1;
if (autocam)
{
if ((bb(2)/bb(3)) > (xM/yM))
pix = bb(3);
else
pix = bb(2);
}
else
pix = (bb(2) < bb(3) ? bb(2) : bb(3));
translate (x_viewport, bb(0)+bb(2)/2, bb(1)+bb(3)/2, 0);
scale (x_viewport, pix, -pix, 1);
}
x_normrender = x_viewport * x_projection * x_view;
x_cube = x_normrender * unit_cube ();
cmin = x_cube.row_min ();
cmax = x_cube.row_max ();
x_zlim.resize (1, 2);
x_zlim(0) = cmin(2);
x_zlim(1) = cmax(2);
x_render = x_normrender;
scale (x_render, xd/(xlimits(1)-xlimits(0)), yd/(ylimits(1)-ylimits(0)),
zd/(zlimits(1)-zlimits(0)));
translate (x_render, -xo, -yo, -zo);
x_viewtransform = x_view;
x_projectiontransform = x_projection;
x_viewporttransform = x_viewport;
x_normrendertransform = x_normrender;
x_rendertransform = x_render;
x_render_inv = x_render.inverse ();
// Note: these matrices are a slight modified version of the regular
// matrices, more suited for OpenGL rendering (x_gl_mat1 => light
// => x_gl_mat2)
x_gl_mat1 = x_view;
scale (x_gl_mat1, xd/(xlimits(1)-xlimits(0)), yd/(ylimits(1)-ylimits(0)),
zd/(zlimits(1)-zlimits(0)));
translate (x_gl_mat1, -xo, -yo, -zo);
x_gl_mat2 = x_viewport * x_projection;
}
static bool updating_axes_layout = false;
void
axes::properties::update_axes_layout (void)
{
if (updating_axes_layout)
return;
graphics_xform xform = get_transform ();
double xd = (xdir_is ("normal") ? 1 : -1);
double yd = (ydir_is ("normal") ? 1 : -1);
double zd = (zdir_is ("normal") ? 1 : -1);
const Matrix xlims = xform.xscale (get_xlim ().matrix_value ());
const Matrix ylims = xform.yscale (get_ylim ().matrix_value ());
const Matrix zlims = xform.zscale (get_zlim ().matrix_value ());
double x_min = xlims(0), x_max = xlims(1);
double y_min = ylims(0), y_max = ylims(1);
double z_min = zlims(0), z_max = zlims(1);
ColumnVector p1, p2, dir (3);
xstate = ystate = zstate = AXE_ANY_DIR;
p1 = xform.transform (x_min, (y_min+y_max)/2, (z_min+z_max)/2, false);
p2 = xform.transform (x_max, (y_min+y_max)/2, (z_min+z_max)/2, false);
dir(0) = xround (p2(0)-p1(0));
dir(1) = xround (p2(1)-p1(1));
dir(2) = (p2(2)-p1(2));
if (dir(0) == 0 && dir(1) == 0)
xstate = AXE_DEPTH_DIR;
else if (dir(2) == 0)
{
if (dir(0) == 0)
xstate = AXE_VERT_DIR;
else if (dir(1) == 0)
xstate = AXE_HORZ_DIR;
}
if (dir(2) == 0)
{
if (dir(1) == 0)
xPlane = (dir(0) > 0 ? x_max : x_min);
else
xPlane = (dir(1) < 0 ? x_max : x_min);
}
else
xPlane = (dir(2) < 0 ? x_min : x_max);
xPlaneN = (xPlane == x_min ? x_max : x_min);
fx = (x_max-x_min) / sqrt (dir(0)*dir(0)+dir(1)*dir(1));
p1 = xform.transform ((x_min+x_max)/2, y_min, (z_min+z_max)/2, false);
p2 = xform.transform ((x_min+x_max)/2, y_max, (z_min+z_max)/2, false);
dir(0) = xround (p2(0)-p1(0));
dir(1) = xround (p2(1)-p1(1));
dir(2) = (p2(2)-p1(2));
if (dir(0) == 0 && dir(1) == 0)
ystate = AXE_DEPTH_DIR;
else if (dir(2) == 0)
{
if (dir(0) == 0)
ystate = AXE_VERT_DIR;
else if (dir(1) == 0)
ystate = AXE_HORZ_DIR;
}
if (dir(2) == 0)
{
if (dir(1) == 0)
yPlane = (dir(0) > 0 ? y_max : y_min);
else
yPlane = (dir(1) < 0 ? y_max : y_min);
}
else
yPlane = (dir(2) < 0 ? y_min : y_max);
yPlaneN = (yPlane == y_min ? y_max : y_min);
fy = (y_max-y_min) / sqrt (dir(0)*dir(0)+dir(1)*dir(1));
p1 = xform.transform ((x_min+x_max)/2, (y_min+y_max)/2, z_min, false);
p2 = xform.transform ((x_min+x_max)/2, (y_min+y_max)/2, z_max, false);
dir(0) = xround (p2(0)-p1(0));
dir(1) = xround (p2(1)-p1(1));
dir(2) = (p2(2)-p1(2));
if (dir(0) == 0 && dir(1) == 0)
zstate = AXE_DEPTH_DIR;
else if (dir(2) == 0)
{
if (dir(0) == 0)
zstate = AXE_VERT_DIR;
else if (dir(1) == 0)
zstate = AXE_HORZ_DIR;
}
if (dir(2) == 0)
{
if (dir(1) == 0)
zPlane = (dir(0) > 0 ? z_min : z_max);
else
zPlane = (dir(1) < 0 ? z_min : z_max);
}
else
zPlane = (dir(2) < 0 ? z_min : z_max);
zPlaneN = (zPlane == z_min ? z_max : z_min);
fz = (z_max-z_min) / sqrt (dir(0)*dir(0)+dir(1)*dir(1));
unwind_protect frame;
frame.protect_var (updating_axes_layout);
updating_axes_layout = true;
xySym = (xd*yd*(xPlane-xPlaneN)*(yPlane-yPlaneN) > 0);
zSign = (zd*(zPlane-zPlaneN) <= 0);
xyzSym = zSign ? xySym : !xySym;
xpTick = (zSign ? xPlaneN : xPlane);
ypTick = (zSign ? yPlaneN : yPlane);
zpTick = (zSign ? zPlane : zPlaneN);
xpTickN = (zSign ? xPlane : xPlaneN);
ypTickN = (zSign ? yPlane : yPlaneN);
zpTickN = (zSign ? zPlaneN : zPlane);
/* 2D mode */
x2Dtop = false;
y2Dright = false;
layer2Dtop = false;
if (xstate == AXE_HORZ_DIR && ystate == AXE_VERT_DIR)
{
if (xaxislocation_is ("top"))
{
double tmp = yPlane;
yPlane = yPlaneN;
yPlaneN = tmp;
x2Dtop = true;
}
ypTick = yPlaneN;
ypTickN = yPlane;
if (yaxislocation_is ("right"))
{
double tmp = xPlane;
xPlane = xPlaneN;
xPlaneN = tmp;
y2Dright = true;
}
xpTick = xPlaneN;
xpTickN = xPlane;
if (layer_is ("top"))
{
zpTick = zPlaneN;
layer2Dtop = true;
}
else
zpTick = zPlane;
}
Matrix viewmat = get_view ().matrix_value ();
nearhoriz = std::abs (viewmat(1)) <= 5;
update_ticklength ();
}
void
axes::properties::update_ticklength (void)
{
bool mode2d = (((xstate > AXE_DEPTH_DIR ? 1 : 0) +
(ystate > AXE_DEPTH_DIR ? 1 : 0) +
(zstate > AXE_DEPTH_DIR ? 1 : 0)) == 2);
if (tickdirmode_is ("auto"))
tickdir.set (mode2d ? "in" : "out", true);
double ticksign = (tickdir_is ("in") ? -1 : 1);
Matrix bbox = get_boundingbox (true);
Matrix ticklen = get_ticklength ().matrix_value ();
ticklen(0) = ticklen(0) * std::max (bbox(2), bbox(3));
ticklen(1) = ticklen(1) * std::max (bbox(2), bbox(3));
xticklen = ticksign * (mode2d ? ticklen(0) : ticklen(1));
yticklen = ticksign * (mode2d ? ticklen(0) : ticklen(1));
zticklen = ticksign * (mode2d ? ticklen(0) : ticklen(1));
xtickoffset = (mode2d ? std::max (0., xticklen) : std::abs (xticklen)) + 5;
ytickoffset = (mode2d ? std::max (0., yticklen) : std::abs (yticklen)) + 5;
ztickoffset = (mode2d ? std::max (0., zticklen) : std::abs (zticklen)) + 5;
update_xlabel_position ();
update_ylabel_position ();
update_zlabel_position ();
update_title_position ();
}
/*
## FIXME: A demo can't be called in a C++ file. This should be made a test
## or moved to a .m file where it can be called.
%!demo
%! clf;
%! subplot (2,1,1);
%! plot (rand (3));
%! xlabel xlabel;
%! ylabel ylabel;
%! title title;
%! subplot (2,1,2);
%! plot (rand (3));
%! set (gca, "ticklength", get (gca, "ticklength") * 2, "tickdir", "out");
%! xlabel xlabel;
%! ylabel ylabel;
%! title title;
*/
static bool updating_xlabel_position = false;
void
axes::properties::update_xlabel_position (void)
{
if (updating_xlabel_position)
return;
text::properties& xlabel_props
= reinterpret_cast<text::properties&>
(gh_manager::get_object (get_xlabel ()).get_properties ());
bool is_empty = xlabel_props.get_string ().is_empty ();
unwind_protect frame;
frame.protect_var (updating_xlabel_position);
updating_xlabel_position = true;
if (! is_empty)
{
if (xlabel_props.horizontalalignmentmode_is ("auto"))
{
xlabel_props.set_horizontalalignment
(xstate > AXE_DEPTH_DIR
? "center" : (xyzSym ? "left" : "right"));
xlabel_props.set_horizontalalignmentmode ("auto");
}
if (xlabel_props.verticalalignmentmode_is ("auto"))
{
xlabel_props.set_verticalalignment
(xstate == AXE_VERT_DIR || x2Dtop ? "bottom" : "top");
xlabel_props.set_verticalalignmentmode ("auto");
}
}
if (xlabel_props.positionmode_is ("auto")
|| xlabel_props.rotationmode_is ("auto"))
{
graphics_xform xform = get_transform ();
Matrix ext (1, 2, 0.0);
ext = get_ticklabel_extents (get_xtick ().matrix_value (),
get_xticklabel ().all_strings (),
get_xlim ().matrix_value ());
double wmax = ext(0), hmax = ext(1), angle = 0;
ColumnVector p =
graphics_xform::xform_vector ((xpTickN+xpTick)/2, ypTick, zpTick);
bool tick_along_z = nearhoriz || xisinf (fy);
if (tick_along_z)
p(2) += (signum (zpTick-zpTickN)*fz*xtickoffset);
else
p(1) += (signum (ypTick-ypTickN)*fy*xtickoffset);
p = xform.transform (p(0), p(1), p(2), false);
switch (xstate)
{
case AXE_ANY_DIR:
p(0) += (xyzSym ? wmax : -wmax);
p(1) += hmax;
break;
case AXE_VERT_DIR:
p(0) -= wmax;
angle = 90;
break;
case AXE_HORZ_DIR:
p(1) += (x2Dtop ? -hmax : hmax);
break;
}
if (xlabel_props.positionmode_is ("auto"))
{
p = xform.untransform (p(0), p(1), p(2), true);
xlabel_props.set_position (p.extract_n (0, 3).transpose ());
xlabel_props.set_positionmode ("auto");
}
if (! is_empty && xlabel_props.rotationmode_is ("auto"))
{
xlabel_props.set_rotation (angle);
xlabel_props.set_rotationmode ("auto");
}
}
}
static bool updating_ylabel_position = false;
void
axes::properties::update_ylabel_position (void)
{
if (updating_ylabel_position)
return;
text::properties& ylabel_props
= reinterpret_cast<text::properties&>
(gh_manager::get_object (get_ylabel ()).get_properties ());
bool is_empty = ylabel_props.get_string ().is_empty ();
unwind_protect frame;
frame.protect_var (updating_ylabel_position);
updating_ylabel_position = true;
if (! is_empty)
{
if (ylabel_props.horizontalalignmentmode_is ("auto"))
{
ylabel_props.set_horizontalalignment
(ystate > AXE_DEPTH_DIR
? "center" : (!xyzSym ? "left" : "right"));
ylabel_props.set_horizontalalignmentmode ("auto");
}
if (ylabel_props.verticalalignmentmode_is ("auto"))
{
ylabel_props.set_verticalalignment
(ystate == AXE_VERT_DIR && !y2Dright ? "bottom" : "top");
ylabel_props.set_verticalalignmentmode ("auto");
}
}
if (ylabel_props.positionmode_is ("auto")
|| ylabel_props.rotationmode_is ("auto"))
{
graphics_xform xform = get_transform ();
Matrix ext (1, 2, 0.0);
// The underlying get_extents() from FreeType produces mismatched values.
// x-extent accurately measures the width of the glyphs.
// y-extent instead measures from baseline-to-baseline.
// Pad x-extent (+4) so that it approximately matches y-extent.
// This keeps ylabels about the same distance from y-axis as
// xlabels are from x-axis.
// ALWAYS use an even number for padding or horizontal alignment
// will be off.
ext = get_ticklabel_extents (get_ytick ().matrix_value (),
get_yticklabel ().all_strings (),
get_ylim ().matrix_value ());
double wmax = ext(0)+4, hmax = ext(1), angle = 0;
ColumnVector p =
graphics_xform::xform_vector (xpTick, (ypTickN+ypTick)/2, zpTick);
bool tick_along_z = nearhoriz || xisinf (fx);
if (tick_along_z)
p(2) += (signum (zpTick-zpTickN)*fz*ytickoffset);
else
p(0) += (signum (xpTick-xpTickN)*fx*ytickoffset);
p = xform.transform (p(0), p(1), p(2), false);
switch (ystate)
{
case AXE_ANY_DIR:
p(0) += (!xyzSym ? wmax : -wmax);
p(1) += hmax;
break;
case AXE_VERT_DIR:
p(0) += (y2Dright ? wmax : -wmax);
angle = 90;
break;
case AXE_HORZ_DIR:
p(1) += hmax;
break;
}
if (ylabel_props.positionmode_is ("auto"))
{
p = xform.untransform (p(0), p(1), p(2), true);
ylabel_props.set_position (p.extract_n (0, 3).transpose ());
ylabel_props.set_positionmode ("auto");
}
if (! is_empty && ylabel_props.rotationmode_is ("auto"))
{
ylabel_props.set_rotation (angle);
ylabel_props.set_rotationmode ("auto");
}
}
}
static bool updating_zlabel_position = false;
void
axes::properties::update_zlabel_position (void)
{
if (updating_zlabel_position)
return;
text::properties& zlabel_props
= reinterpret_cast<text::properties&>
(gh_manager::get_object (get_zlabel ()).get_properties ());
bool camAuto = cameraupvectormode_is ("auto");
bool is_empty = zlabel_props.get_string ().is_empty ();
unwind_protect frame;
frame.protect_var (updating_zlabel_position);
updating_zlabel_position = true;
if (! is_empty)
{
if (zlabel_props.horizontalalignmentmode_is ("auto"))
{
zlabel_props.set_horizontalalignment
((zstate > AXE_DEPTH_DIR || camAuto) ? "center" : "right");
zlabel_props.set_horizontalalignmentmode ("auto");
}
if (zlabel_props.verticalalignmentmode_is ("auto"))
{
zlabel_props.set_verticalalignment
(zstate == AXE_VERT_DIR
? "bottom" : ((zSign || camAuto) ? "bottom" : "top"));
zlabel_props.set_verticalalignmentmode ("auto");
}
}
if (zlabel_props.positionmode_is ("auto")
|| zlabel_props.rotationmode_is ("auto"))
{
graphics_xform xform = get_transform ();
Matrix ext (1, 2, 0.0);
ext = get_ticklabel_extents (get_ztick ().matrix_value (),
get_zticklabel ().all_strings (),
get_zlim ().matrix_value ());
double wmax = ext(0), hmax = ext(1), angle = 0;
ColumnVector p;
if (xySym)
{
p = graphics_xform::xform_vector (xPlaneN, yPlane,
(zpTickN+zpTick)/2);
if (xisinf (fy))
p(0) += (signum (xPlaneN-xPlane)*fx*ztickoffset);
else
p(1) += (signum (yPlane-yPlaneN)*fy*ztickoffset);
}
else
{
p = graphics_xform::xform_vector (xPlane, yPlaneN,
(zpTickN+zpTick)/2);
if (xisinf (fx))
p(1) += (signum (yPlaneN-yPlane)*fy*ztickoffset);
else
p(0) += (signum (xPlane-xPlaneN)*fx*ztickoffset);
}
p = xform.transform (p(0), p(1), p(2), false);
switch (zstate)
{
case AXE_ANY_DIR:
if (camAuto)
{
p(0) -= wmax;
angle = 90;
}
// FIXME: what's the correct offset?
//
// p[0] += (!xySym ? wmax : -wmax);
// p[1] += (zSign ? hmax : -hmax);
break;
case AXE_VERT_DIR:
p(0) -= wmax;
angle = 90;
break;
case AXE_HORZ_DIR:
p(1) += hmax;
break;
}
if (zlabel_props.positionmode_is ("auto"))
{
p = xform.untransform (p(0), p(1), p(2), true);
zlabel_props.set_position (p.extract_n (0, 3).transpose ());
zlabel_props.set_positionmode ("auto");
}
if (! is_empty && zlabel_props.rotationmode_is ("auto"))
{
zlabel_props.set_rotation (angle);
zlabel_props.set_rotationmode ("auto");
}
}
}
static bool updating_title_position = false;
void
axes::properties::update_title_position (void)
{
if (updating_title_position)
return;
text::properties& title_props
= reinterpret_cast<text::properties&>
(gh_manager::get_object (get_title ()).get_properties ());
unwind_protect frame;
frame.protect_var (updating_title_position);
updating_title_position = true;
if (title_props.positionmode_is ("auto"))
{
graphics_xform xform = get_transform ();
// FIXME: bbox should be stored in axes::properties
Matrix bbox = get_extent (false);
ColumnVector p =
graphics_xform::xform_vector (bbox(0)+bbox(2)/2,
bbox(1)-10,
(x_zlim(0)+x_zlim(1))/2);
if (x2Dtop)
{
Matrix ext (1, 2, 0.0);
ext = get_ticklabel_extents (get_xtick ().matrix_value (),
get_xticklabel ().all_strings (),
get_xlim ().matrix_value ());
p(1) -= ext(1);
}
p = xform.untransform (p(0), p(1), p(2), true);
title_props.set_position (p.extract_n (0, 3).transpose ());
title_props.set_positionmode ("auto");
}
}
void
axes::properties::update_autopos (const std::string& elem_type)
{
if (elem_type == "xlabel")
update_xlabel_position ();
else if (elem_type == "ylabel")
update_ylabel_position ();
else if (elem_type == "zlabel")
update_zlabel_position ();
else if (elem_type == "title")
update_title_position ();
else if (elem_type == "sync")
sync_positions ();
}
static void
normalized_aspectratios (Matrix& aspectratios, const Matrix& scalefactors,
double xlength, double ylength, double zlength)
{
double xval = xlength/scalefactors(0);
double yval = ylength/scalefactors(1);
double zval = zlength/scalefactors(2);
double minval = xmin (xmin (xval, yval), zval);
aspectratios(0) = xval/minval;
aspectratios(1) = yval/minval;
aspectratios(2) = zval/minval;
}
static void
max_axes_scale (double& s, Matrix& limits, const Matrix& kids,
double pbfactor, double dafactor, char limit_type, bool tight)
{
if (tight)
{
double minval = octave_Inf;
double maxval = -octave_Inf;
double min_pos = octave_Inf;
double max_neg = -octave_Inf;
get_children_limits (minval, maxval, min_pos, max_neg, kids, limit_type);
if (xfinite (minval) && xfinite (maxval))
{
limits(0) = minval;
limits(1) = maxval;
s = xmax(s, (maxval - minval) / (pbfactor * dafactor));
}
}
else
s = xmax(s, (limits(1) - limits(0)) / (pbfactor * dafactor));
}
static bool updating_aspectratios = false;
void
axes::properties::update_aspectratios (void)
{
if (updating_aspectratios)
return;
Matrix xlimits = get_xlim ().matrix_value ();
Matrix ylimits = get_ylim ().matrix_value ();
Matrix zlimits = get_zlim ().matrix_value ();
double dx = (xlimits(1)-xlimits(0));
double dy = (ylimits(1)-ylimits(0));
double dz = (zlimits(1)-zlimits(0));
Matrix da = get_dataaspectratio ().matrix_value ();
Matrix pba = get_plotboxaspectratio ().matrix_value ();
if (dataaspectratiomode_is ("auto"))
{
if (plotboxaspectratiomode_is ("auto"))
{
pba = Matrix (1, 3, 1.0);
plotboxaspectratio.set (pba, false);
}
normalized_aspectratios (da, pba, dx, dy, dz);
dataaspectratio.set (da, false);
}
else if (plotboxaspectratiomode_is ("auto"))
{
normalized_aspectratios (pba, da, dx, dy, dz);
plotboxaspectratio.set (pba, false);
}
else
{
double s = -octave_Inf;
bool modified_limits = false;
Matrix kids;
if (xlimmode_is ("auto") && ylimmode_is ("auto") && zlimmode_is ("auto"))
{
modified_limits = true;
kids = get_children ();
max_axes_scale (s, xlimits, kids, pba(0), da(0), 'x', true);
max_axes_scale (s, ylimits, kids, pba(1), da(1), 'y', true);
max_axes_scale (s, zlimits, kids, pba(2), da(2), 'z', true);
}
else if (xlimmode_is ("auto") && ylimmode_is ("auto"))
{
modified_limits = true;
max_axes_scale (s, zlimits, kids, pba(2), da(2), 'z', false);
}
else if (ylimmode_is ("auto") && zlimmode_is ("auto"))
{
modified_limits = true;
max_axes_scale (s, xlimits, kids, pba(0), da(0), 'x', false);
}
else if (zlimmode_is ("auto") && xlimmode_is ("auto"))
{
modified_limits = true;
max_axes_scale (s, ylimits, kids, pba(1), da(1), 'y', false);
}
if (modified_limits)
{
unwind_protect frame;
frame.protect_var (updating_aspectratios);
updating_aspectratios = true;
dx = pba(0) *da(0);
dy = pba(1) *da(1);
dz = pba(2) *da(2);
if (xisinf (s))
s = 1 / xmin (xmin (dx, dy), dz);
if (xlimmode_is ("auto"))
{
dx = s * dx;
xlimits(0) = 0.5 * (xlimits(0) + xlimits(1) - dx);
xlimits(1) = xlimits(0) + dx;
set_xlim (xlimits);
set_xlimmode ("auto");
}
if (ylimmode_is ("auto"))
{
dy = s * dy;
ylimits(0) = 0.5 * (ylimits(0) + ylimits(1) - dy);
ylimits(1) = ylimits(0) + dy;
set_ylim (ylimits);
set_ylimmode ("auto");
}
if (zlimmode_is ("auto"))
{
dz = s * dz;
zlimits(0) = 0.5 * (zlimits(0) + zlimits(1) - dz);
zlimits(1) = zlimits(0) + dz;
set_zlim (zlimits);
set_zlimmode ("auto");
}
}
else
{
normalized_aspectratios (pba, da, dx, dy, dz);
plotboxaspectratio.set (pba, false);
}
}
}
void
axes::properties::update_font (void)
{
#ifdef HAVE_FREETYPE
#ifdef HAVE_FONTCONFIG
text_renderer.set_font (get ("fontname").string_value (),
get ("fontweight").string_value (),
get ("fontangle").string_value (),
get ("fontsize").double_value ());
#endif
#endif
}
// The INTERNAL flag defines whether position or outerposition is used.
Matrix
axes::properties::get_boundingbox (bool internal,
const Matrix& parent_pix_size) const
{
Matrix pos = internal ? get_position ().matrix_value ()
: get_outerposition ().matrix_value ();
Matrix parent_size (parent_pix_size);
if (parent_size.numel () == 0)
{
graphics_object obj = gh_manager::get_object (get_parent ());
if (obj.valid_object ())
parent_size =
obj.get_properties ().get_boundingbox (true).extract_n (0, 2, 1, 2);
else
parent_size = default_figure_position ();
}
pos = convert_position (pos, get_units (), "pixels", parent_size);
pos(0)--;
pos(1)--;
pos(1) = parent_size(1) - pos(1) - pos(3);
return pos;
}
Matrix
axes::properties::get_extent (bool with_text, bool only_text_height) const
{
graphics_xform xform = get_transform ();
Matrix ext (1, 4, 0.0);
ext(0) = octave_Inf;
ext(1) = octave_Inf;
ext(2) = -octave_Inf;
ext(3) = -octave_Inf;
for (int i = 0; i <= 1; i++)
for (int j = 0; j <= 1; j++)
for (int k = 0; k <= 1; k++)
{
ColumnVector p = xform.transform (i ? xPlaneN : xPlane,
j ? yPlaneN : yPlane,
k ? zPlaneN : zPlane, false);
ext(0) = std::min (ext(0), p(0));
ext(1) = std::min (ext(1), p(1));
ext(2) = std::max (ext(2), p(0));
ext(3) = std::max (ext(3), p(1));
}
if (with_text)
{
for (int i = 0; i < 4; i++)
{
graphics_handle text_handle;
if (i == 0)
text_handle = get_title ();
else if (i == 1)
text_handle = get_xlabel ();
else if (i == 2)
text_handle = get_ylabel ();
else if (i == 3)
text_handle = get_zlabel ();
text::properties& text_props
= reinterpret_cast<text::properties&>
(gh_manager::get_object (text_handle).get_properties ());
Matrix text_pos = text_props.get_data_position ();
text_pos = xform.transform (text_pos(0), text_pos(1), text_pos(2));
if (text_props.get_string ().is_empty ())
{
ext(0) = std::min (ext(0), text_pos(0));
ext(1) = std::min (ext(1), text_pos(1));
ext(2) = std::max (ext(2), text_pos(0));
ext(3) = std::max (ext(3), text_pos(1));
}
else
{
Matrix text_ext = text_props.get_extent_matrix ();
bool ignore_horizontal = false;
bool ignore_vertical = false;
if (only_text_height)
{
double text_rotation = text_props.get_rotation ();
if (text_rotation == 0. || text_rotation == 180.)
ignore_horizontal = true;
else if (text_rotation == 90. || text_rotation == 270.)
ignore_vertical = true;
}
if (! ignore_horizontal)
{
ext(0) = std::min (ext(0), text_pos(0)+text_ext(0));
ext(2) = std::max (ext(2),
text_pos(0)+text_ext(0)+text_ext(2));
}
if (! ignore_vertical)
{
ext(1) = std::min (ext(1),
text_pos(1)-text_ext(1)-text_ext(3));
ext(3) = std::max (ext(3), text_pos(1)-text_ext(1));
}
}
}
}
ext(2) = ext(2)-ext(0);
ext(3) = ext(3)-ext(1);
return ext;
}
static octave_value
convert_ticklabel_string (const octave_value& val)
{
octave_value retval = val;
if (val.is_cellstr ())
{
// Always return a column vector for Matlab Compatibility
if (val.columns () > 1)
retval = val.reshape (dim_vector (val.numel (), 1));
}
else
{
string_vector sv;
if (val.is_numeric_type ())
{
NDArray data = val.array_value ();
std::ostringstream oss;
oss.precision (5);
for (octave_idx_type i = 0; i < val.numel (); i++)
{
oss.str ("");
oss << data(i);
sv.append (oss.str ());
}
}
else if (val.is_string () && val.rows () == 1)
{
std::string valstr = val.string_value ();
std::istringstream iss (valstr);
std::string tmpstr;
// Split string with delimiter '|'
while (std::getline (iss, tmpstr, '|'))
sv.append (tmpstr);
// If string ends with '|' Matlab appends a null string
if (*valstr.rbegin () == '|')
sv.append (std::string (""));
}
else
return retval;
charMatrix chmat (sv, ' ');
retval = octave_value (chmat);
}
return retval;
}
void
axes::properties::set_xticklabel (const octave_value& v)
{
if (!error_state)
{
if (xticklabel.set (convert_ticklabel_string (v), false))
{
set_xticklabelmode ("manual");
xticklabel.run_listeners (POSTSET);
mark_modified ();
}
else
set_xticklabelmode ("manual");
}
}
void
axes::properties::set_yticklabel (const octave_value& v)
{
if (!error_state)
{
if (yticklabel.set (convert_ticklabel_string (v), false))
{
set_yticklabelmode ("manual");
yticklabel.run_listeners (POSTSET);
mark_modified ();
}
else
set_yticklabelmode ("manual");
}
}
void
axes::properties::set_zticklabel (const octave_value& v)
{
if (!error_state)
{
if (zticklabel.set (convert_ticklabel_string (v), false))
{
set_zticklabelmode ("manual");
zticklabel.run_listeners (POSTSET);
mark_modified ();
}
else
set_zticklabelmode ("manual");
}
}
// Almost identical to convert_ticklabel_string but it only accepts
// cellstr or string, not numeric input.
static octave_value
convert_linestyleorder_string (const octave_value& val)
{
octave_value retval = val;
if (val.is_cellstr ())
{
// Always return a column vector for Matlab Compatibility
if (val.columns () > 1)
retval = val.reshape (dim_vector (val.numel (), 1));
}
else
{
string_vector sv;
if (val.is_string () && val.rows () == 1)
{
std::string valstr = val.string_value ();
std::istringstream iss (valstr);
std::string tmpstr;
// Split string with delimiter '|'
while (std::getline (iss, tmpstr, '|'))
sv.append (tmpstr);
// If string ends with '|' Matlab appends a null string
if (*valstr.rbegin () == '|')
sv.append (std::string (""));
}
else
return retval;
charMatrix chmat (sv, ' ');
retval = octave_value (chmat);
}
return retval;
}
void
axes::properties::set_linestyleorder (const octave_value& v)
{
if (!error_state)
{
linestyleorder.set (convert_linestyleorder_string (v), false);
}
}
void
axes::properties::set_units (const octave_value& v)
{
if (! error_state)
{
caseless_str old_units = get_units ();
if (units.set (v, true))
{
update_units (old_units);
mark_modified ();
}
}
}
void
axes::properties::update_units (const caseless_str& old_units)
{
graphics_object obj = gh_manager::get_object (get_parent ());
Matrix parent_bb
= obj.get_properties ().get_boundingbox (true).extract_n (0, 2, 1, 2);
caseless_str new_units = get_units ();
position.set (octave_value (convert_position (get_position ().matrix_value (),
old_units, new_units,
parent_bb)),
false);
outerposition.set (octave_value (convert_position (get_outerposition ().matrix_value (),
old_units, new_units,
parent_bb)),
false);
tightinset.set (octave_value (convert_position (get_tightinset ().matrix_value (),
old_units, new_units,
parent_bb)),
false);
looseinset.set (octave_value (convert_position (get_looseinset ().matrix_value (),
old_units, new_units,
parent_bb)),
false);
}
void
axes::properties::set_fontunits (const octave_value& v)
{
if (! error_state)
{
caseless_str old_fontunits = get_fontunits ();
if (fontunits.set (v, true))
{
update_fontunits (old_fontunits);
mark_modified ();
}
}
}
void
axes::properties::update_fontunits (const caseless_str& old_units)
{
caseless_str new_units = get_fontunits ();
double parent_height = get_boundingbox (true).elem (3);
double fsz = get_fontsize ();
fsz = convert_font_size (fsz, old_units, new_units, parent_height);
set_fontsize (octave_value (fsz));
}
double
axes::properties::get_fontsize_points (double box_pix_height) const
{
double fs = get_fontsize ();
double parent_height = box_pix_height;
if (fontunits_is ("normalized") && parent_height <= 0)
parent_height = get_boundingbox (true).elem (3);
return convert_font_size (fs, get_fontunits (), "points", parent_height);
}
ColumnVector
graphics_xform::xform_vector (double x, double y, double z)
{
return ::xform_vector (x, y, z);
}
Matrix
graphics_xform::xform_eye (void)
{
return ::xform_matrix ();
}
ColumnVector
graphics_xform::transform (double x, double y, double z,
bool use_scale) const
{
if (use_scale)
{
x = sx.scale (x);
y = sy.scale (y);
z = sz.scale (z);
}
return ::transform (xform, x, y, z);
}
ColumnVector
graphics_xform::untransform (double x, double y, double z,
bool use_scale) const
{
ColumnVector v = ::transform (xform_inv, x, y, z);
if (use_scale)
{
v(0) = sx.unscale (v(0));
v(1) = sy.unscale (v(1));
v(2) = sz.unscale (v(2));
}
return v;
}
octave_value
axes::get_default (const caseless_str& name) const
{
octave_value retval = default_properties.lookup (name);
if (retval.is_undefined ())
{
graphics_handle parent = get_parent ();
graphics_object parent_obj = gh_manager::get_object (parent);
retval = parent_obj.get_default (name);
}
return retval;
}
// FIXME: remove.
// FIXME: maybe this should go into array_property class?
/*
static void
check_limit_vals (double& min_val, double& max_val,
double& min_pos, double& max_neg,
const array_property& data)
{
double val = data.min_val ();
if (xfinite (val) && val < min_val)
min_val = val;
val = data.max_val ();
if (xfinite (val) && val > max_val)
max_val = val;
val = data.min_pos ();
if (xfinite (val) && val > 0 && val < min_pos)
min_pos = val;
val = data.max_neg ();
if (xfinite (val) && val < 0 && val > max_neg)
max_neg = val;
}
*/
static void
check_limit_vals (double& min_val, double& max_val,
double& min_pos, double& max_neg,
const octave_value& data)
{
if (data.is_matrix_type ())
{
Matrix m = data.matrix_value ();
if (! error_state && m.numel () == 4)
{
double val;
val = m(0);
if (xfinite (val) && val < min_val)
min_val = val;
val = m(1);
if (xfinite (val) && val > max_val)
max_val = val;
val = m(2);
if (xfinite (val) && val > 0 && val < min_pos)
min_pos = val;
val = m(3);
if (xfinite (val) && val < 0 && val > max_neg)
max_neg = val;
}
}
}
// magform(x) Returns (a, b), where x = a * 10^b, abs (a) >= 1., and b is
// integer.
static void
magform (double x, double& a, int& b)
{
if (x == 0)
{
a = 0;
b = 0;
}
else
{
b = static_cast<int> (gnulib::floor (std::log10 (std::abs (x))));
a = x / std::pow (10.0, b);
}
}
// A translation from Tom Holoryd's python code at
// http://kurage.nimh.nih.gov/tomh/tics.py
// FIXME: add log ticks
double
axes::properties::calc_tick_sep (double lo, double hi)
{
int ticint = 5;
// Reference: Lewart, C. R., "Algorithms SCALE1, SCALE2, and
// SCALE3 for Determination of Scales on Computer Generated
// Plots", Communications of the ACM, 10 (1973), 639-640.
// Also cited as ACM Algorithm 463.
double a;
int b, x;
magform ((hi-lo)/ticint, a, b);
static const double sqrt_2 = sqrt (2.0);
static const double sqrt_10 = sqrt (10.0);
static const double sqrt_50 = sqrt (50.0);
if (a < sqrt_2)
x = 1;
else if (a < sqrt_10)
x = 2;
else if (a < sqrt_50)
x = 5;
else
x = 10;
return x * std::pow (10., b);
}
// Attempt to make "nice" limits from the actual max and min of the
// data. For log plots, we will also use the smallest strictly positive
// value.
Matrix
axes::properties::get_axis_limits (double xmin, double xmax,
double min_pos, double max_neg,
bool logscale)
{
Matrix retval;
double min_val = xmin;
double max_val = xmax;
if (xisinf (min_val) && min_val > 0 && xisinf (max_val) && max_val < 0)
{
retval = default_lim (logscale);
return retval;
}
else if (! (xisinf (min_val) || xisinf (max_val)))
{
if (logscale)
{
if (xisinf (min_pos) && xisinf (max_neg))
{
// TODO -- max_neg is needed for "loglog ([0 -Inf])"
// This is the only place where max_neg is needed.
// Is there another way?
retval = default_lim ();
retval(0) = pow (10., retval(0));
retval(1) = pow (10., retval(1));
return retval;
}
if ((min_val <= 0 && max_val > 0))
{
warning ("axis: omitting non-positive data in log plot");
min_val = min_pos;
}
// FIXME: maybe this test should also be relative?
if (std::abs (min_val - max_val)
< sqrt (std::numeric_limits<double>::epsilon ()))
{
// Widen range when too small
if (min_val >= 0)
{
min_val *= 0.9;
max_val *= 1.1;
}
else
{
min_val *= 1.1;
max_val *= 0.9;
}
}
if (min_val > 0)
{
// Log plots with all positive data
min_val = pow (10, gnulib::floor (log10 (min_val)));
max_val = pow (10, std::ceil (log10 (max_val)));
}
else
{
// Log plots with all negative data
min_val = -pow (10, std::ceil (log10 (-min_val)));
max_val = -pow (10, gnulib::floor (log10 (-max_val)));
}
}
else
{
if (min_val == 0 && max_val == 0)
{
min_val = -1;
max_val = 1;
}
// FIXME: maybe this test should also be relative?
else if (std::abs (min_val - max_val)
< sqrt (std::numeric_limits<double>::epsilon ()))
{
min_val -= 0.1 * std::abs (min_val);
max_val += 0.1 * std::abs (max_val);
}
double tick_sep = calc_tick_sep (min_val , max_val);
double min_tick = gnulib::floor (min_val / tick_sep);
double max_tick = std::ceil (max_val / tick_sep);
// Prevent round-off from cropping ticks
min_val = std::min (min_val, tick_sep * min_tick);
max_val = std::max (max_val, tick_sep * max_tick);
}
}
retval.resize (1, 2);
retval(1) = max_val;
retval(0) = min_val;
return retval;
}
void
axes::properties::calc_ticks_and_lims (array_property& lims,
array_property& ticks,
array_property& mticks,
bool limmode_is_auto, bool is_logscale)
{
// FIXME: add log ticks and lims
if (lims.get ().is_empty ())
return;
double lo = (lims.get ().matrix_value ()) (0);
double hi = (lims.get ().matrix_value ()) (1);
bool is_negative = lo < 0 && hi < 0;
double tmp;
// FIXME: should this be checked for somewhere else? (i.e. set{x,y,z}lim)
if (hi < lo)
{
tmp = hi;
hi = lo;
lo = tmp;
}
if (is_logscale)
{
if (is_negative)
{
tmp = hi;
hi = std::log10 (-lo);
lo = std::log10 (-tmp);
}
else
{
hi = std::log10 (hi);
lo = std::log10 (lo);
}
}
double tick_sep = calc_tick_sep (lo , hi);
if (is_logscale && ! (xisinf (hi) || xisinf (lo)))
{
// FIXME: what if (hi-lo) < tick_sep?
// ex: loglog ([1 1.1])
tick_sep = std::max (tick_sep, 1.);
tick_sep = std::ceil (tick_sep);
}
int i1 = static_cast<int> (gnulib::floor (lo / tick_sep));
int i2 = static_cast<int> (std::ceil (hi / tick_sep));
if (limmode_is_auto)
{
// adjust limits to include min and max tics
Matrix tmp_lims (1,2);
tmp_lims(0) = std::min (tick_sep * i1, lo);
tmp_lims(1) = std::max (tick_sep * i2, hi);
if (is_logscale)
{
tmp_lims(0) = std::pow (10.,tmp_lims(0));
tmp_lims(1) = std::pow (10.,tmp_lims(1));
if (tmp_lims(0) <= 0)
tmp_lims(0) = std::pow (10., lo);
if (is_negative)
{
tmp = tmp_lims(0);
tmp_lims(0) = -tmp_lims(1);
tmp_lims(1) = -tmp;
}
}
lims = tmp_lims;
}
Matrix tmp_ticks (1, i2-i1+1);
for (int i = 0; i <= i2-i1; i++)
{
tmp_ticks (i) = tick_sep * (i+i1);
if (is_logscale)
tmp_ticks (i) = std::pow (10., tmp_ticks (i));
}
if (is_logscale && is_negative)
{
Matrix rev_ticks (1, i2-i1+1);
rev_ticks = -tmp_ticks;
for (int i = 0; i <= i2-i1; i++)
tmp_ticks (i) = rev_ticks (i2-i1-i);
}
ticks = tmp_ticks;
int n = is_logscale ? 8 : 4;
Matrix tmp_mticks (1, n * (tmp_ticks.numel () - 1));
for (int i = 0; i < tmp_ticks.numel ()-1; i++)
{
double d = (tmp_ticks (i+1) - tmp_ticks (i)) / (n+1);
for (int j = 0; j < n; j++)
{
tmp_mticks (n*i+j) = tmp_ticks (i) + d * (j+1);
}
}
mticks = tmp_mticks;
}
void
axes::properties::calc_ticklabels (const array_property& ticks,
any_property& labels, bool logscale)
{
Matrix values = ticks.get ().matrix_value ();
Cell c (values.dims ());
std::ostringstream os;
if (logscale)
{
double significand;
double exponent;
double exp_max = 0.;
double exp_min = 0.;
for (int i = 0; i < values.numel (); i++)
{
exp_max = std::max (exp_max, std::log10 (values(i)));
exp_min = std::max (exp_min, std::log10 (values(i)));
}
for (int i = 0; i < values.numel (); i++)
{
if (values(i) < 0.)
exponent = gnulib::floor (std::log10 (-values(i)));
else
exponent = gnulib::floor (std::log10 (values(i)));
significand = values(i) * std::pow (10., -exponent);
os.str (std::string ());
os << significand;
if (exponent < 0.)
{
os << "e-";
exponent = -exponent;
}
else
os << "e+";
if (exponent < 10. && (exp_max > 9 || exp_min < -9))
os << "0";
os << exponent;
c(i) = os.str ();
}
}
else
{
for (int i = 0; i < values.numel (); i++)
{
os.str (std::string ());
os << values(i);
c(i) = os.str ();
}
}
labels = c;
}
Matrix
axes::properties::get_ticklabel_extents (const Matrix& ticks,
const string_vector& ticklabels,
const Matrix& limits)
{
#ifndef HAVE_FREETYPE
double fontsize = get ("fontsize").double_value ();
#endif
Matrix ext (1, 2, 0.0);
double wmax = 0., hmax = 0.;
int n = std::min (ticklabels.numel (), ticks.numel ());
for (int i = 0; i < n; i++)
{
double val = ticks(i);
if (limits(0) <= val && val <= limits(1))
{
std::string label (ticklabels(i));
label.erase (0, label.find_first_not_of (" "));
label = label.substr (0, label.find_last_not_of (" ")+1);
#ifdef HAVE_FREETYPE
ext = text_renderer.get_extent (label, 0.0, "none");
wmax = std::max (wmax, ext(0));
hmax = std::max (hmax, ext(1));
#else
// FIXME: find a better approximation
int len = label.length ();
wmax = std::max (wmax, 0.5*fontsize*len);
hmax = fontsize;
#endif
}
}
ext(0) = wmax;
ext(1) = hmax;
return ext;
}
void
get_children_limits (double& min_val, double& max_val,
double& min_pos, double& max_neg,
const Matrix& kids, char limit_type)
{
octave_idx_type n = kids.numel ();
switch (limit_type)
{
case 'x':
for (octave_idx_type i = 0; i < n; i++)
{
graphics_object obj = gh_manager::get_object (kids(i));
if (obj.is_xliminclude ())
{
octave_value lim = obj.get_xlim ();
check_limit_vals (min_val, max_val, min_pos, max_neg, lim);
}
}
break;
case 'y':
for (octave_idx_type i = 0; i < n; i++)
{
graphics_object obj = gh_manager::get_object (kids(i));
if (obj.is_yliminclude ())
{
octave_value lim = obj.get_ylim ();
check_limit_vals (min_val, max_val, min_pos, max_neg, lim);
}
}
break;
case 'z':
for (octave_idx_type i = 0; i < n; i++)
{
graphics_object obj = gh_manager::get_object (kids(i));
if (obj.is_zliminclude ())
{
octave_value lim = obj.get_zlim ();
check_limit_vals (min_val, max_val, min_pos, max_neg, lim);
}
}
break;
case 'c':
for (octave_idx_type i = 0; i < n; i++)
{
graphics_object obj = gh_manager::get_object (kids(i));
if (obj.is_climinclude ())
{
octave_value lim = obj.get_clim ();
check_limit_vals (min_val, max_val, min_pos, max_neg, lim);
}
}
break;
case 'a':
for (octave_idx_type i = 0; i < n; i++)
{
graphics_object obj = gh_manager::get_object (kids(i));
if (obj.is_aliminclude ())
{
octave_value lim = obj.get_alim ();
check_limit_vals (min_val, max_val, min_pos, max_neg, lim);
}
}
break;
default:
break;
}
}
static bool updating_axis_limits = false;
void
axes::update_axis_limits (const std::string& axis_type,
const graphics_handle& h)
{
if (updating_axis_limits)
return;
Matrix kids = Matrix (1, 1, h.value ());
double min_val = octave_Inf;
double max_val = -octave_Inf;
double min_pos = octave_Inf;
double max_neg = -octave_Inf;
char update_type = 0;
Matrix limits;
double val;
#define FIX_LIMITS \
if (limits.numel () == 4) \
{ \
val = limits(0); \
if (xfinite (val)) \
min_val = val; \
val = limits(1); \
if (xfinite (val)) \
max_val = val; \
val = limits(2); \
if (xfinite (val)) \
min_pos = val; \
val = limits(3); \
if (xfinite (val)) \
max_neg = val; \
} \
else \
{ \
limits.resize (4, 1); \
limits(0) = min_val; \
limits(1) = max_val; \
limits(2) = min_pos; \
limits(3) = max_neg; \
}
if (axis_type == "xdata" || axis_type == "xscale"
|| axis_type == "xlimmode" || axis_type == "xliminclude"
|| axis_type == "xlim")
{
if (xproperties.xlimmode_is ("auto"))
{
limits = xproperties.get_xlim ().matrix_value ();
FIX_LIMITS ;
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'x');
limits = xproperties.get_axis_limits (min_val, max_val,
min_pos, max_neg,
xproperties.xscale_is ("log"));
update_type = 'x';
}
}
else if (axis_type == "ydata" || axis_type == "yscale"
|| axis_type == "ylimmode" || axis_type == "yliminclude"
|| axis_type == "ylim")
{
if (xproperties.ylimmode_is ("auto"))
{
limits = xproperties.get_ylim ().matrix_value ();
FIX_LIMITS ;
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'y');
limits = xproperties.get_axis_limits (min_val, max_val,
min_pos, max_neg,
xproperties.yscale_is ("log"));
update_type = 'y';
}
}
else if (axis_type == "zdata" || axis_type == "zscale"
|| axis_type == "zlimmode" || axis_type == "zliminclude"
|| axis_type == "zlim")
{
if (xproperties.zlimmode_is ("auto"))
{
limits = xproperties.get_zlim ().matrix_value ();
FIX_LIMITS ;
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'z');
limits = xproperties.get_axis_limits (min_val, max_val,
min_pos, max_neg,
xproperties.zscale_is ("log"));
update_type = 'z';
}
}
else if (axis_type == "cdata" || axis_type == "climmode"
|| axis_type == "cdatamapping" || axis_type == "climinclude"
|| axis_type == "clim")
{
if (xproperties.climmode_is ("auto"))
{
limits = xproperties.get_clim ().matrix_value ();
FIX_LIMITS ;
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'c');
if (min_val > max_val)
{
min_val = min_pos = 0;
max_val = 1;
}
else if (min_val == max_val)
{
max_val = min_val + 1;
min_val -= 1;
}
limits.resize (1, 2);
limits(0) = min_val;
limits(1) = max_val;
update_type = 'c';
}
}
else if (axis_type == "alphadata" || axis_type == "alimmode"
|| axis_type == "alphadatamapping" || axis_type == "aliminclude"
|| axis_type == "alim")
{
if (xproperties.alimmode_is ("auto"))
{
limits = xproperties.get_alim ().matrix_value ();
FIX_LIMITS ;
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'a');
if (min_val > max_val)
{
min_val = min_pos = 0;
max_val = 1;
}
else if (min_val == max_val)
max_val = min_val + 1;
limits.resize (1, 2);
limits(0) = min_val;
limits(1) = max_val;
update_type = 'a';
}
}
#undef FIX_LIMITS
unwind_protect frame;
frame.protect_var (updating_axis_limits);
updating_axis_limits = true;
switch (update_type)
{
case 'x':
xproperties.set_xlim (limits);
xproperties.set_xlimmode ("auto");
xproperties.update_xlim ();
break;
case 'y':
xproperties.set_ylim (limits);
xproperties.set_ylimmode ("auto");
xproperties.update_ylim ();
break;
case 'z':
xproperties.set_zlim (limits);
xproperties.set_zlimmode ("auto");
xproperties.update_zlim ();
break;
case 'c':
xproperties.set_clim (limits);
xproperties.set_climmode ("auto");
break;
case 'a':
xproperties.set_alim (limits);
xproperties.set_alimmode ("auto");
break;
default:
break;
}
xproperties.update_transform ();
}
void
axes::update_axis_limits (const std::string& axis_type)
{
if (updating_axis_limits || updating_aspectratios)
return;
Matrix kids = xproperties.get_children ();
double min_val = octave_Inf;
double max_val = -octave_Inf;
double min_pos = octave_Inf;
double max_neg = -octave_Inf;
char update_type = 0;
Matrix limits;
if (axis_type == "xdata" || axis_type == "xscale"
|| axis_type == "xlimmode" || axis_type == "xliminclude"
|| axis_type == "xlim")
{
if (xproperties.xlimmode_is ("auto"))
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'x');
limits = xproperties.get_axis_limits (min_val, max_val,
min_pos, max_neg,
xproperties.xscale_is ("log"));
update_type = 'x';
}
}
else if (axis_type == "ydata" || axis_type == "yscale"
|| axis_type == "ylimmode" || axis_type == "yliminclude"
|| axis_type == "ylim")
{
if (xproperties.ylimmode_is ("auto"))
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'y');
limits = xproperties.get_axis_limits (min_val, max_val,
min_pos, max_neg,
xproperties.yscale_is ("log"));
update_type = 'y';
}
}
else if (axis_type == "zdata" || axis_type == "zscale"
|| axis_type == "zlimmode" || axis_type == "zliminclude"
|| axis_type == "zlim")
{
if (xproperties.zlimmode_is ("auto"))
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'z');
limits = xproperties.get_axis_limits (min_val, max_val,
min_pos, max_neg,
xproperties.zscale_is ("log"));
update_type = 'z';
}
}
else if (axis_type == "cdata" || axis_type == "climmode"
|| axis_type == "cdatamapping" || axis_type == "climinclude"
|| axis_type == "clim")
{
if (xproperties.climmode_is ("auto"))
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'c');
if (min_val > max_val)
{
min_val = min_pos = 0;
max_val = 1;
}
else if (min_val == max_val)
{
max_val = min_val + 1;
min_val -= 1;
}
limits.resize (1, 2);
limits(0) = min_val;
limits(1) = max_val;
update_type = 'c';
}
}
else if (axis_type == "alphadata" || axis_type == "alimmode"
|| axis_type == "alphadatamapping" || axis_type == "aliminclude"
|| axis_type == "alim")
{
if (xproperties.alimmode_is ("auto"))
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'a');
if (min_val > max_val)
{
min_val = min_pos = 0;
max_val = 1;
}
else if (min_val == max_val)
max_val = min_val + 1;
limits.resize (1, 2);
limits(0) = min_val;
limits(1) = max_val;
update_type = 'a';
}
}
unwind_protect frame;
frame.protect_var (updating_axis_limits);
updating_axis_limits = true;
switch (update_type)
{
case 'x':
xproperties.set_xlim (limits);
xproperties.set_xlimmode ("auto");
xproperties.update_xlim ();
break;
case 'y':
xproperties.set_ylim (limits);
xproperties.set_ylimmode ("auto");
xproperties.update_ylim ();
break;
case 'z':
xproperties.set_zlim (limits);
xproperties.set_zlimmode ("auto");
xproperties.update_zlim ();
break;
case 'c':
xproperties.set_clim (limits);
xproperties.set_climmode ("auto");
break;
case 'a':
xproperties.set_alim (limits);
xproperties.set_alimmode ("auto");
break;
default:
break;
}
xproperties.update_transform ();
}
inline
double force_in_range (const double x, const double lower, const double upper)
{
if (x < lower)
{ return lower; }
else if (x > upper)
{ return upper; }
else
{ return x; }
}
static Matrix
do_zoom (double val, double factor, const Matrix& lims, bool is_logscale)
{
Matrix new_lims = lims;
double lo = lims(0);
double hi = lims(1);
bool is_negative = lo < 0 && hi < 0;
if (is_logscale)
{
if (is_negative)
{
double tmp = hi;
hi = std::log10 (-lo);
lo = std::log10 (-tmp);
val = std::log10 (-val);
}
else
{
hi = std::log10 (hi);
lo = std::log10 (lo);
val = std::log10 (val);
}
}
// Perform the zooming
lo = val + factor * (lo - val);
hi = val + factor * (hi - val);
if (is_logscale)
{
if (is_negative)
{
double tmp = -std::pow (10.0, hi);
hi = -std::pow (10.0, lo);
lo = tmp;
}
else
{
lo = std::pow (10.0, lo);
hi = std::pow (10.0, hi);
}
}
new_lims(0) = lo;
new_lims(1) = hi;
return new_lims;
}
void
axes::properties::zoom_about_point (double x, double y, double factor,
bool push_to_zoom_stack)
{
// FIXME: Do we need error checking here?
Matrix xlims = get_xlim ().matrix_value ();
Matrix ylims = get_ylim ().matrix_value ();
// Get children axes limits
Matrix kids = get_children ();
double minx = octave_Inf;
double maxx = -octave_Inf;
double min_pos_x = octave_Inf;
double max_neg_x = -octave_Inf;
get_children_limits (minx, maxx, min_pos_x, max_neg_x, kids, 'x');
double miny = octave_Inf;
double maxy = -octave_Inf;
double min_pos_y = octave_Inf;
double max_neg_y = -octave_Inf;
get_children_limits (miny, maxy, min_pos_y, max_neg_y, kids, 'y');
xlims = do_zoom (x, factor, xlims, xscale_is ("log"));
ylims = do_zoom (y, factor, ylims, yscale_is ("log"));
zoom (xlims, ylims, push_to_zoom_stack);
}
void
axes::properties::zoom (const Matrix& xl, const Matrix& yl,
bool push_to_zoom_stack)
{
if (push_to_zoom_stack)
{
zoom_stack.push_front (xlimmode.get ());
zoom_stack.push_front (xlim.get ());
zoom_stack.push_front (ylimmode.get ());
zoom_stack.push_front (ylim.get ());
}
xlim = xl;
xlimmode = "manual";
ylim = yl;
ylimmode = "manual";
update_transform ();
update_xlim (false);
update_ylim (false);
}
static Matrix
do_translate (double x0, double x1, const Matrix& lims, bool is_logscale)
{
Matrix new_lims = lims;
double lo = lims(0);
double hi = lims(1);
bool is_negative = lo < 0 && hi < 0;
double delta;
if (is_logscale)
{
if (is_negative)
{
double tmp = hi;
hi = std::log10 (-lo);
lo = std::log10 (-tmp);
x0 = -x0;
x1 = -x1;
}
else
{
hi = std::log10 (hi);
lo = std::log10 (lo);
}
delta = std::log10 (x0) - std::log10 (x1);
}
else
{
delta = x0 - x1;
}
// Perform the translation
lo += delta;
hi += delta;
if (is_logscale)
{
if (is_negative)
{
double tmp = -std::pow (10.0, hi);
hi = -std::pow (10.0, lo);
lo = tmp;
}
else
{
lo = std::pow (10.0, lo);
hi = std::pow (10.0, hi);
}
}
new_lims(0) = lo;
new_lims(1) = hi;
return new_lims;
}
void
axes::properties::translate_view (double x0, double x1, double y0, double y1)
{
// FIXME: Do we need error checking here?
Matrix xlims = get_xlim ().matrix_value ();
Matrix ylims = get_ylim ().matrix_value ();
// Get children axes limits
Matrix kids = get_children ();
double minx = octave_Inf;
double maxx = -octave_Inf;
double min_pos_x = octave_Inf;
double max_neg_x = -octave_Inf;
get_children_limits (minx, maxx, min_pos_x, max_neg_x, kids, 'x');
double miny = octave_Inf;
double maxy = -octave_Inf;
double min_pos_y = octave_Inf;
double max_neg_y = -octave_Inf;
get_children_limits (miny, maxy, min_pos_y, max_neg_y, kids, 'y');
xlims = do_translate (x0, x1, xlims, xscale_is ("log"));
ylims = do_translate (y0, y1, ylims, yscale_is ("log"));
zoom (xlims, ylims, false);
}
void
axes::properties::rotate_view (double delta_el, double delta_az)
{
Matrix v = get_view ().matrix_value ();
v(1) += delta_el;
if (v(1) > 90)
v(1) = 90;
if (v(1) < -90)
v(1) = -90;
v(0) = fmod (v(0) - delta_az + 720,360);
set_view (v);
update_transform ();
}
void
axes::properties::unzoom (void)
{
if (zoom_stack.size () >= 4)
{
ylim = zoom_stack.front ();
zoom_stack.pop_front ();
ylimmode = zoom_stack.front ();
zoom_stack.pop_front ();
xlim = zoom_stack.front ();
zoom_stack.pop_front ();
xlimmode = zoom_stack.front ();
zoom_stack.pop_front ();
update_transform ();
update_xlim (false);
update_ylim (false);
}
}
void
axes::properties::clear_zoom_stack (void)
{
while (zoom_stack.size () > 4)
zoom_stack.pop_front ();
unzoom ();
}
void
axes::reset_default_properties (void)
{
::reset_default_properties (default_properties);
}
void
axes::initialize (const graphics_object& go)
{
base_graphics_object::initialize (go);
xinitialize (xproperties.get_title ());
xinitialize (xproperties.get_xlabel ());
xinitialize (xproperties.get_ylabel ());
xinitialize (xproperties.get_zlabel ());
xproperties.sync_positions ();
}
// ---------------------------------------------------------------------
Matrix
line::properties::compute_xlim (void) const
{
Matrix m (1, 4);
m(0) = xdata.min_val ();
m(1) = xdata.max_val ();
m(2) = xdata.min_pos ();
m(3) = xdata.max_neg ();
return m;
}
Matrix
line::properties::compute_ylim (void) const
{
Matrix m (1, 4);
m(0) = ydata.min_val ();
m(1) = ydata.max_val ();
m(2) = ydata.min_pos ();
m(3) = ydata.max_neg ();
return m;
}
// ---------------------------------------------------------------------
Matrix
text::properties::get_data_position (void) const
{
Matrix pos = get_position ().matrix_value ();
if (! units_is ("data"))
pos = convert_text_position (pos, *this, get_units (), "data");
return pos;
}
Matrix
text::properties::get_extent_matrix (void) const
{
// FIXME: Should this function also add the (x,y) base position?
return extent.get ().matrix_value ();
}
octave_value
text::properties::get_extent (void) const
{
// FIXME: This doesn't work right for 3D plots.
// (It doesn't in Matlab either, at least not in version 6.5.)
Matrix m = extent.get ().matrix_value ();
Matrix pos = get_position ().matrix_value ();
Matrix p = convert_text_position (pos, *this, get_units (), "pixels");
m(0) += p(0);
m(1) += p(1);
return convert_text_position (m, *this, "pixels", get_units ());
}
void
text::properties::update_font (void)
{
#ifdef HAVE_FREETYPE
#ifdef HAVE_FONTCONFIG
renderer.set_font (get ("fontname").string_value (),
get ("fontweight").string_value (),
get ("fontangle").string_value (),
get ("fontsize").double_value ());
#endif
renderer.set_color (get_color_rgb ());
#endif
}
void
text::properties::update_text_extent (void)
{
#ifdef HAVE_FREETYPE
int halign = 0, valign = 0;
if (horizontalalignment_is ("center"))
halign = 1;
else if (horizontalalignment_is ("right"))
halign = 2;
if (verticalalignment_is ("middle"))
valign = 1;
else if (verticalalignment_is ("top"))
valign = 2;
else if (verticalalignment_is ("baseline"))
valign = 3;
else if (verticalalignment_is ("cap"))
valign = 4;
Matrix bbox;
// FIXME: string should be parsed only when modified, for efficiency
octave_value string_prop = get_string ();
string_vector sv = string_prop.all_strings ();
renderer.text_to_pixels (sv.join ("\n"), pixels, bbox,
halign, valign, get_rotation (),
get_interpreter ());
/* The bbox is relative to the text's position.
We'll leave it that way, because get_position () does not return
valid results when the text is first constructed.
Conversion to proper coordinates is performed in get_extent. */
set_extent (bbox);
#endif
if (autopos_tag_is ("xlabel") || autopos_tag_is ("ylabel") ||
autopos_tag_is ("zlabel") || autopos_tag_is ("title"))
update_autopos ("sync");
}
void
text::properties::request_autopos (void)
{
if (autopos_tag_is ("xlabel") || autopos_tag_is ("ylabel") ||
autopos_tag_is ("zlabel") || autopos_tag_is ("title"))
update_autopos (get_autopos_tag ());
}
void
text::properties::update_units (void)
{
if (! units_is ("data"))
{
set_xliminclude ("off");
set_yliminclude ("off");
set_zliminclude ("off");
}
Matrix pos = get_position ().matrix_value ();
pos = convert_text_position (pos, *this, cached_units, get_units ());
// FIXME: if the current axes view is 2D, then one should
// probably drop the z-component of "pos" and leave "zliminclude"
// to "off".
set_position (pos);
if (units_is ("data"))
{
set_xliminclude ("on");
set_yliminclude ("on");
// FIXME: see above
set_zliminclude ("off");
}
cached_units = get_units ();
}
double
text::properties::get_fontsize_points (double box_pix_height) const
{
double fs = get_fontsize ();
double parent_height = box_pix_height;
if (fontunits_is ("normalized") && parent_height <= 0)
{
graphics_object go (gh_manager::get_object (get___myhandle__ ()));
graphics_object ax (go.get_ancestor ("axes"));
parent_height = ax.get_properties ().get_boundingbox (true).elem (3);
}
return convert_font_size (fs, get_fontunits (), "points", parent_height);
}
// ---------------------------------------------------------------------
octave_value
image::properties::get_color_data (void) const
{
return convert_cdata (*this, get_cdata (),
cdatamapping_is ("scaled"), 3);
}
// ---------------------------------------------------------------------
octave_value
patch::properties::get_color_data (void) const
{
octave_value fvc = get_facevertexcdata ();
if (fvc.is_undefined () || fvc.is_empty ())
return Matrix ();
else
return convert_cdata (*this, fvc,cdatamapping_is ("scaled"), 2);
}
// ---------------------------------------------------------------------
octave_value
surface::properties::get_color_data (void) const
{
return convert_cdata (*this, get_cdata (), cdatamapping_is ("scaled"), 3);
}
inline void
cross_product (double x1, double y1, double z1,
double x2, double y2, double z2,
double& x, double& y, double& z)
{
x += (y1 * z2 - z1 * y2);
y += (z1 * x2 - x1 * z2);
z += (x1 * y2 - y1 * x2);
}
void
surface::properties::update_normals (void)
{
if (normalmode_is ("auto"))
{
Matrix x = get_xdata ().matrix_value ();
Matrix y = get_ydata ().matrix_value ();
Matrix z = get_zdata ().matrix_value ();
int p = z.columns (), q = z.rows ();
int i1 = 0, i2 = 0, i3 = 0;
int j1 = 0, j2 = 0, j3 = 0;
bool x_mat = (x.rows () == q);
bool y_mat = (y.columns () == p);
NDArray n (dim_vector (q, p, 3), 0.0);
for (int i = 0; i < p; i++)
{
if (y_mat)
{
i1 = i - 1;
i2 = i;
i3 = i + 1;
}
for (int j = 0; j < q; j++)
{
if (x_mat)
{
j1 = j - 1;
j2 = j;
j3 = j + 1;
}
double& nx = n(j, i, 0);
double& ny = n(j, i, 1);
double& nz = n(j, i, 2);
if ((j > 0) && (i > 0))
// upper left quadrangle
cross_product
(x(j1,i-1)-x(j2,i), y(j-1,i1)-y(j,i2), z(j-1,i-1)-z(j,i),
x(j2,i-1)-x(j1,i), y(j,i1)-y(j-1,i2), z(j,i-1)-z(j-1,i),
nx, ny, nz);
if ((j > 0) && (i < (p -1)))
// upper right quadrangle
cross_product
(x(j1,i+1)-x(j2,i), y(j-1,i3)-y(j,i2), z(j-1,i+1)-z(j,i),
x(j1,i)-x(j2,i+1), y(j-1,i2)-y(j,i3), z(j-1,i)-z(j,i+1),
nx, ny, nz);
if ((j < (q - 1)) && (i > 0))
// lower left quadrangle
cross_product
(x(j2,i-1)-x(j3,i), y(j,i1)-y(j+1,i2), z(j,i-1)-z(j+1,i),
x(j3,i-1)-x(j2,i), y(j+1,i1)-y(j,i2), z(j+1,i-1)-z(j,i),
nx, ny, nz);
if ((j < (q - 1)) && (i < (p -1)))
// lower right quadrangle
cross_product
(x(j3,i)-x(j2,i+1), y(j+1,i2)-y(j,i3), z(j+1,i)-z(j,i+1),
x(j3,i+1)-x(j2,i), y(j+1,i3)-y(j,i2), z(j+1,i+1)-z(j,i),
nx, ny, nz);
double d = -std::max (std::max (fabs (nx), fabs (ny)), fabs (nz));
nx /= d;
ny /= d;
nz /= d;
}
}
vertexnormals = n;
}
}
// ---------------------------------------------------------------------
void
hggroup::properties::update_limits (void) const
{
graphics_object obj = gh_manager::get_object (__myhandle__);
if (obj)
{
obj.update_axis_limits ("xlim");
obj.update_axis_limits ("ylim");
obj.update_axis_limits ("zlim");
obj.update_axis_limits ("clim");
obj.update_axis_limits ("alim");
}
}
void
hggroup::properties::update_limits (const graphics_handle& h) const
{
graphics_object obj = gh_manager::get_object (__myhandle__);
if (obj)
{
obj.update_axis_limits ("xlim", h);
obj.update_axis_limits ("ylim", h);
obj.update_axis_limits ("zlim", h);
obj.update_axis_limits ("clim", h);
obj.update_axis_limits ("alim", h);
}
}
static bool updating_hggroup_limits = false;
void
hggroup::update_axis_limits (const std::string& axis_type,
const graphics_handle& h)
{
if (updating_hggroup_limits)
return;
Matrix kids = Matrix (1, 1, h.value ());
double min_val = octave_Inf;
double max_val = -octave_Inf;
double min_pos = octave_Inf;
double max_neg = -octave_Inf;
Matrix limits;
double val;
char update_type = 0;
if (axis_type == "xlim" || axis_type == "xliminclude")
{
limits = xproperties.get_xlim ().matrix_value ();
update_type = 'x';
}
else if (axis_type == "ylim" || axis_type == "yliminclude")
{
limits = xproperties.get_ylim ().matrix_value ();
update_type = 'y';
}
else if (axis_type == "zlim" || axis_type == "zliminclude")
{
limits = xproperties.get_zlim ().matrix_value ();
update_type = 'z';
}
else if (axis_type == "clim" || axis_type == "climinclude")
{
limits = xproperties.get_clim ().matrix_value ();
update_type = 'c';
}
else if (axis_type == "alim" || axis_type == "aliminclude")
{
limits = xproperties.get_alim ().matrix_value ();
update_type = 'a';
}
if (limits.numel () == 4)
{
val = limits(0);
if (xfinite (val))
min_val = val;
val = limits(1);
if (xfinite (val))
max_val = val;
val = limits(2);
if (xfinite (val))
min_pos = val;
val = limits(3);
if (xfinite (val))
max_neg = val;
}
else
{
limits.resize (4,1);
limits(0) = min_val;
limits(1) = max_val;
limits(2) = min_pos;
limits(3) = max_neg;
}
get_children_limits (min_val, max_val, min_pos, max_neg, kids, update_type);
unwind_protect frame;
frame.protect_var (updating_hggroup_limits);
updating_hggroup_limits = true;
if (limits(0) != min_val || limits(1) != max_val
|| limits(2) != min_pos || limits(3) != max_neg)
{
limits(0) = min_val;
limits(1) = max_val;
limits(2) = min_pos;
limits(3) = max_neg;
switch (update_type)
{
case 'x':
xproperties.set_xlim (limits);
break;
case 'y':
xproperties.set_ylim (limits);
break;
case 'z':
xproperties.set_zlim (limits);
break;
case 'c':
xproperties.set_clim (limits);
break;
case 'a':
xproperties.set_alim (limits);
break;
default:
break;
}
base_graphics_object::update_axis_limits (axis_type, h);
}
}
void
hggroup::update_axis_limits (const std::string& axis_type)
{
if (updating_hggroup_limits)
return;
Matrix kids = xproperties.get_children ();
double min_val = octave_Inf;
double max_val = -octave_Inf;
double min_pos = octave_Inf;
double max_neg = -octave_Inf;
char update_type = 0;
if (axis_type == "xlim" || axis_type == "xliminclude")
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'x');
update_type = 'x';
}
else if (axis_type == "ylim" || axis_type == "yliminclude")
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'y');
update_type = 'y';
}
else if (axis_type == "zlim" || axis_type == "zliminclude")
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'z');
update_type = 'z';
}
else if (axis_type == "clim" || axis_type == "climinclude")
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'c');
update_type = 'c';
}
else if (axis_type == "alim" || axis_type == "aliminclude")
{
get_children_limits (min_val, max_val, min_pos, max_neg, kids, 'a');
update_type = 'a';
}
unwind_protect frame;
frame.protect_var (updating_hggroup_limits);
updating_hggroup_limits = true;
Matrix limits (1, 4, 0.0);
limits(0) = min_val;
limits(1) = max_val;
limits(2) = min_pos;
limits(3) = max_neg;
switch (update_type)
{
case 'x':
xproperties.set_xlim (limits);
break;
case 'y':
xproperties.set_ylim (limits);
break;
case 'z':
xproperties.set_zlim (limits);
break;
case 'c':
xproperties.set_clim (limits);
break;
case 'a':
xproperties.set_alim (limits);
break;
default:
break;
}
base_graphics_object::update_axis_limits (axis_type);
}
// ---------------------------------------------------------------------
octave_value
uicontrol::properties::get_extent (void) const
{
Matrix m = extent.get ().matrix_value ();
graphics_object parent_obj =
gh_manager::get_object (get_parent ());
Matrix parent_bbox = parent_obj.get_properties ().get_boundingbox (true),
parent_size = parent_bbox.extract_n (0, 2, 1, 2);
return convert_position (m, "pixels", get_units (), parent_size);
}
void
uicontrol::properties::update_text_extent (void)
{
#ifdef HAVE_FREETYPE
text_element *elt;
ft_render text_renderer;
Matrix box;
// FIXME: parsed content should be cached for efficiency
// FIXME: support multiline text
elt = text_parser::parse (get_string_string (), "none");
#ifdef HAVE_FONTCONFIG
text_renderer.set_font (get_fontname (),
get_fontweight (),
get_fontangle (),
get_fontsize ());
#endif
box = text_renderer.get_extent (elt, 0);
delete elt;
Matrix ext (1, 4, 0.0);
// FIXME: also handle left and bottom components
ext(0) = ext(1) = 1;
ext(2) = box(0);
ext(3) = box(1);
set_extent (ext);
#endif
}
void
uicontrol::properties::update_units (void)
{
Matrix pos = get_position ().matrix_value ();
graphics_object parent_obj = gh_manager::get_object (get_parent ());
Matrix parent_bbox = parent_obj.get_properties ().get_boundingbox (true),
parent_size = parent_bbox.extract_n (0, 2, 1, 2);
pos = convert_position (pos, cached_units, get_units (), parent_size);
set_position (pos);
cached_units = get_units ();
}
void
uicontrol::properties::set_style (const octave_value& st)
{
if (get___object__ ().is_empty ())
style = st;
else
error ("set: cannot change the style of a uicontrol object after creation.");
}
Matrix
uicontrol::properties::get_boundingbox (bool,
const Matrix& parent_pix_size) const
{
Matrix pos = get_position ().matrix_value ();
Matrix parent_size (parent_pix_size);
if (parent_size.numel () == 0)
{
graphics_object obj = gh_manager::get_object (get_parent ());
if (obj.valid_object ())
parent_size =
obj.get_properties ().get_boundingbox (true).extract_n (0, 2, 1, 2);
else
parent_size = default_figure_position ();
}
pos = convert_position (pos, get_units (), "pixels", parent_size);
pos(0)--;
pos(1)--;
pos(1) = parent_size(1) - pos(1) - pos(3);
return pos;
}
void
uicontrol::properties::set_fontunits (const octave_value& v)
{
if (! error_state)
{
caseless_str old_fontunits = get_fontunits ();
if (fontunits.set (v, true))
{
update_fontunits (old_fontunits);
mark_modified ();
}
}
}
void
uicontrol::properties::update_fontunits (const caseless_str& old_units)
{
caseless_str new_units = get_fontunits ();
double parent_height = get_boundingbox (false).elem (3);
double fsz = get_fontsize ();
fsz = convert_font_size (fsz, old_units, new_units, parent_height);
fontsize.set (octave_value (fsz), true);
}
double
uicontrol::properties::get_fontsize_points (double box_pix_height) const
{
double fs = get_fontsize ();
double parent_height = box_pix_height;
if (fontunits_is ("normalized") && parent_height <= 0)
parent_height = get_boundingbox (false).elem (3);
return convert_font_size (fs, get_fontunits (), "points", parent_height);
}
// ---------------------------------------------------------------------
Matrix
uipanel::properties::get_boundingbox (bool internal,
const Matrix& parent_pix_size) const
{
Matrix pos = get_position ().matrix_value ();
Matrix parent_size (parent_pix_size);
if (parent_size.numel () == 0)
{
graphics_object obj = gh_manager::get_object (get_parent ());
parent_size =
obj.get_properties ().get_boundingbox (true).extract_n (0, 2, 1, 2);
}
pos = convert_position (pos, get_units (), "pixels", parent_size);
pos(0)--;
pos(1)--;
pos(1) = parent_size(1) - pos(1) - pos(3);
if (internal)
{
double outer_height = pos(3);
pos(0) = pos(1) = 0;
if (! bordertype_is ("none"))
{
double bw = get_borderwidth ();
double mul = 1.0;
if (bordertype_is ("etchedin") || bordertype_is ("etchedout"))
mul = 2.0;
pos(0) += mul * bw;
pos(1) += mul * bw;
pos(2) -= 2 * mul * bw;
pos(3) -= 2 * mul * bw;
}
if (! get_title ().empty ())
{
double fs = get_fontsize ();
if (! fontunits_is ("pixels"))
{
double res = xget (0, "screenpixelsperinch").double_value ();
if (fontunits_is ("points"))
fs *= (res / 72.0);
else if (fontunits_is ("inches"))
fs *= res;
else if (fontunits_is ("centimeters"))
fs *= (res / 2.54);
else if (fontunits_is ("normalized"))
fs *= outer_height;
}
if (titleposition_is ("lefttop") || titleposition_is ("centertop")
|| titleposition_is ("righttop"))
pos(1) += (fs / 2);
pos(3) -= (fs / 2);
}
}
return pos;
}
void
uipanel::properties::set_units (const octave_value& v)
{
if (! error_state)
{
caseless_str old_units = get_units ();
if (units.set (v, true))
{
update_units (old_units);
mark_modified ();
}
}
}
void
uipanel::properties::update_units (const caseless_str& old_units)
{
Matrix pos = get_position ().matrix_value ();
graphics_object parent_obj = gh_manager::get_object (get_parent ());
Matrix parent_bbox = parent_obj.get_properties ().get_boundingbox (true),
parent_size = parent_bbox.extract_n (0, 2, 1, 2);
pos = convert_position (pos, old_units, get_units (), parent_size);
set_position (pos);
}
void
uipanel::properties::set_fontunits (const octave_value& v)
{
if (! error_state)
{
caseless_str old_fontunits = get_fontunits ();
if (fontunits.set (v, true))
{
update_fontunits (old_fontunits);
mark_modified ();
}
}
}
void
uipanel::properties::update_fontunits (const caseless_str& old_units)
{
caseless_str new_units = get_fontunits ();
double parent_height = get_boundingbox (false).elem (3);
double fsz = get_fontsize ();
fsz = convert_font_size (fsz, old_units, new_units, parent_height);
set_fontsize (octave_value (fsz));
}
double
uipanel::properties::get_fontsize_points (double box_pix_height) const
{
double fs = get_fontsize ();
double parent_height = box_pix_height;
if (fontunits_is ("normalized") && parent_height <= 0)
parent_height = get_boundingbox (false).elem (3);
return convert_font_size (fs, get_fontunits (), "points", parent_height);
}
// ---------------------------------------------------------------------
octave_value
uitoolbar::get_default (const caseless_str& name) const
{
octave_value retval = default_properties.lookup (name);
if (retval.is_undefined ())
{
graphics_handle parent = get_parent ();
graphics_object parent_obj = gh_manager::get_object (parent);
retval = parent_obj.get_default (name);
}
return retval;
}
void
uitoolbar::reset_default_properties (void)
{
::reset_default_properties (default_properties);
}
// ---------------------------------------------------------------------
octave_value
base_graphics_object::get_default (const caseless_str& name) const
{
graphics_handle parent = get_parent ();
graphics_object parent_obj = gh_manager::get_object (parent);
return parent_obj.get_default (type () + name);
}
octave_value
base_graphics_object::get_factory_default (const caseless_str& name) const
{
graphics_object parent_obj = gh_manager::get_object (0);
return parent_obj.get_factory_default (type () + name);
}
// We use a random value for the handle to avoid issues with plots and
// scalar values for the first argument.
gh_manager::gh_manager (void)
: handle_map (), handle_free_list (),
next_handle (-1.0 - (rand () + 1.0) / (RAND_MAX + 2.0)),
figure_list (), graphics_lock (), event_queue (),
callback_objects (), event_processing (0)
{
handle_map[0] = graphics_object (new root_figure ());
// Make sure the default graphics toolkit is registered.
gtk_manager::default_toolkit ();
}
void
gh_manager::create_instance (void)
{
instance = new gh_manager ();
if (instance)
singleton_cleanup_list::add (cleanup_instance);
}
graphics_handle
gh_manager::do_make_graphics_handle (const std::string& go_name,
const graphics_handle& p,
bool integer_figure_handle,
bool do_createfcn,
bool do_notify_toolkit)
{
graphics_handle h = get_handle (integer_figure_handle);
base_graphics_object *go = 0;
go = make_graphics_object_from_type (go_name, h, p);
if (go)
{
graphics_object obj (go);
handle_map[h] = obj;
if (do_createfcn)
go->get_properties ().execute_createfcn ();
// Notify graphics toolkit.
if (do_notify_toolkit)
obj.initialize ();
}
else
error ("gh_manager::do_make_graphics_handle: invalid object type '%s'",
go_name.c_str ());
return h;
}
graphics_handle
gh_manager::do_make_figure_handle (double val, bool do_notify_toolkit)
{
graphics_handle h = val;
base_graphics_object* go = new figure (h, 0);
graphics_object obj (go);
handle_map[h] = obj;
// Notify graphics toolkit.
if (do_notify_toolkit)
obj.initialize ();
return h;
}
void
gh_manager::do_push_figure (const graphics_handle& h)
{
do_pop_figure (h);
figure_list.push_front (h);
}
void
gh_manager::do_pop_figure (const graphics_handle& h)
{
for (figure_list_iterator p = figure_list.begin ();
p != figure_list.end ();
p++)
{
if (*p == h)
{
figure_list.erase (p);
break;
}
}
}
class
callback_event : public base_graphics_event
{
public:
callback_event (const graphics_handle& h, const std::string& name,
const octave_value& data = Matrix ())
: base_graphics_event (), handle (h), callback_name (name),
callback (), callback_data (data) { }
callback_event (const graphics_handle& h, const octave_value& cb,
const octave_value& data = Matrix ())
: base_graphics_event (), handle (h), callback_name (),
callback (cb), callback_data (data) { }
void execute (void)
{
if (callback.is_defined ())
gh_manager::execute_callback (handle, callback, callback_data);
else
gh_manager::execute_callback (handle, callback_name, callback_data);
}
private:
callback_event (void)
: base_graphics_event (), handle (), callback_name (), callback_data ()
{ }
private:
graphics_handle handle;
std::string callback_name;
octave_value callback;
octave_value callback_data;
};
class
function_event : public base_graphics_event
{
public:
function_event (graphics_event::event_fcn fcn, void* data = 0)
: base_graphics_event (), function (fcn), function_data (data)
{ }
void execute (void)
{
function (function_data);
}
private:
graphics_event::event_fcn function;
void* function_data;
// function_event objects must be created with at least a function.
function_event (void);
// No copying!
function_event (const function_event &);
function_event & operator = (const function_event &);
};
class
set_event : public base_graphics_event
{
public:
set_event (const graphics_handle& h, const std::string& name,
const octave_value& value, bool do_notify_toolkit = true)
: base_graphics_event (), handle (h), property_name (name),
property_value (value), notify_toolkit (do_notify_toolkit) { }
void execute (void)
{
gh_manager::auto_lock guard;
graphics_object go = gh_manager::get_object (handle);
if (go)
{
property p = go.get_properties ().get_property (property_name);
if (p.ok ())
p.set (property_value, true, notify_toolkit);
}
}
private:
set_event (void)
: base_graphics_event (), handle (), property_name (), property_value ()
{ }
private:
graphics_handle handle;
std::string property_name;
octave_value property_value;
bool notify_toolkit;
};
graphics_event
graphics_event::create_callback_event (const graphics_handle& h,
const std::string& name,
const octave_value& data)
{
graphics_event e;
e.rep = new callback_event (h, name, data);
return e;
}
graphics_event
graphics_event::create_callback_event (const graphics_handle& h,
const octave_value& cb,
const octave_value& data)
{
graphics_event e;
e.rep = new callback_event (h, cb, data);
return e;
}
graphics_event
graphics_event::create_function_event (graphics_event::event_fcn fcn,
void *data)
{
graphics_event e;
e.rep = new function_event (fcn, data);
return e;
}
graphics_event
graphics_event::create_set_event (const graphics_handle& h,
const std::string& name,
const octave_value& data,
bool notify_toolkit)
{
graphics_event e;
e.rep = new set_event (h, name, data, notify_toolkit);
return e;
}
static void
xset_gcbo (const graphics_handle& h)
{
graphics_object go = gh_manager::get_object (0);
root_figure::properties& props =
dynamic_cast<root_figure::properties&> (go.get_properties ());
props.set_callbackobject (h.as_octave_value ());
}
void
gh_manager::do_restore_gcbo (void)
{
gh_manager::auto_lock guard;
callback_objects.pop_front ();
xset_gcbo (callback_objects.empty ()
? graphics_handle ()
: callback_objects.front ().get_handle ());
}
void
gh_manager::do_execute_listener (const graphics_handle& h,
const octave_value& l)
{
if (octave_thread::is_octave_thread ())
gh_manager::execute_callback (h, l, octave_value ());
else
{
gh_manager::auto_lock guard;
do_post_event (graphics_event::create_callback_event (h, l));
}
}
void
gh_manager::do_execute_callback (const graphics_handle& h,
const octave_value& cb_arg,
const octave_value& data)
{
if (cb_arg.is_defined () && ! cb_arg.is_empty ())
{
octave_value_list args;
octave_function *fcn = 0;
args(0) = h.as_octave_value ();
if (data.is_defined ())
args(1) = data;
else
args(1) = Matrix ();
unwind_protect_safe frame;
frame.add_fcn (gh_manager::restore_gcbo);
if (true)
{
gh_manager::auto_lock guard;
callback_objects.push_front (get_object (h));
xset_gcbo (h);
}
BEGIN_INTERRUPT_WITH_EXCEPTIONS;
// Copy CB because "function_value" method is non-const.
octave_value cb = cb_arg;
if (cb.is_function () || cb.is_function_handle ())
fcn = cb.function_value ();
else if (cb.is_string ())
{
int status;
std::string s = cb.string_value ();
eval_string (s, false, status, 0);
}
else if (cb.is_cell () && cb.length () > 0
&& (cb.rows () == 1 || cb.columns () == 1)
&& (cb.cell_value ()(0).is_function ()
|| cb.cell_value ()(0).is_function_handle ()))
{
Cell c = cb.cell_value ();
fcn = c(0).function_value ();
if (! error_state)
{
for (int i = 1; i < c.length () ; i++)
args(1+i) = c(i);
}
}
else
{
std::string nm = cb.class_name ();
error ("trying to execute non-executable object (class = %s)",
nm.c_str ());
}
if (fcn && ! error_state)
feval (fcn, args);
END_INTERRUPT_WITH_EXCEPTIONS;
}
}
void
gh_manager::do_post_event (const graphics_event& e)
{
event_queue.push_back (e);
command_editor::add_event_hook (gh_manager::process_events);
}
void
gh_manager::do_post_callback (const graphics_handle& h, const std::string name,
const octave_value& data)
{
gh_manager::auto_lock guard;
graphics_object go = get_object (h);
if (go.valid_object ())
{
if (callback_objects.empty ())
do_post_event (graphics_event::create_callback_event (h, name, data));
else
{
const graphics_object& current = callback_objects.front ();
if (current.get_properties ().is_interruptible ())
do_post_event (graphics_event::create_callback_event (h, name,
data));
else
{
caseless_str busy_action (go.get_properties ().get_busyaction ());
if (busy_action.compare ("queue"))
do_post_event (graphics_event::create_callback_event (h, name,
data));
else
{
caseless_str cname (name);
if (cname.compare ("deletefcn") || cname.compare ("createfcn")
|| (go.isa ("figure")
&& (cname.compare ("closerequestfcn")
|| cname.compare ("resizefcn"))))
do_post_event (
graphics_event::create_callback_event (h, name, data));
}
}
}
}
}
void
gh_manager::do_post_function (graphics_event::event_fcn fcn, void* fcn_data)
{
gh_manager::auto_lock guard;
do_post_event (graphics_event::create_function_event (fcn, fcn_data));
}
void
gh_manager::do_post_set (const graphics_handle& h, const std::string name,
const octave_value& value, bool notify_toolkit)
{
gh_manager::auto_lock guard;
do_post_event (graphics_event::create_set_event (h, name, value,
notify_toolkit));
}
int
gh_manager::do_process_events (bool force)
{
graphics_event e;
bool old_Vdrawnow_requested = Vdrawnow_requested;
bool events_executed = false;
do
{
e = graphics_event ();
gh_manager::lock ();
if (! event_queue.empty ())
{
if (callback_objects.empty () || force)
{
e = event_queue.front ();
event_queue.pop_front ();
}
else
{
const graphics_object& go = callback_objects.front ();
if (go.get_properties ().is_interruptible ())
{
e = event_queue.front ();
event_queue.pop_front ();
}
}
}
gh_manager::unlock ();
if (e.ok ())
{
e.execute ();
events_executed = true;
}
}
while (e.ok ());
gh_manager::lock ();
if (event_queue.empty () && event_processing == 0)
command_editor::remove_event_hook (gh_manager::process_events);
gh_manager::unlock ();
if (events_executed)
flush_octave_stdout ();
if (Vdrawnow_requested && ! old_Vdrawnow_requested)
{
Fdrawnow ();
Vdrawnow_requested = false;
}
return 0;
}
void
gh_manager::do_enable_event_processing (bool enable)
{
gh_manager::auto_lock guard;
if (enable)
{
event_processing++;
command_editor::add_event_hook (gh_manager::process_events);
}
else
{
event_processing--;
if (event_queue.empty () && event_processing == 0)
command_editor::remove_event_hook (gh_manager::process_events);
}
}
property_list::plist_map_type
root_figure::init_factory_properties (void)
{
property_list::plist_map_type plist_map;
plist_map["figure"] = figure::properties::factory_defaults ();
plist_map["axes"] = axes::properties::factory_defaults ();
plist_map["line"] = line::properties::factory_defaults ();
plist_map["text"] = text::properties::factory_defaults ();
plist_map["image"] = image::properties::factory_defaults ();
plist_map["patch"] = patch::properties::factory_defaults ();
plist_map["surface"] = surface::properties::factory_defaults ();
plist_map["hggroup"] = hggroup::properties::factory_defaults ();
plist_map["uimenu"] = uimenu::properties::factory_defaults ();
plist_map["uicontrol"] = uicontrol::properties::factory_defaults ();
plist_map["uipanel"] = uipanel::properties::factory_defaults ();
plist_map["uicontextmenu"] = uicontextmenu::properties::factory_defaults ();
plist_map["uitoolbar"] = uitoolbar::properties::factory_defaults ();
plist_map["uipushtool"] = uipushtool::properties::factory_defaults ();
plist_map["uitoggletool"] = uitoggletool::properties::factory_defaults ();
return plist_map;
}
// ---------------------------------------------------------------------
DEFUN (ishandle, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} ishandle (@var{h})\n\
Return true if @var{h} is a graphics handle and false otherwise.\n\
\n\
@var{h} may also be a matrix of handles in which case a logical\n\
array is returned that is true where the elements of @var{h} are\n\
graphics handles and false where they are not.\n\
@seealso{isaxes, isfigure}\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
if (args.length () == 1)
retval = is_handle (args(0));
else
print_usage ();
return retval;
}
static bool
is_handle_visible (const graphics_handle& h)
{
return h.ok () && gh_manager::is_handle_visible (h);
}
static bool
is_handle_visible (double val)
{
return is_handle_visible (gh_manager::lookup (val));
}
static octave_value
is_handle_visible (const octave_value& val)
{
octave_value retval = false;
if (val.is_real_scalar () && is_handle_visible (val.double_value ()))
retval = true;
else if (val.is_numeric_type () && val.is_real_type ())
{
const NDArray handles = val.array_value ();
if (! error_state)
{
boolNDArray result (handles.dims ());
for (octave_idx_type i = 0; i < handles.numel (); i++)
result.xelem (i) = is_handle_visible (handles (i));
retval = result;
}
}
return retval;
}
DEFUN (__is_handle_visible__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} __is_handle_visible__ (@var{h})\n\
Undocumented internal function.\n\
@end deftypefn")
{
octave_value retval;
if (args.length () == 1)
retval = is_handle_visible (args(0));
else
print_usage ();
return retval;
}
DEFUN (reset, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} reset (@var{h}, @var{property})\n\
Remove any defaults set for the handle @var{h}. The default figure\n\
properties of @qcode{\"position\"}, @qcode{\"units\"},\n\
@qcode{\"windowstyle\"} and @qcode{\"paperunits\"} and the default axes\n\
properties of @qcode{\"position\"} and @qcode{\"units\"} are not reset.\n\
@seealso{cla, clf}\n\
@end deftypefn")
{
int nargin = args.length ();
if (nargin != 1)
print_usage ();
else
{
// get vector of graphics handles
ColumnVector hcv (args(0).vector_value ());
if (! error_state)
{
// loop over graphics objects
for (octave_idx_type n = 0; n < hcv.length (); n++)
gh_manager::get_object (hcv(n)).reset_default_properties ();
}
}
return octave_value ();
}
DEFUN (set, args, nargout,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} set (@var{h}, @var{property}, @var{value}, @dots{})\n\
@deftypefnx {Built-in Function} {} set (@var{h}, @var{properties}, @var{values})\n\
@deftypefnx {Built-in Function} {} set (@var{h}, @var{pv})\n\
Set named property values for the graphics handle (or vector of graphics\n\
handles) @var{h}.\n\
There are three ways how to give the property names and values:\n\
\n\
@itemize\n\
@item as a comma separated list of @var{property}, @var{value} pairs\n\
\n\
Here, each @var{property} is a string containing the property name, each\n\
@var{value} is a value of the appropriate type for the property.\n\
\n\
@item as a cell array of strings @var{properties} containing property names\n\
and a cell array @var{values} containing property values.\n\
\n\
In this case, the number of columns of @var{values} must match the number of\n\
elements in @var{properties}. The first column of @var{values} contains\n\
values for the first entry in @var{properties}, etc. The number of rows of\n\
@var{values} must be 1 or match the number of elements of @var{h}. In the\n\
first case, each handle in @var{h} will be assigned the same values. In the\n\
latter case, the first handle in @var{h} will be assigned the values from\n\
the first row of @var{values} and so on.\n\
\n\
@item as a structure array @var{pv}\n\
\n\
Here, the field names of @var{pv} represent the property names, and the field\n\
values give the property values. In contrast to the previous case, all\n\
elements of @var{pv} will be set in all handles in @var{h} independent of\n\
the dimensions of @var{pv}.\n\
@end itemize\n\
@seealso{get}\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
int nargin = args.length ();
if (nargin > 0)
{
// get vector of graphics handles
ColumnVector hcv (args(0).vector_value ());
if (! error_state)
{
bool request_drawnow = false;
// loop over graphics objects
for (octave_idx_type n = 0; n < hcv.length (); n++)
{
graphics_object obj = gh_manager::get_object (hcv(n));
if (obj)
{
if (nargin == 3 && args(1).is_cellstr ()
&& args(2).is_cell ())
{
if (args(2).cell_value ().rows () == 1)
{
obj.set (args(1).cellstr_value (),
args(2).cell_value (), 0);
}
else if (hcv.length () == args(2).cell_value ().rows ())
{
obj.set (args(1).cellstr_value (),
args(2).cell_value (), n);
}
else
{
error ("set: number of graphics handles must match number of value rows (%d != %d)",
hcv.length (), args(2).cell_value ().rows ());
break;
}
}
else if (nargin == 2 && args(1).is_map ())
{
obj.set (args(1).map_value ());
}
else if (nargin == 1)
{
if (nargout != 0)
retval = obj.values_as_struct ();
else
{
std::string s = obj.values_as_string ();
if (! error_state)
octave_stdout << s;
}
}
else
{
obj.set (args.splice (0, 1));
request_drawnow = true;
}
}
else
{
error ("set: invalid handle (= %g)", hcv(n));
break;
}
if (error_state)
break;
request_drawnow = true;
}
if (! error_state && request_drawnow)
Vdrawnow_requested = true;
}
else
error ("set: expecting graphics handle as first argument");
}
else
print_usage ();
return retval;
}
static std::string
get_graphics_object_type (const double val)
{
std::string retval;
graphics_object obj = gh_manager::get_object (val);
if (obj)
retval = obj.type ();
else
error ("get: invalid handle (= %g)", val);
return retval;
}
DEFUN (get, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {@var{val} =} get (@var{h})\n\
@deftypefnx {Built-in Function} {@var{val} =} get (@var{h}, @var{p})\n\
Return the value of the named property @var{p} from the graphics handle\n\
@var{h}. If @var{p} is omitted, return the complete property list for\n\
@var{h}. If @var{h} is a vector, return a cell array including the property\n\
values or lists respectively.\n\
@seealso{set}\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
Cell vals;
int nargin = args.length ();
bool use_cell_format = false;
if (nargin == 1 || nargin == 2)
{
if (args(0).is_empty ())
{
retval = Matrix ();
return retval;
}
ColumnVector hcv (args(0).vector_value ());
if (! error_state)
{
octave_idx_type len = hcv.length ();
if (nargin == 1 && len > 1)
{
std::string t0 = get_graphics_object_type (hcv(0));
if (! error_state)
{
for (octave_idx_type n = 1; n < len; n++)
{
std::string t = get_graphics_object_type (hcv(n));
if (error_state)
break;
if (t != t0)
{
error ("get: vector of handles must all have same type");
break;
}
}
}
}
if (! error_state)
{
if (nargin > 1 && args(1).is_cellstr ())
{
Array<std::string> plist = args(1).cellstr_value ();
if (! error_state)
{
octave_idx_type plen = plist.numel ();
use_cell_format = true;
vals.resize (dim_vector (len, plen));
for (octave_idx_type n = 0; ! error_state && n < len; n++)
{
graphics_object obj = gh_manager::get_object (hcv(n));
if (obj)
{
for (octave_idx_type m = 0;
! error_state && m < plen;
m++)
{
caseless_str property = plist(m);
vals(n, m) = obj.get (property);
}
}
else
{
error ("get: invalid handle (= %g)", hcv(n));
break;
}
}
}
else
error ("get: expecting property name or cell array of property names as second argument");
}
else
{
caseless_str property;
if (nargin > 1)
{
property = args(1).string_value ();
if (error_state)
error ("get: expecting property name or cell array of property names as second argument");
}
vals.resize (dim_vector (len, 1));
if (! error_state)
{
for (octave_idx_type n = 0; ! error_state && n < len; n++)
{
graphics_object obj = gh_manager::get_object (hcv(n));
if (obj)
{
if (nargin == 1)
vals(n) = obj.get ();
else
vals(n) = obj.get (property);
}
else
{
error ("get: invalid handle (= %g)", hcv(n));
break;
}
}
}
}
}
}
else
error ("get: expecting graphics handle as first argument");
}
else
print_usage ();
if (! error_state)
{
if (use_cell_format)
retval = vals;
else
{
octave_idx_type len = vals.numel ();
if (len == 0)
retval = Matrix ();
else if (len == 1)
retval = vals(0);
else if (len > 1 && nargin == 1)
{
OCTAVE_LOCAL_BUFFER (octave_scalar_map, tmp, len);
for (octave_idx_type n = 0; n < len; n++)
tmp[n] = vals(n).scalar_map_value ();
retval = octave_map::cat (0, len, tmp);
}
else
retval = vals;
}
}
return retval;
}
/*
%!assert (get (findobj (0, "Tag", "nonexistenttag"), "nonexistentproperty"), [])
*/
// Return all properties from the graphics handle @var{h}.
// If @var{h} is a vector, return a cell array including the
// property values or lists respectively.
DEFUN (__get__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __get__ (@var{h})\n\
Undocumented internal function.\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
Cell vals;
int nargin = args.length ();
if (nargin == 1)
{
ColumnVector hcv (args(0).vector_value ());
if (! error_state)
{
octave_idx_type len = hcv.length ();
vals.resize (dim_vector (len, 1));
for (octave_idx_type n = 0; n < len; n++)
{
graphics_object obj = gh_manager::get_object (hcv(n));
if (obj)
vals(n) = obj.get (true);
else
{
error ("get: invalid handle (= %g)", hcv(n));
break;
}
}
}
else
error ("get: expecting graphics handle as first argument");
}
else
print_usage ();
if (! error_state)
{
octave_idx_type len = vals.numel ();
if (len > 1)
retval = vals;
else if (len == 1)
retval = vals(0);
}
return retval;
}
static octave_value
make_graphics_object (const std::string& go_name,
bool integer_figure_handle,
const octave_value_list& args)
{
octave_value retval;
double val = octave_NaN;
octave_value_list xargs = args.splice (0, 1);
caseless_str p ("parent");
for (int i = 0; i < xargs.length (); i++)
if (xargs(i).is_string ()
&& p.compare (xargs(i).string_value ()))
{
if (i < (xargs.length () - 1))
{
val = xargs(i+1).double_value ();
if (! error_state)
{
xargs = xargs.splice (i, 2);
break;
}
}
else
error ("__go_%s__: missing value for parent property",
go_name.c_str ());
}
if (! error_state && xisnan (val))
val = args(0).double_value ();
if (! error_state)
{
graphics_handle parent = gh_manager::lookup (val);
if (parent.ok ())
{
graphics_handle h
= gh_manager::make_graphics_handle (go_name, parent,
integer_figure_handle,
false, false);
if (! error_state)
{
adopt (parent, h);
xset (h, xargs);
xcreatefcn (h);
xinitialize (h);
retval = h.value ();
if (! error_state)
Vdrawnow_requested = true;
}
else
error ("__go%s__: unable to create graphics handle",
go_name.c_str ());
}
else
error ("__go_%s__: invalid parent", go_name.c_str ());
}
else
error ("__go_%s__: invalid parent", go_name.c_str ());
return retval;
}
DEFUN (__go_figure__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_figure__ (@var{fignum})\n\
Undocumented internal function.\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
if (args.length () > 0)
{
double val = args(0).double_value ();
if (! error_state)
{
if (is_figure (val))
{
graphics_handle h = gh_manager::lookup (val);
xset (h, args.splice (0, 1));
retval = h.value ();
}
else
{
bool int_fig_handle = true;
octave_value_list xargs = args.splice (0, 1);
graphics_handle h = octave_NaN;
if (xisnan (val))
{
caseless_str p ("integerhandle");
for (int i = 0; i < xargs.length (); i++)
{
if (xargs(i).is_string ()
&& p.compare (xargs(i).string_value ()))
{
if (i < (xargs.length () - 1))
{
std::string pval = xargs(i+1).string_value ();
if (! error_state)
{
caseless_str on ("on");
int_fig_handle = on.compare (pval);
xargs = xargs.splice (i, 2);
break;
}
}
}
}
h = gh_manager::make_graphics_handle ("figure", 0,
int_fig_handle,
false, false);
if (! int_fig_handle)
{
// We need to intiailize the integerhandle
// property without calling the set_integerhandle
// method, because doing that will generate a new
// handle value...
graphics_object go = gh_manager::get_object (h);
go.get_properties ().init_integerhandle ("off");
}
}
else if (val > 0 && D_NINT (val) == val)
h = gh_manager::make_figure_handle (val, false);
if (! error_state && h.ok ())
{
adopt (0, h);
gh_manager::push_figure (h);
xset (h, xargs);
xcreatefcn (h);
xinitialize (h);
retval = h.value ();
}
else
error ("__go_figure__: failed to create figure handle");
}
}
else
error ("__go_figure__: expecting figure number to be double value");
}
else
print_usage ();
return retval;
}
#define GO_BODY(TYPE) \
gh_manager::auto_lock guard; \
\
octave_value retval; \
\
if (args.length () > 0) \
retval = make_graphics_object (#TYPE, false, args); \
else \
print_usage (); \
\
return retval
int
calc_dimensions (const graphics_object& go)
{
int nd = 2;
if (go.isa ("surface"))
nd = 3;
else if ((go.isa ("line") || go.isa ("patch"))
&& ! go.get ("zdata").is_empty ())
nd = 3;
else
{
Matrix kids = go.get_properties ().get_children ();
for (octave_idx_type i = 0; i < kids.length (); i++)
{
graphics_handle hnd = gh_manager::lookup (kids(i));
if (hnd.ok ())
{
const graphics_object& kid = gh_manager::get_object (hnd);
if (kid.valid_object ())
nd = calc_dimensions (kid);
if (nd == 3)
break;
}
}
}
return nd;
}
DEFUN (__calc_dimensions__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __calc_dimensions__ (@var{axes})\n\
Internal function. Determine the number of dimensions in a graphics\n\
object, whether 2 or 3.\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
int nargin = args.length ();
if (nargin != 1)
print_usage ();
double h = args(0).double_value ();
if (! error_state)
retval = calc_dimensions (gh_manager::get_object (h));
else
error ("__calc_dimensions__: expecting graphics handle as only argument");
return retval;
}
DEFUN (__go_axes__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_axes__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (axes);
}
DEFUN (__go_line__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_line__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (line);
}
DEFUN (__go_text__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_text__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (text);
}
DEFUN (__go_image__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_image__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (image);
}
DEFUN (__go_surface__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_surface__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (surface);
}
DEFUN (__go_patch__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_patch__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (patch);
}
DEFUN (__go_hggroup__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_hggroup__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (hggroup);
}
DEFUN (__go_uimenu__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_uimenu__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (uimenu);
}
DEFUN (__go_uicontrol__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_uicontrol__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (uicontrol);
}
DEFUN (__go_uipanel__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_uipanel__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (uipanel);
}
DEFUN (__go_uicontextmenu__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_uicontextmenu__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (uicontextmenu);
}
DEFUN (__go_uitoolbar__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_uitoolbar__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (uitoolbar);
}
DEFUN (__go_uipushtool__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_uipushtool__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (uipushtool);
}
DEFUN (__go_uitoggletool__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_uitoggletool__ (@var{parent})\n\
Undocumented internal function.\n\
@end deftypefn")
{
GO_BODY (uitoggletool);
}
DEFUN (__go_delete__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_delete__ (@var{h})\n\
Undocumented internal function.\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value_list retval;
if (args.length () == 1)
{
graphics_handle h = octave_NaN;
const NDArray vals = args (0).array_value ();
if (! error_state)
{
// Check is all the handles to delete are valid first
// as callbacks might delete one of the handles we
// later want to delete
for (octave_idx_type i = 0; i < vals.numel (); i++)
{
h = gh_manager::lookup (vals.elem (i));
if (! h.ok ())
{
error ("delete: invalid graphics object (= %g)",
vals.elem (i));
break;
}
}
if (! error_state)
delete_graphics_objects (vals);
}
else
error ("delete: invalid graphics object");
}
else
print_usage ();
return retval;
}
DEFUN (__go_axes_init__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_axes_init__ (@var{h}, @var{mode})\n\
Undocumented internal function.\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
int nargin = args.length ();
std::string mode = "";
if (nargin == 2)
{
mode = args(1).string_value ();
if (error_state)
return retval;
}
if (nargin == 1 || nargin == 2)
{
graphics_handle h = octave_NaN;
double val = args(0).double_value ();
if (! error_state)
{
h = gh_manager::lookup (val);
if (h.ok ())
{
graphics_object obj = gh_manager::get_object (h);
obj.set_defaults (mode);
h = gh_manager::lookup (val);
if (! h.ok ())
error ("__go_axes_init__: axis deleted during initialization (= %g)",
val);
}
else
error ("__go_axes_init__: invalid graphics object (= %g)", val);
}
else
error ("__go_axes_init__: invalid graphics object");
}
else
print_usage ();
return retval;
}
DEFUN (__go_handles__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_handles__ (@var{show_hidden})\n\
Undocumented internal function.\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
bool show_hidden = false;
if (args.length () > 0)
show_hidden = args(0).bool_value ();
return octave_value (gh_manager::handle_list (show_hidden));
}
DEFUN (__go_figure_handles__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_figure_handles__ (@var{show_hidden})\n\
Undocumented internal function.\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
bool show_hidden = false;
if (args.length () > 0)
show_hidden = args(0).bool_value ();
return octave_value (gh_manager::figure_handle_list (show_hidden));
}
DEFUN (__go_execute_callback__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} __go_execute_callback__ (@var{h}, @var{name})\n\
@deftypefnx {Built-in Function} {} __go_execute_callback__ (@var{h}, @var{name}, @var{param})\n\
Undocumented internal function.\n\
@end deftypefn")
{
octave_value retval;
int nargin = args.length ();
if (nargin == 2 || nargin == 3)
{
double val = args(0).double_value ();
if (! error_state)
{
graphics_handle h = gh_manager::lookup (val);
if (h.ok ())
{
std::string name = args(1).string_value ();
if (! error_state)
{
if (nargin == 2)
gh_manager::execute_callback (h, name);
else
gh_manager::execute_callback (h, name, args(2));
}
else
error ("__go_execute_callback__: invalid callback name");
}
else
error ("__go_execute_callback__: invalid graphics object (= %g)",
val);
}
else
error ("__go_execute_callback__: invalid graphics object");
}
else
print_usage ();
return retval;
}
DEFUN (__image_pixel_size__, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {@var{px}, @var{py}} __image_pixel_size__ (@var{h})\n\
Internal function: returns the pixel size of the image in normalized units.\n\
@end deftypefn")
{
octave_value retval;
int nargin = args.length ();
if (nargin == 1)
{
double h = args(0).double_value ();
if (! error_state)
{
graphics_object fobj = gh_manager::get_object (h);
if (fobj && fobj.isa ("image"))
{
image::properties& ip =
dynamic_cast<image::properties&> (fobj.get_properties ());
Matrix dp = Matrix (1, 2, 0);
dp(0, 0) = ip.pixel_xsize ();
dp(0, 1) = ip.pixel_ysize ();
retval = dp;
}
else
error ("__image_pixel_size__: object is not an image");
}
else
error ("__image_pixel_size__: argument is not a handle");
}
else
print_usage ();
return retval;
}
gtk_manager *gtk_manager::instance = 0;
gtk_manager::gtk_manager (void)
: dtk (), available_toolkits (), loaded_toolkits ()
{
#if defined (HAVE_FLTK)
dtk = display_info::display_available () ? "fltk" : "gnuplot";
#else
dtk = "gnuplot";
#endif
}
void
gtk_manager::create_instance (void)
{
instance = new gtk_manager ();
if (instance)
singleton_cleanup_list::add (cleanup_instance);
}
graphics_toolkit
gtk_manager::do_get_toolkit (void) const
{
graphics_toolkit retval;
const_loaded_toolkits_iterator pl = loaded_toolkits.find (dtk);
if (pl == loaded_toolkits.end ())
{
const_available_toolkits_iterator pa = available_toolkits.find (dtk);
if (pa != available_toolkits.end ())
{
octave_value_list args;
args(0) = dtk;
feval ("graphics_toolkit", args);
if (! error_state)
pl = loaded_toolkits.find (dtk);
if (error_state || pl == loaded_toolkits.end ())
error ("failed to load %s graphics toolkit", dtk.c_str ());
else
retval = pl->second;
}
else
error ("default graphics toolkit '%s' is not available!",
dtk.c_str ());
}
else
retval = pl->second;
return retval;
}
DEFUN (available_graphics_toolkits, , ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} available_graphics_toolkits ()\n\
Return a cell array of registered graphics toolkits.\n\
@seealso{graphics_toolkit, register_graphics_toolkit}\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
return octave_value (gtk_manager::available_toolkits_list ());
}
DEFUN (register_graphics_toolkit, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} register_graphics_toolkit (@var{toolkit})\n\
List @var{toolkit} as an available graphics toolkit.\n\
@seealso{available_graphics_toolkits}\n\
@end deftypefn")
{
octave_value retval;
gh_manager::auto_lock guard;
if (args.length () == 1)
{
std::string name = args(0).string_value ();
if (! error_state)
gtk_manager::register_toolkit (name);
else
error ("register_graphics_toolkit: expecting character string");
}
else
print_usage ();
return retval;
}
DEFUN (loaded_graphics_toolkits, , ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} loaded_graphics_toolkits ()\n\
Return a cell array of the currently loaded graphics toolkits.\n\
@seealso{available_graphics_toolkits}\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
return octave_value (gtk_manager::loaded_toolkits_list ());
}
DEFUN (drawnow, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} drawnow ()\n\
@deftypefnx {Built-in Function} {} drawnow (\"expose\")\n\
@deftypefnx {Built-in Function} {} drawnow (@var{term}, @var{file}, @var{mono}, @var{debug_file})\n\
Update figure windows and their children. The event queue is flushed and\n\
any callbacks generated are executed. With the optional argument\n\
@qcode{\"expose\"}, only graphic objects are updated and no other events or\n\
callbacks are processed.\n\
The third calling form of @code{drawnow} is for debugging and is\n\
undocumented.\n\
@end deftypefn")
{
static int drawnow_executing = 0;
octave_value retval;
gh_manager::lock ();
unwind_protect frame;
frame.protect_var (Vdrawnow_requested, false);
frame.protect_var (drawnow_executing);
if (++drawnow_executing <= 1)
{
if (args.length () == 0 || args.length () == 1)
{
Matrix hlist = gh_manager::figure_handle_list (true);
for (int i = 0; ! error_state && i < hlist.length (); i++)
{
graphics_handle h = gh_manager::lookup (hlist(i));
if (h.ok () && h != 0)
{
graphics_object go = gh_manager::get_object (h);
figure::properties& fprops
= dynamic_cast <figure::properties&> (go.get_properties ());
if (fprops.is_modified ())
{
if (fprops.is_visible ())
{
gh_manager::unlock ();
fprops.get_toolkit ().redraw_figure (go);
gh_manager::lock ();
}
fprops.set_modified (false);
}
}
}
bool do_events = true;
if (args.length () == 1)
{
caseless_str val (args(0).string_value ());
if (! error_state && val.compare ("expose"))
do_events = false;
else
{
error ("drawnow: invalid argument, expected 'expose' as argument");
return retval;
}
}
if (do_events)
{
gh_manager::unlock ();
gh_manager::process_events ();
gh_manager::lock ();
}
}
else if (args.length () >= 2 && args.length () <= 4)
{
std::string term, file, debug_file;
bool mono;
term = args(0).string_value ();
if (! error_state)
{
file = args(1).string_value ();
if (! error_state)
{
size_t pos = file.find_first_not_of ("|");
if (pos > 0)
file = file.substr (pos);
else
{
pos = file.find_last_of (file_ops::dir_sep_chars ());
if (pos != std::string::npos)
{
std::string dirname = file.substr (0, pos+1);
file_stat fs (dirname);
if (! (fs && fs.is_dir ()))
{
error ("drawnow: nonexistent directory '%s'",
dirname.c_str ());
return retval;
}
}
}
mono = (args.length () >= 3 ? args(2).bool_value () : false);
if (! error_state)
{
debug_file = (args.length () > 3 ? args(3).string_value ()
: "");
if (! error_state)
{
graphics_handle h = gcf ();
if (h.ok ())
{
graphics_object go = gh_manager::get_object (h);
gh_manager::unlock ();
go.get_toolkit ().print_figure (go, term, file,
mono, debug_file);
gh_manager::lock ();
}
else
error ("drawnow: nothing to draw");
}
else
error ("drawnow: invalid DEBUG_FILE, expected a string value");
}
else
error ("drawnow: invalid colormode MONO, expected a boolean value");
}
else
error ("drawnow: invalid FILE, expected a string value");
}
else
error ("drawnow: invalid terminal TERM, expected a string value");
}
else
print_usage ();
}
gh_manager::unlock ();
return retval;
}
DEFUN (addlistener, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} addlistener (@var{h}, @var{prop}, @var{fcn})\n\
Register @var{fcn} as listener for the property @var{prop} of the graphics\n\
object @var{h}. Property listeners are executed (in order of registration)\n\
when the property is set. The new value is already available when the\n\
listeners are executed.\n\
\n\
@var{prop} must be a string naming a valid property in @var{h}.\n\
\n\
@var{fcn} can be a function handle, a string or a cell array whose first\n\
element is a function handle. If @var{fcn} is a function handle, the\n\
corresponding function should accept at least 2 arguments, that will be\n\
set to the object handle and the empty matrix respectively. If @var{fcn}\n\
is a string, it must be any valid octave expression. If @var{fcn} is a cell\n\
array, the first element must be a function handle with the same signature\n\
as described above. The next elements of the cell array are passed\n\
as additional arguments to the function.\n\
\n\
Example:\n\
\n\
@example\n\
@group\n\
function my_listener (h, dummy, p1)\n\
fprintf (\"my_listener called with p1=%s\\n\", p1);\n\
endfunction\n\
\n\
addlistener (gcf, \"position\", @{@@my_listener, \"my string\"@})\n\
@end group\n\
@end example\n\
\n\
@seealso{addproperty, hggroup}\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
if (args.length () >= 3 && args.length () <= 4)
{
double h = args(0).double_value ();
if (! error_state)
{
std::string pname = args(1).string_value ();
if (! error_state)
{
graphics_handle gh = gh_manager::lookup (h);
if (gh.ok ())
{
graphics_object go = gh_manager::get_object (gh);
go.add_property_listener (pname, args(2), POSTSET);
if (args.length () == 4)
{
caseless_str persistent = args(3).string_value ();
if (persistent.compare ("persistent"))
go.add_property_listener (pname, args(2), PERSISTENT);
}
}
else
error ("addlistener: invalid graphics object (= %g)",
h);
}
else
error ("addlistener: invalid property name, expected a string value");
}
else
error ("addlistener: invalid handle");
}
else
print_usage ();
return retval;
}
DEFUN (dellistener, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} dellistener (@var{h}, @var{prop}, @var{fcn})\n\
Remove the registration of @var{fcn} as a listener for the property\n\
@var{prop} of the graphics object @var{h}. The function @var{fcn} must\n\
be the same variable (not just the same value), as was passed to the\n\
original call to @code{addlistener}.\n\
\n\
If @var{fcn} is not defined then all listener functions of @var{prop}\n\
are removed.\n\
\n\
Example:\n\
\n\
@example\n\
@group\n\
function my_listener (h, dummy, p1)\n\
fprintf (\"my_listener called with p1=%s\\n\", p1);\n\
endfunction\n\
\n\
c = @{@@my_listener, \"my string\"@};\n\
addlistener (gcf, \"position\", c);\n\
dellistener (gcf, \"position\", c);\n\
@end group\n\
@end example\n\
\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
if (args.length () == 3 || args.length () == 2)
{
double h = args(0).double_value ();
if (! error_state)
{
std::string pname = args(1).string_value ();
if (! error_state)
{
graphics_handle gh = gh_manager::lookup (h);
if (gh.ok ())
{
graphics_object go = gh_manager::get_object (gh);
if (args.length () == 2)
go.delete_property_listener (pname, octave_value (),
POSTSET);
else
{
caseless_str persistent = args(2).string_value ();
if (persistent.compare ("persistent"))
{
go.delete_property_listener (pname, octave_value (),
PERSISTENT);
go.delete_property_listener (pname, octave_value (),
POSTSET);
}
else
go.delete_property_listener (pname, args(2), POSTSET);
}
}
else
error ("dellistener: invalid graphics object (= %g)",
h);
}
else
error ("dellistener: invalid property name, expected a string value");
}
else
error ("dellistener: invalid handle");
}
else
print_usage ();
return retval;
}
DEFUN (addproperty, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} addproperty (@var{name}, @var{h}, @var{type})\n\
@deftypefnx {Built-in Function} {} addproperty (@var{name}, @var{h}, @var{type}, @var{arg}, @dots{})\n\
Create a new property named @var{name} in graphics object @var{h}.\n\
@var{type} determines the type of the property to create. @var{args}\n\
usually contains the default value of the property, but additional\n\
arguments might be given, depending on the type of the property.\n\
\n\
The supported property types are:\n\
\n\
@table @code\n\
@item string\n\
A string property. @var{arg} contains the default string value.\n\
\n\
@item any\n\
An @nospell{un-typed} property. This kind of property can hold any octave\n\
value. @var{args} contains the default value.\n\
\n\
@item radio\n\
A string property with a limited set of accepted values. The first\n\
argument must be a string with all accepted values separated by\n\
a vertical bar ('|'). The default value can be marked by enclosing\n\
it with a '@{' '@}' pair. The default value may also be given as\n\
an optional second string argument.\n\
\n\
@item boolean\n\
A boolean property. This property type is equivalent to a radio\n\
property with \"on|off\" as accepted values. @var{arg} contains\n\
the default property value.\n\
\n\
@item double\n\
A scalar double property. @var{arg} contains the default value.\n\
\n\
@item handle\n\
A handle property. This kind of property holds the handle of a\n\
graphics object. @var{arg} contains the default handle value.\n\
When no default value is given, the property is initialized to\n\
the empty matrix.\n\
\n\
@item data\n\
A data (matrix) property. @var{arg} contains the default data\n\
value. When no default value is given, the data is initialized to\n\
the empty matrix.\n\
\n\
@item color\n\
A color property. @var{arg} contains the default color value.\n\
When no default color is given, the property is set to black.\n\
An optional second string argument may be given to specify an\n\
additional set of accepted string values (like a radio property).\n\
@end table\n\
\n\
@var{type} may also be the concatenation of a core object type and\n\
a valid property name for that object type. The property created\n\
then has the same characteristics as the referenced property (type,\n\
possible values, hidden state@dots{}). This allows to clone an existing\n\
property into the graphics object @var{h}.\n\
\n\
Examples:\n\
\n\
@example\n\
@group\n\
addproperty (\"my_property\", gcf, \"string\", \"a string value\");\n\
addproperty (\"my_radio\", gcf, \"radio\", \"val_1|val_2|@{val_3@}\");\n\
addproperty (\"my_style\", gcf, \"linelinestyle\", \"--\");\n\
@end group\n\
@end example\n\
\n\
@seealso{addlistener, hggroup}\n\
@end deftypefn")
{
gh_manager::auto_lock guard;
octave_value retval;
if (args.length () >= 3)
{
std::string name = args(0).string_value ();
if (! error_state)
{
double h = args(1).double_value ();
if (! error_state)
{
graphics_handle gh = gh_manager::lookup (h);
if (gh.ok ())
{
graphics_object go = gh_manager::get_object (gh);
std::string type = args(2).string_value ();
if (! error_state)
{
if (! go.get_properties ().has_property (name))
{
property p = property::create (name, gh, type,
args.splice (0, 3));
if (! error_state)
go.get_properties ().insert_property (name, p);
}
else
error ("addproperty: a '%s' property already exists in the graphics object",
name.c_str ());
}
else
error ("addproperty: invalid property TYPE, expected a string value");
}
else
error ("addproperty: invalid graphics object (= %g)", h);
}
else
error ("addproperty: invalid handle value");
}
else
error ("addproperty: invalid property NAME, expected a string value");
}
else
print_usage ();
return retval;
}
octave_value
get_property_from_handle (double handle, const std::string& property,
const std::string& func)
{
gh_manager::auto_lock guard;
graphics_object obj = gh_manager::get_object (handle);
octave_value retval;
if (obj)
retval = obj.get (caseless_str (property));
else
error ("%s: invalid handle (= %g)", func.c_str (), handle);
return retval;
}
bool
set_property_in_handle (double handle, const std::string& property,
const octave_value& arg, const std::string& func)
{
gh_manager::auto_lock guard;
graphics_object obj = gh_manager::get_object (handle);
int ret = false;
if (obj)
{
obj.set (caseless_str (property), arg);
if (! error_state)
ret = true;
}
else
error ("%s: invalid handle (= %g)", func.c_str (), handle);
return ret;
}
static bool
compare_property_values (const octave_value& o1, const octave_value& o2)
{
octave_value_list args (2);
args(0) = o1;
args(1) = o2;
octave_value_list result = feval ("isequal", args, 1);
if (! error_state && result.length () > 0)
return result(0).bool_value ();
return false;
}
static std::map<uint32_t, bool> waitfor_results;
static void
cleanup_waitfor_id (uint32_t id)
{
waitfor_results.erase (id);
}
static void
do_cleanup_waitfor_listener (const octave_value& listener,
listener_mode mode = POSTSET)
{
Cell c = listener.cell_value ();
if (c.numel () >= 4)
{
double h = c(2).double_value ();
if (! error_state)
{
caseless_str pname = c(3).string_value ();
if (! error_state)
{
gh_manager::auto_lock guard;
graphics_handle handle = gh_manager::lookup (h);
if (handle.ok ())
{
graphics_object go = gh_manager::get_object (handle);
if (go.get_properties ().has_property (pname))
{
go.get_properties ().delete_listener (pname, listener,
mode);
if (mode == POSTSET)
go.get_properties ().delete_listener (pname, listener,
PERSISTENT);
}
}
}
}
}
}
static void
cleanup_waitfor_postset_listener (const octave_value& listener)
{ do_cleanup_waitfor_listener (listener, POSTSET); }
static void
cleanup_waitfor_predelete_listener (const octave_value& listener)
{ do_cleanup_waitfor_listener (listener, PREDELETE); }
static octave_value_list
waitfor_listener (const octave_value_list& args, int)
{
if (args.length () > 3)
{
uint32_t id = args(2).uint32_scalar_value ().value ();
if (! error_state)
{
if (args.length () > 5)
{
double h = args(0).double_value ();
if (! error_state)
{
caseless_str pname = args(4).string_value ();
if (! error_state)
{
gh_manager::auto_lock guard;
graphics_handle handle = gh_manager::lookup (h);
if (handle.ok ())
{
graphics_object go = gh_manager::get_object (handle);
octave_value pvalue = go.get (pname);
if (compare_property_values (pvalue, args(5)))
waitfor_results[id] = true;
}
}
}
}
else
waitfor_results[id] = true;
}
}
return octave_value_list ();
}
static octave_value_list
waitfor_del_listener (const octave_value_list& args, int)
{
if (args.length () > 2)
{
uint32_t id = args(2).uint32_scalar_value ().value ();
if (! error_state)
waitfor_results[id] = true;
}
return octave_value_list ();
}
DEFUN (waitfor, args, ,
"-*- texinfo -*-\n\
@deftypefn {Built-in Function} {} waitfor (@var{h})\n\
@deftypefnx {Built-in Function} {} waitfor (@var{h}, @var{prop})\n\
@deftypefnx {Built-in Function} {} waitfor (@var{h}, @var{prop}, @var{value})\n\
@deftypefnx {Built-in Function} {} waitfor (@dots{}, \"timeout\", @var{timeout})\n\
Suspend the execution of the current program until a condition is\n\
satisfied on the graphics handle @var{h}.\n\
\n\
While the program is suspended graphics events are still being processed\n\
normally, allowing callbacks to modify the state of graphics objects. This\n\
function is reentrant and can be called from a callback, while another\n\
@code{waitfor} call is pending at the top-level.\n\
\n\
In the first form, program execution is suspended until the graphics object\n\
@var{h} is destroyed. If the graphics handle is invalid, the function\n\
returns immediately.\n\
\n\
In the second form, execution is suspended until the graphics object is\n\
destroyed or the property named @var{prop} is modified. If the graphics\n\
handle is invalid or the property does not exist, the function returns\n\
immediately.\n\
\n\
In the third form, execution is suspended until the graphics object is\n\
destroyed or the property named @var{prop} is set to @var{value}. The\n\
function @code{isequal} is used to compare property values. If the graphics\n\
handle is invalid, the property does not exist or the property is already\n\
set to @var{value}, the function returns immediately.\n\
\n\
An optional timeout can be specified using the property @code{timeout}.\n\
This timeout value is the number of seconds to wait for the condition to be\n\
true. @var{timeout} must be at least 1. If a smaller value is specified, a\n\
warning is issued and a value of 1 is used instead. If the timeout value is\n\
not an integer, it is truncated towards 0.\n\
\n\
To define a condition on a property named @code{timeout}, use the string\n\
@code{\\timeout} instead.\n\
\n\
In all cases, typing CTRL-C stops program execution immediately.\n\
@seealso{waitforbuttonpress, isequal}\n\
@end deftypefn")
{
if (args.length () > 0)
{
double h = args(0).double_value ();
if (! error_state)
{
caseless_str pname;
unwind_protect frame;
static uint32_t id_counter = 0;
uint32_t id = 0;
int max_arg_index = 0;
int timeout_index = -1;
int timeout = 0;
if (args.length () > 1)
{
pname = args(1).string_value ();
if (! error_state
&& ! pname.empty ()
&& ! pname.compare ("timeout"))
{
if (pname.compare ("\\timeout"))
pname = "timeout";
static octave_value wf_listener;
if (! wf_listener.is_defined ())
wf_listener =
octave_value (new octave_builtin (waitfor_listener,
"waitfor_listener"));
max_arg_index++;
if (args.length () > 2)
{
if (args(2).is_string ())
{
caseless_str s = args(2).string_value ();
if (! error_state)
{
if (s.compare ("timeout"))
timeout_index = 2;
else
max_arg_index++;
}
}
else
max_arg_index++;
}
Cell listener (1, max_arg_index >= 2 ? 5 : 4);
id = id_counter++;
frame.add_fcn (cleanup_waitfor_id, id);
waitfor_results[id] = false;
listener(0) = wf_listener;
listener(1) = octave_uint32 (id);
listener(2) = h;
listener(3) = pname;
if (max_arg_index >= 2)
listener(4) = args(2);
octave_value ov_listener (listener);
gh_manager::auto_lock guard;
graphics_handle handle = gh_manager::lookup (h);
if (handle.ok ())
{
graphics_object go = gh_manager::get_object (handle);
if (max_arg_index >= 2
&& compare_property_values (go.get (pname),
args(2)))
waitfor_results[id] = true;
else
{
frame.add_fcn (cleanup_waitfor_postset_listener,
ov_listener);
go.add_property_listener (pname, ov_listener,
POSTSET);
go.add_property_listener (pname, ov_listener,
PERSISTENT);
if (go.get_properties ()
.has_dynamic_property (pname))
{
static octave_value wf_del_listener;
if (! wf_del_listener.is_defined ())
wf_del_listener =
octave_value (new octave_builtin
(waitfor_del_listener,
"waitfor_del_listener"));
Cell del_listener (1, 4);
del_listener(0) = wf_del_listener;
del_listener(1) = octave_uint32 (id);
del_listener(2) = h;
del_listener(3) = pname;
octave_value ov_del_listener (del_listener);
frame.add_fcn (cleanup_waitfor_predelete_listener,
ov_del_listener);
go.add_property_listener (pname, ov_del_listener,
PREDELETE);
}
}
}
}
else if (error_state || pname.empty ())
error ("waitfor: invalid property name, expected a non-empty string value");
}
if (! error_state
&& timeout_index < 0
&& args.length () > (max_arg_index + 1))
{
caseless_str s = args(max_arg_index + 1).string_value ();
if (! error_state)
{
if (s.compare ("timeout"))
timeout_index = max_arg_index + 1;
else
error ("waitfor: invalid parameter '%s'", s.c_str ());
}
else
error ("waitfor: invalid parameter, expected 'timeout'");
}
if (! error_state && timeout_index >= 0)
{
if (args.length () > (timeout_index + 1))
{
timeout = static_cast<int>
(args(timeout_index + 1).scalar_value ());
if (! error_state)
{
if (timeout < 1)
{
warning ("waitfor: the timeout value must be >= 1, using 1 instead");
timeout = 1;
}
}
else
error ("waitfor: invalid timeout value, expected a value >= 1");
}
else
error ("waitfor: missing timeout value");
}
// FIXME: There is still a "hole" in the following loop. The code
// assumes that an object handle is unique, which is a fair
// assumption, except for figures. If a figure is destroyed
// then recreated with the same figure ID, within the same
// run of event hooks, then the figure destruction won't be
// caught and the loop will not stop. This is an unlikely
// possibility in practice, though.
//
// Using deletefcn callback is also unreliable as it could be
// modified during a callback execution and the waitfor loop
// would not stop.
//
// The only "good" implementation would require object
// listeners, similar to property listeners.
time_t start = 0;
if (timeout > 0)
start = time (0);
while (! error_state)
{
if (true)
{
gh_manager::auto_lock guard;
graphics_handle handle = gh_manager::lookup (h);
if (handle.ok ())
{
if (! pname.empty () && waitfor_results[id])
break;
}
else
break;
}
octave_usleep (100000);
OCTAVE_QUIT;
command_editor::run_event_hooks ();
if (timeout > 0)
{
if (start + timeout < time (0))
break;
}
}
}
else
error ("waitfor: invalid handle value.");
}
else
print_usage ();
return octave_value ();
}
| gpl-3.0 |
leftstick/BaiduMapForAngularJS | demo/js/features/apidoc/main.js | 1533 | import routes from './routes'
import apidoc from './components/apidoc'
import apiSidebar from './components/subs/apiSidebar'
import apiContent from './components/subs/apiContent'
import docBaiduMap from './components/subs/apiContent/subs/docBaiduMap'
import docMapOptions from './components/subs/apiContent/subs/docMapOptions'
import docCenterAndZoom from './components/subs/apiContent/subs/docCenterAndZoom'
import docMarker from './components/subs/apiContent/subs/docMarker'
import docPolyline from './components/subs/apiContent/subs/docPolyline'
import docCircle from './components/subs/apiContent/subs/docCircle'
import docPolygon from './components/subs/apiContent/subs/docPolygon'
import docHeatmap from './components/subs/apiContent/subs/docHeatmap'
import docPoint from './components/subs/apiContent/subs/docPoint'
import docMarkerOptions from './components/subs/apiContent/subs/docMarkerOptions'
import docSize from './components/subs/apiContent/subs/docSize'
import docIcon from './components/subs/apiContent/subs/docIcon'
import docControl from './components/subs/apiContent/subs/docControl'
import docOverlay from './components/subs/apiContent/subs/docOverlay'
export default {
type: 'feature',
name: 'apidoc',
routes,
component: {
apidoc,
apiSidebar,
apiContent,
docBaiduMap,
docMapOptions,
docCenterAndZoom,
docMarker,
docPolyline,
docCircle,
docPolygon,
docHeatmap,
docPoint,
docMarkerOptions,
docSize,
docIcon,
docControl,
docOverlay
}
}
| gpl-3.0 |
seadas/seadas | seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParamTextfield.java | 3973 | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/12/12
* Time: 4:20 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParamTextfield {
private ParamInfo paramInfo;
private L2genData l2genData;
private JLabel jLabel;
private JTextField jTextField;
private int fill;
public L2genParamTextfield(L2genData l2genData, ParamInfo paramInfo) {
this.l2genData = l2genData;
this.paramInfo = paramInfo;
final String PROTOTYPE_70 = buildStringPrototype(70);
final String PROTOTYPE_60 = buildStringPrototype(60);
final String PROTOTYPE_15 = buildStringPrototype(15);
String textfieldPrototype;
if (paramInfo.getType() == ParamInfo.Type.STRING) {
textfieldPrototype = PROTOTYPE_60;
fill = GridBagConstraints.NONE;
} else if (paramInfo.getType() == ParamInfo.Type.INT) {
textfieldPrototype = PROTOTYPE_15;
fill = GridBagConstraints.NONE;
} else if (paramInfo.getType() == ParamInfo.Type.FLOAT) {
textfieldPrototype = buildStringPrototype(60);
fill = GridBagConstraints.NONE;
} else if (paramInfo.getType() == ParamInfo.Type.IFILE) {
textfieldPrototype = PROTOTYPE_70;
fill = GridBagConstraints.HORIZONTAL;
} else if (paramInfo.getType() == ParamInfo.Type.OFILE) {
textfieldPrototype = PROTOTYPE_70;
fill = GridBagConstraints.HORIZONTAL;
} else {
textfieldPrototype = PROTOTYPE_70;
fill = GridBagConstraints.NONE;
}
jTextField = new JTextField(textfieldPrototype);
jTextField.setPreferredSize(jTextField.getPreferredSize());
jTextField.setMaximumSize(jTextField.getPreferredSize());
jTextField.setMinimumSize(jTextField.getPreferredSize());
jTextField.setText("");
jLabel = new JLabel(paramInfo.getName());
jLabel.setToolTipText(paramInfo.getDescription());
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jTextField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
l2genData.setParamValue(paramInfo.getName(), jTextField.getText().toString());
}
});
jTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
l2genData.setParamValue(paramInfo.getName(), jTextField.getText().toString());
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
jTextField.setText(l2genData.getParamValue(paramInfo.getName()));
}
});
}
private String buildStringPrototype(int size) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < size; i++) {
stringBuilder.append("p");
}
return stringBuilder.toString();
}
public JLabel getjLabel() {
return jLabel;
}
public JTextField getjTextField() {
return jTextField;
}
public int getFill() {
return fill;
}
}
| gpl-3.0 |
cunvoas/springsecurity_iam | iam-webapp/src/main/java/com/github/iam/web/front/util/Constants.java | 2296 | package com.github.cunvoas.iam.web.front.util;
/**
* MVC Constants
* @author CUNVOAS
*/
public interface Constants {
int FALSE_ID = -10000;
String FORM_ERRORS = "errors";
String REDIRECT_PREFIX = "redirect:";
String SESSION_APP_VERSION="SESSION_APP_VERSION";
String SESSION_LOCALES="SESSION_LOCALES";
String SESSION_LOCALE="SESSION_LOCALE";
String SESSION_WORK_APPLICATION="SESSION_APPLICATION";
String UC_ACTIVE="UC_ACTIVE";
// error page
String VIEW_ERROR="error";
String VIEW_BLANK="blank";
// home page
String VIEW_HOME="home";
// application creation
String VIEW_APPLICATION_LIST="applicationList";
String VIEW_APPLICATION_ADD="applicationAdd";
String VIEW_APPLICATION_EDIT="applicationEdit";
String VIEW_APPLICATION_UPLOAD="applicationUpload";
String VIEW_APPLICATION_DWD_XLS="exportIamExcelView";
String FORM_APPLICATION="applicationForm";
String FORM_APPLICATION_UPLOAD="applicationFormUpload";
String VIEW_RESOURCE_TREE="resourceTree";
String VIEW_RESOURCE_VALUE="resourceValue";
String FORM_RESOURCE_VALUE_SEARCH="SearchResValForm";
String APP_ID = "appId";
String ROLE_ID = "roleId";
String MODEL_DASHBOARD = "dashboard";
String MODEL_DASHBOARD_CHART = "dashboardChart";
String MODEL_APP = "application";
String MODEL_APPS = "applications";
String MODEL_RESS = "resource";
String MODEL_RES_VAL_REF = "resValRef";
String MODEL_RESS_JSTREE = "resourceTree";
// role creation
String MODEL_ROLE = "role";
String MODEL_ROLES = "roles";
String FORM_ROLE="roleForm";
String VIEW_ROLE_ADD="roleAdd";
String VIEW_ROLE_EDIT="roleEdit";
String VIEW_ROLE_LIST = "roleList";
// DELEGATION
String MODEL_DELEGATION = "delegation";
String MODEL_DELEGATION_STATE = "delegationState";
String MODEL_DELEGATIONS = "delegations";
String MODEL_DELEGATIONS_AFFECTED = "delegationsAffected";
String FORM_DELEGATION="delegationForm";
String VIEW_DELEGATION_ADD="delegationAdd";
String VIEW_DELEGATION_EDIT="delegationEdit";
String VIEW_DELEGATION_LIST = "delegationList";
String VIEW_DELEGATION_WKF = "delegationWkf";
}
| gpl-3.0 |
pwnall/battlecode-server | src/main/battlecode/world/BuffRemovalPolicy.java | 422 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package battlecode.world;
/**
*
* @author Sasa
*/
public abstract class BuffRemovalPolicy {
private final InternalBuff buff;
public BuffRemovalPolicy(InternalBuff buff) {
this.buff = buff;
}
public InternalBuff getBuff() {
return buff;
}
public abstract boolean remove();
}
| gpl-3.0 |
GWASpi/GWASpi | src/main/java/org/gwaspi/operations/qasamples/QASamplesOperation.java | 4951 | /*
* Copyright (C) 2013 Universitat Pompeu Fabra
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gwaspi.operations.qasamples;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.gwaspi.constants.NetCDFConstants.Defaults.AlleleByte;
import org.gwaspi.model.DataSetSource;
import org.gwaspi.model.GenotypesList;
import org.gwaspi.model.MarkerMetadata;
import org.gwaspi.model.MarkersMetadataSource;
import org.gwaspi.model.OperationKey;
import org.gwaspi.model.SampleKey;
import org.gwaspi.model.SamplesGenotypesSource;
import org.gwaspi.operations.AbstractOperationCreatingOperation;
import org.gwaspi.operations.OperationManager;
import org.gwaspi.operations.OperationTypeInfo;
import org.gwaspi.progress.DefaultProcessInfo;
import org.gwaspi.progress.ProcessInfo;
import org.gwaspi.progress.ProcessStatus;
import org.gwaspi.progress.ProgressHandler;
public class QASamplesOperation extends AbstractOperationCreatingOperation<QASamplesOperationDataSet, QASamplesOperationParams> {
private static final ProcessInfo PROCESS_INFO = new DefaultProcessInfo(
"Samples Quality Assurance",
""); // TODO
public static void register() {
// NOTE When converting to OSGi, this would be done in bundle init,
// or by annotations.
OperationManager.registerOperationFactory(new QASamplesOperationFactory());
}
public QASamplesOperation(QASamplesOperationParams params) {
super(params);
}
@Override
public OperationTypeInfo getTypeInfo() {
return QASamplesOperationFactory.OPERATION_TYPE_INFO;
}
@Override
public ProcessInfo getProcessInfo() {
return PROCESS_INFO;
}
@Override
public boolean isValid() {
return true;
}
@Override
public String getProblemDescription() {
return null;
}
@Override
public OperationKey call() throws IOException {
OperationKey resultOpKey;
final ProgressHandler progressHandler = getProgressHandler();
progressHandler.setNewStatus(ProcessStatus.INITIALIZING);
org.gwaspi.global.Utils.sysoutStart("Sample QA");
DataSetSource dataSetSource = getParentDataSetSource();
QASamplesOperationDataSet dataSet = generateFreshOperationDataSet();
dataSet.setNumMarkers(dataSetSource.getNumMarkers());
dataSet.setNumChromosomes(dataSetSource.getNumChromosomes());
dataSet.setNumSamples(dataSetSource.getNumSamples());
SamplesGenotypesSource samplesGenotypes = dataSetSource.getSamplesGenotypesSource();
MarkersMetadataSource markersInfSrc = dataSetSource.getMarkersMetadatasSource();
// Iterate through samples
Iterator<GenotypesList> samplesGenotypesIt = samplesGenotypes.iterator();
progressHandler.setNewStatus(ProcessStatus.RUNNING);
int localSampleIndex = 0;
for (Map.Entry<Integer, SampleKey> sampleKeyEntry
: dataSetSource.getSamplesKeysSource().getIndicesMap().entrySet())
{
final int sampleOrigIndex = sampleKeyEntry.getKey();
final SampleKey sampleKey = sampleKeyEntry.getValue();
int missingCount = 0;
int heterozygCount = 0;
// Iterate through markerset
GenotypesList sampleGenotypes = samplesGenotypesIt.next();
Iterator<MarkerMetadata> markersInfSrcIt = markersInfSrc.iterator();
for (byte[] tempGT : sampleGenotypes) {
if ((tempGT[0] == AlleleByte._0_VALUE) && (tempGT[1] == AlleleByte._0_VALUE)) {
missingCount++;
}
// WE DON'T WANT NON AUTOSOMAL CHR FOR HETZY
String currentChr = markersInfSrcIt.next().getChr();
if (!currentChr.equals("X")
&& !currentChr.equals("Y")
&& !currentChr.equals("XY")
&& !currentChr.equals("MT")
&& (tempGT[0] != tempGT[1]))
{
heterozygCount++;
}
}
final double missingRatio = (double) missingCount
/ dataSetSource.getNumMarkers();
final double heterozygRatio = (double) heterozygCount
/ (dataSetSource.getNumMarkers() - missingCount);
dataSet.addEntry(new DefaultQASamplesOperationEntry(
sampleKey,
sampleOrigIndex,
missingRatio,
missingCount,
heterozygRatio
));
progressHandler.setProgress(localSampleIndex);
localSampleIndex++;
}
progressHandler.setNewStatus(ProcessStatus.FINALIZING);
dataSet.finnishWriting();
resultOpKey = dataSet.getOperationKey();
org.gwaspi.global.Utils.sysoutCompleted("Sample QA");
progressHandler.setNewStatus(ProcessStatus.COMPLEETED);
return resultOpKey;
}
}
| gpl-3.0 |
milot-mirdita/PocketGnuBoy | wce/dialog.cpp | 11779 | #include "PocketGnuboy.h"
#include "Dialog.h"
#include "wce.h"
#define REG_KEY_GNUBOYROM _T("GnuboyROM")
#define REG_KEY_GB _T(".gb")
#define REG_KEY_GBC _T(".gbc")
#define IsDlgButtonChecked(hwnd, id) SendMessage(GetDlgItem(hwnd, id), BM_GETCHECK, 0, 0)
#define CheckDlgButton(hwnd, id, check) SendMessage(GetDlgItem(hwnd, id), BM_SETCHECK, check, 0)
void AssociateGBExtension()
{
TCHAR sz[MAX_PATH];
TCHAR szModule[MAX_PATH];
TCHAR szType[MAX_LOADSTRING];
int nIconID = IDI_MAIN;
GetModuleFileName(NULL, szModule, MAX_PATH);
LoadString(g_hInst, IDS_ROM_TYPENAME, szType, MAX_LOADSTRING);
HKEY hKey, hKeySub;
DWORD dwDisposition;
if (RegCreateKeyEx(HKEY_CLASSES_ROOT, REG_KEY_GNUBOYROM, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisposition) == ERROR_SUCCESS) {
// type
RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)szType, sizeof(TCHAR) * (_tcslen(szType) + 1));
// DefaultIcon
if (RegCreateKeyEx(hKey, _T("DefaultIcon"), 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKeySub, &dwDisposition) == ERROR_SUCCESS) {
wsprintf(sz, _T("%s,-%d"), szModule, nIconID);
RegSetValueEx(hKeySub, NULL, 0, REG_SZ, (LPBYTE)sz, sizeof(TCHAR) * (_tcslen(sz) + 1));
RegCloseKey(hKeySub);
}
// Shell-Open-Command
if (RegCreateKeyEx(hKey, _T("Shell\\Open\\Command"), 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKeySub, &dwDisposition) == ERROR_SUCCESS) {
wsprintf(sz, _T("\"%s\" \"%%1\""), szModule);
RegSetValueEx(hKeySub, NULL, 0, REG_SZ, (LPBYTE)sz, sizeof(TCHAR) * (_tcslen(sz) + 1));
RegCloseKey(hKeySub);
}
RegCloseKey(hKey);
_tcscpy(sz, REG_KEY_GNUBOYROM);
// .gb
if (RegCreateKeyEx(HKEY_CLASSES_ROOT, REG_KEY_GB, 0, 0,
REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &hKey, &dwDisposition) == ERROR_SUCCESS) {
RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)sz, sizeof(TCHAR) * (_tcslen(sz) + 1));
RegCloseKey(hKey);
}
// .gbc
if (RegCreateKeyEx(HKEY_CLASSES_ROOT, REG_KEY_GBC, 0, 0,
REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &hKey, &dwDisposition) == ERROR_SUCCESS) {
RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)sz, sizeof(TCHAR) * (_tcslen(sz) + 1));
RegCloseKey(hKey);
}
}
}
void UndoAssociateGBExtension()
{
RegDeleteKey(HKEY_CLASSES_ROOT, REG_KEY_GB);
RegDeleteKey(HKEY_CLASSES_ROOT, REG_KEY_GBC);
RegDeleteKey(HKEY_CLASSES_ROOT, REG_KEY_GNUBOYROM);
}
int press_key;
BOOL CALLBACK CTR_KeyPressDlg(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
case WM_INITDIALOG:
press_key = 0;
return TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDCANCEL) {
press_key = 0;
EndDialog(hwndDlg, IDCANCEL);
}
return TRUE;
case WM_KEYDOWN:
/*{
if (wParam == 0x5B) {
for (int i = 0xC1; i < 0xC6; i++) {
if (GetAsyncKeyState(i)) {
press_key = i;
EndDialog(hwndDlg, IDOK);
return TRUE;
}
}
}
// for jornada 56x
if (wParam == 0x84) {
for (int i = 0x25; i < 0x29; i++) {
if (GetAsyncKeyState(i)) {
press_key = i;
EndDialog(hwndDlg, IDOK);
return TRUE;
}
}
}
return FALSE;
}
case WM_KEYUP:*/
press_key = wParam;
EndDialog(hwndDlg, IDOK);
return TRUE;
default: return FALSE;
}
}
int CTR_StartKeyDialog(HWND hwndParent)
{
AllKeys(true);
DialogBox(g_hInst, (LPCTSTR)IDD_KEYPRESS, hwndParent, CTR_KeyPressDlg);
AllKeys(false);
return press_key;
}
void CTR_InitDialog(HWND hwndDlg, int keys[])
{
TCHAR sz[32];
SHINITDLGINFO shidi;
shidi.dwMask = SHIDIM_FLAGS;
shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN;
shidi.hDlg = hwndDlg;
SHInitDialog(&shidi);
for (int i = 0; i < JOY_MAX; i++) {
keys[i] = joy_get_key(i);
wsprintf(sz, _T("0x%X"), keys[i]);
SetWindowText(GetDlgItem(hwndDlg, IDC_STATIC_KEY_A + i), sz);
}
}
void CTR_OnOK(HWND hwndDlg, int keys[])
{
for (int i = 0; i < JOY_MAX; i++)
joy_set_key(i, keys[i]);
EndDialog(hwndDlg, IDOK);
}
BOOL CALLBACK ControllersDlgProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
static int keys[JOY_MAX];
switch (message) {
case WM_INITDIALOG:
{
CTR_InitDialog(hwndDlg, keys);
break;
}
case WM_COMMAND:
{
WORD wID = LOWORD(wParam);
if (wID == IDOK) {
CTR_OnOK(hwndDlg, keys);
return TRUE;
}
else if (wID == IDCANCEL) {
EndDialog(hwndDlg, LOWORD(wParam));
return TRUE;
}
else if (wID >= IDC_A && wID <= IDC_ESCAPE) {
int n = CTR_StartKeyDialog(hwndDlg);
if (n) {
TCHAR sz[32];
int nIndex = wID - IDC_A;
wsprintf(sz, _T("0x%X"), n);
SetWindowText(GetDlgItem(hwndDlg, IDC_STATIC_KEY_A + nIndex), sz);
keys[nIndex] = n;
}
return TRUE;
}
else if (wID >= IDC_DEL_A && wID <= IDC_DEL_ESCAPE) {
TCHAR sz[32];
int nIndex = wID - IDC_DEL_A;
wsprintf(sz, _T("0x%X"), 0);
SetWindowText(GetDlgItem(hwndDlg, IDC_STATIC_KEY_A + nIndex), sz);
keys[nIndex] = 0;
return TRUE;
}
break;
}
}
return FALSE;
}
void ShowControllersDlg(HWND hwnd)
{
DialogBox(g_hInst, MAKEINTRESOURCE(IDD_CONTROLLERS), hwnd, ControllersDlgProc);
}
///////////////////////////////////////////////////////
void PRF_InitDialog(HWND hwndDlg)
{
char dir[MAX_PATH];
TCHAR sz[MAX_PATH];
SHINITDLGINFO shidi;
shidi.dwMask = SHIDIM_FLAGS;
shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN;
shidi.hDlg = hwndDlg;
SHInitDialog(&shidi);
get_savedir(dir);
MultiByteToWideChar(CP_ACP, 0, dir, -1, sz, MAX_PATH);
if (!_tcslen(sz))
CheckRadioButton(hwndDlg, IDC_RADIO_SRAM_ROMDIRECTORY,
IDC_RADIO_SRAM_DIRECTORY, IDC_RADIO_SRAM_ROMDIRECTORY);
else {
CheckRadioButton(hwndDlg, IDC_RADIO_SRAM_ROMDIRECTORY,
IDC_RADIO_SRAM_DIRECTORY, IDC_RADIO_SRAM_DIRECTORY);
SetWindowText(GetDlgItem(hwndDlg, IDC_EDIT_SRAM), sz);
}
if (g_fThrottling)
CheckDlgButton(hwndDlg, IDC_CHECK_THROTTLING, BST_CHECKED);
if (lcd_get_contrast())
CheckDlgButton(hwndDlg, IDC_CHECK_CONTRAST, BST_CHECKED);
if (g_fShowFPS)
CheckDlgButton(hwndDlg, IDC_CHECK_SHOWFPS, BST_CHECKED);
if (g_fDrawScreen)
CheckDlgButton(hwndDlg, IDC_CHECK_DRAWSCREEN, BST_CHECKED);
if (vid_get_ddraw())
CheckDlgButton(hwndDlg, IDC_CHECK_DDRAW, BST_CHECKED);
if (g_fGSGetFile)
CheckDlgButton(hwndDlg, IDC_CHECK_GSGETFILE, BST_CHECKED);
}
void PRF_OnOK(HWND hwndDlg)
{
char dir[MAX_PATH];
TCHAR sz[MAX_PATH] = {0};
if (IsDlgButtonChecked(hwndDlg, IDC_RADIO_SRAM_DIRECTORY))
GetWindowText(GetDlgItem(hwndDlg, IDC_EDIT_SRAM), sz, MAX_PATH);
WideCharToMultiByte(CP_ACP, NULL, sz, -1, dir, MAX_PATH, NULL, NULL);
set_savedir(dir);
g_fThrottling = IsDlgButtonChecked(hwndDlg, IDC_CHECK_THROTTLING);
lcd_set_contrast(IsDlgButtonChecked(hwndDlg, IDC_CHECK_CONTRAST));
g_fShowFPS = IsDlgButtonChecked(hwndDlg, IDC_CHECK_SHOWFPS);
g_fDrawScreen = IsDlgButtonChecked(hwndDlg, IDC_CHECK_DRAWSCREEN);
vid_set_ddraw(IsDlgButtonChecked(hwndDlg, IDC_CHECK_DDRAW));
g_fGSGetFile = IsDlgButtonChecked(hwndDlg, IDC_CHECK_GSGETFILE);
EndDialog(hwndDlg, IDOK);
}
BOOL CALLBACK PreferencesDlgProc(HWND hwndDlg, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch (message){
case WM_INITDIALOG:
{
PRF_InitDialog(hwndDlg);
return TRUE;
}
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
PRF_OnOK(hwndDlg);
return TRUE;
case IDCANCEL:
EndDialog(hwndDlg, LOWORD(wParam));
return TRUE;
case IDC_ASSOCIATE:
AssociateGBExtension();
return TRUE;
case IDC_UNDO:
UndoAssociateGBExtension();
return TRUE;
}
return FALSE;
}
return FALSE;
}
void ShowPreferencesDlg(HWND hwnd)
{
DialogBox(g_hInst, MAKEINTRESOURCE(IDD_PREFERENCES), hwnd, PreferencesDlgProc);
}
| gpl-3.0 |
REDetector/RED | red/com/xl/display/dialog/gotodialog/GoToWindowDialog.java | 6204 | /*
* RED: RNA Editing Detector
* Copyright (C) <2014> <Xing Li>
*
* RED is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* RED is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.xl.display.dialog.gotodialog;
import com.xl.datatypes.genome.Chromosome;
import com.xl.main.RedApplication;
import com.xl.preferences.DisplayPreferences;
import com.xl.utils.NumberKeyListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* The Class GoToWindowDialog provides a quick way to jump to a known position in the genome.
*/
public class GoToWindowDialog extends JDialog implements ActionListener, KeyListener {
/**
* The chromosome.
*/
private JComboBox chromosome;
/**
* The centre position.
*/
private JTextField centre;
/**
* The window size.
*/
private JTextField window;
/**
* The ok button.
*/
private JButton okButton;
/**
* Instantiates a new goto window dialog.
*
* @param application the application
*/
public GoToWindowDialog(RedApplication application) {
super(application, "Jump to window...");
setSize(300, 200);
setLocationRelativeTo(application);
setModal(true);
getContentPane().setLayout(new BorderLayout());
JPanel choicePanel = new JPanel();
choicePanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.2;
gbc.weighty = 0.5;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
choicePanel.add(new JLabel("Chromosome", JLabel.RIGHT), gbc);
gbc.gridx++;
gbc.weightx = 0.6;
Chromosome[] chrNames = application.dataCollection().genome().getAllChromosomes();
chromosome = new JComboBox(chrNames);
choicePanel.add(chromosome, gbc);
Chromosome currentChromosome = DisplayPreferences.getInstance().getCurrentChromosome();
chromosome.setSelectedItem(currentChromosome);
gbc.gridx = 0;
gbc.gridy++;
gbc.weightx = 0.2;
choicePanel.add(new JLabel("Centre ", JLabel.RIGHT), gbc);
gbc.gridx++;
gbc.weightx = 0.6;
centre = new JTextField("" + DisplayPreferences.getInstance().getCurrentMidPoint(), 5);
centre.addKeyListener(new NumberKeyListener(false, false));
centre.addKeyListener(this);
choicePanel.add(centre, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.weightx = 0.2;
choicePanel.add(new JLabel("Window ", JLabel.RIGHT), gbc);
gbc.gridx++;
gbc.weightx = 0.6;
window = new JTextField("" + DisplayPreferences.getInstance().getCurrentLength(), 5);
window.addKeyListener(new NumberKeyListener(false, false));
window.addKeyListener(this);
choicePanel.add(window, gbc);
getContentPane().add(choicePanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("cancel");
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
okButton = new JButton("OK");
okButton.setActionCommand("ok");
okButton.addActionListener(this);
okButton.setEnabled(true);
getRootPane().setDefaultButton(okButton);
buttonPanel.add(okButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
/**
* Do goto.
*/
private void doGoTo() {
Chromosome chr = (Chromosome) chromosome.getSelectedItem();
int centreValue = chr.getLength() / 2;
int windowValue = 1000;
int startValue;
int endValue;
// Work out the window positions we want
if (centre.getText().length() > 0) {
centreValue = Integer.parseInt(centre.getText());
}
if (window.getText().length() > 0) {
windowValue = Integer.parseInt(window.getText());
}
if (windowValue < 1)
windowValue = 1;
startValue = centreValue - (windowValue / 2);
endValue = startValue + (windowValue - 1);
DisplayPreferences.getInstance().setLocation(chr, startValue, endValue);
setVisible(false);
dispose();
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("cancel")) {
setVisible(false);
dispose();
} else if (ae.getActionCommand().equals("ok")) {
doGoTo();
}
}
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
*/
public void keyTyped(KeyEvent arg0) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
*/
public void keyPressed(KeyEvent ke) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
public void keyReleased(KeyEvent ke) {
if (centre.getText().length() == 0 || window.getText().length() == 0) {
okButton.setEnabled(false);
} else {
okButton.setEnabled(true);
}
}
}
| gpl-3.0 |
Embraser01/IUT-PTUT | api/models/Style.js | 1363 | /*
* Style.js :
* Copyright (C) 2016 Hugo ALLIAUME Benjamin CHAZELLE Marc-Antoine FERNANDES
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
module.exports = {
tableName: 'Style',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
//===== ATTRIBUTES =====//
style: {
type: 'string',
required: true,
size: 255
},
//===== FOREIGN KEYS =====//
node: {
model: 'node'
},
owner: {
model: 'user'
}
},
beforeValidate: function (values, cb) {
values.style = SerializeService.serialize(values.style);
if (!values.style) return cb(new Error("Malformed style"));
cb();
}
} | gpl-3.0 |
durandj/codeeval | javascript/18_multiples_of_a_number.js | 290 | var fs = require('fs');
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line == '') {
return;
}
var tokens = line.split(',');
var x = parseInt(tokens[0]);
var n = parseInt(tokens[1]);
var v = n;
for (; v < x; v += n);
console.log(v);
});
| gpl-3.0 |
geopaparazzi/geopaparazzi | geopaparazzi_map/src/main/java/eu/geopaparazzi/map/layers/interfaces/IEditableLayer.java | 1975 | package eu.geopaparazzi.map.layers.interfaces;
import org.hortonmachine.dbs.datatypes.EGeometryType;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import java.util.List;
import eu.geopaparazzi.map.features.Feature;
/**
*
*/
public interface IEditableLayer extends IGpLayer {
/**
* @return true if the layer allows for geometry editing.
*/
boolean isEditable();
/**
* @return true if the layer is activated for editing.
*/
boolean isInEditingMode();
/**
* Get the list of features, given a query.
*
* @param env optional envelope.
* @return the list of features
* @throws Exception
*/
List<Feature> getFeatures(Envelope env) throws Exception;
/**
* Delete a list of features in the given database.
* <p/>
* <b>The features need to be from the same table</b>
*
* @param features the features list to remove.
* @throws Exception if something goes wrong.
*/
void deleteFeatures(List<Feature> features) throws Exception;
/**
* Add a new feature that has only the geometry (all other fields are default value).
*
* @param geometry the geometry.
* @param srid the srid of the added geometry, in case reprojection is needed.
* @throws Exception
*/
void addNewFeatureByGeometry(Geometry geometry, int srid) throws Exception;
/**
* Updates the geometry of a feature in the given database.
*
* @param feature the feature to update.
* @param geometry the new geometry to set.
* @param geometrySrid the srid of the new geometry, in case reprojection is necessary.
* @throws Exception if something goes wrong.
*/
void updateFeatureGeometry(Feature feature, Geometry geometry, int geometrySrid) throws Exception;
/**
* @return the type of the geometry fo rthis layer.
*/
EGeometryType getGeometryType();
}
| gpl-3.0 |
lu1sd4/CityMate | cityMate/test/controllers/articulos_controller_test.rb | 1035 | require 'test_helper'
class ArticulosControllerTest < ActionController::TestCase
setup do
@articulo = articulos(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:articulos)
end
test "should get new" do
get :new
assert_response :success
end
test "should create articulo" do
assert_difference('Articulo.count') do
post :create, articulo: { }
end
assert_redirected_to articulo_path(assigns(:articulo))
end
test "should show articulo" do
get :show, id: @articulo
assert_response :success
end
test "should get edit" do
get :edit, id: @articulo
assert_response :success
end
test "should update articulo" do
patch :update, id: @articulo, articulo: { }
assert_redirected_to articulo_path(assigns(:articulo))
end
test "should destroy articulo" do
assert_difference('Articulo.count', -1) do
delete :destroy, id: @articulo
end
assert_redirected_to articulos_path
end
end
| gpl-3.0 |
insomynwa/wp-content | plugins/woo-variations-table/woo-variations-table.php | 19149 | <?php
/*
Plugin Name: Woo Variations table
Plugin URI: https://lb.linkedin.com/in/alaa-rihan-6971b686
Description: Show WooCommerce variable products variations as table with filters and sorting instead of normal dropdowns.
Author: Alaa Rihan
Author URI: https://lb.linkedin.com/in/alaa-rihan-6971b686
Text Domain: woo-variations-table
Domain Path: /languages/
Version: 1.3.5
*/
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
define("WOO_VARIATIONS_TABLE_VERSION", '1.3.5');
// Check if WooCommerce is enabled
add_action('plugins_loaded', 'check_woocommerce_enabled', 1);
function check_woocommerce_enabled(){
if (!class_exists('WooCommerce')) {
add_action('admin_notices','woocommerce_disabled_notice');
return;
}
}
// Display WC disabled notice
function woocommerce_disabled_notice(){
echo '<div class="error"><p><strong>' .__('Woo Variations Table', 'woo-variations-table') .'</strong> ' .sprintf( __( 'requires %sWooCommerce%s to be installed & activated!' , 'woo-variations-table' ), '<a href="http://wordpress.org/extend/plugins/woocommerce/">', '</a>' ) .'</p></div>';
}
// Settings menu item
add_action('admin_menu', 'woo_variations_table_settings',99);
function woo_variations_table_settings() {
add_submenu_page( 'woocommerce', __('Woo Variations Table', 'woo-variations-table'), __('Woo Variations Table', 'woo-variations-table'), 'manage_options', 'woo_variations_table', 'woo_variations_table_settings_page_callback' );
//call register settings function
add_action( 'admin_init', 'woo_variations_table_register_settings' );
}
// Register our settings
function woo_variations_table_register_settings() {
register_setting( 'woo_variations_table_columns', 'woo_variations_table_columns' );
register_setting( 'woo_variations_table_columns', 'woo_variations_table_show_attributes' );
}
// Settings page callback function
function woo_variations_table_settings_page_callback() {
$default_columns = array(
'image_link' => 1,
'sku' => 1,
'variation_description' => 1,
'dimensions' => 0,
'weight_html' => 0,
'stock' => 1,
'price_html' => 1,
);
$columns_labels = array(
'image_link' => __('Thumbnail', 'woo-variations-table'),
'sku' => __('SKU', 'woo-variations-table'),
'variation_description' => __('Description', 'woo-variations-table'),
'dimensions' => __('Dimensions', 'woo-variations-table'),
'weight_html' => __('Weight', 'woo-variations-table'),
'stock' => __('Stock', 'woo-variations-table'),
'price_html' => __('Price', 'woo-variations-table'),
);
$columns = get_option('woo_variations_table_columns', $default_columns);
$showAttributes = get_option('woo_variations_table_show_attributes', '');
?>
<div class="wrap">
<h1><?php echo __('Woo Variations Table Settings', 'woo-variations-table'); ?></h1>
<form method="post" action="options.php">
<?php settings_fields( 'woo_variations_table_columns' ); ?>
<?php do_settings_sections( 'woo_variations_table_columns' ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row"><?php echo __('Columns to show', 'woo-variations-table'); ?></th>
<td><?php woo_variations_table_create_multi_select_options('woo-variations-table-columns', $default_columns, $columns, $columns_labels); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php echo __('Show Attributes', 'woo-variations-table'); ?></th>
<td><ul style="margin-top: 5px;" class='mnt-checklist' id='woo-variations-table-attributes'><li>
<input type='checkbox' name='woo_variations_table_show_attributes' <?php echo $showAttributes ? "checked='checked'" : ''; ?> /> Show Attributes
</li></ul></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
function woo_variations_table_create_multi_select_options($id, $columns, $values, $labels) {
echo "<ul style='margin-top: 5px;' class='mnt-checklist' id='$id' >"."\n";
foreach ($columns as $key => $value) {
$checked = " ";
if (isset($values[$key])) {
$checked = " checked='checked' ";
}
echo "<li>\n";
echo "<input type='checkbox' name='woo_variations_table_columns[$key]' $checked />".$labels[$key]."\n";
echo "</li>\n";
}
echo "</ul>\n";
}
// Remove default variable product add to cart
add_action( 'plugins_loaded', 'remove_variable_product_add_to_cart' );
function remove_variable_product_add_to_cart() {
remove_action( 'woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30 );
}
add_action( 'woocommerce_single_product_summary', 'woo_variations_table_available_options_btn', 11 );
function woo_variations_table_available_options_btn(){
global $product;
if(!$product->is_type('variable'))
return;
?>
<div class="available-options-btn">
<button scrollto="#variations-table" type="button" class="single_add_to_cart_button button alt"><?php echo apply_filters( 'woo_variations_table_available_options_btn_text', __('Available options', 'woo-variations-table') ); ?></button>
</div>
<?php
}
// Enqueue scripts and styles
add_action( 'wp_enqueue_scripts', 'variations_table_scripts' );
function variations_table_scripts() {
if(is_product()){
wp_enqueue_script( 'vuejs', '//unpkg.com/vue@2.3.2/dist/vue.min.js', array(), '2.3.2', false );
wp_enqueue_script( 'woo-variations-table', plugins_url( 'js/woo-variations-table.js', __FILE__), 'vuejs', WOO_VARIATIONS_TABLE_VERSION, false );
wp_enqueue_script( 'woo-variations-table-scripts', plugins_url( 'js/woo-variations-table-scripts.js', __FILE__), array( 'jquery' ), WOO_VARIATIONS_TABLE_VERSION , true);
wp_localize_script( 'woo-variations-table', 'localData', array(
'ajaxURL' => admin_url( 'admin-ajax.php?add_variation_to_cart=1' ),
) );
wp_enqueue_style( 'woo-variations-table-style', plugins_url( 'css/woo-variations-table.css', __FILE__ ), array(), WOO_VARIATIONS_TABLE_VERSION);
}
}
// Add ajax callback to add variation to cart
add_action( 'wp_ajax_variation_add_to_cart', 'variations_table_ajax_variation_add_to_cart' );
add_action( 'wp_ajax_nopriv_variation_add_to_cart', 'variations_table_ajax_variation_add_to_cart' );
function variations_table_ajax_variation_add_to_cart() {
ob_start();
$product_id = apply_filters( 'vartable_add_to_cart_product_id', absint( $_POST['product_id'] ) );
$quantity = empty( $_POST['quantity'] ) ? 1 : wc_stock_amount( $_POST['quantity'] );
$variation_id = isset( $_POST['variation_id'] ) ? absint( $_POST['variation_id'] ) : '';
$variations = variations_table_get_variation_data_from_variation_id($variation_id);
$passed_validation = apply_filters( 'vartable_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations);
if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) ) {
do_action( 'vartable_ajax_added_to_cart', $product_id );
if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) {
wc_add_to_cart_message( $product_id );
}
// Return fragments
WC_AJAX::get_refreshed_fragments();
} else {
// If there was an error adding to the cart, redirect to the product page to show any errors
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id )
);
wp_send_json( $data );
}
die();
}
function variations_table_get_variation_data_from_variation_id( $variation_id ) {
$_product = new WC_Product_Variation( $variation_id );
$variation_data = $_product->get_variation_attributes();
return $variation_data; // $variation_data will return only the data which can be used to store variation data
}
// Update database
add_action('admin_init', 'variations_table_database_update');
function variations_table_database_update(){
$plugin_db_version = get_option('woo_variations_table_db_version', '1.1');
if (in_array($plugin_db_version, array('1.1', '1.0', '0.9.0', '0.8.1'))){
$activeColumns = get_option('woo_variations_table_columns');
if(isset($activeColumns['weight'])){
$activeColumns['weight_html'] = $activeColumns['weight'];
unset($activeColumns['weight']);
update_option('woo_variations_table_columns', $activeColumns);
}
update_option('woo_variations_table_show_attributes', '');
}
if($plugin_db_version != WOO_VARIATIONS_TABLE_VERSION){
update_option('woo_variations_table_db_version', WOO_VARIATIONS_TABLE_VERSION);
}
}
// Print variations table after product summary
add_filter('woocommerce_after_single_product_summary','variations_table_print_table',9);
function variations_table_print_table(){
global $product;
if( $product->is_type( 'variable' ) ){
$productImageURL = wp_get_attachment_image_src(get_post_thumbnail_id( $product->get_id() ), 'shop_single')[0];
$variations = $product->get_available_variations();
// Image link is no longer exist in WooCommerce 3.x so do this work around
foreach ( $variations as $key => $variation ) {
if(!isset($variation['image_link']) && isset($variation['image'])){
$variations[$key]['image_link'] = $variation['image']['src'];
}
// price_html is empty if all variations have the same price in WooCommerce 3.x so do this work around
if(empty($variation['price_html'])){
$variations[$key]['price_html'] = $product->get_price_html();
}
}
$variations = json_encode($variations);
$product_attributes = $product->get_attributes();
$variation_attributes = $product->get_variation_attributes();
$attrs = array();
foreach ( $variation_attributes as $key => $name ) {
$correctkey = wc_sanitize_taxonomy_name( stripslashes( $key ) );
$attrs[$correctkey]['name']= wc_attribute_label($key);
$attrs[$correctkey]['visible'] = $product_attributes[$correctkey]->get_visible();
for($i=0; count($name) > $i; $i++){
$term = get_term_by('slug', array_values($name)[$i], $key);
if($term){
$attrs[$key]['options'][]=array('name'=>$term->name, 'slug'=>array_values($name)[$i]);
}else{
$attrs[$correctkey]['options'][]= array('name'=>array_values($name)[$i], 'slug'=>array_values($name)[$i]);
}
}
}
$attributes = json_encode($attrs);
$default_columns = array(
'image_link' => 'on',
'sku' => 'on',
'variation_description' => 'on',
'dimensions' => 0,
'weight_html' => 0,
'stock' => 0,
'price_html' => 'on',
);
$activeColumns = json_encode(get_option('woo_variations_table_columns', $default_columns));
$showAttributes = json_encode(get_option('woo_variations_table_show_attributes', ''));
?>
<div id='variations-table' class="variations-table">
<h3 class="available-title"><?php echo esc_html_e( 'Available Options', 'woo-variations-table' );?>:</h3>
<!-- grid component template -->
<script type="text/x-template" id="grid-template">
<table class="variations">
<thead>
<tr>
<th v-for="column in columns" v-if="activeColumns[column.key] == 'on'"
@click="sortBy(column.key)"
:class="[{ active: sortKey == column.key }, column.key]">
{{ column.title }}
<span class="arrow" :class="sortOrders[column.key] > 0 ? 'asc' : 'dsc'">
</span>
</th>
<template v-if="showAttributes" v-for="attr in attributes">
<th v-if="attr.visible"> {{ attr.name }} </th>
</template>
<th class="stock" v-if="activeColumns['stock'] == 'on'"
@click="sortBy('stock')"
:class="[{ active: sortKey == 'stock' }, 'stock']">
<?php echo __("Stock", 'woo-variations-table'); ?>
<span class="arrow" :class="sortOrders['stock'] > 0 ? 'asc' : 'dsc'">
</span>
</th>
<th class="quantity"><?php echo __("Quantity", 'woo-variations-table'); ?></th>
<th class="add-to-cart"></th>
</tr>
</thead>
<tbody>
<tr v-for="(entry, index) in filteredData" :class="'variation-'+entry.variation_id+ ' image-'+ imageClass(entry['image_link'])">
<td v-for="column in columns" :class="column.key" v-if="activeColumns[column.key] == 'on'" :data-title="column.title">
<span class="item" v-if="column.type == 'image'"><img v-if="imageURL(entry[column.key]) != ''" :src="imageURL(entry[column.key])"></span>
<span class="item" v-if="column.type == 'text' ">{{entry[column.key]}}</span>
<span class="item" v-if="column.type == 'html'" v-html="entry[column.key]"></span>
</td>
<template v-if="showAttributes" v-for="(attr, key, index) in entry.attributes">
<td v-if="attributes[key.substr(10)].visible" :data-title="attributes[key.substr(10)].name">{{ showAttributeNameFromSlug(attr, attributes[key.substr(10)].options) }}</td>
</template>
<td class="stock" v-if="activeColumns['stock'] == 'on'" data-title="Stock">
<span class="item">
<template v-if="entry['is_in_stock']">
<span class='in-stock' v-if="entry['availability_html']" v-html="entry['availability_html']"></span>
<?php do_action('woo_variations_table_after_stock', $product->get_id()); ?>
</template>
<span v-else class="out-of-stock"><?php echo __("Out of Stock", 'woo-variations-table'); ?></span>
</span>
</td>
<td class="quantity"><input :ref="'quantity-'+entry.variation_id" value="1" type="number" step="1" min="1" name="quantity" data-title="Qty" title="Qty" class="input-text qty text" size="4" pattern="[0-9]*" inputmode="numeric"></td>
<td class="add-to-cart"><button :ref="'variation-'+entry.variation_id" @click="addToCart(entry)" type="submit" class="single_add_to_cart_button button alt" :class="{added: entry.added}"><?php echo __("Add to Cart", 'woo-variations-table'); ?></button></td>
</tr>
</tbody>
</table>
</script>
<div id="variations">
<div class="variation-filters">
<div class="filters form-inline">
<div class="filter">
<input placeholder="Keywords" name="query" v-model="searchQuery" class="form-control">
</div>
<div v-for="(attribute, key, index) in attributes" class="filter">
<label>{{ attribute.name }} </label>
<select v-model="activeFilters[index]" @change="setFilters()" class="form-control">
<option value="">Any</option>
<option v-for="option in attribute.options" :value="'attribute_'+key+':'+option.slug">{{ option.name }}</option>
</select>
</div>
</div>
</div>
<data-grid
:data="gridData"
:columns="gridColumns"
:active-columns="activeColumns"
:filter-key="searchQuery"
:filters="filters"
:attributes="attributes"
:show-attributes="showAttributes">
</data-grid>
</div>
<script type="text/javascript">
var productID = '<?php echo $product->get_id(); ?>';
var variations = <?php echo $variations; ?>;
var attributes = <?php echo $attributes; ?>;
var imageURL = '<?php echo $productImageURL; ?>';
var activeColumns = <?php echo $activeColumns; ?>;
var showAttributes = <?php echo $showAttributes; ?>;
// bootstrap the grid
var vm = new Vue({
el: '#variations',
data: {
searchQuery: '',
gridColumns: [
{key: 'image_link', title: '', type: 'image'},
{key: 'sku', title: 'SKU', type: 'text'},
{key: 'variation_description', title: 'Description', type: 'html'},
{key: 'weight_html', title: 'Weight', type: 'text'},
{key: 'dimensions', title: 'Dimensions', type: 'text'},
{key: 'price_html', title: 'Price', type: 'html'}
],
activeColumns: activeColumns,
gridData: variations,
attributes: attributes,
activeFilters: [],
filters: [],
isLoading: true,
productID: productID,
imageURL: imageURL,
showAttributes: showAttributes
},
mounted: function(){
var activeFilters = []
for (i = 0; i < Object.keys(this.attributes).length; i++) {
activeFilters.push("");
}
this.activeFilters = activeFilters;
},
methods: {
setFilters: function () {
var activeFilters = this.activeFilters;
var filters = [];
if(activeFilters.length){
var filterAny = 0
for(i=0; i < activeFilters.length; i++){
if(activeFilters[i] != ""){
var tup = activeFilters[i].split(':');
filters[i-filterAny] = {};
filters[i-filterAny][tup[0]] = tup[1];
}else{
filterAny++
}
}
}
this.filters = filters;
return filters;
}
}
})
</script>
</div>
<?php
}
}
| gpl-3.0 |
reosarevok/trykicovers | system/upload_file.php | 2031 | <?
function upload_file($uuid)
{
if (is_uploaded_file($_FILES['cover_image']['tmp_name']) && getimagesize($_FILES['cover_image']['tmp_name']) != false) {
$image = $_FILES['cover_image']['tmp_name'];
$imageFileType = pathinfo($_FILES['cover_image']['name'], PATHINFO_EXTENSION);
$image_dir = dirname(getcwd()) . '/static/images';
if (preg_match('/jpg|jpeg/i', $imageFileType)) {
$imageTmp = imagecreatefromjpeg($image);
} else if (preg_match('/png/i', $imageFileType)) {
$imageTmp = imagecreatefrompng($image);
} else if (preg_match('/gif/i', $imageFileType)) {
$imageTmp = imagecreatefromgif($image);
} else if (preg_match('/bmp/i', $imageFileType)) {
$imageTmp = imagecreatefrombmp($image);
} else {
return 0;
}
/* Create jpg */
list($width_orig, $height_orig) = getimagesize($image);
$ratio = $width_orig / $height_orig;
$width = 1600;
$height = 1600;
if (($width / $height) > $ratio) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $imageTmp, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
$dest_file = "$image_dir/$uuid.jpg";
imagejpeg($new_image, $dest_file);
/* Create thumbnail */
$width_thumb = 500;
$height_thumb = 500;
if (($width_thumb / $height_thumb) > $ratio) {
$width_thumb = $height_thumb * $ratio;
} else {
$height_thumb = $width_thumb / $ratio;
}
$new_thumbnail = imagecreatetruecolor($width_thumb, $height_thumb);
imagecopyresampled($new_thumbnail, $imageTmp, 0, 0, 0, 0, $width_thumb, $height_thumb, $width_orig, $height_orig);
$dest_thumbnail = "$image_dir/$uuid-thumb.jpg";
imagejpeg($new_thumbnail, $dest_thumbnail);
}
}
; | gpl-3.0 |
epam/JDI | Java/Tests/jdi-uitest-tutorialtests/src/test/java/com/epam/jdi/uitests/testing/career/common/tests/CareerTests.java | 1116 | package com.epam.jdi.uitests.testing.career.common.tests;
import com.epam.jdi.dataProviders.AttendeesProvider;
import com.epam.jdi.entities.Attendee;
import com.epam.jdi.uitests.testing.TestsBase;
import com.epam.web.matcher.testng.Check;
import org.testng.annotations.Test;
import static com.epam.jdi.enums.HeaderMenu.CAREERS;
import static com.epam.jdi.site.epam.EpamSite.*;
public class CareerTests extends TestsBase {
@Test(dataProvider = "attendees", dataProviderClass = AttendeesProvider.class)
public void sendCVTest(Attendee attendee) {
headerMenu.select(CAREERS);
careerPage.checkOpened();
careerPage.jobFilter.search(attendee.filter);
jobListingPage.checkOpened();
new Check("Table is not empty").isFalse(jobListingPage.jobsList::isEmpty);
jobListingPage.getJobRowByName("Test Automation Engineer (back-end)");
jobDescriptionPage.addCVForm.submit(attendee);
new Check("Captcha class contains 'form-error__tooltip'")
.contains(() -> jobDescriptionPage.captcha.getAttribute("class"), "form-error__field");
}
}
| gpl-3.0 |
Eugnis/easy-learning-of-paintings | app/src/main/java/com/eugnis/easylearningofpaintings/data/repo/PaintersRepo.java | 4896 | package com.eugnis.easylearningofpaintings.data.repo;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.eugnis.easylearningofpaintings.data.DatabaseManager;
import com.eugnis.easylearningofpaintings.data.model.Painter;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
/**
* Created by Eugnis on 03.12.2016.
*/
public class PaintersRepo {
private Painter painter;
public PaintersRepo(){
painter = new Painter();
}
public static String createTable(){
return "CREATE TABLE " + Painter.TABLE + "("
+ Painter.KEY_PainterID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Painter.KEY_Name + " TEXT, "
+ Painter.KEY_Years + " TEXT, "
+ Painter.KEY_About + " TEXT, "
+ Painter.KEY_Country + " TEXT )";
}
public int insert(Painter painter) {
int painterId;
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
ContentValues values = new ContentValues();
//values.put(Painter.KEY_PainterID, painter.getPainterID());
values.put(Painter.KEY_Name, painter.getName());
values.put(Painter.KEY_Years, painter.getYears());
values.put(Painter.KEY_About, painter.getAbout());
values.put(Painter.KEY_Country, painter.getCountry());
// Inserting Row
painterId=(int)db.insert(Painter.TABLE, null, values);
DatabaseManager.getInstance().closeDatabase();
return painterId;
}
public void delete( ) {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
db.delete(Painter.TABLE,null,null);
DatabaseManager.getInstance().closeDatabase();
}
public List<Painter> getPainters(){
Painter painter;
List<Painter> paintersList = new ArrayList<>();
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
String selectQuery = " SELECT " + Painter.KEY_PainterID
+ ", " + Painter.KEY_Name
+ ", " + Painter.KEY_Years
+ ", " + Painter.KEY_About
+ ", " + Painter.KEY_Country
+ ", " + Painter.KEY_Folder
+ " FROM " + Painter.TABLE;
Log.d(TAG, selectQuery);
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
painter= new Painter();
painter.setPainterID(cursor.getInt(cursor.getColumnIndex(Painter.KEY_PainterID)));
painter.setName(cursor.getString(cursor.getColumnIndex(Painter.KEY_Name)));
painter.setAbout(cursor.getString(cursor.getColumnIndex(Painter.KEY_About)));
painter.setYears(cursor.getString(cursor.getColumnIndex(Painter.KEY_Years)));
painter.setCountry(cursor.getString(cursor.getColumnIndex(Painter.KEY_Country)));
painter.setFolder(cursor.getString(cursor.getColumnIndex(Painter.KEY_Folder)));
paintersList.add(painter);
} while (cursor.moveToNext());
}
cursor.close();
DatabaseManager.getInstance().closeDatabase();
return paintersList;
}
public Painter getPainter(String ID) {
Painter painter= new Painter();
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
String selectQuery = " SELECT " + Painter.KEY_PainterID
+ ", " + Painter.KEY_Name
+ ", " + Painter.KEY_Years
+ ", " + Painter.KEY_About
+ ", " + Painter.KEY_Country
+ ", " + Painter.KEY_Folder
+ " FROM " + Painter.TABLE
+ " WHERE " + Painter.KEY_PainterID + " = " + ID;
Log.d(TAG, selectQuery);
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
painter.setPainterID(cursor.getInt(cursor.getColumnIndex(Painter.KEY_PainterID)));
painter.setName(cursor.getString(cursor.getColumnIndex(Painter.KEY_Name)));
painter.setAbout(cursor.getString(cursor.getColumnIndex(Painter.KEY_About)));
painter.setYears(cursor.getString(cursor.getColumnIndex(Painter.KEY_Years)));
painter.setCountry(cursor.getString(cursor.getColumnIndex(Painter.KEY_Country)));
painter.setFolder(cursor.getString(cursor.getColumnIndex(Painter.KEY_Folder)));
} while (cursor.moveToNext());
}
cursor.close();
DatabaseManager.getInstance().closeDatabase();
return painter;
}
}
| gpl-3.0 |
james-monkeyshines/rna-phase-3 | src/Models/CodonParent.cc | 6220 | #include "Models/CodonParent.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
using namespace std;
CodonParent::CodonParent(){
}
CodonParent::CodonParent( const string & registrationName ) :
MatrixModel( registrationName ){
}
CodonParent::CodonParent( ParametersSet & parameters ) : MatrixModel( parameters ){
aminoAcid.reserve(20);
aminoAcid.push_back('A');
aminoAcid.push_back('R');
aminoAcid.push_back('N');
aminoAcid.push_back('D');
aminoAcid.push_back('C');
aminoAcid.push_back('Q');
aminoAcid.push_back('E');
aminoAcid.push_back('G');
aminoAcid.push_back('H');
aminoAcid.push_back('I');
aminoAcid.push_back('L');
aminoAcid.push_back('K');
aminoAcid.push_back('M');
aminoAcid.push_back('F');
aminoAcid.push_back('P');
aminoAcid.push_back('S');
aminoAcid.push_back('T');
aminoAcid.push_back('W');
aminoAcid.push_back('Y');
aminoAcid.push_back('V');
}
void CodonParent::readGeneticCode(string fileName){
ifstream fileStream;
// Attempt to open the file
fileStream.open( fileName.c_str() );
if ( !fileStream ) {
cerr << "Unable to open file " << fileName << " for reading" << endl;
exit(EXIT_FAILURE);
}
while(!fileStream.eof()){
string codon;
char aa;
fileStream >> codon;
if (codon.length()!=3){
cerr << "Invalid codon \"" << codon << "\" in your genetic code" << endl;
}
for ( unsigned int n = 0; n < 3; ++n ){
unsigned int i = getSingleSymbolNumber(codon[n]);
if ( (i!=0x01) && (i!=0x02) && (i!=0x04) && (i!=0x08) ){
cerr << "Invalid codon \"" << codon << "\" in your genetic code" << endl;
exit(EXIT_FAILURE);
}
}
fileStream >> ws;
fileStream >> aa;
if ( find(aminoAcid.begin(), aminoAcid.end(), aa) == aminoAcid.end() ){
cerr << "Unrecognized amino-acid \"" << aa << "\" in your genetic code" << endl;
exit(EXIT_FAILURE);
}
geneticCode.push_back( pair <string, char> (codon, aa) );
fileStream >> ws;
}
}
CodonParent::~CodonParent() {
}
int CodonParent::getSingleSymbolNumber(const char & base) const {
//for efficiency reason we use binary bits and mask there
switch (base) {
case 'a': case 'A':
return 0x01;
case 'c': case 'C':
return 0x02;
case 'g': case 'G':
return 0x04;
case 'u': case 't': case 'U': case 'T':
return 0x08;
case 'r': case 'R':
return 0x05; // Unknown purine (A or G)
case 'y': case 'Y':
return 0x0A; // Unknown pyramidine (C or U)
case 'm': case 'M':
return 0x03; // (A or C)
case 'k': case 'K':
return 0x0C; // (U or G)
case 'w': case 'W':
return 0X09; // (U or A)
case 's': case 'S':
return 0X06; // (C or G)
case 'b': case 'B':
return 0X0E; // (U, C or G)
case 'd': case 'D':
return 0X0D; // (U, A or G)
case 'h': case 'H':
return 0x0B; // (U, A or C)
case 'v': case 'V':
return 0X07; // (A, C or G)
case 'n': case 'x': case '?': case 'N': case 'X': case '-':
return 0x0F; // Unknown nucleotide (A, C, G or T)
default :
return -1; // Out of range (unrecognized symbol)
}
}
string CodonParent::getSingleSymbol( unsigned int symbolNumber) const{
switch ( symbolNumber ) {
case 0x01 :
return ( string( "A" ) );
case 0x02 :
return ( string( "C" ) );
case 0x04 :
return ( string( "G" ) );
case 0x08 :
return ( string( "U" ) );
case 0x05 :
return ( string( "R" ) ); // Unknown Purine (A or G)
case 0x0A :
return ( string( "Y" ) ); // Unknown Pyramidine (C or T)
case 0x03 :
return ( string( "M" ) ); // (A or C)
case 0x0C :
return ( string( "K" ) ); // (U or G)
case 0x09 :
return ( string( "W" ) ); // (U or A)
case 0x06 :
return ( string( "S" ) ); // (C or G)
case 0x0E :
return ( string( "B" ) ); // (C, G or T)
case 0x0D :
return ( string( "D" ) ); // (A, G or T)
case 0x0B :
return ( string( "H" ) ); // (A, C or T)
case 0x07 :
return ( string( "V" ) ); // (A, C or G)
case 0x0F :
return ( string( "N" ) ); // Unknown (A , C , G or T)
default :
return ( string( "Z" ) ); // Unrecognized symbol
}
}
int CodonParent::getSymbolNumber( const string & codonSymbol, unsigned int ) const {
if (codonSymbol.length() != 3) return getNumberSymbols();
int nuc1 = getSingleSymbolNumber(codonSymbol[0]) - 1 ;
if (nuc1==-2) return getNumberSymbols();
int nuc2 = getSingleSymbolNumber(codonSymbol[1]) - 1 ;
if (nuc2==-2) return getNumberSymbols();
int nuc3 = getSingleSymbolNumber(codonSymbol[2]) - 1 ;
if (nuc3==-2) return getNumberSymbols();
return (nuc1*225+nuc2*15+nuc3);
}
unsigned int CodonParent::getMask( unsigned int symbolNumber ) const {
unsigned int n1 = symbolNumber/225;
unsigned int r = symbolNumber%225;
unsigned int n2 = r/15;
unsigned int n3 = r%15;
return (((n1+1)<<8) | ((n2+1)<<4) | (n3+1));
}
string CodonParent::getSymbol( unsigned int symbolNumber, unsigned int ) const {
if (symbolNumber>=getNumberSymbols()) return "ZZZ";
unsigned int q = symbolNumber/225;
unsigned int r = symbolNumber%225;
string s = getSingleSymbol(q+1);
s += getSingleSymbol(r/15+1);
s += getSingleSymbol(r%15+1);
return s;
}
| gpl-3.0 |
yahongie/CMS-spell-AD | js/ckeditor/plugins/kcfinder/js/browser/clipboard.js | 10477 | <?php
/** This file is part of KCFinder project
*
* @desc Clipboard functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var size = 0;
$.each(this.clipboard, function(i, val) {
size += parseInt(val.size);
});
size = this.humanSize(size);
$('#clipboard').html('<div title="' + this.label("Clipboard") + ' (' + this.clipboard.length + ' ' + this.label("files") + ', ' + size + ')" onclick="browser.openClipboard()"></div>');
var resize = function() {
$('#clipboard').css({
left: $(window).width() - $('#clipboard').outerWidth() + 'px',
top: $(window).height() - $('#clipboard').outerHeight() + 'px'
});
};
resize();
$('#clipboard').css('display', 'block');
$(window).unbind();
$(window).resize(function() {
browser.resize();
resize();
});
};
browser.openClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
if ($('.menu a[href="kcact:cpcbd"]').html()) {
$('#clipboard').removeClass('selected');
this.hideDialog();
return;
}
var html = '<div class="menu"><div class="list">';
$.each(this.clipboard, function(i, val) {
icon = _.getFileExtension(val.name);
if (val.thumb)
icon = '.image';
else if (!val.smallIcon || !icon.length)
icon = '.';
var icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png';
html += '<a style="background-image:url(' + _.escapeDirs(icon) + ')" title="' + browser.label("Click to remove from the Clipboard") + '" onclick="browser.removeFromClipboard(' + i + ')">' + _.htmlData(_.basename(val.name)) + '</a>';
});
html += '</div><div class="delimiter"></div>';
if (this.support.zip) html+=
'<a href="kcact:download">' + this.label("Download files") + '</a>';
if (this.access.files.copy || this.access.files.move || this.access.files['delete'])
html += '<div class="delimiter"></div>';
if (this.access.files.copy)
html += '<a href="kcact:cpcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' +
this.label("Copy files here") + '</a>';
if (this.access.files.move)
html += '<a href="kcact:mvcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' +
this.label("Move files here") + '</a>';
if (this.access.files['delete'])
html += '<a href="kcact:rmcbd">' + this.label("Delete files") + '</a>';
html += '<div class="delimiter"></div>' +
'<a href="kcact:clrcbd">' + this.label("Clear the Clipboard") + '</a>' + '</div>';
setTimeout(function() {
$('#clipboard').addClass('selected');
$('#dialog').html(html);
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
browser.downloadClipboard();
return false;
});
$('.menu a[href="kcact:cpcbd"]').click(function() {
if (!browser.dirWritable) return false;
browser.hideDialog();
browser.copyClipboard(browser.dir);
return false;
});
$('.menu a[href="kcact:mvcbd"]').click(function() {
if (!browser.dirWritable) return false;
browser.hideDialog();
browser.moveClipboard(browser.dir);
return false;
});
$('.menu a[href="kcact:rmcbd"]').click(function() {
browser.hideDialog();
browser.confirm(
browser.label("Are you sure you want to delete all files in the Clipboard?"),
function(callBack) {
if (callBack) callBack();
browser.deleteClipboard();
}
);
return false;
});
$('.menu a[href="kcact:clrcbd"]').click(function() {
browser.hideDialog();
browser.clearClipboard();
return false;
});
var left = $(window).width() - $('#dialog').outerWidth();
var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight();
var lheight = top + _.outerTopSpace('#dialog');
$('.menu .list').css('max-height', lheight + 'px');
var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight();
$('#dialog').css({
left: (left - 4) + 'px',
top: top + 'px'
});
$('#dialog').fadeIn();
}, 1);
};
browser.removeFromClipboard = function(i) {
if (!this.clipboard || !this.clipboard[i]) return false;
if (this.clipboard.length == 1) {
this.clearClipboard();
this.hideDialog();
return;
}
if (i < this.clipboard.length - 1) {
var last = this.clipboard.slice(i + 1);
this.clipboard = this.clipboard.slice(0, i);
this.clipboard = this.clipboard.concat(last);
} else
this.clipboard.pop();
this.initClipboard();
this.hideDialog();
this.openClipboard();
return true;
};
browser.copyClipboard = function(dir) {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not readable."));
return;
}
var go = function(callBack) {
if (dir == browser.dir)
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('cp_cbd'),
data: {dir: dir, files: files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
if (dir == browser.dir)
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not readable. Do you want to copy the rest?", {count:failed}),
go
);
else
go();
};
browser.moveClipboard = function(dir) {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable && this.clipboard[i].writable)
files[i] = this.clipboard[i].dir + "/" + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not movable."));
return;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('mv_cbd'),
data: {dir: dir, files: files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not movable. Do you want to move the rest?", {count: failed}),
go
);
else
go();
};
browser.deleteClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable && this.clipboard[i].writable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not removable."));
return;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('rm_cbd'),
data: {files:files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter:''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not removable. Do you want to delete the rest?", {count: failed}),
go
);
else
go();
};
browser.downloadClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
if (files.length)
this.post(this.baseGetData('downloadClipboard'), {files:files});
};
browser.clearClipboard = function() {
$('#clipboard').html('');
this.clipboard = [];
};
| gpl-3.0 |
fangxinmiao/projects | Architeture/Backend/Library/Java/Pdfbox/demo/pdfbox-demo/src/main/java/demo/pdfbox/PdfboxApplication.java | 2158 | package demo.pdfbox;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
/**
* 使用pdfbox库
* Created by fangxm on 17-6-6.
*
* Note:
* CentOS下使用pdfbox库进行pdf转jpg操作,出现中文乱码的解决方式:
1. 删除用户主目录下的 .pdfbox.cache文件
2. 将simhei.ttf拷贝到/usr/share/fonts目录下
3. 执行: fc-cache
*/
public class PdfboxApplication {
private static void pdf2jpg(String pdfFile, String jpgFile){
try {
PDDocument doc = PDDocument.load(new File(pdfFile));
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
String name;
String prefix;
int index = jpgFile.lastIndexOf(".");
if (index == -1) {
name = jpgFile;
prefix = null;
} else {
name = jpgFile.substring(0, index);
prefix = jpgFile.substring(index + 1);
}
for (int i = 0; i < pageCount; i++) {
BufferedImage image = renderer.renderImageWithDPI(i, 120, ImageType.RGB);
image.flush();
String saveName;
if (pageCount == 1 || prefix == null || prefix.length() == 0) {
saveName = jpgFile;
} else {
saveName = String.format("%s-%d.%s", name, i + 1, prefix);
}
ImageIO.write(image, "jpg", new File(saveName));
}
doc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java -jar foo.jar input.pdf output.jpg");
System.exit(1);
}
long start = System.currentTimeMillis();
pdf2jpg(args[0], args[1]);
System.out.println((System.currentTimeMillis() - start) + " ms");
}
}
| gpl-3.0 |
edwardwkrohne/satcolors | src/pattern.cpp | 3851 | // -*- Mode: C++ -*-
////////////////////////////////////////////////////////////////////////////
//
// satcolors -- for writably and readably building problems for SAT-solving
// Copyright (C) 2014 Edward W. Krohne III
//
// The research that led to this product was partially supported by the
// U.S. NSF grants DMS-0943870 and DMS-1201290.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
////////////////////////////////////////////////////////////////////////////
//
// Implementation of the Pattern class
#include <cmath>
#include <iostream>
#include <sstream>
#include <vector>
#include <stdexcept>
#include "pattern.h"
using namespace std;
namespace {
// Increase readability.
enum {
BLANK,
FILLED,
BLANK_CENTER,
FILLED_CENTER,
NEWLINE
};
}
void Pattern::computePattern(istream& strin) {
// Will need to pass through the strings more than once, so build a list of tokens to do it with.
vector<int> tokens(0);
isBlank = true;
for ( string token; strin >> token; ) {
if ( token == ";" ) {
tokens.push_back(NEWLINE);
} else if ( token == "x" ) {
tokens.push_back(FILLED);
} else if ( token == "." ) {
tokens.push_back(BLANK);
} else if ( token == "(x)" ) {
tokens.push_back(FILLED_CENTER);
} else if ( token == "(.)" ) {
tokens.push_back(BLANK_CENTER);
} else {
throw runtime_error("Unrecognized token for Pattern constructor: " + token);
}
}
// Compute dimensions and look for center
int row = 0;
int col = 0;
centerRow = -1;
centerCol = -1;
height = 0;
width = 0;
for ( auto iter = tokens.begin(); iter != tokens.end(); ++iter ) {
// Look for end of row
if ( *iter == NEWLINE) {
col = 0;
height = max(++row, height);
continue;
}
// Look for center
if ( *iter == FILLED_CENTER || *iter == BLANK_CENTER ) {
if ( centerRow != -1 ) {
throw runtime_error("Multiple centers found by Pattern constructor.");
}
centerRow = row;
centerCol = col;
}
// Increment column
width = max(++col, width);
}
// Create space in the pattern (should probably make a resize function).
{
decltype(pattern) tempPat(height,width);
pattern.swap(tempPat);
}
// Get the actual pattern
row = col = 0;
for ( auto iter = tokens.begin(); iter != tokens.end(); ++iter ) {
// Look for end of row
if ( *iter == NEWLINE) {
// If we see a newline, fill zeros out to the end.
while ( col < width ) {
pattern[row][col++] = false;
}
row++;
col = 0;
continue;
}
// Fill in any spaces
bool cellFilled = *iter == FILLED || *iter == FILLED_CENTER;
pattern[row][col] = cellFilled;
isBlank &= !cellFilled;
col++;
}
}
Pattern::Pattern(const string& str) :
pattern(0,0)
{
istringstream strin(str);
computePattern(strin);
}
Pattern::Pattern(istream&& strin) :
pattern(0,0)
{
computePattern(strin);
}
Pattern::Pattern(istream& strin) :
pattern(0,0)
{
computePattern(strin);
}
Pattern::subscript_type Pattern::operator[] (int index) {
return pattern[index];
}
Pattern::const_subscript_type Pattern::operator[] (int index) const {
return pattern[index];
}
| gpl-3.0 |
ozbek/quran_android | app/src/main/java/com/quran/labs/androidquran/data/SuraAyahIterator.java | 1203 | package com.quran.labs.androidquran.data;
import com.quran.data.core.QuranInfo;
import com.quran.data.model.SuraAyah;
public class SuraAyahIterator {
private SuraAyah start;
private SuraAyah end;
private boolean started;
private int curSura;
private int curAyah;
private final QuranInfo quranInfo;
public SuraAyahIterator(QuranInfo quranInfo, SuraAyah start, SuraAyah end) {
this.quranInfo = quranInfo;
// Sanity check
if (start.compareTo(end) <= 0) {
this.start = start;
this.end = end;
} else {
this.start = end;
this.end = start;
}
reset();
}
private void reset() {
curSura = start.sura;
curAyah = start.ayah;
started = false;
}
public int getSura() {
return curSura;
}
public int getAyah() {
return curAyah;
}
private boolean hasNext() {
return !started || curSura < end.sura || curAyah < end.ayah;
}
public boolean next() {
if (!started) {
return started = true;
} else if (!hasNext()) {
return false;
}
if (curAyah < quranInfo.getNumberOfAyahs(curSura)) {
curAyah++;
} else {
curAyah = 1;
curSura++;
}
return true;
}
}
| gpl-3.0 |
j-otsuki/SpM | thirdparty/cpplapack/include/zhsmatrix-/zhsmatrix-constructor.hpp | 2629 | //=============================================================================
/*! zhsmatrix constructor without arguments */
inline zhsmatrix::zhsmatrix()
: m(n)
{CPPL_VERBOSE_REPORT;
//////// initialize ////////
n =0;
data.clear();
line.clear();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//=============================================================================
/*! zhsmatrix copy constructor */
inline zhsmatrix::zhsmatrix(const zhsmatrix& mat)
: m(n)
{CPPL_VERBOSE_REPORT;
data.clear();
line.clear();
copy(mat);
}
//=============================================================================
/*! zhsmatrix constructor to cast _zhsmatrix */
inline zhsmatrix::zhsmatrix(const _zhsmatrix& mat)
: m(n)
{CPPL_VERBOSE_REPORT;
n =mat.n;
data.clear();
line.clear();
data.swap(mat.data);
line.swap(mat.line);
mat.nullify();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//=============================================================================
/*! zhsmatrix constructor with size specification */
inline zhsmatrix::zhsmatrix(const CPPL_INT& _n, const CPPL_INT _c)
: m(n)
{CPPL_VERBOSE_REPORT;
#ifdef CPPL_DEBUG
if( _n<0 || _c<0 ){
ERROR_REPORT;
std::cerr << "Matrix sizes and the length of arrays must be positive integers. " << std::endl
<< "Your input was (" << _n << "," << _c << ")." << std::endl;
exit(1);
}
#endif//CPPL_DEBUG
//////// initialize ////////
n =_n;
data.resize(0);
data.reserve(_c);
line.resize(n);
}
//=============================================================================
/*! zhsmatrix constructor with filename */
inline zhsmatrix::zhsmatrix(const char* filename)
: m(n)
{CPPL_VERBOSE_REPORT;
data.clear();
line.clear();
//// read ////
read(filename);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//=============================================================================
/*! zhsmatrix destructor */
inline zhsmatrix::~zhsmatrix()
{CPPL_VERBOSE_REPORT;
data.clear();
line.clear();
}
| gpl-3.0 |
Dwarfex/Hosting-Service | hosting_project/ws_versions/ws2/languages/no/imprint.php | 5024 | <?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2010 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'admins'=>'Administrator(er):',
'coding'=>'Programmering',
'coding_info'=>'This site is using the <a href="http://www.webspell.org" target="_blank">webSPELL Free Content Management System (version: $version)</a>. It is based on PHP4/5 and MySQL and running under the <a href="http://www.fsf.org/licensing/licenses/gpl.html" target="_blank">GNU GENERAL PUBLIC LICENSE</a>.<br />Get it for free at this location: <a href="http://www.webspell.org" target="_blank">www.webSPELL.org</a>',
'disclaimer'=>'Disclaimer',
'disclaimer_text'=>'<b>1. Content</b><br />
The author reserves the right not to be responsible for the topicality, correctness, completeness or quality of the information provided. Liability claims regarding damage caused by the use of any information provided, including any kind of information which is incomplete or incorrect,will therefore be rejected.<br />
All offers are not-binding and without obligation. Parts of the pages or the complete publication including all offers and information might be extended, changed or partly or completely deleted by the author without separate announcement.<br /><br />
<b>2. Referrals and links</b><br />
The author is not responsible for any contents linked or referred to from his pages - unless he has full knowledge of illegal contents and would be able to prevent the visitors of his site fromviewing those pages. If any damage occurs by the use of information presented there, only the author of the respective pages might be liable, not the one who has linked to these pages. Furthermore the author is not liable for any postings or messages published by users of discussion boards, guestbooks or mailinglists provided on his page.<br /><br />
<b>3. Copyright</b><br />
The author intended not to use any copyrighted material for the publication or, if not possible, to indicatethe copyright of the respective object.
The copyright for any material created by the author is reserved. Any duplication or use of objects such as images, diagrams, sounds or texts in other electronic or printed publications is not permitted without the authors agreement.<br /><br />
<b>4. Privacy policy</b><br />
If the opportunity for the input of personal or business data (email addresses, name, addresses) is given, the input of these data takes place voluntarily. The use and payment of all offered services are permitted - if and so far technically possible and reasonable - without specification of any personal data or under specification of anonymized data or an alias. The use of published postal addresses, telephone or fax numbers and email addresses for marketing purposes is prohibited, offenders sending unwanted spam messages will be punished.<br /><br />
<b>5. Legal validity of this disclaimer</b><br />
This disclaimer is to be regarded as part of the internet publication which you were referred from. If sections or individual terms of this statement are not legal or correct, the content or validity of the other parts remain uninfluenced by this fact.',
'imprint'=>'Opphavsrett',
'mods'=>'Moderator(er):',
'responsible_persons'=>'Ansvarlige personer',
'webmaster'=>'Webmaster:'
);
?> | gpl-3.0 |
jimbo8098/core | modules/Finance/invoices_manage_processBulk.php | 35265 | <?php
/*
Gibbon, Flexible & Open School System
Copyright (C) 2010, Ross Parker
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
include '../../functions.php';
include '../../config.php';
//New PDO DB connection
$pdo = new Gibbon\sqlConnection();
$connection2 = $pdo->getConnection();
@session_start();
//PHPMailer include
require $_SESSION[$guid]['absolutePath'].'/lib/PHPMailer/PHPMailerAutoload.php';
$from = getSettingByScope($connection2, 'Finance', 'email');
//Module includes
include './moduleFunctions.php';
$action = $_POST['action'];
$gibbonSchoolYearID = $_GET['gibbonSchoolYearID'];
$status = $_GET['status'];
$gibbonFinanceInvoiceeID = $_GET['gibbonFinanceInvoiceeID'];
$monthOfIssue = $_GET['monthOfIssue'];
$gibbonFinanceBillingScheduleID = $_GET['gibbonFinanceBillingScheduleID'];
$gibbonFinanceFeeCategoryID = $_GET['gibbonFinanceFeeCategoryID'];
if ($gibbonSchoolYearID == '' or $action == '') { echo 'Fatal error loading this page!';
} else {
if ($action == 'issue' or $action == 'issueNoEmail') {
$URL = $_SESSION[$guid]['absoluteURL'].'/index.php?q=/modules/'.getModuleName($_POST['address'])."/invoices_manage.php&gibbonSchoolYearID=$gibbonSchoolYearID&status=Issued&gibbonFinanceInvoiceeID=$gibbonFinanceInvoiceeID&monthOfIssue=$monthOfIssue&gibbonFinanceBillingScheduleID=$gibbonFinanceBillingScheduleID";
} else {
$URL = $_SESSION[$guid]['absoluteURL'].'/index.php?q=/modules/'.getModuleName($_POST['address'])."/invoices_manage.php&gibbonSchoolYearID=$gibbonSchoolYearID&status=$status&gibbonFinanceInvoiceeID=$gibbonFinanceInvoiceeID&monthOfIssue=$monthOfIssue&gibbonFinanceBillingScheduleID=$gibbonFinanceBillingScheduleID&gibbonFinanceFeeCategoryID=$gibbonFinanceFeeCategoryID";
}
if (isActionAccessible($guid, $connection2, '/modules/Finance/invoices_manage.php') == false) {
$URL .= '&return=error0';
header("Location: {$URL}");
} else {
$gibbonFinanceInvoiceIDs = $_POST['gibbonFinanceInvoiceIDs'];
if (count($gibbonFinanceInvoiceIDs) < 1) {
$URL .= '&return=error1';
header("Location: {$URL}");
} else {
$partialFail = false;
//DELETE
if ($action == 'delete') {
foreach ($gibbonFinanceInvoiceIDs as $gibbonFinanceInvoiceID) {
try {
$data = array('gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID);
$sql = 'DELETE FROM gibbonFinanceInvoice WHERE gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID';
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
$partialFail = true;
}
try {
$data = array('gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID);
$sql = 'DELETE FROM gibbonFinanceInvoiceFee WHERE gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID';
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
$partialFail = true;
}
}
if ($partialFail == true) {
$URL .= '&return=warning1';
header("Location: {$URL}");
} else {
$URL .= '&return=success0';
header("Location: {$URL}");
}
}
//ISSUE
elseif ($action == 'issue' or $action == 'issueNoEmail') {
$thisLockFail = false;
//LOCK INVOICE TABLES
try {
$data = array();
$sql = 'LOCK TABLES gibbonFinanceInvoice WRITE, gibbonFinanceInvoiceFee WRITE, gibbonFinanceInvoicee WRITE, gibbonFinanceFee WRITE, gibbonFinanceFeeCategory WRITE, gibbonFinanceBillingSchedule WRITE';
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
$partialFail = true;
$thisLockFail = true;
}
if ($thisLockFail == false) {
$emailFail = false;
foreach ($gibbonFinanceInvoiceIDs as $gibbonFinanceInvoiceID) {
try {
$data = array('gibbonSchoolYearID' => $gibbonSchoolYearID, 'gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID);
$sql = "SELECT gibbonFinanceInvoice.*, gibbonFinanceBillingSchedule.invoiceDueDate AS invoiceDueDateScheduled FROM gibbonFinanceInvoice LEFT JOIN gibbonFinanceBillingSchedule ON (gibbonFinanceInvoice.gibbonFinanceBillingScheduleID=gibbonFinanceBillingSchedule.gibbonFinanceBillingScheduleID) WHERE gibbonFinanceInvoice.gibbonSchoolYearID=:gibbonSchoolYearID AND gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID AND status='Pending'";
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
}
if ($result->rowCount() != 1) {
$partialFail = true;
} else {
$row = $result->fetch();
$status = 'Issued';
if ($row['billingScheduleType'] == 'Scheduled') {
$separated = 'Y';
$invoiceDueDate = $row['invoiceDueDateScheduled'];
} else {
$separated = null;
$invoiceDueDate = $row['invoiceDueDate'];
}
$invoiceIssueDate = date('Y-m-d');
if ($invoiceDueDate == '') {
$partialFail = true;
} else {
//Write to database
try {
$data = array('status' => $status, 'separated' => $separated, 'invoiceDueDate' => $invoiceDueDate, 'invoiceIssueDate' => $invoiceIssueDate, 'gibbonPersonIDUpdate' => $_SESSION[$guid]['gibbonPersonID'], 'gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID);
$sql = "UPDATE gibbonFinanceInvoice SET status=:status, separated=:separated, invoiceDueDate=:invoiceDueDate, invoiceIssueDate=:invoiceIssueDate, gibbonPersonIDUpdate=:gibbonPersonIDUpdate, timestampUpdate='".date('Y-m-d H:i:s')."' WHERE gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID";
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
$URL .= '&return=error2';
header("Location: {$URL}");
exit();
}
//Read & Organise Fees
$fees = array();
$count = 0;
//Standard Fees
try {
$dataFees['gibbonFinanceInvoiceID'] = $gibbonFinanceInvoiceID;
$sqlFees = "SELECT gibbonFinanceInvoiceFee.gibbonFinanceInvoiceFeeID, gibbonFinanceInvoiceFee.feeType, gibbonFinanceFeeCategory.name AS category, gibbonFinanceFee.name AS name, gibbonFinanceFee.fee AS fee, gibbonFinanceFee.description AS description, gibbonFinanceInvoiceFee.gibbonFinanceFeeID AS gibbonFinanceFeeID, gibbonFinanceFee.gibbonFinanceFeeCategoryID AS gibbonFinanceFeeCategoryID, sequenceNumber FROM gibbonFinanceInvoiceFee JOIN gibbonFinanceFee ON (gibbonFinanceInvoiceFee.gibbonFinanceFeeID=gibbonFinanceFee.gibbonFinanceFeeID) JOIN gibbonFinanceFeeCategory ON (gibbonFinanceFee.gibbonFinanceFeeCategoryID=gibbonFinanceFeeCategory.gibbonFinanceFeeCategoryID) WHERE gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID AND feeType='Standard' ORDER BY sequenceNumber";
$resultFees = $connection2->prepare($sqlFees);
$resultFees->execute($dataFees);
} catch (PDOException $e) {
$partialFail = true;
}
while ($rowFees = $resultFees->fetch()) {
$fees[$count]['name'] = $rowFees['name'];
$fees[$count]['gibbonFinanceFeeCategoryID'] = $rowFees['gibbonFinanceFeeCategoryID'];
$fees[$count]['fee'] = $rowFees['fee'];
$fees[$count]['feeType'] = 'Standard';
$fees[$count]['gibbonFinanceFeeID'] = $rowFees['gibbonFinanceFeeID'];
$fees[$count]['separated'] = 'Y';
$fees[$count]['description'] = $rowFees['description'];
$fees[$count]['sequenceNumber'] = $rowFees['sequenceNumber'];
++$count;
}
//Ad Hoc Fees
try {
$dataFees['gibbonFinanceInvoiceID'] = $gibbonFinanceInvoiceID;
$sqlFees = "SELECT gibbonFinanceInvoiceFee.gibbonFinanceInvoiceFeeID, gibbonFinanceInvoiceFee.feeType, gibbonFinanceFeeCategory.name AS category, gibbonFinanceInvoiceFee.name AS name, gibbonFinanceInvoiceFee.fee, gibbonFinanceInvoiceFee.description AS description, NULL AS gibbonFinanceFeeID, gibbonFinanceInvoiceFee.gibbonFinanceFeeCategoryID AS gibbonFinanceFeeCategoryID, sequenceNumber FROM gibbonFinanceInvoiceFee JOIN gibbonFinanceFeeCategory ON (gibbonFinanceInvoiceFee.gibbonFinanceFeeCategoryID=gibbonFinanceFeeCategory.gibbonFinanceFeeCategoryID) WHERE gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID AND feeType='Ad Hoc' ORDER BY sequenceNumber";
$resultFees = $connection2->prepare($sqlFees);
$resultFees->execute($dataFees);
} catch (PDOException $e) {
$partialFail = true;
}
while ($rowFees = $resultFees->fetch()) {
$fees[$count]['name'] = $rowFees['name'];
$fees[$count]['gibbonFinanceFeeCategoryID'] = $rowFees['gibbonFinanceFeeCategoryID'];
$fees[$count]['fee'] = $rowFees['fee'];
$fees[$count]['feeType'] = 'Ad Hoc';
$fees[$count]['gibbonFinanceFeeID'] = null;
$fees[$count]['separated'] = null;
$fees[$count]['description'] = $rowFees['description'];
$fees[$count]['sequenceNumber'] = $rowFees['sequenceNumber'];
++$count;
}
//Remove fees
try {
$data = array('gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID);
$sql = 'DELETE FROM gibbonFinanceInvoiceFee WHERE gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID';
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
$partialFail = true;
}
//Add fees to invoice
foreach ($fees as $fee) {
try {
$dataInvoiceFee = array('gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID, 'feeType' => $fee['feeType'], 'gibbonFinanceFeeID' => $fee['gibbonFinanceFeeID'], 'name' => $fee['name'], 'description' => $fee['description'], 'gibbonFinanceFeeCategoryID' => $fee['gibbonFinanceFeeCategoryID'], 'fee' => $fee['fee'], 'separated' => $fee['separated'], 'sequenceNumber' => $fee['sequenceNumber']);
$sqlInvoiceFee = 'INSERT INTO gibbonFinanceInvoiceFee SET gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID, feeType=:feeType, gibbonFinanceFeeID=:gibbonFinanceFeeID, name=:name, description=:description, gibbonFinanceFeeCategoryID=:gibbonFinanceFeeCategoryID, fee=:fee, separated=:separated, sequenceNumber=:sequenceNumber';
$resultInvoiceFee = $connection2->prepare($sqlInvoiceFee);
$resultInvoiceFee->execute($dataInvoiceFee);
} catch (PDOException $e) {
$partialFail = true;
}
}
}
}
}
}
//Unlock invoice table
try {
$sql = 'UNLOCK TABLES';
$result = $connection2->query($sql);
} catch (PDOException $e) {}
if ($action == 'issue') {
//Loop through invoices again, this time to send invoices....they can not be sent in first loop due to table locking issues.
foreach ($gibbonFinanceInvoiceIDs as $gibbonFinanceInvoiceID) {
try {
$data = array('gibbonSchoolYearID' => $gibbonSchoolYearID, 'gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID);
$sql = 'SELECT gibbonFinanceInvoice.*, gibbonFinanceBillingSchedule.invoiceDueDate AS invoiceDueDateScheduled FROM gibbonFinanceInvoice LEFT JOIN gibbonFinanceBillingSchedule ON (gibbonFinanceInvoice.gibbonFinanceBillingScheduleID=gibbonFinanceBillingSchedule.gibbonFinanceBillingScheduleID) WHERE gibbonFinanceInvoice.gibbonSchoolYearID=:gibbonSchoolYearID AND gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID';
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
}
if ($result->rowCount() != 1) {
$emailFail = true;
} else {
$row = $result->fetch();
//DEAL WITH EMAILS
$emails = array();
$emailsCount = 0;
if ($row['invoiceTo'] == 'Company') {
try {
$dataCompany = array('gibbonFinanceInvoiceeID' => $row['gibbonFinanceInvoiceeID']);
$sqlCompany = 'SELECT * FROM gibbonFinanceInvoicee WHERE gibbonFinanceInvoiceeID=:gibbonFinanceInvoiceeID';
$resultCompany = $connection2->prepare($sqlCompany);
$resultCompany->execute($dataCompany);
} catch (PDOException $e) {
$emailFail = true;
}
if ($resultCompany->rowCount() != 1) {
$emailFail = true;
} else {
$rowCompany = $resultCompany->fetch();
if ($rowCompany['companyEmail'] != '' and $rowCompany['companyContact'] != '' and $rowCompany['companyName'] != '') {
$emailsInner = explode(',', $rowCompany['companyEmail']);
for ($n = 0; $n < count($emailsInner); ++$n) {
if ($n == 0) {
$emails[$emailsCount] = trim($emailsInner[$n]);
++$emailsCount;
} else {
array_push($emails, trim($emailsInner[$n]));
++$emailsCount;
}
}
if ($rowCompany['companyCCFamily'] == 'Y') {
try {
$dataParents = array('gibbonFinanceInvoiceeID' => $row['gibbonFinanceInvoiceeID']);
$sqlParents = "SELECT parent.title, parent.surname, parent.preferredName, parent.email, parent.address1, parent.address1District, parent.address1Country, homeAddress, homeAddressDistrict, homeAddressCountry FROM gibbonFinanceInvoicee JOIN gibbonPerson AS student ON (gibbonFinanceInvoicee.gibbonPersonID=student.gibbonPersonID) JOIN gibbonFamilyChild ON (gibbonFamilyChild.gibbonPersonID=student.gibbonPersonID) JOIN gibbonFamily ON (gibbonFamilyChild.gibbonFamilyID=gibbonFamily.gibbonFamilyID) JOIN gibbonFamilyAdult ON (gibbonFamily.gibbonFamilyID=gibbonFamilyAdult.gibbonFamilyID) JOIN gibbonPerson AS parent ON (gibbonFamilyAdult.gibbonPersonID=parent.gibbonPersonID) WHERE gibbonFinanceInvoiceeID=:gibbonFinanceInvoiceeID AND (contactPriority=1 OR (contactPriority=2 AND contactEmail='Y')) ORDER BY contactPriority, surname, preferredName";
$resultParents = $connection2->prepare($sqlParents);
$resultParents->execute($dataParents);
} catch (PDOException $e) {
$emailFail = true;
}
if ($resultParents->rowCount() < 1) {
$emailFail = true;
} else {
while ($rowParents = $resultParents->fetch()) {
if ($rowParents['preferredName'] != '' and $rowParents['surname'] != '' and $rowParents['email'] != '') {
$emails[$emailsCount] = $rowParents['email'];
++$emailsCount;
}
}
}
}
} else {
$emailFail = true;
}
}
} else {
try {
$dataParents = array('gibbonFinanceInvoiceeID' => $row['gibbonFinanceInvoiceeID']);
$sqlParents = "SELECT parent.title, parent.surname, parent.preferredName, parent.email, parent.address1, parent.address1District, parent.address1Country, homeAddress, homeAddressDistrict, homeAddressCountry FROM gibbonFinanceInvoicee JOIN gibbonPerson AS student ON (gibbonFinanceInvoicee.gibbonPersonID=student.gibbonPersonID) JOIN gibbonFamilyChild ON (gibbonFamilyChild.gibbonPersonID=student.gibbonPersonID) JOIN gibbonFamily ON (gibbonFamilyChild.gibbonFamilyID=gibbonFamily.gibbonFamilyID) JOIN gibbonFamilyAdult ON (gibbonFamily.gibbonFamilyID=gibbonFamilyAdult.gibbonFamilyID) JOIN gibbonPerson AS parent ON (gibbonFamilyAdult.gibbonPersonID=parent.gibbonPersonID) WHERE gibbonFinanceInvoiceeID=:gibbonFinanceInvoiceeID AND (contactPriority=1 OR (contactPriority=2 AND contactEmail='Y')) ORDER BY contactPriority, surname, preferredName";
$resultParents = $connection2->prepare($sqlParents);
$resultParents->execute($dataParents);
} catch (PDOException $e) {
$emailFail = true;
}
if ($resultParents->rowCount() < 1) {
$emailFail = true;
} else {
while ($rowParents = $resultParents->fetch()) {
if ($rowParents['preferredName'] != '' and $rowParents['surname'] != '' and $rowParents['email'] != '') {
$emails[$emailsCount] = $rowParents['email'];
++$emailsCount;
}
}
}
}
if ($from == '' or count($emails) < 1) {
$emailFail = true;
} else {
//Prep message
$body = invoiceContents($guid, $connection2, $gibbonFinanceInvoiceID, $gibbonSchoolYearID, $_SESSION[$guid]['currency'], true)."<p style='font-style: italic;'>Email sent via ".$_SESSION[$guid]['systemName'].' at '.$_SESSION[$guid]['organisationName'].'.</p>';
$bodyPlain = 'This email is not viewable in plain text: enable rich text/HTML in your email client to view the invoice. Please reply to this email if you have any questions.';
$mail = getGibbonMailer($guid);
$mail->IsSMTP();
$mail->SetFrom($from, $_SESSION[$guid]['preferredName'].' '.$_SESSION[$guid]['surname']);
foreach ($emails as $address) {
$mail->AddBCC($address);
}
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->IsHTML(true);
$mail->Subject = 'Invoice From '.$_SESSION[$guid]['organisationNameShort'].' via '.$_SESSION[$guid]['systemName'];
$mail->Body = $body;
$mail->AltBody = $bodyPlain;
if (!$mail->Send()) {
$emailFail = true;
}
}
}
}
}
if ($partialFail == true) {
$URL .= '&return=warning1';
header("Location: {$URL}");
} elseif ($emailFail == true) {
$URL .= '&return=success1';
header("Location: {$URL}");
} else {
$URL .= '&return=success0';
header("Location: {$URL}");
}
}
//REMINDERS
elseif ($action == 'reminders') {
foreach ($gibbonFinanceInvoiceIDs as $gibbonFinanceInvoiceID) {
try {
$data = array('gibbonSchoolYearID' => $gibbonSchoolYearID, 'gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID);
$sql = "SELECT gibbonFinanceInvoice.*, gibbonFinanceBillingSchedule.invoiceDueDate AS invoiceDueDateScheduled FROM gibbonFinanceInvoice LEFT JOIN gibbonFinanceBillingSchedule ON (gibbonFinanceInvoice.gibbonFinanceBillingScheduleID=gibbonFinanceBillingSchedule.gibbonFinanceBillingScheduleID) WHERE gibbonFinanceInvoice.gibbonSchoolYearID=:gibbonSchoolYearID AND gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID AND status='Issued'";
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
}
if ($result->rowCount() != 1) {
$partialFail = true;
} else {
$row = $result->fetch();
//DEAL WITH EMAILS
$emailFail = false;
$emails = array();
$emailsCount = 0;
if ($row['invoiceTo'] == 'Company') {
try {
$dataCompany = array('gibbonFinanceInvoiceeID' => $row['gibbonFinanceInvoiceeID']);
$sqlCompany = 'SELECT * FROM gibbonFinanceInvoicee WHERE gibbonFinanceInvoiceeID=:gibbonFinanceInvoiceeID';
$resultCompany = $connection2->prepare($sqlCompany);
$resultCompany->execute($dataCompany);
} catch (PDOException $e) {
$emailFail = true;
}
if ($resultCompany->rowCount() != 1) {
$emailFail = true;
} else {
$rowCompany = $resultCompany->fetch();
if ($rowCompany['companyEmail'] != '' and $rowCompany['companyContact'] != '' and $rowCompany['companyName'] != '') {
$emails[$emailsCount] = $rowCompany['companyEmail'];
++$emailsCount;
if ($rowCompany['companyCCFamily'] == 'Y') {
try {
$dataParents = array('gibbonFinanceInvoiceeID' => $row['gibbonFinanceInvoiceeID']);
$sqlParents = "SELECT parent.title, parent.surname, parent.preferredName, parent.email, parent.address1, parent.address1District, parent.address1Country, homeAddress, homeAddressDistrict, homeAddressCountry FROM gibbonFinanceInvoicee JOIN gibbonPerson AS student ON (gibbonFinanceInvoicee.gibbonPersonID=student.gibbonPersonID) JOIN gibbonFamilyChild ON (gibbonFamilyChild.gibbonPersonID=student.gibbonPersonID) JOIN gibbonFamily ON (gibbonFamilyChild.gibbonFamilyID=gibbonFamily.gibbonFamilyID) JOIN gibbonFamilyAdult ON (gibbonFamily.gibbonFamilyID=gibbonFamilyAdult.gibbonFamilyID) JOIN gibbonPerson AS parent ON (gibbonFamilyAdult.gibbonPersonID=parent.gibbonPersonID) WHERE gibbonFinanceInvoiceeID=:gibbonFinanceInvoiceeID AND (contactPriority=1 OR (contactPriority=2 AND contactEmail='Y')) ORDER BY contactPriority, surname, preferredName";
$resultParents = $connection2->prepare($sqlParents);
$resultParents->execute($dataParents);
} catch (PDOException $e) {
$emailFail = true;
}
if ($resultParents->rowCount() < 1) {
$emailFail = true;
} else {
while ($rowParents = $resultParents->fetch()) {
if ($rowParents['preferredName'] != '' and $rowParents['surname'] != '' and $rowParents['email'] != '') {
$emails[$emailsCount] = $rowParents['email'];
++$emailsCount;
}
}
}
}
} else {
$emailFail = true;
}
}
} else {
try {
$dataParents = array('gibbonFinanceInvoiceeID' => $row['gibbonFinanceInvoiceeID']);
$sqlParents = "SELECT parent.title, parent.surname, parent.preferredName, parent.email, parent.address1, parent.address1District, parent.address1Country, homeAddress, homeAddressDistrict, homeAddressCountry FROM gibbonFinanceInvoicee JOIN gibbonPerson AS student ON (gibbonFinanceInvoicee.gibbonPersonID=student.gibbonPersonID) JOIN gibbonFamilyChild ON (gibbonFamilyChild.gibbonPersonID=student.gibbonPersonID) JOIN gibbonFamily ON (gibbonFamilyChild.gibbonFamilyID=gibbonFamily.gibbonFamilyID) JOIN gibbonFamilyAdult ON (gibbonFamily.gibbonFamilyID=gibbonFamilyAdult.gibbonFamilyID) JOIN gibbonPerson AS parent ON (gibbonFamilyAdult.gibbonPersonID=parent.gibbonPersonID) WHERE gibbonFinanceInvoiceeID=:gibbonFinanceInvoiceeID AND (contactPriority=1 OR (contactPriority=2 AND contactEmail='Y')) ORDER BY contactPriority, surname, preferredName";
$resultParents = $connection2->prepare($sqlParents);
$resultParents->execute($dataParents);
} catch (PDOException $e) {
$emailFail = true;
}
if ($resultParents->rowCount() < 1) {
$emailFail = true;
} else {
while ($rowParents = $resultParents->fetch()) {
if ($rowParents['preferredName'] != '' and $rowParents['surname'] != '' and $rowParents['email'] != '') {
$emails[$emailsCount] = $rowParents['email'];
++$emailsCount;
}
}
}
}
}
if ($from == '' or count($emails) < 1) {
$emailFail = true;
} else {
//Prep message
$body = '';
if ($row['reminderCount'] == '0') {
$reminderText = getSettingByScope($connection2, 'Finance', 'reminder1Text');
} elseif ($row['reminderCount'] == '1') {
$reminderText = getSettingByScope($connection2, 'Finance', 'reminder2Text');
} elseif ($row['reminderCount'] >= '2') {
$reminderText = getSettingByScope($connection2, 'Finance', 'reminder3Text');
}
if ($reminderText != '') {
$reminderOutput = $row['reminderCount'] + 1;
if ($reminderOutput > 3) {
$reminderOutput = '3+';
}
$body .= '<p>Reminder '.$reminderOutput.': '.$reminderText.'</p><br/>';
}
$body .= invoiceContents($guid, $connection2, $gibbonFinanceInvoiceID, $gibbonSchoolYearID, $_SESSION[$guid]['currency'], true)."<p style='font-style: italic;'>Email sent via ".$_SESSION[$guid]['systemName'].' at '.$_SESSION[$guid]['organisationName'].'.</p>';
$bodyPlain = 'This email is not viewable in plain text: enable rich text/HTML in your email client to view the reminder. Please reply to this email if you have any questions.';
//Update reminder count
if ($row['reminderCount'] < 3) {
try {
$data = array('gibbonFinanceInvoiceID' => $gibbonFinanceInvoiceID);
$sql = 'UPDATE gibbonFinanceInvoice SET reminderCount='.($row['reminderCount'] + 1).' WHERE gibbonFinanceInvoiceID=:gibbonFinanceInvoiceID';
$result = $connection2->prepare($sql);
$result->execute($data);
} catch (PDOException $e) {
}
}
$mail = getGibbonMailer($guid);
$mail->IsSMTP();
$mail->SetFrom($from, $_SESSION[$guid]['preferredName'].' '.$_SESSION[$guid]['surname']);
foreach ($emails as $address) {
$mail->AddBCC($address);
}
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->IsHTML(true);
$mail->Subject = 'Reminder From '.$_SESSION[$guid]['organisationNameShort'].' via '.$_SESSION[$guid]['systemName'];
$mail->Body = $body;
$mail->AltBody = $bodyPlain;
if (!$mail->Send()) {
$emailFail = true;
}
}
}
if ($partialFail == true) {
$URL .= '&return=warning1';
header("Location: {$URL}");
} elseif ($emailFail == true) {
$URL .= '&return=success1';
header("Location: {$URL}");
} else {
$URL .= '&return=success0';
header("Location: {$URL}");
}
}
//Export
elseif ($action == 'export') {
$_SESSION[$guid]['financeInvoiceExportIDs'] = $gibbonFinanceInvoiceIDs;
include ('./invoices_manage_processBulkExportContents.php');
} else {
$URL .= '&return=error1';
header("Location: {$URL}");
}
}
}
}
| gpl-3.0 |
gamegineer/dev | main/table/org.gamegineer.table.net.impl/src/org/gamegineer/table/internal/net/impl/node/client/handlers/HelloResponseMessageHandler.java | 4932 | /*
* HelloResponseMessageHandler.java
* Copyright 2008-2015 Gamegineer contributors and others.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Created on Apr 23, 2011 at 4:02:18 PM.
*/
package org.gamegineer.table.internal.net.impl.node.client.handlers;
import net.jcip.annotations.Immutable;
import org.gamegineer.table.internal.net.impl.Debug;
import org.gamegineer.table.internal.net.impl.node.client.IRemoteServerNodeController;
import org.gamegineer.table.internal.net.impl.node.common.ProtocolVersions;
import org.gamegineer.table.internal.net.impl.node.common.messages.ErrorMessage;
import org.gamegineer.table.internal.net.impl.node.common.messages.HelloResponseMessage;
import org.gamegineer.table.net.TableNetworkError;
/**
* A message handler for the {@link HelloResponseMessage} message.
*/
@Immutable
public final class HelloResponseMessageHandler
extends AbstractClientMessageHandler
{
// ======================================================================
// Fields
// ======================================================================
/** The singleton instance of this class. */
public static final HelloResponseMessageHandler INSTANCE = new HelloResponseMessageHandler();
// ======================================================================
// Constructors
// ======================================================================
/**
* Initializes a new instance of the {@code HelloResponseMessageHandler}
* class.
*/
private HelloResponseMessageHandler()
{
}
// ======================================================================
// Methods
// ======================================================================
/**
* Handles an {@code ErrorMessage} message.
*
* @param remoteNodeController
* The control interface for the remote node that received the
* message.
* @param message
* The message.
*/
@SuppressWarnings( {
"static-method", "unused"
} )
private void handleMessage(
final IRemoteServerNodeController remoteNodeController,
final ErrorMessage message )
{
Debug.getDefault().trace( Debug.OPTION_DEFAULT, //
String.format( "Received error '%s' in response to hello request (id=%d, correlation-id=%d)", //$NON-NLS-1$
message.getError(), //
Integer.valueOf( message.getId() ), //
Integer.valueOf( message.getCorrelationId() ) ) );
remoteNodeController.close( message.getError() );
}
/**
* Handles a {@code HelloResponseMessage} message.
*
* @param remoteNodeController
* The control interface for the remote node that received the
* message.
* @param message
* The message.
*/
@SuppressWarnings( {
"static-method", "unused"
} )
private void handleMessage(
final IRemoteServerNodeController remoteNodeController,
final HelloResponseMessage message )
{
Debug.getDefault().trace( Debug.OPTION_DEFAULT, //
String.format( "Received hello response with chosen version '%d' (id=%d, correlation-id=%d)", //$NON-NLS-1$
Integer.valueOf( message.getChosenProtocolVersion() ), //
Integer.valueOf( message.getId() ), //
Integer.valueOf( message.getCorrelationId() ) ) );
if( message.getChosenProtocolVersion() != ProtocolVersions.VERSION_1 )
{
Debug.getDefault().trace( Debug.OPTION_DEFAULT, "Received unsupported chosen protocol version" ); //$NON-NLS-1$
remoteNodeController.close( TableNetworkError.UNSUPPORTED_PROTOCOL_VERSION );
}
}
/*
* @see org.gamegineer.table.internal.net.impl.node.AbstractMessageHandler#handleUnexpectedMessage(org.gamegineer.table.internal.net.impl.node.IRemoteNodeController)
*/
@Override
protected void handleUnexpectedMessage(
final IRemoteServerNodeController remoteNodeController )
{
remoteNodeController.close( TableNetworkError.UNEXPECTED_MESSAGE );
}
}
| gpl-3.0 |
voran/tiny-rails-gallery | config/environments/development.rb | 1009 | Gallery::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.eager_load = false
end
| gpl-3.0 |
openurp/edu-eams-webapp | core/src/main/scala/org/openurp/edu/eams/teach/time/util/TermCalculator.scala | 4720 | package org.openurp.edu.eams.teach.time.util
import java.sql.Date
import java.util.regex.Pattern
import scala.annotation.migration
import org.beangle.commons.collection.Collections
import org.beangle.commons.lang.Numbers
import org.beangle.commons.lang.Strings
import org.beangle.commons.logging.Logging
import org.openurp.base.Semester
import org.openurp.edu.eams.core.service.SemesterService
object TermCalculator {
private var termMap = Collections.newMap[String, Set[Integer]]
val autumn = Set(1, 3, 5, 7, 9, 11)
val spring = Set(2, 3, 4, 8, 10, 12)
val all = Set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
termMap.put("春", spring.map { a => Integer.valueOf(a) })
termMap.put("秋", autumn.map { a => Integer.valueOf(a) })
termMap.put("春季", spring.map { a => Integer.valueOf(a) })
termMap.put("春秋", all.map { a => Integer.valueOf(a) })
termMap.put("春,秋", all.map { a => Integer.valueOf(a) })
def inTerm(termStr: String, term: java.lang.Integer): Boolean = {
if (Strings.contains(termStr, "*")) return true
var termSet = termMap.get(termStr).orNull
if (null == termSet) {
val terms = Strings.split(termStr, ",")
val newSet = Collections.newSet[Integer]
for (one <- terms) {
newSet += Numbers.convert2Int(one)
}
termMap.put(termStr, newSet.toSet)
}
termSet.contains(term)
}
def lessOrEqualTerm(termStr: String, term: java.lang.Integer): Boolean = {
if (Strings.contains(termStr, "*")) return true
var termSet = termMap.get(termStr).orNull
if (null == termSet) {
val terms = Strings.split(termStr, ",")
val newtermSet = Collections.newSet[Integer]
for (one <- terms) {
newtermSet += Numbers.convert2Int(one)
}
termMap.put(termStr, newtermSet.toSet)
}
termSet.exists { t => t.compareTo(term) <= 0 }
}
}
class TermCalculator(private var semesterService: SemesterService, private var semester: Semester) extends Logging {
private var termCalcCache = Collections.newMap[String, Integer]
def getTermBetween(pre: Semester, post: Semester, omitSmallTerm: Boolean): Int = {
semesterService.getTermsBetween(pre, post, omitSmallTerm)
}
def getTerm(begOn: java.util.Date, endOn: java.util.Date, omitSmallTerm: Boolean): Int = {
var term = termCalcCache.get(begOn.toString + "~" + endOn.toString).orNull
if (term != null) {
return term
}
val enrollSemester = semesterService.getSemester(semester.calendar, new Date(begOn.getTime), new Date(endOn.getTime))
debug(s"calculate a term for [$begOn~$endOn]")
if (null == enrollSemester) {
info(s"cannot find enrollterm for grade $begOn~$endOn")
term = new java.lang.Integer(-1)
} else {
term = new java.lang.Integer(semesterService.getTermsBetween(enrollSemester, semester, omitSmallTerm))
}
termCalcCache.put(begOn.toString + "~" + endOn.toString, term)
if (term == null) -1 else term
}
def getTerm(date: java.util.Date, omitSmallTerm: Boolean): Int = {
var term = termCalcCache.get(date.toString).orNull
// termCalcCache.clear()
if (term != null) {
return term
}
val enrollSemester = semesterService.getSemester(semester.calendar, new Date(date.getTime))
debug("calculate a term for [$date]")
if (null == enrollSemester) {
info("cannot find enrollterm for grade $date")
term = new java.lang.Integer(-1)
} else {
term = new java.lang.Integer(semesterService.getTermsBetween(enrollSemester, semester, omitSmallTerm))
}
termCalcCache.put(date.toString, term)
if (term == null) -1 else term
}
@Deprecated
def getTerm(grade: String, omitSmallTerm: Boolean): Int = {
var dateString = grade + "-29"
var term = termCalcCache.get(grade).asInstanceOf[java.lang.Integer]
if (term != null) {
return term
}
val datePattern = Pattern.compile("(\\d+)-(\\d+)-(\\d+)")
val matcher = datePattern.matcher(dateString)
matcher.matches()
val month = matcher.group(2)
if (1 == month.length) {
dateString = if (month == "2") matcher.group(1) + "-0" + month + '-' + "28" else matcher.group(1) + "-0" + month + '-' + matcher.group(3)
}
val date = Date.valueOf(dateString)
val enrollSemester = semesterService.getSemester(semester.calendar, date)
debug(s"calculate a term for [$grade]")
if (null == enrollSemester) {
info(s"cannot find enrollterm for grade grade")
term = new java.lang.Integer(-1)
} else {
term = new java.lang.Integer(semesterService.getTermsBetween(enrollSemester, semester, omitSmallTerm))
}
termCalcCache.put(grade, term)
if (term == null) -1 else term
}
}
| gpl-3.0 |
directactioneverywhere/server | drupal/sites/all/modules/civicrm/CRM/Case/BAO/Query.php | 33470 | <?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
*/
class CRM_Case_BAO_Query {
/**
* Get fields.
*
* @param bool $excludeActivityFields
*
* @return array
*/
public static function &getFields($excludeActivityFields = FALSE) {
$fields = CRM_Case_BAO_Case::exportableFields();
// add activity related fields
if (!$excludeActivityFields) {
$fields = array_merge($fields, CRM_Activity_BAO_Activity::exportableFields('Case'));
}
return $fields;
}
/**
* Build select for Case.
*
* @param CRM_Contact_BAO_Query $query
*/
public static function select(&$query) {
if (($query->_mode & CRM_Contact_BAO_Query::MODE_CASE) || !empty($query->_returnProperties['case_id'])) {
$query->_select['case_id'] = "civicrm_case.id as case_id";
$query->_element['case_id'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
}
if (!empty($query->_returnProperties['case_type_id'])) {
$query->_select['case_type_id'] = "civicrm_case_type.id as case_type_id";
$query->_element['case_type_id'] = 1;
$query->_tables['case_type'] = $query->_whereTables['case_type'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_type'])) {
$query->_select['case_type'] = "civicrm_case_type.title as case_type";
$query->_element['case_type'] = 1;
$query->_tables['case_type'] = $query->_whereTables['case_type'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_start_date'])) {
$query->_select['case_start_date'] = "civicrm_case.start_date as case_start_date";
$query->_element['case_start_date'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_end_date'])) {
$query->_select['case_end_date'] = "civicrm_case.end_date as case_end_date";
$query->_element['case_end_date'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_status_id'])) {
$query->_select['case_status_id'] = "case_status.id as case_status_id";
$query->_element['case_status_id'] = 1;
$query->_tables['case_status_id'] = $query->_whereTables['case_status_id'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_status'])) {
$query->_select['case_status'] = "case_status.label as case_status";
$query->_element['case_status'] = 1;
$query->_tables['case_status_id'] = $query->_whereTables['case_status_id'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_deleted'])) {
$query->_select['case_deleted'] = "civicrm_case.is_deleted as case_deleted";
$query->_element['case_deleted'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_role'])) {
$query->_select['case_role'] = "case_relation_type.label_b_a as case_role";
$query->_element['case_role'] = 1;
$query->_tables['case_relationship'] = $query->_whereTables['case_relationship'] = 1;
$query->_tables['case_relation_type'] = $query->_whereTables['case_relation_type'] = 1;
}
if (!empty($query->_returnProperties['case_recent_activity_date'])) {
$query->_select['case_recent_activity_date'] = "case_activity.activity_date_time as case_recent_activity_date";
$query->_element['case_recent_activity_date'] = 1;
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
}
if (!empty($query->_returnProperties['case_activity_subject'])) {
$query->_select['case_activity_subject'] = "case_activity.subject as case_activity_subject";
$query->_element['case_activity_subject'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_subject'])) {
$query->_select['case_subject'] = "civicrm_case.subject as case_subject";
$query->_element['case_subject'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_source_contact_id'])) {
$query->_select['case_source_contact_id'] = "civicrm_case_reporter.sort_name as case_source_contact_id";
$query->_element['case_source_contact_id'] = 1;
$query->_tables['civicrm_case_reporter'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_activity_status_id'])) {
$query->_select['case_activity_status_id'] = "rec_activity_status.id as case_activity_status_id";
$query->_element['case_activity_status_id'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['recent_activity_status'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_activity_status'])) {
$query->_select['case_activity_status'] = "rec_activity_status.label as case_activity_status";
$query->_element['case_activity_status'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['recent_activity_status'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_activity_duration'])) {
$query->_select['case_activity_duration'] = "case_activity.duration as case_activity_duration";
$query->_element['case_activity_duration'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_activity_medium_id'])) {
$query->_select['case_activity_medium_id'] = "recent_activity_medium.label as case_activity_medium_id";
$query->_element['case_activity_medium_id'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['case_activity_medium'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_activity_details'])) {
$query->_select['case_activity_details'] = "case_activity.details as case_activity_details";
$query->_element['case_activity_details'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_activity_is_auto'])) {
$query->_select['case_activity_is_auto'] = "case_activity.is_auto as case_activity_is_auto";
$query->_element['case_activity_is_auto'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_scheduled_activity_date'])) {
$query->_select['case_scheduled_activity_date'] = "case_activity.activity_date_time as case_scheduled_activity_date";
$query->_element['case_scheduled_activity_date'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
if (!empty($query->_returnProperties['case_recent_activity_type'])) {
$query->_select['case_recent_activity_type'] = "rec_activity_type.label as case_recent_activity_type";
$query->_element['case_recent_activity_type'] = 1;
$query->_tables['case_activity'] = 1;
$query->_tables['case_activity_type'] = 1;
$query->_tables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case'] = 1;
}
}
/**
* Given a list of conditions in query generate the required where clause.
*
* @param CRM_Contact_BAO_Query $query
*/
public static function where(&$query) {
foreach ($query->_params as $id => $values) {
if (!is_array($values) || count($values) != 5) {
continue;
}
if (substr($query->_params[$id][0], 0, 5) == 'case_') {
if ($query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
self::whereClauseSingle($query->_params[$id], $query);
}
}
// Add acl clause
// This is new and so far only for cases - it would be good to find a more abstract
// way to auto-apply this for all search components rather than copy-pasting this code to others
if (isset($query->_tables['civicrm_case'])) {
$aclClauses = array_filter(CRM_Case_BAO_Case::getSelectWhereClause());
foreach ($aclClauses as $clause) {
$query->_where[0][] = $clause;
}
}
}
/**
* Where clause for a single field.
*
* CRM-17120 adds a test that checks the Qill on some of these parameters.
* However, I couldn't find a way, other than via test, to access the
* case_activity options in the code below and invalid sql was returned.
* Perhaps the options are just legacy?
*
* Also, CRM-17120 locks in the Qill - but it probably is not quite right as I
* see 'Activity Type = Scheduled' (rather than activity status).
*
* See CRM_Case_BAO_QueryTest for more.
*
* @param array $values
* @param CRM_Contact_BAO_Query $query
*/
public static function whereClauseSingle(&$values, &$query) {
list($name, $op, $value, $grouping, $wildcard) = $values;
$val = $names = array();
switch ($name) {
case 'case_type_id':
case 'case_type':
case 'case_status':
case 'case_status_id':
case 'case_id':
if (strpos($name, 'type')) {
$name = 'case_type_id';
$label = 'Case Type(s)';
}
elseif (strpos($name, 'status')) {
$name = 'status_id';
$label = 'Case Status(s)';
}
else {
$name = 'id';
$label = 'Case ID';
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.{$name}", $op, $value, "Integer");
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Case_DAO_Case', $name, $value, $op);
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $label, 2 => $op, 3 => $value));
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
return;
case 'case_owner':
case 'case_mycases':
if (!empty($value)) {
if ($value == 2) {
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_relationship.contact_id_b", $op, $userID, 'Int');
$query->_qill[$grouping][] = ts('Case %1 My Cases', array(1 => $op));
$query->_tables['case_relationship'] = $query->_whereTables['case_relationship'] = 1;
}
elseif ($value == 1) {
$query->_qill[$grouping][] = ts('Case %1 All Cases', array(1 => $op));
$query->_where[$grouping][] = "civicrm_case_contact.contact_id = contact_a.id";
}
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
}
return;
case 'case_deleted':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.is_deleted", $op, $value, 'Boolean');
if ($value) {
$query->_qill[$grouping][] = ts("Find Deleted Cases");
}
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
return;
case 'case_activity_subject':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.subject", $op, $value, 'String');
$query->_qill[$grouping][] = ts("Activity Subject %1 '%2'", array(1 => $op, 2 => $value));
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_subject':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.subject", $op, $value, 'String');
$query->_qill[$grouping][] = ts("Case Subject %1 '%2'", array(1 => $op, 2 => $value));
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_source_contact_id':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case_reporter.sort_name", $op, $value, 'String');
$query->_qill[$grouping][] = ts("Activity Reporter %1 '%2'", array(1 => $op, 2 => $value));
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case_reporter'] = $query->_whereTables['civicrm_case_reporter'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_recent_activity_date':
$date = CRM_Utils_Date::format($value);
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_date_time", $op, $date, 'Date');
if ($date) {
$date = CRM_Utils_Date::customFormat($date);
$query->_qill[$grouping][] = ts("Activity Actual Date %1 %2", array(1 => $op, 2 => $date));
}
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_scheduled_activity_date':
$date = CRM_Utils_Date::format($value);
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_date_time", $op, $date, 'Date');
if ($date) {
$date = CRM_Utils_Date::customFormat($date);
$query->_qill[$grouping][] = ts("Activity Schedule Date %1 %2", array(1 => $op, 2 => $date));
}
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_recent_activity_type':
$names = $value;
if (($activityType = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $value)) != FALSE) {
$names = $activityType;
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_type_id", $op, $value, 'Int');
$query->_qill[$grouping][] = ts("Activity Type %1 %2", array(1 => $op, 2 => $names));
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['case_activity_type'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_activity_status_id':
$names = $value;
if (($activityStatus = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'status_id', $value)) != FALSE) {
$names = $activityStatus;
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.status_id", $op, $value, 'Int');
$query->_qill[$grouping][] = ts("Activity Type %1 %2", array(1 => $op, 2 => $names));
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['case_activity_status'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_activity_duration':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.duration", $op, $value, 'Int');
$query->_qill[$grouping][] = ts("Activity Duration %1 %2", array(1 => $op, 2 => $value));
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_activity_medium_id':
$names = $value;
if (($activityMedium = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'medium_id', $value)) != FALSE) {
$names = $activityMedium;
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.medium_id", $op, $value, 'Int');
$query->_qill[$grouping][] = ts("Activity Medium %1 %2", array(1 => $op, 2 => $names));
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['case_activity_medium'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_activity_details':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.details", $op, $value, 'String');
$query->_qill[$grouping][] = ts("Activity Details %1 '%2'", array(1 => $op, 2 => $value));
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_activity_is_auto':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.is_auto", $op, $value, 'Boolean');
$query->_qill[$grouping][] = ts("Activity Auto Genrated %1 '%2'", array(1 => $op, 2 => $value));
$query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
// adding where clause for case_role
case 'case_role':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_relation_type.name_b_a", $op, $value, 'String');
$query->_qill[$grouping][] = ts("Role in Case %1 '%2'", array(1 => $op, 2 => $value));
$query->_tables['case_relation_type'] = $query->_whereTables['case_relationship_type'] = 1;
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
return;
case 'case_from_start_date_low':
case 'case_from_start_date_high':
$query->dateQueryBuilder($values,
'civicrm_case', 'case_from_start_date', 'start_date', 'Start Date'
);
return;
case 'case_to_end_date_low':
case 'case_to_end_date_high':
$query->dateQueryBuilder($values,
'civicrm_case', 'case_to_end_date', 'end_date', 'End Date'
);
return;
case 'case_start_date':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.start_date", $op, $value, 'Int');
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
return;
case 'case_end_date':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.end_date", $op, $value, 'Int');
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
return;
case 'case_taglist':
$taglist = $value;
$value = array();
foreach ($taglist as $val) {
if ($val) {
$val = explode(',', $val);
foreach ($val as $tId) {
if (is_numeric($tId)) {
$value[$tId] = 1;
}
}
}
}
case 'case_tags':
$tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
if (is_array($value)) {
foreach ($value as $k => $v) {
if ($v) {
$val[$k] = $k;
$names[] = $tags[$k];
}
}
}
$query->_where[$grouping][] = " civicrm_case_tag.tag_id IN (" . implode(',', $val) . " )";
$query->_qill[$grouping][] = ts('Case Tags %1', array(1 => $op)) . ' ' . implode(' ' . ts('or') . ' ', $names);
$query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
$query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
$query->_tables['civicrm_case_tag'] = $query->_whereTables['civicrm_case_tag'] = 1;
return;
}
}
/**
* Build from clause.
*
* @param string $name
* @param string $mode
* @param string $side
*
* @return string
*/
public static function from($name, $mode, $side) {
$from = "";
switch ($name) {
case 'civicrm_case_contact':
$from .= " $side JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id ";
break;
case 'civicrm_case_reporter':
$activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$from .= " $side JOIN civicrm_activity_contact as case_activity_contact ON (case_activity.id = case_activity_contact.activity_id AND case_activity_contact.record_type_id = {$sourceID} ) ";
$from .= " $side JOIN civicrm_contact as civicrm_case_reporter ON case_activity_contact.contact_id = civicrm_case_reporter.id ";
break;
case 'civicrm_case':
$from .= " INNER JOIN civicrm_case ON civicrm_case_contact.case_id = civicrm_case.id";
break;
case 'case_status_id':
$from .= " $side JOIN civicrm_option_group option_group_case_status ON (option_group_case_status.name = 'case_status')";
$from .= " $side JOIN civicrm_option_value case_status ON (civicrm_case.status_id = case_status.value AND option_group_case_status.id = case_status.option_group_id ) ";
break;
case 'case_type':
$from .= " $side JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id ";
break;
case 'case_activity_type':
$from .= " $side JOIN civicrm_option_group option_group_activity_type ON (option_group_activity_type.name = 'activity_type')";
$from .= " $side JOIN civicrm_option_value rec_activity_type ON (case_activity.activity_type_id = rec_activity_type.value AND option_group_activity_type.id = rec_activity_type.option_group_id ) ";
break;
case 'recent_activity_status':
$from .= " $side JOIN civicrm_option_group option_group_activity_status ON (option_group_activity_status.name = 'activity_status')";
$from .= " $side JOIN civicrm_option_value rec_activity_status ON (case_activity.status_id = rec_activity_status.value AND option_group_activity_status.id = rec_activity_status.option_group_id ) ";
break;
case 'case_relationship':
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
$from .= " $side JOIN civicrm_relationship case_relationship ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID} AND case_relationship.case_id = civicrm_case.id )";
break;
case 'case_relation_type':
$from .= " $side JOIN civicrm_relationship_type case_relation_type ON ( case_relation_type.id = case_relationship.relationship_type_id AND
case_relation_type.id = case_relationship.relationship_type_id )";
break;
case 'case_activity_medium':
$from .= " $side JOIN civicrm_option_group option_group_activity_medium ON (option_group_activity_medium.name = 'encounter_medium')";
$from .= " $side JOIN civicrm_option_value recent_activity_medium ON (case_activity.medium_id = recent_activity_medium.value AND option_group_activity_medium.id = recent_activity_medium.option_group_id ) ";
break;
case 'case_activity':
$from .= " INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = civicrm_case.id ";
$from .= " INNER JOIN civicrm_activity case_activity ON ( civicrm_case_activity.activity_id = case_activity.id
AND case_activity.is_current_revision = 1 )";
break;
case 'civicrm_case_tag':
$from .= " $side JOIN civicrm_entity_tag as civicrm_case_tag ON ( civicrm_case_tag.entity_table = 'civicrm_case' AND civicrm_case_tag.entity_id = civicrm_case.id ) ";
break;
}
return $from;
}
/**
* Getter for the qill object.
*
* @return string
*/
public function qill() {
return (isset($this->_qill)) ? $this->_qill : "";
}
/**
* @param $mode
* @param bool $includeCustomFields
*
* @return array|null
*/
public static function defaultReturnProperties(
$mode,
$includeCustomFields = TRUE
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_CASE) {
$properties = array(
'contact_type' => 1,
'contact_sub_type' => 1,
'contact_id' => 1,
'sort_name' => 1,
'display_name' => 1,
'case_id' => 1,
'case_activity_subject' => 1,
'case_subject' => 1,
'case_status' => 1,
'case_type' => 1,
'case_role' => 1,
'case_deleted' => 1,
'case_recent_activity_date' => 1,
'case_recent_activity_type' => 1,
'case_scheduled_activity_date' => 1,
'phone' => 1,
// 'case_scheduled_activity_type'=> 1
);
if ($includeCustomFields) {
// also get all the custom case properties
$fields = CRM_Core_BAO_CustomField::getFieldsForImport('Case');
if (!empty($fields)) {
foreach ($fields as $name => $dontCare) {
$properties[$name] = 1;
}
}
}
}
return $properties;
}
/**
* This includes any extra fields that might need for export etc.
*
* @param string $mode
*
* @return array|null
*/
public static function extraReturnProperties($mode) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_CASE) {
$properties = array(
'case_start_date' => 1,
'case_end_date' => 1,
'case_subject' => 1,
'case_source_contact_id' => 1,
'case_activity_status' => 1,
'case_activity_duration' => 1,
'case_activity_medium_id' => 1,
'case_activity_details' => 1,
'case_activity_is_auto' => 1,
);
}
return $properties;
}
/**
* @param $tables
*/
public static function tableNames(&$tables) {
if (!empty($tables['civicrm_case'])) {
$tables = array_merge(array('civicrm_case_contact' => 1), $tables);
}
if (!empty($tables['case_relation_type'])) {
$tables = array_merge(array('case_relationship' => 1), $tables);
}
}
/**
* Add all the elements shared between case search and advanced search.
*
* @param CRM_Core_Form $form
*/
public static function buildSearchForm(&$form) {
$config = CRM_Core_Config::singleton();
//validate case configuration.
$configured = CRM_Case_BAO_Case::isCaseConfigured();
$form->assign('notConfigured', !$configured['configured']);
$form->addField('case_type_id', array('context' => 'search', 'entity' => 'Case'));
$form->addField('case_status_id', array('context' => 'search', 'entity' => 'Case'));
CRM_Core_Form_Date::buildDateRange($form, 'case_from', 1, '_start_date_low', '_start_date_high', ts('From'), FALSE);
CRM_Core_Form_Date::buildDateRange($form, 'case_to', 1, '_end_date_low', '_end_date_high', ts('From'), FALSE);
$form->addElement('hidden', 'case_from_start_date_range_error');
$form->addElement('hidden', 'case_to_end_date_range_error');
$form->addFormRule(array('CRM_Case_BAO_Query', 'formRule'), $form);
$form->assign('validCiviCase', TRUE);
//give options when all cases are accessible.
$accessAllCases = FALSE;
if (CRM_Core_Permission::check('access all cases and activities')) {
$accessAllCases = TRUE;
$caseOwner = array(1 => ts('Search All Cases'), 2 => ts('Only My Cases'));
$form->addRadio('case_owner', ts('Cases'), $caseOwner);
}
$form->assign('accessAllCases', $accessAllCases);
$caseTags = CRM_Core_BAO_Tag::getTags('civicrm_case');
if ($caseTags) {
foreach ($caseTags as $tagID => $tagName) {
$form->_tagElement = &$form->addElement('checkbox', "case_tags[$tagID]", NULL, $tagName);
}
}
$parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_case');
CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_case', NULL, TRUE, FALSE);
if (CRM_Core_Permission::check('administer CiviCase')) {
$form->addElement('checkbox', 'case_deleted', ts('Deleted Cases'));
}
// add all the custom searchable fields
$extends = array('Case');
$groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $extends);
if ($groupDetails) {
$form->assign('caseGroupTree', $groupDetails);
foreach ($groupDetails as $group) {
foreach ($group['fields'] as $field) {
$fieldId = $field['id'];
$elementName = 'custom_' . $fieldId;
CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE);
}
}
}
$form->setDefaults(array('case_owner' => 1));
}
/**
* @param $row
* @param int $id
*/
public static function searchAction(&$row, $id) {
}
/**
* Custom form rules.
*
* @param array $fields
* @param array $files
* @param CRM_Core_Form $form
*
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
$errors = array();
if ((empty($fields['case_from_start_date_low']) || empty($fields['case_from_start_date_high'])) && (empty($fields['case_to_end_date_low']) || empty($fields['case_to_end_date_high']))) {
return TRUE;
}
CRM_Utils_Rule::validDateRange($fields, 'case_from_start_date', $errors, ts('Case Start Date'));
CRM_Utils_Rule::validDateRange($fields, 'case_to_end_date', $errors, ts('Case End Date'));
return empty($errors) ? TRUE : $errors;
}
}
| gpl-3.0 |
stephanfo/OpenBuy | src/APIDigikeyBundle/Controller/GraphController.php | 2533 | <?php
namespace APIDigikeyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
class GraphController extends Controller
{
public function graphStatusAction()
{
return $this->render('APIDigikeyBundle:graph:status.html.twig');
}
/**
* @Route("/datagraph/status", name="api_digikey_datagraph_status")
* @Security("has_role('ROLE_STATS')")
*/
public function dataStatusAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$em->getFilters()->disable('userfilter');
$codes = $em->getRepository("APIDigikeyBundle:Transaction")->getLastCode();
return $this->json($codes);
}
public function graphRequestsAction()
{
return $this->render('APIDigikeyBundle:graph:requests.html.twig');
}
/**
* @Route("/datagraph/requests", name="api_digikey_datagraph_requests")
* @Security("has_role('ROLE_STATS')")
*/
public function dataRequetsAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$em->getFilters()->disable('userfilter');
$requests = $em->getRepository("APIDigikeyBundle:Transaction")->getRequests();
return $this->json($requests);
}
public function graphUsersAction()
{
return $this->render('APIDigikeyBundle:graph:users.html.twig');
}
/**
* @Route("/datagraph/users", name="api_digikey_datagraph_users")
* @Security("has_role('ROLE_STATS')")
*/
public function dataUsersAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$em->getFilters()->disable('userfilter');
$requests = $em->getRepository("APIDigikeyBundle:Transaction")->getUsersSuppliers();
return $this->json($requests);
}
public function graphTimingAction()
{
return $this->render('APIDigikeyBundle:graph:timing.html.twig');
}
/**
* @Route("/datagraph/timing", name="api_digikey_datagraph_timing")
* @Security("has_role('ROLE_STATS')")
*/
public function dataTimingAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$em->getFilters()->disable('userfilter');
$requests = $em->getRepository("APIDigikeyBundle:Transaction")->getTiming();
return $this->json($requests);
}
}
| gpl-3.0 |
Darkpeninsula/Darkcore-Rebase | src/server/scripts/EasternKingdoms/Deadmines/boss_glubtok.cpp | 1959 | /*
* Copyright (C) 2011-2012 DarkCore <http://www.darkpeninsula.eu/>
* Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptPCH.h"
#include "deadmines.h"
enum eSpels
{
SPELL_ARCANE_POWER = 88009,
SPELL_FIST_OF_FLAME = 87859,
SPELL_FIST_OF_FROST = 87861,
SPELL_FIRE_BLOSSOM = 88129,
SPELL_FIRE_BLOSSOM_H = 91286,
SPELL_FROST_BLOSSOM = 88169,
SPELL_FROST_BLOSSOM_H = 91287
};
class boss_glubtok : public CreatureScript
{
public:
boss_glubtok() : CreatureScript("boss_glubtok") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_glubtokAI (creature);
}
struct boss_glubtokAI : public ScriptedAI
{
boss_glubtokAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
uint32 TrashTimer;
uint32 SlamTimer;
uint32 NimbleReflexesTimer;
uint8 Health;
uint32 Phase;
uint32 Timer;
// TODO: MAKE THE CORRECT SCRIPT :)
};
};
void AddSC_boss_glubtok()
{
new boss_glubtok();
} | gpl-3.0 |
beia/beialand | projects/SAFECARE/XProtect/BeiaDeviceDriver_Movement/DriverFramework/BeiaDeviceDriverContainer.cs | 1410 | using VideoOS.Platform.DriverFramework;
namespace Safecare.BeiaDeviceDriver_Movement
{
/// <summary>
/// Container holding all the different managers.
/// TODO: If your hardware does not support some of the functionality, you can remove the class and the instantiation below.
/// </summary>
public class BeiaDeviceDriver_MovementContainer : Container
{
public new BeiaDeviceDriver_MovementConnectionManager ConnectionManager => base.ConnectionManager as BeiaDeviceDriver_MovementConnectionManager;
public new BeiaDeviceDriver_MovementStreamManager StreamManager => base.StreamManager as BeiaDeviceDriver_MovementStreamManager;
public BeiaDeviceDriver_MovementContainer(DriverDefinition definition)
: base(definition)
{
base.StreamManager = new BeiaDeviceDriver_MovementStreamManager(this);
base.PtzManager = new BeiaDeviceDriver_MovementPtzManager(this);
base.OutputManager = new BeiaDeviceDriver_MovementOutputManager(this);
base.SpeakerManager = new BeiaDeviceDriver_MovementSpeakerManager(this);
base.PlaybackManager = new BeiaDeviceDriver_MovementPlaybackManager(this);
base.ConnectionManager = new BeiaDeviceDriver_MovementConnectionManager(this);
base.ConfigurationManager = new BeiaDeviceDriver_MovementConfigurationManager(this);
}
}
}
| gpl-3.0 |
magarena/magarena | src/magic/ui/screen/about/LicenseButton.java | 1314 | package magic.ui.screen.about;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import magic.data.MagicIcon;
import magic.translate.MText;
import magic.ui.MagicImages;
import magic.ui.ScreenController;
import magic.ui.screen.widget.ActionBarButton;
@SuppressWarnings("serial")
class LicenseButton extends ActionBarButton {
private static final String _S9 = "Magarena License";
private static final String _S10 = "This program is free software : you can redistribute it and/or<br>modify it under the terms of the GNU General Public License<br>as published by the Free Software Foundation.";
private static final String _S11 = "Magarena License";
private static final String _S12 = "Displays the license details.";
LicenseButton() {
super(MagicImages.getIcon(MagicIcon.SCROLL),
MText.get(_S11),
MText.get(_S12),
new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
ScreenController.showInfoMessage(String.format("<html><b>%s</b><br>%s<html>",
MText.get(_S9),
MText.get(_S10))
);
}
}
);
}
}
| gpl-3.0 |
thehub/hubplus | apps/microblogging/urls.py | 903 |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'microblogging.views.personal', name='tweets_you_follow'),
url(r'^all/$', 'microblogging.views.public', name='all_tweets'),
url(r'^(\d+)/$', 'microblogging.views.single', name='single_tweet'),
url(r'^followers/(\w+)/$', 'microblogging.views.followers', name='tweet_followers'),
url(r'^following/(\w+)/$', 'microblogging.views.following', name='tweet_following'),
url(r'^toggle_follow/([\w\.-]+)/$', 'microblogging.views.toggle_follow', name='toggle_follow'),
url(r'^toggle_group/(?P<resource_id>[0-9]+)/$', 'microblogging.views.toggle_group', name='toggle_group'),
url(r'^ajax_form/(?P<target_type>[\w\.\_]+)/(?P<target_id>[\w\.\_]+)/$', 'microblogging.views.ajax_tweet_form', name='ajax_tweet_form'),
url(r'^post/$', 'microblogging.views.post', name='status_post'),
)
| gpl-3.0 |
iaa5765/Flutter | Clover/app/src/main/java/org/floens/flutter/ui/controller/ThreadSlideController.java | 9700 | /*
* Clover - 4chan browser https://github.com/Floens/Clover/
* Copyright (C) 2014 Floens
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.floens.flutter.ui.controller;
import android.content.Context;
import android.support.v4.widget.SlidingPaneLayout;
import android.view.View;
import android.view.ViewGroup;
import org.floens.flutter.R;
import org.floens.flutter.controller.Controller;
import org.floens.flutter.controller.ControllerTransition;
import org.floens.flutter.ui.layout.ThreadSlidingPaneLayout;
import org.floens.flutter.ui.toolbar.NavigationItem;
import org.floens.flutter.ui.toolbar.Toolbar;
import org.floens.flutter.utils.Logger;
import java.lang.reflect.Field;
import static org.floens.flutter.utils.AndroidUtils.dp;
import static org.floens.flutter.utils.AndroidUtils.getAttrColor;
public class ThreadSlideController extends Controller implements DoubleNavigationController, SlidingPaneLayout.PanelSlideListener, ToolbarNavigationController.ToolbarSearchCallback {
private static final String TAG = "ThreadSlideController";
public Controller leftController;
public Controller rightController;
private boolean leftOpen = true;
private ViewGroup emptyView;
private ThreadSlidingPaneLayout slidingPaneLayout;
public ThreadSlideController(Context context) {
super(context);
}
@Override
public void onCreate() {
super.onCreate();
doubleNavigationController = this;
navigationItem.swipeable = false;
navigationItem.handlesToolbarInset = true;
navigationItem.hasDrawer = true;
view = inflateRes(R.layout.controller_thread_slide);
slidingPaneLayout = (ThreadSlidingPaneLayout) view.findViewById(R.id.sliding_pane_layout);
slidingPaneLayout.setThreadSlideController(this);
slidingPaneLayout.setPanelSlideListener(this);
slidingPaneLayout.setParallaxDistance(dp(100));
slidingPaneLayout.setShadowResourceLeft(R.drawable.panel_shadow);
int fadeColor = (getAttrColor(context, R.attr.backcolor) & 0xffffff) + 0xCC000000;
slidingPaneLayout.setSliderFadeColor(fadeColor);
slidingPaneLayout.openPane();
setLeftController(null);
setRightController(null);
}
public void onSlidingPaneLayoutStateRestored() {
// SlidingPaneLayout does some annoying things for state restoring and incorrectly
// tells us if the restored state was open or closed
// We need to use reflection to get the private field that stores this correct state
boolean restoredOpen = false;
try {
Field field = SlidingPaneLayout.class.getDeclaredField("mPreservedOpenState");
field.setAccessible(true);
restoredOpen = field.getBoolean(slidingPaneLayout);
} catch (Exception e) {
Logger.e(TAG, "Error getting restored open state with reflection", e);
}
if (restoredOpen != leftOpen) {
leftOpen = restoredOpen;
slideStateChanged(leftOpen);
}
}
@Override
public void onPanelSlide(View panel, float slideOffset) {
}
@Override
public void onPanelOpened(View panel) {
if (this.leftOpen != leftOpen()) {
this.leftOpen = leftOpen();
slideStateChanged(leftOpen());
}
}
@Override
public void onPanelClosed(View panel) {
if (this.leftOpen != leftOpen()) {
this.leftOpen = leftOpen();
slideStateChanged(leftOpen());
}
}
@Override
public void switchToController(boolean leftController) {
if (leftController != leftOpen()) {
if (leftController) {
slidingPaneLayout.openPane();
} else {
slidingPaneLayout.closePane();
}
Toolbar toolbar = ((ToolbarNavigationController) navigationController).toolbar;
toolbar.processScrollCollapse(Toolbar.TOOLBAR_COLLAPSE_SHOW, true);
}
}
@Override
public void setEmptyView(ViewGroup emptyView) {
this.emptyView = emptyView;
}
public void setLeftController(Controller leftController) {
if (this.leftController != null) {
this.leftController.onHide();
removeChildController(this.leftController);
}
this.leftController = leftController;
if (leftController != null) {
addChildController(leftController);
leftController.attachToParentView(slidingPaneLayout.leftPane);
leftController.onShow();
if (leftOpen()) {
setParentNavigationItem(true);
}
}
}
public void setRightController(Controller rightController) {
if (this.rightController != null) {
this.rightController.onHide();
removeChildController(this.rightController);
} else {
this.slidingPaneLayout.rightPane.removeAllViews();
}
this.rightController = rightController;
if (rightController != null) {
addChildController(rightController);
rightController.attachToParentView(slidingPaneLayout.rightPane);
rightController.onShow();
if (!leftOpen()) {
setParentNavigationItem(false);
}
} else {
slidingPaneLayout.rightPane.addView(emptyView);
}
}
@Override
public Controller getLeftController() {
return leftController;
}
@Override
public Controller getRightController() {
return rightController;
}
@Override
public boolean pushController(Controller to) {
return navigationController.pushController(to);
}
@Override
public boolean pushController(Controller to, boolean animated) {
return navigationController.pushController(to, animated);
}
@Override
public boolean pushController(Controller to, ControllerTransition controllerTransition) {
return navigationController.pushController(to, controllerTransition);
}
@Override
public boolean popController() {
return navigationController.popController();
}
@Override
public boolean popController(boolean animated) {
return navigationController.popController(animated);
}
@Override
public boolean popController(ControllerTransition controllerTransition) {
return navigationController.popController(controllerTransition);
}
@Override
public boolean onBack() {
if (!leftOpen()) {
if (rightController != null && rightController.onBack()) {
return true;
} else {
switchToController(true);
return true;
}
} else {
if (leftController != null && leftController.onBack()) {
return true;
}
}
return super.onBack();
}
@Override
public void onSearchVisibilityChanged(boolean visible) {
if (leftOpen() && leftController != null && leftController instanceof ToolbarNavigationController.ToolbarSearchCallback) {
((ToolbarNavigationController.ToolbarSearchCallback) leftController).onSearchVisibilityChanged(visible);
}
if (!leftOpen() && rightController != null && rightController instanceof ToolbarNavigationController.ToolbarSearchCallback) {
((ToolbarNavigationController.ToolbarSearchCallback) rightController).onSearchVisibilityChanged(visible);
}
}
@Override
public void onSearchEntered(String entered) {
if (leftOpen() && leftController != null && leftController instanceof ToolbarNavigationController.ToolbarSearchCallback) {
((ToolbarNavigationController.ToolbarSearchCallback) leftController).onSearchEntered(entered);
}
if (!leftOpen() && rightController != null && rightController instanceof ToolbarNavigationController.ToolbarSearchCallback) {
((ToolbarNavigationController.ToolbarSearchCallback) rightController).onSearchEntered(entered);
}
}
private boolean leftOpen() {
return slidingPaneLayout.isOpen();
}
private void slideStateChanged(boolean leftOpen) {
setParentNavigationItem(leftOpen);
}
private void setParentNavigationItem(boolean left) {
Toolbar toolbar = ((ToolbarNavigationController) navigationController).toolbar;
NavigationItem item = null;
if (left) {
if (leftController != null) {
item = leftController.navigationItem;
}
} else {
if (rightController != null) {
item = rightController.navigationItem;
}
}
if (item != null) {
navigationItem = item;
navigationItem.swipeable = false;
navigationItem.handlesToolbarInset = true;
navigationItem.hasDrawer = true;
toolbar.setNavigationItem(false, true, navigationItem);
}
}
}
| gpl-3.0 |
vvolkl/DD4hep | DDCore/src/SurfaceInstaller.cpp | 4950 | // $Id: $
//==========================================================================
// AIDA Detector description implementation for LCD
//--------------------------------------------------------------------------
// Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
// All rights reserved.
//
// For the licensing terms see $DD4hepINSTALL/LICENSE.
// For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
//
// Author : M.Frank
//
//==========================================================================
// Framework include files
#include "DD4hep/Shapes.h"
#include "DD4hep/Printout.h"
#include "DD4hep/SurfaceInstaller.h"
// C/C++ include files
#include <stdexcept>
// ROOT includes
#include "TClass.h"
using namespace std;
using namespace DD4hep;
using namespace DD4hep::Geometry;
typedef DetElement::Children _C;
/// Initializing constructor
SurfaceInstaller::SurfaceInstaller(LCDD& lcdd, int argc, char** argv)
: m_lcdd(lcdd), m_det(), m_stopScanning(false)
{
if ( argc > 0 ) {
string det_name = argv[0];
string n = det_name[0] == '-' ? det_name.substr(1) : det_name;
m_det = lcdd.detector(n);
if ( !m_det.isValid() ) {
stringstream err;
err << "The subdetector " << det_name << " is not known to the geometry.";
printout(INFO,"SurfaceInstaller",err.str().c_str());
throw runtime_error(err.str());
}
printout(INFO,m_det.name(),"+++ Processing SurfaceInstaller for subdetector: '%s'",m_det.name());
return;
}
throw runtime_error("The plugin takes at least one argument. No argument supplied");
}
/// Indicate error message and throw exception
void SurfaceInstaller::invalidInstaller(const std::string& msg) const {
const char* det = m_det.isValid() ? m_det.name() : "<UNKNOWN>";
const char* typ = m_det.isValid() ? m_det.type().c_str() : "<UNKNOWN>";
printout(FATAL,"SurfaceInstaller","+++ Surfaces for: %s",det);
printout(FATAL,"SurfaceInstaller","+++ %s.",msg.c_str());
printout(FATAL,"SurfaceInstaller","+++ You sure you apply the correct plugin to generate");
printout(FATAL,"SurfaceInstaller","+++ surfaces for a detector of type %s",typ);
throw std::runtime_error("+++ Failed to install Surfaces to detector "+string(det));
}
/// Shortcut to access the parent detectorelement's volume
Volume SurfaceInstaller::parentVolume(DetElement component) const {
DetElement module = component.parent();
if ( module.isValid() ) {
return module.placement().volume();
}
return Volume();
}
/// Shortcut to access the translation vector of a given component
const double* SurfaceInstaller::placementTranslation(DetElement component) const {
TGeoMatrix* mat = component.placement()->GetMatrix();
const double* trans = mat->GetTranslation();
return trans;
}
/// Printout volume information
void SurfaceInstaller::install(DetElement component, PlacedVolume pv) {
if ( pv.volume().isSensitive() ) {
stringstream log;
PlacementPath all_nodes;
ElementPath det_elts;
DetectorTools::elementPath(component,det_elts);
DetectorTools::placementPath(component,all_nodes);
string elt_path = DetectorTools::elementPath(det_elts);
string node_path = DetectorTools::placementPath(all_nodes);
log << "Lookup " << " Detector[" << det_elts.size() << "]: " << elt_path;
printout(INFO,m_det.name(),log.str());
log.str("");
log << " " << " Places[" << all_nodes.size() << "]: " << node_path;
printout(INFO,m_det.name(),log.str());
log.str("");
log << " " << " Matrices[" << all_nodes.size() << "]: ";
for(PlacementPath::const_reverse_iterator i=all_nodes.rbegin(); i!=all_nodes.rend(); ++i) {
PlacedVolume placed = *i;
log << (void*)(placed->GetMatrix()) << " ";
if ( placed->GetUserExtension() ) {
const PlacedVolume::VolIDs& vid = placed.volIDs();
for(PlacedVolume::VolIDs::const_iterator j=vid.begin(); j!=vid.end(); ++j) {
log << (*j).first << ":" << (*j).second << " ";
}
}
log << " ";
if ( i+1 == all_nodes.rend() ) log << "( -> " << placed->GetName() << ")";
}
// Get the module element:
printout(INFO,m_det.name(),log.str());
log.str("");
Volume vol = pv.volume();
log << " "
<< " Sensitive: " << (vol.isSensitive() ? "YES" : "NO ")
<< " Volume: " << (void*)vol.ptr() << " "
<< " Shape: " << vol.solid().toString();
printout(INFO,m_det.name(),log.str());
return;
}
cout << component.name() << ": " << pv.name() << endl;
}
/// Scan through tree of volume placements
void SurfaceInstaller::scan(DetElement e) {
const _C& children = e.children();
install(e,e.placement());
for (_C::const_iterator i=children.begin(); !m_stopScanning && i!=children.end(); ++i)
scan((*i).second);
}
/// Scan through tree of volume placements
void SurfaceInstaller::scan() {
scan(m_det);
}
| gpl-3.0 |
cronkite-asu/poliverse | features/support/env.rb | 2963 | # IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# instead of editing this one. Cucumber will automatically load all features/**/*.rb
# files.
ENV["RAILS_ENV"] ||= "test"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'cucumber/rails/rspec'
require 'cucumber/rails/world'
require 'cucumber/rails/active_record'
require 'cucumber/web/tableish'
require 'capybara/rails'
require 'capybara/cucumber'
require 'capybara/session'
require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links with onclick javascript handlers without using @culerity or @javascript
# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
# order to ease the transition to Capybara we set the default here. If you'd
# prefer to use XPath just remove this line and adjust any selectors in your
# steps to use the XPath syntax.
Capybara.default_selector = :css
# If you set this to false, any error raised from within your app will bubble
# up to your step definition and out to cucumber unless you catch it somewhere
# on the way. You can make Rails rescue errors and render error pages on a
# per-scenario basis by tagging a scenario or feature with the @allow-rescue tag.
#
# If you set this to true, Rails will rescue all errors and render error
# pages, more or less in the same way your application would behave in the
# default production environment. It's not recommended to do this for all
# of your scenarios, as this makes it hard to discover errors in your application.
ActionController::Base.allow_rescue = false
# If you set this to true, each scenario will run in a database transaction.
# You can still turn off transactions on a per-scenario basis, simply tagging
# a feature or scenario with the @no-txn tag. If you are using Capybara,
# tagging with @culerity or @javascript will also turn transactions off.
#
# If you set this to false, transactions will be off for all scenarios,
# regardless of whether you use @no-txn or not.
#
# Beware that turning transactions off will leave data in your database
# after each scenario, which can lead to hard-to-debug failures in
# subsequent scenarios. If you do this, we recommend you create a Before
# block that will explicitly put your database in a known state.
Cucumber::Rails::World.use_transactional_fixtures = true
# How to clean your database when transactions are turned off. See
# http://github.com/bmabey/database_cleaner for more info.
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
# Factory Girl
require 'factory_girl'
Dir.glob(File.join(File.dirname(__FILE__), '../../test/factories/*.rb')).each {|f| require f } | gpl-3.0 |
nickthecoder/webwidgets | webwidgets-core/src/main/java/uk/co/nickthecoder/webwidgets/tags/BoxTitleTag.java | 3704 | /*
* Copyright (c) Nick Robinson 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
*/
package uk.co.nickthecoder.webwidgets.tags;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import uk.co.nickthecoder.webwidgets.util.TagUtil;
import uk.co.nickthecoder.webwidgets.tags.StandardButtonTag;
public class BoxTitleTag extends BodyTagSupport
{
/**
*
*/
private static final long serialVersionUID = -5998999585644062475L;
private String _title;
private boolean _clickable;
private boolean _minMax;
private boolean _close;
public BoxTitleTag()
{
super();
initialise();
}
public void release()
{
super.release();
initialise();
}
private void initialise()
{
_title = "";
_clickable = false;
_minMax = false;
_close = false;
}
public String getTitle()
{
return _title;
}
public void setTitle( String title )
{
_title = title;
}
public boolean getClickable()
{
return _clickable;
}
public void setClickable( boolean value )
{
_clickable = value;
}
public boolean getMinMax()
{
return _minMax;
}
public void setMinMax( boolean value )
{
_minMax = value;
}
public boolean getClose()
{
return _close;
}
public void setClose( boolean value )
{
_close = value;
}
public int doStartTag() throws JspException
{
try {
JspWriter out = pageContext.getOut();
String onclick = getClickable() ? " onclick=\"ww_doToggleMinimize( event )\"" : "";
String cssClass = getClickable() ? "ww_boxTitle ww_clickable" : "ww_boxTitle";
out.println("<div class=\"" + cssClass + "\"" + onclick + ">");
out.print(TagUtil.safeText(getTitle()));
if (_close) {
out.print("<div class=\"ww_boxIcon\">");
out.println(StandardButtonTag.makeButton(pageContext, StandardButtonTag.CLOSE_BUTTON));
out.println( "</div>" );
}
if (_minMax) {
out.print("<div class=\"ww_boxIcon\">");
out.println(StandardButtonTag.makeButton(pageContext, StandardButtonTag.MINIMIZE_BUTTON));
out.println( "</div>" );
out.print("<div class=\"ww_boxIcon\">");
out.println(StandardButtonTag.makeButton(pageContext, StandardButtonTag.MAXIMIZE_BUTTON));
out.println( "</div>" );
}
return EVAL_BODY_INCLUDE;
} catch (IOException e) {
// @MORE@
e.printStackTrace();
throw new JspException("Unexpected IO Exception.");
}
}
public int doEndTag() throws JspException
{
try {
JspWriter out = pageContext.getOut();
out.println("</div>");
// This is closed in BoxTag (or InnerBoxTag) doEndTag
// That menas that all BoxTags MUST have one and only one BoxTitle Tag.
// That is VERY bad design :-(
out.println("<div class=\"ww_minimizable\">");
return EVAL_PAGE;
} catch (IOException e) {
// @MORE@
e.printStackTrace();
throw new JspException("Unexpected IO Exception.");
}
}
}
| gpl-3.0 |
kevoree-modeling/framework | microframework/src/main/java/org/kevoree/modeling/memory/manager/DataManagerBuilder.java | 3470 | package org.kevoree.modeling.memory.manager;
import org.kevoree.modeling.cdn.KContentDeliveryDriver;
import org.kevoree.modeling.cdn.impl.MemoryContentDeliveryDriver;
import org.kevoree.modeling.memory.space.KChunkSpace;
import org.kevoree.modeling.memory.space.KChunkSpaceManager;
import org.kevoree.modeling.memory.space.impl.PhantomQueueChunkSpaceManager;
import org.kevoree.modeling.memory.space.impl.press.PressHeapChunkSpace;
import org.kevoree.modeling.memory.manager.impl.DataManager;
import org.kevoree.modeling.memory.manager.internal.KInternalDataManager;
import org.kevoree.modeling.scheduler.KScheduler;
import org.kevoree.modeling.scheduler.impl.AsyncScheduler;
import org.kevoree.modeling.util.maths.structure.blas.KBlas;
import org.kevoree.modeling.util.maths.structure.blas.impl.JavaBlas;
public class DataManagerBuilder {
private KContentDeliveryDriver _driver;
private KScheduler _scheduler;
private KBlas _blas;
private KChunkSpace _space;
private KChunkSpaceManager _spaceManager;
public KContentDeliveryDriver driver() {
if (this._driver == null) {
this._driver = new MemoryContentDeliveryDriver();
}
return _driver;
}
public KBlas blas() {
if (this._blas == null) {
this._blas = new JavaBlas();
}
return _blas;
}
/**
* @native ts
* if (this._scheduler == null) { this._scheduler = new org.kevoree.modeling.scheduler.impl.DirectScheduler(); }
* return this._scheduler;
*/
public KScheduler scheduler() {
if (this._scheduler == null) {
this._scheduler = new AsyncScheduler();
}
return _scheduler;
}
/**
* @native ts
* if (this._space == null) { this._space = new org.kevoree.modeling.memory.space.impl.HeapChunkSpace(); }
* return this._space;
*/
public KChunkSpace space() {
if (this._space == null) {
this._space = new PressHeapChunkSpace(100000, 10);
}
return _space;
}
/**
* @native ts
* if (this._spaceManager == null) { this._spaceManager = new org.kevoree.modeling.memory.space.impl.ManualChunkSpaceManager(); }
* return this._spaceManager;
*/
public KChunkSpaceManager spaceManager() {
if (this._spaceManager == null) {
this._spaceManager = new PhantomQueueChunkSpaceManager();
}
return _spaceManager;
}
public static DataManagerBuilder create() {
return new DataManagerBuilder();
}
public DataManagerBuilder withContentDeliveryDriver(KContentDeliveryDriver p_driver) {
this._driver = p_driver;
return this;
}
public DataManagerBuilder withScheduler(KScheduler p_scheduler) {
this._scheduler = p_scheduler;
return this;
}
public DataManagerBuilder withSpace(KChunkSpace p_space) {
this._space = p_space;
return this;
}
public DataManagerBuilder withSpaceManager(KChunkSpaceManager p_spaceManager) {
this._spaceManager = p_spaceManager;
return this;
}
public DataManagerBuilder withBlas(KBlas p_blas) {
this._blas = p_blas;
return this;
}
public KInternalDataManager build() {
return new DataManager(driver(), scheduler(), space(), spaceManager(), blas());
}
public static KInternalDataManager buildDefault() {
return create().build();
}
}
| gpl-3.0 |
aelfimow/cppasm | src/st.cpp | 965 | /*! \file st.cpp
\brief Class representing FPU's ST register.
*/
#include <string>
#include <map>
#include <stdexcept>
#include "reg.h"
#include "st.h"
static st ST0 { "%st(0)" };
static st ST1 { "%st(1)" };
static st ST2 { "%st(2)" };
static st ST3 { "%st(3)" };
static st ST4 { "%st(4)" };
static st ST5 { "%st(5)" };
static st ST6 { "%st(6)" };
static st ST7 { "%st(7)" };
st::st() :
m_name { "%st(0)" }
{
}
st::st(std::string const &name) :
m_name { name }
{
}
st::~st()
{
}
st &st::operator()(size_t i)
{
static std::map<size_t, st&> const st_regs
{
{ 0, ST0 },
{ 1, ST1 },
{ 2, ST2 },
{ 3, ST3 },
{ 4, ST4 },
{ 5, ST5 },
{ 6, ST6 },
{ 7, ST7 }
};
auto it = st_regs.find(i);
if (it == st_regs.end())
{
throw std::invalid_argument("Invalid ST register index");
}
return it->second;
}
std::string st::name() const
{
return m_name;
}
| gpl-3.0 |
Xane123/MaryMagicalAdventure | src/maploader/slopes.cpp | 15807 | /*
** p_slopes.cpp
** Slope creation
**
**---------------------------------------------------------------------------
** Copyright 1998-2008 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include "doomtype.h"
#include "p_local.h"
#include "cmdlib.h"
#include "p_lnspec.h"
#include "p_maputl.h"
#include "p_spec.h"
#include "g_levellocals.h"
#include "actor.h"
#include "p_setup.h"
#include "maploader.h"
//===========================================================================
//
// P_SpawnSlopeMakers
//
//===========================================================================
void MapLoader::SlopeLineToPoint (int lineid, const DVector3 &pos, bool slopeCeil)
{
int linenum;
auto itr = Level->GetLineIdIterator(lineid);
while ((linenum = itr.Next()) >= 0)
{
const line_t *line = &Level->lines[linenum];
sector_t *sec;
secplane_t *plane;
if (P_PointOnLineSidePrecise (pos, line) == 0)
{
sec = line->frontsector;
}
else
{
sec = line->backsector;
}
if (sec == NULL)
{
continue;
}
if (slopeCeil)
{
plane = &sec->ceilingplane;
}
else
{
plane = &sec->floorplane;
}
DVector3 p, v1, v2, cross;
p[0] = line->v1->fX();
p[1] = line->v1->fY();
p[2] = plane->ZatPoint (line->v1);
v1[0] = line->Delta().X;
v1[1] = line->Delta().Y;
v1[2] = plane->ZatPoint (line->v2) - p[2];
v2[0] = pos.X - p[0];
v2[1] = pos.Y - p[1];
v2[2] = pos.Z - p[2];
cross = v1 ^ v2;
double len = cross.Length();
if (len == 0)
{
Printf ("Slope thing at (%f,%f) lies directly on its target line.\n", pos.X, pos.Y);
return;
}
cross /= len;
// Fix backward normals
if ((cross.Z < 0 && !slopeCeil) || (cross.Z > 0 && slopeCeil))
{
cross = -cross;
}
double dist = -cross[0] * pos.X - cross[1] * pos.Y - cross[2] * pos.Z;
plane->set(cross[0], cross[1], cross[2], dist);
}
}
//===========================================================================
//
// P_CopyPlane
//
//===========================================================================
void MapLoader::CopyPlane (int tag, sector_t *dest, bool copyCeil)
{
sector_t *source;
int secnum;
secnum = Level->FindFirstSectorFromTag (tag);
if (secnum == -1)
{
return;
}
source = &Level->sectors[secnum];
if (copyCeil)
{
dest->ceilingplane = source->ceilingplane;
}
else
{
dest->floorplane = source->floorplane;
}
}
void MapLoader::CopyPlane (int tag, const DVector2 &pos, bool copyCeil)
{
sector_t *dest = Level->PointInSector (pos);
CopyPlane(tag, dest, copyCeil);
}
//===========================================================================
//
// P_SetSlope
//
//===========================================================================
void MapLoader::SetSlope (secplane_t *plane, bool setCeil, int xyangi, int zangi, const DVector3 &pos)
{
DAngle xyang;
DAngle zang;
if (zangi >= 180)
{
zang = 179.;
}
else if (zangi <= 0)
{
zang = 1.;
}
else
{
zang = (double)zangi;
}
if (setCeil)
{
zang += 180.;
}
xyang = (double)xyangi;
DVector3 norm;
if (Level->ib_compatflags & BCOMPATF_SETSLOPEOVERFLOW)
{
// We have to consider an integer multiplication overflow here.
norm[0] = FixedToFloat(FloatToFixed(zang.Cos()) * FloatToFixed(xyang.Cos())) / 65536.;
norm[1] = FixedToFloat(FloatToFixed(zang.Cos()) * FloatToFixed(xyang.Sin())) / 65536.;
}
else
{
norm[0] = zang.Cos() * xyang.Cos();
norm[1] = zang.Cos() * xyang.Sin();
}
norm[2] = zang.Sin();
norm.MakeUnit();
double dist = -norm[0] * pos.X - norm[1] * pos.Y - norm[2] * pos.Z;
plane->set(norm[0], norm[1], norm[2], dist);
}
//===========================================================================
//
// P_VavoomSlope
//
//===========================================================================
void MapLoader::VavoomSlope(sector_t * sec, int id, const DVector3 &pos, int which)
{
for(auto l : sec->Lines)
{
if (l->args[0]==id)
{
DVector3 v1, v2, cross;
secplane_t *srcplane = (which == 0) ? &sec->floorplane : &sec->ceilingplane;
double srcheight = (which == 0) ? sec->GetPlaneTexZ(sector_t::floor) : sec->GetPlaneTexZ(sector_t::ceiling);
v1[0] = pos.X - l->v2->fX();
v1[1] = pos.Y - l->v2->fY();
v1[2] = pos.Z - srcheight;
v2[0] = pos.X - l->v1->fX();
v2[1] = pos.Y - l->v1->fY();
v2[2] = pos.Z - srcheight;
cross = v1 ^ v2;
double len = cross.Length();
if (len == 0)
{
Printf ("Slope thing at (%f,%f) lies directly on its target line.\n", pos.X, pos.Y);
return;
}
cross /= len;
// Fix backward normals
if ((cross.Z < 0 && which == 0) || (cross.Z > 0 && which == 1))
{
cross = -cross;
}
double dist = -cross[0] * pos.X - cross[1] * pos.Y - cross[2] * pos.Z;
srcplane->set(cross[0], cross[1], cross[2], dist);
return;
}
}
}
//==========================================================================
//
// P_SetSlopesFromVertexHeights
//
//==========================================================================
void MapLoader::SetSlopesFromVertexHeights(FMapThing *firstmt, FMapThing *lastmt, const int *oldvertextable)
{
TMap<int, double> vt_heights[2];
FMapThing *mt;
bool vt_found = false;
for (mt = firstmt; mt < lastmt; ++mt)
{
if (mt->info != NULL && mt->info->Type == NULL)
{
if (mt->info->Special == SMT_VertexFloorZ || mt->info->Special == SMT_VertexCeilingZ)
{
for (unsigned i = 0; i < Level->vertexes.Size(); i++)
{
if (Level->vertexes[i].fX() == mt->pos.X && Level->vertexes[i].fY() == mt->pos.Y)
{
if (mt->info->Special == SMT_VertexFloorZ)
{
vt_heights[0][i] = mt->pos.Z;
}
else
{
vt_heights[1][i] = mt->pos.Z;
}
vt_found = true;
}
}
mt->EdNum = 0;
}
}
}
for(unsigned i = 0; i < vertexdatas.Size(); i++)
{
int ii = oldvertextable == NULL ? i : oldvertextable[i];
if (vertexdatas[i].flags & VERTEXFLAG_ZCeilingEnabled)
{
vt_heights[1][ii] = vertexdatas[i].zCeiling;
vt_found = true;
}
if (vertexdatas[i].flags & VERTEXFLAG_ZFloorEnabled)
{
vt_heights[0][ii] = vertexdatas[i].zFloor;
vt_found = true;
}
}
// If vertexdata_t is ever extended for non-slope usage, this will obviously have to be deferred or removed.
vertexdatas.Clear();
vertexdatas.ShrinkToFit();
if (vt_found)
{
for (auto &sec : Level->sectors)
{
if (sec.Lines.Size() != 3) continue; // only works with triangular sectors
DVector3 vt1, vt2, vt3;
DVector3 vec1, vec2;
int vi1, vi2, vi3;
vi1 = Index(sec.Lines[0]->v1);
vi2 = Index(sec.Lines[0]->v2);
vi3 = (sec.Lines[1]->v1 == sec.Lines[0]->v1 || sec.Lines[1]->v1 == sec.Lines[0]->v2)?
Index(sec.Lines[1]->v2) : Index(sec.Lines[1]->v1);
vt1 = DVector3(Level->vertexes[vi1].fPos(), 0);
vt2 = DVector3(Level->vertexes[vi2].fPos(), 0);
vt3 = DVector3(Level->vertexes[vi3].fPos(), 0);
for(int j=0; j<2; j++)
{
double *h1 = vt_heights[j].CheckKey(vi1);
double *h2 = vt_heights[j].CheckKey(vi2);
double *h3 = vt_heights[j].CheckKey(vi3);
if (h1 == NULL && h2 == NULL && h3 == NULL) continue;
vt1.Z = h1? *h1 : j==0? sec.GetPlaneTexZ(sector_t::floor) : sec.GetPlaneTexZ(sector_t::ceiling);
vt2.Z = h2? *h2 : j==0? sec.GetPlaneTexZ(sector_t::floor) : sec.GetPlaneTexZ(sector_t::ceiling);
vt3.Z = h3? *h3 : j==0? sec.GetPlaneTexZ(sector_t::floor) : sec.GetPlaneTexZ(sector_t::ceiling);
if (P_PointOnLineSidePrecise(Level->vertexes[vi3].fX(), Level->vertexes[vi3].fY(), sec.Lines[0]) == 0)
{
vec1 = vt2 - vt3;
vec2 = vt1 - vt3;
}
else
{
vec1 = vt1 - vt3;
vec2 = vt2 - vt3;
}
DVector3 cross = vec1 ^ vec2;
double len = cross.Length();
if (len == 0)
{
// Only happens when all vertices in this sector are on the same line.
// Let's just ignore this case.
continue;
}
cross /= len;
// Fix backward normals
if ((cross.Z < 0 && j == 0) || (cross.Z > 0 && j == 1))
{
cross = -cross;
}
secplane_t *plane = j==0? &sec.floorplane : &sec.ceilingplane;
double dist = -cross[0] * Level->vertexes[vi3].fX() - cross[1] * Level->vertexes[vi3].fY() - cross[2] * vt3.Z;
plane->set(cross[0], cross[1], cross[2], dist);
}
}
}
}
//===========================================================================
//
// P_SpawnSlopeMakers
//
//===========================================================================
void MapLoader::SpawnSlopeMakers (FMapThing *firstmt, FMapThing *lastmt, const int *oldvertextable)
{
FMapThing *mt;
for (mt = firstmt; mt < lastmt; ++mt)
{
if (mt->info != NULL && mt->info->Type == NULL &&
(mt->info->Special >= SMT_SlopeFloorPointLine && mt->info->Special <= SMT_VavoomCeiling))
{
DVector3 pos = mt->pos;
secplane_t *refplane;
sector_t *sec;
bool ceiling;
sec = Level->PointInSector (mt->pos);
if (mt->info->Special == SMT_SlopeCeilingPointLine || mt->info->Special == SMT_VavoomCeiling || mt->info->Special == SMT_SetCeilingSlope)
{
refplane = &sec->ceilingplane;
ceiling = true;
}
else
{
refplane = &sec->floorplane;
ceiling = false;
}
pos.Z = refplane->ZatPoint (mt->pos) + mt->pos.Z;
if (mt->info->Special <= SMT_SlopeCeilingPointLine)
{ // SlopeFloorPointLine and SlopCeilingPointLine
SlopeLineToPoint (mt->args[0], pos, ceiling);
}
else if (mt->info->Special <= SMT_SetCeilingSlope)
{ // SetFloorSlope and SetCeilingSlope
SetSlope (refplane, ceiling, mt->angle, mt->args[0], pos);
}
else
{ // VavoomFloor and VavoomCeiling (these do not perform any sector height adjustment - z is absolute)
VavoomSlope(sec, mt->thingid, mt->pos, ceiling);
}
mt->EdNum = 0;
}
}
for (mt = firstmt; mt < lastmt; ++mt)
{
if (mt->info != NULL && mt->info->Type == NULL &&
(mt->info->Special == SMT_CopyFloorPlane || mt->info->Special == SMT_CopyCeilingPlane))
{
CopyPlane (mt->args[0], mt->pos, mt->info->Special == SMT_CopyCeilingPlane);
mt->EdNum = 0;
}
}
SetSlopesFromVertexHeights(firstmt, lastmt, oldvertextable);
}
//===========================================================================
//
// [RH] Set slopes for sectors, based on line specials
//
// P_AlignPlane
//
// Aligns the floor or ceiling of a sector to the corresponding plane
// on the other side of the reference line. (By definition, line must be
// two-sided.)
//
// If (which & 1), sets floor.
// If (which & 2), sets ceiling.
//
//===========================================================================
void MapLoader::AlignPlane(sector_t *sec, line_t *line, int which)
{
sector_t *refsec;
double bestdist;
vertex_t *refvert = sec->Lines[0]->v1; // Shut up, GCC
if (line->backsector == NULL)
return;
// Find furthest vertex from the reference line. It, along with the two ends
// of the line, will define the plane.
bestdist = 0;
for (auto ln : sec->Lines)
{
for (int i = 0; i < 2; i++)
{
double dist;
vertex_t *vert;
vert = i == 0 ? ln->v1 : ln->v2;
dist = fabs((line->v1->fY() - vert->fY()) * line->Delta().X -
(line->v1->fX() - vert->fX()) * line->Delta().Y);
if (dist > bestdist)
{
bestdist = dist;
refvert = vert;
}
}
}
refsec = line->frontsector == sec ? line->backsector : line->frontsector;
DVector3 p, v1, v2, cross;
secplane_t *srcplane;
double srcheight, destheight;
srcplane = (which == 0) ? &sec->floorplane : &sec->ceilingplane;
srcheight = (which == 0) ? sec->GetPlaneTexZ(sector_t::floor) : sec->GetPlaneTexZ(sector_t::ceiling);
destheight = (which == 0) ? refsec->GetPlaneTexZ(sector_t::floor) : refsec->GetPlaneTexZ(sector_t::ceiling);
p[0] = line->v1->fX();
p[1] = line->v1->fY();
p[2] = destheight;
v1[0] = line->Delta().X;
v1[1] = line->Delta().Y;
v1[2] = 0;
v2[0] = refvert->fX() - line->v1->fX();
v2[1] = refvert->fY() - line->v1->fY();
v2[2] = srcheight - destheight;
cross = (v1 ^ v2).Unit();
// Fix backward normals
if ((cross.Z < 0 && which == 0) || (cross.Z > 0 && which == 1))
{
cross = -cross;
}
double dist = -cross[0] * line->v1->fX() - cross[1] * line->v1->fY() - cross[2] * destheight;
srcplane->set(cross[0], cross[1], cross[2], dist);
}
//===========================================================================
//
// P_SetSlopes
//
//===========================================================================
void MapLoader::SetSlopes ()
{
int s;
for (auto &line : Level->lines)
{
if (line.special == Plane_Align)
{
line.special = 0;
if (line.backsector != nullptr)
{
// args[0] is for floor, args[1] is for ceiling
//
// As a special case, if args[1] is 0,
// then args[0], bits 2-3 are for ceiling.
for (s = 0; s < 2; s++)
{
int bits = line.args[s] & 3;
if (s == 1 && bits == 0)
bits = (line.args[0] >> 2) & 3;
if (bits == 1) // align front side to back
AlignPlane (line.frontsector, &line, s);
else if (bits == 2) // align back side to front
AlignPlane (line.backsector, &line, s);
}
}
}
}
}
//===========================================================================
//
// P_CopySlopes
//
//===========================================================================
void MapLoader::CopySlopes()
{
for (auto &line : Level->lines)
{
if (line.special == Plane_Copy)
{
// The args are used for the tags of sectors to copy:
// args[0]: front floor
// args[1]: front ceiling
// args[2]: back floor
// args[3]: back ceiling
// args[4]: copy slopes from one side of the line to the other.
line.special = 0;
for (int s = 0; s < (line.backsector ? 4 : 2); s++)
{
if (line.args[s])
CopyPlane(line.args[s],
(s & 2 ? line.backsector : line.frontsector), s & 1);
}
if (line.backsector != NULL)
{
if ((line.args[4] & 3) == 1)
{
line.backsector->floorplane = line.frontsector->floorplane;
}
else if ((line.args[4] & 3) == 2)
{
line.frontsector->floorplane = line.backsector->floorplane;
}
if ((line.args[4] & 12) == 4)
{
line.backsector->ceilingplane = line.frontsector->ceilingplane;
}
else if ((line.args[4] & 12) == 8)
{
line.frontsector->ceilingplane = line.backsector->ceilingplane;
}
}
}
}
}
| gpl-3.0 |
avt-br/avt-br.github.io | scripts.js | 6192 | //============================================================================
// Gallery
//============================================================================
var active_element = null;
function current_gallery_element(){
return active_element;
}
function set_gallery_image(entry_element){
var image = document.getElementById("gallery-image");
image.style.width= "200px";
image.style.height= "200px";
image.src = "img/static.gif";
var downloadingImage = new Image();
downloadingImage.onload = function(){
image.style.width = "100%";
image.style.height = "100%";
image.style.background = "";
image.src = this.src;
};
downloadingImage.src = entry_element.getAttribute("link");
}
function set_gallery_video(entry_element){
var video_element = document.getElementById("gallery-video");
video_element.style.display = "block";
video_element.src = entry_element.getAttribute("link");
}
function disable_button(element){
element.classList.remove("osd-button");
element.classList.add("disabled-osd-button");
}
function enable_button(element){
element.classList.remove("disabled-osd-button");
element.classList.add("osd-button");
}
function set_gallery(entry_element){
var video_gallery = document.getElementById("gallery-video");
var image_gallery = document.getElementById("gallery-image");
var prevButton = document.getElementById("gallery-previous");
var nextButton = document.getElementById("gallery-next");
enable_button(prevButton);
enable_button(nextButton);
video_gallery.style.display = "none";
image_gallery.style.display = "none";
active_element = entry_element;
var entry_type = entry_element.getAttribute("type");
if (entry_type == "image"){
set_gallery_image(entry_element);
image_gallery.style.display = "block";
}
else if(entry_type == "video"){
set_gallery_video(entry_element);
video_gallery.style.display = "block";
}
//Now that we changed the gallery element,
//we check if the buttons should be enabled
var next = next_gallery_element();
if(!next){
disable_button(nextButton);
}
var prev = previous_gallery_element();
if(!prev){
disable_button(prevButton);
}
}
function next_gallery_element(){
var next = current_gallery_element().nextElementSibling;
if (next && next.classList.contains("entry")){
return next;
}
}
function previous_gallery_element(){
var prev = current_gallery_element().previousElementSibling;
if (prev && prev.classList.contains("entry")){
return prev;
}
}
function set_next_gallery_element(){
var next = next_gallery_element();
if (next) {
set_gallery(next);
}
}
function set_previous_gallery_element(){
var prev = previous_gallery_element();
if (prev){
set_gallery(prev);
}
}
function open_gallery(element){
set_gallery(element);
var title_el = document.querySelector("#gallery-overlay .osd-header h1");
title_el.innerHTML = element.parentElement.getAttribute("name");
document.getElementById("gallery-overlay").style.display = "block";
}
function close_gallery(){
document.getElementById("gallery-overlay").style.display = "none";
}
//============================================================================
// Resize background video to fill screen
//============================================================================
function set_background_video_size(video_element){
var aspectRatio = 9./16.;
var screenHeight = document.querySelector("body").offsetHeight;
var screenWidth = document.querySelector("body").offsetWidth;
var height = screenHeight;
var width = height/aspectRatio;
if(width < screenWidth)
{
width = screenWidth;
height = width*aspectRatio;
}
video_element.style.width = "" + width + "px";
video_element.style.height = "" + height + "px";
}
window.addEventListener('resize', function(event){
set_background_video_size(document.getElementById("background_video"));
});
//============================================================================
// OSD transitions
//============================================================================
function close_osd(element, callback) {
var old_height = element.offsetHeight;
var interval = setInterval(frame, 5);
element.style.overflow = "hidden";
function frame() {
var frame_height = element.offsetHeight;
if (frame_height <= 0) {
element.style.display = "none";
element.style.overflow = "auto";
element.style.height = "" + old_height + "px";
clearInterval(interval);
if (callback) callback();
} else {
element.style.height = "" + frame_height-10 + "px";
}
}
}
function open_osd(element, callback) {
element.style.overflow = "hidden";
element.style.visibility= "hidden";
element.style.display = "block";
var old_height = parseInt(element.offsetHeight);
element.style.height = "0px";
element.style.visibility= "visible";
var interval = setInterval(frame, 5);
function frame() {
var frame_height = element.offsetHeight;
if (frame_height >= old_height) {
element.style.height = "" + old_height + "px";
clearInterval(interval);
element.style.overflow = "auto";
if (callback) callback();
} else {
element.style.height = "" + (frame_height+10) + "px";
}
}
}
function change_osd(from, to){
var from_el = document.getElementById(from);
var to_el = document.getElementById(to);
close_osd(from_el, function(){open_osd(to_el);});
}
//============================================================================
// Startup
//============================================================================
document.addEventListener("DOMContentLoaded", function(event) {
var entries = document.querySelectorAll("div.album");
for(var i=0; i<entries.length; ++i){
var img = document.createElement("img");
img.src = entries[i].getAttribute("thumb");
entries[i].appendChild(img);
entries[i].addEventListener("click", function(ev){
open_gallery(ev.currentTarget.firstElementChild);
});
}
set_background_video_size(document.getElementById("background_video"))
});
| gpl-3.0 |
Shedward/Clementine-copy | src/core/database.cpp | 21547 | /* This file is part of Clementine.
Copyright 2010, David Sansome <me@davidsansome.com>
Clementine is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Clementine 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 Clementine. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "database.h"
#include "scopedtransaction.h"
#include "utilities.h"
#include "core/application.h"
#include "core/logging.h"
#include "core/taskmanager.h"
#include <boost/scope_exit.hpp>
#include <sqlite3.h>
#include <QCoreApplication>
#include <QDir>
#include <QLibrary>
#include <QLibraryInfo>
#include <QSqlDriver>
#include <QSqlQuery>
#include <QtDebug>
#include <QThread>
#include <QUrl>
#include <QVariant>
const char* Database::kDatabaseFilename = "clementine.db";
const int Database::kSchemaVersion = 46;
const char* Database::kMagicAllSongsTables = "%allsongstables";
int Database::sNextConnectionId = 1;
QMutex Database::sNextConnectionIdMutex;
Database::Token::Token(const QString& token, int start, int end)
: token(token), start_offset(start), end_offset(end) {}
struct sqlite3_tokenizer_module {
int iVersion;
int (*xCreate)(int argc, /* Size of argv array */
const char* const* argv, /* Tokenizer argument strings */
sqlite3_tokenizer** ppTokenizer); /* OUT: Created tokenizer */
int (*xDestroy)(sqlite3_tokenizer* pTokenizer);
int (*xOpen)(
sqlite3_tokenizer* pTokenizer, /* Tokenizer object */
const char* pInput, int nBytes, /* Input buffer */
sqlite3_tokenizer_cursor** ppCursor); /* OUT: Created tokenizer cursor */
int (*xClose)(sqlite3_tokenizer_cursor* pCursor);
int (*xNext)(
sqlite3_tokenizer_cursor* pCursor, /* Tokenizer cursor */
const char** ppToken, int* pnBytes, /* OUT: Normalized text for token */
int* piStartOffset, /* OUT: Byte offset of token in input buffer */
int* piEndOffset, /* OUT: Byte offset of end of token in input buffer */
int* piPosition); /* OUT: Number of tokens returned before this one */
};
struct sqlite3_tokenizer {
const sqlite3_tokenizer_module* pModule; /* The module for this tokenizer */
/* Tokenizer implementations will typically add additional fields */
};
struct sqlite3_tokenizer_cursor {
sqlite3_tokenizer* pTokenizer; /* Tokenizer for this cursor. */
/* Tokenizer implementations will typically add additional fields */
};
sqlite3_tokenizer_module* Database::sFTSTokenizer = nullptr;
int Database::FTSCreate(int argc, const char* const* argv,
sqlite3_tokenizer** tokenizer) {
*tokenizer = reinterpret_cast<sqlite3_tokenizer*>(new UnicodeTokenizer);
return SQLITE_OK;
}
int Database::FTSDestroy(sqlite3_tokenizer* tokenizer) {
UnicodeTokenizer* real_tokenizer =
reinterpret_cast<UnicodeTokenizer*>(tokenizer);
delete real_tokenizer;
return SQLITE_OK;
}
int Database::FTSOpen(sqlite3_tokenizer* pTokenizer, const char* input,
int bytes, sqlite3_tokenizer_cursor** cursor) {
UnicodeTokenizerCursor* new_cursor = new UnicodeTokenizerCursor;
new_cursor->pTokenizer = pTokenizer;
new_cursor->position = 0;
QString str = QString::fromUtf8(input, bytes).toLower();
QChar* data = str.data();
// Decompose and strip punctuation.
QList<Token> tokens;
QString token;
int start_offset = 0;
int offset = 0;
for (int i = 0; i < str.length(); ++i) {
QChar c = data[i];
ushort unicode = c.unicode();
if (unicode <= 0x007f) {
offset += 1;
} else if (unicode >= 0x0080 && unicode <= 0x07ff) {
offset += 2;
} else if (unicode >= 0x0800) {
offset += 3;
}
// Unicode astral planes unsupported in Qt?
/*else if (unicode >= 0x010000 && unicode <= 0x10ffff) {
offset += 4;
}*/
if (!data[i].isLetterOrNumber()) {
// Token finished.
if (token.length() != 0) {
tokens << Token(token, start_offset, offset - 1);
start_offset = offset;
token.clear();
} else {
++start_offset;
}
} else {
if (data[i].decompositionTag() != QChar::NoDecomposition) {
token.push_back(data[i].decomposition()[0]);
} else {
token.push_back(data[i]);
}
}
if (i == str.length() - 1) {
if (token.length() != 0) {
tokens << Token(token, start_offset, offset);
token.clear();
}
}
}
new_cursor->tokens = tokens;
*cursor = reinterpret_cast<sqlite3_tokenizer_cursor*>(new_cursor);
return SQLITE_OK;
}
int Database::FTSClose(sqlite3_tokenizer_cursor* cursor) {
UnicodeTokenizerCursor* real_cursor =
reinterpret_cast<UnicodeTokenizerCursor*>(cursor);
delete real_cursor;
return SQLITE_OK;
}
int Database::FTSNext(sqlite3_tokenizer_cursor* cursor, const char** token,
int* bytes, int* start_offset, int* end_offset,
int* position) {
UnicodeTokenizerCursor* real_cursor =
reinterpret_cast<UnicodeTokenizerCursor*>(cursor);
QList<Token> tokens = real_cursor->tokens;
if (real_cursor->position >= tokens.size()) {
return SQLITE_DONE;
}
Token t = tokens[real_cursor->position];
QByteArray utf8 = t.token.toUtf8();
*token = utf8.constData();
*bytes = utf8.size();
*start_offset = t.start_offset;
*end_offset = t.end_offset;
*position = real_cursor->position++;
real_cursor->current_utf8 = utf8;
return SQLITE_OK;
}
void Database::StaticInit() {
sFTSTokenizer = new sqlite3_tokenizer_module;
sFTSTokenizer->iVersion = 0;
sFTSTokenizer->xCreate = &Database::FTSCreate;
sFTSTokenizer->xDestroy = &Database::FTSDestroy;
sFTSTokenizer->xOpen = &Database::FTSOpen;
sFTSTokenizer->xNext = &Database::FTSNext;
sFTSTokenizer->xClose = &Database::FTSClose;
return;
}
Database::Database(Application* app, QObject* parent,
const QString& database_name)
: QObject(parent),
app_(app),
mutex_(QMutex::Recursive),
injected_database_name_(database_name),
query_hash_(0),
startup_schema_version_(-1) {
{
QMutexLocker l(&sNextConnectionIdMutex);
connection_id_ = sNextConnectionId++;
}
directory_ =
QDir::toNativeSeparators(Utilities::GetConfigPath(Utilities::Path_Root));
attached_databases_["jamendo"] = AttachedDatabase(
directory_ + "/jamendo.db", ":/schema/jamendo.sql", false);
QMutexLocker l(&mutex_);
Connect();
}
QSqlDatabase Database::Connect() {
QMutexLocker l(&connect_mutex_);
// Create the directory if it doesn't exist
if (!QFile::exists(directory_)) {
QDir dir;
if (!dir.mkpath(directory_)) {
}
}
const QString connection_id = QString("%1_thread_%2").arg(connection_id_).arg(
reinterpret_cast<quint64>(QThread::currentThread()));
// Try to find an existing connection for this thread
QSqlDatabase db = QSqlDatabase::database(connection_id);
if (db.isOpen()) {
return db;
}
db = QSqlDatabase::addDatabase("QSQLITE", connection_id);
if (!injected_database_name_.isNull())
db.setDatabaseName(injected_database_name_);
else
db.setDatabaseName(directory_ + "/" + kDatabaseFilename);
if (!db.open()) {
app_->AddError("Database: " + db.lastError().text());
return db;
}
// Find Sqlite3 functions in the Qt plugin.
StaticInit();
{
QSqlQuery set_fts_tokenizer("SELECT fts3_tokenizer(:name, :pointer)", db);
set_fts_tokenizer.bindValue(":name", "unicode");
set_fts_tokenizer.bindValue(
":pointer", QByteArray(reinterpret_cast<const char*>(&sFTSTokenizer),
sizeof(&sFTSTokenizer)));
if (!set_fts_tokenizer.exec()) {
qLog(Warning) << "Couldn't register FTS3 tokenizer";
}
// Implicit invocation of ~QSqlQuery() when leaving the scope
// to release any remaining database locks!
}
if (db.tables().count() == 0) {
// Set up initial schema
qLog(Info) << "Creating initial database schema";
UpdateDatabaseSchema(0, db);
}
// Attach external databases
for (const QString& key : attached_databases_.keys()) {
QString filename = attached_databases_[key].filename_;
if (!injected_database_name_.isNull()) filename = injected_database_name_;
// Attach the db
QSqlQuery q("ATTACH DATABASE :filename AS :alias", db);
q.bindValue(":filename", filename);
q.bindValue(":alias", key);
if (!q.exec()) {
qFatal("Couldn't attach external database '%s'",
key.toAscii().constData());
}
}
if (startup_schema_version_ == -1) {
UpdateMainSchema(&db);
}
// We might have to initialise the schema in some attached databases now, if
// they were deleted and don't match up with the main schema version.
for (const QString& key : attached_databases_.keys()) {
if (attached_databases_[key].is_temporary_ &&
attached_databases_[key].schema_.isEmpty())
continue;
// Find out if there are any tables in this database
QSqlQuery q(QString(
"SELECT ROWID FROM %1.sqlite_master"
" WHERE type='table'").arg(key),
db);
if (!q.exec() || !q.next()) {
q.finish();
ExecSchemaCommandsFromFile(db, attached_databases_[key].schema_, 0);
}
}
return db;
}
void Database::UpdateMainSchema(QSqlDatabase* db) {
// Get the database's schema version
int schema_version = 0;
{
QSqlQuery q("SELECT version FROM schema_version", *db);
if (q.next()) schema_version = q.value(0).toInt();
// Implicit invocation of ~QSqlQuery() when leaving the scope
// to release any remaining database locks!
}
startup_schema_version_ = schema_version;
if (schema_version > kSchemaVersion) {
qLog(Warning) << "The database schema (version" << schema_version
<< ") is newer than I was expecting";
return;
}
if (schema_version < kSchemaVersion) {
// Update the schema
for (int v = schema_version + 1; v <= kSchemaVersion; ++v) {
UpdateDatabaseSchema(v, *db);
}
}
}
void Database::RecreateAttachedDb(const QString& database_name) {
if (!attached_databases_.contains(database_name)) {
qLog(Warning) << "Attached database does not exist:" << database_name;
return;
}
const QString filename = attached_databases_[database_name].filename_;
QMutexLocker l(&mutex_);
{
QSqlDatabase db(Connect());
QSqlQuery q("DETACH DATABASE :alias", db);
q.bindValue(":alias", database_name);
if (!q.exec()) {
qLog(Warning) << "Failed to detach database" << database_name;
return;
}
if (!QFile::remove(filename)) {
qLog(Warning) << "Failed to remove file" << filename;
}
}
// We can't just re-attach the database now because it needs to be done for
// each thread. Close all the database connections, so each thread will
// re-attach it when they next connect.
for (const QString& name : QSqlDatabase::connectionNames()) {
QSqlDatabase::removeDatabase(name);
}
}
void Database::AttachDatabase(const QString& database_name,
const AttachedDatabase& database) {
attached_databases_[database_name] = database;
}
void Database::AttachDatabaseOnDbConnection(const QString& database_name,
const AttachedDatabase& database,
QSqlDatabase& db) {
AttachDatabase(database_name, database);
// Attach the db
QSqlQuery q("ATTACH DATABASE :filename AS :alias", db);
q.bindValue(":filename", database.filename_);
q.bindValue(":alias", database_name);
if (!q.exec()) {
qFatal("Couldn't attach external database '%s'",
database_name.toAscii().constData());
}
}
void Database::DetachDatabase(const QString& database_name) {
QMutexLocker l(&mutex_);
{
QSqlDatabase db(Connect());
QSqlQuery q("DETACH DATABASE :alias", db);
q.bindValue(":alias", database_name);
if (!q.exec()) {
qLog(Warning) << "Failed to detach database" << database_name;
return;
}
}
attached_databases_.remove(database_name);
}
void Database::UpdateDatabaseSchema(int version, QSqlDatabase& db) {
QString filename;
if (version == 0)
filename = ":/schema/schema.sql";
else
filename = QString(":/schema/schema-%1.sql").arg(version);
if (version == 31) {
// This version used to do a bad job of converting filenames in the songs
// table to file:// URLs. Now we do it properly here instead.
ScopedTransaction t(&db);
UrlEncodeFilenameColumn("songs", db);
UrlEncodeFilenameColumn("playlist_items", db);
for (const QString& table : db.tables()) {
if (table.startsWith("device_") && table.endsWith("_songs")) {
UrlEncodeFilenameColumn(table, db);
}
}
qLog(Debug) << "Applying database schema update" << version << "from"
<< filename;
ExecSchemaCommandsFromFile(db, filename, version - 1, true);
t.Commit();
} else {
qLog(Debug) << "Applying database schema update" << version << "from"
<< filename;
ExecSchemaCommandsFromFile(db, filename, version - 1);
}
}
void Database::UrlEncodeFilenameColumn(const QString& table, QSqlDatabase& db) {
QSqlQuery select(QString("SELECT ROWID, filename FROM %1").arg(table), db);
QSqlQuery update(
QString("UPDATE %1 SET filename=:filename WHERE ROWID=:id").arg(table),
db);
select.exec();
if (CheckErrors(select)) return;
while (select.next()) {
const int rowid = select.value(0).toInt();
const QString filename = select.value(1).toString();
if (filename.isEmpty() || filename.contains("://")) {
continue;
}
const QUrl url = QUrl::fromLocalFile(filename);
update.bindValue(":filename", url.toEncoded());
update.bindValue(":id", rowid);
update.exec();
CheckErrors(update);
}
}
void Database::ExecSchemaCommandsFromFile(QSqlDatabase& db,
const QString& filename,
int schema_version,
bool in_transaction) {
// Open and read the database schema
QFile schema_file(filename);
if (!schema_file.open(QIODevice::ReadOnly))
qFatal("Couldn't open schema file %s", filename.toUtf8().constData());
ExecSchemaCommands(db, QString::fromUtf8(schema_file.readAll()),
schema_version, in_transaction);
}
void Database::ExecSchemaCommands(QSqlDatabase& db, const QString& schema,
int schema_version, bool in_transaction) {
// Run each command
const QStringList commands(schema.split(QRegExp("; *\n\n")));
// We don't want this list to reflect possible DB schema changes
// so we initialize it before executing any statements.
// If no outer transaction is provided the song tables need to
// be queried before beginning an inner transaction! Otherwise
// DROP TABLE commands on song tables may fail due to database
// locks.
const QStringList song_tables(SongsTables(db, schema_version));
if (!in_transaction) {
ScopedTransaction inner_transaction(&db);
ExecSongTablesCommands(db, song_tables, commands);
inner_transaction.Commit();
} else {
ExecSongTablesCommands(db, song_tables, commands);
}
}
void Database::ExecSongTablesCommands(QSqlDatabase& db,
const QStringList& song_tables,
const QStringList& commands) {
for (const QString& command : commands) {
// There are now lots of "songs" tables that need to have the same schema:
// songs, magnatune_songs, and device_*_songs. We allow a magic value
// in the schema files to update all songs tables at once.
if (command.contains(kMagicAllSongsTables)) {
for (const QString& table : song_tables) {
// Another horrible hack: device songs tables don't have matching _fts
// tables, so if this command tries to touch one, ignore it.
if (table.startsWith("device_") &&
command.contains(QString(kMagicAllSongsTables) + "_fts")) {
continue;
}
qLog(Info) << "Updating" << table << "for" << kMagicAllSongsTables;
QString new_command(command);
new_command.replace(kMagicAllSongsTables, table);
QSqlQuery query(db.exec(new_command));
if (CheckErrors(query))
qFatal("Unable to update music library database");
}
} else {
QSqlQuery query(db.exec(command));
if (CheckErrors(query)) qFatal("Unable to update music library database");
}
}
}
QStringList Database::SongsTables(QSqlDatabase& db, int schema_version) const {
QStringList ret;
// look for the tables in the main db
for (const QString& table : db.tables()) {
if (table == "songs" || table.endsWith("_songs")) ret << table;
}
// look for the tables in attached dbs
for (const QString& key : attached_databases_.keys()) {
QSqlQuery q(
QString(
"SELECT NAME FROM %1.sqlite_master"
" WHERE type='table' AND name='songs' OR name LIKE '%songs'")
.arg(key),
db);
if (q.exec()) {
while (q.next()) {
QString tab_name = key + "." + q.value(0).toString();
ret << tab_name;
}
}
}
if (schema_version > 29) {
// The playlist_items table became a songs table in version 29.
ret << "playlist_items";
}
return ret;
}
bool Database::CheckErrors(const QSqlQuery& query) {
QSqlError last_error = query.lastError();
if (last_error.isValid()) {
qLog(Error) << "db error: " << last_error;
qLog(Error) << "faulty query: " << query.lastQuery();
qLog(Error) << "bound values: " << query.boundValues();
return true;
}
return false;
}
bool Database::IntegrityCheck(QSqlDatabase db) {
qLog(Debug) << "Starting database integrity check";
int task_id = app_->task_manager()->StartTask(tr("Integrity check"));
bool ok = false;
bool error_reported = false;
// Ask for 10 error messages at most.
QSqlQuery q(QString("PRAGMA integrity_check(10)"), db);
while (q.next()) {
QString message = q.value(0).toString();
// If no errors are found, a single row with the value "ok" is returned
if (message == "ok") {
ok = true;
break;
} else {
if (!error_reported) {
app_->AddError(
tr("Database corruption detected. Please read "
"https://code.google.com/p/clementine-player/wiki/"
"DatabaseCorruption "
"for instructions on how to recover your database"));
}
app_->AddError("Database: " + message);
error_reported = true;
}
}
app_->task_manager()->SetTaskFinished(task_id);
return ok;
}
void Database::DoBackup() {
QSqlDatabase db(this->Connect());
// Before we overwrite anything, make sure the database is not corrupt
QMutexLocker l(&mutex_);
const bool ok = IntegrityCheck(db);
if (ok) {
BackupFile(db.databaseName());
}
}
bool Database::OpenDatabase(const QString& filename,
sqlite3** connection) const {
int ret = sqlite3_open(filename.toUtf8(), connection);
if (ret != 0) {
if (*connection) {
const char* error_message = sqlite3_errmsg(*connection);
qLog(Error) << "Failed to open database for backup:" << filename
<< error_message;
} else {
qLog(Error) << "Failed to open database for backup:" << filename;
}
return false;
}
return true;
}
void Database::BackupFile(const QString& filename) {
qLog(Debug) << "Starting database backup";
QString dest_filename = QString("%1.bak").arg(filename);
const int task_id =
app_->task_manager()->StartTask(tr("Backing up database"));
sqlite3* source_connection = nullptr;
sqlite3* dest_connection = nullptr;
BOOST_SCOPE_EXIT((source_connection)(dest_connection)(task_id)(app_)) {
// Harmless to call sqlite3_close() with a nullptr pointer.
sqlite3_close(source_connection);
sqlite3_close(dest_connection);
app_->task_manager()->SetTaskFinished(task_id);
}
BOOST_SCOPE_EXIT_END
bool success = OpenDatabase(filename, &source_connection);
if (!success) {
return;
}
success = OpenDatabase(dest_filename, &dest_connection);
if (!success) {
return;
}
sqlite3_backup* backup =
sqlite3_backup_init(dest_connection, "main", source_connection, "main");
if (!backup) {
const char* error_message = sqlite3_errmsg(dest_connection);
qLog(Error) << "Failed to start database backup:" << error_message;
return;
}
int ret = SQLITE_OK;
do {
ret = sqlite3_backup_step(backup, 16);
const int page_count = sqlite3_backup_pagecount(backup);
app_->task_manager()->SetTaskProgress(
task_id, page_count - sqlite3_backup_remaining(backup), page_count);
} while (ret == SQLITE_OK);
if (ret != SQLITE_DONE) {
qLog(Error) << "Database backup failed";
}
sqlite3_backup_finish(backup);
}
| gpl-3.0 |
donatellosantoro/Llunatic | LunaticGUI/gui/src/it/unibas/lunatic/gui/node/PagedBatchTupleFactory.java | 4571 | package it.unibas.lunatic.gui.node;
import speedy.model.algebra.operators.ITupleIterator;
import speedy.model.database.ITable;
import speedy.model.database.Tuple;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
public class PagedBatchTupleFactory extends Children.Keys<Tuple> implements ITupleFactory {
private static Log logger = LogFactory.getLog(PagedBatchTupleFactory.class);
private TableNode tableNode;
private Thread asyncThread;
private Node waitNode;
private final Thread viewThread;
private final int limit;
private final int offset;
public PagedBatchTupleFactory(TableNode table, int offset, int limit) {
this.tableNode = table;
this.waitNode = createWaitNode();
this.viewThread = Thread.currentThread();
this.offset = offset;
this.limit = limit;
}
public TableNode getTableNode() {
return tableNode;
}
@Override
@SuppressWarnings("deprecation")
protected void addNotify() {
logger.debug("Initialized");
super.add(new Node[]{waitNode});
if (asyncThread == null) {
asyncThread = new Thread(getKeyCreator(), "Async table cerator thread");
asyncThread.start();
}
}
@Override
@SuppressWarnings("unchecked")
protected void removeNotify() {
logger.debug("Removed");
setKeys(Collections.EMPTY_SET);
}
@Override
protected Node[] createNodes(Tuple key) {
return new Node[]{createNodeForKey(key)};
}
protected TableTupleNode createNodeForKey(Tuple key) {
if (tableNode.isMcResultNode()) {
return new TableTupleNode(key, tableNode.getTable(), tableNode.getDb(), tableNode.getChaseStep());
}
return new TableTupleNode(key, tableNode.getTable(), tableNode.getDb());
}
private Node createWaitNode() {
AbstractNode n = new AbstractNode(Children.LEAF) {
public @Override
Action[] getActions(boolean context) {
return new Action[0];
}
};
n.setIconBaseWithExtension("org/openide/nodes/wait.gif"); //NOI18N
n.setDisplayName(NbBundle.getMessage(ChildFactory.class, "LBL_WAIT")); //NOI18N
return n;
}
public Runnable getKeyCreator() {
return new KeyCreator();
}
@Override
public void interrupt() {
if (asyncThread != null) {
asyncThread.interrupt();
logger.info("Interrupt async thread");
}
}
@Override
public Node createTuples() {
return new TableNodeWithTuples(tableNode, this);
}
class KeyCreator implements Runnable {
@Override
@SuppressWarnings("deprecation")
public void run() {
ArrayList<Tuple> keys = new ArrayList<Tuple>();
ITable table = tableNode.getTable();
ITupleIterator iterator = null;
try {
iterator = table.getTupleIterator(offset, limit);
boolean threadInterrupted = isInterrupted();
while (iterator.hasNext() && !viewThread.isInterrupted() && !threadInterrupted) {
keys.add(iterator.next());
threadInterrupted = isInterrupted();
}
remove(new Node[]{waitNode});
if (!viewThread.isInterrupted() && !threadInterrupted) {
setKeys(keys);
}
asyncThread = null;
if (viewThread.isInterrupted()) {
logger.info("Factory interrupted: view thread");
}
if (threadInterrupted) {
logger.debug("Factory interrupted: async thread");
}
} finally {
if (iterator != null) {
iterator.close();
}
}
}
private boolean isInterrupted() {
boolean interrupted = Thread.currentThread().isInterrupted();
logger.trace("Thread interrupted: " + interrupted);
return interrupted;
}
}
}
| gpl-3.0 |
opensupports/opensupports | client/src/core-components/checkbox.js | 2977 | import React from 'react';
import classNames from 'classnames';
import _ from 'lodash';
import keyCode from 'keycode';
import callback from 'lib-core/callback';
import getIcon from 'lib-core/get-icon';
class CheckBox extends React.Component {
static propTypes = {
alignment: React.PropTypes.string,
label: React.PropTypes.node,
value: React.PropTypes.bool,
wrapInLabel: React.PropTypes.bool,
onChange: React.PropTypes.func
};
static defaultProps = {
wrapInLabel: false,
alignment: 'right'
};
state = {
checked: false
};
render() {
let Wrapper = (this.props.wrapInLabel) ? 'label' : 'span';
return (
<Wrapper className={this.getClass()}>
<span {...this.getIconProps()}>
{getIcon((this.getValue()) ? 'check-square' : 'square', 'lg') }
</span>
<input {...this.getProps()}/>
{(this.props.label) ? this.renderLabel() : null}
</Wrapper>
);
}
renderLabel() {
return (
<span className="checkbox__label">
{this.props.label}
</span>
);
}
getProps() {
let props = _.clone(this.props);
props.type = 'checkbox';
props['aria-hidden'] = true;
props.className = 'checkbox__box';
props.checked = this.getValue();
props.onChange = callback(this.handleChange.bind(this), this.props.onChange);
delete props.alignment;
delete props.errored;
delete props.label;
delete props.value;
delete props.wrapInLabel;
return props;
}
getClass() {
const {
className,
disabled
} = this.props;
let classes = {
'checkbox': true,
'checkbox_checked': this.getValue(),
'checkbox_disabled': disabled,
[className]: (className)
};
return classNames(classes);
}
getIconProps() {
return {
'aria-checked': this.getValue(),
className: 'checkbox__icon',
onKeyDown: callback(this.handleIconKeyDown.bind(this), this.props.onKeyDown),
role: "checkbox",
tabIndex: 0
};
}
getValue() {
return (this.props.value === undefined) ? this.state.checked : this.props.value;
}
handleChange(event) {
this.setState({
checked: event.target.checked
});
}
handleIconKeyDown(event) {
if (event.keyCode === keyCode('SPACE')) {
event.preventDefault();
callback(this.handleChange.bind(this), this.props.onChange)({
target: {
checked: !this.state.checked
}
});
}
}
}
export default CheckBox;
| gpl-3.0 |
key-consulting/kcatoes | apps/frontend/modules/test/templates/regroupementSuccess.php | 217 | <h2><span>Configuration des tests - Regroupements</span></h2>
<form method="post" action="<?php echo url_for('test/regroupement') ?>">
<?php echo $form ?>
<p><input type="submit" value="Suivant" /></p>
</form> | gpl-3.0 |
ASG-ULINK/moodle | blocks/wizard/assign_wizard_group.php | 3760 | <?php
require('../../config.php');
require_once("$CFG->dirroot/lib/filelib.php");
require_once("$CFG->dirroot/repository/lib.php");
require_once("$CFG->dirroot/blocks/wizard/wizard_form.php");
require_login();
if (isguestuser()) {
die();
}
global $DB;
$context = get_context_instance(CONTEXT_USER, $USER->id);
require_capability('moodle/user:manageownfiles', $context);
$struser = get_string('user');
$PAGE->set_url('/blockswizard/assignwizard.php');
$PAGE->set_context($context);
$PAGE->set_title(format_string('Assign wizard Group'));
$PAGE->set_heading(format_string('wizard'));
$PAGE->set_pagelayout();
$data = new stdClass();
echo $OUTPUT->header();
echo $OUTPUT->heading(format_string('Assign wizard Group'), 2, 'headingblock header');
$group_wizard = $DB->get_records_sql("SELECT * FROM `mdl_assign_group_wizard` WHERE status = '0'");
$columnStarts = "<td style='border-width:0px 0px 1px 0px; border:0px 0px 1px 0px solid;border-color:#dbdfe7'>";
$columnEnds = "</td>";
echo "<style>th{text-align:left !important;}</style>";
echo "<table width='100%'>";
echo "<tr>";
echo "<td colspan='2'>";
echo "<table width='100%' cellpadding='0' cellspacing='0' border='0' class='display' id='example'><thead>";
echo "<tr><td> </td></tr>";
echo "<tr style='background: none repeat scroll 0 0 #efefef'>";
echo "<th><b>Sr.No.</b></th>";
echo "<th><b>wizard</b></th>";
echo "<th><b>Group</b></th>";
echo "<th><b>Course</b></th>";
echo "<th><b></b></th>";
echo "<th><b></b></th>";
echo "<th><b></b></th>";
echo "</tr></thead>";
$i=1;
foreach ($group_wizard as $group_wizardvalue) {
$course=$DB->get_record_sql('SELECT * FROM `mdl_course` WHERE id="'.$group_wizardvalue->course.'"');
$rec=$DB->get_record_sql('SELECT * FROM `mdl_wizard_name` WHERE id="'.$group_wizardvalue->wizard.'"');
$group=$DB->get_record_sql('SELECT * FROM `mdl_groups` WHERE id="'.$group_wizardvalue->groups.'"');
echo "<tr>";
echo $columnStarts . $i++ . $columnEnds;
echo $columnStarts . $rec->name . $columnEnds;
echo $columnStarts . $group->name . $columnEnds;
echo $columnStarts . $course->fullname . $columnEnds;
echo $columnStarts . '<a href="'.$CFG->wwwroot.'/blocks/wizard/assignwizard.php?id='.$group_wizardvalue->id.'"><img height="10px" src="'.$CFG->wwwroot.'/blocks/wizard/images/icons/edit.png"/></a>' . $columnEnds;
echo $columnStarts . '<a href="'.$CFG->wwwroot.'/blocks/wizard/assignwizard.php?id='.$group_wizardvalue->id.'&selectdel=del"><img height="10px" src="'.$CFG->wwwroot.'/blocks/wizard/images/icons/delete.png"/></a>' . $columnEnds;
// echo $columnStarts . '<a href="'.$CFG->wwwroot.'/blocks/cpd/cpd.php?id='.$group_cpdvalue->id.'"><img height="10px" src="'.$CFG->wwwroot.'/blocks/cpd/images/icons/edit.png"/></a>' . $columnEnds;
// echo $columnStarts . '<a href="'.$CFG->wwwroot.'/blocks/cpd/cpd.php?id='.$group_cpdvalue->id.'&select=1"><img height="10px" src="'.$CFG->wwwroot.'/blocks/cpd/images/icons/delete.png"/></a>' . $columnEnds;
echo "</tr>";
// }
}
echo "</table>";
echo "</td>";
echo "</tr>";
echo "</table>";
?>
<style type="text/css" title="currentStyle">
strong
{
line-height: 50px;
}
h2.headingblock{
line-height: 3em;
}
select, input, button, textarea {
padding: 3px;
margin-left: 66px;
width: 150px
}
.group
{
margin-left: 74px;
}
.course1
{
margin-left: 70px;
}
.wizard
{
margin-left: 84px;
}
</style>
| gpl-3.0 |
optimizationBenchmarking/evaluator-base | src/test/java/test/junit/org/optimizationBenchmarking/evaluator/dataAndIO/BBOBExampleTest.java | 479 | package test.junit.org.optimizationBenchmarking.evaluator.dataAndIO;
import examples.org.optimizationBenchmarking.evaluator.dataAndIO.BBOBExample;
import shared.junit.TestBase;
import shared.junit.org.optimizationBenchmarking.evaluator.dataAndIO.ExperimentSetTest;
/** Test the BBOB example data. */
public class BBOBExampleTest extends ExperimentSetTest {
/** create */
public BBOBExampleTest() {
super(new BBOBExample(TestBase.getNullLogger()));
}
}
| gpl-3.0 |
windkit/codfs-win | codfs/src/datastructure/ringbuffer.hh | 1172 | #ifndef RINGBUFFER_HH_
#define RINGBUFFER_HH_
#include <thread>
#include <malloc.h>
#include "../common/define.hh"
using namespace std;
template<typename T>
class RingBuffer {
public:
RingBuffer (uint64_t size) :
_size(size + 1),
_head(0),
_tail(0)
{
//_buffer = (T*)memalign(getpagesize(), sizeof(T) * size);
_buffer = (T*)malloc(sizeof(T) * _size);
}
void push(T ele) {
unique_lock<mutex> lock(_mutex);
_full.wait(lock, [this]() {return !RingBuffer<T>::checkFull();});
_buffer[_head] = ele;
_head = advance(_head);
_empty.notify_one();
}
T pop() {
unique_lock<mutex> lock(_mutex);
_empty.wait(lock, [this]() {return !RingBuffer<T>::checkEmpty();});
T tempEle = _buffer[_tail];
_tail = advance(_tail);
_full.notify_one();
return tempEle;
}
private:
inline uint64_t advance(uint64_t pos) {
return (pos + 1) % _size;
}
bool checkEmpty() {
return (_head == _tail);
}
bool checkFull() {
return (advance(_head) == _tail);
}
uint64_t _size;
uint64_t _head;
uint64_t _tail;
mutex _mutex;
condition_variable _empty;
condition_variable _full;
T *_buffer;
};
#endif
| gpl-3.0 |
thanhdongsl1990/h3h3_Y2Knight | Support/Plugins/Nunu.cs | 6012 | #region LICENSE
// Copyright 2014 - 2014 Support
// Nunu.cs is part of Support.
// Support is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Support 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 Support. If not, see <http://www.gnu.org/licenses/>.
#endregion
#region
using System;
using System.Linq;
using LeagueSharp;
using LeagueSharp.Common;
using Support.Util;
using ActiveGapcloser = Support.Util.ActiveGapcloser;
#endregion
namespace Support.Plugins
{
public class Nunu : PluginBase
{
private int LastLaugh { get; set; }
public Nunu()
{
Q = new Spell(SpellSlot.Q, 125);
W = new Spell(SpellSlot.W, 700);
E = new Spell(SpellSlot.E, 550);
R = new Spell(SpellSlot.R, 650);
}
public override void OnProcessPacket(GamePacketEventArgs args)
{
if (args.PacketData[0] == Packet.S2C.PlayEmote.Header &&
ConfigValue<StringList>("Misc.Laugh").SelectedIndex == 2)
{
var packet = Packet.S2C.PlayEmote.Decoded(args.PacketData);
if (packet.NetworkId == Player.NetworkId && packet.EmoteId == (byte) Packet.Emotes.Laugh)
args.Process = false;
}
}
public override void OnUpdate(EventArgs args)
{
if (ComboMode)
{
if (Q.IsReady() && ConfigValue<bool>("Combo.Q") &&
Player.HealthPercentage() < ConfigValue<Slider>("Combo.Q.Health").Value)
{
var minion = MinionManager.GetMinions(Player.Position, Q.Range).FirstOrDefault();
if (minion.IsValidTarget(Q.Range))
Q.CastOnUnit(minion, UsePackets);
}
var allys = Helpers.AllyInRange(W.Range).OrderByDescending(h => h.FlatPhysicalDamageMod).ToList();
if (W.IsReady() && allys.Count > 0 && ConfigValue<bool>("Combo.W"))
{
W.CastOnUnit(allys.FirstOrDefault(), UsePackets);
}
if (W.IsReady() && Target.IsValidTarget(AttackRange) && ConfigValue<bool>("Combo.W"))
{
W.CastOnUnit(Player, UsePackets);
}
if (E.IsReady() && Target.IsValidTarget(E.Range) && ConfigValue<bool>("Combo.E"))
{
E.CastOnUnit(Target, UsePackets && ConfigValue<bool>("Misc.E.NoFace"));
}
}
if (HarassMode)
{
if (Q.IsReady() && ConfigValue<bool>("Harass.Q") &&
Player.HealthPercentage() < ConfigValue<Slider>("Harass.Q.Health").Value)
{
var minion = MinionManager.GetMinions(Player.Position, Q.Range).FirstOrDefault();
if (minion.IsValidTarget(Q.Range))
Q.CastOnUnit(minion, UsePackets);
}
var allys = Helpers.AllyInRange(W.Range).OrderByDescending(h => h.FlatPhysicalDamageMod).ToList();
if (W.IsReady() && allys.Count > 0 && ConfigValue<bool>("Harass.W"))
{
W.CastOnUnit(allys.FirstOrDefault(), UsePackets);
}
if (W.IsReady() && Target.IsValidTarget(AttackRange) && ConfigValue<bool>("Harass.W"))
{
W.CastOnUnit(Player, UsePackets);
}
if (E.IsReady() && Target.IsValidTarget(E.Range) && ConfigValue<bool>("Harass.E"))
{
E.CastOnUnit(Target, UsePackets && ConfigValue<bool>("Misc.E.NoFace"));
}
}
// most import part!!!
if (Environment.TickCount > LastLaugh + 4200 && Player.CountEnemysInRange(2000) > 0 &&
ConfigValue<StringList>("Misc.Laugh").SelectedIndex > 0)
{
Packet.C2S.Emote.Encoded(new Packet.C2S.Emote.Struct((byte) Packet.Emotes.Laugh)).Send();
LastLaugh = Environment.TickCount;
}
}
public override void OnEnemyGapcloser(ActiveGapcloser gapcloser)
{
if (gapcloser.Sender.IsAlly)
return;
if (E.CastCheck(gapcloser.Sender, "Gapcloser.E"))
{
E.CastOnUnit(gapcloser.Sender, UsePackets);
if (W.IsReady())
W.CastOnUnit(Player, UsePackets);
}
}
public override void ComboMenu(Menu config)
{
config.AddBool("Combo.Q", "Use Q", true);
config.AddBool("Combo.W", "Use W", true);
config.AddBool("Combo.E", "Use E", true);
config.AddSlider("Combo.Q.Health", "Consume below %HP", 50, 1, 100);
}
public override void HarassMenu(Menu config)
{
config.AddBool("Harass.Q", "Use Q", true);
config.AddBool("Harass.W", "Use W", false);
config.AddBool("Harass.E", "Use E", true);
config.AddSlider("Harass.Q.Health", "Consume below %HP", 50, 1, 100);
}
public override void MiscMenu(Menu config)
{
config.AddList("Misc.Laugh", "Laugh Emote", new[] {"OFF", "ON", "ON + Mute"});
config.AddBool("Misc.E.NoFace", "E NoFace Exploit", false);
}
public override void InterruptMenu(Menu config)
{
config.AddBool("Gapcloser.E", "Use E to Interrupt Gapcloser", true);
}
}
} | gpl-3.0 |
lwuckel/WebosPrinterServer | IO/PclFileReader.cs | 1869 | using System;
using System.IO;
using WebosPrinter.Net;
using System.Text;
namespace WebosPrinter.IO
{
public class PclFileReader
{
string pclFilePath;
private const int DUPLEX_SETTING_OFFSET = 0x36;
private const string DUPLEX_SETTING_STRING = "ON";
private const int SEARCH_SIZE = 512;
private const string BLACK_WHITE_STRING = "&b1M";
public PclFileReader (string pclFilePath){
this.pclFilePath = pclFilePath;
}
public PrintJobProperties GetProperties()
{
byte[] initialBytes = new byte[SEARCH_SIZE];
using (var stream = File.OpenRead(pclFilePath))
{
int totalRead = 0;
do{
int read = stream.Read(initialBytes, totalRead, initialBytes.Length - totalRead);
if (read < 1)
throw new EndOfStreamException("PCL file is too small, cannot read job properties");
totalRead += read;
} while (totalRead < SEARCH_SIZE);
}
PlexMode plexMode = this.GetPlexMode(initialBytes);
ColorMode colorMode = this.GetColorMode(initialBytes);
return new PrintJobProperties(colorMode, plexMode);
}
ColorMode GetColorMode(byte[] initialBytes){
string searchString = Encoding.ASCII.GetString(initialBytes);
return (searchString.Contains(BLACK_WHITE_STRING))
? ColorMode.BlackAndWhite
: ColorMode.Color;
}
PlexMode GetPlexMode(byte[] initialBytes){
string ascii = Encoding.ASCII.GetString(initialBytes, DUPLEX_SETTING_OFFSET, DUPLEX_SETTING_STRING.Length);
PlexMode plexMode = (String.Equals(DUPLEX_SETTING_STRING,ascii , StringComparison.Ordinal))
? PlexMode.Duplex
: PlexMode.Simplex;
return plexMode;
}
}
}
| gpl-3.0 |
donkeyxote/djangle | docs/html/search/namespaces_0.js | 525 | var searchData=
[
['celery',['celery',['../namespacedjangle_1_1celery.html',1,'djangle']]],
['djangle',['djangle',['../namespacedjangle.html',1,'']]],
['forms',['forms',['../namespacedjangle_1_1forms.html',1,'djangle']]],
['settings',['settings',['../namespacedjangle_1_1settings.html',1,'djangle']]],
['urls',['urls',['../namespacedjangle_1_1urls.html',1,'djangle']]],
['views',['views',['../namespacedjangle_1_1views.html',1,'djangle']]],
['wsgi',['wsgi',['../namespacedjangle_1_1wsgi.html',1,'djangle']]]
];
| gpl-3.0 |
MehmetNuri/Beebo | app/src/main/java/org/zarroboogs/weibo/dialogfragment/RemoveGroupDialog.java | 2003 |
package org.zarroboogs.weibo.dialogfragment;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import java.util.ArrayList;
import org.zarroboogs.weibo.R;
import org.zarroboogs.weibo.activity.ManageGroupActivity;
/**
* User: qii Date: 13-2-15
*/
@SuppressLint("ValidFragment")
public class RemoveGroupDialog extends DialogFragment {
private ArrayList<String> checkedNames;
public RemoveGroupDialog() {
}
public RemoveGroupDialog(ArrayList<String> checkedNames) {
this.checkedNames = checkedNames;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("checkedNames", checkedNames);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (savedInstanceState != null) {
checkedNames = savedInstanceState.getStringArrayList("checkedNames");
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.remove_group)).setMessage(getString(R.string.remove_group_content))
.setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ManageGroupActivity.ManageGroupFragment fragment = (ManageGroupActivity.ManageGroupFragment) getTargetFragment();
fragment.removeGroup(checkedNames);
}
}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}
| gpl-3.0 |
cmiic/moodle-filter_geogebra | filterlocalsettings.php | 7954 | <?php
/*
* GeoGebra Moodle filter
* Copyright (C) 2009 Sara Arjona, Florian Sonner, Christoph Reinisch
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* GeoGebra filter local settings
*
* @package filter
* @subpackage geogebra
* @copyright 2011 Christoph Reinisch
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
//not all of the admin-settings are included here since urljar and java-arguments should only be used by admins
class geogebra_filter_local_settings_form extends filter_local_settings_form {
protected function definition_inner($mform) {
global $CFG;
require_once($CFG->dirroot.'/filter/geogebra/lib.php');
$ggbparams = filter_geogebra_get_params();
$stroff = get_string('off', 'filters');
$stron = get_string('on', 'filters');
$strdefaultoff = get_string('defaultforsite', 'filter_geogebra') . ' ('.$stroff.')';
$strdefaulton = get_string('defaultforsite', 'filter_geogebra') . ' ('.$stron.')';
$choices = array();
//get all default choices
//the "''=>" is a little terrifying - but at least it unsets the setting
foreach ($ggbparams as $value) {
$choices[$value] = array(
''=>(($CFG->$value === "true")? $strdefaulton : $strdefaultoff) ,
'true' => $stron,
'false' => $stroff
);
}
$choices['filter_geogebra_use_objecttag'] = array(
''=>(($CFG->filter_geogebra_use_objecttag === "true")? $strdefaulton : $strdefaultoff) ,
'true' => $stron,
'false' => $stroff
);
$mform->addElement('header', 'filter_geogebra_dimensions', get_string('dimensionsheading', 'filter_geogebra'));
$mform->addHelpButton('filter_geogebra_dimensions','localdimensheading','filter_geogebra');
$mform->addElement('text', 'filter_geogebra_width', get_string('width', 'filter_geogebra'), array('size' => 20));
$mform->setType('filter_geogebra_width', PARAM_RAW);
$mform->addElement('text', 'filter_geogebra_height', get_string('height', 'filter_geogebra'), array('size' => 20));
$mform->setType('filter_geogebra_height', PARAM_RAW);
//Functionality
$mform->addElement('header', 'filter_geogebra_functionality', get_string('functionalityheading', 'filter_geogebra'));
$mform->addElement('select', 'filter_geogebra_enable_rightclick', get_string('enable_rightclick','filter_geogebra'), $choices['filter_geogebra_enable_rightclick']);
$mform->addHelpButton('filter_geogebra_enable_rightclick', 'enable_rightclick', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_enable_labeldrags', get_string('enable_labeldrags','filter_geogebra'), $choices['filter_geogebra_enable_labeldrags']);
$mform->addHelpButton('filter_geogebra_enable_labeldrags', 'enable_labeldrags', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_show_reseticon', get_string('show_reseticon','filter_geogebra'), $choices['filter_geogebra_show_reseticon']);
$mform->addHelpButton('filter_geogebra_show_reseticon', 'show_reseticon', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_framepossible', get_string('framepossible','filter_geogebra'), $choices['filter_geogebra_framepossible']);
$mform->addHelpButton('filter_geogebra_framepossible', 'framepossible', 'filter_geogebra');
//User Interface
$mform->addElement('header', 'filter_geogebra_interface', get_string('interfaceheading', 'filter_geogebra'));
$mform->addElement('select', 'filter_geogebra_show_menubar', get_string('show_menubar','filter_geogebra'), $choices['filter_geogebra_show_menubar']);
$mform->addHelpButton('filter_geogebra_show_menubar', 'show_menubar', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_show_toolbar', get_string('show_toolbar','filter_geogebra'), $choices['filter_geogebra_show_toolbar']);
$mform->addHelpButton('filter_geogebra_show_toolbar', 'show_toolbar', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_show_toolbarhelp', get_string('show_toolbarhelp','filter_geogebra'), $choices['filter_geogebra_show_toolbarhelp']);
$mform->addHelpButton('filter_geogebra_show_toolbarhelp', 'show_toolbarhelp', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_show_algebrainput', get_string('show_algebrainput','filter_geogebra'), $choices['filter_geogebra_show_algebrainput']);
$mform->addHelpButton('filter_geogebra_show_algebrainput', 'show_algebrainput', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_show_animationbutton', get_string('show_animationbutton','filter_geogebra'), $choices['filter_geogebra_show_animationbutton']);
$mform->addHelpButton('filter_geogebra_show_animationbutton', 'show_animationbutton', 'filter_geogebra');
//Language specific Options
$mform->addElement('header', 'filter_geogebra_language', get_string('languageheading', 'filter_geogebra'));
$mform->addElement('text', 'filter_geogebra_iso_language', get_string('iso_language','filter_geogebra'));
$mform->addHelpButton('filter_geogebra_iso_language', 'iso_language', 'filter_geogebra');
$mform->addElement('text', 'filter_geogebra_iso_country', get_string('iso_country','filter_geogebra'));
$mform->addHelpButton('filter_geogebra_iso_country', 'iso_country', 'filter_geogebra');
//Miscellaneous Options
$mform->addElement('header', 'filter_geogebra_miscellaneous', get_string('miscellaneousheading', 'filter_geogebra'));
$mform->addElement('select', 'filter_geogebra_error_dialogs', get_string('error_dialogs','filter_geogebra'), $choices['filter_geogebra_error_dialogs']);
$mform->addHelpButton('filter_geogebra_error_dialogs', 'error_dialogs', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_use_browserforjs', get_string('use_browserforjs','filter_geogebra'), $choices['filter_geogebra_use_browserforjs']);
$mform->addHelpButton('filter_geogebra_use_browserforjs', 'use_browserforjs', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_allow_rescaling', get_string('allow_rescaling','filter_geogebra'), $choices['filter_geogebra_allow_rescaling']);
$mform->addHelpButton('filter_geogebra_allow_rescaling', 'allow_rescaling', 'filter_geogebra');
$mform->addElement('text', 'filter_geogebra_on_initparam', get_string('on_initparam','filter_geogebra'));
$mform->addHelpButton('filter_geogebra_on_initparam', 'on_initparam', 'filter_geogebra');
$mform->addElement('select', 'filter_geogebra_show_button', get_string('show_button','filter_geogebra'), $choices['filter_geogebra_show_button']);
$mform->addHelpButton('filter_geogebra_show_button', 'show_button', 'filter_geogebra');
//HTML specific options
$mform->addElement('select', 'filter_geogebra_use_objecttag', get_string('use_objecttag','filter_geogebra'), $choices['filter_geogebra_use_objecttag']);
$mform->addHelpButton('filter_geogebra_use_objecttag', 'use_objecttag', 'filter_geogebra');
$mform->addElement('text', 'filter_geogebra_id', get_string('embed_id','filter_geogebra'));
$mform->addHelpButton('filter_geogebra_id', 'embed_id', 'filter_geogebra');
$mform->addElement('text', 'filter_geogebra_class', get_string('embed_class','filter_geogebra'));
$mform->addHelpButton('filter_geogebra_class', 'embed_class', 'filter_geogebra');
}
}
| gpl-3.0 |
akryzhanovskiy/E-Shop | html/admin/language/russian/common/header.php | 1037 | <?php
// Heading
$_['heading_title'] = 'Администрирование';
// Text
$_['text_order'] = 'Заказы';
$_['text_order_status'] = 'Статусы заказов';
$_['text_complete_status'] = 'Завершено';
$_['text_customer'] = 'Клиенты';
$_['text_online'] = 'Клиенты Online';
$_['text_approval'] = 'Ожидают одобрения';
$_['text_product'] = 'Товары';
$_['text_stock'] = 'Нет в наличии';
$_['text_review'] = 'Отзывы';
$_['text_return'] = 'Возвраты';
$_['text_affiliate'] = 'Партнерская программа';
$_['text_store'] = 'Магазин';
$_['text_front'] = 'Магазин';
$_['text_help'] = 'Помощь';
$_['text_homepage'] = 'Сайт ';
$_['text_support'] = 'Форум';
$_['text_documentation'] = 'Документация';
$_['text_logout'] = 'Выход';
| gpl-3.0 |
mariotsi/SDA-Tracking | src/TrackingSDA.java | 490 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.swing.*;
/**
* @author Simone
*/
public class TrackingSDA {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainGUI();
}
});
}
}
| gpl-3.0 |
jtux270/translate | ovirt/3.6_source/backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/DiskDaoTest.java | 8126 | package org.ovirt.engine.core.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskStorageType;
import org.ovirt.engine.core.compat.Guid;
public class DiskDaoTest extends BaseReadDaoTestCase<Guid, Disk, DiskDao> {
private static final int TOTAL_DISK_IMAGES = 8;
@Override
protected Guid getExistingEntityId() {
return FixturesTool.DISK_ID;
}
@Override
protected DiskDao prepareDao() {
return dbFacade.getDiskDao();
}
@Override
protected Guid generateNonExistingId() {
return Guid.Empty;
}
@Override
protected int getEneitiesTotalCount() {
return TOTAL_DISK_IMAGES + DiskLunMapDaoTest.TOTAL_DISK_LUN_MAPS;
}
@Override
@Test
public void testGet() {
Disk result = dao.get(getExistingEntityId());
assertNotNull(result);
assertEquals(getExistingEntityId().toString(), result.getId().toString());
}
@Test
public void testGetFilteredWithPermissions() {
Disk result = dao.get(getExistingEntityId(), PRIVILEGED_USER_ID, true);
assertNotNull(result);
assertEquals(getExistingEntityId().toString(), result.getId().toString());
}
@Test
public void testGetFilteredWithoutPermissions() {
Disk result = dao.get(getExistingEntityId(), UNPRIVILEGED_USER_ID, true);
assertNull(result);
}
@Test
public void testGetFilteredWithoutPermissionsNoFilter() {
Disk result = dao.get(getExistingEntityId(), UNPRIVILEGED_USER_ID, false);
assertNotNull(result);
assertEquals(getExistingEntityId().toString(), result.getId().toString());
}
@Test
public void testGetFilteredWithPermissionsNoFilter() {
Disk result = dao.get(getExistingEntityId(), PRIVILEGED_USER_ID, false);
assertNotNull(result);
assertEquals(getExistingEntityId().toString(), result.getId().toString());
}
@Test
public void testGetAllForVMFilteredWithPermissions() {
// test user 3 - has permissions
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, PRIVILEGED_USER_ID, true);
assertFullGetAllForVMResult(disks);
}
@Test
public void testGetAllForVMFilteredWithPermissionsNoPermissions() {
// test user 2 - hasn't got permissions
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, UNPRIVILEGED_USER_ID, true);
assertTrue("VM should have no disks viewable to the user", disks.isEmpty());
}
@Test
public void testGetAllForVMFilteredWithPermissionsNoPermissionsAndNoFilter() {
// test user 2 - hasn't got permissions, but no filtering was requested
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, UNPRIVILEGED_USER_ID, false);
assertFullGetAllForVMResult(disks);
}
@Test
public void testGetPluggedForVMFilteredWithPermissions() {
// test user 3 - has permissions
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, true, PRIVILEGED_USER_ID, true);
assertPluggedGetAllForVMResult(disks);
}
@Test
public void testGetPluggedForVMFilteredWithPermissionsNoPermissions() {
// test user 2 - hasn't got permissions
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, true, UNPRIVILEGED_USER_ID, true);
assertTrue("VM should have no disks viewable to the user", disks.isEmpty());
}
@Test
public void testGetPluggedForVMFilteredWithPermissionsNoPermissionsAndNoFilter() {
// test user 2 - hasn't got permissions, but no filtering was requested
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, true, UNPRIVILEGED_USER_ID, false);
assertPluggedGetAllForVMResult(disks);
}
@Test
public void testGetAllForVM() {
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57);
assertFullGetAllForVMResult(disks);
}
@Test
public void testGetAllAttachableDisksByPoolIdNoDisks() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(FixturesTool.STORAGE_POOL_NFS,
null,
null,
false);
assertTrue(result.isEmpty());
}
@Test
public void testGetAllAttachableDisksByPoolIdNull() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(null, null, null, false);
assertFullGetAllAttachableDisksByPoolId(result);
}
@Test
public void testGetAllAttachableDisksByPoolWithPermissions() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(null, null, PRIVILEGED_USER_ID, true);
assertFullGetAllAttachableDisksByPoolId(result);
}
@Test
public void testGetAllAttachableDisksByPoolWithNoPermissions() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(null, null, UNPRIVILEGED_USER_ID, true);
assertTrue(result.isEmpty());
}
@Test
public void testGetAllAttachableDisksByPoolWithNoPermissionsFilterDisabled() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(null, null, UNPRIVILEGED_USER_ID, false);
assertFullGetAllAttachableDisksByPoolId(result);
}
@Test
public void testGetVmBootActiveDisk() {
Disk bootDisk = dao.getVmBootActiveDisk(FixturesTool.VM_RHEL5_POOL_57);
assertNotNull("VM should have a boot disk attached", bootDisk);
assertEquals("Wrong boot disk for VM", bootDisk.getId(), FixturesTool.BOOTABLE_DISK_ID);
}
@Test
public void testGetVmPartialData() {
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, PRIVILEGED_USER_ID, true);
assertFullGetAllForVMResult(disks);
assertEquals("New Description", disks.get(0).getDiskDescription());
assertNotNull(disks.get(0).getDiskAlias());
}
@Test
public void testGetAllFromDisksByDiskStorageType() {
List<Disk> disks = dao.getAllFromDisksByDiskStorageType(DiskStorageType.CINDER, PRIVILEGED_USER_ID, true);
assertEquals("We should have one disk", 1, disks.size());
}
/**
* Asserts the result of {@link DiskImageDao#getAllForVm(Guid)} contains the correct disks.
* @param disks
* The result to check
*/
private static void assertFullGetAllForVMResult(List<Disk> disks) {
assertEquals("VM should have six disks", 6, disks.size());
}
/**
* Asserts the result of {@link DiskImageDao#getAllForVm(Guid)} contains the correct plugged disks.
* @param disks
* The result to check
*/
private static void assertPluggedGetAllForVMResult(List<Disk> disks) {
Integer numberOfDisks = 5;
assertEquals("VM should have " + numberOfDisks + " plugged disk", numberOfDisks.intValue(), disks.size());
}
/**
* Asserts the result of {@link DiskDao#getAllAttachableDisksByPoolId} contains the floating disk.
* @param disks
* The result to check
*/
private static void assertFullGetAllAttachableDisksByPoolId(List<Disk> disks) {
assertEquals("There should be only four attachable disks", 4, disks.size());
Set<Guid> expectedFloatingDiskIds =
new HashSet<Guid>(Arrays.asList(FixturesTool.FLOATING_DISK_ID, FixturesTool.FLOATING_LUN_ID,
FixturesTool.FLOATING_CINDER_DISK_ID));
Set<Guid> actualFloatingDiskIds = new HashSet<Guid>();
for (Disk disk : disks) {
actualFloatingDiskIds.add(disk.getId());
}
assertEquals("Wrong attachable disks", expectedFloatingDiskIds, actualFloatingDiskIds);
}
}
| gpl-3.0 |
alafighting/JianshuApp | app/src/main/java/com/copy/jianshuapp/utils/CheckFormatUtils.java | 2489 | package com.copy.jianshuapp.utils;
import com.copy.jianshuapp.common.ObjectUtils;
import java.util.regex.Pattern;
/**
* 格式检查相关的工具类
* @version imkarl 2017-03
*/
public class CheckFormatUtils {
private CheckFormatUtils() {
}
/**
* 正则:用户昵称
* 只能包含英文、汉字、数字及下划线,长度为4-15个字符
*/
private static final String REGEX_NICKNAME = "[\\u4e00-\\u9fa5_a-zA-Z0-9]{4,15}";
/**
* 正则:密码
* 不能包含任何空白字符【中英文空格\f\n\r\t\v】及汉字,长度不能少于6个字符
*/
private static final String REGEX_PASSWORD = "[^\\s\\u4e00-\\u9fa5]{6,}";
/**
* 正则:手机号(精确)
* <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188</p>
* <p>联通:130、131、132、145、155、156、175、176、185、186</p>
* <p>电信:133、153、173、177、180、181、189</p>
* <p>全球星:1349</p>
* <p>虚拟运营商:170</p>
*/
public static final String REGEX_PHONE = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$";
/**
* 正则:邮箱
*/
public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* 判断是否匹配正则
* @param regex 正则表达式
* @param input 要匹配的字符串
* @return {@code true}: 匹配<br>{@code false}: 不匹配
*/
public static boolean isMatch(String regex, CharSequence input) {
return !ObjectUtils.isEmpty(input) && Pattern.matches(regex, input);
}
/**
* 用户昵称是否合法
* @return true:格式合法,false:非法
*/
public static boolean isNickname(String text) {
return isMatch(REGEX_NICKNAME, text);
}
/**
* 手机号是否合法
* @return true:格式合法,false:非法
*/
public static boolean isPhone(String text) {
return isMatch(REGEX_PHONE, text);
}
/**
* 邮箱是否合法
* @return true:格式合法,false:非法
*/
public static boolean isEmail(String text) {
return isMatch(REGEX_EMAIL, text);
}
/**
* 密码是否合法
* @return true:格式合法,false:非法
*/
public static boolean isPassword(String text) {
return isMatch(REGEX_PASSWORD, text);
}
}
| gpl-3.0 |
ZeroOne71/ql | 02_ECCentral/03_Service/EventMessage/PO/CollectionPaymentSettlementMessage.cs | 730 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ECCentral.Service.EventMessage.PO
{
/// <summary>
/// 代收代付结算单结算
/// </summary>
public class CollectionPaymentSettlementMessage : ECCentral.Service.Utility.EventMessage
{
public override string Subject
{
get
{
return "ECC_COLLECTIONPAYMENT_SETTLEMENTED";
}
}
/// <summary>
/// 当前用户编号
/// </summary>
public int CurrentUserSysNo { get; set; }
/// <summary>
/// 代收代付结算单编号
/// </summary>
public int SysNo { get; set; }
}
}
| gpl-3.0 |
ViewTouch/viewtouch | tests/conf_file/test_conf_file.cc | 10889 | #define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
#include "conf_file.hh"
#include <string>
#include <vector>
#include <fstream>
#include <limits> // std::numeric_limits
#include <cmath> // std::isnan, std::isinf
#include <locale>
TEST_CASE("setter_default_section", "[conf_file]")
{
ConfFile conf("setter.ini");
CHECK(conf.SetValue("value", "key"));
std::string val;
CHECK(conf.GetValue(val, "key"));
CHECK(val == "value");
}
TEST_CASE("setter_missing_section", "[conf_file]")
{
ConfFile conf("setter_missing_section.ini");
CHECK(conf.SetValue("value", "key", "new_section"));
std::string value_ret;
CHECK(conf.GetValue(value_ret, "key", "new_section"));
CHECK_FALSE(conf.GetValue(value_ret, "key", "missing_section"));
}
TEST_CASE("setter_emtpy_parameter", "[conf_file]")
{
ConfFile conf("setter_empty_parameter.ini");
CHECK_FALSE(conf.SetValue("", "key"));
CHECK_FALSE(conf.SetValue("value", ""));
}
TEST_CASE("strings", "[conf_file]")
{
ConfFile conf("strings.ini");
const std::vector<std::string> strings = {
"a",
"bb",
"1",
"NaN",
"string with spaces in it",
"string with brackets [ { } ] in it",
"string with brackets ; _ - in it",
"; value starting with semicolon",
"# value starting with hashtag",
"\" value surrounded by \"",
};
for (const std::string &val : strings)
{
std::string val_ret;
REQUIRE(conf.SetValue(val, "key"));
CHECK(conf.GetValue(val_ret, "key"));
CHECK(val == val_ret);
}
}
TEST_CASE("integer", "[conf_file]")
{
ConfFile conf("integer.ini");
const std::vector<int> integers = {
0,
1, 3, 5, 7, 1337,
-1, -3, -5, -7, -1337,
};
for (const int val : integers)
{
int val_ret;
REQUIRE(conf.SetValue(val, "key"));
CHECK(conf.GetValue(val_ret, "key"));
CHECK(val == val_ret);
}
}
TEST_CASE("doubles", "[conf_file]")
{
ConfFile conf("doubles.ini");
const std::vector<double> doubles = {
0, 1, 3, 5, 7, 1337, -1, -3, -5, -7, -1337,
0.001, 1.0/4,
0.000031212421108108183401041,
};
for (const double val : doubles)
{
double val_ret;
REQUIRE(conf.SetValue(val, "key"));
CHECK(conf.GetValue(val_ret, "key"));
// printf(%f) and std::to_string(double) have a standard precision of
// 6 digits after the comma
CHECK(val == Approx{val_ret}.epsilon(1e-6));
}
}
TEST_CASE("doubles_inf", "[conf_file]")
{
ConfFile conf("doubles_inf.ini");
const std::vector<double> doubles = {
std::numeric_limits<double>::infinity(),
-std::numeric_limits<double>::infinity(),
};
for (const double val : doubles)
{
double val_ret;
REQUIRE(conf.SetValue(val, "key"));
CHECK(conf.GetValue(val_ret, "key"));
CHECK(std::signbit(val) == std::signbit(val_ret));
CHECK(std::isinf(val_ret));
}
}
TEST_CASE("doubles_nan", "[conf_file]")
{
ConfFile conf("doubles_nan.ini");
// can't compare NaN like the other doubles, NaN == NaN --> false
const std::vector<double> doubles = {
std::numeric_limits<double>::quiet_NaN(),
-std::numeric_limits<double>::signaling_NaN(),
};
for (const double val : doubles)
{
double val_ret;
REQUIRE(conf.SetValue(val, "key"));
CHECK(conf.GetValue(val_ret, "key"));
CHECK(std::isnan(val_ret));
}
}
TEST_CASE("load_default_section", "[conf_file]")
{
const std::string filename = "load_default_section.ini";
{
std::ofstream fout(filename);
fout << "key=value" << std::endl;
fout << "k_no_value=" << std::endl;
fout << "=value_no_key" << std::endl;
fout << "# comment with key value pair key_comment=value_comment" << std::endl;
}
ConfFile conf(filename, true); // load config file
std::string val;
CHECK(conf.GetValue(val, "key"));
CHECK(val == "value");
CHECK_FALSE(conf.GetValue(val, "k_no_value"));
CHECK_FALSE(conf.GetValue(val, ""));
}
namespace // locale namespace for load_double
{
// https://stackoverflow.com/questions/15220861/how-can-i-set-the-decimal-separator-to-be-a-comma
template <class charT>
class punct_facet: public std::numpunct<charT> {
protected:
charT do_decimal_point() const { return ','; }
charT do_thousands_sep() const { return '.'; }
};
}
TEST_CASE("load_double", "[conf_file]")
{
// create and set a locale where '.' is the thousand separator and ',' is
// the decimal separator (as is the case in locales (i.e. de_DE, nb_NO, ...)
auto loc_comma = std::locale(std::locale::classic(), new punct_facet<char>);
std::locale::global(loc_comma);
const std::string filename = "load_double.ini";
{
std::ofstream fout(filename);
fout << "key=1.337" << std::endl;
fout << "inf=inf" << std::endl;
}
ConfFile conf(filename, true); // load config file
double val;
CHECK(conf.GetValue(val, "key"));
CHECK(val == Approx{1.337}.epsilon(1e-6));
CHECK(conf.GetValue(val, "inf"));
CHECK(val == std::numeric_limits<double>::infinity());
}
TEST_CASE("load_string_as_number", "[conf_file]")
{
const std::string filename = "load_string_as_number.ini";
{
std::ofstream fout(filename);
fout << "key=value" << std::endl;
}
ConfFile conf(filename, true); // load config file
double val;
CHECK_FALSE(conf.GetValue(val, "key"));
int int_val;
CHECK_FALSE(conf.GetValue(int_val, "key"));
}
TEST_CASE("getter_no_modification", "[conf_file]")
{
// reads of non existing keys don't modify the target variable
const std::string filename = "conf_file_getter_no_modification.ini";
ConfFile conf(filename); // load config file
std::string val_str = "1337";
int val_int = 1337;
double val_dbl = 1337;
CHECK_FALSE(conf.GetValue(val_str, "key"));
CHECK_FALSE(conf.GetValue(val_int, "key"));
CHECK_FALSE(conf.GetValue(val_dbl, "key"));
CHECK(val_str == "1337");
CHECK(val_int == 1337);
CHECK(val_dbl == 1337);
}
TEST_CASE("load_with_section", "[conf_file]")
{
const std::string filename = "load_with_section.ini";
{
std::ofstream fout(filename);
fout << "key=value" << std::endl;
fout << "[section_no_keys]" << std::endl;
fout << "# comment with key value pair key_comment=value_comment" << std::endl;
fout << "[section]" << std::endl;
fout << "key=section_value" << std::endl;
fout << "k_no_value=" << std::endl;
fout << "=value_no_key" << std::endl;
fout << "# comment with key value pair key_comment=value_comment" << std::endl;
}
ConfFile conf(filename, true); // load config file
std::string val;
// read key from default section
CHECK(conf.GetValue(val, "key"));
CHECK(val == "value");
// read key from section with no keys, expect failure
CHECK_FALSE(conf.GetValue(val, "key", "section_no_keys"));
// read key from section, expect different value
CHECK(conf.GetValue(val, "key", "section"));
CHECK(val == "section_value");
// try to read not available keys
CHECK_FALSE(conf.GetValue(val, "k_no_value", "section"));
CHECK_FALSE(conf.GetValue(val, "", "section"));
}
TEST_CASE("save_with_section", "[conf_file]")
{
const std::string filename = "save_with_section.ini";
{
ConfFile conf_save(filename);
conf_save.SetValue("value", "key");
conf_save.SetValue("section_value", "key", "section");
// destructor also saves to the ini file
}
ConfFile conf(filename, true); // load config file
std::string val;
// read key from default section
CHECK(conf.GetValue(val, "key"));
CHECK(val == "value");
// read key from section, expect different value
CHECK(conf.GetValue(val, "key", "section"));
CHECK(val == "section_value");
// try to read not available keys
CHECK_FALSE(conf.GetValue(val, "k_no_value", "section"));
CHECK_FALSE(conf.GetValue(val, "", "section"));
}
TEST_CASE("no_delete_default_section", "[conf_file]")
{
const std::string filename = "conf_file_no_delete_default_section.ini";
ConfFile conf(filename);
CHECK_FALSE(conf.DeleteSection(""));
}
TEST_CASE("delete_key_twice", "[conf_file]")
{
const std::string filename = "conf_file_delete_key_twice.ini";
ConfFile conf(filename);
// add a key to delete later
REQUIRE(conf.SetValue("value", "key"));
// delete key
REQUIRE(conf.DeleteKey("key"));
// can't delete the same key twice
CHECK_FALSE(conf.DeleteKey("key"));
}
TEST_CASE("delete_empty_key", "[conf_file]")
{
const std::string filename = "conf_file_delete_empty_key.ini";
ConfFile conf(filename);
CHECK_FALSE(conf.DeleteKey(""));
}
TEST_CASE("list_all_sections", "[conf_file]")
{
const std::string filename = "conf_file_list_all_sections.ini";
ConfFile conf(filename);
conf.SetValue("value", "key");
conf.SetValue("section_value", "key", "section");
const std::vector<std::string> sections = conf.getSectionNames();
CHECK(sections[0] == "");
CHECK(sections[1] == "section");
}
TEST_CASE("set_dirty_false", "[conf_file]")
{
const std::string filename = "conf_file_set_dirty_false.ini";
{
ConfFile conf(filename);
conf.SetValue("value", "key");
conf.SetValue("section_value", "key", "section");
// disable writing of conf file
conf.set_dirty(false);
}
// file should not exist
std::ifstream conf_file(filename);
CHECK(conf_file.fail());
}
TEST_CASE("keys_empty_section", "[conf_file]")
{
const std::string filename = "conf_file_keys_empty_section.ini";
ConfFile conf(filename);
const std::vector<std::string> default_keys = conf.keys("");
CHECK(default_keys.size() == 0);
}
TEST_CASE("keys_exception_invalid_section", "[conf_file]")
{
const std::string filename = "conf_file_keys_exception_invalid_section.ini";
ConfFile conf(filename);
CHECK_THROWS_AS(conf.keys("invalid_section"), std::out_of_range);
}
TEST_CASE("keys_list", "[conf_file]")
{
const std::string filename = "conf_file_keys_list.ini";
ConfFile conf(filename);
conf.SetValue("value", "key1");
conf.SetValue("value", "key2");
conf.SetValue("value", "key3");
conf.SetValue("section_value", "key", "section");
const std::vector<std::string> default_keys = conf.keys("");
const std::vector<std::string> section_keys = conf.keys("section");
REQUIRE(default_keys.size() == 3);
REQUIRE(section_keys.size() == 1);
CHECK(default_keys[0] == "key1");
CHECK(default_keys[1] == "key2");
CHECK(default_keys[2] == "key3");
CHECK(section_keys[0] == "key");
}
| gpl-3.0 |
neo4j-contrib/java-rest-binding | src/main/java/org/neo4j/rest/graphdb/index/RestRelationshipIndex.java | 1923 | /**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.rest.graphdb.index;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.RelationshipIndex;
import org.neo4j.rest.graphdb.RestAPI;
/**
* @author mh
* @since 24.01.11
*/
public class RestRelationshipIndex extends RestIndex<Relationship> implements RelationshipIndex {
public RestRelationshipIndex(String indexName, RestAPI restApi) {
super(indexName, restApi );
}
public Class<Relationship> getEntityType() {
return Relationship.class;
}
public org.neo4j.graphdb.index.IndexHits<Relationship> get( String s, Object o, Node node, Node node1 ) {
throw new UnsupportedOperationException();
}
public org.neo4j.graphdb.index.IndexHits<Relationship> query( String s, Object o, Node node, Node node1 ) {
throw new UnsupportedOperationException();
}
public org.neo4j.graphdb.index.IndexHits<Relationship> query( Object o, Node node, Node node1 ) {
throw new UnsupportedOperationException();
}
@Override
public boolean isWriteable() {
return true;
}
}
| gpl-3.0 |
RedHatQE/rhui-testing-tools | rhui-tests/test_rhui_tcms324680.py | 2400 | #! /usr/bin/python -tt
import nose
from rhuilib.rhui_testcase import *
from rhuilib.rhuimanager import *
from rhuilib.rhuimanager_repo import *
from rhuilib.rhuimanager_entitlements import *
class test_tcms324680(RHUITestcase):
''' for more ditails see bz 957128
try toupload fake rpms and signed rpm from a directory in cli mode
fake rpm sould not be uploaded
signed and unsigned rpm should be uploaded'''
def _setup(self):
"""[TCMS#324680 setup] Do initial rhui-manager run"""
RHUIManager.initial_run(self.rs.Instances["RHUA"][0])
'''[TCMS#324680 setup] Create custom repo '''
RHUIManagerRepo.add_custom_repo(self.rs.Instances["RHUA"][0], "repo324680")
"""[TCMS#324680 setup] Create fake rpm"""
Expect.ping_pong(self.rs.Instances["RHUA"][0], "mkdir /root/rpms324680 && echo SUCCESS", "[^ ]SUCCESS")
Expect.enter(self.rs.Instances["RHUA"][0], "touch /root/rpms324680/fake.rpm && echo SUCCESS")
"""[TCMS#324680 setup] Create rpm files"""
self.rs.Instances["RHUA"][0].sftp.put("/usr/share/rhui-testing-tools/testing-data/custom-signed-rpm-1-0.1.fc17.noarch.rpm", "/root/rpms324680/custom-signed-rpm-1-0.1.fc17.noarch.rpm")
self.rs.Instances["RHUA"][0].sftp.put("/usr/share/rhui-testing-tools/testing-data/custom-unsigned-rpm-1-0.1.fc17.noarch.rpm", "/root/rpms324680/custom-unsigned-rpm-1-0.1.fc17.noarch.rpm")
'''[TCMS#324680 setup] Upload content to custom repo324680 in cli mode'''
Expect.ping_pong(self.rs.Instances["RHUA"][0], "rhui-manager packages upload --repo_id repo324680 --packages /root/rpms324680 && echo SUCCESS", "[^ ]SUCCESS", 10)
def _test(self):
'''[TCMS#324680 test] Check the packages list for repo324680'''
nose.tools.assert_equal(RHUIManagerRepo.check_for_package(self.rs.Instances["RHUA"][0], "repo324680", ""), ["custom-signed-rpm-1-0.1.fc17.noarch.rpm", "custom-unsigned-rpm-1-0.1.fc17.noarch.rpm"])
def _cleanup(self):
'''[TCMS#324680 cleanup] Delete custom repo '''
RHUIManagerRepo.delete_repo(self.rs.Instances["RHUA"][0], ["repo324680"])
'''[TCMS#284279 cleanup] Remove rpms from RHUI '''
Expect.ping_pong(self.rs.Instances["RHUA"][0], " rm -f -r /root/rpms324680 && echo SUCCESS", "[^ ]SUCCESS")
if __name__ == "__main__":
nose.run(defaultTest=__name__, argv=[__file__, '-v'])
| gpl-3.0 |
benkuper/Chataigne | Source/StateMachine/Transition/StateTransitionManager.cpp | 1861 | /*
==============================================================================
StateTransitionManager.cpp
Created: 28 Oct 2016 8:20:59pm
Author: bkupe
==============================================================================
*/
StateTransitionManager::StateTransitionManager(StateManager * _sm) :
BaseManager("Transitions"),
sm(_sm)
{
}
StateTransitionManager::~StateTransitionManager()
{
}
StateTransition * StateTransitionManager::addItemFromData(var data, bool addToUndo)
{
State * sourceState = sm->getItemWithName(data.getProperty("sourceState", ""));
State * destState = sm->getItemWithName(data.getProperty("destState", ""));
if (sourceState == nullptr || destState == nullptr) return nullptr;
return addItem(sourceState, destState, data, addToUndo);
}
StateTransition * StateTransitionManager::addItem(State * source, State * dest, var data, bool addToUndo)
{
if (getItemForSourceAndDest(source, dest) != nullptr) return nullptr;
return BaseManager::addItem(new StateTransition(source, dest), data,addToUndo);
}
Array<State*> StateTransitionManager::getAllStatesLinkedTo(State * state)
{
Array<State*> result;
for (auto &t : state->inTransitions) result.add(t->sourceState);
for (auto &t : state->outTransitions) result.add(t->destState);
return result;
}
Array<UndoableAction *> StateTransitionManager::getRemoveAllLinkedTransitionsAction(State * linkedState)
{
Array<StateTransition *> transitionsToRemove;
transitionsToRemove.addArray(linkedState->inTransitions);
transitionsToRemove.addArray(linkedState->outTransitions);
return getRemoveItemsUndoableAction(transitionsToRemove);
}
StateTransition * StateTransitionManager::getItemForSourceAndDest(State * source, State * dest)
{
for (auto &st : items)
{
if (st->sourceState == source && st->destState == dest) return st;
}
return nullptr;
}
| gpl-3.0 |
rforge/biocep | src_aws_client/com/amazonaws/ec2/doc/_2008_12_01/BundleInstanceType.java | 2329 |
package com.amazonaws.ec2.doc._2008_12_01;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for BundleInstanceType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="BundleInstanceType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="instanceId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="storage" type="{http://ec2.amazonaws.com/doc/2008-12-01/}BundleInstanceTaskStorageType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BundleInstanceType", propOrder = {
"instanceId",
"storage"
})
public class BundleInstanceType {
@XmlElement(required = true)
protected String instanceId;
@XmlElement(required = true)
protected BundleInstanceTaskStorageType storage;
/**
* Gets the value of the instanceId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInstanceId() {
return instanceId;
}
/**
* Sets the value of the instanceId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInstanceId(String value) {
this.instanceId = value;
}
/**
* Gets the value of the storage property.
*
* @return
* possible object is
* {@link BundleInstanceTaskStorageType }
*
*/
public BundleInstanceTaskStorageType getStorage() {
return storage;
}
/**
* Sets the value of the storage property.
*
* @param value
* allowed object is
* {@link BundleInstanceTaskStorageType }
*
*/
public void setStorage(BundleInstanceTaskStorageType value) {
this.storage = value;
}
}
| gpl-3.0 |
juandesant/spatterlight | terps/tads/tads3/vmbifregn.cpp | 2981 | #ifdef RCSID
static char RCSid[] =
"$Header: d:/cvsroot/tads/tads3/vmbifreg.cpp,v 1.2 1999/05/17 02:52:29 MJRoberts Exp $";
#endif
/*
* Copyright (c) 1998, 2002 Michael J. Roberts. All Rights Reserved.
*
* Please see the accompanying license file, LICENSE.TXT, for information
* on using and copying this software.
*/
/*
Name
vmbifreg.cpp - built-in function set registry
Function
Defines the built-in functions that are linked in to this implementation
of the VM.
This file is dependent on the host application environment configuration.
This particular file includes a table for the base set of T3 VM
built-in functions. Some host application environments may provide
additional function sets; if you're building a host system with its own
extra function sets, do the following:
1. Make a copy of this file (DO NOT MODIFY THE ORIGINAL).
2. Remove this file (and/or derived files, such as object files) from
your makefile, and add your modified version instead.
3. In the table below, add an entry for each of your extra function
sets. (Of course, for each of your added function sets, you must
implement the function set and link the implementation into your
host application executable.)
Notes
Modified
12/05/98 MJRoberts - Creation
*/
#include "vmbifreg.h"
/* ------------------------------------------------------------------------ */
/*
* Include the function set vector definitions. Define
* VMBIF_DEFINE_VECTOR so that the headers all generate vector
* definitions.
*/
#define VMBIF_DEFINE_VECTOR
#include "vmbiftad.h"
#include "vmbiftio.h"
#include "vmbift3.h"
#include "vmbifnet.h"
// !!! INCLUDE HOST-SPECIFIC FUNCTION SET HEADERS HERE ("vmbifxxx.h")
/* done with the vector definition */
#undef VMBIF_DEFINE_VECTOR
#define MAKE_ENTRY(entry_name, cls) \
{ entry_name, countof(cls::bif_table), cls::bif_table, \
&cls::attach, &cls::detach }
/* ------------------------------------------------------------------------ */
/*
* The function set registration table. Each entry in the table
* provides the definition of one function set, keyed by the function
* set's universally unique identifier.
*/
vm_bif_entry_t G_bif_reg_table[] =
{
/* T3 VM system function set, v1 */
MAKE_ENTRY("t3vm/010006", CVmBifT3),
/* T3 VM Testing interface, v1 */
MAKE_ENTRY("t3vmTEST/010000", CVmBifT3Test),
/* TADS generic data manipulation functions */
MAKE_ENTRY("tads-gen/030008", CVmBifTADS),
/* TADS input/output functions */
MAKE_ENTRY("tads-io/030007", CVmBifTIO),
/* TADS input/output functions */
MAKE_ENTRY("tads-net/030001", CVmBifNet),
// !!! ADD ANY HOST-SPECIFIC FUNCTION SETS HERE
/* end of table marker */
{ 0, 0, 0 }
};
/* we don't need the MAKE_ENTRY macro any longer */
#undef MAKE_ENTRY
| gpl-3.0 |
TheBigBear/openpetra | csharp/ICT/Petra/Tools/FinanceGDPdUExportIncomeTax/workers.cs | 6119 | //
// DO NOT REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
//
// @Authors:
// timop
//
// Copyright 2004-2015 by OM International
//
// This file is part of OpenPetra.org.
//
// OpenPetra.org is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// OpenPetra.org 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 OpenPetra.org. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Data;
using System.Data.Odbc;
using System.Configuration;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Ict.Petra.Shared.MFinance.Account.Data;
using Ict.Petra.Shared.MPartner.Partner.Data;
using Ict.Petra.Shared.MPersonnel.Personnel.Data;
using Ict.Testing.NUnitPetraServer;
using Ict.Common;
using Ict.Common.DB;
using Ict.Common.Data;
using Ict.Petra.Shared.MFinance;
using Ict.Petra.Server.MFinance.GL.WebConnectors;
namespace Ict.Petra.Tools.MFinance.Server.GDPdUExportIncomeTax
{
/// This will export the finance data for the tax office, according to GDPdU
public class TGDPdUExportWorkers
{
/// <summary>
/// export all details of workers in this year
/// </summary>
public static void Export(string AOutputPath,
char ACSVSeparator,
string ANewLine,
Int64 SiteKey,
Int32 AYear)
{
string filename = Path.GetFullPath(Path.Combine(AOutputPath, "angestellte.csv"));
Console.WriteLine("Writing file: " + filename);
StringBuilder sb = new StringBuilder();
PmStaffDataTable staffdata = new PmStaffDataTable();
PPartnerTable partners = new PPartnerTable();
partners.Constraints.Clear();
PPersonTable persons = new PPersonTable();
persons.Constraints.Clear();
TDBTransaction Transaction = null;
DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction,
delegate
{
// get all partners with a commitment period for this date range
// ignore non-native workers. field must be home office, or receiving field
string sql =
String.Format(
"SELECT * FROM PUB_pm_staff_data s, PUB_p_partner p, PUB_p_person per " +
"WHERE p.p_partner_key_n = s.p_partner_key_n " +
"AND (s.pm_home_office_n = ? OR pm_receiving_field_office_n = ? OR pm_receiving_field_n = ?) " +
"AND per.p_partner_key_n = s.p_partner_key_n " +
// start of commitment during this year
"AND ((pm_start_of_commitment_d BETWEEN ? AND ?) " +
// start of commitment before this year, end of commitment null or during/after this year
" OR (pm_start_of_commitment_d < ? AND (pm_start_of_commitment_d IS NULL OR pm_start_of_commitment_d >= ?)))");
List <OdbcParameter>Parameters = new List <OdbcParameter>();
OdbcParameter param;
param = new OdbcParameter("field", OdbcType.Numeric);
param.Value = SiteKey;
Parameters.Add(param);
param = new OdbcParameter("field", OdbcType.Numeric);
param.Value = SiteKey;
Parameters.Add(param);
param = new OdbcParameter("field", OdbcType.Numeric);
param.Value = SiteKey;
Parameters.Add(param);
param = new OdbcParameter("startdate", OdbcType.DateTime);
param.Value = new DateTime(AYear, 1, 1);
Parameters.Add(param);
param = new OdbcParameter("enddate", OdbcType.DateTime);
param.Value = new DateTime(AYear, 12, 31);
Parameters.Add(param);
param = new OdbcParameter("startdate", OdbcType.DateTime);
param.Value = new DateTime(AYear, 1, 1);
Parameters.Add(param);
param = new OdbcParameter("startdate", OdbcType.DateTime);
param.Value = new DateTime(AYear, 1, 1);
Parameters.Add(param);
DBAccess.GDBAccessObj.SelectDT(staffdata, sql.Replace("SELECT *", "SELECT s.*"), Transaction, Parameters.ToArray(), 0, 0);
DBAccess.GDBAccessObj.SelectDT(partners, sql.Replace("SELECT *", "SELECT p.*"), Transaction, Parameters.ToArray(), 0, 0);
DBAccess.GDBAccessObj.SelectDT(persons, sql.Replace("SELECT *", "SELECT per.*"), Transaction, Parameters.ToArray(), 0, 0);
});
foreach (PmStaffDataRow staff in staffdata.Rows)
{
partners.DefaultView.Sort = "p_partner_key_n";
persons.DefaultView.Sort = "p_partner_key_n";
PPartnerRow partner = (PPartnerRow)partners.DefaultView.FindRows(new object[] { staff.PartnerKey })[0].Row;
PPersonRow person = (PPersonRow)persons.DefaultView.FindRows(new object[] { staff.PartnerKey })[0].Row;
sb.Append(StringHelper.StrMerge(
new string[] {
partner.PartnerKey.ToString(),
partner.PartnerShortName.ToString(),
person.DateOfBirth.HasValue?person.DateOfBirth.Value.ToString("yyyyMMdd"):String.Empty,
partner.PartnerKey.ToString()
}, ACSVSeparator));
sb.Append(ANewLine);
}
StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding(1252));
sw.Write(sb.ToString());
sw.Close();
}
}
}
| gpl-3.0 |
Stiivi/vvo-reports | sandbox/create_dimnesion_index.rb | 1892 | require 'rubygems'
require 'brewery'
class Tool
include Brewery
def initialize_brewery
Brewery::load_default_configuration
Brewery::create_default_workspace(:vvo_data)
@workspace = Brewery::workspace
puts "WS: #{@workspace} CONN: #{@workspace.connection}"
@index_table = :idx_dimensions
end
def initialize_table
@workspace.connection << "DROP TABLE IF EXISTS #{@index_table.to_s}"
@workspace.connection.create_table(@index_table) do
primary_key :id
column :dimension, :varchar
column :dimension_id, :integer
column :level, :varchar
column :level_id, :integer
column :level_key, :varchar
column :field, :varchar
column :value, :text
end
end
def index_dimension(dimension)
puts "==> indexing dimension #{dimension.name}"
levels = dimension.levels
levels.each { |level|
puts "--> indexing level #{level.name} (#{level.id})"
level.level_fields.each { |field|
puts "--- field #{field}"
# begin
index_field(dimension, level, field)
# rescue
# puts "!!! unable to index field #{field}"
# end
}
}
end
def index_field(dimension, level, field)
query = @cube.create_star_query
query.create_dimension_field_index(@index_table, dimension, level, field)
end
def run
initialize_brewery
initialize_table
@model_name = "verejne_obstaravania"
model = Brewery::LogicalModel.model_with_name(@model_name)
@cube = model.cube_with_name('zmluvy')
if ! model
raise "No model '#{@model_name}'"
return
end
if ! @cube
raise "No cube 'zmluvy'"
return
end
puts "Indexing #{model.dimensions.count} dimensions"
@cube.dimensions.each { |dim|
index_dimension(dim)
}
end
end # class
tool = Tool.new
tool.run
# end # module Brewery | gpl-3.0 |
PanuWeb/espocrm | client/src/views/fields/enum-int.js | 2009 | /************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2017 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
Espo.define('views/fields/enum-int', 'views/fields/enum', function (Dep) {
return Dep.extend({
type: 'enumInt',
listTemplate: 'fields/enum/detail',
detailTemplate: 'fields/enum/detail',
editTemplate: 'fields/enum/edit',
searchTemplate: 'fields/enum/search',
validations: [],
fetch: function () {
var value = parseInt(this.$el.find('[name="' + this.name + '"]').val());
var data = {};
data[this.name] = value;
return data;
},
parseItemForSearch: function (item) {
return parseInt(item);
}
});
});
| gpl-3.0 |
fwahyudi17/ofiskita | catalog/language/english/product/adv_ajaxfilter.php | 702 | <?php
// Heading
$_['heading_title'] = 'Filter Results';
// Text
$_['text_display'] = 'Display:';
$_['text_list'] = 'List';
$_['text_grid'] = 'Grid';
$_['text_sort'] = 'Sort By:';
$_['text_default'] = 'Default';
$_['text_name_asc'] = 'Name (A - Z)';
$_['text_name_desc'] = 'Name (Z - A)';
$_['text_price_asc'] = 'Price (Low > High)';
$_['text_price_desc'] = 'Price (High > Low)';
$_['text_rating_asc'] = 'Rating (Lowest)';
$_['text_rating_desc'] = 'Rating (Highest)';
$_['text_model_asc'] = 'Model (A - Z)';
$_['text_model_desc'] = 'Model (Z - A)';
$_['text_limit'] = 'Show:';
$_['text_compare'] = 'Product Compare (%s)';
?> | gpl-3.0 |
OnroerendErfgoed/urihandler | tests/conftest.py | 1190 | import pytest
from urihandler.handler import UriHandler
@pytest.fixture(scope="session")
def handlerconfig():
cfg = {
"uris": [
{
"match": r"^/foobar/(?P<id>\d+)$",
"mount": True,
"redirect": "http://localhost:5555/foobar/{id}",
},
{
"match": r"^/bar/(?P<name>\w+)$",
"redirect": "http://localhost:5555/bar/{name}",
},
{
"match": r"^urn:x-barbar:(?P<namespace>\w+):(?P<id>\d+)$",
"mount": False,
"redirect": "http://localhost:2222/{namespace}/{id}",
},
{
"match": r"override/(?P<namespace>\w+)/(?P<id>\d+)$",
"redirect": "http://localhost:2222/{namespace}/{id}",
},
{
"match": r"^/foo/(?P<foo_id>\d+)/bar/(?P<bar_id>\d+)$",
"mount": True,
"redirect": "http://localhost:5555/foo/{foo_id}/bar/{bar_id}",
},
]
}
return cfg
@pytest.fixture(scope="session")
def urihandler(handlerconfig):
return UriHandler(handlerconfig["uris"])
| gpl-3.0 |
sea75300/fanpresscm3 | inc/lang/en/users.php | 1687 | <?php
/**
* System options language file
* @author Stefan Seehafer <sea75300@yahoo.de>
* @copyright (c) 2011-2017, Stefan Seehafer
* @license http://www.gnu.org/licenses/gpl.txt GPLv3
*/
$lang = array(
'USERS_DISPLAYNAME' => 'Display name',
'USERS_PASSWORD_CONFIRM' => 'Confirm password',
'USERS_REQUIREMENTS' => 'Password requires at least six digits including upper and lower case letters and numbers',
'USERS_ROLL' => 'Roll',
'USERS_BIOGRAPHY' => 'Biography / Other',
'USERS_AVATAR' => 'Avatar',
'USERS_REGISTEREDTIME' => 'Registered on',
'USERS_ARTICLE_COUNT' => 'Article count',
'USERS_LIST_ACTIVE' => 'Active Users',
'USERS_LIST_DISABLED' => 'Disabled Users',
'USERS_LIST_ROLLS' => 'User Rolls',
'USERS_ROLLS_NAME' => 'Roll name',
'USERS_ROLLS_PERMISSIONS' => 'Edit roll permissions',
'USERS_ADD' => 'Create user',
'USERS_EDIT' => 'Edit user',
'USERS_ROLL_ADD' => 'Create user roll',
'USERS_ROLL_EDIT' => 'Edit user roll',
'USERS_META_OPTIONS' => 'User settings',
'USERS_PASSGEN' => 'Generate password',
'USERS_ARTICLES_SELECT' => 'Please select what to do with articles of the selected user',
'USERS_ARTICLES_USER' => 'Select user',
'USERS_ARTICLES_LIST' => [
'Don\'t perform any action' => '',
'Delete articles' => 'delete',
'Move articles to' => 'move'
]
); | gpl-3.0 |
alexeykish/aircompany-spring | entities/src/main/java/by/pvt/kish/aircompany/pojos/Plane.java | 4107 | package by.pvt.kish.aircompany.pojos;
import by.pvt.kish.aircompany.enums.PlaneStatus;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Set;
/**
* This class represents the Plane model.
* The plane is used for Flight.
* The plane is characterized by passenger capacity of <code>capacity</code> and a flight range of <code>range</code>
* For service flights on a particular aircraft,
* flight crew should consist of particular number of professionals (pilots, navigators, radiooperators, stewardesses).
* These amounts are described by Map <code>team</code>
* This model class can be used throughout all
* layers, the data layer, the controller layer and the view layer.
*
* @author Kish Alexey
*/
@Entity
public class Plane implements Serializable {
@Id
@GeneratedValue
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
private Long pid;
@Column(nullable = false)
@NotEmpty()
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
private String model;
@Column(nullable = false)
@NotNull()
@Min(value = 0)
public Integer getCapacity() {
return capacity;
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
private Integer capacity;
@Column(nullable = false)
@NotNull()
@Min(value = 0)
public Integer getFlightRange() {
return flightRange;
}
public void setFlightRange(Integer flightRange) {
this.flightRange = flightRange;
}
private Integer flightRange;
@OneToMany(mappedBy = "plane")
public Set<Flight> getFlights() {
return flights;
}
public void setFlights(Set<Flight> flights) {
this.flights = flights;
}
private Set<Flight> flights;
@Enumerated(EnumType.STRING)
@Column(columnDefinition = "enum('AVAILABLE','MAINTENANCE','BLOCKED')")
public PlaneStatus getStatus() {
return status;
}
public void setStatus(PlaneStatus status) {
this.status = status;
}
private PlaneStatus status = PlaneStatus.AVAILABLE;
@OneToOne(mappedBy = "plane", cascade=CascadeType.ALL)
@Valid
public PlaneCrew getPlaneCrew() {
return planeCrew;
}
public void setPlaneCrew(PlaneCrew crew) {
this.planeCrew = crew;
}
private PlaneCrew planeCrew;
public Plane() {
}
/**
* @param model - plane model
* @param capacity - plane passenger capacity
* @param flightRange - plane flight range
*/
public Plane(String model, int capacity, int flightRange) {
this.model = model;
this.capacity = capacity;
this.flightRange = flightRange;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Plane plane = (Plane) o;
if (pid != null ? !pid.equals(plane.pid) : plane.pid != null) return false;
if (model != null ? !model.equals(plane.model) : plane.model != null) return false;
return capacity != null ? capacity.equals(plane.capacity) : plane.capacity == null;
}
@Override
public int hashCode() {
int result = pid != null ? pid.hashCode() : 0;
result = 31 * result + (model != null ? model.hashCode() : 0);
result = 31 * result + (capacity != null ? capacity.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Plane{" +
"pid=" + pid +
", model='" + model + '\'' +
", capacity=" + capacity +
", flightRange=" + flightRange +
", status=" + status +
", planeCrew=" + planeCrew +
'}';
}
}
| gpl-3.0 |
olivettikatz/libincandescence | util/Util.cpp | 497 | #include "util.h"
namespace incandescence
{
bool fileExists(string path)
{
ifstream file(path.c_str(), ios::in);
if (file.is_open())
{
file.close();
return true;
}
else
{
return false;
}
}
string loadFile(string path)
{
ifstream file(path.c_str(), ios::in);
if (file.is_open())
{
string page((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
return page;
}
else
{
INCD_ERROR("could not open file: " << path);
return "";
}
}
} | gpl-3.0 |
TonyClark/ESL | src_before_threads/ast/patterns/PWild.java | 1298 | package ast.patterns;
import java.util.HashSet;
import java.util.Vector;
import java.util.function.BiConsumer;
import ast.AST;
import ast.binding.Var;
import ast.binding.declarations.DeclaringLocation;
import ast.data.Apply;
import ast.data.Fun;
import ast.refs.Ref;
import ast.types.Type;
import compiler.DynamicVar;
import compiler.FrameVar;
import env.Env;
import list.List;
import runtime.functions.CodeBox;
public class PWild extends Pattern {
public void vars(HashSet<String> vars) {
}
public void bound(Vector<String> vars) {
}
public String toString() {
return "PWild()";
}
public void compile(List<FrameVar> locals, List<DynamicVar> dynamics, Ref ref, CodeBox code) {
}
public void type(Env<String, Type> env, BiConsumer<Env<String, Type>, Type> cont) {
setType(ast.types.Void.VOID);
cont.accept(env, ast.types.Void.VOID);
}
public Env<String, Type> bind(Env<String, Type> env, Type type) {
return env;
}
public Type getDeclaredType() {
// A wildcard pattern should declare its type.
return ast.types.Void.VOID;
}
public void processDeclarations(Env<String, Type> env) {
}
public DeclaringLocation[] getContainedDecs() {
return new DeclaringLocation[] {};
}
public String pprint() {
return "_";
}
}
| gpl-3.0 |
reasonablegraph/webapp | app/lib/graph/rules/GRuleRemoveInference.php | 255 | <?php
class GRuleRemoveInference extends AbstractBaseRule implements GRule {
public function execute(){
// error_log("REMOVe INFERENCE");
Log::info("REMOVe INFERENCE");
$graph = $this->context->graph();
$graph->removeInferredEdges();
}
}
| gpl-3.0 |