repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
leo-the-manic/django-combinedform | combinedform/__init__.py | 424 | from .combinedform import (
CombinedForm,
CombinedFormMetaclass,
FieldValidationError,
Subform,
SubformError,
extract_subform_args,
get_model_dependencies,
order_by_dependency,
)
__all__ = [
'CombinedForm',
'CombinedFormMetaclass',
'FieldValidationError',
'Subform',
'SubformError',
'extract_subform_args',
'get_model_dependencies',
'order_by_dependency',
]
| lgpl-3.0 |
gabrielmueller/aljebra-topo | Algebra/src/module/VectorSpace.java | 163 | package module;
import field.AbstractField;
public interface VectorSpace<V extends VectorSpace<V, F>, F extends AbstractField<F>>
extends CommModule<V, F> {
}
| lgpl-3.0 |
SIM-TU-Darmstadt/mbslib | src/mbslib/elements/drive/PassiveSpringDamperDrive.cpp | 1917 | /*
* Copyright (C) 2015
* Simulation, Systems Optimization and Robotics Group (SIM)
* Technische Universitaet Darmstadt
* Hochschulstr. 10
* 64289 Darmstadt, Germany
* www.sim.tu-darmstadt.de
*
* This file is part of the MBSlib.
* All rights are reserved by the copyright holder.
*
* MBSlib is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation in version 3 of the License.
*
* The MBSlib is distributed WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with MBSlib. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file mbslib/elements/drive/PassiveSpringDamperDrive.cpp
* Definition of mbslib ::PassiveSpringDamperDrive
*/
#include <mbslib/elements/drive/PassiveSpringDamperDrive.hpp>
using namespace mbslib;
PassiveSpringDamperDrive::PassiveSpringDamperDrive(Joint1DOF & joint, TScalar springCoeff_, TScalar damperCoeff_, const std::string & name)
: PassiveDrive(joint, name)
, springCoeff(springCoeff_)
, damperCoeff(damperCoeff_) {
}
void PassiveSpringDamperDrive::doForwardDrive() {
TScalar springEffort;
springEffort = -springCoeff * (attachedJoint->getJointState().q) - damperCoeff * (attachedJoint->getJointState().dotq);
attachedJoint->setJointForceTorque(springEffort);
}
void PassiveSpringDamperDrive::doInverseDrive() {
TScalar springEffort;
springEffort = -springCoeff * (attachedJoint->getJointState().q) - damperCoeff * (attachedJoint->getJointState().dotq);
attachedJoint->setJointForceTorque(attachedJoint->getJointForceTorque() - springEffort);
}
PassiveSpringDamperDrive::~PassiveSpringDamperDrive() {
}
| lgpl-3.0 |
besley/Slickflow | NETCORE/Slickflow/Source/Slickflow.Engine/Xpdl/Entity/ActionEntity.cs | 2312 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Slickflow.Engine.Xpdl.Common;
namespace Slickflow.Engine.Xpdl.Entity
{
/// <summary>
/// 操作实体
/// </summary>
public class ActionEntity
{
#region 属性列表
/// <summary>
/// 操作类型
/// </summary>
public ActionTypeEnum ActionType { get; set; }
/// <summary>
/// 事件触发类型
/// </summary>
public FireTypeEnum FireType { get; set; }
/// <summary>
/// 方法类型
/// </summary>
public ActionMethodEnum ActionMethod { get; set; }
/// <summary>
/// 子方法类型
/// </summary>
public SubMethodEnum SubMethod { get; set; }
/// <summary>
/// 参数列表
/// </summary>
public string Arguments { get; set; }
/// <summary>
/// 表达式
/// </summary>
public string Expression { get; set; }
/// <summary>
/// 反射方法配置信息
/// </summary>
public MethodInfo MethodInfo { get; set; }
/// <summary>
/// 文本脚本代码
/// </summary>
public CodeInfo CodeInfo { get; set; }
#endregion
}
/// <summary>
/// 反射组件方法
/// </summary>
public class MethodInfo
{
/// <summary>
/// Assembly Full Name
/// </summary>
public string AssemblyFullName { get; set; }
/// <summary>
/// Class Full Name
/// </summary>
public string TypeFullName { get; set; }
/// <summary>
/// Class Constructor Parameter
/// </summary>
public object[] ConstructorParameters { get; set; }
/// <summary>
/// Method Name
/// </summary>
public string MethodName { get; set; }
/// <summary>
/// Method Parameters
/// </summary>
public object[] MethodParameters { get; set; }
}
/// <summary>
/// Code Info
/// </summary>
public class CodeInfo
{
/// <summary>
/// Code Script Text
/// </summary>
public string CodeText { get; set; }
}
}
| lgpl-3.0 |
nebulasio/go-nebulas | nbre/common/math/softfloat.cpp | 2107 | // Copyright (C) 2018 go-nebulas authors
//
// This file is part of the go-nebulas library.
//
// the go-nebulas 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.
//
// the go-nebulas 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 go-nebulas library. If not, see
// <http://www.gnu.org/licenses/>.
//
#include "common/math/softfloat.hpp"
#include <glog/logging.h>
#include <sstream>
/*----------------------------------------------------------------------------
| Software floating-point exception flags.
| extern THREAD_LOCAL uint_fast8_t softfloat_exceptionFlags;
| enum {
| softfloat_flag_inexact = 1,
| softfloat_flag_underflow = 2,
| softfloat_flag_overflow = 4,
| softfloat_flag_infinite = 8,
| softfloat_flag_invalid = 16
| };
*----------------------------------------------------------------------------*/
void softfloat_raiseFlags(uint_fast8_t exception_flag) {
std::stringstream ss;
ss << "raise flag: " << static_cast<int>(exception_flag)
<< ", softfloat exception: ";
uint_fast8_t flag = 0x10;
while (flag) {
switch (flag & exception_flag) {
case softfloat_flag_inexact:
ss << "inexact ";
break;
case softfloat_flag_underflow:
ss << "underflow ";
break;
case softfloat_flag_overflow:
ss << "overflow ";
break;
case softfloat_flag_infinite:
ss << "infinite ";
break;
case softfloat_flag_invalid:
ss << "invalid ";
break;
default:
break;
}
flag >>= 1;
}
LOG(INFO) << ss.str();
// ignore softfloat exception
// throw std::runtime_error("softfloat exception");
}
| lgpl-3.0 |
sebkpp/TUIFramework | src/TUIPluginsDLL/xcontroller/TUILibXControllerDLL.cpp | 117 | // TUILibXControllerDLL.cpp : Definiert die exportierten Funktionen für die DLL-Anwendung.
//
#include "stdafx.h"
| lgpl-3.0 |
urbanmassage/hata | forbidden.ts | 243 | import HataError = require('./hata');
class ForbiddenError<T> extends HataError<T> {
httpCode = 403;
name = 'ForbiddenError';
constructor(message: string = 'Access forbidden', obj?: T) {super(message, obj);}
}
export = ForbiddenError;
| lgpl-3.0 |
xenioplatform/go-xenio | bmt/bmt.go | 15514 | // Copyright 2017 The go-xenio Authors
// Copyright 2017 The go-ethereum Authors
//
// This file is part of the go-xenio library.
//
// The go-xenio library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-xenio library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-xenio library. If not, see <http://www.gnu.org/licenses/>.
// Package bmt provides a binary merkle tree implementation
package bmt
import (
"fmt"
"hash"
"io"
"strings"
"sync"
"sync/atomic"
)
/*
Binary Merkle Tree Hash is a hash function over arbitrary datachunks of limited size
It is defined as the root hash of the binary merkle tree built over fixed size segments
of the underlying chunk using any base hash function (e.g keccak 256 SHA3)
It is used as the chunk hash function in swarm which in turn is the basis for the
128 branching swarm hash http://swarm-guide.readthedocs.io/en/latest/architecture.html#swarm-hash
The BMT is optimal for providing compact inclusion proofs, i.e. prove that a
segment is a substring of a chunk starting at a particular offset
The size of the underlying segments is fixed at 32 bytes (called the resolution
of the BMT hash), the EVM word size to optimize for on-chain BMT verification
as well as the hash size optimal for inclusion proofs in the merkle tree of the swarm hash.
Two implementations are provided:
* RefHasher is optimized for code simplicity and meant as a reference implementation
* Hasher is optimized for speed taking advantage of concurrency with minimalistic
control structure to coordinate the concurrent routines
It implements the ChunkHash interface as well as the go standard hash.Hash interface
*/
const (
// DefaultSegmentCount is the maximum number of segments of the underlying chunk
DefaultSegmentCount = 128 // Should be equal to storage.DefaultBranches
// DefaultPoolSize is the maximum number of bmt trees used by the hashers, i.e,
// the maximum number of concurrent BMT hashing operations performed by the same hasher
DefaultPoolSize = 8
)
// BaseHasher is a hash.Hash constructor function used for the base hash of the BMT.
type BaseHasher func() hash.Hash
// Hasher a reusable hasher for fixed maximum size chunks representing a BMT
// implements the hash.Hash interface
// reuse pool of Tree-s for amortised memory allocation and resource control
// supports order-agnostic concurrent segment writes
// as well as sequential read and write
// can not be called concurrently on more than one chunk
// can be further appended after Sum
// Reset gives back the Tree to the pool and guaranteed to leave
// the tree and itself in a state reusable for hashing a new chunk
type Hasher struct {
pool *TreePool // BMT resource pool
bmt *Tree // prebuilt BMT resource for flowcontrol and proofs
blocksize int // segment size (size of hash) also for hash.Hash
count int // segment count
size int // for hash.Hash same as hashsize
cur int // cursor position for righmost currently open chunk
segment []byte // the rightmost open segment (not complete)
depth int // index of last level
result chan []byte // result channel
hash []byte // to record the result
max int32 // max segments for SegmentWriter interface
blockLength []byte // The block length that needes to be added in Sum
}
// New creates a reusable Hasher
// implements the hash.Hash interface
// pulls a new Tree from a resource pool for hashing each chunk
func New(p *TreePool) *Hasher {
return &Hasher{
pool: p,
depth: depth(p.SegmentCount),
size: p.SegmentSize,
blocksize: p.SegmentSize,
count: p.SegmentCount,
result: make(chan []byte),
}
}
// Node is a reuseable segment hasher representing a node in a BMT
// it allows for continued writes after a Sum
// and is left in completely reusable state after Reset
type Node struct {
level, index int // position of node for information/logging only
initial bool // first and last node
root bool // whether the node is root to a smaller BMT
isLeft bool // whether it is left side of the parent double segment
unbalanced bool // indicates if a node has only the left segment
parent *Node // BMT connections
state int32 // atomic increment impl concurrent boolean toggle
left, right []byte
}
// NewNode constructor for segment hasher nodes in the BMT
func NewNode(level, index int, parent *Node) *Node {
return &Node{
parent: parent,
level: level,
index: index,
initial: index == 0,
isLeft: index%2 == 0,
}
}
// TreePool provides a pool of Trees used as resources by Hasher
// a Tree popped from the pool is guaranteed to have clean state
// for hashing a new chunk
// Hasher Reset releases the Tree to the pool
type TreePool struct {
lock sync.Mutex
c chan *Tree
hasher BaseHasher
SegmentSize int
SegmentCount int
Capacity int
count int
}
// NewTreePool creates a Tree pool with hasher, segment size, segment count and capacity
// on GetTree it reuses free Trees or creates a new one if size is not reached
func NewTreePool(hasher BaseHasher, segmentCount, capacity int) *TreePool {
return &TreePool{
c: make(chan *Tree, capacity),
hasher: hasher,
SegmentSize: hasher().Size(),
SegmentCount: segmentCount,
Capacity: capacity,
}
}
// Drain drains the pool uptil it has no more than n resources
func (self *TreePool) Drain(n int) {
self.lock.Lock()
defer self.lock.Unlock()
for len(self.c) > n {
<-self.c
self.count--
}
}
// Reserve is blocking until it returns an available Tree
// it reuses free Trees or creates a new one if size is not reached
func (self *TreePool) Reserve() *Tree {
self.lock.Lock()
defer self.lock.Unlock()
var t *Tree
if self.count == self.Capacity {
return <-self.c
}
select {
case t = <-self.c:
default:
t = NewTree(self.hasher, self.SegmentSize, self.SegmentCount)
self.count++
}
return t
}
// Release gives back a Tree to the pool.
// This Tree is guaranteed to be in reusable state
// does not need locking
func (self *TreePool) Release(t *Tree) {
self.c <- t // can never fail but...
}
// Tree is a reusable control structure representing a BMT
// organised in a binary tree
// Hasher uses a TreePool to pick one for each chunk hash
// the Tree is 'locked' while not in the pool
type Tree struct {
leaves []*Node
}
// Draw draws the BMT (badly)
func (self *Tree) Draw(hash []byte, d int) string {
var left, right []string
var anc []*Node
for i, n := range self.leaves {
left = append(left, fmt.Sprintf("%v", hashstr(n.left)))
if i%2 == 0 {
anc = append(anc, n.parent)
}
right = append(right, fmt.Sprintf("%v", hashstr(n.right)))
}
anc = self.leaves
var hashes [][]string
for l := 0; len(anc) > 0; l++ {
var nodes []*Node
hash := []string{""}
for i, n := range anc {
hash = append(hash, fmt.Sprintf("%v|%v", hashstr(n.left), hashstr(n.right)))
if i%2 == 0 && n.parent != nil {
nodes = append(nodes, n.parent)
}
}
hash = append(hash, "")
hashes = append(hashes, hash)
anc = nodes
}
hashes = append(hashes, []string{"", fmt.Sprintf("%v", hashstr(hash)), ""})
total := 60
del := " "
var rows []string
for i := len(hashes) - 1; i >= 0; i-- {
var textlen int
hash := hashes[i]
for _, s := range hash {
textlen += len(s)
}
if total < textlen {
total = textlen + len(hash)
}
delsize := (total - textlen) / (len(hash) - 1)
if delsize > len(del) {
delsize = len(del)
}
row := fmt.Sprintf("%v: %v", len(hashes)-i-1, strings.Join(hash, del[:delsize]))
rows = append(rows, row)
}
rows = append(rows, strings.Join(left, " "))
rows = append(rows, strings.Join(right, " "))
return strings.Join(rows, "\n") + "\n"
}
// NewTree initialises the Tree by building up the nodes of a BMT
// segment size is stipulated to be the size of the hash
// segmentCount needs to be positive integer and does not need to be
// a power of two and can even be an odd number
// segmentSize * segmentCount determines the maximum chunk size
// hashed using the tree
func NewTree(hasher BaseHasher, segmentSize, segmentCount int) *Tree {
n := NewNode(0, 0, nil)
n.root = true
prevlevel := []*Node{n}
// iterate over levels and creates 2^level nodes
level := 1
count := 2
for d := 1; d <= depth(segmentCount); d++ {
nodes := make([]*Node, count)
for i := 0; i < len(nodes); i++ {
var parent *Node
parent = prevlevel[i/2]
t := NewNode(level, i, parent)
nodes[i] = t
}
prevlevel = nodes
level++
count *= 2
}
// the datanode level is the nodes on the last level where
return &Tree{
leaves: prevlevel,
}
}
// methods needed by hash.Hash
// Size returns the size
func (self *Hasher) Size() int {
return self.size
}
// BlockSize returns the block size
func (self *Hasher) BlockSize() int {
return self.blocksize
}
// Sum returns the hash of the buffer
// hash.Hash interface Sum method appends the byte slice to the underlying
// data before it calculates and returns the hash of the chunk
func (self *Hasher) Sum(b []byte) (r []byte) {
t := self.bmt
i := self.cur
n := t.leaves[i]
j := i
// must run strictly before all nodes calculate
// datanodes are guaranteed to have a parent
if len(self.segment) > self.size && i > 0 && n.parent != nil {
n = n.parent
} else {
i *= 2
}
d := self.finalise(n, i)
self.writeSegment(j, self.segment, d)
c := <-self.result
self.releaseTree()
// sha3(length + BMT(pure_chunk))
if self.blockLength == nil {
return c
}
res := self.pool.hasher()
res.Reset()
res.Write(self.blockLength)
res.Write(c)
return res.Sum(nil)
}
// Hasher implements the SwarmHash interface
// Hash waits for the hasher result and returns it
// caller must call this on a BMT Hasher being written to
func (self *Hasher) Hash() []byte {
return <-self.result
}
// Hasher implements the io.Writer interface
// Write fills the buffer to hash
// with every full segment complete launches a hasher go routine
// that shoots up the BMT
func (self *Hasher) Write(b []byte) (int, error) {
l := len(b)
if l <= 0 {
return 0, nil
}
s := self.segment
i := self.cur
count := (self.count + 1) / 2
need := self.count*self.size - self.cur*2*self.size
size := self.size
if need > size {
size *= 2
}
if l < need {
need = l
}
// calculate missing bit to complete current open segment
rest := size - len(s)
if need < rest {
rest = need
}
s = append(s, b[:rest]...)
need -= rest
// read full segments and the last possibly partial segment
for need > 0 && i < count-1 {
// push all finished chunks we read
self.writeSegment(i, s, self.depth)
need -= size
if need < 0 {
size += need
}
s = b[rest : rest+size]
rest += size
i++
}
self.segment = s
self.cur = i
// otherwise, we can assume len(s) == 0, so all buffer is read and chunk is not yet full
return l, nil
}
// Hasher implements the io.ReaderFrom interface
// ReadFrom reads from io.Reader and appends to the data to hash using Write
// it reads so that chunk to hash is maximum length or reader reaches EOF
// caller must Reset the hasher prior to call
func (self *Hasher) ReadFrom(r io.Reader) (m int64, err error) {
bufsize := self.size*self.count - self.size*self.cur - len(self.segment)
buf := make([]byte, bufsize)
var read int
for {
var n int
n, err = r.Read(buf)
read += n
if err == io.EOF || read == len(buf) {
hash := self.Sum(buf[:n])
if read == len(buf) {
err = NewEOC(hash)
}
break
}
if err != nil {
break
}
n, err = self.Write(buf[:n])
if err != nil {
break
}
}
return int64(read), err
}
// Reset needs to be called before writing to the hasher
func (self *Hasher) Reset() {
self.getTree()
self.blockLength = nil
}
// Hasher implements the SwarmHash interface
// ResetWithLength needs to be called before writing to the hasher
// the argument is supposed to be the byte slice binary representation of
// the legth of the data subsumed under the hash
func (self *Hasher) ResetWithLength(l []byte) {
self.Reset()
self.blockLength = l
}
// Release gives back the Tree to the pool whereby it unlocks
// it resets tree, segment and index
func (self *Hasher) releaseTree() {
if self.bmt != nil {
n := self.bmt.leaves[self.cur]
for ; n != nil; n = n.parent {
n.unbalanced = false
if n.parent != nil {
n.root = false
}
}
self.pool.Release(self.bmt)
self.bmt = nil
}
self.cur = 0
self.segment = nil
}
func (self *Hasher) writeSegment(i int, s []byte, d int) {
h := self.pool.hasher()
n := self.bmt.leaves[i]
if len(s) > self.size && n.parent != nil {
go func() {
h.Reset()
h.Write(s)
s = h.Sum(nil)
if n.root {
self.result <- s
return
}
self.run(n.parent, h, d, n.index, s)
}()
return
}
go self.run(n, h, d, i*2, s)
}
func (self *Hasher) run(n *Node, h hash.Hash, d int, i int, s []byte) {
isLeft := i%2 == 0
for {
if isLeft {
n.left = s
} else {
n.right = s
}
if !n.unbalanced && n.toggle() {
return
}
if !n.unbalanced || !isLeft || i == 0 && d == 0 {
h.Reset()
h.Write(n.left)
h.Write(n.right)
s = h.Sum(nil)
} else {
s = append(n.left, n.right...)
}
self.hash = s
if n.root {
self.result <- s
return
}
isLeft = n.isLeft
n = n.parent
i++
}
}
// getTree obtains a BMT resource by reserving one from the pool
func (self *Hasher) getTree() *Tree {
if self.bmt != nil {
return self.bmt
}
t := self.pool.Reserve()
self.bmt = t
return t
}
// atomic bool toggle implementing a concurrent reusable 2-state object
// atomic addint with %2 implements atomic bool toggle
// it returns true if the toggler just put it in the active/waiting state
func (self *Node) toggle() bool {
return atomic.AddInt32(&self.state, 1)%2 == 1
}
func hashstr(b []byte) string {
end := len(b)
if end > 4 {
end = 4
}
return fmt.Sprintf("%x", b[:end])
}
func depth(n int) (d int) {
for l := (n - 1) / 2; l > 0; l /= 2 {
d++
}
return d
}
// finalise is following the zigzags on the tree belonging
// to the final datasegment
func (self *Hasher) finalise(n *Node, i int) (d int) {
isLeft := i%2 == 0
for {
// when the final segment's path is going via left segments
// the incoming data is pushed to the parent upon pulling the left
// we do not need toogle the state since this condition is
// detectable
n.unbalanced = isLeft
n.right = nil
if n.initial {
n.root = true
return d
}
isLeft = n.isLeft
n = n.parent
d++
}
}
// EOC (end of chunk) implements the error interface
type EOC struct {
Hash []byte // read the hash of the chunk off the error
}
// Error returns the error string
func (self *EOC) Error() string {
return fmt.Sprintf("hasher limit reached, chunk hash: %x", self.Hash)
}
// NewEOC creates new end of chunk error with the hash
func NewEOC(hash []byte) *EOC {
return &EOC{hash}
}
| lgpl-3.0 |
muk-it/muk_dms | muk_dms_lobject/tests/test_download.py | 1847 | ###################################################################################
#
# Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Documents Large Object
# (see https://mukit.at).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###################################################################################
import os
import time
import hmac
import base64
import hashlib
import logging
from odoo.http import request
from odoo.addons.muk_utils.tests import common
_path = os.path.dirname(os.path.dirname(__file__))
_logger = logging.getLogger(__name__)
class DownloadTestCase(common.HttpCase):
def test_attachment_download(self):
self.authenticate('admin', 'admin')
self.assertTrue(self.url_open('/web/lobject', data={
'field': 'content_lobject',
'filename_field': 'name',
'model': 'muk_dms.file',
'id': self.browse_ref("muk_dms.file_01_demo").id,
}, csrf=True))
self.assertTrue(self.url_open('/web/lobject', data={
'xmlid': 'muk_dms.file_01_demo',
'field': 'content_lobject',
'filename_field': 'name',
}, csrf=True))
| lgpl-3.0 |
dmitriyzhdankin/avantmarketcomua | wa-apps/site/lib/config/app.php | 406 | <?php
return array(
'name' => 'Site', // _w('Site')
'icon' => array(
48 => 'img/site.png',
24 => 'img/site24.png',
16 => 'img/site16.png'
),
'frontend' => true,
'version'=>'2.0.0',
'critical'=>'2.0.0',
'vendor' => 'webasyst',
'system' => true,
'rights' => true,
'themes' => true,
'pages' => true,
'auth' => true
); | lgpl-3.0 |
mkdgs/wkhtmltopdf | src/lib/reflect.cc | 3212 | // -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
// vi:set ts=4 sts=4 sw=4 noet :
//
// Copyright 2010, 2011 wkhtmltopdf authors
//
// This file is part of wkhtmltopdf.
//
// wkhtmltopdf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// wkhtmltopdf 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 Lesser General Public License
// along with wkhtmltopdf. If not, see <http://www.gnu.org/licenses/>.
#ifdef __WKHTMLTOX_UNDEF_QT_DLL__
#ifdef QT_DLL
#undef QT_DLL
#endif
#endif
#include "reflect.hh"
namespace wkhtmltopdf {
namespace settings {
bool ReflectSimple::set(const char * name, const QString & value) {
bool ok=false;
if (name[0]=='\0') set(value, &ok);
return ok;
}
QString ReflectClass::get(const char * name) {
int i=0;
while (name[i] !=0 && name[i] != '.' && name[i] != '[') ++i;
if (!elms.contains(QString::fromAscii(name, i))) return QString();
return elms[QString::fromAscii(name,i)]->get(name + (name[i] == '.'?i+1:i));
}
bool ReflectClass::set(const char * name, const QString & value) {
int i=0;
while (name[i] !=0 && name[i] != '.' && name[i] != '[') ++i;
if (!elms.contains(QString::fromAscii(name, i))) return false;
return elms[QString::fromAscii(name,i)]->set(name + (name[i] == '.'?i+1:i), value);
}
ReflectClass::~ReflectClass() {
for (QMap<QString, Reflect *>::iterator i=elms.begin(); i != elms.end(); ++i)
delete i.value();
}
ReflectImpl<LoadGlobal>::ReflectImpl(LoadGlobal & c) {
WKHTMLTOPDF_REFLECT(cookieJar);
}
ReflectImpl<LoadPage>::ReflectImpl(LoadPage & c) {
WKHTMLTOPDF_REFLECT(username);
WKHTMLTOPDF_REFLECT(password);
WKHTMLTOPDF_REFLECT(jsdelay);
WKHTMLTOPDF_REFLECT(windowStatus);
WKHTMLTOPDF_REFLECT(dumpHtml);
WKHTMLTOPDF_REFLECT(zoomFactor);
WKHTMLTOPDF_REFLECT(customHeaders);
WKHTMLTOPDF_REFLECT(repeatCustomHeaders);
WKHTMLTOPDF_REFLECT(cookies);
WKHTMLTOPDF_REFLECT(post);
WKHTMLTOPDF_REFLECT(blockLocalFileAccess);
WKHTMLTOPDF_REFLECT(allowed);
WKHTMLTOPDF_REFLECT(stopSlowScripts);
WKHTMLTOPDF_REFLECT(debugJavascript);
WKHTMLTOPDF_REFLECT(loadErrorHandling);
WKHTMLTOPDF_REFLECT(proxy);
WKHTMLTOPDF_REFLECT(runScript);
WKHTMLTOPDF_REFLECT(checkboxSvg);
WKHTMLTOPDF_REFLECT(checkboxCheckedSvg);
WKHTMLTOPDF_REFLECT(radiobuttonSvg);
WKHTMLTOPDF_REFLECT(radiobuttonCheckedSvg);
WKHTMLTOPDF_REFLECT(cacheDir);
}
ReflectImpl<Web>::ReflectImpl(Web & c) {
WKHTMLTOPDF_REFLECT(background);
WKHTMLTOPDF_REFLECT(loadImages);
WKHTMLTOPDF_REFLECT(enableJavascript);
WKHTMLTOPDF_REFLECT(enableIntelligentShrinking);
WKHTMLTOPDF_REFLECT(minimumFontSize);
WKHTMLTOPDF_REFLECT(printMediaType);
WKHTMLTOPDF_REFLECT(defaultEncoding);
WKHTMLTOPDF_REFLECT(userStyleSheet);
WKHTMLTOPDF_REFLECT(enablePlugins);
}
}
}
| lgpl-3.0 |
Grasia/phatsim | phat-bodies/src/main/java/phat/body/sensing/vision/VisibleObjectManager.java | 3110 | /*
* Copyright (C) 2014 pablo <pabcampi@ucm.es>
*
* This software has been developed as part of the
* SociAAL project directed by Jorge J. Gomez Sanz
* (http://grasia.fdi.ucm.es/sociaal)
*
* 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 phat.body.sensing.vision;
import com.jme3.math.Vector3f;
import com.jme3.scene.Spatial;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* This class contains objects that human is seeing using @see VisionControl.
* A map of listeners with ids are notified when new object are in visual field
* and when they leave the visual field.
*
* @author pablo <pabcampi@ucm.es>
*/
public class VisibleObjectManager {
Map<String, VisibleObjectsListener> listeners;
Map<String, VisibleObjInfo> objects; // <Id, Object>
public VisibleObjectManager() {
objects = new HashMap<>();
listeners = new HashMap<>();
}
void update(String id, Spatial spatial, Vector3f origin, Vector3f targetPos) {
VisibleObjInfo voi = get(id);
if (voi == null) {
voi = new VisibleObjInfo(id, spatial, origin, targetPos);
add(id, voi);
} else {
voi.getOrigin().set(origin);
voi.getTargetPos().set(targetPos);
}
}
private void notifyVisibleObjToListeners(VisibleObjInfo objInfo) {
for (VisibleObjectsListener l : listeners.values()) {
l.visible(objInfo, this);
}
}
private void notifyNoVisibleObjToListeners(VisibleObjInfo objInfo) {
for (VisibleObjectsListener l : listeners.values()) {
l.noVisible(objInfo, this);
}
}
public void add(String id, VisibleObjInfo objInfo) {
if (get(id) == null) {
objects.put(id, objInfo);
notifyVisibleObjToListeners(objInfo);
}
}
public void remove(String id) {
VisibleObjInfo objInfo = get(id);
if (objInfo != null) {
objects.remove(id);
notifyNoVisibleObjToListeners(objInfo);
}
}
public VisibleObjInfo get(String id) {
return objects.get(id);
}
public Set<String> getIds() {
return objects.keySet();
}
public void addListener(VisibleObjectsListener listener) {
if (listeners.get(listener.getId()) == null) {
listeners.put(listener.getId(), listener);
}
}
public void removeListener(String listenerId) {
listeners.remove(listenerId);
}
}
| lgpl-3.0 |
dbolkensteyn/sonarlint-vs | src/Tests/SonarLint.UnitTest/Rules/UnaryPrefixOperatorRepeatedTest.cs | 1701 | /*
* SonarLint for Visual Studio
* Copyright (C) 2015-2016 SonarSource SA
* mailto:contact@sonarsource.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SonarLint.Rules.CSharp;
namespace SonarLint.UnitTest.Rules
{
[TestClass]
public class UnaryPrefixOperatorRepeatedTest
{
[TestMethod]
[TestCategory("Rule")]
public void UnaryPrefixOperatorRepeated()
{
Verifier.VerifyAnalyzer(@"TestCases\UnaryPrefixOperatorRepeated.cs", new UnaryPrefixOperatorRepeated());
}
[TestMethod]
[TestCategory("CodeFix")]
public void UnaryPrefixOperatorRepeated_CodeFix()
{
Verifier.VerifyCodeFix(
@"TestCases\UnaryPrefixOperatorRepeated.cs",
@"TestCases\UnaryPrefixOperatorRepeated.Fixed.cs",
new UnaryPrefixOperatorRepeated(),
new UnaryPrefixOperatorRepeatedCodeFixProvider());
}
}
}
| lgpl-3.0 |
glidernet/ogn-commons-java | src/main/java/org/ogn/commons/igc/IgcLogger.java | 11674 | /**
* Copyright (c) 2014 OGN, All Rights Reserved.
*/
package org.ogn.commons.igc;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import javax.annotation.PostConstruct;
import org.ogn.commons.beacon.AircraftBeacon;
import org.ogn.commons.beacon.AircraftDescriptor;
import org.ogn.commons.utils.AprsUtils;
import org.ogn.commons.utils.AprsUtils.Coordinate;
import org.ogn.commons.utils.IgcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The IGC logger creates and writes to IGC files. The logger's log() operation is non-blocking (logs are written to a
* file by a background thread)
*
* @author wbuczak
*/
public class IgcLogger {
public enum Mode {
ASYNC, SYNC
}
private static final Logger LOG = LoggerFactory.getLogger(IgcLogger.class);
private static final String DEFAULT_IGC_BASE_DIR = "log";
private final String igcBaseDir;
private static final String LINE_SEP = System.lineSeparator();
private final Mode workingMode;
private BlockingQueue<LogRecord> logRecords;
private volatile Future<?> pollerFuture;
private ExecutorService executor;
private static class LogRecord {
AircraftBeacon beacon;
Optional<AircraftDescriptor> descriptor;
Optional<LocalDate> date;
public LogRecord(AircraftBeacon beacon, Optional<LocalDate> date, Optional<AircraftDescriptor> descriptor) {
this.beacon = beacon;
this.descriptor = descriptor;
this.date = date;
}
}
public int getQueueSize() {
return this.logRecords.size();
}
private class PollerTask implements Runnable {
@Override
public void run() {
LOG.trace("starting...");
LogRecord record = null;
while (!Thread.interrupted()) {
try {
record = logRecords.take();
logToIgcFile(record.beacon, record.date, record.descriptor);
} catch (final InterruptedException e) {
LOG.trace("interrupted exception caught. Was the poller task interrupted on purpose?");
Thread.currentThread().interrupt();
continue;
} catch (final Exception e) {
LOG.error("exception caught", e);
continue;
}
} // while
LOG.trace("exiting..");
}
}
@PostConstruct
private void logConf() {
LOG.info("created igc logger [log-folder: {}, mode: {}]", igcBaseDir, workingMode);
}
public IgcLogger(Mode mode) {
this(DEFAULT_IGC_BASE_DIR, mode);
}
public IgcLogger(final String logsFolder, Mode mode) {
igcBaseDir = logsFolder;
workingMode = mode;
if (workingMode == Mode.ASYNC) {
logRecords = new LinkedBlockingQueue<>();
executor = Executors.newSingleThreadExecutor();
pollerFuture = executor.submit(new PollerTask());
}
}
public IgcLogger() {
this(DEFAULT_IGC_BASE_DIR, Mode.ASYNC);
}
public IgcLogger(final String logsFolder) {
this(logsFolder, Mode.ASYNC);
}
private void writeIgcHeader(FileWriter igcFile, ZonedDateTime datetime, Optional<AircraftDescriptor> descriptor) {
// Write IGC file header
final StringBuilder bld = new StringBuilder();
try {
bld.append("AGNE001 OGN gateway").append(LINE_SEP);
bld.append("HFDTE").append(String.format("%02d", datetime.getDayOfMonth()))
.append(String.format("%02d", datetime.getMonthValue()))
.append(String.format("%04d", datetime.getYear()).substring(2)); // last
// 2
// chars
// of
// the
// year
if (descriptor.isPresent())
bld.append(LINE_SEP).append("HFGIDGLIDERID:").append(descriptor.get().getRegNumber()).append(LINE_SEP)
.append("HFGTYGLIDERTYPE:").append(descriptor.get().getModel()).append(LINE_SEP)
.append("HFCIDCOMPETITIONID:").append(descriptor.get().getCN()).append(LINE_SEP);
igcFile.write(bld.toString());
} catch (final IOException e) {
LOG.error("exception caught", e);
}
}
private void logToIgcFile(final AircraftBeacon beacon, final Optional<LocalDate> date,
final Optional<AircraftDescriptor> descriptor) {
final String igcId = IgcUtils.toIgcLogFileId(beacon, descriptor);
final LocalDate d = date.isPresent() ? date.get() : LocalDate.now();
final ZonedDateTime beaconTimestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(beacon.getTimestamp()),
ZoneOffset.UTC);
// take the time part from the beacon
final ZonedDateTime timestamp = ZonedDateTime.of(d,
LocalTime.of(beaconTimestamp.getHour(), beaconTimestamp.getMinute(), beaconTimestamp.getSecond()),
ZoneOffset.UTC);
final StringBuilder dateString = new StringBuilder(String.format("%04d", timestamp.getYear())).append("-")
.append(String.format("%02d", timestamp.getMonth().getValue())).append("-")
.append(String.format("%02d", timestamp.getDayOfMonth()));
// Generate filename from date and immat
final String igcFileName = dateString + "_" + igcId + ".IGC";
final File theDir = new File(igcBaseDir);
if (!theDir.exists() && !theDir.mkdir()) {
LOG.warn("the directory {} could not be created", theDir);
return;
}
final File subDir = new File(igcBaseDir + File.separatorChar + dateString);
if (!subDir.exists()) {
// if directory doesn't exist create it
if (!subDir.mkdir()) {
LOG.warn("the directory {} could not be created", subDir);
return;
}
}
final String filePath = igcBaseDir + File.separatorChar + dateString + File.separatorChar + igcFileName;
// Check if the IGC file already exist
final File f = new File(filePath);
boolean writeHeader = false;
if (!f.exists())
// if this is a brand new file - write the header
writeHeader = true;
FileWriter igcFile = null;
// create (if not exists) and/or open the file
try {
igcFile = new FileWriter(filePath, true);
} catch (final IOException ex) {
LOG.error("exception caught", ex);
return; // no point to continue - file could not be created
}
// if this is a brand new file - write the header
if (writeHeader) {
// write the igc header
writeIgcHeader(igcFile, timestamp, descriptor);
}
// Add fix
try {
final StringBuilder bld = new StringBuilder();
// log original APRS sentence to IGC file for debug, SAR & co
bld.append("LGNE ").append(beacon.getRawPacket()).append(LINE_SEP);
bld.append("B").append(String.format("%02d", timestamp.getHour()))
.append(String.format("%02d", timestamp.getMinute()))
.append(String.format("%02d", timestamp.getSecond()))
.append(AprsUtils.degToIgc(beacon.getLat(), Coordinate.LAT))
.append(AprsUtils.degToIgc(beacon.getLon(), Coordinate.LON)).append("A") // A
// for
// 3D
// fix
// (and
// not
// 2D)
.append("00000") // baro. altitude (but it is false as we
// have only GPS altitude
.append(String.format("%05.0f", beacon.getAlt())) // GPS
// altitude
.append(LINE_SEP);
igcFile.write(bld.toString());
} catch (final IOException e) {
LOG.error("exception caught", e);
} finally {
try {
igcFile.close();
} catch (final Exception ex) {
LOG.warn("could not close igc file", ex);
}
}
}
/**
* @param immat
* aircraft registration (if known) or unique tracker/flarm id
* @param lat
* latitude
* @param lon
* longitude
* @param alt
* altitude
* @param comment
* a string which will fall into the igc file as a comment (e.g. aprs sentence can be logged for
* debugging purposes)
*/
public void log(final AircraftBeacon beacon, final Optional<LocalDate> date,
final Optional<AircraftDescriptor> descriptor) {
switch (workingMode) {
case ASYNC:
if (!logRecords.offer(new LogRecord(beacon, date, descriptor))) {
LOG.warn("could not insert LogRecord to the igc logging queue");
}
break;
default:
logToIgcFile(beacon, date, descriptor);
}
}
public void log(final AircraftBeacon beacon, final Optional<AircraftDescriptor> descriptor) {
log(beacon, Optional.empty(), descriptor);
}
/**
* can be used to stop the poller thread. only affects IgcLogger in ASYNC mode
*/
public void stop() {
if (pollerFuture != null) {
pollerFuture.cancel(false);
}
}
}
/*
* From IGC spec (http://www.fai.org/gnss-recording-devices/igc-approved-flight-recorders):
*
* Altitude - Metres, separate records for GNSS and pressure altitudes. Date (of the first line in the B record) - UTC
* DDMMYY (day, month, year). Latitude and Longitude - Degrees, minutes and decimal minutes to three decimal places,
* with N,S,E,W designators Time - UTC, for source, see para 3.4 in the main body in this document. Note that UTC is not
* the same as the internal system time in the U.S. GPS system, see under "GPS system time" in the Glossary.
*
* ---
*
* Altitude - AAAAAaaa AAAAA - fixed to 5 digits with leading 0 aaa - where used, the number of altitude decimals (the
* number of fields recorded are those available for altitude in the Record concerned, less fields already used for
* AAAAA) Altitude, GNSS. Where GNSS altitude is not available from GNSS position-lines such as in the case of a 2D fix
* (altitude drop-out), it shall be recorded in the IGC format file as zero so that the lack of valid GNSS altitude can
* be clearly seen during post-flight analysis.
*
* Date - DDMMYY DD - number of the day in the month, fixed to 2 digits with leading 0 where necessary MM - number of
* the month in year, fixed to 2 digits with leading 0 where necessary YY - number of the year, fixed to 2 digits with
* leading 0 where necessary
*
* Lat/Long - D D M M m m m N D D D M M m m m E DD - Latitude degrees with leading 0 where necessary DDD - Longitude
* degrees with leading 0 or 00 where necessary MMmmmNSEW - Lat/Long minutes with leading 0 where necessary, 3 decimal
* places of minutes (mandatory, not optional), followed by North, South, East or West letter as appropriate
*
* Time - HHMMSS (UTC) - for optional decimal seconds see "s" below HH - Hours fixed to 2 digits with leading 0 where
* necessary MM - Minutes fixed to 2 digits with leading 0 where necessary SS - Seconds fixed to 2 digits with leading 0
* where necessary s - number of decimal seconds (if used), placed after seconds (SS above). If the recorder uses fix
* intervals of less than one second, the extra number(s) are added in the B-record line, their position on the line
* being identified in the I-record under the Three Letter Code TDS (Time Decimal Seconds, see the codes in para A7).
* One number "s" indicates tenths of seconds and "ss" is tenths and hundredths, and so forth. If tenths are used at,
* for instance, character number 49 in the B-record (after other codes such as FXA, SIU, ENL), this is indicated in the
* I record as: "4949TDS".
*
* B HHMMSS DDMMmmmN DDDMMmmmE V PPPPP GGGGG CR LF B 130353 4344108N 00547165E A 00275 00275 4533.12N 00559.93E
*
* Condor example: HFDTE140713 HFGIDGLIDERID:F-SEB B1303534344108N00547165EA0027500275
*/
| lgpl-3.0 |
zaizi/sensefy | sensefy-authserver/src/main/java/org/zaizi/sensefy/auth/WebSecurityConfigurations.java | 3865 | /**
* (C) Copyright 2015 Zaizi Limited (http://www.zaizi.com).
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 3.0 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.en.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
**/
package org.zaizi.sensefy.auth;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;
/**
* @author mfahiz
*/
@Component
@Configuration
@Order(-10)
class LoginConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/login").permitAll().and().requestMatchers()
.antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access").and().authorizeRequests()
.anyRequest().authenticated().and().csrf().csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager);
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
// response.setHeader("Access-Control-Allow-Origin",
// "*");
// response.setHeader("Access-Control-Allow-Methods",
// "POST, GET, OPTIONS, DELETE");
// response.setHeader("Access-Control-Max-Age",
// "3600");
// response.setHeader("Access-Control-Allow-Headers",
// "x-requested-with");
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
} | lgpl-3.0 |
racodond/sonar-gherkin-plugin | gherkin-checks/src/test/java/org/sonar/gherkin/checks/MissingDataTableColumnCheckTest.java | 1198 | /*
* SonarQube Cucumber Gherkin Analyzer
* Copyright (C) 2016-2017 David RACODON
* david.racodon@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.gherkin.checks;
import org.junit.Test;
import org.sonar.gherkin.checks.verifier.GherkinCheckVerifier;
public class MissingDataTableColumnCheckTest {
@Test
public void test() {
GherkinCheckVerifier.verify(new MissingDataTableColumnCheck(), CheckTestUtils.getTestFile("missing-data-table-column.feature"));
}
}
| lgpl-3.0 |
nyatla/NyARToolkit | lib/src.markersystem/jp/nyatla/nyartoolkit/markersystem/utils/ARMarkerSortList.java | 3463 | /*
* PROJECT: NyARToolkit(Extension)
* --------------------------------------------------------------------------------
*
* The NyARToolkit is Java edition ARToolKit class library.
* Copyright (C)2008-2012 Ryo Iizuka
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as publishe
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* For further information please contact.
* http://nyatla.jp/nyatoolkit/
* <airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp>
*
*/
package jp.nyatla.nyartoolkit.markersystem.utils;
import jp.nyatla.nyartoolkit.core.types.NyARLinkList;
/**
* このクラスは、ARマーカの検出結果をマッピングするためのリストです。
*/
public class ARMarkerSortList extends NyARLinkList<ARMarkerSortList.Item>
{
public class Item extends NyARLinkList.Item
{
public ARMarkerList.Item marker;
public double cf;
public int dir;
public SquareStack.Item ref_sq;
};
/**
* 指定個数のリンクリストを生成。
* @param i_num_of_item
*/
public ARMarkerSortList()
{
super(1);
}
protected Item createElement()
{
return new Item();
}
/**
* 挿入ポイントを返す。挿入ポイントは、i_sd_point(距離点数)が
* 登録済のポイントより小さい場合のみ返却する。
* @return
*/
public Item getInsertPoint(double i_cf)
{
Item ptr=_head_item;
//先頭の場合
if(ptr.cf<i_cf){
return ptr;
}
//それ以降
ptr=(Item) ptr.next;
for(int i=this._num_of_item-2;i>=0;i--)
{
if(ptr.cf<i_cf){
return ptr;
}
ptr=(Item) ptr.next;
}
//対象外。
return null;
}
public void reset()
{
Item ptr=this._head_item;
for(int i=this._num_of_item-1;i>=0;i--)
{
ptr.cf=0;
ptr.marker=null;
ptr.ref_sq=null;
ptr=(Item) ptr.next;
}
}
/**
* リストから最も高い一致率のアイテムを取得する。
*/
public Item getTopItem()
{
Item ptr=this._head_item;
for(int i=this._num_of_item-1;i>=0;i--)
{
if(ptr.marker==null){
ptr=(Item) ptr.next;
continue;
}
return ptr;
}
return null;
}
/**
* リスト中の、i_itemと同じマーカIDか、同じ矩形情報を参照しているものを無効に(ptr.idを-1)する。
*/
public void disableMatchItem(Item i_item)
{
//削除対象のオブジェクトのポインタ保存
ARMarkerList.Item match_mk=i_item.marker;
SquareStack.Item match_sq=i_item.ref_sq;
//リストを走査して該当アイテムを削除
Item ptr=this._head_item;
for(int i=this._num_of_item-1;i>=0;i--)
{
if(ptr.marker!=null){
if((ptr.marker==match_mk) || (ptr.ref_sq==match_sq)){
ptr.marker=null;
}
}
ptr=(Item) ptr.next;
}
}
public int getLength(){
return this._num_of_item;
}
} | lgpl-3.0 |
wienerschnitzel/schnitzelserver | schnitzelserver/dispatcher.py | 384 | __author__ = 'duesenfranz, hiaselhans'
exposed_commands = {}
def exposed_method(method, route):
def wrapper(func):
exposed_commands[route][func.__name__] = func
return func
return wrapper
class Dispatcher():
def __init__(self):
pass
@exposed_method("model")
def my_func(self, blbal):
pass
def handle(self):
pass
| lgpl-3.0 |
bullda/DroidText | src/bouncycastle/repack/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java | 4938 | package repack.org.bouncycastle.jce.provider;
import repack.org.bouncycastle.asn1.ASN1Sequence;
import repack.org.bouncycastle.asn1.DEREncodable;
import repack.org.bouncycastle.asn1.DERInteger;
import repack.org.bouncycastle.asn1.DERObjectIdentifier;
import repack.org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import repack.org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import repack.org.bouncycastle.asn1.x509.DSAParameter;
import repack.org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import repack.org.bouncycastle.crypto.params.DSAPrivateKeyParameters;
import repack.org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.spec.DSAParameterSpec;
import java.security.spec.DSAPrivateKeySpec;
import java.util.Enumeration;
public class JDKDSAPrivateKey
implements DSAPrivateKey, PKCS12BagAttributeCarrier
{
private static final long serialVersionUID = -4677259546958385734L;
BigInteger x;
DSAParams dsaSpec;
private PKCS12BagAttributeCarrierImpl attrCarrier = new PKCS12BagAttributeCarrierImpl();
protected JDKDSAPrivateKey()
{
}
JDKDSAPrivateKey(
DSAPrivateKey key)
{
this.x = key.getX();
this.dsaSpec = key.getParams();
}
JDKDSAPrivateKey(
DSAPrivateKeySpec spec)
{
this.x = spec.getX();
this.dsaSpec = new DSAParameterSpec(spec.getP(), spec.getQ(), spec.getG());
}
JDKDSAPrivateKey(
PrivateKeyInfo info)
{
DSAParameter params = new DSAParameter((ASN1Sequence)info.getAlgorithmId().getParameters());
DERInteger derX = (DERInteger)info.getPrivateKey();
this.x = derX.getValue();
this.dsaSpec = new DSAParameterSpec(params.getP(), params.getQ(), params.getG());
}
JDKDSAPrivateKey(
DSAPrivateKeyParameters params)
{
this.x = params.getX();
this.dsaSpec = new DSAParameterSpec(params.getParameters().getP(), params.getParameters().getQ(), params.getParameters().getG());
}
public String getAlgorithm()
{
return "DSA";
}
/**
* return the encoding format we produce in getEncoded().
*
* @return the string "PKCS#8"
*/
public String getFormat()
{
return "PKCS#8";
}
/**
* Return a PKCS8 representation of the key. The sequence returned
* represents a full PrivateKeyInfo object.
*
* @return a PKCS8 representation of the key.
*/
public byte[] getEncoded()
{
PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(dsaSpec.getP(), dsaSpec.getQ(), dsaSpec.getG()).getDERObject()), new DERInteger(getX()));
return info.getDEREncoded();
}
public DSAParams getParams()
{
return dsaSpec;
}
public BigInteger getX()
{
return x;
}
public boolean equals(
Object o)
{
if (!(o instanceof DSAPrivateKey))
{
return false;
}
DSAPrivateKey other = (DSAPrivateKey)o;
return this.getX().equals(other.getX())
&& this.getParams().getG().equals(other.getParams().getG())
&& this.getParams().getP().equals(other.getParams().getP())
&& this.getParams().getQ().equals(other.getParams().getQ());
}
public int hashCode()
{
return this.getX().hashCode() ^ this.getParams().getG().hashCode()
^ this.getParams().getP().hashCode() ^ this.getParams().getQ().hashCode();
}
public void setBagAttribute(
DERObjectIdentifier oid,
DEREncodable attribute)
{
attrCarrier.setBagAttribute(oid, attribute);
}
public DEREncodable getBagAttribute(
DERObjectIdentifier oid)
{
return attrCarrier.getBagAttribute(oid);
}
public Enumeration getBagAttributeKeys()
{
return attrCarrier.getBagAttributeKeys();
}
private void readObject(
ObjectInputStream in)
throws IOException, ClassNotFoundException
{
this.x = (BigInteger)in.readObject();
this.dsaSpec = new DSAParameterSpec((BigInteger)in.readObject(), (BigInteger)in.readObject(), (BigInteger)in.readObject());
this.attrCarrier = new PKCS12BagAttributeCarrierImpl();
attrCarrier.readObject(in);
}
private void writeObject(
ObjectOutputStream out)
throws IOException
{
out.writeObject(x);
out.writeObject(dsaSpec.getP());
out.writeObject(dsaSpec.getQ());
out.writeObject(dsaSpec.getG());
attrCarrier.writeObject(out);
}
}
| lgpl-3.0 |
hkust-smartcar/libsccc | src/libbase/k60/pin_isr_manager.cpp | 2944 | /*
* pin_isr_manager.cpp
* Manage ISR for ports
*
* Author: Ming Tsang
* Copyright (c) 2014-2015 HKUST SmartCar Team
* Refer to LICENSE for details
*/
#include <cstring>
#include <bitset>
#include <functional>
#include "libbase/k60/misc_utils.h"
#include "libbase/k60/pin.h"
#include "libbase/k60/pin_isr_manager.h"
#include "libbase/k60/pin_utils.h"
#include "libbase/k60/vectors.h"
#include "libutil/misc.h"
using namespace libbase::k60;
using namespace libutil;
namespace libbase
{
namespace k60
{
PinIsrManager* PinIsrManager::m_instance = nullptr;
PinIsrManager* PinIsrManager::GetInstance()
{
if (!m_instance)
{
m_instance = new PinIsrManager;
}
return m_instance;
}
PinIsrManager::PinIsrManager()
{
for (Uint i = 0; i < PINOUT::GetPortCount(); ++i)
{
m_pin_data[i] = nullptr;
m_is_enable[i] = false;
}
}
PinIsrManager::~PinIsrManager()
{
for (Uint i = 0; i < PINOUT::GetPortCount(); ++i)
{
if (m_is_enable[i])
{
SetIsr(EnumAdvance(PORTA_IRQn, i), DefaultIsr);
DisableIrq(EnumAdvance(PORTA_IRQn, i));
}
if (m_pin_data[i])
{
delete[] m_pin_data[i];
}
}
}
void PinIsrManager::InitPort(const Uint port)
{
if (!m_pin_data[port])
{
m_pin_data[port] = new PinData[PINOUT::GetPortPinCount()];
memset(m_pin_data[port], 0, PINOUT::GetPortPinCount() * sizeof(PinData));
}
switch (port)
{
case 0:
SetIsr(PORTA_IRQn, PortIrqHandler<0>);
break;
case 1:
SetIsr(PORTB_IRQn, PortIrqHandler<1>);
break;
case 2:
SetIsr(PORTC_IRQn, PortIrqHandler<2>);
break;
case 3:
SetIsr(PORTD_IRQn, PortIrqHandler<3>);
break;
case 4:
SetIsr(PORTE_IRQn, PortIrqHandler<4>);
break;
default:
return;
}
EnableIrq(EnumAdvance(PORTA_IRQn, port));
m_is_enable[port] = true;
}
void PinIsrManager::SetPinIsr_(Pin *pin, const OnPinIrqListener &isr)
{
const Uint port = PinUtils::GetPort(pin->GetName());
const Uint pin_num = PinUtils::GetPinNumber(pin->GetName());
if (isr)
{
if (!m_is_enable[port])
{
InitPort(port);
}
m_pin_data[port][pin_num].pin = nullptr;
m_pin_data[port][pin_num].isr = isr;
m_pin_data[port][pin_num].pin = pin;
}
else if (m_is_enable[port])
{
m_pin_data[port][pin_num].pin = nullptr;
m_pin_data[port][pin_num].isr = nullptr;
// Disable interrupt only if all are null
for (Uint i = 0; i < PINOUT::GetPortPinCount(); ++i)
{
if (m_pin_data[port][i].isr)
{
return;
}
}
SetIsr(EnumAdvance(PORTA_IRQn, port), DefaultIsr);
DisableIrq(EnumAdvance(PORTA_IRQn, port));
m_is_enable[port] = false;
}
}
template<Uint port>
__ISR void PinIsrManager::PortIrqHandler()
{
PinData *pin_data = PinIsrManager::GetInstance()->m_pin_data[port];
for (Uint i = 0; i < PINOUT::GetPortPinCount(); ++i)
{
const Pin::Name pin = PinUtils::GetPin(port, i);
if (Pin::IsInterruptRequested(pin))
{
if (pin_data[i].pin && pin_data[i].isr)
{
pin_data[i].isr(pin);
}
Pin::ConsumeInterrupt(pin);
}
}
}
}
}
| lgpl-3.0 |
gothicsyn/VampireReboot | VampyreReboot/Assets/BurgZergArcade/System/Item System/Scripts/Interfaces/IItemSystemEquipmentSlot.cs | 190 | using UnityEngine;
using System.Collections;
namespace BurgZergArcade.ItemSystem
{
public interface IItemSystemEquipmentSlot
{
string Name {get; set;}
Sprite Icon {get; set;}
}
} | lgpl-3.0 |
xiaoqing-yuanfang/test | python/decrator.py | 289 | #!/usr/bin/python
#-*-coding:utf8-*-
nihao = "你好"
def my_wrapper(func):
def _my_wrapper(*args,**kwargs):
value = func(*args,**kwargs)
return value**2
return _my_wrapper
@my_wrapper
def add(a,b):
return a+b
if __name__ == "__main__":
print(add(3,4))
| lgpl-3.0 |
StijnVA/Qasparov | QBisSDK/QBisMessage.cs | 438 | using System;
namespace org.qasparov.qbis.SDK
{
/// <summary>
/// QBisMessage is an message that will be send to the selected QBisClients.
/// </summary>
public class QBisMessage
{
//TODO: Think about it
enum SecurityLevel {
PUBLIC,
INFORMATIVE,
CRITICAL
}
//TODO Think about it
enum TypeOfMessage {
TEMPERATURE,
OTHER
}
public String Desciption { get; set; }
public QBisMessage ()
{
}
}
}
| lgpl-3.0 |
kbss-cvut/jopa | jopa-impl/src/main/java/cz/cvut/kbss/jopa/query/soql/SoqlQueryParser.java | 2013 | /**
* Copyright (C) 2022 Czech Technical University in Prague
*
* 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 cz.cvut.kbss.jopa.query.soql;
import cz.cvut.kbss.jopa.model.MetamodelImpl;
import cz.cvut.kbss.jopa.query.QueryHolder;
import cz.cvut.kbss.jopa.query.QueryParser;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
public class SoqlQueryParser implements QueryParser {
private final QueryParser sparqlParser;
private final MetamodelImpl metamodel;
public SoqlQueryParser(QueryParser sparqlParser, MetamodelImpl metamodel) {
this.sparqlParser = sparqlParser;
this.metamodel = metamodel;
}
@Override
public QueryHolder parseQuery(String query) {
CharStream cs = CharStreams.fromString(query);
SoqlLexer lexer = new SoqlLexer(cs);
final CommonTokenStream tokens = new CommonTokenStream(lexer);
SoqlParser parser = new SoqlParser(tokens);
final ParseTree tree = parser.querySentence();
final SoqlQueryListener listener = new SoqlQueryListener(this.metamodel);
final ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(listener, tree);
return sparqlParser.parseQuery(listener.getSoqlQuery());
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/repository/source/java/org/alfresco/service/cmr/avm/deploy/DeploymentCallback.java | 1211 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.service.cmr.avm.deploy;
/**
* Callback interface for deployments.
* @author britt
*/
public interface DeploymentCallback
{
/**
* Called each time something happens during deployment.
* This is called synchronously by the deployer and should
* therefore be handled rapidly, if possible.
* @param event The event that occurred.
*/
public void eventOccurred(DeploymentEvent event);
}
| lgpl-3.0 |
felixem/EI-P1Tests | boost/boost/mpl/aux_/config/gcc.hpp | 665 |
#ifndef BOOST_MPL_AUX_CONFIG_GCC_HPP_INCLUDED
#define BOOST_MPL_AUX_CONFIG_GCC_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: gcc.hpp,v 1.1 2010-07-13 06:44:24 egraf Exp $
// $Date: 2010-07-13 06:44:24 $
// $Revision: 1.1 $
#if defined(__GNUC__) && !defined(__EDG_VERSION__)
# define BOOST_MPL_CFG_GCC ((__GNUC__ << 8) | __GNUC_MINOR__)
#else
# define BOOST_MPL_CFG_GCC 0
#endif
#endif // BOOST_MPL_AUX_CONFIG_GCC_HPP_INCLUDED
| lgpl-3.0 |
dennisbappert/fileharbor | src/Services/ServiceBase.cs | 715 | using System.Data;
using System.Threading.Tasks;
using Npgsql;
namespace Fileharbor.Services
{
public abstract class ServiceBase
{
private readonly IDbConnection _connection;
protected ServiceBase(IDbConnection connection)
{
_connection = connection;
}
protected async Task<IDbConnection> GetDatabaseConnectionAsync()
{
if (_connection.State == ConnectionState.Open)
return _connection;
if (_connection is NpgsqlConnection postgresConnection)
await postgresConnection.OpenAsync();
else
_connection.Open();
return _connection;
}
}
} | lgpl-3.0 |
Godin/sonar | server/sonar-server/src/main/java/org/sonar/server/telemetry/package-info.java | 967 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.telemetry;
import javax.annotation.ParametersAreNonnullByDefault;
| lgpl-3.0 |
aimeos/ai-admin-extadm | controller/extjs/tests/Controller/ExtJS/Supplier/Lists/FactoryTest.php | 1212 | <?php
namespace Aimeos\Controller\ExtJS\Supplier\Lists;
/**
* @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
* @copyright Aimeos (aimeos.org), 2015-2017
*/
class FactoryTest extends \PHPUnit\Framework\TestCase
{
public function testCreateController()
{
$obj = \Aimeos\Controller\ExtJS\Supplier\Lists\Factory::createController( \TestHelperExtjs::getContext() );
$this->assertInstanceOf( '\\Aimeos\\Controller\\ExtJS\\Iface', $obj );
}
public function testFactoryExceptionWrongName()
{
$this->setExpectedException( '\\Aimeos\\Controller\\ExtJS\\Exception' );
\Aimeos\Controller\ExtJS\Supplier\Lists\Factory::createController( \TestHelperExtjs::getContext(), 'Wrong$$$Name' );
}
public function testFactoryExceptionWrongClass()
{
$this->setExpectedException( '\\Aimeos\\Controller\\ExtJS\\Exception' );
\Aimeos\Controller\ExtJS\Supplier\Lists\Factory::createController( \TestHelperExtjs::getContext(), 'WrongClass' );
}
public function testFactoryExceptionWrongInterface()
{
$this->setExpectedException( '\\Aimeos\\Controller\\ExtJS\\Exception' );
\Aimeos\Controller\ExtJS\Supplier\Lists\Factory::createController( \TestHelperExtjs::getContext(), 'Factory' );
}
}
| lgpl-3.0 |
sones/sones-RemoteTagExample | java/RemoteTagExample/src/com/sones/HasOutgoingEdgeByVertexType.java | 3825 |
package com.sones;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.datacontract.schemas._2004._07.sones_library_commons.SecurityToken;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="mySecurityToken" type="{http://schemas.datacontract.org/2004/07/sones.Library.Commons.Security}SecurityToken" minOccurs="0"/>
* <element name="myTransToken" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="myServiceVertexType" type="{http://www.sones.com}ServiceVertexType" minOccurs="0"/>
* <element name="myEdgeName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"mySecurityToken",
"myTransToken",
"myServiceVertexType",
"myEdgeName"
})
@XmlRootElement(name = "HasOutgoingEdgeByVertexType")
public class HasOutgoingEdgeByVertexType {
@XmlElement(nillable = true)
protected SecurityToken mySecurityToken;
protected Long myTransToken;
@XmlElement(nillable = true)
protected ServiceVertexType myServiceVertexType;
@XmlElement(nillable = true)
protected String myEdgeName;
/**
* Gets the value of the mySecurityToken property.
*
* @return
* possible object is
* {@link SecurityToken }
*
*/
public SecurityToken getMySecurityToken() {
return mySecurityToken;
}
/**
* Sets the value of the mySecurityToken property.
*
* @param value
* allowed object is
* {@link SecurityToken }
*
*/
public void setMySecurityToken(SecurityToken value) {
this.mySecurityToken = value;
}
/**
* Gets the value of the myTransToken property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getMyTransToken() {
return myTransToken;
}
/**
* Sets the value of the myTransToken property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setMyTransToken(Long value) {
this.myTransToken = value;
}
/**
* Gets the value of the myServiceVertexType property.
*
* @return
* possible object is
* {@link ServiceVertexType }
*
*/
public ServiceVertexType getMyServiceVertexType() {
return myServiceVertexType;
}
/**
* Sets the value of the myServiceVertexType property.
*
* @param value
* allowed object is
* {@link ServiceVertexType }
*
*/
public void setMyServiceVertexType(ServiceVertexType value) {
this.myServiceVertexType = value;
}
/**
* Gets the value of the myEdgeName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMyEdgeName() {
return myEdgeName;
}
/**
* Sets the value of the myEdgeName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMyEdgeName(String value) {
this.myEdgeName = value;
}
}
| lgpl-3.0 |
vrsys/avango | avango-blender/blender-addon/starter.py | 1428 | import bpy
import bpy.types
from . import export_avango
import os
import tempfile
class StartAvango(bpy.types.Operator):
bl_idname = "start.avango"
bl_label = "Start Avango"
bl_description =\
"exports an .avango file, loads it in avango and starts it"
def invoke(self, context, event):
print("invoke avango application")
tmpdir = tempfile.mkdtemp()
tmpfilepath = tmpdir+'/automatic_export.avango'
bpy.ops.export_scene.avango(
filepath=tmpfilepath)
relativ_path =\
context.user_preferences.\
addons['avango-blender'].\
preferences['filepath_loader']
absolute_path = bpy.path.abspath(relativ_path)
command = "./start.sh "+tmpfilepath
#cmd = "gnome-terminal --hide-menubar --working-directory=" + absolute_path + " --command=\"" + command + "\" "
#cmd = "cd "+tmpdir+"; " + absolute_path + "start.sh " + tmpfilepath
cmd = "python3.5 " + absolute_path + "main.py " + tmpfilepath
print(cmd)
try:
os.system(cmd)
except:
self.report({'ERROR'},
"avango starter not found, "
"please fix starter.py")
return {'FINISHED'}
def draw(self, context):
pass
def register():
bpy.utils.register_class(StartAvango)
def unregister():
bpy.utils.unregister_class(StartAvango)
| lgpl-3.0 |
horazont/aioxmpp | aioxmpp/connector.py | 12042 | ########################################################################
# File name: connector.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
"""
:mod:`~aioxmpp.connector` --- Ways to establish XML streams
###########################################################
This module provides classes to establish XML streams. Currently, there are two
different ways to establish XML streams: normal TCP connection which is then
upgraded using STARTTLS, and directly using TLS.
.. versionadded:: 0.6
The whole module was added in version 0.6.
Abstract base class
===================
The connectors share a common abstract base class, :class:`BaseConnector`:
.. autoclass:: BaseConnector
Specific connectors
===================
.. autoclass:: STARTTLSConnector
.. autoclass:: XMPPOverTLSConnector
"""
import abc
import asyncio
import logging
from datetime import timedelta
import aioxmpp.errors as errors
import aioxmpp.nonza as nonza
import aioxmpp.protocol as protocol
import aioxmpp.ssl_transport as ssl_transport
def to_ascii(s):
return s.encode("idna").decode("ascii")
class BaseConnector(metaclass=abc.ABCMeta):
"""
This is the base class for connectors. It defines the public interface of
all connectors.
.. autoattribute:: tls_supported
.. automethod:: connect
Existing connectors:
.. autosummary::
STARTTLSConnector
XMPPOverTLSConnector
"""
@abc.abstractproperty
def tls_supported(self):
"""
Boolean which indicates whether TLS is supported by this connector.
"""
@abc.abstractproperty
def dane_supported(self):
"""
Boolean which indicates whether DANE is supported by this connector.
"""
@abc.abstractmethod
async def connect(self, loop, metadata, domain, host, port,
negotiation_timeout,
base_logger=None):
"""
Establish a :class:`.protocol.XMLStream` for `domain` with the given
`host` at the given TCP `port`.
`metadata` must be a :class:`.security_layer.SecurityLayer` instance to
use for the connection. `loop` must be a :class:`asyncio.BaseEventLoop`
to use.
`negotiation_timeout` must be the maximum time in seconds to wait for
the server to reply in each negotiation step. The `negotiation_timeout`
is used as value for
:attr:`~aioxmpp.protocol.XMLStream.deadtime_hard_limit` in the returned
stream.
Return a triple consisting of the :class:`asyncio.Transport`, the
:class:`.protocol.XMLStream` and the
:class:`aioxmpp.nonza.StreamFeatures` of the stream.
To detect the use of TLS on the stream, check whether
:meth:`asyncio.Transport.get_extra_info` returns a non-:data:`None`
value for ``"ssl_object"``.
`base_logger` is passed to :class:`aioxmpp.protocol.XMLStream`.
.. versionchanged:: 0.10
Assignment of
:attr:`~aioxmpp.protocol.XMLStream.deadtime_hard_limit` was added.
"""
class STARTTLSConnector(BaseConnector):
"""
Establish an XML stream using STARTTLS.
.. automethod:: connect
"""
@property
def tls_supported(self):
return True
@property
def dane_supported(self):
return False
async def connect(self, loop, metadata, domain: str, host, port,
negotiation_timeout, base_logger=None):
"""
.. seealso::
:meth:`BaseConnector.connect`
For general information on the :meth:`connect` method.
Connect to `host` at TCP port number `port`. The
:class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used
to determine the parameters of the TLS connection.
First, a normal TCP connection is opened and the stream header is sent.
The stream features are waited for, and then STARTTLS is negotiated if
possible.
:attr:`~.security_layer.SecurityLayer.tls_required` is honoured: if it
is true and TLS negotiation fails, :class:`~.errors.TLSUnavailable` is
raised. TLS negotiation is always attempted if
:attr:`~.security_layer.SecurityLayer.tls_required` is true, even if
the server does not advertise a STARTTLS stream feature. This might
help to prevent trivial downgrade attacks, and we don’t have anything
to lose at this point anymore anyways.
:attr:`~.security_layer.SecurityLayer.ssl_context_factory` and
:attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are
used to configure the TLS connection.
.. versionchanged:: 0.10
The `negotiation_timeout` is set as
:attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream.
"""
features_future = asyncio.Future(loop=loop)
stream = protocol.XMLStream(
to=domain,
features_future=features_future,
base_logger=base_logger,
)
if base_logger is not None:
logger = base_logger.getChild(type(self).__name__)
else:
logger = logging.getLogger(".".join([
__name__, type(self).__qualname__,
]))
try:
transport, _ = await ssl_transport.create_starttls_connection(
loop,
lambda: stream,
host=host,
port=port,
peer_hostname=host,
server_hostname=to_ascii(domain),
use_starttls=True,
)
except: # NOQA
stream.abort()
raise
stream.deadtime_hard_limit = timedelta(seconds=negotiation_timeout)
features = await features_future
try:
features[nonza.StartTLSFeature]
except KeyError:
if not metadata.tls_required:
return transport, stream, await features_future
logger.debug(
"attempting STARTTLS despite not announced since it is"
" required")
try:
response = await protocol.send_and_wait_for(
stream,
[
nonza.StartTLS(),
],
[
nonza.StartTLSFailure,
nonza.StartTLSProceed,
]
)
except errors.StreamError:
raise errors.TLSUnavailable(
"STARTTLS not supported by server, but required by client"
)
if not isinstance(response, nonza.StartTLSProceed):
if metadata.tls_required:
message = (
"server failed to STARTTLS"
)
protocol.send_stream_error_and_close(
stream,
condition=errors.StreamErrorCondition.POLICY_VIOLATION,
text=message,
)
raise errors.TLSUnavailable(message)
return transport, stream, await features_future
verifier = metadata.certificate_verifier_factory()
await verifier.pre_handshake(
domain,
host,
port,
metadata,
)
ssl_context = metadata.ssl_context_factory()
verifier.setup_context(ssl_context, transport)
await stream.starttls(
ssl_context=ssl_context,
post_handshake_callback=verifier.post_handshake,
)
features = await protocol.reset_stream_and_get_features(
stream,
timeout=negotiation_timeout,
)
return transport, stream, features
class XMPPOverTLSConnector(BaseConnector):
"""
Establish an XML stream using XMPP-over-TLS, as per :xep:`368`.
.. automethod:: connect
"""
@property
def dane_supported(self):
return False
@property
def tls_supported(self):
return True
def _context_factory_factory(self, logger, metadata, verifier):
def context_factory(transport):
ssl_context = metadata.ssl_context_factory()
if hasattr(ssl_context, "set_alpn_protos"):
try:
ssl_context.set_alpn_protos([b'xmpp-client'])
except NotImplementedError:
logger.warning(
"the underlying OpenSSL library does not support ALPN"
)
else:
logger.warning(
"OpenSSL.SSL.Context lacks set_alpn_protos - "
"please update pyOpenSSL to a recent version"
)
verifier.setup_context(ssl_context, transport)
return ssl_context
return context_factory
async def connect(self, loop, metadata, domain, host, port,
negotiation_timeout, base_logger=None):
"""
.. seealso::
:meth:`BaseConnector.connect`
For general information on the :meth:`connect` method.
Connect to `host` at TCP port number `port`. The
:class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used
to determine the parameters of the TLS connection.
The connector connects to the server by directly establishing TLS; no
XML stream is started before TLS negotiation, in accordance to
:xep:`368` and how legacy SSL was handled in the past.
:attr:`~.security_layer.SecurityLayer.ssl_context_factory` and
:attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are
used to configure the TLS connection.
.. versionchanged:: 0.10
The `negotiation_timeout` is set as
:attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream.
"""
features_future = asyncio.Future(loop=loop)
stream = protocol.XMLStream(
to=domain,
features_future=features_future,
base_logger=base_logger,
)
if base_logger is not None:
logger = base_logger.getChild(type(self).__name__)
else:
logger = logging.getLogger(".".join([
__name__, type(self).__qualname__,
]))
verifier = metadata.certificate_verifier_factory()
await verifier.pre_handshake(
domain,
host,
port,
metadata,
)
context_factory = self._context_factory_factory(logger, metadata,
verifier)
try:
transport, _ = await ssl_transport.create_starttls_connection(
loop,
lambda: stream,
host=host,
port=port,
peer_hostname=host,
server_hostname=to_ascii(domain),
post_handshake_callback=verifier.post_handshake,
ssl_context_factory=context_factory,
use_starttls=False,
)
except: # NOQA
stream.abort()
raise
stream.deadtime_hard_limit = timedelta(seconds=negotiation_timeout)
return transport, stream, await features_future
| lgpl-3.0 |
yonghuang/fastui | src/component/basecontrol/Text.js | 1720 | (function() {
talkweb.BaseControl.Text = function(settings) {
return fastDev.create("talkweb.BaseControl.Text.Class", settings);
};
fastDev.define("talkweb.BaseControl.Text.Class", {
extend : "talkweb.BaseControl.Input",
_options : {
id : null,
name : null,
className : null,
value : null,
initialContent : "",
type : "text"
},
init : function() {
this.setInitContent();
//talkweb.BaseControl.Button.Class.superClass.init.call(this);
},
getValue : function() {
var options = this.getOptions();
if(options.initialContent && options.initialContent === this.attr("value")) {
return "";
} else {
return this.attr("value");
}
},
getInitText : function() {
return this.attr("value");
},
setValue : function(param) {
if(param === "" || param === 0 || param) {
this.attr("value", param);
this.getOptions().initialContent && this.setStyle({
color : "#075586"
});
}
},
setInitContent : function(initialContent) {
var options = this.getOptions();
if(options.initialContent) {
this.setValue(options.initialContent);
this.setStyle({
color : "#cccccc"
});
var that = this;
var focusIncon = function() {
if(options.initialContent && options.initialContent === that.getInitText()) {
that.setValue("");
that.setStyle({
color : "#075586"
});
}
return that;
};
var blurIncon = function() {
if(options.initialContent && (!that.getInitText())) {
that.setValue(options.initialContent);
that.setStyle({
color : "#cccccc"
});
}
return that;
};
this.onFocus(focusIncon);
this.onBlur(blurIncon);
}
}
});
})() | lgpl-3.0 |
clojj/mac-watchservice | src/test/java/com/barbarysoftware/watchservice/WatchServiceTest.java | 1407 | package com.barbarysoftware.watchservice;
import org.junit.Assert;
import java.io.File;
import static com.barbarysoftware.watchservice.StandardWatchEventKind.*;
public class WatchServiceTest {
@org.junit.Test
public void testNewWatchService() throws Exception {
Assert.assertNotNull(WatchService.newWatchService());
}
@org.junit.Test
public void testWatchingInvalidFolder() throws Exception {
final WatchService watcher = WatchService.newWatchService();
WatchableFile f = new WatchableFile(new File("/thisfolderdoesntexist"));
f.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
}
@org.junit.Test
public void testNonsensePath() throws Exception {
final WatchService watcher = WatchService.newWatchService();
WatchableFile f = new WatchableFile(new File("/path/to/watch"));
f.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
}
@org.junit.Test(expected = NullPointerException.class)
public void testWatchingNull() throws Exception {
new WatchableFile(null);
}
@org.junit.Test
public void testWatchingFile() throws Exception {
final WatchService watcher = WatchService.newWatchService();
WatchableFile f = new WatchableFile(File.createTempFile("watcher_", null));
f.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
}
}
| lgpl-3.0 |
cyclomedia/streetsmart-dotnet | StreetSmartAPI/StreetSmart.API/Common/Data/GeoJson/MeasurementProperties.cs | 10312 | /*
* Street Smart .NET integration
* Copyright (c) 2016 - 2019, CycloMedia, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using StreetSmart.Common.Interfaces.GeoJson;
namespace StreetSmart.Common.Data.GeoJson
{
internal class MeasurementProperties: Properties, IMeasurementProperties
{
public MeasurementProperties(Dictionary<string, object> properties, GeometryType geometryType)
{
DataConvert converter = new DataConvert();
Id = converter.ToString(properties, "id");
Name = converter.ToString(properties, "name");
Group = converter.ToString(properties, "group");
var measureDetails = converter.GetListValue(properties, "measureDetails");
FontSize = converter.ToNullInt(properties, "fontsize");
Dimension = converter.ToInt(properties, "dimension");
var derivedData = converter.GetDictValue(properties, "derivedData");
string measureReliability = converter.ToString(properties, "measureReliability");
string measurementTool = converter.ToString(properties, "measurementTool");
var pointsWithErrors = converter.GetListValue(properties, "pointsWithErrors");
ValidGeometry = converter.ToBool(properties, "validGeometry");
var observationLines = converter.GetDictValue(properties, "observationLines");
MeasureDetails = new List<IMeasureDetails>();
PointsWithErrors = new List<int>();
ObservationLines = new ObservationLines(observationLines);
var wgsGeometry = converter.GetDictValue(properties, "wgsGeometry");
if (wgsGeometry != null)
{
switch (geometryType)
{
case GeometryType.Point:
WgsGeometry = new Point(wgsGeometry);
break;
case GeometryType.LineString:
WgsGeometry = new LineString(wgsGeometry);
break;
case GeometryType.Polygon:
WgsGeometry = new Polygon(wgsGeometry);
break;
case GeometryType.Unknown:
WgsGeometry = null;
break;
}
Add("WgsGeometry", WgsGeometry);
}
switch (measurementTool)
{
case "MAP":
MeasurementTool = MeasurementTools.Map;
break;
case "PANORAMA":
MeasurementTool = MeasurementTools.Panorama;
break;
case "POINTCLOUD":
MeasurementTool = MeasurementTools.PointCloud;
break;
case "OBLIQUE":
MeasurementTool = MeasurementTools.Oblique;
break;
}
foreach (var measureDetail in measureDetails)
{
MeasureDetails.Add(new MeasureDetails(measureDetail as Dictionary<string, object>, MeasurementTool));
}
try
{
CustomGeometryType =
(CustomGeometryType) converter.ToEnum(typeof(CustomGeometryType), properties, "customGeometryType");
}
catch (ArgumentException)
{
CustomGeometryType = CustomGeometryType.NotDefined;
}
switch (geometryType)
{
case GeometryType.Point:
DerivedData = new DerivedDataPoint(derivedData);
break;
case GeometryType.LineString:
DerivedData = new DerivedDataLineString(derivedData);
break;
case GeometryType.Polygon:
DerivedData = new DerivedDataPolygon(derivedData);
break;
case GeometryType.Unknown:
DerivedData = null;
break;
}
switch (measureReliability)
{
case "RELIABLE":
MeasureReliability = Reliability.Reliable;
break;
case "ACCEPTABLE":
MeasureReliability = Reliability.Acceptable;
break;
case "UNRELIABLE":
MeasureReliability = Reliability.Unreliable;
break;
}
foreach (var pointsWithError in pointsWithErrors)
{
PointsWithErrors.Add(pointsWithError as int? ?? 0);
}
Add("Id", Id);
Add("Name", Name);
Add("Group", Group);
Add("MeasureDetails", MeasureDetails);
Add("Dimension", Dimension);
Add("CustomGeometryType", CustomGeometryType);
Add("DerivedData", DerivedData);
Add("MeasureReliability", MeasureReliability);
Add("PointsWithErrors", PointsWithErrors);
Add("ValidGeometry", ValidGeometry);
Add("ObservationLines", ObservationLines);
Add("MeasurementTool", MeasurementTool);
if (FontSize != null)
{
Add("FontSize", FontSize);
}
}
public MeasurementProperties(IMeasurementProperties properties)
{
if (properties != null)
{
Id = properties.Id != null ? string.Copy(properties.Id) : null;
Name = properties.Name != null ? string.Copy(properties.Name) : null;
Group = properties.Group != null ? string.Copy(properties.Group) : null;
MeasurementTool = properties.MeasurementTool;
if (properties.MeasureDetails != null)
{
MeasureDetails = new List<IMeasureDetails>();
foreach (var measureDetail in properties.MeasureDetails)
{
MeasureDetails.Add(new MeasureDetails(measureDetail, MeasurementTool));
}
}
Dimension = properties.Dimension;
FontSize = properties.FontSize;
CustomGeometryType = properties.CustomGeometryType;
IDerivedData derivedData = properties.DerivedData;
switch (derivedData)
{
case IDerivedDataPoint point:
DerivedData = new DerivedDataPoint(point);
break;
case IDerivedDataPolygon polygon:
DerivedData = new DerivedDataPolygon(polygon);
break;
case IDerivedDataLineString lineString:
DerivedData = new DerivedDataLineString(lineString);
break;
}
MeasureReliability = properties.MeasureReliability;
if (properties.PointsWithErrors != null)
{
PointsWithErrors = new List<int>();
foreach (int pointWithError in properties.PointsWithErrors)
{
PointsWithErrors.Add(pointWithError);
}
}
ValidGeometry = properties.ValidGeometry;
ObservationLines = new ObservationLines(properties.ObservationLines);
IGeometry wgsGeometry = properties.WgsGeometry;
switch (wgsGeometry)
{
case IPoint point:
WgsGeometry = new Point(point);
break;
case ILineString lineString:
WgsGeometry = new LineString(lineString);
break;
case IPolygon polygon:
WgsGeometry = new Polygon(polygon);
break;
}
if (WgsGeometry != null)
{
Add("WgsGeometry", WgsGeometry);
}
Add("Id", Id);
Add("Name", Name);
Add("Group", Group);
Add("MeasureDetails", MeasureDetails);
Add("Dimension", Dimension);
Add("CustomGeometryType", CustomGeometryType);
Add("DerivedData", DerivedData);
Add("MeasureReliability", MeasureReliability);
Add("PointsWithErrors", PointsWithErrors);
Add("ValidGeometry", ValidGeometry);
Add("ObservationLines", ObservationLines);
Add("MeasurementTool", MeasurementTool);
if (FontSize != null)
{
Add("FontSize", FontSize);
}
}
}
public string Id { get; }
public string Name { get; set; }
public string Group { get; }
public IList<IMeasureDetails> MeasureDetails { get; }
public int? FontSize { get; }
public int Dimension { get; }
public CustomGeometryType CustomGeometryType { get; }
public IDerivedData DerivedData { get; }
public Reliability MeasureReliability { get; }
public IList<int> PointsWithErrors { get; }
public bool ValidGeometry { get; }
public IObservationLines ObservationLines { get; }
public MeasurementTools MeasurementTool { get; }
public IGeometry WgsGeometry { get; }
public override string ToString()
{
string pointsWithErrors = PointsWithErrors.Aggregate("[", (current, point) => $"{current}{point},");
string pointsWithErrorsStr = $"{pointsWithErrors.Substring(0, Math.Max(pointsWithErrors.Length - 1, 1))}]";
string measureDetails = MeasureDetails.Aggregate("[", (current, detail) => $"{current}{detail},");
string measureDetailsStr = MeasureDetails.Count >= 1 || MeasurementTool == MeasurementTools.Oblique
? $",\"measureDetails\":{measureDetails.Substring(0, Math.Max(measureDetails.Length - 1, 1))}]"
: string.Empty;
string fontSize = FontSize == null ? string.Empty : $",\"fontSize\": {FontSize}";
string customGeometryType = MeasurementTool == MeasurementTools.Oblique ? string.Empty : $",\"customGeometryType\":\"{CustomGeometryType.Description()}\"";
string strGeometry = WgsGeometry == null ? string.Empty : $",{WgsGeometry.ToString().Replace("geometry", "wgsGeometry")}";
string properties = $"\"id\":\"{Id}\",\"name\":\"{Name}\",\"group\":\"{Group}\"{measureDetailsStr}{fontSize},\"dimension\":{Dimension}" +
$"{customGeometryType},\"derivedData\":{DerivedData}" +
$",\"measureReliability\":\"{MeasureReliability.Description()}\",\"pointsWithErrors\":{pointsWithErrorsStr}" +
$",\"validGeometry\":{ValidGeometry.ToJsBool()},\"observationLines\":{ObservationLines}" +
$"{strGeometry},\"measurementTool\":\"{MeasurementTool.Description()}\"";
return $"\"properties\":{{{properties}}}";
}
}
}
| lgpl-3.0 |
Nath99000/TougherTools | src/main/java/com/nath99000/toughertools/block/BlockSteel.java | 275 | package com.nath99000.toughertools.block;
import net.minecraft.block.material.Material;
public class BlockSteel extends BlockTT{
public BlockSteel(){
super();
setBlockName("SteelBlock");
setHardness(30.0F);
setResistance(30.0F);
}
}
| lgpl-3.0 |
meteoinfo/meteoinfolib | src/org/meteoinfo/data/mapdata/webmap/GoogleSatelliteMapInfo.java | 1381 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.meteoinfo.data.mapdata.webmap;
/**
*
* @author yaqiang
*/
public class GoogleSatelliteMapInfo extends TileFactoryInfo {
// <editor-fold desc="Variables">
// </editor-fold>
// <editor-fold desc="Constructor">
/**
* Constructor
*/
public GoogleSatelliteMapInfo() {
super("GoogleSatelliteMap", 1, 17, 19,
256, true, true, // tile size is 256 and x/y orientation is normal
"http://mt3.google.cn/vt/lyrs=s&hl=%1$s&gl=cn&x=%2$d&y=%3$d&z=%4$d&s=Galil",
"x", "y", "z");
//String url = "http://mt1.google.com/vt/lyrs=y&hl=%s&x=%d&y=%d&z=%d&s=Ga";
//String url = "http://mt3.google.com/vt/lyrs=s&hl=%1$s&gl=cn&x=%2$d&y=%3$d&z=%4$d&s=Galil";
//this.baseURL = url;
}
// // </editor-fold>
// // <editor-fold desc="Get Set Methods">
// // </editor-fold>
// // <editor-fold desc="Methods">
@Override
public String getTileUrl(int x, int y, int zoom) {
zoom = this.getTotalMapZoom() - zoom;
String url = String.format(this.baseURL, this.getLanguage(), x, y, zoom);
//String url = String.format(this.baseURL, x, y, zoom);
return url;
}
// </editor-fold>
}
| lgpl-3.0 |
dreamcat4/moonshadow_old | test/test_helper.rb | 875 | # Must set before requiring generator libs.
TMP_ROOT = File.dirname(__FILE__) + "/tmp" unless defined?(TMP_ROOT)
PROJECT_NAME = "moonshadow" unless defined?(PROJECT_NAME)
app_root = File.join(TMP_ROOT, PROJECT_NAME)
if defined?(APP_ROOT)
APP_ROOT.replace(app_root)
else
APP_ROOT = app_root
end
#load path, rubygems
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), '/../lib')
$LOAD_PATH.unshift File.dirname(__FILE__)
require 'rubygems'
#testing dependencies
require 'test/unit'
require 'fileutils'
require 'rubigen'
require 'rubigen/helpers/generator_test_helper'
require 'mocha'
#generate and require the fake rails app
`rails --force #{APP_ROOT}`
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= APP_ROOT
require File.expand_path(File.join(APP_ROOT, 'config/environment.rb'))
#require what we're actually testing
require 'moonshadow'
require 'shadow_puppet/test' | lgpl-3.0 |
bioothod/cocaine-core | include/cocaine/detail/raft/repository.hpp | 5727 | /*
Copyright (c) 2013-2014 Andrey Goryachev <andrey.goryachev@gmail.com>
Copyright (c) 2011-2014 Other contributors as noted in the AUTHORS file.
This file is part of Cocaine.
Cocaine is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
Cocaine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COCAINE_RAFT_REPOSITORY_HPP
#define COCAINE_RAFT_REPOSITORY_HPP
#include "cocaine/detail/raft/configuration.hpp"
#include "cocaine/detail/raft/log.hpp"
#include "cocaine/locked_ptr.hpp"
#include "cocaine/detail/atomic.hpp"
namespace cocaine { namespace raft {
// This class stores Raft actors, which replicate named state machines.
// Raft service uses this class to deliver messages from other nodes to actors.
// Core uses it to setup new state machines.
class repository_t {
friend class configuration_machine_t;
friend class control_service_t;
public:
typedef std::map<std::string, lockable_config_t> configs_type;
repository_t(context_t& context);
const node_id_t&
id() const {
return m_id;
}
const options_t&
options() const {
return m_options;
}
locked_ptr<const configs_type>
configuration() const {
return m_configs.synchronize();
}
std::shared_ptr<actor_concept_t>
get(const std::string& name) const;
template<class Machine, class Config>
std::shared_ptr<actor<
typename std::decay<Machine>::type,
typename std::decay<Config>::type
>>
insert(const std::string& name, Machine&& machine, Config&& config);
template<class Machine>
std::shared_ptr<actor<
typename std::decay<Machine>::type,
cocaine::raft::configuration<typename std::decay<Machine>::type>
>>
insert(const std::string& name, Machine&& machine);
void
activate();
private:
void
set_options(const options_t& value) {
m_options = value;
}
template<class Machine, class Config>
std::shared_ptr<actor<
typename std::decay<Machine>::type,
typename std::decay<Config>::type
>>
create_cluster(const std::string& name, Machine&& machine, Config&& config);
private:
context_t& m_context;
std::shared_ptr<io::reactor_t> m_reactor;
node_id_t m_id;
options_t m_options;
synchronized<std::map<std::string, std::shared_ptr<actor_concept_t>>> m_actors;
synchronized<configs_type> m_configs;
std::atomic<bool> m_active;
};
}} // namespace cocaine::raft
#include "cocaine/detail/raft/actor.hpp"
namespace cocaine { namespace raft {
template<class Machine, class Config>
std::shared_ptr<actor<
typename std::decay<Machine>::type,
typename std::decay<Config>::type
>>
repository_t::insert(const std::string& name, Machine&& machine, Config&& config) {
auto actors = m_actors.synchronize();
typedef typename std::decay<Machine>::type machine_type;
typedef typename std::decay<Config>::type config_type;
typedef actor<machine_type, config_type> actor_type;
auto actor = std::make_shared<actor_type>(m_context,
*m_reactor,
name,
std::forward<Machine>(machine),
std::forward<Config>(config));
if(actors->insert(std::make_pair(name, actor)).second) {
if(m_active) {
m_reactor->post(std::bind(&actor_type::join_cluster, actor));
}
return actor;
} else {
return std::shared_ptr<actor_type>();
}
}
template<class Machine>
std::shared_ptr<actor<
typename std::decay<Machine>::type,
cocaine::raft::configuration<typename std::decay<Machine>::type>
>>
repository_t::insert(const std::string& name, Machine&& machine) {
typedef cocaine::raft::configuration<typename std::decay<Machine>::type> config_type;
return insert(name,
std::forward<Machine>(machine),
config_type(cluster_config_t {std::set<node_id_t>(), boost::none}));
}
template<class Machine, class Config>
std::shared_ptr<actor<
typename std::decay<Machine>::type,
typename std::decay<Config>::type
>>
repository_t::create_cluster(const std::string& name, Machine&& machine, Config&& config) {
auto actors = m_actors.synchronize();
typedef typename std::decay<Machine>::type machine_type;
typedef typename std::decay<Config>::type config_type;
typedef actor<machine_type, config_type> actor_type;
auto actor = std::make_shared<actor_type>(m_context,
*m_reactor,
name,
std::forward<Machine>(machine),
std::forward<Config>(config));
if(actors->insert(std::make_pair(name, actor)).second) {
if(m_active) {
m_reactor->post(std::bind(&actor_type::create_cluster, actor));
}
return actor;
} else {
return std::shared_ptr<actor_type>();
}
}
}} // namespace cocaine::raft
#endif // COCAINE_RAFT_REPOSITORY_HPP
| lgpl-3.0 |
Fran89/K2Status-V2 | src/k2statusv2.cpp | 9075 | #include "k2statusv2.h"
#include "ui_k2statusv2.h"
K2StatusV2::K2StatusV2(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::K2StatusV2)
{
// Setup
ui->setupUi(this);
ui->mainToolBar->hide();
ui->actionDisconnect->setDisabled(true);
ui->actionGraph->setDisabled(true);
connect(ui->actionQuit,SIGNAL(triggered(bool)),qApp,SLOT(quit()));
// Context Menu
showGT = context.addAction("Show Temperature Graph");
showGV = context.addAction("Show Voltage Graph");
connect(showGT,SIGNAL(triggered(bool)),this,SLOT(temp()));
connect(showGV,SIGNAL(triggered(bool)),this,SLOT(volt()));
// Debug?
debug = false;
ui->textBrowser->hide();
connect(ui->actionDebug_Mode,SIGNAL(triggered(bool)),this,SLOT(DebugToggle()));
// UDP Configuration
MyUDPConfig = new UDPConfig;
connected = false;
connect(ui->actionAdd_a_Connection,SIGNAL(triggered(bool)),MyUDPConfig,SLOT(exec()));
connect(ui->actionDisconnect,SIGNAL(triggered(bool)),this,SLOT(disconnectUDP()));
connect(MyUDPConfig,SIGNAL(accepted()),this,SLOT(connectUDP()));
connect(MyUDPConfig,SIGNAL(rejected()),this,SLOT(nothing()));
// About Help
MyHelp = new AboutMe;
connect(ui->actionAbout_Me,SIGNAL(triggered(bool)),MyHelp,SLOT(show()));
connect(ui->actionAbout_QT,SIGNAL(triggered(bool)),qApp,SLOT(aboutQt()));
// Setup Socket
EWUdpSock = new K2UDPSock(this);
connect(this,SIGNAL(sendDebug(bool)),EWUdpSock,SLOT(setDebug(bool)));
connect(EWUdpSock,SIGNAL(debugMessage(QString)),this,SLOT(appendToDebugBrowser(QString)));
// EW Message Manager
MyMsgMgr = new EWMessageMgr;
EWUdpSock->setupEWMsgMgr(MyMsgMgr);
// Station Info and connect the EW Msg Manager to Station Info
MyStnInfo = new StnInfo;
connect(MyMsgMgr,SIGNAL(exportK2Status(K2INFO_HEADER*,STATUS_INFO*,QMutex*)),
MyStnInfo,SLOT(recieveK2Status(K2INFO_HEADER*,STATUS_INFO*,QMutex*)));
connect(MyMsgMgr,SIGNAL(exportK2Status2(K2INFO_HEADER*,EXT2_STATUS_INFO*,QMutex*)),
MyStnInfo,SLOT(recieveK2Status2(K2INFO_HEADER*,EXT2_STATUS_INFO*,QMutex*)));
connect(MyMsgMgr,SIGNAL(exportK2HeaderS(K2INFO_HEADER*,K2_HEADER*,QMutex*)),
MyStnInfo,SLOT(recieveK2HeaderS(K2INFO_HEADER*,K2_HEADER*,QMutex*)));
connect(MyStnInfo,SIGNAL(debugMessage(QString)),this,SLOT(appendToDebugBrowser(QString)));
connect(MyStnInfo,SIGNAL(statusMessage(QString)),this,SLOT(showStatusMessage(QString)));
// New MetadataTable and connect Station Info to DataTable
MyMetaDataTable = new MetadataTable(this);
connect(MyMetaDataTable,SIGNAL(debugMessage(QString)), this,SLOT(appendToDebugBrowser(QString)));
MyMetaDataTable->setStationInfo(MyStnInfo);
ui->MyMetadataTableView->setModel(MyMetaDataTable);
connect(MyStnInfo,SIGNAL(stationAdded(QMutex*)),MyMetaDataTable,SLOT(addStaInformation(QMutex*)));
connect(MyStnInfo,SIGNAL(stationsUpdated()),MyMetaDataTable,SLOT(updateMetadata()));
// Setup Table View
connect(MyStnInfo,SIGNAL(stationsUpdated()),this,SLOT(resizeTable()));
ui->MyMetadataTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->MyMetadataTableView->setSelectionMode(QAbstractItemView::SingleSelection);
// Setup Logging
MyK2Logger = new K2Logger;
connect(ui->actionEnable_Logging,SIGNAL(toggled(bool)),MyK2Logger,SLOT(enableLogging(bool)));
MyK2Logger->setupStations(MyStnInfo);
ui->actionEnable_Logging->setChecked(true);
connect(MyStnInfo,SIGNAL(stationLogEvt(QMutex*,QString)),MyK2Logger,SLOT(startLog(QMutex*,QString)));
connect(MyStnInfo,SIGNAL(stationXmlEvt(QString)),MyK2Logger,SLOT(writeXML(QString)));
// Add a station
ui->actionLoad_Station_list->setDisabled(true);
connect(ui->actionLoad_Station_list,SIGNAL(triggered(bool)),this,SLOT(addStation()));
// Add K2 Graph;
MyK2Graph = new K2Graph(false,this);
MyK2Graph->setStations(MyStnInfo);
ui->MyMetadataTableView->setContextMenuPolicy(Qt::CustomContextMenu);
ui->MyMetadataTableView->horizontalHeader()->setSectionsClickable(true);
connect(ui->actionGraph,SIGNAL(triggered(bool)),MyK2Graph,SLOT(show()));
connect(MyStnInfo,SIGNAL(stationsUpdated()),MyK2Graph,SLOT(stnupdated()));
connect(ui->MyMetadataTableView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(onClicked(QPoint)));
connect(ui->MyMetadataTableView->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(onLClicked(int)));
// Status
status = new QLabel;
ui->statusBar->addWidget(status);
}
K2StatusV2::~K2StatusV2()
{
delete ui;
delete MyHelp;
}
// Show Status Message
void K2StatusV2::showStatusMessage(const QString &message)
{
status->setText(message);
}
// Append to Debug Browser
void K2StatusV2::appendToDebugBrowser(const QString &message)
{
ui->textBrowser->append(message);
}
// Toggle Debug Mode
void K2StatusV2::DebugToggle()
{
if(debug){
debug = false;
emit sendDebug(debug);
ui->textBrowser->hide();
showStatusMessage("Debug mode is off");
} else {
debug = true;
emit sendDebug(debug);
ui->textBrowser->show();
showStatusMessage("Debug mode is on");
}
}
// Connect to EW UDP
void K2StatusV2::connectUDP()
{
showStatusMessage("Connecting");
appendToDebugBrowser("UDP Connecting");
quint16 Port = MyUDPConfig->config.Port.toInt();
QHostAddress IP(MyUDPConfig->config.MyIPAddress.toString());
MyK2Logger->setupPath(QDir(MyUDPConfig->config.LogFolder.toString()));
MyStnInfo->reloadStations(QDir(MyUDPConfig->config.LogFolder.toString()));
MyK2Graph->setPath(QDir(MyUDPConfig->config.LogFolder.toString()));
MyK2Graph->stnupdated();
if (!connected){
if (EWUdpSock->bind(IP,Port)) {
connected = true;
showStatusMessage("Connected!");
ui->actionAdd_a_Connection->setDisabled(true);
ui->actionLoad_Station_list->setEnabled(true);
ui->actionGraph->setEnabled(true);
ui->actionDisconnect->setEnabled(true);
appendToDebugBrowser("K2Status connected");
}
else {
connected = false;
showStatusMessage("Could not connect, is the port being used?");
appendToDebugBrowser("K2Status could not connect");
}
}
}
// Disconnect UDP
void K2StatusV2::disconnectUDP()
{
if(connected){
EWUdpSock->close();
showStatusMessage("Disconnected");
ui->actionLoad_Station_list->setDisabled(true);
ui->actionAdd_a_Connection->setEnabled(true);
ui->actionGraph->setDisabled(true);
ui->actionDisconnect->setDisabled(true);
connected=false;
}
}
// Do nothing if canceled
void K2StatusV2::nothing(){
showStatusMessage("Not Connecting");
}
// Resize Table
void K2StatusV2::resizeTable(){
ui->MyMetadataTableView->resizeColumnsToContents();
ui->MyMetadataTableView->repaint();
//this->setFixedWidth(ui->MyMetadataTableView->horizontalHeader()->length()+45);
}
// Add a station
void K2StatusV2::addStation(){
QString staName;
QString netName;
bool stard;
staName = QInputDialog::getText(this,"Add a station", "Station" ,QLineEdit::Normal,"NULL",&stard);
netName = QInputDialog::getText(this,"Station Network", "Network" ,QLineEdit::Normal,"XX",&stard);
if(stard && staName != "NULL" && netName != "XX" && !staName.isEmpty() && !netName.isEmpty())
MyStnInfo->stationIndex(staName,netName);
appendToDebugBrowser("Added: " + staName);
MyK2Graph->stnupdated();
}
// On right clicked
void K2StatusV2::onClicked(QPoint index){
int row;
row = ui->MyMetadataTableView->rowAt(index.y());
if(row >= 0){
currentsta.clear();
currentsta = MyStnInfo->Stations.value(MyStnInfo->Stations.keys().at(row))->Station;
context.exec(QCursor::pos());
}
return;
}
//On left clicked
void K2StatusV2::onLClicked(int index){
appendToDebugBrowser("What is:" + QString::number(index));
if(index == 11)
ui->MyMetadataTableView->hideColumn(index);
}
void K2StatusV2::keyPressEvent(QKeyEvent * key){
if(key->key() == Qt::Key_Escape)
ui->MyMetadataTableView->clearSelection();
}
void K2StatusV2::volt(){
appendToDebugBrowser(currentsta);
K2Graph *station;
station = new K2Graph(true,this);
station->setAttribute( Qt::WA_DeleteOnClose, true );
station->setWindowTitle(currentsta + " Voltage");
station->setPath(QDir(MyUDPConfig->config.LogFolder.toString()));
station->showVGraph(currentsta);
station->show();
currentsta.clear();
}
void K2StatusV2::temp(){
appendToDebugBrowser(currentsta);
K2Graph *station;
station = new K2Graph(true,this);
station->setAttribute( Qt::WA_DeleteOnClose, true );
station->setWindowTitle(currentsta + " Temperature");
station->setPath(QDir(MyUDPConfig->config.LogFolder.toString()));
station->showTGraph(currentsta);
station->show();
currentsta.clear();
}
| lgpl-3.0 |
jeid64/xdmod | html/controllers/role_manager/downgrade_member.php | 870 | <?php
\xd_security\assertParameterSet('member_id', RESTRICTION_UID);
// -----------------------------
$member = XDUser::getUserByID($_POST['member_id']);
if ($member == NULL){
\xd_response\presentError('user_does_not_exist');
}
// -----------------------------
try {
$active_user = \xd_security\getLoggedInUser();
$member_organizations = $member->getOrganizationCollection();
if (!in_array($active_user->getActiveOrganization(), $member_organizations)) {
\xd_response\presentError('center_mismatch_between_member_and_director');
}
$active_user->getActiveRole()->downgradeStaffMember($member);
$returnData['success'] = true;
}
catch (\Exception $e){
\xd_response\presentError($e->getMessage());
}
echo json_encode($returnData);
?> | lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter | pdfreporter-core/src/org/oss/pdfreporter/engine/export/JRHyperlinkProducer.java | 1666 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2011 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oss.pdfreporter.engine.export;
import org.oss.pdfreporter.engine.JRPrintHyperlink;
/**
* A simple hyperlink generator that can be used to handle custom
* hyperlink types.
* <p>
* The generator produces Strings which should be used as hyperlinks.
* </p>
*
* @author Lucian Chirita (lucianc@users.sourceforge.net)
* @version $Id: JRHyperlinkProducer.java 5180 2012-03-29 13:23:12Z teodord $
*/
public interface JRHyperlinkProducer
{
/**
* Generates the String hyperlink for a hyperlink instance.
*
* @param hyperlink the hyperlink instance
* @return the genereated String hyperlink
*/
String getHyperlink(JRPrintHyperlink hyperlink);
}
| lgpl-3.0 |
Latency/UtopianBot | src/org/rsbot/script/methods/Keyboard.java | 1573 | package org.rsbot.script.methods;
import org.rsbot.script.provider.MethodContext;
import org.rsbot.script.provider.MethodProvider;
/**
* Keyboard related operations.
*/
public class Keyboard extends MethodProvider {
public Keyboard(final MethodContext ctx) {
super(ctx);
}
/**
* Presses and releases a given key.
*
* @param c
* The character to press.
*/
public void sendKey(final char c) {
methods.inputManager.sendKey(c);
}
/**
* Types a given string.
*
* @param text
* The text to press/send.
* @param pressEnter
* <tt>true</tt> to press enter after pressing the text.
*/
public void sendText(final String text, final boolean pressEnter) {
methods.inputManager.sendKeys(text, pressEnter);
}
/**
* Types a given string instantly.
*
* @param text
* The text to press/send.
* @param pressEnter
* <tt>true</tt> to press enter after pressing the text.
*/
public void sendTextInstant(final String text, final boolean pressEnter) {
methods.inputManager.sendKeysInstant(text, pressEnter);
}
/**
* Presses and holds a given key.
*
* @param c
* The character to press.
* @see #releaseKey(char)
*/
public void pressKey(final char c) {
methods.inputManager.pressKey(c);
}
/**
* Releases a given held key.
*
* @param c
* The character to release.
* @see #pressKey(char)
*/
public void releaseKey(final char c) {
methods.inputManager.releaseKey(c);
}
}
| lgpl-3.0 |
iskoda/Bubing-crawler-BUT | test/it/unimi/di/law/warc/io/RandomReadWritesTest.java | 11099 | package it.unimi.di.law.warc.io;
/*
* Copyright (C) 2013 Paolo Boldi, Massimo Santini, and Sebastiano Vigna
*
* 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/>.
*
*/
//RELEASE-STATUS: DIST
import it.unimi.di.law.warc.io.gzarc.GZIPIndexer;
import it.unimi.di.law.warc.records.HttpRequestWarcRecord;
import it.unimi.di.law.warc.records.HttpResponseWarcRecord;
import it.unimi.di.law.warc.records.RandomTestMocks;
import it.unimi.di.law.warc.records.WarcRecord;
import it.unimi.di.law.warc.util.BufferedHttpEntityFactory;
import it.unimi.dsi.fastutil.io.FastBufferedInputStream;
import it.unimi.dsi.fastutil.io.FastBufferedOutputStream;
import it.unimi.dsi.fastutil.longs.LongBigArrayBigList;
import it.unimi.dsi.logging.ProgressLogger;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.ByteStreams;
import com.google.common.io.CountingInputStream;
import com.google.common.io.CountingOutputStream;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Parameter;
import com.martiansoftware.jsap.SimpleJSAP;
import com.martiansoftware.jsap.Switch;
import com.martiansoftware.jsap.UnflaggedOption;
public class RandomReadWritesTest {
private final static Logger LOGGER = LoggerFactory.getLogger( RandomReadWritesTest.class );
final static int RND_RECORDS = 100;
final static int MAX_NUMBER_OF_HEADERS = 50;
final static int MAX_LENGTH_OF_HEADER = 20;
final static int MAX_LENGTH_OF_BODY = 10 * 1024;
final static float RESPONSE_PROBABILITY = 0.7f;
final static int TEST_RECORDS = 200;
private WarcRecord[] randomRecords;
@Before
public void init() throws IOException {
randomRecords = prepareRndRecords();
}
public static WarcRecord[] prepareRndRecords() throws IOException {
return prepareRndRecords( RND_RECORDS, RESPONSE_PROBABILITY, MAX_NUMBER_OF_HEADERS, MAX_LENGTH_OF_HEADER, MAX_LENGTH_OF_BODY );
}
public static WarcRecord[] prepareRndRecords( final int numRecords, final float responseProbability) throws IOException {
return prepareRndRecords( numRecords, responseProbability, MAX_NUMBER_OF_HEADERS, MAX_LENGTH_OF_HEADER, MAX_LENGTH_OF_BODY );
}
public static WarcRecord[] prepareRndRecords( final int numRecords, final float responseProbability, final int maxNumberOfHeaders, final int maxLenghtOfHeader, final int maxLengthOfBody ) throws IOException {
final WarcRecord[] randomRecords = new WarcRecord[ numRecords ];
URI fakeUri = null;
try {
fakeUri = new URI( "http://this.is/a/fake" );
} catch ( URISyntaxException ignored ) {}
for ( int pos = 0; pos < numRecords; pos++ ) {
if ( RandomTestMocks.RNG.nextFloat() < responseProbability )
randomRecords[ pos ] = new HttpResponseWarcRecord( fakeUri, new RandomTestMocks.HttpResponse( maxNumberOfHeaders, maxLenghtOfHeader, maxLengthOfBody, pos ), BufferedHttpEntityFactory.INSTANCE );
else
randomRecords[ pos ] = new HttpRequestWarcRecord( fakeUri, new RandomTestMocks.HttpRequest( maxNumberOfHeaders, maxLenghtOfHeader, pos ) );
}
return randomRecords;
}
public static int[] writeRecords( final String path, final int numRecords, final WarcRecord[] randomRecords, final int parallel ) throws IOException, InterruptedException {
final ProgressLogger pl = new ProgressLogger( LOGGER, "records" );
if ( parallel <= 1 ) pl.expectedUpdates = numRecords;
final ProgressLogger plb = new ProgressLogger( LOGGER, "KB" );
final CountingOutputStream cos = new CountingOutputStream( new FastBufferedOutputStream( new FileOutputStream ( path ) ) );
final WarcWriter ww;
if ( parallel == 0 ) {
ww = new UncompressedWarcWriter( cos );
pl.start( "Writing records…" );
} else if ( parallel == 1 ) {
ww = new CompressedWarcWriter( cos );
pl.start( "Writing records (compressed)…" );
} else {
ww = null;
pl.start( "SOULD NOT HAPPEN" );
}
plb.start();
long written = 0;
int[] position = new int[ numRecords ];
for ( int i = 0; i < numRecords; i++ ) {
int pos = RandomTestMocks.RNG.nextInt( randomRecords.length );
position[ i ] = pos;
ww.write( randomRecords[ pos ] );
if ( parallel <= 0 ) {
pl.lightUpdate();
plb.update( ( cos.getCount() - written ) / 1024 );
}
written = cos.getCount();
}
ww.close();
pl.done( numRecords );
plb.done( cos.getCount() );
return position;
}
protected static int getPosition( final WarcRecord record ) {
int pos;
if ( record instanceof HttpResponseWarcRecord ) {
HttpResponseWarcRecord response = (HttpResponseWarcRecord)record;
pos = Integer.parseInt( response.getFirstHeader( "Position" ).getValue() );
} else
pos = Integer.parseInt( ((HttpRequestWarcRecord)record).getFirstHeader( "Position" ).getValue() );
return pos;
}
protected static void readRecords( final String path, final int[] position, final int maxLengthOfBody, final boolean readFully, final boolean compress ) throws IOException {
ProgressLogger pl = new ProgressLogger( LOGGER, "records" );
ProgressLogger plb = new ProgressLogger( LOGGER, "KB" );
CountingInputStream cis = new CountingInputStream( new FileInputStream( path ) );
WarcReader wr = compress ? new CompressedWarcReader( cis ) : new UncompressedWarcReader( cis );
pl.start( "Reading records" + ( readFully ? " (fully)" : "" ) + ( compress ? " (compressed)…" : "…" ) );
plb.start();
long read = 0;
byte[] body = new byte[ maxLengthOfBody ];
for ( int i = 0 ;; i++ ) {
WarcRecord record = wr.read();
if ( record == null ) break;
if ( readFully ) {
int pos = getPosition( record );
if ( record instanceof HttpResponseWarcRecord ) {
HttpResponseWarcRecord response = (HttpResponseWarcRecord)record;
HttpEntity entity = response.getEntity();
ByteStreams.readFully( entity.getContent(), body, 0, (int)entity.getContentLength() );
}
assert position[ i ] == pos : "At position " + i + " expected record " + position[ i ] + ", but found record " + pos;
}
pl.lightUpdate();
plb.update( ( cis.getCount() - read ) / 1024 );
read = cis.getCount();
}
pl.done();
plb.done();
cis.close();
}
@Test
public void testUncompressedWritesReads() throws IOException, InterruptedException {
final String path = "/tmp/random.warc";
int[] sequence = writeRecords( path, TEST_RECORDS, randomRecords, 0 );
readRecords( path, sequence, MAX_LENGTH_OF_BODY, true, false );
}
@Test
public void testCompressedWritesReads() throws IOException, InterruptedException {
final String path = "/tmp/random.warc.gz";
int[] sequence = writeRecords( path, TEST_RECORDS, randomRecords, 1 );
readRecords( path, sequence, MAX_LENGTH_OF_BODY, true, true );
}
@Test
public void testCompressedIndexedReads() throws IOException, InterruptedException {
final String path = "/tmp/random.warc.gz";
int[] sequence = writeRecords( path, TEST_RECORDS, randomRecords, 1 );
final LongBigArrayBigList index = GZIPIndexer.index( new FileInputStream( path ) );
final FastBufferedInputStream input = new FastBufferedInputStream( new FileInputStream( path ) );
WarcReader wr = new CompressedWarcReader( input );
for ( int i = (int)index.size64() - 1; i >= 0 ; i-- ) {
wr.position( index.getLong( i ) );
WarcRecord r = wr.read();
int pos = getPosition( r );
System.err.println( sequence[ i ] + " DIOCANE " + pos );
assert sequence[ i ] == pos : "At position " + i + " expected record " + sequence[ i ] + ", but found record " + pos;
System.err.println( pos );
}
readRecords( path, sequence, MAX_LENGTH_OF_BODY, true, true );
}
@Test
public void testCompressedCachedIndexedReads() throws IOException, InterruptedException {
final String path = "/tmp/random.warc.gz";
int[] sequence = writeRecords( path, TEST_RECORDS, randomRecords, 1 );
final LongBigArrayBigList index = GZIPIndexer.index( new FileInputStream( path ) );
final FastBufferedInputStream input = new FastBufferedInputStream( new FileInputStream( path ) );
WarcCachingReader cwr = new CompressedWarcCachingReader( input );
for ( int i = (int)index.size64() - 1; i >= 0 ; i-- ) {
cwr.position( index.getLong( i ) );
WarcRecord r = cwr.cache().read();
int pos = getPosition( r );
assert sequence[ i ] == pos : "At position " + i + " expected record " + sequence[ i ] + ", but found record " + pos;
}
readRecords( path, sequence, MAX_LENGTH_OF_BODY, true, true );
}
public static void main( String[] args ) throws JSAPException, IOException, InterruptedException {
SimpleJSAP jsap = new SimpleJSAP( RandomReadWritesTest.class.getName(), "Writes some random records on disk.",
new Parameter[] {
new FlaggedOption( "random", JSAP.INTEGER_PARSER, "100", JSAP.NOT_REQUIRED, 'r', "random", "The number of random record to sample from."),
new FlaggedOption( "body", JSAP.INTSIZE_PARSER, "4K", JSAP.NOT_REQUIRED, 'b', "body", "The maximum size of the random generated body (in bytes)."),
new Switch( "fully", 'f', "fully", "Whether to read fully the record (and do a minimal sequential cosnsistency check)."),
new Switch( "writeonly", 'w', "writeonly", "Whether to skip the read part (if present, 'fully' will be ignored." ),
new UnflaggedOption( "path", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The path to write to." ),
new UnflaggedOption( "records", JSAP.INTSIZE_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The numer of records to write." ),
} );
final JSAPResult jsapResult = jsap.parse( args );
if ( jsap.messagePrinted() ) System.exit( 1 );
final String path = jsapResult.getString( "path" );
boolean compress = path.endsWith( ".gz" );
boolean fully = jsapResult.getBoolean( "fully" );
int parallel = compress ? 1 : 0;
int body = jsapResult.getInt( "body" );
final WarcRecord[] rnd = prepareRndRecords( jsapResult.getInt( "random" ), RESPONSE_PROBABILITY, MAX_NUMBER_OF_HEADERS, MAX_LENGTH_OF_HEADER, body );
final int[] sequence = writeRecords( path, jsapResult.getInt( "records" ), rnd, parallel );
if ( ! jsapResult.getBoolean( "writeonly" ) )
readRecords( path, sequence, body, fully, compress );
}
}
| lgpl-3.0 |
marianosimone/a-tale-of-two-brains | src/game_layout.rb | 7515 | require 'game_scene'
require 'images_provider'
class GameLayout < Gtk::VBox
def initialize(main_window,filename, game)
super()
@game = game
@main_window=main_window
time = Time.new
layout = Gtk::VBox.new
menubar = Gtk::MenuBar.new
menubar.append(menu_item)
menubar.append(acciones_item)
layout.pack_start(menubar, false, false, 0)
@main_window.add_events(Gdk::Event::KEY_PRESS)
@key_press_signal_id = @main_window.signal_connect("key-press-event") do |w, e|
if e.keyval == 116 #t
end_turn
end
end
@game_scene = GameScene.new(filename, game) { |selected| @selected_character_info.update(selected)}
layout.pack_start(@game_scene, false, false, 0)
info_layout = Gtk::HBox.new
@status_bar = PlayersStatusBar.new(game)
@status_bar.update
info_layout.pack_start(@status_bar, true, true, 0)
info_layout.pack_start(Gtk::VSeparator.new,false,false,5)
@selected_character_info = CharacterInfoBox.new
info_layout.pack_start(@selected_character_info, false, false, 5)
layout.pack_start(info_layout, false, false, 0)
pack_start(layout)
show_all
end
private
def menu_item
menu_item = Gtk::MenuItem.new("Menu")
game_menu = Gtk::Menu.new
menu_item.set_submenu(game_menu)
item_back = Gtk::MenuItem.new("Volver a empezar")
item_help=Gtk::MenuItem.new("Ayuda")
item_exit = Gtk::MenuItem.new("Salir del Juego")
game_menu.append(item_back)
game_menu.append(item_help)
game_menu.append(item_exit)
item_back.signal_connect("activate"){
@main_window.remove(self)
@main_window.signal_handler_disconnect(@key_press_signal_id) if @main_window.signal_handler_is_connected?(@key_press_signal_id)
SoundsPlayer.instance.play_background(MainMenuMusic)
@main_window.toConfigWin
}
item_help.signal_connect("activate"){}
item_exit.signal_connect("activate"){
save_info_for_reports
Gtk.main_quit
}
return menu_item
end
def acciones_item
acciones_item = Gtk::MenuItem.new("Acciones")
acciones_menu = Gtk::Menu.new
acciones_item.set_submenu(acciones_menu)
item_fin_turno = Gtk::MenuItem.new("Fin de turno")
acciones_menu.append(item_fin_turno)
item_fin_turno.signal_connect("activate"){ end_turn }
return acciones_item
end
def end_turn
taken_action = @game.play_round
@status_bar.update(taken_action)
@game_scene.update_from_action(taken_action)
@status_bar.update
if @game.can_continue?
#end_turn unless !@game.active_player.automatic? #TODO: Sacar en la presentacion, para poder ir viendo paso a paso
else
@main_window.signal_handler_disconnect(@key_press_signal_id) if @main_window.signal_handler_is_connected?(@key_press_signal_id)
@game_scene.end_of_game
end
end
end
class CharacterInfoBox < Gtk::VBox
def initialize
super()
#No uso el ImagesProvider porque necesito ir modificando el pixbuf y no la image
@pixbuf = Gdk::Pixbuf.new("#{SpritesLocation}/shadow.png")
@image = Gtk::Image.new(@pixbuf)
#"Miembros: 10"
@name_label = Gtk::Label.new("Informacion ")
@alive_memebers = Gtk::Label.new("")
pack_start(@name_label,false, false, 0)
pack_start(@alive_memebers, false, false, 0)
pack_start(@image, false, false, 0)
show_all
end
def update(character)
return unless (not character.nil?) #TODO: Podriamos hacer que si no es un character, mostremos info de terreno?
remove(@image)
@pixbuf = Gdk::Pixbuf.new(character.file_image_name)
@image = Gtk::Image.new(@pixbuf)
@name_label.text = character.nice_name
@alive_memebers.text = "Miembros: #{character.number_of_members}"
pack_start(@image, false, false, 0)
show_all
end
end
class AttackWindow < Gtk::Window
def initialize(player, attacker,x,y)
super("Ataque")
set_icon(IconLocation)
set_window_position(Gtk::Window::POS_CENTER)
self.modal = true
self.skip_taskbar_hint = true
self.resizable = false
@ppal_box = Gtk::VBox.new
@ppal_box.pack_start(Gtk::Label.new("\n Seleccione el tipo de ataque para: #{attacker.nice_name} \n"),false,false,0)
@central_box=Gtk::HBox.new
@radio_box=Gtk::VBox.new
@radio_box.set_border_width(10)
@buttons_box=Gtk::HBox.new
@button_ok = Gtk::Button.new("Aceptar")
@button_cancel = Gtk::Button.new("Cancelar")
update_attacks(player, attacker,x,y)
end
def active_attack_type
@buttons.each { |b|
b.each { |label|
return AttackType.value_for(label.text) if b.active?
}
}
end
def update_attacks(player, attacker,x,y)
@buttons=[]
attacker.possible_attacks_to(x,y).each_with_index{|attack,index|
if index == 0
radioButton = Gtk::RadioButton.new(AttackType.name_for(attack))
radioButton.set_active(true)
else
radioButton = Gtk::RadioButton.new(@buttons[index-1],AttackType.name_for(attack))
end
@buttons << radioButton
#agrego el resto de los radioButtons
@radio_box.pack_start(radioButton,false,false,0)
}
@central_box.pack_start(@radio_box,false,false,0)
@central_box.pack_start(Gtk::Image.new(Gdk::Pixbuf.new(attacker.file_image_name)))
@buttons_box.pack_start(@button_ok)
@buttons_box.pack_start(@button_cancel)
@button_ok.signal_connect("clicked"){
player.notify_selection(active_attack_type)
hide
}
@button_cancel.signal_connect("clicked"){
hide
}
@ppal_box.pack_start(@central_box,false,false,0)
@ppal_box.pack_start(@buttons_box,false,false,0)
add(@ppal_box)
end
end
class PlayersStatusBar < Gtk::Table
def initialize(game)
super(game.players.size, 5, false)
@game = game
@players_units_labels = []
@active_player_labels = []
@last_action_labels = []
@game.players.each_with_index{|player, i|
row_begin, row_end = i+1, i+2
attach(ImagesProvider.get(:flag, player.color), 0, 1, row_begin, row_end, Gtk::SHRINK, Gtk::SHRINK, 5, 5)
attach(Gtk::Label.new(player.name), 1, 2, row_begin, row_end, Gtk::SHRINK, Gtk::SHRINK, 5, 5)
attach(ImagesProvider.get(:units_icon), 3, 4, row_begin, row_end, Gtk::SHRINK, Gtk::SHRINK, 5, 5)
label_units = Gtk::Label.new(player.number_of_units.to_s)
@players_units_labels << label_units
attach(label_units, 4, 5, row_begin, row_end, Gtk::SHRINK, Gtk::SHRINK, 5, 0)
label_active_player = Gtk::Label.new("")
@active_player_labels << label_active_player
attach(label_active_player, 5, 6, row_begin, row_end, Gtk::SHRINK, Gtk::SHRINK, 5, 0)
last_action_label = Gtk::Label.new("")
@last_action_labels << last_action_label
attach(last_action_label, 6, 7, row_begin, row_end, Gtk::SHRINK, Gtk::SHRINK, 5, 0)
}
end
def update(taken_action = nil)
@players_units_labels.each_with_index{|label,index|
label.text = "#{@game.players[index].number_of_units}"
}
@active_player_labels.each_with_index{|label,index|
label.text = @game.players[index] == @game.active_player ? '[X]' : ''
}
if taken_action
@last_action_labels.each_with_index{|label,index|
label.set_text("#{taken_action.description}") unless @game.players[index] == @game.active_player
}
end
end
end
| lgpl-3.0 |
akwiatkowski/gpx_utils | spec/gpx_utils/track_importer_spec.rb | 506 | require 'spec_helper'
describe GpxUtils::TrackImporter do
it "should parse garmin etrex gpx file" do
g = GpxUtils::TrackImporter.new
g.add_file(File.join('spec', 'fixtures', 'sample.gpx'))
g.coords.should be_kind_of(Array)
g.coords.size.should == 602
g.coords.each do |coord|
coord[:lat].should be_kind_of(Float)
coord[:lon].should be_kind_of(Float)
coord[:lat].should_not == 0.0
coord[:lon].should_not == 0.0
end
g.error_count.should == 1
end
end
| lgpl-3.0 |
Alfresco/activiti-android-app | activiti-app/src/main/java/com/activiti/android/app/fragments/task/TaskDetailsFragment.java | 9496 | /*
* Copyright (C) 2005-2016 Alfresco Software Limited.
*
* This file is part of Alfresco Activiti Mobile for Android.
*
* Alfresco Activiti Mobile for Android is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco Activiti Mobile for Android is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package com.activiti.android.app.fragments.task;
import java.util.Map;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.activiti.android.app.R;
import com.activiti.android.app.activity.MainActivity;
import com.activiti.android.app.fragments.process.ProcessDetailsFragment;
import com.activiti.android.platform.event.CreateTaskEvent;
import com.activiti.android.platform.integration.analytics.AnalyticsHelper;
import com.activiti.android.platform.integration.analytics.AnalyticsManager;
import com.activiti.android.platform.intent.IntentUtils;
import com.activiti.android.platform.provider.transfer.ContentTransferEvent;
import com.activiti.android.sdk.model.runtime.ParcelTask;
import com.activiti.android.ui.fragments.FragmentDisplayer;
import com.activiti.android.ui.fragments.builder.LeafFragmentBuilder;
import com.activiti.android.ui.fragments.comment.FragmentWithComments;
import com.activiti.android.ui.fragments.task.TaskDetailsFoundationFragment;
import com.activiti.android.ui.utils.DisplayUtils;
import com.activiti.android.ui.utils.UIUtils;
import com.activiti.client.api.model.runtime.TaskRepresentation;
import com.squareup.otto.Subscribe;
public class TaskDetailsFragment extends TaskDetailsFoundationFragment implements FragmentWithComments
{
public static final String TAG = TaskDetailsFragment.class.getName();
protected Menu menu;
// ///////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS & HELPERS
// ///////////////////////////////////////////////////////////////////////////
public TaskDetailsFragment()
{
super();
eventBusRequired = true;
setHasOptionsMenu(true);
}
public static TaskDetailsFragment newInstanceByTemplate(Bundle b)
{
TaskDetailsFragment cbf = new TaskDetailsFragment();
cbf.setArguments(b);
return cbf;
}
// ///////////////////////////////////////////////////////////////////////////
// LIFECYCLE
// ///////////////////////////////////////////////////////////////////////////
@Override
public void onStart()
{
Fragment fr = getFragmentManager().findFragmentById(R.id.right_drawer);
if (fr == null || (fr != null && !(fr.equals(commentFragment))))
{
if (fr != null)
{
FragmentDisplayer.with(getActivity()).back(false).animate(null).remove(fr);
}
}
setLockRightMenu(false);
super.onStart();
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
onParentTaskListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
TaskDetailsFragment.with(getActivity()).taskId(taskRepresentation.getParentTaskId()).back(true)
.display();
}
};
onProcessListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
ProcessDetailsFragment.with(getActivity()).processId(processInstanceRepresentation.getId())
.back(DisplayUtils.hasCentralPane(getActivity())).display();
}
};
}
@Override
public void onStop()
{
super.onStop();
getToolbar().getMenu().clear();
UIUtils.setTitle(getActivity(), "", "", true);
}
// ///////////////////////////////////////////////////////////////////////////
// MENU
// ///////////////////////////////////////////////////////////////////////////
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
if (taskRepresentation != null)
{
if (!DisplayUtils.hasCentralPane(getActivity()))
{
menu.clear();
inflater.inflate(R.menu.task_details, menu);
}
else
{
getToolbar().getMenu().clear();
getToolbar().inflateMenu(R.menu.task_details);
// Set an OnMenuItemClickListener to handle menu item clicks
getToolbar().setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener()
{
@Override
public boolean onMenuItemClick(MenuItem item)
{
return onOptionsItemSelected(item);
}
});
}
this.menu = menu;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
switch (id)
{
case R.id.task_action_share_link:
// Analytics
AnalyticsHelper.reportOperationEvent(getActivity(), AnalyticsManager.CATEGORY_TASK,
AnalyticsManager.ACTION_SHARE, AnalyticsManager.LABEL_LINK, 1, false);
IntentUtils.actionShareLink(this, taskRepresentation.getName(),
getAPI().getTaskService().getShareUrl(taskId));
return true;
case R.id.display_comments:
if (getActivity() instanceof MainActivity)
{
((MainActivity) getActivity())
.setRightMenuVisibility(!((MainActivity) getActivity()).isRightMenuVisible());
}
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
// ///////////////////////////////////////////////////////////////////////////
// INTERFACE
// ///////////////////////////////////////////////////////////////////////////
@Override
public void hasComment(boolean hascomment)
{
if (menu != null && hascomment && menu.findItem(R.id.display_comments) != null)
{
menu.findItem(R.id.display_comments).setIcon(R.drawable.ic_comment);
}
}
// ///////////////////////////////////////////////////////////////////////////
// EVENTS
// ///////////////////////////////////////////////////////////////////////////
@Subscribe
public void onContentTransfer(ContentTransferEvent event)
{
super.onContentTransfer(event);
}
@Subscribe
public void onTaskCreated(CreateTaskEvent event)
{
if (event.hasException) { return; }
if (event.taskId != null && event.taskId.equals(taskRepresentation.getId()))
{
requestChecklist();
}
}
// ///////////////////////////////////////////////////////////////////////////
// BUILDER
// ///////////////////////////////////////////////////////////////////////////
public static Builder with(FragmentActivity activity)
{
return new Builder(activity);
}
public static class Builder extends LeafFragmentBuilder
{
// ///////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
// ///////////////////////////////////////////////////////////////////////////
public Builder(FragmentActivity activity)
{
super(activity);
this.extraConfiguration = new Bundle();
}
public Builder(FragmentActivity appActivity, Map<String, Object> configuration)
{
super(appActivity, configuration);
}
public Builder taskId(String taskId)
{
extraConfiguration.putString(ARGUMENT_TASK_ID, taskId);
return this;
}
public Builder task(TaskRepresentation task)
{
extraConfiguration.putParcelable(ARGUMENT_TASK, new ParcelTask(task));
return this;
}
public Builder bindFragmentTag(String fragmentListTag)
{
extraConfiguration.putString(ARGUMENT_BIND_FRAGMENT_TAG, fragmentListTag);
return this;
}
// ///////////////////////////////////////////////////////////////////////////
// CLICK
// ///////////////////////////////////////////////////////////////////////////
protected Fragment createFragment(Bundle b)
{
return newInstanceByTemplate(b);
};
}
}
| lgpl-3.0 |
JasonStapley/TSQLScriptGenerator | TSQLScriptGenerator/TSQLScriptGenerator/SQLLocator.cs | 5674 | using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Data;
using System.Data.SqlClient;
namespace TSQLScriptGenerator
{
public class SqlLocator
{
[DllImport("odbc32.dll")]
private static extern short SQLAllocHandle(short hType, IntPtr inputHandle, out IntPtr outputHandle);
[DllImport("odbc32.dll")]
private static extern short SQLSetEnvAttr(IntPtr henv, int attribute, IntPtr valuePtr, int strLength);
[DllImport("odbc32.dll")]
private static extern short SQLFreeHandle(short hType, IntPtr handle);
[DllImport("odbc32.dll", CharSet = CharSet.Ansi)]
private static extern short SQLBrowseConnect(IntPtr hconn, StringBuilder inString,
short inStringLength, StringBuilder outString, short outStringLength,
out short outLengthNeeded);
private const short SQL_HANDLE_ENV = 1;
private const short SQL_HANDLE_DBC = 2;
private const int SQL_ATTR_ODBC_VERSION = 200;
private const int SQL_OV_ODBC3 = 3;
private const short SQL_SUCCESS = 0;
private const short SQL_NEED_DATA = 99;
private const short DEFAULT_RESULT_SIZE = 1024;
private const string SQL_DRIVER_STR = "DRIVER=SQL SERVER";
private SqlLocator() { }
public static string[] GetServers()
{
string[] retval = null;
string txt = string.Empty;
IntPtr henv = IntPtr.Zero;
IntPtr hconn = IntPtr.Zero;
StringBuilder inString = new StringBuilder(SQL_DRIVER_STR);
StringBuilder outString = new StringBuilder(DEFAULT_RESULT_SIZE);
short inStringLength = (short)inString.Length;
short lenNeeded = 0;
try
{
if (SQL_SUCCESS == SQLAllocHandle(SQL_HANDLE_ENV, henv, out henv))
{
if (SQL_SUCCESS == SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (IntPtr)SQL_OV_ODBC3, 0))
{
if (SQL_SUCCESS == SQLAllocHandle(SQL_HANDLE_DBC, henv, out hconn))
{
if (SQL_NEED_DATA == SQLBrowseConnect(hconn, inString, inStringLength, outString,
DEFAULT_RESULT_SIZE, out lenNeeded))
{
if (DEFAULT_RESULT_SIZE < lenNeeded)
{
outString.Capacity = lenNeeded;
if (SQL_NEED_DATA != SQLBrowseConnect(hconn, inString, inStringLength, outString,
lenNeeded, out lenNeeded))
{
throw new ApplicationException("Unabled to aquire SQL Servers from ODBC driver.");
}
}
txt = outString.ToString();
int start = txt.IndexOf("{") + 1;
int len = txt.IndexOf("}") - start;
if ((start > 0) && (len > 0))
{
txt = txt.Substring(start, len);
}
else
{
txt = string.Empty;
}
}
}
}
}
}
catch (Exception ex)
{
//Throw away any error if we are not in debug mode
MessageBox.Show(ex.Message, "Acquire SQL Servier List Error");
txt = string.Empty;
}
finally
{
if (hconn != IntPtr.Zero)
{
SQLFreeHandle(SQL_HANDLE_DBC, hconn);
}
if (henv != IntPtr.Zero)
{
SQLFreeHandle(SQL_HANDLE_ENV, hconn);
}
}
if (txt.Length > 0)
{
retval = txt.Split(",".ToCharArray());
}
return retval;
}
/// <summary>
/// Get a list of databases deployed to this instance
/// </summary>
/// <param name="sqlserver"></param>
/// <returns></returns>
public static string[] GetDatabases(string sqlserver)
{
List<String> ListOfDatabases = new List<String>();
try
{
using (SqlConnection sqlconn = new SqlConnection(string.Format("server={0};integrated security=SSPI", sqlserver)))
{
sqlconn.Open();
sqlconn.ChangeDatabase("master");
using (SqlCommand SqlCmd = new SqlCommand("SELECT [name] FROM sys.databases", sqlconn))
{
SqlCmd.CommandType = CommandType.Text;
SqlDataReader xReader = SqlCmd.ExecuteReader();
while (xReader.Read())
{
ListOfDatabases.Add(xReader.GetValue(0).ToString());
}
}
sqlconn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ListOfDatabases.ToArray();
}
}
}
| lgpl-3.0 |
TylerAndrew/ImagicalMine | src/pocketmine/entity/Tameable.php | 1015 | <?php
/*
*
* _ _ _ __ __ _
* (_) (_) | | \/ (_)
* _ _ __ ___ __ _ __ _ _ ___ __ _| | \ / |_ _ __ ___
* | | '_ ` _ \ / _` |/ _` | |/ __/ _` | | |\/| | | '_ \ / _ \
* | | | | | | | (_| | (_| | | (_| (_| | | | | | | | | | __/
* |_|_| |_| |_|\__,_|\__, |_|\___\__,_|_|_| |_|_|_| |_|\___|
* __/ |
* |___/
*
* This program is a third party build by ImagicalMine.
*
* PocketMine is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author ImagicalMine Team
* @link http://forums.imagicalcorp.ml/
*
*
*/
namespace pocketmine\entity;
interface Tameable{
} | lgpl-3.0 |
meta-it/misc-addons | attachment_large_object/__init__.py | 68 | # -*- coding: utf-8 -*-
# flake8:noqa
from . import ir_attachment
| lgpl-3.0 |
smol/doom | debug/src/actions/treedata.tsx | 6993 | import { Wad } from "wad";
import { ColorMap } from "../colormap.debug";
import { Endoom } from "../endoom.debug";
import { Flat, Graphic } from "../graphic.debug";
import { Linedefs } from "../linedefs.debug";
import { Map, Things } from "../map.debug";
import { Music } from "../music.debug";
import { Node } from "../nodes.debug";
import { Playpal } from "../playpal.debug";
import { Sector } from "../sector.debug";
import { Subsector } from "../subsector.debug";
import { Texture } from "../texture.debug";
import { TreeData } from "../treeview";
import { Vertexes } from "../vertexes.debug";
export default (wad: Wad): TreeData[] => {
const graphics = wad
.getGraphics()
.sort((a, b) => a.getName().localeCompare(b.getName()))
.map((graphic) => ({
label: graphic.getName(),
url: graphic.getName(),
Component: () => <Graphic graphic={graphic} />,
children: null,
}));
const textures = wad.getTextures().map<TreeData>((texture) => ({
label: texture.getName(),
url: texture.getName(),
children: texture.getTextures().map((texture) => ({
label: texture.getName(),
url: texture.getName(),
Component: () => <Texture texture={texture} colormaps={wad.ColorMap} />,
children: [],
})),
}));
const flats = wad.getFlats().map<TreeData>((flat) => ({
label: flat.getName(),
url: flat.getName(),
Component: () => <Flat flat={flat} />,
children: null,
}));
return [
{
label: "PLAYPAL",
url: "playpal",
children: [],
Component: () => <Playpal />,
},
{
label: "COLORMAP",
url: "colormap",
Component: () => <ColorMap />,
children: [],
},
{
label: "ENDOOM",
url: "endoom",
Component: () => <Endoom />,
children: [],
},
{
label: "GRAPHICS",
url: "graphics",
children: [
{ label: "GRAPHICS", url: "graphics", children: graphics },
{ label: "TEXTURES", url: "textures", children: textures },
{ label: "FLATS", url: "flats", children: flats },
],
},
{
label: "MUSICS",
url: "musics",
children: wad.getMusics().map((music) => ({
label: music.getName(),
url: music.getName(),
Component: () => <Music music={music} />,
children: [],
})),
},
{
label: "MAPS",
url: "maps",
children: wad.getMaps().map((map) => ({
label: map.getName(),
url: map.getName(),
Component: () => <Map map={map} wad={wad} />,
children: [
{
label: "LINEDEFS",
url: "linedefs",
children: map.getLinedefs().map((linedef, index) => ({
url: `linedef-${index}`,
label: `LINEDEF-${index}`,
children: [],
Component: () => (
<Linedefs
current={linedef}
linedefs={map.getLinedefs()}
vertexes={map.getVertexes()}
/>
),
})),
},
{
label: "THINGS",
url: "things",
Component: () => <Things things={map.getThings()} />,
children: [],
},
{
label: "VERTEXES",
url: "vertexes",
Component: () => (
<Vertexes
vertexes={map.getVertexes()}
linedefs={map.getLinedefs()}
/>
),
children: [],
},
{
label: "NODES",
url: "nodes",
children: map.getNodes().map((node, index) => ({
label: `NODE-${index}`,
url: `node-${index}`,
Component: () => (
<Node
vertexes={map.getVertexes()}
linedefs={map.getLinedefs()}
node={node}
/>
),
children: [],
})),
},
{
label: "SUBSECTORS",
url: "subsectors",
children: map.getSubsectors().map((subsector, index) => ({
label: `SUBSECTOR-${index}`,
url: `subsector-${index}`,
Component: () => <Subsector subsector={subsector} />,
children: [],
})),
},
{
label: "SECTORS",
url: "sectors",
children: map.getSectors().map((sector, index) => ({
label: `SECTOR-${index}`,
url: `sector-${index}`,
Component: () => (
<Sector
sector={sector}
flats={wad.getFlats()}
textures={wad.getTextures()}
things={map.getThings()}
graphics={wad.getGraphics()}
/>
),
children: [],
})),
},
],
})),
},
];
};
// private getMaps(): TreeData[] {
// var datas: TreeData[] = [];
// datas = this.props.wad.getMaps().map((map) => {
// var data: TreeData = {
// label: map.getName(),
// component: <Map.Map map={map} wad={this.props.wad} />,
// children: [],
// };
// data.children = [
// {
// label: "THINGS",
// component: <Map.Things things={map.getThings()} />,
// children: [],
// },
// {
// label: "VERTEXES",
// component: (
// <Vertexes.Vertexes
// vertexes={map.getVertexes()}
// linedefs={map.getLinedefs()}
// />
// ),
// children: [],
// },
// { label: "NODES", component: null, children: this.getNodes(map) },
// {
// label: "SUBSECTORS",
// component: <Subsectors.Subsectors subsectors={map.getSubsectors()} />,
// children: [],
// },
// {
// label: "SECTORS",
// component: <Wtf.Wtf sectors={map.getSectors()} />,
// children: this.getSectors(map),
// },
// ];
// return data;
// });
// return datas;
// }
// private getSectors(map: Wad.Map): TreeData[] {
// return map.getSectors().map((sector, index) => {
// return {
// label: `SECTOR ${index}`,
// component: <Wtf.Wtf sectors={[sector]} />,
// children: [],
// };
// });
// }
// private getNodes(map: Wad.Map): TreeData[] {
// var datas: TreeData[] = [];
// var nodes: Wad.Node[] = map.getNodes();
// for (var i = 0; i < nodes.length; i++) {
// datas.push({
// label: "NODE " + i,
// component: (
// <Nodes.Nodes
// vertexes={map.getVertexes()}
// linedefs={map.getLinedefs()}
// node={nodes[i]}
// />
// ),
// children: [],
// });
// }
// return datas;
// }
// private getMusics(): TreeData[] {
// var data: TreeData[] = [];
// data = this.props.wad.
// return data;
// }
| lgpl-3.0 |
FenixEdu/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/enrolment/EnrolmentContext.java | 9029 | /**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Academic is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain.enrolment;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.fenixedu.academic.domain.ExecutionSemester;
import org.fenixedu.academic.domain.Person;
import org.fenixedu.academic.domain.StudentCurricularPlan;
import org.fenixedu.academic.domain.curricularRules.executors.ruleExecutors.CurricularRuleLevel;
import org.fenixedu.academic.domain.degreeStructure.DegreeModule;
import org.fenixedu.academic.domain.exceptions.DomainException;
import org.fenixedu.academic.domain.person.RoleType;
import org.fenixedu.academic.domain.student.Registration;
import org.fenixedu.academic.domain.studentCurriculum.CurriculumModule;
import org.fenixedu.academic.domain.studentCurriculum.NoCourseGroupCurriculumGroup;
import org.fenixedu.academic.domain.studentCurriculum.NoCourseGroupCurriculumGroupType;
import org.fenixedu.academic.dto.administrativeOffice.studentEnrolment.NoCourseGroupEnrolmentBean;
import org.fenixedu.bennu.core.domain.User;
import org.fenixedu.bennu.core.security.Authenticate;
public class EnrolmentContext {
private StudentCurricularPlan studentCurricularPlan;
private ExecutionSemester executionSemester;
private final Set<IDegreeModuleToEvaluate> degreeModulesToEvaluate;
private final List<CurriculumModule> curriculumModulesToRemove;
private CurricularRuleLevel curricularRuleLevel;
//private Person responsiblePerson;
private final User userView;
public EnrolmentContext(final StudentCurricularPlan studentCurricularPlan, final ExecutionSemester executionSemester,
final Set<IDegreeModuleToEvaluate> degreeModulesToEnrol, final List<CurriculumModule> curriculumModulesToRemove,
final CurricularRuleLevel curricularRuleLevel) {
this.userView = Authenticate.getUser();
this.studentCurricularPlan = studentCurricularPlan;
this.degreeModulesToEvaluate = new HashSet<IDegreeModuleToEvaluate>();
for (final IDegreeModuleToEvaluate moduleToEnrol : degreeModulesToEnrol) {
if (curriculumModulesToRemove.contains(moduleToEnrol.getCurriculumGroup())) {
throw new DomainException(
"error.StudentCurricularPlan.cannot.remove.enrollment.on.curriculum.group.because.other.enrollments.depend.on.it",
moduleToEnrol.getCurriculumGroup().getName().getContent());
}
this.addDegreeModuleToEvaluate(moduleToEnrol);
}
this.executionSemester = executionSemester;
this.curriculumModulesToRemove = curriculumModulesToRemove;
this.curricularRuleLevel = curricularRuleLevel;
}
public Set<IDegreeModuleToEvaluate> getDegreeModulesToEvaluate() {
return degreeModulesToEvaluate;
}
public Set<IDegreeModuleToEvaluate> getAllChildDegreeModulesToEvaluateFor(final DegreeModule degreeModule) {
final Set<IDegreeModuleToEvaluate> result = new HashSet<IDegreeModuleToEvaluate>();
for (final IDegreeModuleToEvaluate degreeModuleToEvaluate : this.degreeModulesToEvaluate) {
if (degreeModule.hasDegreeModule(degreeModuleToEvaluate.getDegreeModule())) {
result.add(degreeModuleToEvaluate);
}
}
return result;
}
public void addDegreeModuleToEvaluate(final IDegreeModuleToEvaluate degreeModuleToEvaluate) {
getDegreeModulesToEvaluate().add(degreeModuleToEvaluate);
}
public boolean hasDegreeModulesToEvaluate() {
return degreeModulesToEvaluate != null && !degreeModulesToEvaluate.isEmpty();
}
public ExecutionSemester getExecutionPeriod() {
return executionSemester;
}
public void setExecutionPeriod(ExecutionSemester executionSemester) {
this.executionSemester = executionSemester;
}
public StudentCurricularPlan getStudentCurricularPlan() {
return studentCurricularPlan;
}
public Registration getRegistration() {
return studentCurricularPlan.getRegistration();
}
public void setStudentCurricularPlan(StudentCurricularPlan studentCurricularPlan) {
this.studentCurricularPlan = studentCurricularPlan;
}
public List<CurriculumModule> getToRemove() {
return curriculumModulesToRemove;
}
public CurricularRuleLevel getCurricularRuleLevel() {
return curricularRuleLevel;
}
public void setCurricularRuleLevel(CurricularRuleLevel curricularRuleLevel) {
this.curricularRuleLevel = curricularRuleLevel;
}
public Person getResponsiblePerson() {
return userView.getPerson();
}
public boolean hasResponsiblePerson() {
return getResponsiblePerson() != null;
}
public boolean isResponsiblePersonStudent() {
return RoleType.STUDENT.isMember(userView.getPerson().getUser());
}
public boolean isRegistrationFromResponsiblePerson() {
return getResponsiblePerson() == getRegistration().getPerson();
}
public boolean isNormal() {
return getCurricularRuleLevel().isNormal();
}
public boolean isImprovement() {
return getCurricularRuleLevel() == CurricularRuleLevel.IMPROVEMENT_ENROLMENT;
}
public boolean isSpecialSeason() {
return getCurricularRuleLevel() == CurricularRuleLevel.SPECIAL_SEASON_ENROLMENT;
}
public boolean isExtraordinarySeason() {
return getCurricularRuleLevel() == CurricularRuleLevel.EXTRAORDINARY_SEASON_ENROLMENT;
}
public boolean isExtra() {
return getCurricularRuleLevel() == CurricularRuleLevel.EXTRA_ENROLMENT;
}
public boolean isPropaeudeutics() {
return getCurricularRuleLevel() == CurricularRuleLevel.PROPAEUDEUTICS_ENROLMENT;
}
public boolean isStandalone() {
return getCurricularRuleLevel() == CurricularRuleLevel.STANDALONE_ENROLMENT
|| getCurricularRuleLevel() == CurricularRuleLevel.STANDALONE_ENROLMENT_NO_RULES;
}
public boolean isEnrolmentWithoutRules() {
return getCurricularRuleLevel() == CurricularRuleLevel.ENROLMENT_NO_RULES;
}
public boolean isPhdDegree() {
return studentCurricularPlan.getDegreeType().isAdvancedSpecializationDiploma();
}
@SuppressWarnings("unchecked")
static public EnrolmentContext createForVerifyWithRules(final StudentCurricularPlan studentCurricularPlan,
final ExecutionSemester executionSemester) {
return createForVerifyWithRules(studentCurricularPlan, executionSemester, Collections.EMPTY_SET);
}
@SuppressWarnings("unchecked")
static public EnrolmentContext createForVerifyWithRules(final StudentCurricularPlan studentCurricularPlan,
final ExecutionSemester executionSemester, final Set<IDegreeModuleToEvaluate> degreeModulesToEvaluate) {
return new EnrolmentContext(studentCurricularPlan, executionSemester, degreeModulesToEvaluate, Collections.EMPTY_LIST,
CurricularRuleLevel.ENROLMENT_WITH_RULES);
}
@SuppressWarnings("unchecked")
static public EnrolmentContext createForNoCourseGroupCurriculumGroupEnrolment(
final StudentCurricularPlan studentCurricularPlan, final NoCourseGroupEnrolmentBean bean) {
final IDegreeModuleToEvaluate moduleToEvaluate =
new ExternalCurricularCourseToEnrol(readOrCreateNoCourseGroupCurriculumGroup(studentCurricularPlan,
bean.getGroupType()), bean.getSelectedCurricularCourse(), bean.getExecutionPeriod());
return new EnrolmentContext(studentCurricularPlan, bean.getExecutionPeriod(), Collections.singleton(moduleToEvaluate),
Collections.EMPTY_LIST, bean.getCurricularRuleLevel());
}
static private NoCourseGroupCurriculumGroup readOrCreateNoCourseGroupCurriculumGroup(
final StudentCurricularPlan studentCurricularPlan, final NoCourseGroupCurriculumGroupType groupType) {
NoCourseGroupCurriculumGroup group = studentCurricularPlan.getNoCourseGroupCurriculumGroup(groupType);
if (group == null) {
group = studentCurricularPlan.createNoCourseGroupCurriculumGroup(groupType);
}
return group;
}
}
| lgpl-3.0 |
gfg-development/linkslist | languages/nl/tl_linkslist_list.php | 1471 | <?php
/**
* TL_ROOT/system/modules/linkslist/languages/nl/tl_linkslist_list.php
*
* Contao extension: linkslist 1.1.1 rc1
* Dutch translation file
*
* Copyright : © 2014 gfg-development
* License : LGPL
* Author : Gerrit Grutzeck (gfg-development), http://www.gfg-development.de
* Translator: Just Schimmelpenninck (justs)
*
* This file was created automatically be the Contao extension repository translation module.
* Do not edit this file manually. Contact the author or translator for this module to establish
* permanent text corrections which are update-safe.
*/
$GLOBALS['TL_LANG']['tl_linkslist_list']['title_legend'] = "Titel";
$GLOBALS['TL_LANG']['tl_linkslist_list']['name']['0'] = "Titel";
$GLOBALS['TL_LANG']['tl_linkslist_list']['name']['1'] = "Geef titel van de linklijst";
$GLOBALS['TL_LANG']['tl_linkslist_list']['new']['0'] = "Nieuwe linklijst";
$GLOBALS['TL_LANG']['tl_linkslist_list']['new']['1'] = "Maak een nieuwe linklijst.";
$GLOBALS['TL_LANG']['tl_linkslist_list']['edit']['0'] = "Bewerk linklijst";
$GLOBALS['TL_LANG']['tl_linkslist_list']['edit']['1'] = "Bewerk linklijst ID %s";
$GLOBALS['TL_LANG']['tl_linkslist_list']['delete']['0'] = "Wis linklijst";
$GLOBALS['TL_LANG']['tl_linkslist_list']['delete']['1'] = "Wis linklijst ID %s";
$GLOBALS['TL_LANG']['tl_linkslist_list']['show']['0'] = "Details linklijst";
$GLOBALS['TL_LANG']['tl_linkslist_list']['show']['1'] = "Toon details linklijst ID %s";
?>
| lgpl-3.0 |
wanduow/libprotoident | lib/tcp/lpi_rabbitmq.cc | 2354 | /*
*
* Copyright (c) 2011-2016 The University of Waikato, Hamilton, New Zealand.
* All rights reserved.
*
* This file is part of libprotoident.
*
* This code has been developed by the University of Waikato WAND
* research group. For further information please see http://www.wand.net.nz/
*
* libprotoident is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* libprotoident is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
#include <string.h>
#include "libprotoident.h"
#include "proto_manager.h"
#include "proto_common.h"
static inline bool match_amqp_header(uint32_t payload, uint32_t len) {
if (len == 8 && MATCH(payload, 'A', 'M', 'Q', 'P')) {
return true;
}
return false;
}
static inline bool match_amqp_start(uint32_t payload) {
/* only seen length 498 so far, but surely this could vary more */
if (MATCH(payload, 0x01, 0x00, 0x00, 0x00)) {
return true;
}
return false;
}
static inline bool match_rabbitmq(lpi_data_t *data, lpi_module_t *mod UNUSED) {
if (data->server_port != 5672 && data->client_port != 5672) {
return false;
}
if (match_amqp_header(data->payload[0], data->payload_len[0])) {
if (match_amqp_start(data->payload[1])) {
return true;
}
}
if (match_amqp_header(data->payload[1], data->payload_len[1])) {
if (match_amqp_start(data->payload[0])) {
return true;
}
}
return false;
}
static lpi_module_t lpi_rabbitmq = {
LPI_PROTO_RABBITMQ,
LPI_CATEGORY_MESSAGE_QUEUE,
"RabbitMQ",
75,
match_rabbitmq
};
void register_rabbitmq(LPIModuleMap *mod_map) {
register_protocol(&lpi_rabbitmq, mod_map);
}
| lgpl-3.0 |
justinjohn83/utils-java | utils/src/main/java/com/gamesalutes/utils/CollectionUtils.java | 29567 | /*
* Copyright (c) 2013 Game Salutes.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* Contributors:
* Game Salutes - Repackaging and modifications of original work under University of Chicago and Apache License 2.0 shown below
*
* Repackaging from edu.uchicago.nsit.iteco.utils to com.gamesalutes.utils
*
* Copyright 2008 - 2011 University of Chicago
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.gamesalutes.utils;
import java.lang.reflect.Constructor;
import java.util.*;
/**
* Adding utility methods for <code>java.util.Collection</code>.
*
* These methods are used to supplement the common tasks for collections
* implemented in <code>java.util.Collections</code>.
*
* @author Justin Montgomery
* @version $Id: CollectionUtils.java 2524 2011-01-03 19:32:18Z jmontgomery $
*
*/
public final class CollectionUtils
{
public static final float LOAD_FACTOR = 0.7F;
private CollectionUtils() {}
/**
* Returns <code>true</code> if <code>source</code> contains at least one
* element in <code>target</code>.
*
* @param source the source <code>Collection</code>
* @param target the target <code>Collection</code>
* @return <code>true</code> if <code>source</code> contains at least one
* element in <code>target</code> and <code>false</code> otherwise
*/
public static boolean containsSome(Collection<?> source,Collection<?> target)
{
if(source == target) return true;
if((source == null) != (target == null)) return false;
return !Collections.disjoint(source, target);
}
/**
* Determines whether <code>col</code> contains only <code>elm</code>
* as its element(s).
*
* @param <T> the type of the <code>Collection</code>
* @param col input <code>Collection</code>
* @param elm the test element
* @return <code>true</code> if <code>col</code> contains only
* <code>elm</code> and <code>false</code> otherwise
*/
public static <T> boolean containsOnly(Collection<? extends T> col,T elm)
{
if(col.size() == 1)
return col.contains(elm);
else if(!col.isEmpty() && !(col instanceof Set))
{
// make sure every element in this collection is
// "elm"
for(T t : col)
{
if(!MiscUtils.safeEquals(t,elm))
return false;
}
return true;
}
else // collection either empty or is a set with more than 1 element
return false;
}
/**
* Replaces all the equal elements between <code>source</code> and <code>dest</code>
* in <code>dest</code> with the elements in <code>target</code>.
* Replacement proceeds for each equal element in order returned by <code>Iterator</code>
* of <code>target</code>. If <code>target</code> is <code>null</code>, then the elements in
* <code>dest</code> that are equal to those in <code>source</code> are removed from
* <code>dest</code>. Otherwise, target must have the same size as the source or an
* <code>IllegalArgumentException</code> is thrown.
*
* @param <T> the <code>Collection</code> type
* @param source the reference source
* @param dest the <code>Collection</code> to be modified
* @param target the replacements elements for equal elements in <code>source</code>
* and <code>dest</code>
* @return <code>true</code> if dest modified as result of this method and
* <code>false</code> otherwise
* @throws IllegalArgumentException if <code>target</code> is not null and
* <code>source.size() != target.size()</code>
*
*/
public static <T> boolean replaceAll(Collection<? extends T> source,
Collection<T> dest,
Collection<? extends T> target)
{
if(source == null) throw new NullPointerException("source");
if(dest == null) throw new NullPointerException("dest");
if(target == null)
target = Collections.<T>emptyList();
else if(source.size() != target.size())
{
StringBuilder str = new StringBuilder(1024);
str.append("source.size()=");
str.append(source.size());
str.append(" != target.size()=");
str.append(target.size());
str.append(" ; [source=");
str.append(source);
str.append(";dest=");
str.append(dest);
str.append(";target=");
str.append(target);
str.append("]");
throw new IllegalArgumentException(str.toString());
}
boolean modified = false;
// nothing to do
if(source.isEmpty())
return false;
// preserve order of replacements
if(dest instanceof List)
{
ListIterator<T> destIt =
((List<T>)dest).listIterator();
List<? extends T> sourceList;
List<? extends T> targetList;
if(!(source instanceof List))
sourceList = new ArrayList<T>(source);
else
sourceList = (List)source;
if(!(target instanceof List))
targetList = new ArrayList<T>(target);
else
targetList = (List)target;
while(destIt.hasNext())
{
T targetElm = null;
T destElm = destIt.next();
int index = -1;
if((index = sourceList.indexOf(destElm)) != -1)
{
modified = true;
if(!targetList.isEmpty())
targetElm = targetList.get(index);
// set value to target elm
if(targetElm != null)
destIt.set(targetElm);
else // no match, so delete the destElm
destIt.remove();
}
} // end while
}
else
{
final int oldSize = dest.size();
modified = dest.removeAll(source);
if(modified)
{
final int count = oldSize - dest.size();
int i = 0;
for(Iterator<? extends T> targetIt = target.iterator();
targetIt.hasNext() && i++ < count;)
{
dest.add(targetIt.next());
}
}
}
return modified;
}
/**
* Calculates the optimal hash capacity for given maximum size and the
* load factor.
*
* @param size maximum size of the collection
* @param loadFactor usage percentage before a rehash occurs. Default value for
* Collections framework is 0.75. Lower values result in less
* chance of collisions at the expense of larger memory footprint
* @return the optimal hash capacity
*/
public static int calcHashCapacity(int size,float loadFactor)
{
return (int)Math.ceil(size/loadFactor);
}
/**
* Creates a <code>HashMap</code> of the optimal hash capacity for given
* maximum size and the load factor.
*
* @param <U> key type
* @param <V> value type
* @param size maximum size of the map
* @param loadFactor usage percentage before a rehash occurs. Default value for
* Collections framework is 0.75. Lower values result in less
* chance of collisions at the expense of larger memory footprint
* @return the created <code>HashMap</code>
*/
public static <U,V> HashMap<U,V> createHashMap(int size,float loadFactor)
{
return new HashMap<U,V>(
calcHashCapacity(size,loadFactor),loadFactor);
}
/**
* Creates a <code>LinkedHashMap</code> of the optimal hash capacity for given
* maximum size and the load factor.
*
* @param <U> key type
* @param <V> value type
* @param size maximum size of the map
* @param loadFactor usage percentage before a rehash occurs. Default value for
* Collections framework is 0.75. Lower values result in less
* chance of collisions at the expense of larger memory footprint
* @return the created <code>HashMap</code>
*/
public static <U,V> LinkedHashMap<U,V> createLinkedHashMap(int size,float loadFactor)
{
return new LinkedHashMap<U,V>(
calcHashCapacity(size,loadFactor),loadFactor);
}
/**
* Creates a <code>HashMap</code> subclass instance of the optimal hash capacity for given
* maximum size and the load factor.
*
* @param <U> key type
* @param <V> value type
*
* @param clazz the subclass instance to create
* @param size maximum size of the map
* @param loadFactor usage percentage before a rehash occurs. Default value for
* Collections framework is 0.75. Lower values result in less
* chance of collisions at the expense of larger memory footprint
* @return the created <code>LinkedHashSet</code>
*/
public static <U,V,C extends HashMap<U,V>> C createHashMap(Class<C> clazz,
int size,float loadFactor)
{
return (C)createHash(clazz,size,loadFactor);
}
/**
* Creates a <code>HashSet</code> of the optimal hash capacity for given
* maximum size and the load factor.
*
* @param <E> the element type
*
* @param size maximum size of the collection
* @param loadFactor usage percentage before a rehash occurs. Default value for
* Collections framework is 0.75. Lower values result in less
* chance of collisions at the expense of larger memory footprint
* @return the created <code>HashSet</code>
*/
public static <E> HashSet<E> createHashSet(int size,float loadFactor)
{
return new HashSet<E>(
calcHashCapacity(size,loadFactor),loadFactor);
}
/**
* Creates a <code>LinkedHashSet</code> of the optimal hash capacity for given
* maximum size and the load factor.
*
* @param <E> the element type
*
* @param size maximum size of the collection
* @param loadFactor usage percentage before a rehash occurs. Default value for
* Collections framework is 0.75. Lower values result in less
* chance of collisions at the expense of larger memory footprint
* @return the created <code>LinkedHashSet</code>
*/
public static <E> LinkedHashSet<E> createLinkedHashSet(int size,float loadFactor)
{
return new LinkedHashSet<E>(
calcHashCapacity(size,loadFactor),loadFactor);
}
/**
* Creates a <code>HashSet</code> subclass instance of the optimal hash capacity for given
* maximum size and the load factor.
*
* @param <E> the element type
*
* @param clazz the subclass instance to create
* @param size maximum size of the collection
* @param loadFactor usage percentage before a rehash occurs. Default value for
* Collections framework is 0.75. Lower values result in less
* chance of collisions at the expense of larger memory footprint
* @return the created <code>LinkedHashSet</code>
*/
public static <E,C extends HashSet<E>> C createHashSet(Class<C> clazz,
int size,float loadFactor)
{
return (C)createHash(clazz,size,loadFactor);
}
private static Object createHash(Class<?> clazz,int size,float loadFactor)
{
// try to use reflection to create the instance
try
{
// use performance parameters
Constructor<?> c = clazz.getConstructor(int.class,float.class);
return c.newInstance(calcHashCapacity(size,loadFactor),loadFactor);
}
catch(Exception e)
{
try
{
// try default constructor
return clazz.newInstance();
}
catch(Exception e2)
{
throw new IllegalArgumentException("clazz=" + clazz);
}
}
}
/**
* Returns a hashcode that is computed irrespective of the order of the collection. This method should be used
* to compute a hashcode of a collection field when <code>unorderedListEquals</code> or
* <code>unorderedCollectionEquals</code> is used for that field in the object's equals method.
*
* @param c the <code>Collection</code>
* @return the hashcode
*/
public static int unorderedCollectionHashCode(Collection<?> c)
{
if(c == null) return 0;
int h = 0;
Iterator<?> i = c.iterator();
while (i.hasNext())
{
Object o = i.next();
if(o != null)
h += o.hashCode();
}
return h;
}
/**
* Returns whether two collections are equal irrespective of their order and regardless of
* their implemented subinterfaces of <code>Collection</code>. The running time of this method is
* no worse than <code>O(nlogn)</code>.
*
* By definition a <code>java.util.Set</code> cannot be equal to a <code>java.util.List</code>
* in order to obey the contracts of their respective interfaces. This method gets around that by
* comparing the two collections using <code>equals</code> if they are both <code>java.util.Set</code>.
* Otherwise, the collections are dumped into arrays, sorted using <code>GeneralComparator</code> and
* then the sorted arrays are compared.
*
* @param c1 first <code>Collection</code>
* @param c2 second <code>Collection</code>
* @return <code>true</code> if they have the same size and are equal by containment and
* <code>false</code> otherwise
*/
public static boolean unorderedCollectionEquals(Collection<?> c1, Collection<?> c2)
{
if(c1 == c2) return true;
// null checks
if(c1 == null || c2 == null) return false;
int size1 = c1.size();
int size2 = c2.size();
// sizes must be the same
if(size1 != size2) return false;
// compare using regular equals if both collections are sets since this is O(n)
if(c1 instanceof Set && c2 instanceof Set)
return c1.equals(c2);
// dump both collections into arrays, sort them using GeneralComparator and then compare the arrays
Object[] a1 = c1.toArray();
Object[] a2 = c2.toArray();
Arrays.sort(a1,new GeneralComparator(true));
Arrays.sort(a2,new GeneralComparator(true));
return Arrays.equals(a1, a2);
}
/**
* Compares two collections irrespective of their order and regardless of
* their implemented subinterfaces of <code>Collection</code>. The running time of this method is
* no worse than <code>O(nlogn)</code>.
*
* The collections are dumped into arrays, sorted using <code>GeneralComparator</code> and
* then the sorted arrays are compared one element at a time.
*
* @param c1 first <code>Collection</code>
* @param c2 second <code>Collection</code>
* @return negative integer,zero, or positive integer as <code>c1</code> is less than, equal to,
* or greater than <code>c2</code>, respectively
*/
public static int unorderedCollectionCompare(Collection<?> c1,Collection<?> c2)
{
if(c1 == c2) return 0;
// null checks
if(c1 == null) return -1;
if(c2 == null) return 1;
Comparator<Object> comp = new GeneralComparator(true);
// dump both collections into arrays, sort them using GeneralComparator and then compare the arrays
Object[] a1 = c1.toArray();
Object[] a2 = c2.toArray();
Arrays.sort(a1,comp);
Arrays.sort(a2,comp);
//now compare values
for(int i = 0, size = Math.min(a1.length,a2.length); i < size; ++i)
{
int result = comp.compare(a1[i], a2[i]);
if(result != 0) return result;
}
return a1.length - a2.length;
}
/**
* Compares two ordered collections using <code>GeneralComparator</code>.
*
*
* @param c1 first <code>Collection</code>
* @param c2 second <code>Collection</code>
* @return negative integer,zero, or positive integer as <code>c1</code> is less than, equal to,
* or greater than <code>c2</code>, respectively
*/
public static int orderedCollectionCompare(Collection<?> c1,Collection<?> c2)
{
if(c1 == c2) return 0;
// null checks
if(c1 == null) return -1;
if(c2 == null) return 1;
Comparator<Object> comp = new GeneralComparator(true);
Iterator<?> i1 = c1.iterator();
Iterator<?> i2 = c2.iterator();
while(i1.hasNext() && i2.hasNext())
{
int result = comp.compare(i1.next(), i2.next());
if(result != 0) return result;
}
return c1.size() - c2.size();
}
/**
* Converts a <code>Collection</code> into a deliminator-separated String
* @param input <code>Collection</code> to convert
* @param del the deliminator character
* @return the deliminated string
*/
public static String convertCollectionIntoDelStr(Collection<?> input,String del)
{
if(input == null)
return null;
if(del == null)
throw new NullPointerException("del");
StringBuilder str = new StringBuilder();
boolean first = true;
for(Iterator<?> it = input.iterator(); it.hasNext();)
{
String s = MiscUtils.toString(it.next());
// if(!MiscUtils.isEmpty(s))
// {
if(!first)
str.append(del);
str.append(s);
first = false;
// }
}
return str.toString();
}
/**
* Converts an input <code>Collection</code> of objects into a collection of the string
* representations of those objects. The order of the elements in the returned collection is
* the same as those returned by <code>input.iterator()</code>.
*
* @param input the input <code>Collection</code>
* @return <code>input</code> converted to a collection of strings
*/
public static Collection<String> toStringCollection(Collection<?> input)
{
if(input == null) throw new NullPointerException("input");
List<String> values = new ArrayList<String>(input.size());
for(Object o : input)
values.add(MiscUtils.toString(o));
return values;
}
/**
* Converts a deliminated string into a collection of the separated parts.
* Each delimited entry is trimmed of whitespace.
*
* @param input the deliminated string
* @param del the deliminator charactor
* @return the <code>Collection</code> of the deliminated terms
*/
public static Collection<String> convertDelStrIntoCollection(String input,String del)
{
if(input == null) return null;
if(del == null) throw new NullPointerException("del");
String [] split = delimSplit(input,del);
List<String> values = new ArrayList<String>(split.length);
if(split.length != 1 || !MiscUtils.isEmpty(split[0]))
{
for(String s : split)
{
s = s.trim();
// if(!MiscUtils.isEmpty(s))
values.add(s);
}
}
return values;
}
private static String[] delimSplit(String s,String del)
{
// del = !del.endsWith("?") ?
// new StringBuilder(del.length() + 3).append('(').append(del).append(")+").toString() :
// del;
// return s.split(del);
// don't discard trailing empty values
return s.split(del,-1);
}
/**
* Converts a map into a delimited string. Each map entry is trimmed of whitespace.
*
* @param input the input map
* @param entryDel the delimiter sequence for separating map entries
* @param keyValueDelim the delimiter sequence for separating keys and values
* @return the delimited string
*/
public static String convertMapIntoDelStr(Map<?,?> input,String entryDel,String keyValueDelim)
{
if(input == null)
return null;
if(entryDel == null)
throw new NullPointerException("entryDel");
if(keyValueDelim == null)
throw new NullPointerException("keyValueDel");
StringBuilder str = new StringBuilder();
boolean first = true;
for(Iterator<?> it = input.entrySet().iterator();it.hasNext();)
{
Map.Entry<?,?> E = (Map.Entry<?, ?>)it.next();
String key = MiscUtils.toString(E.getKey()).trim();
String value = MiscUtils.toString(E.getValue()).trim();
// if(!MiscUtils.isEmpty(key))
// {
if(!first)
str.append(entryDel);
str.append(key);
str.append(keyValueDelim);
str.append(value);
first = false;
// }
}
return str.toString();
}
/**
* This method is the inverse of {@link #convertMapIntoDelStr(Map, String, String)} and converts
* the string-delimited map back into a <code>java.util.Map</code>, but each key-value
* is a string.
*
* @param input the delimited input string
* @param entryDel the delimiter sequence for separating map entries
* @param keyValueDelim the delimiter sequence for separating keys and values
* @return the parsed map
*/
public static Map<String,String> convertDelStrIntoMap(String input,String entryDel,String keyValueDelim)
{
if(input == null)
return null;
if(entryDel == null)
throw new NullPointerException("entryDel");
if(keyValueDelim == null)
throw new NullPointerException("keyValueDel");
Map<String,String> map = new LinkedHashMap<String,String>();
String [] entries = delimSplit(input,entryDel);
for(String entry : entries)
{
entry = entry.trim();
if(!MiscUtils.isEmpty(entry))
{
String [] split = delimSplit(entry,keyValueDelim);
if(split.length == 2)
{
map.put(split[0], split[1]);
}
// check for empty key or value
else if(split.length == 1)
{
String keyValue = split[0];
if(entry.startsWith(keyValueDelim))
map.put("", keyValue);
else if(entry.endsWith(keyValueDelim))
map.put(keyValue, "");
else
throw new IllegalArgumentException("input=[" + input + "] contains invalid entry: " + entry);
}
// empty key and value
else if(split.length == 0)
{
map.put("", "");
}
else // bad input
{
throw new IllegalArgumentException("input=[" + input + "] contains invalid entry: " + entry);
}
}
}
return map;
}
/**
* Creates a <code>Map</code> from a <code>List</code> of pairs by mapping the first element
* of each pair in the list to its corresponding second element. The order in the map is the same
* as the order in the list. If a first element in a pair is repeated then the last such pair encountered
* will be the entry in the map.
*
* @param pairList the list of pairs
* @return a <code>Map</code> of the pairs
*/
public static <S,T> Map<S,T> createMapFromPairList(List<Pair<S,T>> pairList)
{
if(pairList == null)
return null;
Map<S,T> m = CollectionUtils.createLinkedHashMap(pairList.size(), LOAD_FACTOR);
for(Pair<S,T> p : pairList)
m.put(p.first,p.second);
return m;
}
/*
* Creates a <code>List</code> of pairs from the input <code>Map</code>. Each pair is formed
* from the key,value pairing in each entry in the map. The order of the returned <code>List</code>
* is the same as that of the iteration order of the map.
*
* @param the map
* @return a <code>List</code> of pairs holding the entries of the map
*/
public static <S,T> List<Pair<S,T>> createPairListFromMap(Map<S,T> map)
{
if(map == null)
return null;
List<Pair<S,T>> pairs = new ArrayList<Pair<S,T>>(map.size());
for(Map.Entry<S,T> e : map.entrySet())
pairs.add(Pair.makePair(e.getKey(), e.getValue()));
return pairs;
}
/**
* Returns a new <code>ArrayList</code> containing only those elements
* in <code>origList</code> that are also present in <code>universe</code>.
* This method is meant to be a faster alternative to <code>Collection.retainAll</code>
* for <code>ArrayList</code> since removal operations take O(n) in <code>ArrayList</code>.
*
* @param <E> type of element
* @param origList original element <code>ArrayList</code>
* @param universe <code>Set</code> of all valid elements
* @return new <code>ArrayList</code> containing only those elements
* in <code>origList</code> that are also present in <code>universe</code>
*/
public static<E> ArrayList<E> retainAll(ArrayList<E> origList,Set<E> universe)
{
ArrayList<E> newElms = new ArrayList<E>(origList.size());
for(E elm : origList)
{
if(universe.contains(elm))
newElms.add(elm);
}
return newElms;
}
/**
* Compares whether two lists contain the same objects, irrespective of order.
* May be faster than {@link #unorderedCollectionEquals(Collection, Collection)}
* for lists.
*
* @param lhs the first list
* @param rhs the second list
* @return <code>true</code> if the lists containing the same strings, disregarding
* order, and <code>false</code> otherwise
*/
public static <T extends Comparable<? super T>> boolean unorderedListEquals(List<T> lhs,List<T> rhs)
{
return unorderedCollectionEquals(lhs,rhs);
}
/**
* Returns a read-only copy of
* <code>Map</code> that orders its entries according
* to the natural order of its values. The copy is read-only
* because further invocations of <code>Map.put</code> may break the
* established ordering.
*
* @param m the <code>Map</code> for which to return a value-ordered copy
* @return a read-only <code>Map</code> ordered by its values
* @throws NullPointerException if a <code>null</code> key or value exists in <code>m</code>
* or if a key or value does not implement the <code>java.lang.Comparable</code> interface
*/
@SuppressWarnings("unchecked")
public static <K,V> Map<K,V> valueSortedMap(Map<K,V> m)
{
if(m == null)
throw new NullPointerException("m");
// use an array since it is faster to sort than a list since no extra
// copies are made
Pair [] entries = new Pair [m.size()];
int count = 0;
for(Map.Entry<K, V> E : m.entrySet())
entries[count++] = new Pair<K,V>(E.getKey(),E.getValue());
Arrays.sort(entries);
final float lf = CollectionUtils.LOAD_FACTOR;
Map<K,V> orderedMap =
new LinkedHashMap<K,V>(CollectionUtils.calcHashCapacity(
m.size(), lf),lf);
for(int i = 0, len = entries.length; i < len; ++i)
{
Pair<K,V> entry = entries[i];
orderedMap.put(entry.first,entry.second);
}
return Collections.unmodifiableMap(orderedMap);
}
/**
* Creates a synchronization wrapper for <code>BidiMap</code>.
*
* @param <K> key type
* @param <V> value type
* @param map the <code>BidiMap</code>
* @return a synchronized version of the original <code>map</code>
*/
public static <K,V> BidiMap<K,V> synchronizedBidiMap(BidiMap<K,V> map)
{
return new SynchronizedBidiMap<K,V>(map);
}
/**
* Creates a unmodifiable wrapper for <code>BidiMap</code>.
*
* @param <K> key type
* @param <V> value type
* @param map the <code>BidiMap</code>
* @return an unmodifiable version of the original <code>map</code>
*/
public static <K,V> BidiMap<K,V> unmodifiableBidiMap(BidiMap<K,V> map)
{
return new UnmodifiableBidiMap<K,V>(map);
}
/**
* Wraps <code>map</code> in an object that implements the <code>BidiMap</code> interface.
* The <code>getKey</code> and <code>removeValue</code> operations of <code>BidiMap</code>
* as well as the <code>containsValue</code> method of <code>java.util.Map</code>
* may be implemented by iterating over the entry set of <code>map</code> and therefore can
* be expected to perform in <code>O(n)</code> time. The resulting map is unsynchronized;
* a synchronized version can be obtained by calling {@link #synchronizedBidiMap(BidiMap)}
* with the returned <code>BidiMap</code>.
*
* @param <K> key type
* @param <V> value type
* @param map the <code>Map</code> to wrap
* @return a <code>BidiMap</code> wrapper around <code>map</code>
*/
public static <K,V> BidiMap<K,V> bidiMapWrapper(Map<K,V> map)
{
return new BidiMapWrapper<K,V>(map);
}
/**
* Removes the <code>null</code> values from the list.
*
* @param values the values
*/
public static void removeNulls(List<?> values)
{
if(values != null)
{
for(ListIterator<?> i = values.listIterator(values.size());i.hasPrevious();)
{
Object value = i.previous();
if(value == null)
i.remove();
}
}
}
/**
* Removes the duplicates from the given list and optionally stores elements
* that were duplicated in <code>outDuplicated</code>.
*
* @param list the <code>List</code>
* @param outDuplicated <code>Set</code> to store duplicated elements or <code>null</code>
*
*/
public static <T> void removeDuplicates(List<T> list,Set<T> outDuplicated)
{
for(ListIterator<T> it = list.listIterator(); it.hasNext();)
{
T first = it.next();
while(it.hasNext())
{
T second = it.next();
// remove and note the duplicate
if(MiscUtils.safeEquals(first, second))
{
it.remove();
if(outDuplicated != null)
outDuplicated.add(second);
}
// compare second with following element
else
{
it.previous();
break;
}
}
}
}
/**
* Removes all occurrences of <code>e</code> from <code>c</code>.
*
* @param c the <code>Collection</code>
* @param e the element to remove
*/
public static <T> void removeAll(Collection<?> c,Object e)
{
if(c instanceof List)
{
List<?> list = (List<?>)c;
int index = -1;
do
{
index = list.lastIndexOf(e);
if(index != -1)
list.remove(index);
}
while(index != -1);
}
else if(c instanceof Set)
{
c.remove(e);
}
else
{
while(c.remove(e))
;
}
}
public static <T extends Comparable<? super T>> Comparator<T> createComparatorFromComparable(T c)
{
return new Comparator<T>()
{
public int compare(T s, T t)
{
return s.compareTo(t);
}
};
}
}
| lgpl-3.0 |
trust-tech/go-trustmachine | vendor/github.com/nsf/termbox-go/api.go | 11987 | // +build !windows
package termbox
import "github.com/mattn/go-runewidth"
import "fmt"
import "os"
import "os/signal"
import "syscall"
import "runtime"
// public API
// Initializes termbox library. This function should be called before any other functions.
// After successful initialization, the library must be finalized using 'Close' function.
//
// Example usage:
// err := termbox.Init()
// if err != nil {
// panic(err)
// }
// defer termbox.Close()
func Init() error {
var err error
out, err = os.OpenFile("/dev/tty", syscall.O_WRONLY, 0)
if err != nil {
return err
}
in, err = syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
if err != nil {
return err
}
err = setup_term()
if err != nil {
return fmt.Errorf("termbox: error while reading terminfo data: %v", err)
}
signal.Notify(sigwinch, syscall.SIGWINCH)
signal.Notify(sigio, syscall.SIGIO)
_, err = fcntl(in, syscall.F_SETFL, syscall.O_ASYNC|syscall.O_NONBLOCK)
if err != nil {
return err
}
_, err = fcntl(in, syscall.F_SETOWN, syscall.Getpid())
if runtime.GOOS != "darwin" && err != nil {
return err
}
err = tcgetattr(out.Fd(), &orig_tios)
if err != nil {
return err
}
tios := orig_tios
tios.Iflag &^= syscall_IGNBRK | syscall_BRKINT | syscall_PARMRK |
syscall_ISTRIP | syscall_INLCR | syscall_IGNCR |
syscall_ICRNL | syscall_IXON
tios.Lflag &^= syscall_ECHO | syscall_ECHONL | syscall_ICANON |
syscall_ISIG | syscall_IEXTEN
tios.Cflag &^= syscall_CSIZE | syscall_PARENB
tios.Cflag |= syscall_CS8
tios.Cc[syscall_VMIN] = 1
tios.Cc[syscall_VTIME] = 0
err = tcsetattr(out.Fd(), &tios)
if err != nil {
return err
}
out.WriteString(funcs[t_enter_ca])
out.WriteString(funcs[t_enter_keypad])
out.WriteString(funcs[t_hide_cursor])
out.WriteString(funcs[t_clear_screen])
termw, termh = get_term_size(out.Fd())
back_buffer.init(termw, termh)
front_buffer.init(termw, termh)
back_buffer.clear()
front_buffer.clear()
go func() {
buf := make([]byte, 128)
for {
select {
case <-sigio:
for {
n, err := syscall.Read(in, buf)
if err == syscall.EAGAIN || err == syscall.EWOULDBLOCK {
break
}
select {
case input_comm <- input_event{buf[:n], err}:
ie := <-input_comm
buf = ie.data[:128]
case <-quit:
return
}
}
case <-quit:
return
}
}
}()
IsInit = true
return nil
}
// Interrupt an in-progress call to PollEvent by causing it to return
// EventInterrupt. Note that this function will block until the PollEvent
// function has successfully been interrupted.
func Interrupt() {
interrupt_comm <- struct{}{}
}
// Finalizes termbox library, should be called after successful initialization
// when termbox's functionality isn't required anymore.
func Close() {
quit <- 1
out.WriteString(funcs[t_show_cursor])
out.WriteString(funcs[t_sgr0])
out.WriteString(funcs[t_clear_screen])
out.WriteString(funcs[t_exit_ca])
out.WriteString(funcs[t_exit_keypad])
out.WriteString(funcs[t_exit_mouse])
tcsetattr(out.Fd(), &orig_tios)
out.Close()
syscall.Close(in)
// reset the state, so that on next Init() it will work again
termw = 0
termh = 0
input_mode = InputEsc
out = nil
in = 0
lastfg = attr_invalid
lastbg = attr_invalid
lastx = coord_invalid
lasty = coord_invalid
cursor_x = cursor_hidden
cursor_y = cursor_hidden
foreground = ColorDefault
background = ColorDefault
IsInit = false
}
// Synchronizes the internal back buffer with the terminal.
func Flush() error {
// invalidate cursor position
lastx = coord_invalid
lasty = coord_invalid
update_size_maybe()
for y := 0; y < front_buffer.height; y++ {
line_offset := y * front_buffer.width
for x := 0; x < front_buffer.width; {
cell_offset := line_offset + x
back := &back_buffer.cells[cell_offset]
front := &front_buffer.cells[cell_offset]
if back.Ch < ' ' {
back.Ch = ' '
}
w := runewidth.RuneWidth(back.Ch)
if w == 0 || w == 2 && runewidth.IsAmbiguousWidth(back.Ch) {
w = 1
}
if *back == *front {
x += w
continue
}
*front = *back
send_attr(back.Fg, back.Bg)
if w == 2 && x == front_buffer.width-1 {
// there's not enough space for 2-cells rune,
// let's just put a space in there
send_char(x, y, ' ')
} else {
send_char(x, y, back.Ch)
if w == 2 {
next := cell_offset + 1
front_buffer.cells[next] = Cell{
Ch: 0,
Fg: back.Fg,
Bg: back.Bg,
}
}
}
x += w
}
}
if !is_cursor_hidden(cursor_x, cursor_y) {
write_cursor(cursor_x, cursor_y)
}
return flush()
}
// Sets the position of the cursor. See also HideCursor().
func SetCursor(x, y int) {
if is_cursor_hidden(cursor_x, cursor_y) && !is_cursor_hidden(x, y) {
outbuf.WriteString(funcs[t_show_cursor])
}
if !is_cursor_hidden(cursor_x, cursor_y) && is_cursor_hidden(x, y) {
outbuf.WriteString(funcs[t_hide_cursor])
}
cursor_x, cursor_y = x, y
if !is_cursor_hidden(cursor_x, cursor_y) {
write_cursor(cursor_x, cursor_y)
}
}
// The shortcut for SetCursor(-1, -1).
func HideCursor() {
SetCursor(cursor_hidden, cursor_hidden)
}
// Changes cell's parameters in the internal back buffer at the specified
// position.
func SetCell(x, y int, ch rune, fg, bg Attribute) {
if x < 0 || x >= back_buffer.width {
return
}
if y < 0 || y >= back_buffer.height {
return
}
back_buffer.cells[y*back_buffer.width+x] = Cell{ch, fg, bg}
}
// Returns a slice into the termbox's back buffer. You can get its dimensions
// using 'Size' function. The slice remains valid as long as no 'Clear' or
// 'Flush' function calls were made after call to this function.
func CellBuffer() []Cell {
return back_buffer.cells
}
// After getting a raw event from PollRawEvent function call, you can parse it
// again into an ordinary one using termbox logic. That is parse an event as
// termbox would do it. Returned event in addition to usual Event struct fields
// sets N field to the amount of bytes used within 'data' slice. If the length
// of 'data' slice is zero or event cannot be parsed for some other reason, the
// function will return a special event type: EventNone.
//
// IMPORTANT: EventNone may contain a non-zero N, which means you should skip
// these bytes, because termbox cannot recognize them.
//
// NOTE: This API is experimental and may change in future.
func ParseEvent(data []byte) Event {
event := Event{Type: EventKey}
ok := extract_event(data, &event)
if !ok {
return Event{Type: EventNone, N: event.N}
}
return event
}
// Wait for an event and return it. This is a blocking function call. Instead
// of EventKey and EventMouse it returns EventRaw events. Raw event is written
// into `data` slice and Event's N field is set to the amount of bytes written.
// The minimum required length of the 'data' slice is 1. This requirement may
// vary on different platforms.
//
// NOTE: This API is experimental and may change in future.
func PollRawEvent(data []byte) Event {
if len(data) == 0 {
panic("len(data) >= 1 is a requirement")
}
var event Event
if extract_raw_event(data, &event) {
return event
}
for {
select {
case ev := <-input_comm:
if ev.err != nil {
return Event{Type: EventError, Err: ev.err}
}
inbuf = append(inbuf, ev.data...)
input_comm <- ev
if extract_raw_event(data, &event) {
return event
}
case <-interrupt_comm:
event.Type = EventInterrupt
return event
case <-sigwinch:
event.Type = EventResize
event.Width, event.Height = get_term_size(out.Fd())
return event
}
}
}
// Wait for an event and return it. This is a blocking function call.
func PollEvent() Event {
var event Event
// try to extract event from input buffer, return on success
event.Type = EventKey
ok := extract_event(inbuf, &event)
if event.N != 0 {
copy(inbuf, inbuf[event.N:])
inbuf = inbuf[:len(inbuf)-event.N]
}
if ok {
return event
}
for {
select {
case ev := <-input_comm:
if ev.err != nil {
return Event{Type: EventError, Err: ev.err}
}
inbuf = append(inbuf, ev.data...)
input_comm <- ev
ok := extract_event(inbuf, &event)
if event.N != 0 {
copy(inbuf, inbuf[event.N:])
inbuf = inbuf[:len(inbuf)-event.N]
}
if ok {
return event
}
case <-interrupt_comm:
event.Type = EventInterrupt
return event
case <-sigwinch:
event.Type = EventResize
event.Width, event.Height = get_term_size(out.Fd())
return event
}
}
}
// Returns the size of the internal back buffer (which is mostly the same as
// terminal's window size in characters). But it doesn't always match the size
// of the terminal window, after the terminal size has changed, the internal
// back buffer will get in sync only after Clear or Flush function calls.
func Size() (width int, height int) {
return termw, termh
}
// Clears the internal back buffer.
func Clear(fg, bg Attribute) error {
foreground, background = fg, bg
err := update_size_maybe()
back_buffer.clear()
return err
}
// Sets termbox input mode. Termbox has two input modes:
//
// 1. Esc input mode. When ESC sequence is in the buffer and it doesn't match
// any known sequence. ESC means KeyEsc. This is the default input mode.
//
// 2. Alt input mode. When ESC sequence is in the buffer and it doesn't match
// any known sequence. ESC enables ModAlt modifier for the next keyboard event.
//
// Both input modes can be OR'ed with Mouse mode. Setting Mouse mode bit up will
// enable mouse button press/release and drag events.
//
// If 'mode' is InputCurrent, returns the current input mode. See also Input*
// constants.
func SetInputMode(mode InputMode) InputMode {
if mode == InputCurrent {
return input_mode
}
if mode&(InputEsc|InputAlt) == 0 {
mode |= InputEsc
}
if mode&(InputEsc|InputAlt) == InputEsc|InputAlt {
mode &^= InputAlt
}
if mode&InputMouse != 0 {
out.WriteString(funcs[t_enter_mouse])
} else {
out.WriteString(funcs[t_exit_mouse])
}
input_mode = mode
return input_mode
}
// Sets the termbox output mode. Termbox has four output options:
//
// 1. OutputNormal => [1..8]
// This mode provides 8 different colors:
// black, red, green, yellow, blue, magenta, cyan, white
// Shortcut: ColorBlack, ColorRed, ...
// Attributes: AttrBold, AttrUnderline, AttrReverse
//
// Example usage:
// SetCell(x, y, '@', ColorBlack | AttrBold, ColorRed);
//
// 2. Output256 => [1..256]
// In this mode you can leverage the 256 terminal mode:
// 0x01 - 0x08: the 8 colors as in OutputNormal
// 0x09 - 0x10: Color* | AttrBold
// 0x11 - 0xe8: 216 different colors
// 0xe9 - 0x1ff: 24 different shades of grey
//
// Example usage:
// SetCell(x, y, '@', 184, 240);
// SetCell(x, y, '@', 0xb8, 0xf0);
//
// 3. Output216 => [1..216]
// This mode supports the 3rd range of the 256 mode only.
// But you dont need to provide an offset.
//
// 4. OutputGrayscale => [1..26]
// This mode supports the 4th range of the 256 mode
// and black and white colors from 3th range of the 256 mode
// But you dont need to provide an offset.
//
// In all modes, 0x00 represents the default color.
//
// `go run _demos/output.go` to see its impact on your terminal.
//
// If 'mode' is OutputCurrent, it returns the current output mode.
//
// Note that this may return a different OutputMode than the one requested,
// as the requested mode may not be available on the target platform.
func SetOutputMode(mode OutputMode) OutputMode {
if mode == OutputCurrent {
return output_mode
}
output_mode = mode
return output_mode
}
// Sync comes handy when somentrusting causes desync between termbox's understanding
// of a terminal buffer and the reality. Such as a third party process. Sync
// forces a complete resync between the termbox and a terminal, it may not be
// visually pretty though.
func Sync() error {
front_buffer.clear()
err := send_clear()
if err != nil {
return err
}
return Flush()
}
| lgpl-3.0 |
premiummarkets/pm | premiumMarkets/pm-core/src/main/java/com/finance/pms/datasources/web/HttpSourceExchange.java | 3673 | /**
* Premium Markets is an automated stock market analysis system.
* It implements a graphical environment for monitoring stock markets technical analysis
* major indicators, for portfolio management and historical data charting.
* In its advanced packaging -not provided under this license- it also includes :
* Screening of financial web sites to pick up the best market shares,
* Price trend prediction based on stock markets technical analysis and indices rotation,
* Back testing, Automated buy sell email notifications on trend signals calculated over
* markets and user defined portfolios.
* With in mind beating the buy and hold strategy.
* Type 'Premium Markets FORECAST' in your favourite search engine for a free workable demo.
*
* Copyright (C) 2008-2014 Guillaume Thoreton
*
* This file is part of Premium Markets.
*
* Premium Markets is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.finance.pms.datasources.web;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.finance.pms.datasources.shares.Currency;
public class HttpSourceExchange extends HttpSourceYahoo {
public HttpSourceExchange(String pathToprops, MyBeanFactoryAware beanFactory) {
super(pathToprops, beanFactory);
}
public String getUrl(Currency currency) {
//String url = "http://www.xe.com/ucc/convert.cgi?Amount=1&From=%S&To=%S&image.x=51&image.y=10&image=Submit";
//String url = "http://uk.finance.yahoo.com/currencies/converter/#from=%S;to=EUR;amt=1"
String url = "http://www.gocurrency.com/v2/dorate.php?inV=1&from=%S&to=%S&Calculate=Convert";
return String.format(url,currency.toString(),"EUR");
}
public String getOandaHistoryUrl(Currency fromCurrency, Currency toCurrency, Date start, Date end) {
//String url="http://www.oanda.com/transactionCurrency/historical-rates?date_fmt=us&date=%s&date1=%s&exch=%S&expr=%S&margin_fixed=0&format=CSV&redirected=1";
//http://www.oanda.com/currency/historical-rates-classic?date_fmt=normal&date=08/06/14&date1=01/06/14&exch=GBP&expr=EUR&margin_fixed=0&format=CSV&redirected=1
String url="http://www.oanda.com/currency/historical-rates-classic?date_fmt=normal&date=%s&date1=%s&exch=%S&expr=%S&margin_fixed=0&format=CSV&redirected=1";
return String.format(url,new SimpleDateFormat("dd/MM/yy").format(end),new SimpleDateFormat("dd/MM/yy").format(start),fromCurrency.toString(),toCurrency.toString());
}
public String getImfHistoryUrl(Date date) {
String url="http://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=%s&reportType=REP&tsvflag=Y";
//String url="http://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=%s";
return String.format(url,new SimpleDateFormat("yyyy-MM-dd").format(date));
}
public String getEuropeanCentralBankUrl() {
return "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.zip";
}
public String getXRatesHistoryUrl(Date date) {
String url="http://www.x-rates.com/historical/?from=USD&amount=1.00&date=%s";
return String.format(url,new SimpleDateFormat("yyyy-MM-dd").format(date));
}
}
| lgpl-3.0 |
marcokemper/DVTk | DVTk_Library/Source/Libraries/Validation/validator.cpp | 69216 | // ------------------------------------------------------
// DVTk - The Healthcare Validation Toolkit (www.dvtk.org)
// Copyright © 2009 DVTk
// ------------------------------------------------------
// This file is part of DVTk.
//
// DVTk is free software; you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License as published by the Free Software Foundation; either version 3.0
// of the License, or (at your option) any later version.
//
// DVTk is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with this
// library; if not, see <http://www.gnu.org/licenses/>
//*****************************************************************************
// DESCRIPTION : Validation engine class.
//*****************************************************************************
//*****************************************************************************
// EXTERNAL DECLARATIONS
//*****************************************************************************
#include "validator.h"
#include "val_attribute.h"
#include "val_attribute_group.h"
#include "val_object_results.h"
#include "val_value_sq.h"
#include "record_types.h"
#include "qr_validator.h"
#include "IAttributeGroup.h" // AttributeGroup component interface file.
#include "Idefinition.h" // Definition component interface file.
#include "Idicom.h" // Dicom component interface file.
//>>===========================================================================
VALIDATOR_CLASS::VALIDATOR_CLASS()
// DESCRIPTION : Class constructor.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
objectResultsM_ptr = NULL;
resultsTypeM = RESULTS_OBJECT;
specificCharacterSetM_ptr = NULL;
flagsM = ATTR_FLAG_DO_NOT_INCLUDE_TYPE3;
defDatasetM_ptr = NULL;
loggerM_ptr = NULL;
}
//>>===========================================================================
VALIDATOR_CLASS::~VALIDATOR_CLASS()
// DESCRIPTION : Class destructor.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
if (specificCharacterSetM_ptr)
{
delete specificCharacterSetM_ptr;
}
delete objectResultsM_ptr;
}
//>>===========================================================================
RESULTS_TYPE VALIDATOR_CLASS::GetResultsType()
// DESCRIPTION : Get the results type.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
return resultsTypeM;
}
//>>===========================================================================
void VALIDATOR_CLASS::SetLogger(LOG_CLASS *logger_ptr)
// DESCRIPTION : Set the logger.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
loggerM_ptr = logger_ptr;
}
//>>===========================================================================
void VALIDATOR_CLASS::SetFlags(UINT flags)
// DESCRIPTION : Set the flags.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
flagsM = flags;
}
//>>===========================================================================
bool VALIDATOR_CLASS::CreateResultsObject()
// DESCRIPTION : Create the results object.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
objectResultsM_ptr = new VAL_OBJECT_RESULTS_CLASS();
resultsTypeM = RESULTS_OBJECT;
return (objectResultsM_ptr == NULL) ? false : true;
}
//>>===========================================================================
void VALIDATOR_CLASS::UpdateSpecificCharacterSet(DCM_ATTRIBUTE_GROUP_CLASS *attributeGroup_ptr)
// DESCRIPTION : Updates the Specific Character Set.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// check if the attribute group is present
if (attributeGroup_ptr == NULL) return;
// initialize the specific character set
if (specificCharacterSetM_ptr)
{
specificCharacterSetM_ptr->ClearCharacterSets();
}
else
{
specificCharacterSetM_ptr = new SPECIFIC_CHARACTER_SET_CLASS();
}
// try to get the specific character set attribute
DCM_ATTRIBUTE_CLASS *attribute_ptr = attributeGroup_ptr->GetAttributeByTag(TAG_SPECIFIC_CHARACTER_SET);
if (attribute_ptr == NULL) return;
// loop adding each specific character set value
for (int i = 0; i < attribute_ptr->GetNrValues(); i++)
{
// Extended Character Set: needed for checking VR's of PN, ST, LT, UT, SH, LO
BASE_VALUE_CLASS *value_ptr = attribute_ptr->GetValue(i);
if (value_ptr)
{
string value;
value_ptr->Get(value);
specificCharacterSetM_ptr->AddCharacterSet(i+1, value);
}
}
}
//>>===========================================================================
bool VALIDATOR_CLASS::CreateCommandResultsFromDef(DCM_COMMAND_CLASS *dcmCommand_ptr)
// DESCRIPTION : Create the Command Validation Results from the Command Definition.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
objectResultsM_ptr = new VAL_OBJECT_RESULTS_CLASS();
resultsTypeM = RESULTS_OBJECT;
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "CreateCommandResultsFromDef");
}
// Check for valid input.
if (dcmCommand_ptr == NULL)
{
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_COMMAND_1,
"No Command provided - validation skipped");
return false;
}
// First find out what SOP class we're dealing with.
string sopClassUid;
if (dcmCommand_ptr->getUIValue(TAG_AFFECTED_SOP_CLASS_UID, sopClassUid) == false)
{
dcmCommand_ptr->getUIValue(TAG_REQUESTED_SOP_CLASS_UID, sopClassUid);
}
// Get command id for the dimse.
DIMSE_CMD_ENUM dimseCommand = dcmCommand_ptr->getCommandId();
// Give the results a name.
objectResultsM_ptr->SetName(mapCommandName(dimseCommand));
// Get the command definition.
DEF_COMMAND_CLASS *defCommand_ptr = DEFINITION->GetCommand(dimseCommand);
if (defCommand_ptr == NULL)
{
char message[256];
sprintf(message,
"Could not find Command definition for SOP: %s, Dimse: %s",
sopClassUid.c_str(), objectResultsM_ptr->GetName().c_str());
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_COMMAND_2, message);
return false;
}
CreateModuleResultsFromDef(defCommand_ptr,
dcmCommand_ptr);
return true;
}
//>>===========================================================================
bool VALIDATOR_CLASS::CreateDatasetResultsFromDef(DCM_COMMAND_CLASS *dcmCommand_ptr,
DCM_DATASET_CLASS *dcmDataset_ptr,
AE_SESSION_CLASS *aeSession_ptr)
// DESCRIPTION : Create the Dataset Validation Results from the Dataset Definition.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
char message[256];
defDatasetM_ptr = NULL;
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "CreateDatasetResultsFromDef");
}
// Check for valid input.
if ((dcmCommand_ptr == NULL) ||
(dcmDataset_ptr == NULL))
{
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_COMMAND_1,
"No Command and/or Dataset provided - validation skipped");
LogSystemDefinitions();
return false;
}
DIMSE_CMD_ENUM dimseCommand = dcmCommand_ptr->getCommandId();
string iodName = "";
if (dcmDataset_ptr->getIodName())
{
iodName = dcmDataset_ptr->getIodName();
}
string aeName = aeSession_ptr->GetName();
string aeVersion = aeSession_ptr->GetVersion();
if (iodName != "")
{
// Try to find the dataset definition through the name of the SOP class.
DVT_STATUS result = DEFINITION->GetDataset(dimseCommand, iodName, aeSession_ptr, &defDatasetM_ptr);
switch(result)
{
case MSG_DEFINITION_NOT_FOUND:
// defDatasetM_ptr is returned NULL here - nothing further to do
break;
case MSG_DEFAULT_DEFINITION_FOUND:
// not using the requested definition AE - should inform the user
// defDatasetM_ptr contains the default definition
{
aeName = DEFAULT_AE_NAME;
aeVersion = DEFAULT_AE_VERSION;
string stringMessage;
sprintf(message,
"Could not find System AE Name \"%s\" - AE Version \"%s\" Dataset definition for SOP: \"%s\", Dimse: %s.",
aeSession_ptr->GetName().c_str(),
aeSession_ptr->GetVersion().c_str(),
FILE_META_SOP_CLASS_NAME,
mapCommandName(DIMSE_CMD_CSTORE_RQ));
stringMessage.append(message);
sprintf(message,
" Using Default AE Name \"%s\" - AE Version \"%s\"",
DEFAULT_AE_NAME,
DEFAULT_AE_VERSION);
stringMessage.append(message);
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_DEFINITION_6, stringMessage);
}
break;
case MSG_OK:
// found the requested definition
// defDatasetM_ptr contains the requested definition
break;
default:
break;
}
}
if (defDatasetM_ptr == NULL)
{
// Definition dataset not found. Try to find the dataset through
// the SOP UID. First find out what SOP class we're dealing with.
string sopClassUid;
bool status = dcmCommand_ptr->getUIValue(TAG_AFFECTED_SOP_CLASS_UID, sopClassUid);
if (!status)
{
status = dcmCommand_ptr->getUIValue(TAG_REQUESTED_SOP_CLASS_UID, sopClassUid);
}
if (!status)
{
sprintf(message,
"Could not find definition for Dimse: %s %s",
mapCommandName(dimseCommand),
iodName.c_str());
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_DEFINITION_5, message);
LogSystemDefinitions();
return false;
}
DEF_SOPCLASS_CLASS *defSopClass_ptr = NULL;
DVT_STATUS result = DEFINITION->GetSopClassByUid(sopClassUid, aeSession_ptr, &defSopClass_ptr);
switch(result)
{
case MSG_DEFINITION_NOT_FOUND:
// sop_class is returned NULL here - nothing further to do
break;
case MSG_DEFAULT_DEFINITION_FOUND:
// not using the requested definition AE - should inform the user
// sop_class contains the default definition
{
aeName = DEFAULT_AE_NAME;
aeVersion = DEFAULT_AE_VERSION;
string stringMessage;
sprintf(message,
"Could not find System AE Name \"%s\" - AE Version \"%s\" Dataset definition for SOP: \"%s\", Dimse: %s %s.",
aeSession_ptr->GetName().c_str(),
aeSession_ptr->GetVersion().c_str(),
sopClassUid.c_str(),
mapCommandName(dimseCommand),
iodName.c_str());
stringMessage.append(message);
sprintf(message,
" Using Default AE Name \"%s\" - AE Version \"%s\"",
DEFAULT_AE_NAME,
DEFAULT_AE_VERSION);
stringMessage.append(message);
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_DEFINITION_6, stringMessage);
}
break;
case MSG_OK:
// found the requested definition
// sop_class contains the requested definition
break;
default:
break;
}
if (defSopClass_ptr != NULL)
{
// Get the dataset for the SOP - DIMSE combination.
if (iodName.length())
{
defDatasetM_ptr = defSopClass_ptr->GetDataset(iodName, dimseCommand);
}
else
{
// We don't have an IOD name, try for command only.
defDatasetM_ptr = defSopClass_ptr->GetDataset(dimseCommand);
}
}
if (defDatasetM_ptr == NULL)
{
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_COMMAND_1,
"No Command and/or Dataset definition found - validation skipped");
LogSystemDefinitions();
return false;
}
}
string stringMessage;
sprintf(message,
"Validate: Selected Dataset definition: \"%s\".",
defDatasetM_ptr->GetName().c_str());
stringMessage.append(message);
sprintf(message,
" Using AE Name \"%s\" - AE Version \"%s\"",
aeName.c_str(),
aeVersion.c_str());
stringMessage.append(message);
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_DEFINITION_4, stringMessage);
// give the results a name.
objectResultsM_ptr->SetName(defDatasetM_ptr->GetName());
// set the dataset co-object as the command
objectResultsM_ptr->SetCommand(dcmCommand_ptr);
CreateModuleResultsFromDef(defDatasetM_ptr,
dcmDataset_ptr);
return true;
}
//>>===========================================================================
void VALIDATOR_CLASS::CreateModuleResultsFromDef(DEF_DICOM_OBJECT_CLASS *defDicomObject_ptr,
DCM_ATTRIBUTE_GROUP_CLASS *dcmAttributeGroup_ptr)
// DESCRIPTION : Create the Module Validation Results from the Module Definition.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
if ((defDicomObject_ptr == NULL) ||
(dcmAttributeGroup_ptr == NULL))
{
return;
}
// Update the Specific Character Set - required for extended character set validation
UpdateSpecificCharacterSet(dcmAttributeGroup_ptr);
// Check if the attributes in the attribute group are sorted.
if (!dcmAttributeGroup_ptr->IsSorted())
{
objectResultsM_ptr->GetMessages()->AddMessage(VAL_RULE_GENERAL_1, "Attributes are not sorted in ascending tag order");
}
for (UINT i = 0; i < defDicomObject_ptr->GetNrModules(); i++)
{
DEF_MODULE_CLASS *defModule_ptr = defDicomObject_ptr->GetModule(i);
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "CreateModuleResultsFromDef for \"%s\"", defModule_ptr->GetName().c_str());
}
// find out whether the module has to be included
bool addModule = false;
bool attributeTypeNotImportantSetToType3 = false;
bool useTextualCondition = false;
UINT32 singleMatchingAttribute = 0;
MOD_USAGE_ENUM usage = defModule_ptr->GetUsage();
switch (usage)
{
case MOD_USAGE_M:
addModule = true;
break;
case MOD_USAGE_C:
{
CONDITION_CLASS *condition_ptr = defModule_ptr->GetCondition();
if (condition_ptr)
{
CONDITION_RESULT_ENUM conditionResult = condition_ptr->Evaluate(dcmAttributeGroup_ptr, NULL, loggerM_ptr);
switch(conditionResult)
{
case CONDITION_TRUE:
// the module must be included - leave attribute types as defined
addModule = true;
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Module - Condition for \"%s\" is TRUE", defModule_ptr->GetName().c_str());
}
break;
case CONDITION_UNIMPORTANT:
// the module should be added but all attributes in the module can be set to Type 3
// - their presence is not important to the final validation result.
addModule = true;
attributeTypeNotImportantSetToType3 = true;
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Module - Condition for \"%s\" is UNIMPORTANT", defModule_ptr->GetName().c_str());
}
break;
case CONDITION_FALSE:
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Module - Condition for \"%s\" is not FALSE", defModule_ptr->GetName().c_str());
}
break;
case CONDITION_TRUE_REQUIRES_MANUAL_INTERPRETATION:
default:
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Module - Condition for \"%s\" is not supported", defModule_ptr->GetName().c_str());
}
break;
}
}
else
{
// check if a textual condition is defined
// useTextualCondition = (defModule_ptr->GetTextualCondition().length() > 0 ? true : false);
// - This check does not need to be made here as the addModule boolean will be set according
// to the presence of attributes in this conditional module being checked directly in the given
// attribute group - dcmAttributeGroup_ptr
// So leave useTextualCondition = false here.
// Add the module when an attribute is present in the dcm stream.
// This is the same rule as the with the User optional module.
addModule = defModule_ptr->EvaluateAddUserOptionalModule(dcmAttributeGroup_ptr, &singleMatchingAttribute);
if (loggerM_ptr)
{
if (addModule)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Module - Attributes found for \"%s\" is TRUE", defModule_ptr->GetName().c_str());
}
else
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Module - Attributes found for \"%s\" is FALSE", defModule_ptr->GetName().c_str());
}
}
}
}
break;
case MOD_USAGE_U:
{
addModule = defModule_ptr->EvaluateAddUserOptionalModule(dcmAttributeGroup_ptr, &singleMatchingAttribute);
if (loggerM_ptr)
{
if (addModule)
{
loggerM_ptr->text(LOG_DEBUG, 1, "User Optional Module - Attributes found for \"%s\" is TRUE", defModule_ptr->GetName().c_str());
}
else
{
loggerM_ptr->text(LOG_DEBUG, 1, "User Optional Module - Attributes found for \"%s\" is FALSE", defModule_ptr->GetName().c_str());
}
}
}
break;
default:
break;
}
if (addModule)
{
// Get a new Module Results object
VAL_ATTRIBUTE_GROUP_CLASS *moduleResults_ptr = new VAL_ATTRIBUTE_GROUP_CLASS();
// Link it to the parent Object Results
moduleResults_ptr->SetParentObject(objectResultsM_ptr);
// Update the singleMatchingAttribute
// - non zero value indicates that only one attribute was found in the dcmAttributeGroup_ptr that is in the defModule_ptr
// - we will check after completing the results object whether or not this moduleResults_ptr should be ignored or not when
// performing the final validation.
moduleResults_ptr->SetSingleMatchingAttribute(singleMatchingAttribute);
// Create the Attribute Group Results from the Module Definition
CreateAttributeGroupResultsFromDef(defModule_ptr,
dcmAttributeGroup_ptr,
moduleResults_ptr,
useTextualCondition,
attributeTypeNotImportantSetToType3);
// Add the Module Results to the Object Results
objectResultsM_ptr->AddModuleResults(moduleResults_ptr);
}
}
// now check if any of the Conditional or User Optional modules should be ignored in the final validation results
CheckIfAnyModulesShouldBeIgnored();
}
//>>===========================================================================
void VALIDATOR_CLASS::CreateAttributeGroupResultsFromDef(DEF_ATTRIBUTE_GROUP_CLASS *defAttrGroup_ptr,
DCM_ATTRIBUTE_GROUP_CLASS *dcmAttrGroup_ptr,
VAL_ATTRIBUTE_GROUP_CLASS *valAttrGroup_ptr,
bool useTextualCondition,
bool attributeTypeNotImportantSetToType3)
// DESCRIPTION : Create the Attribute Group Results from the Attribute Group Definition.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// link module definition
valAttrGroup_ptr->SetDefAttributeGroup(defAttrGroup_ptr);
if (defAttrGroup_ptr == NULL) return;
defAttrGroup_ptr->SortAttributes();
// handle all the attribute in the group
for (int i = 0; i < defAttrGroup_ptr->GetNrAttributes(); i++)
{
VAL_ATTRIBUTE_CLASS *valAttr_ptr;
if (resultsTypeM == RESULTS_QR)
{
valAttr_ptr = new VAL_QR_ATTRIBUTE_CLASS();
}
else
{
valAttr_ptr = new VAL_ATTRIBUTE_CLASS();
}
// link to parent
valAttr_ptr->SetParent(valAttrGroup_ptr);
// set the textual condition usage
valAttr_ptr->SetUseConditionalTextDuringValidation(useTextualCondition);
// create the attribute results from the attribute definition
CreateAttributeResultsFromDef(defAttrGroup_ptr->GetAttribute(i),
dcmAttrGroup_ptr,
valAttr_ptr,
useTextualCondition,
attributeTypeNotImportantSetToType3);
// link to attribute group
valAttrGroup_ptr->AddValAttribute(valAttr_ptr);
}
// handle any macros in the group
for (int i = 0; i < defAttrGroup_ptr->GetNrMacros(); i++)
{
bool addMacro = false;
bool useMacroTextualCondition = false;
DEF_MACRO_CLASS* defMacro_ptr = defAttrGroup_ptr->GetMacro(i);
CONDITION_CLASS* macroCondition_ptr = defAttrGroup_ptr->GetMacroCondition(i);
if (macroCondition_ptr == NULL)
{
// check if a textual condition is defined
useMacroTextualCondition = (defAttrGroup_ptr->GetMacroTextualCondition(i).length() > 0 ? true : false);
// There's no condition for this macro, so we'll need to add
// the attributes of the macro to the results structure.
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "No Macro Condition for \"%s\" - defaulting to TRUE", defMacro_ptr->GetName().c_str());
}
addMacro = true;
}
else
{
// macroCondition_ptr->Log(loggerM_ptr);
CONDITION_RESULT_ENUM conditionResult = macroCondition_ptr->Evaluate(dcmAttrGroup_ptr, NULL, loggerM_ptr);
switch(conditionResult)
{
case CONDITION_TRUE:
// the macro must be included - leave attribute types as defined
addMacro = true;
attributeTypeNotImportantSetToType3 = false; // not sure if this is correct - should it keep the value from the caller ?
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Macro - Condition for \"%s\" is TRUE", defMacro_ptr->GetName().c_str());
}
break;
case CONDITION_UNIMPORTANT:
// the macro should be added but all attributes in the macro can be set to Type 3
// - their presence is not important to the final validation result.
addMacro = true;
attributeTypeNotImportantSetToType3 = true;
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Macro - Condition for \"%s\" is UNIMPORTANT", defMacro_ptr->GetName().c_str());
}
break;
case CONDITION_FALSE:
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Macro - Condition for \"%s\" is not FALSE", defMacro_ptr->GetName().c_str());
}
break;
case CONDITION_TRUE_REQUIRES_MANUAL_INTERPRETATION:
default:
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Macro - Condition for \"%s\" is not supported", defMacro_ptr->GetName().c_str());
}
break;
}
}
if (addMacro)
{
// create the macro results from the macro definition
CreateMacroResultsFromDef(defMacro_ptr,
dcmAttrGroup_ptr,
valAttrGroup_ptr,
useMacroTextualCondition,
attributeTypeNotImportantSetToType3);
}
}
}
//>>===========================================================================
void VALIDATOR_CLASS::CreateSQResultsFromDef(VALUE_SQ_CLASS *defValueSq_ptr,
DCM_VALUE_SQ_CLASS *dcmSqValue_ptr,
VAL_VALUE_SQ_CLASS *valSqValue_ptr,
bool useTextualCondition,
bool attributeTypeNotImportantSetToType3)
// DESCRIPTION : Create the Sequence Results from the Sequence Definition.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
if (dcmSqValue_ptr == NULL) return;
// handle all the items in the sequence
for (int i = 0; i < dcmSqValue_ptr->GetNrItems(); i++)
{
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "CreateSQResultsFromDef for Item (%d of %d)", i+1, dcmSqValue_ptr->GetNrItems());
}
VAL_ATTRIBUTE_GROUP_CLASS *valItem_ptr = new VAL_ATTRIBUTE_GROUP_CLASS();
// link to parent
valItem_ptr->SetParentSQ(valSqValue_ptr);
// get the item definition - only one item is defined so we use it over all the dcmSqValue_ptr items
ATTRIBUTE_GROUP_CLASS *item_ptr;
defValueSq_ptr->Get(&item_ptr);
#ifdef NDEBUG
DEF_ATTRIBUTE_GROUP_CLASS *defAttrGroup_ptr = static_cast<DEF_ATTRIBUTE_GROUP_CLASS*>(item_ptr);
#else
DEF_ATTRIBUTE_GROUP_CLASS *defAttrGroup_ptr = dynamic_cast<DEF_ATTRIBUTE_GROUP_CLASS*>(item_ptr);
#endif
// create the item results from the item definition
CreateAttributeGroupResultsFromDef(defAttrGroup_ptr,
dcmSqValue_ptr->getItem(i),
valItem_ptr,
useTextualCondition,
attributeTypeNotImportantSetToType3);
// add to parent
valSqValue_ptr->AddValItem(valItem_ptr);
}
}
//>>===========================================================================
void VALIDATOR_CLASS::CreateMacroResultsFromDef(DEF_MACRO_CLASS *defMacro_ptr,
DCM_ATTRIBUTE_GROUP_CLASS *dcmAttrGroup_ptr,
VAL_ATTRIBUTE_GROUP_CLASS *valAttrGroup_ptr,
bool useTextualCondition,
bool attributeTypeNotImportantSetToType3)
// DESCRIPTION : Create the Marco Results from the Macro Definition.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "CreateMacroResultsFromDef");
}
// handle all attributes in macro
for (int i = 0; i < defMacro_ptr->GetNrAttributes(); i++)
{
DEF_ATTRIBUTE_CLASS *defAttr_ptr = defMacro_ptr->GetAttribute(i);
// check if the definition attribute is already in the validation attribute group or not
VAL_ATTRIBUTE_CLASS *valAttr_ptr = valAttrGroup_ptr->GetAttribute(defAttr_ptr->GetGroup(),
defAttr_ptr->GetElement());
if (valAttr_ptr != NULL)
{
// the attribute is already in the validation attribute group
// update the contents of the attribute - if necessary
valAttr_ptr->SetUseConditionalTextDuringValidation(useTextualCondition);
}
else
{
if (resultsTypeM == RESULTS_QR)
{
valAttr_ptr = new VAL_QR_ATTRIBUTE_CLASS();
}
else
{
valAttr_ptr = new VAL_ATTRIBUTE_CLASS();
}
// link parent
valAttr_ptr->SetParent(valAttrGroup_ptr);
// create the attribute results from the attribute definition
CreateAttributeResultsFromDef(defAttr_ptr,
dcmAttrGroup_ptr,
valAttr_ptr,
useTextualCondition,
attributeTypeNotImportantSetToType3);
// set the textual condition usage
valAttr_ptr->SetUseConditionalTextDuringValidation(useTextualCondition);
// add to parent
valAttrGroup_ptr->AddValAttribute(valAttr_ptr);
}
}
// handle all macros in macro
for (int i = 0; i < defMacro_ptr->GetNrMacros(); i++)
{
bool addMacro = false;
bool useMacroTextualCondition = false;
CONDITION_CLASS* macroCondition_ptr = defMacro_ptr->GetMacroCondition(i);
if (macroCondition_ptr == NULL)
{
// check if a textual condition is defined
useMacroTextualCondition = (defMacro_ptr->GetMacroTextualCondition(i).length() > 0 ? true : false);
// there's no condition for this macro, so we'll need to add
// the attributes of the macro to the results structure.
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Macro in Macro - No Macro Condition for \"%s\" - defaulting to TRUE", defMacro_ptr->GetName().c_str());
}
addMacro = true;
}
else
{
// macroCondition_ptr->Log(loggerM_ptr);
CONDITION_RESULT_ENUM conditionResult = macroCondition_ptr->Evaluate(dcmAttrGroup_ptr, NULL, loggerM_ptr);
switch(conditionResult)
{
case CONDITION_TRUE:
// the macro must be included - leave attribute types as defined
addMacro = true;
attributeTypeNotImportantSetToType3 = false; // not sure if this is correct - should it keep the value from the caller ?
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Macro in Macro - Condition for \"%s\" is TRUE", defMacro_ptr->GetName().c_str());
}
break;
case CONDITION_UNIMPORTANT:
// the macro should be added but all attributes in the macro can be set to Type 3
// - their presence is not important to the final validation result.
addMacro = true;
attributeTypeNotImportantSetToType3 = true;
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Macro in Macro - Condition for \"%s\" is UNIMPORTANT", defMacro_ptr->GetName().c_str());
}
break;
case CONDITION_FALSE:
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Macro in Macro - Condition for \"%s\" is not FALSE", defMacro_ptr->GetName().c_str());
}
break;
case CONDITION_TRUE_REQUIRES_MANUAL_INTERPRETATION:
default:
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "Conditional Macro in Macro - Condition for \"%s\" is not supported", defMacro_ptr->GetName().c_str());
}
break;
}
}
if (addMacro)
{
// create the macro results from the macro definition
CreateMacroResultsFromDef(defMacro_ptr->GetMacro(i),
dcmAttrGroup_ptr,
valAttrGroup_ptr,
useMacroTextualCondition,
attributeTypeNotImportantSetToType3);
}
}
}
//>>===========================================================================
void VALIDATOR_CLASS::CreateAttributeResultsFromDef(DEF_ATTRIBUTE_CLASS *defAttr_ptr,
DCM_ATTRIBUTE_GROUP_CLASS *dcmAttrGroup_ptr,
VAL_ATTRIBUTE_CLASS *valAttr_ptr,
bool useTextualCondition,
bool attributeTypeNotImportantSetToType3)
// DESCRIPTION : Create the Attribute Results from Attribute Definition.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// set the attribute definition
valAttr_ptr->SetDefAttribute(defAttr_ptr, attributeTypeNotImportantSetToType3);
if (defAttr_ptr->GetVR() == ATTR_VR_SQ)
{
// TODO: Is it possible to have a list of SQ attributes?
// if so, loop over the number of values in the dicom attribute group.
#ifdef NDEBUG
VALUE_SQ_CLASS *defSqValue_ptr = static_cast<VALUE_SQ_CLASS*>(defAttr_ptr->GetValue());
#else
VALUE_SQ_CLASS *defSqValue_ptr = dynamic_cast<VALUE_SQ_CLASS*>(defAttr_ptr->GetValue());
#endif
VAL_VALUE_SQ_CLASS *valSqValue_ptr = new VAL_VALUE_SQ_CLASS();
// link parent
valSqValue_ptr->SetParent(valAttr_ptr);
// set definition value list
valSqValue_ptr->SetDefValueList(defAttr_ptr->GetValueList());
// get the Dicom attribute, if available. If no attribute is
// available, we don't build a new SQ attribute results object.
DCM_ATTRIBUTE_CLASS *dcmAttr_ptr = dcmAttrGroup_ptr->GetMappedAttribute(defAttr_ptr->GetGroup(),
defAttr_ptr->GetElement());
if (dcmAttr_ptr != NULL)
{
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "CreateAttributeResultsFromDef for SQ Attribute (%04X,%04X)", defAttr_ptr->GetGroup(), defAttr_ptr->GetElement());
}
// Check if the dcm attribute has any values. If none available,
// don't build the value results.
if (dcmAttr_ptr->GetNrValues() > 0)
{
#ifdef NDEBUG
DCM_VALUE_SQ_CLASS *dcmSqValue_ptr = static_cast<DCM_VALUE_SQ_CLASS*>(dcmAttr_ptr->GetValue());
#else
DCM_VALUE_SQ_CLASS *dcmSqValue_ptr = dynamic_cast<DCM_VALUE_SQ_CLASS*>(dcmAttr_ptr->GetValue());
#endif
// create the sequence results from the sequence definition
CreateSQResultsFromDef(defSqValue_ptr,
dcmSqValue_ptr,
valSqValue_ptr,
useTextualCondition,
attributeTypeNotImportantSetToType3);
}
}
// add to parent
valAttr_ptr->AddValValue(valSqValue_ptr);
}
else
{
if (loggerM_ptr)
{
loggerM_ptr->text(LOG_DEBUG, 1, "CreateAttributeResultsFromDef for Attribute (%04X,%04X)", defAttr_ptr->GetGroup(), defAttr_ptr->GetElement());
}
// create the value results from the value definition
CreateValueResultsFromDef(defAttr_ptr,
valAttr_ptr);
}
}
//>>===========================================================================
void VALIDATOR_CLASS::CreateValueResultsFromDef(DEF_ATTRIBUTE_CLASS *defAttr_ptr,
VAL_ATTRIBUTE_CLASS *valAttr_ptr)
// DESCRIPTION : Create the value results from the value definition.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// handle all the value definitions
for (int i = 0; i < defAttr_ptr->GetNrLists(); i++)
{
VAL_BASE_VALUE_CLASS *valValue_ptr = new VAL_BASE_VALUE_CLASS();
// link parent
valValue_ptr->SetParent(valAttr_ptr);
// set the value definitions
valValue_ptr->SetDefValueList(defAttr_ptr->GetValueList(i));
// add to parent
valAttr_ptr->AddValValue(valValue_ptr);
}
}
//>>===========================================================================
void VALIDATOR_CLASS::CheckIfAnyModulesShouldBeIgnored()
// DESCRIPTION : Check to see if any of the modules in the results object
// : should be ignored.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES : A module will be ignored if it is a conditional or user
// : optional module that only contains one attribute that is
// : already found in another module. This is our best guess
// : as to whether the module should be included or not.
//<<===========================================================================
{
if (objectResultsM_ptr == NULL) return;
// outer loop over all modules
for (int i = 0; i < objectResultsM_ptr->GetNrModuleResults(); i++)
{
VAL_ATTRIBUTE_GROUP_CLASS *outerLoopModule_ptr = objectResultsM_ptr->GetModuleResults(i);
// inner loop over all modules
for (int j = 0; j < objectResultsM_ptr->GetNrModuleResults(); j++)
{
// avoid checking against yourself
if (i != j)
{
VAL_ATTRIBUTE_GROUP_CLASS *innerLoopModule_ptr = objectResultsM_ptr->GetModuleResults(j);
// if a single matching attribute is defined in the outer loop module
// and not in the inner loop module - see if the single matching attribute is
// defined in the inner module. If so ignore the outer loop module.
UINT32 singleMatchingAttribute = outerLoopModule_ptr->GetSingleMatchingAttribute();
if ((singleMatchingAttribute > 0) &&
(singleMatchingAttribute != innerLoopModule_ptr->GetSingleMatchingAttribute()))
{
if (innerLoopModule_ptr->GetDefAttributeByTag(singleMatchingAttribute) != NULL)
{
// ignore the outer loop module
outerLoopModule_ptr->SetIgnoreThisAttributeGroup(true);
}
}
}
}
}
}
//>>===========================================================================
void VALIDATOR_CLASS::SetModuleResultsFromDcm(DCM_ATTRIBUTE_GROUP_CLASS *dcmAttrGroup_ptr,
bool setSourceObjectNotRefObject, bool isCommandSet)
// DESCRIPTION : Set the module results from the source/reference dcm object.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// check if results already exist
if (objectResultsM_ptr == NULL)
{
// create new results
objectResultsM_ptr = new VAL_OBJECT_RESULTS_CLASS();
resultsTypeM = RESULTS_OBJECT;
}
// Set has reference object flag
if (setSourceObjectNotRefObject == false)
{
objectResultsM_ptr->HasReferenceObject(true);
}
// The following loop sets the dcm attribute group to all modules that
// have not yet been assigned a dcm attribute group.
// What really should be done here is to assign the dcm
// attribute group to only those modules that have the same attributes
// in the def attribute group.
for (int i = 0; i < objectResultsM_ptr->GetNrModuleResults(); i++)
{
VAL_ATTRIBUTE_GROUP_CLASS *valAttrGroup_ptr = objectResultsM_ptr->GetModuleResults(i);
// check if dcm object is a source object or reference object
if (setSourceObjectNotRefObject)
{
if (valAttrGroup_ptr->GetDcmAttributeGroup() == NULL)
{
valAttrGroup_ptr->SetDcmAttributeGroup(dcmAttrGroup_ptr);
}
}
else
{
if (valAttrGroup_ptr->GetRefAttributeGroup() == NULL)
{
valAttrGroup_ptr->SetRefAttributeGroup(dcmAttrGroup_ptr);
}
}
}
// Iterate over the DCM object itself - handle each attribute in turn
for (int i = 0; i < dcmAttrGroup_ptr->GetNrAttributes(); i++)
{
DCM_ATTRIBUTE_CLASS *dcmAttr_ptr = dcmAttrGroup_ptr->GetAttribute(i);
UINT16 group = dcmAttr_ptr->GetMappedGroup();
UINT16 element = dcmAttr_ptr->GetMappedElement();
VAL_ATTRIBUTE_CLASS *valAttr_ptr = NULL;
bool isAdditionalAttr = false;
vector<VAL_ATTRIBUTE_CLASS*> valAttrList;
valAttrList.clear();
if (objectResultsM_ptr->GetListOfAttributeResults(group, element, &valAttrList))
{
for (UINT i = 0; i < valAttrList.size(); i++)
{
valAttr_ptr = valAttrList[i];
if (setSourceObjectNotRefObject)
{
// set a dcm attribute as the source
valAttr_ptr->SetDcmAttribute(dcmAttr_ptr);
}
else
{
// set the dcm attribute as the reference
valAttr_ptr->SetRefAttribute(dcmAttr_ptr);
}
// check for a SQ attribute - need to handle the enclosed items if present
if (dcmAttr_ptr->GetVR() == ATTR_VR_SQ)
{
// handle the SQ attribute value
SetSQResultsFromDcm(dcmAttr_ptr, valAttr_ptr, setSourceObjectNotRefObject);
}
else
{
// handle the other attribute values
SetValueResultsFromDcm(dcmAttr_ptr, valAttr_ptr, setSourceObjectNotRefObject);
}
}
}
else
{
// No attribute is found. Maybe this is a special attribute?
valAttr_ptr = objectResultsM_ptr->GetAttributeResults(group, element);
if (valAttr_ptr == NULL)
{
// Is the attribute located in a repeating group, and is not a private attribute?
if ((((group & REPEATING_GROUP_MASK) == REPEATING_GROUP_5000) ||
((group & REPEATING_GROUP_MASK) == REPEATING_GROUP_6000)) &&
((group != REPEATING_GROUP_5000) &&
(group != REPEATING_GROUP_6000)))
{
VAL_ATTRIBUTE_GROUP_CLASS *valAttrGroup_ptr = objectResultsM_ptr->GetAGWithAttributeInGroup(group);
if (valAttrGroup_ptr != NULL)
{
valAttr_ptr = valAttrGroup_ptr->GetAttribute(group & REPEATING_GROUP_MASK, element);
if (valAttr_ptr == NULL)
{
// The attribute is not known in the object results structure
// Add a new validation attribute to an additional attribute
// results structure
if (resultsTypeM == RESULTS_QR)
{
valAttr_ptr = new VAL_QR_ATTRIBUTE_CLASS();
}
else
{
valAttr_ptr = new VAL_ATTRIBUTE_CLASS();
}
// Link Attribute into the Group
valAttr_ptr->SetParent(valAttrGroup_ptr);
valAttrGroup_ptr->AddValAttribute(valAttr_ptr);
}
// Try to get a definition for the attribute
DEF_ATTRIBUTE_CLASS *defAttr_ptr = DEFINITION->GetAttribute(group & REPEATING_GROUP_MASK, element);
valAttr_ptr->SetDefAttribute(defAttr_ptr, false);
}
else
{
// The repeating group is not in the results structure,
// create a duplicate results group using the base
// def attribute and the parent module of that def
// attribute.
VAL_ATTRIBUTE_CLASS *repeatAttrResults_ptr = objectResultsM_ptr->GetAttributeResults(group & REPEATING_GROUP_MASK, element);
if (repeatAttrResults_ptr != NULL)
{
DEF_ATTRIBUTE_GROUP_CLASS *defModule_ptr = repeatAttrResults_ptr->GetParent()->GetDefAttributeGroup();
VAL_ATTRIBUTE_GROUP_CLASS *moduleResults_ptr = new VAL_ATTRIBUTE_GROUP_CLASS();
moduleResults_ptr->SetParentObject(objectResultsM_ptr);
if (setSourceObjectNotRefObject)
{
moduleResults_ptr->SetDcmAttributeGroup(dcmAttrGroup_ptr);
}
else // ref_results
{
moduleResults_ptr->SetRefAttributeGroup(dcmAttrGroup_ptr);
}
CreateAttributeGroupResultsFromDef(defModule_ptr, dcmAttrGroup_ptr, moduleResults_ptr, false, false);
objectResultsM_ptr->AddModuleResults(moduleResults_ptr);
valAttr_ptr = moduleResults_ptr->GetAttribute(group & REPEATING_GROUP_MASK, element);
}
}
}
}
if ((valAttr_ptr == NULL) &&
!((element == 0x0000) && // Don't add group length attributes,
(group != 0x0000) && (group != 0x0002) // except for group 0000 and 0002
)
)
{
isAdditionalAttr = true;
// The attribute is not known in the object results structure
// Add a new validation attribute to an additional attribute
// results structure
if (resultsTypeM == RESULTS_QR)
{
valAttr_ptr = new VAL_QR_ATTRIBUTE_CLASS();
}
else
{
valAttr_ptr = new VAL_ATTRIBUTE_CLASS();
}
// Try to get a definition for the attribute
DEF_ATTRIBUTE_CLASS *defAttr_ptr = NULL;
if ((defDatasetM_ptr) &&
(dcmAttr_ptr->GetVR() == ATTR_VR_SQ))
{
// If the attribute is a sequence then we need to try to find the full definition of
// the sequence in the dataset definition (as a sequence contains nested items, etc)
defAttr_ptr = defDatasetM_ptr->GetAttribute(group, element);
}
else if (dcmAttr_ptr->GetVR() != ATTR_VR_SQ)
{
// Try to get the definition of the attribute from the registered attributes list
// - but only if not a sequence as the sequence definition will not be correct
defAttr_ptr = DEFINITION->GetAttribute(group, element);
}
valAttr_ptr->SetDefAttribute(defAttr_ptr, false);
}
if (valAttr_ptr != NULL)
{
if (setSourceObjectNotRefObject)
{
valAttr_ptr->SetDcmAttribute(dcmAttr_ptr);
}
else
{
valAttr_ptr->SetRefAttribute(dcmAttr_ptr);
}
if (dcmAttr_ptr->GetVR() == ATTR_VR_SQ)
{
SetSQResultsFromDcm(dcmAttr_ptr, valAttr_ptr, setSourceObjectNotRefObject);
}
else
{
SetValueResultsFromDcm(dcmAttr_ptr, valAttr_ptr, setSourceObjectNotRefObject);
}
}
if (isAdditionalAttr)
{
// Get the Additional Attribute Group
VAL_ATTRIBUTE_GROUP_CLASS *valAdditionalAttrGroup_ptr = objectResultsM_ptr->GetAdditionalAttributeGroup();
if (isCommandSet)
valAttr_ptr->GetMessages()->AddMessage(VAL_RULE_DEF_COMMAND_3, "Additional attribute is present in command set");
// Link Additional Attribute into the Group
valAttr_ptr->SetParent(valAdditionalAttrGroup_ptr);
valAdditionalAttrGroup_ptr->AddValAttribute(valAttr_ptr);
}
}
}
}
//>>===========================================================================
void VALIDATOR_CLASS::SetAttributeGroupResultsFromDcm(DCM_ATTRIBUTE_GROUP_CLASS *dcmAttrGroup_ptr,
VAL_ATTRIBUTE_GROUP_CLASS *valAttrGroup_ptr,
bool setSourceObjectNotRefObject)
// DESCRIPTION : Set the Attribute Group results from the Dcm object.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
if (setSourceObjectNotRefObject)
{
valAttrGroup_ptr->SetDcmAttributeGroup(dcmAttrGroup_ptr);
}
else
{
valAttrGroup_ptr->SetRefAttributeGroup(dcmAttrGroup_ptr);
}
for (int i = 0; i < dcmAttrGroup_ptr->GetNrAttributes(); i++)
{
DCM_ATTRIBUTE_CLASS *dcmAttr_ptr = dcmAttrGroup_ptr->GetAttribute(i);
VAL_ATTRIBUTE_CLASS *valAttr_ptr = valAttrGroup_ptr->GetAttribute(dcmAttr_ptr->GetMappedGroup(), dcmAttr_ptr->GetMappedElement());
if (valAttr_ptr == NULL)
{
// The attribute is not known in the object results structure
// Add a new validation attribute to the results structure.
if (resultsTypeM == RESULTS_QR)
{
valAttr_ptr = new VAL_QR_ATTRIBUTE_CLASS();
}
else
{
valAttr_ptr = new VAL_ATTRIBUTE_CLASS();
}
valAttr_ptr->SetParent(valAttrGroup_ptr);
valAttrGroup_ptr->AddValAttribute(valAttr_ptr);
}
if (setSourceObjectNotRefObject)
{
valAttr_ptr->SetDcmAttribute(dcmAttr_ptr);
}
else
{
valAttr_ptr->SetRefAttribute(dcmAttr_ptr);
}
if (dcmAttr_ptr->GetVR() == ATTR_VR_SQ)
{
SetSQResultsFromDcm(dcmAttr_ptr, valAttr_ptr, setSourceObjectNotRefObject);
}
else
{
SetValueResultsFromDcm(dcmAttr_ptr, valAttr_ptr, setSourceObjectNotRefObject);
}
}
}
//>>===========================================================================
void VALIDATOR_CLASS::SetSQResultsFromDcm(DCM_ATTRIBUTE_CLASS *dcmAttr_ptr,
VAL_ATTRIBUTE_CLASS *valAttr_ptr,
bool setSourceObjectNotRefObject)
// DESCRIPTION : Set the SQ results from the DCM attribute.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
DCM_VALUE_SQ_CLASS *dcmSqValue_ptr = NULL;
if (dcmAttr_ptr->GetNrValues() != 0)
{
#ifdef NDEBUG
dcmSqValue_ptr = static_cast<DCM_VALUE_SQ_CLASS *>(dcmAttr_ptr->GetValue());
#else
dcmSqValue_ptr = dynamic_cast<DCM_VALUE_SQ_CLASS *>(dcmAttr_ptr->GetValue());
#endif
}
if (dcmSqValue_ptr == NULL)
{
// This is apparently an empty sequence. The validation value has
// been created, so the results structure maps correctly to the
// incoming data stream, but we can't build any items since we
// have no data to refer to.
return;
}
VAL_VALUE_SQ_CLASS *valSqValue_ptr = NULL;
bool useTextualCondition = valAttr_ptr->GetUseConditionalTextDuringValidation();
if (valAttr_ptr->GetNrValues() == 0)
{
// No value allocation for items has been made yet.
valSqValue_ptr = new VAL_VALUE_SQ_CLASS();
valSqValue_ptr->SetParent(valAttr_ptr);
valAttr_ptr->AddValValue(valSqValue_ptr);
}
else
{
#ifdef NDEBUG
valSqValue_ptr = static_cast<VAL_VALUE_SQ_CLASS *>(valAttr_ptr->GetValue(0));
#else
valSqValue_ptr = dynamic_cast<VAL_VALUE_SQ_CLASS *>(valAttr_ptr->GetValue(0));
#endif
}
// check that we have a val_value
if (valSqValue_ptr == NULL) return;
ATTRIBUTE_GROUP_CLASS *attrGroup = NULL;
DEF_ATTRIBUTE_CLASS *defAttr_ptr = valAttr_ptr->GetDefAttribute();
if (defAttr_ptr != NULL)
{
// We assume that an attribute in the definition component always
// contains exactly 1 item.
#ifdef NDEBUG
VALUE_SQ_CLASS *sqValue_ptr = static_cast<VALUE_SQ_CLASS*>(defAttr_ptr->GetValue());
#else
VALUE_SQ_CLASS *sqValue_ptr = dynamic_cast<VALUE_SQ_CLASS*>(defAttr_ptr->GetValue());
#endif
if (sqValue_ptr != NULL)
{
sqValue_ptr->Get(&attrGroup);
}
}
// We need to create a new validation item results for each
// item present in the dcm/ref attribute.
// By default, 1 item will be present in the validation results - since
// that was the assumption we made while building the results structure
// with the definition attributes.
for (int i = 0; i < dcmSqValue_ptr->GetNrItems(); i++)
{
VAL_ATTRIBUTE_GROUP_CLASS *valItem_ptr = valSqValue_ptr->GetValItem(i);
if (valItem_ptr == NULL)
{
// There's at least 1 more item in the dcm attribute than in the
// validation attribute. We need to create a new validation item
// and copy the definition item to that validation item before
// we can fill the results structure with the dcm/ref attributes.
valItem_ptr = new VAL_ATTRIBUTE_GROUP_CLASS();
valSqValue_ptr->AddValItem(valItem_ptr);
if (attrGroup != NULL)
{
// Fill the new item with the definition attributes.
#ifdef NDEBUG
DEF_ITEM_CLASS *defItem_ptr = static_cast<DEF_ITEM_CLASS*>(attrGroup);
#else
DEF_ITEM_CLASS *defItem_ptr = dynamic_cast<DEF_ITEM_CLASS*>(attrGroup);
#endif
CreateAttributeGroupResultsFromDef(defItem_ptr,
dcmSqValue_ptr->getItem(i),
valItem_ptr,
useTextualCondition,
false);
}
}
valItem_ptr->SetParentSQ(valSqValue_ptr);
SetAttributeGroupResultsFromDcm(dcmSqValue_ptr->getItem(i), valItem_ptr, setSourceObjectNotRefObject);
}
if (setSourceObjectNotRefObject)
{
valSqValue_ptr->SetDcmValue(dcmSqValue_ptr);
}
else
{
valSqValue_ptr->SetRefValue(dcmSqValue_ptr);
}
}
//>>===========================================================================
void VALIDATOR_CLASS::SetValueResultsFromDcm(DCM_ATTRIBUTE_CLASS *dcmAttr_ptr,
VAL_ATTRIBUTE_CLASS *valAttr_ptr,
bool setSourceObjectNotRefObject)
// DESCRIPTION : Set the attribute Value results from the DCM attribute.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
for (int i = 0; i < dcmAttr_ptr->GetNrValues(); i++)
{
VAL_BASE_VALUE_CLASS *valValue_ptr;
if (i < valAttr_ptr->GetNrValues())
{
valValue_ptr = valAttr_ptr->GetValue(i);
}
else
{
valValue_ptr = new VAL_BASE_VALUE_CLASS();
valValue_ptr->SetParent(valAttr_ptr);
valAttr_ptr->AddValValue(valValue_ptr);
}
if (setSourceObjectNotRefObject)
{
valValue_ptr->SetDcmValue(dcmAttr_ptr->GetValue(i));
}
else
{
valValue_ptr->SetRefValue(dcmAttr_ptr->GetValue(i));
}
}
}
//>>===========================================================================
void VALIDATOR_CLASS::ValidateResults(VALIDATION_CONTROL_FLAG_ENUM validationFlag)
// DESCRIPTION : Validates the data present in the object results
// structure.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// validate according to the current validation flag settings
// - validate against the definition
if (validationFlag & USE_DEFINITION)
{
objectResultsM_ptr->ValidateAgainstDef(flagsM);
}
// - validate the vr
if (validationFlag & USE_VR)
{
objectResultsM_ptr->ValidateVR(flagsM, specificCharacterSetM_ptr);
}
// - validate against the reference
if (validationFlag & USE_REFERENCE)
{
objectResultsM_ptr->ValidateAgainstRef(flagsM);
}
}
//>>===========================================================================
void VALIDATOR_CLASS::Serialize(BASE_SERIALIZER *serializer_ptr)
// DESCRIPTION : Serialize the validation results.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// serialize the object results
if (serializer_ptr)
{
serializer_ptr->SerializeValidate(objectResultsM_ptr, flagsM);
}
}
//>>===========================================================================
void VALIDATOR_CLASS::LogSystemDefinitions()
// DESCRIPTION : Log the system definitions.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
LOG_MESSAGE_CLASS *messages_ptr = objectResultsM_ptr->GetMessages();
messages_ptr->AddMessage (VAL_RULE_DEF_DEFINITION_1, "No Dataset definition found - no validation done");
string names[MAX_APPLICATION_ENTITY];
string versions[MAX_APPLICATION_ENTITY];
DEFINITION->GetSystemDefinitions(names, versions);
string msg;
int index = 0;
while (names[index] != "")
{
msg = "Name: \"" + names[index] + "\" Version: \"" + versions[index] + "\"";
messages_ptr->AddMessage(VAL_RULE_DEF_DEFINITION_2, msg);
index++;
}
}
//>>===========================================================================
bool VALIDATOR_CLASS::UpdateDatasetResultsFromLastSent(DCM_COMMAND_CLASS *command_ptr,
DCM_COMMAND_CLASS *lastSentCommand_ptr,
DCM_DATASET_CLASS *lastSentDataset_ptr)
// DESCRIPTION : Update the Dataset Results from the last command/dataset sent.
// : Example: If the last command/dataset sent was a C-FIND-RQ Identifier
// : then in order to validate the results of the C-FIND-RSP Dataset we should
// : take the Identifer into account.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
if ((command_ptr == NULL) ||
(lastSentCommand_ptr == NULL)) return true;
// Get the command field
UINT16 commandField = 0;
command_ptr->getUSValue(TAG_COMMAND_FIELD, &commandField);
UINT16 lastSentCommandField = 0;
lastSentCommand_ptr->getUSValue(TAG_COMMAND_FIELD, &lastSentCommandField);
bool status = true;
if ((commandField == C_FIND_RSP) &&
(lastSentCommandField == C_FIND_RQ))
{
// we are validating a C-FIND-RSP following a C-FIND-RQ being sent
status = UpdateDatasetResultsFromLastSentDataset(lastSentDataset_ptr);
}
return status;
}
//>>===========================================================================
bool VALIDATOR_CLASS::UpdateDatasetResultsFromLastSentDataset(DCM_DATASET_CLASS *lastSentDataset_ptr)
// DESCRIPTION : Update the Dataset Results from the last dataset sent.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
char message[256];
// check if results already exist
if (objectResultsM_ptr == NULL) return false;
// check if last sent dataset is defined
if (lastSentDataset_ptr == NULL) return false;
bool status = true;
// iterate over the last sent dataset object itself - handle each attribute in turn
for (int i = 0; i < lastSentDataset_ptr->GetNrAttributes(); i++)
{
DCM_ATTRIBUTE_CLASS *dcmAttr_ptr = lastSentDataset_ptr->GetAttribute(i);
UINT16 group = dcmAttr_ptr->GetMappedGroup();
UINT16 element = dcmAttr_ptr->GetMappedElement();
vector<VAL_ATTRIBUTE_CLASS*> valAttrList;
valAttrList.clear();
if (objectResultsM_ptr->GetListOfAttributeResults(group, element, &valAttrList))
{
for (UINT j = 0; j < valAttrList.size(); j++)
{
VAL_ATTRIBUTE_CLASS *valAttr_ptr = valAttrList[j];
DEF_ATTRIBUTE_CLASS *defAttr_ptr = valAttr_ptr->GetDefAttribute();
if (defAttr_ptr != NULL)
{
// check for a SQ attribute - need to handle the enclosed items if present
if (defAttr_ptr->GetVR() == ATTR_VR_SQ)
{
// handle the SQ attribute
VAL_VALUE_SQ_CLASS *valSqValue_ptr = NULL;
#ifdef NDEBUG
valSqValue_ptr = static_cast<VAL_VALUE_SQ_CLASS *>(valAttr_ptr->GetValue(0));
#else
valSqValue_ptr = dynamic_cast<VAL_VALUE_SQ_CLASS *>(valAttr_ptr->GetValue(0));
#endif
DCM_VALUE_SQ_CLASS *sqValue_ptr = NULL;
if (dcmAttr_ptr->GetNrValues())
{
sqValue_ptr = static_cast<DCM_VALUE_SQ_CLASS*>(dcmAttr_ptr->GetValue(0));
}
UpdateSequenceItemsResultsFromLastSentDataset(valSqValue_ptr, sqValue_ptr);
}
else
{
if (dcmAttr_ptr->GetNrValues())
{
BASE_VALUE_CLASS* value_ptr = dcmAttr_ptr->GetValue();
if (value_ptr->GetLength() == 0)
{
if (valAttr_ptr->GetDefAttributeType() == ATTR_TYPE_1C)
{
// Message to user - DVTk cannot determine if this 1C attribute should be present or not - needs further
// manual validation.
LOG_MESSAGE_CLASS *message_ptr = valAttr_ptr->GetMessages();
if (message_ptr != NULL)
{
sprintf(message, "Equivalent attribute (%04X,%04X) in request has zero-length - maybe response attribute. Changing this Attribute Type from %s to Type 2 - requires further manual validation.",
dcmAttr_ptr->GetGroup(),
dcmAttr_ptr->GetElement(),
mapTypeName(valAttr_ptr->GetDefAttributeType()));
message_ptr->AddMessage(VAL_RULE_DEF_DEFINITION_7, message);
}
valAttr_ptr->SetDefAttributeType(ATTR_TYPE_2);
}
}
else
{
if ((valAttr_ptr->GetDefAttributeType() != ATTR_TYPE_1) &&
(valAttr_ptr->GetDefAttributeType() != ATTR_TYPE_1C))
{
LOG_MESSAGE_CLASS *message_ptr = valAttr_ptr->GetMessages();
if (message_ptr != NULL)
{
sprintf(message, "Equivalent attribute (%04X,%04X) in request has value - expecting response attribute. Changing this Attribute Type from %s to Type 1.",
dcmAttr_ptr->GetGroup(),
dcmAttr_ptr->GetElement(),
mapTypeName(valAttr_ptr->GetDefAttributeType()));
message_ptr->AddMessage(VAL_RULE_DEF_DEFINITION_7, message);
}
valAttr_ptr->SetDefAttributeType(ATTR_TYPE_1);
}
}
}
}
}
}
}
}
// Now iterate over the validation results and set any definition attribute which does not
// have a DCM attribute to Type 3. This means that response definition is updated according
// to the requested attributes.
for (int i = 0; i < objectResultsM_ptr->GetNrModuleResults(); i++)
{
VAL_ATTRIBUTE_GROUP_CLASS *valAttrGroup_ptr = objectResultsM_ptr->GetModuleResults(i);
for (int j = 0; j < valAttrGroup_ptr->GetNrAttributes(); j++)
{
VAL_ATTRIBUTE_CLASS *valAttr_ptr = valAttrGroup_ptr->GetAttribute(j);
if ((valAttr_ptr) &&
(valAttr_ptr->GetDcmAttribute() == NULL))
{
valAttr_ptr->SetDefAttributeType(ATTR_TYPE_3);
}
}
}
return status;
}
//>>===========================================================================
bool VALIDATOR_CLASS::UpdateSequenceItemsResultsFromLastSentDataset(VAL_VALUE_SQ_CLASS *valSqValue_ptr, DCM_VALUE_SQ_CLASS *sqValue_ptr)
// DESCRIPTION : Update the Sequence Items Results from the last dataset sent.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
char message[256];
if ((valSqValue_ptr == NULL) ||
(sqValue_ptr == NULL))
{
return false;
}
if (valSqValue_ptr->GetNrValItems() == sqValue_ptr->GetNrItems())
{
// iterate over all the items
for (int i = 0; i < sqValue_ptr->GetNrItems(); i++)
{
DCM_ITEM_CLASS *dcmItem_ptr = sqValue_ptr->getItem(i);
VAL_ATTRIBUTE_GROUP_CLASS *valItem_ptr = valSqValue_ptr->GetValItem(i);
for (int j = 0; j < dcmItem_ptr->GetNrAttributes(); j++)
{
DCM_ATTRIBUTE_CLASS *dcmAttr_ptr = dcmItem_ptr->GetAttribute(j);
if (dcmAttr_ptr)
{
VAL_ATTRIBUTE_CLASS *valAttr_ptr = valItem_ptr->GetAttribute(dcmAttr_ptr->GetMappedGroup(), dcmAttr_ptr->GetMappedElement());
if (valAttr_ptr)
{
if (dcmAttr_ptr->GetNrValues())
{
BASE_VALUE_CLASS* value_ptr = dcmAttr_ptr->GetValue();
if (value_ptr->GetLength() == 0)
{
if (valAttr_ptr->GetDefAttributeType() == ATTR_TYPE_1C)
{
// Message to user - DVTk cannot determine if this 1C attribute should be present or not - needs further
// manual validation.
LOG_MESSAGE_CLASS *message_ptr = valAttr_ptr->GetMessages();
if (message_ptr != NULL)
{
sprintf(message, "Equivalent attribute (%04X,%04X) in request has zero-length - maybe response attribute. Changing this Attribute Type from %s to Type 2 - requires further manual validation.",
dcmAttr_ptr->GetMappedGroup(),
dcmAttr_ptr->GetMappedElement(),
mapTypeName(valAttr_ptr->GetDefAttributeType()));
message_ptr->AddMessage(VAL_RULE_DEF_DEFINITION_7, message);
}
valAttr_ptr->SetDefAttributeType(ATTR_TYPE_2);
}
}
else
{
if ((valAttr_ptr->GetDefAttributeType() != ATTR_TYPE_1) &&
(valAttr_ptr->GetDefAttributeType() != ATTR_TYPE_1C))
{
LOG_MESSAGE_CLASS *message_ptr = valAttr_ptr->GetMessages();
if (message_ptr != NULL)
{
sprintf(message, "Equivalent attribute (%04X,%04X) in request has value - expecting response attribute. Changing this Attribute Type from %s to Type 1.",
dcmAttr_ptr->GetMappedGroup(),
dcmAttr_ptr->GetMappedElement(),
mapTypeName(valAttr_ptr->GetDefAttributeType()));
message_ptr->AddMessage(VAL_RULE_DEF_DEFINITION_7, message);
}
valAttr_ptr->SetDefAttributeType(ATTR_TYPE_1);
}
}
}
}
}
}
}
}
// Now iterate over the validation results and set any definition attribute which does not
// have a DCM attribute to Type 3. This means that response definition is updated according
// to the requested attributes.
// iterate over all the items
for (int i = 0; i < valSqValue_ptr->GetNrValItems(); i++)
{
VAL_ATTRIBUTE_GROUP_CLASS *valItem_ptr = valSqValue_ptr->GetValItem(i);
for (int j = 0; j < valItem_ptr->GetNrAttributes(); j++)
{
VAL_ATTRIBUTE_CLASS *valAttr_ptr = valItem_ptr->GetAttribute(j);
if ((valAttr_ptr) &&
(valAttr_ptr->GetDcmAttribute() == NULL))
{
valAttr_ptr->SetDefAttributeType(ATTR_TYPE_3);
}
}
}
return true;
}
| lgpl-3.0 |
olivergondza/MapFilter_TreePattern | PHP/MapFilter/TreePattern/Tree/Leaf/AliasAttr/Builder.php | 2628 | <?php
/**
* Class to load Pattern tree from xml.
*
* PHP Version 5.1.0
*
* This file is part of MapFilter package.
*
* MapFilter is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* MapFilter is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with MapFilter. If not, see <http://www.gnu.org/licenses/>.
*
* @category Pear
* @package MapFilter_TreePattern
* @author Oliver Gondža <324706@mail.muni.cz>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License
* @link http://github.com/olivergondza/MapFilter
* @since $NEXT$
*/
require_once 'PHP/MapFilter/TreePattern/Tree/Leaf/Attr/Builder.php';
require_once 'PHP/MapFilter/TreePattern/Tree/Leaf/AliasAttr.php';
/**
* Tree All element builder class
*
* @category Pear
* @package MapFilter_TreePattern
* @class MapFilter_TreePattern_Tree_Leaf_AliasAttr_Builder
* @author Oliver Gondža <324706@mail.muni.cz>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License
* @link http://github.com/olivergondza/MapFilter
* @since $NEXT$
*/
class MapFilter_TreePattern_Tree_Leaf_AliasAttr_Builder extends
MapFilter_TreePattern_Tree_Leaf_Attr_Builder
{
/**
* Fluent Method; Set content.
*
* @param Array $content A content to set.
*
* @return MapFilter_TreePattern_Tree_Node
*
* @since $NEXT$
*/
public function setContent(Array $content)
{
foreach ($content as $follower) {
$class = get_class($follower);
if ($class === 'MapFilter_TreePattern_Tree_Key') continue;
throw new MapFilter_TreePattern_Tree_Leaf_AliasAttr_DisallowedFollowerException(
$class
);
}
$this->content = $content;
}
public function setName($name)
{
$this->setAttr($name);
}
/**
* Build tree element
*
* @return MapFilter_TreePattern_Tree_Leaf_AliasAttr Tree Element
*/
public function build()
{
return new MapFilter_TreePattern_Tree_Leaf_AliasAttr($this);
}
}
| lgpl-3.0 |
mikeyoon/FakeItEasyAutoMocker | AutoMocker/MockContainer.cs | 990 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FakeItEasy;
namespace FakeItEasy
{
public class MockContainer<T> where T : class
{
internal MockContainer(T sub, Dictionary<Type, object> fakes)
{
Subject = sub;
this.fakes = fakes;
}
Dictionary<Type, object> fakes;
/// <summary>
/// The concrete class that is under test
/// </summary>
public T Subject
{
get;
private set;
}
/// <summary>
/// Retrieves the faked instance of a dependency for setups
/// </summary>
/// <typeparam name="U"></typeparam>
/// <returns></returns>
public U GetMock<U>() where U : class
{
if (fakes.ContainsKey(typeof(U)))
return fakes[typeof(U)] as U;
return default(U);
}
}
}
| lgpl-3.0 |
skltp-incubator/nt | modules/intsvc/src/test/java/se/skltp/nt/intsvc/EndToEndIntegrationTest.java | 6940 | /**
* Copyright (c) 2013 Sveriges Kommuner och Landsting (SKL). <http://www.skl.se/>
*
* This file is part of SKLTP.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package se.skltp.nt.intsvc;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soitoolkit.commons.mule.test.Dispatcher;
import se.rivta.itintegration.engagementindex.ProcessNotificationResponder.v1.rivtabp21.ProcessNotificationType;
import se.rivta.itintegration.notification.ReceiveNotificationResponder.v1.rivtabp21.ReceiveNotificationType;
import se.skltp.nt.NtMuleServer;
import se.skltp.nt.intsvc.ReceiveNotificationTestProducer.ReceiveData;
import static org.junit.Assert.assertEquals;
public class EndToEndIntegrationTest extends AbstractTestCase implements MessageListener {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(EndToEndIntegrationTest.class);
private static final long SERVICE_TIMOUT_MS = Long.parseLong(rb.get("SERVICE_TIMEOUT_MS"));
private static final String LOGICAL_ADDRESS = rb.get("NT_SERVICECONSUMER_HSAID");
@SuppressWarnings("unused")
private static final String EXPECTED_ERR_TIMEOUT_MSG = "Read timed out";
private static final String RECEIVE_ADDRESS = NtMuleServer.getAddress("NOTIFY_TEST_OUTBOUND_URL");
private static final String PROCESS_ADDRESS = NtMuleServer.getAddress("PROCESS_TEST_OUTBOUND_URL");
private TextMessage receiveNotificationMessage = null;
@Override
public void onMessage(Message message) {
receiveNotificationMessage = (TextMessage) message;
}
public EndToEndIntegrationTest() {
// Only start up Mule once to make the tests run faster...
// Set to false if tests interfere with each other when Mule is started only once.
setDisposeContextPerClass(true);
}
protected String getConfigResources() {
return
"soitoolkit-mule-jms-connector-activemq-embedded.xml," +
"nt-common.xml," +
"receive-service.xml," +
"teststub-services/init-dynamic-flows.xml," +
"teststub-services/receive-notification-teststub-service.xml," +
"teststub-services/process-notification-teststub-service.xml";
}
@Before
public void setUp() throws Exception {
// Clear queues used for the tests
getJmsUtil().clearQueues(INFO_LOG_QUEUE, ERROR_LOG_QUEUE);
}
/**
* Verify that a Publisher can send a ReceiveNotification through the system to the Subscribers.
*/
@Test
public void endToEnd_OK() {
final String logicalAddress = LOGICAL_ADDRESS;
final ProcessNotificationType procRequest = createProcessNotificationRequest();
dispatchAndWaitForServiceComponent(new Dispatcher() {
public void doDispatch() {
new ProcessNotificationTestConsumer(PROCESS_ADDRESS).callService(logicalAddress, procRequest);
}
}, "process-notification-teststub-service", EI_TEST_TIMEOUT);
final ReceiveNotificationType[] requests = {
createReceiveNotificationRequest("domain-1", "category-1"),
createReceiveNotificationRequest("domain-1", "category-2"),
createReceiveNotificationRequest("domain-1", ""),
createReceiveNotificationRequest("domain-2", "category-1"),
createReceiveNotificationRequest("domain-2", "category-2"),
createReceiveNotificationRequest("domain-2", ""),
createReceiveNotificationRequest("", ""),
};
for ( final ReceiveNotificationType request : requests ) {
dispatchAndWaitForServiceComponent(new Dispatcher() {
public void doDispatch() {
new ReceiveNotificationTestConsumer(RECEIVE_ADDRESS).callService(logicalAddress, request);
}
}, "receive-notification-teststub-service", EI_TEST_TIMEOUT);
}
// Wait a short while for all background processing to complete
waitForBackgroundProcessing();
// Expect no error logs
assertQueueDepth(ERROR_LOG_QUEUE, 0);
// Expect info entries?
assertQueueDepth(INFO_LOG_QUEUE, 80);
List<ReceiveNotificationTestProducer.ReceiveData> recNotMessages = ReceiveNotificationTestProducer.getReceiveDataList();
Map<String, Integer> recMsgCount = new HashMap<String, Integer>();
assertEquals(21, recNotMessages.size());
for ( ReceiveData data : recNotMessages ) {
Integer count = recMsgCount.get(data.logicalAddress);
count = (count == null ? 1 : count + 1);
recMsgCount.put(data.logicalAddress, count);
}
assertEquals(4, recMsgCount.size());
assertEquals(3, (int) recMsgCount.get("Foo-1")); // gets only domain-1, cat-1 -> 3
assertEquals(4, (int) recMsgCount.get("Foo-2")); // gets only domain-1, any cat -> 4
assertEquals(7, (int) recMsgCount.get("Foo-3")); // gets every message -> 7
assertEquals(7, (int) recMsgCount.get("Foo-4")); // gets all receive notification messages -> 7
List<ProcessNotificationTestProducer.ReceiveData> procNotMessages = ProcessNotificationTestProducer.getReceiveDataList();
Map<String, Integer> procMsgCount = new HashMap<String, Integer>();
assertEquals(3, procNotMessages.size());
for ( ProcessNotificationTestProducer.ReceiveData data : procNotMessages ) {
Integer count = procMsgCount.get(data.logicalAddress);
count = (count == null ? 1 : count + 1);
procMsgCount.put(data.logicalAddress, count);
}
assertEquals(3, procMsgCount.size());
assertEquals(1, (int) procMsgCount.get("Foo-1"));
assertEquals(1, (int) procMsgCount.get("Foo-2"));
assertEquals(1, (int) procMsgCount.get("Foo-3"));
assertEquals(null, procMsgCount.get("Foo-4"));
}
} | lgpl-3.0 |
precice/precice | src/utils/Event.hpp | 2569 | #pragma once
#include <chrono>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "logging/Logger.hpp"
namespace precice {
namespace utils {
/// Represents an event that can be started and stopped.
/** Additionally to the duration there is a special property that can be set for a event.
A property is a a key-value pair with a numerical value that can be used to trace certain events,
like MPI calls in an event. It is intended to be set by the user. */
class Event {
public:
enum class State : int {
STOPPED = 0,
STARTED = 1,
PAUSED = 2,
};
/// Default clock type. All other chrono types are derived from it.
using Clock = std::chrono::steady_clock;
using StateChanges = std::vector<std::pair<State, Clock::time_point>>;
using Data = std::map<std::string, std::vector<int>>;
/// An Event can't be copied.
Event(const Event &other) = delete;
/// Name used to identify the timer. Events of the same name are accumulated to
std::string name;
/// Allows to put a non-measured (i.e. with a given duration) Event to the measurements.
Event(const std::string &eventName, Clock::duration initialDuration);
/// Creates a new event and starts it, unless autostart = false, synchronize processes, when barrier == true
/** Use barrier == true with caution, as it can lead to deadlocks. */
Event(const std::string &eventName, bool barrier = false, bool autostart = true);
/// Stops the event if it's running and report its times to the EventRegistry
~Event();
/// Starts an event. If it's already started it has no effect.
void start(bool barrier = false);
/// Stops an event and commit it. If it's already stopped it has no effect.
void stop(bool barrier = false);
/// Pauses an event, does not commit. If it's already paused it has no effect.
void pause(bool barrier = false);
/// Gets the duration of the event.
Clock::duration getDuration() const;
/// Adds named integer data, associated to an event.
void addData(const std::string &key, int value);
Data data;
StateChanges stateChanges;
private:
logging::Logger _log{"utils::Events"};
Clock::time_point starttime;
Clock::duration duration = Clock::duration::zero();
State state = State::STOPPED;
bool _barrier = false;
};
/// Class that changes the prefix in its scope
class ScopedEventPrefix {
public:
ScopedEventPrefix(const std::string &name);
~ScopedEventPrefix();
private:
std::string previousName = "";
};
} // namespace utils
} // namespace precice
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/mobile/thug/pathfinder.lua | 1058 | pathfinder = Creature:new {
objectName = "",
costumName = "Pathfinder",
socialGroup = "Wilder",
pvpFaction = "",
faction = "",
level = 21,
chanceHit = 0.33,
damageMin = 180,
damageMax = 190,
baseXp = 2006,
baseHAM = 4500,
baseHAMmax = 5500,
armor = 0,
resists = {0,0,0,35,35,35,35,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER + STALKER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {},
lootGroups = {
{
groups = {
{group = "junk", chance = 4000000},
{group = "wearables_common", chance = 3000000},
{group = "loot_kit_parts", chance = 2000000},
{group = "tailor_components", chance = 1000000},
},
lootChance = 3000000
}
},
weapons = {"rebel_weapons_heavy"},
conversationTemplate = "",
attacks = merge(riflemanmaster,pistoleermaster,carbineermaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(pathfinder, "pathfinder") | lgpl-3.0 |
PCMSolver/pcmsolver | src/utils/SplineFunction.hpp | 3028 | /*
* PCMSolver, an API for the Polarizable Continuum Model
* Copyright (C) 2020 Roberto Di Remigio, Luca Frediani and contributors.
*
* This file is part of PCMSolver.
*
* PCMSolver is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PCMSolver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with PCMSolver. If not, see <http://www.gnu.org/licenses/>.
*
* For information on the complete list of contributors to the
* PCMSolver API, see: <http://pcmsolver.readthedocs.io/>
*/
#pragma once
#include <algorithm>
#include "Config.hpp"
#include <Eigen/Core>
#include <unsupported/Eigen/Splines>
/*! \file SplineFunction.hpp
* \class SplineFunction
* \brief Spline interpolation of a function
* \author Roberto Di Remigio
* \date 2015
*
* Taken from StackOverflow http://stackoverflow.com/a/29825204/2528668
*/
class SplineFunction final {
private:
typedef Eigen::Spline<double, 1> CubicSpline;
public:
/*! \brief Constructor from abscissa and function values
* \param[in] x vector with abscissa values
* \param[in] y vector with function values
*
* Interpolation happens in the initialization of the spline_ data
* member. We use std::min to set the degree in order to ensure that no
* more than a cubic spline is used, but short vectors are still accepted.
*/
SplineFunction(const Eigen::VectorXd & x, const Eigen::VectorXd & y)
: xMin_(x.minCoeff()),
xMax_(x.maxCoeff()),
spline_(Eigen::SplineFitting<CubicSpline>::Interpolate(
y.transpose(),
std::min<int>(x.rows() - 1, 3),
fitVector(x))) {}
/*! \brief Evaluate spline at given point
* \param[in] x evaluation point
*/
double operator()(double x) const { return spline_(fitScalar(x))(0); }
private:
double xMin_;
double xMax_;
CubicSpline spline_;
/*! \brief Scale a scalar value to [0, 1] interval
* \param[in] x value to be scaled
*
* val is defined in [min, max] This function returns the variable
* as scaled to fit in the [0, 1] interval.
*/
double fitScalar(double x) const { return (x - xMin_) / (xMax_ - xMin_); }
/*! \brief Scale a vector to [0, 1] interval
* \param[in] x_vec a vector
*
* Given column vector, returns a *row* vector with the values scaled
* to fit a preset interval. The interval is embedded in the callable object.
*/
Eigen::RowVectorXd fitVector(const Eigen::VectorXd & x_vec) const {
return x_vec.unaryExpr([this](double x) -> double { return fitScalar(x); })
.transpose();
}
};
| lgpl-3.0 |
dcoredump/zynthian-stage-ui | pedalpi.py | 2038 | #!/usr/bin/python3
from pluginsmanager.banks_manager import BanksManager
from pluginsmanager.model.bank import Bank
#from pluginsmanager.model.connection import Connection
#from pluginsmanager.model.midi_connection import MidiConnection
#from pluginsmanager.observer.autosaver.autosaver import Autosaver
from pluginsmanager.observer.mod_host.mod_host import ModHost
from pluginsmanager.model.pedalboard import Pedalboard
from pluginsmanager.model.lv2.lv2_effect_builder import Lv2EffectBuilder
from pluginsmanager.model.system.system_effect import SystemEffect
from pluginsmanager.model.system.system_effect_builder import SystemEffectBuilder
from pluginsmanager.jack.jack_client import JackClient
client = JackClient()
jack_system = SystemEffect(
'system',
[], # audio inputs
['playback_1', 'playback_2'], # audio output
['midi_capture_1'], # midi inputs
[] # midi outputs
)
#jack_ttymidi = SystemEffect(
# 'ttymidi',
# [], # audio inputs
# [], # audio output
# ['MIDI_in'], # midi inputs
# ['MIDI_out'] # midi outputs
#)
modhost = ModHost('localhost')
modhost.connect()
#manager = BanksManager()
#manager.register(modhost)
pedalboard = Pedalboard('MDA-EP')
builder = Lv2EffectBuilder()
#builder.reload(builder.lv2_plugins_data())
ep = builder.build('http://moddevices.com/plugins/mda/EPiano')
#ep = builder.build('https://github.com/dcoredump/dexed.lv2')
#ep = builder.build('http://tytel.org/helm')
pedalboard.append(ep)
# REMEMBER: FIRST OUTPUT, SECOND INPUT
# EPiano contains two audio output ports and one midi input port
pedalboard.connect(ep.outputs[0],jack_system.outputs[0])
#pedalboard.connect(ep.outputs[1],jack_system.inputs[1])
#pedalboard.connect(jack_ttymidi.midi_outputs[0],ep.midi_inputs[0])
pedalboard.connect(jack_system.midi_outputs[0],ep.midi_inputs[0])
modhost.pedalboard = pedalboard
print("Running...")
# Safe close
from signal import pause
try:
pause()
except KeyboardInterrupt:
modhost.close()
| lgpl-3.0 |
uniba-dsg/BPELlint | src/main/java/bpellint/core/validators/rules/SA00034Validator.java | 2315 | package bpellint.core.validators.rules;
import api.SimpleValidationResult;
import nu.xom.Node;
import nu.xom.Nodes;
import java.util.List;
import bpellint.core.model.NavigationException;
import bpellint.core.model.NodeHelper;
import bpellint.core.model.NodesUtil;
import bpellint.core.model.ProcessContainer;
import bpellint.core.model.bpel.var.VariableLike;
import static bpellint.core.model.Standards.CONTEXT;
public class SA00034Validator extends Validator {
private static final int VARIABLE_IS_MISSING = 2;
private static final int PART_IS_PROHIBITED_FOR_NON_MESSAGE_TYPES = 1;
public SA00034Validator(ProcessContainer files,
SimpleValidationResult validationCollector) {
super(files, validationCollector);
}
@Override
public void validate() {
List<Node> fromTos = getFroms();
fromTos.addAll(getTos());
checkPartAttributeUsage(fromTos);
}
private List<Node> getTos() {
Nodes toNodes = processContainer.getBpel().getDocument()
.query("//bpel:to[@variable]", CONTEXT);
return NodesUtil.toList(toNodes);
}
private List<Node> getFroms() {
Nodes fromNodes = processContainer.getBpel().getDocument()
.query("//bpel:copy/bpel:from[@variable]", CONTEXT);
return NodesUtil.toList(fromNodes);
}
private void checkPartAttributeUsage(List<Node> fromTos) {
for (Node fromToNode : fromTos) {
NodeHelper fromTo = new NodeHelper(fromToNode);
String variableName = fromTo.getAttribute("variable");
if (!isCorrespondingVariableOfMessageType(fromTo, variableName)
&& fromTo.hasAttribute("part")) {
addViolation(fromToNode, PART_IS_PROHIBITED_FOR_NON_MESSAGE_TYPES);
}
}
}
private boolean isCorrespondingVariableOfMessageType(NodeHelper fromTo, String variableName) {
try {
VariableLike variable = navigator.getVariableByName(fromTo, variableName);
return variable.hasVariableMessageType();
} catch (NavigationException e) {
addViolation(fromTo, VARIABLE_IS_MISSING);
return false;
}
}
@Override
public int getSaNumber() {
return 34;
}
}
| lgpl-3.0 |
Godin/sonar | server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ReportScmInfoTest.java | 5130 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.scm;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.scanner.protocol.output.ScannerReport;
import static org.assertj.core.api.Assertions.assertThat;
public class ReportScmInfoTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
static final int FILE_REF = 1;
@Test
public void create_scm_info_with_some_changesets() {
ScmInfo scmInfo = new ReportScmInfo(ScannerReport.Changesets.newBuilder()
.setComponentRef(FILE_REF)
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("john")
.setDate(123456789L)
.setRevision("rev-1")
.build())
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("henry")
.setDate(1234567810L)
.setRevision("rev-2")
.build())
.addChangesetIndexByLine(0)
.addChangesetIndexByLine(1)
.addChangesetIndexByLine(0)
.addChangesetIndexByLine(0)
.build());
assertThat(scmInfo.getAllChangesets()).hasSize(4);
}
@Test
public void return_changeset_for_a_given_line() {
ScmInfo scmInfo = new ReportScmInfo(ScannerReport.Changesets.newBuilder()
.setComponentRef(FILE_REF)
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("john")
.setDate(123456789L)
.setRevision("rev-1")
.build())
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("henry")
.setDate(1234567810L)
.setRevision("rev-2")
.build())
.addChangesetIndexByLine(0)
.addChangesetIndexByLine(1)
.addChangesetIndexByLine(1)
.addChangesetIndexByLine(0)
.build());
assertThat(scmInfo.getAllChangesets()).hasSize(4);
Changeset changeset = scmInfo.getChangesetForLine(4);
assertThat(changeset.getAuthor()).isEqualTo("john");
assertThat(changeset.getDate()).isEqualTo(123456789L);
assertThat(changeset.getRevision()).isEqualTo("rev-1");
}
@Test
public void return_latest_changeset() {
ScmInfo scmInfo = new ReportScmInfo(ScannerReport.Changesets.newBuilder()
.setComponentRef(FILE_REF)
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("john")
.setDate(123456789L)
.setRevision("rev-1")
.build())
// Older changeset
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("henry")
.setDate(1234567810L)
.setRevision("rev-2")
.build())
.addChangesetIndexByLine(0)
.addChangesetIndexByLine(1)
.addChangesetIndexByLine(0)
.build());
Changeset latestChangeset = scmInfo.getLatestChangeset();
assertThat(latestChangeset.getAuthor()).isEqualTo("henry");
assertThat(latestChangeset.getDate()).isEqualTo(1234567810L);
assertThat(latestChangeset.getRevision()).isEqualTo("rev-2");
}
@Test
public void fail_with_ISE_when_no_changeset() {
thrown.expect(IllegalStateException.class);
new ReportScmInfo(ScannerReport.Changesets.newBuilder().build());
}
@Test
public void fail_with_NPE_when_report_is_null() {
thrown.expect(NullPointerException.class);
new ReportScmInfo(null);
}
@Test
public void fail_with_ISE_when_changeset_has_no_revision() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Changeset on line 1 must have a revision");
new ReportScmInfo(ScannerReport.Changesets.newBuilder()
.setComponentRef(FILE_REF)
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("john")
.setDate(123456789L)
.build())
.addChangesetIndexByLine(0)
.build());
}
@Test
public void fail_with_ISE_when_changeset_has_no_date() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Changeset on line 1 must have a date");
new ReportScmInfo(ScannerReport.Changesets.newBuilder()
.setComponentRef(FILE_REF)
.addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
.setAuthor("john")
.setRevision("rev-1")
.build())
.addChangesetIndexByLine(0)
.build());
}
}
| lgpl-3.0 |
leon737/MvcBlanket | MvcBlanketLibTest/MaybeMonadTest.cs | 1800 | /*
MVC Blanket Library Copyright (C) 2009-2012 Leonid Gordo
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation;
either version 3.0 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library;
if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MvcBlanketLib.Fluent;
namespace MvcBlanketLibTest
{
[TestClass]
public class MaybeMonadTest
{
[TestMethod]
public void ReferenceWithValueToMaybe()
{
string reference = "Some string";
Maybe<string> maybe = reference.ToMaybe();
Assert.IsTrue(maybe.HasValue);
Assert.AreEqual(reference, maybe.Value);
}
[TestMethod]
public void ReferenceWithoutValueToMaybe()
{
Maybe<string> maybe = new Maybe<string>(null);
Assert.IsFalse(maybe.HasValue);
}
[TestMethod]
public void ValueToMaybe()
{
int value = 10;
Maybe<int> maybe = new Maybe<int>(value);
Assert.IsTrue(maybe.HasValue);
Assert.AreEqual(value, maybe.Value);
}
}
}
| lgpl-3.0 |
NoobSaibot/Baukasten.old | src/services/src/services.cpp | 1071 | #include "services/Services"
#include "audio/IAudio"
#include "core/Debug"
#include "graphics/IGraphics"
#include "input/IInput"
using namespace Baukasten;
Services&
Services::instance()
{
static Services instance;
return instance;
}
Services::Services() :
m_audio( AudioInterface::instance() ),
m_graphics( GraphicsInterface::instance() ),
m_input( InputInterface::instance() )
{
}
Services::~Services()
{
BK_DEBUG( "destroy Services" );
m_audio->shutdown();
m_graphics->shutdown();
m_input->shutdown();
}
void
Services::init( int argc, char** argv )
{
m_argc = argc;
m_argv = argv;
m_audio->init( *this );
m_graphics->init( *this );
m_input->init( *this );
}
void
Services::shutdown()
{
m_input->shutdown();
m_graphics->shutdown();
m_audio->shutdown();
}
IAudio&
Services::audioService() const
{
return *m_audio;
}
IInput&
Services::inputService() const
{
return *m_input;
}
IGraphics&
Services::graphicsService() const
{
return *m_graphics;
}
int
Services::argc()
{
return m_argc;
}
char**
Services::argv() const
{
return m_argv;
}
| lgpl-3.0 |
Wingman/wingman | src/main/java/com/wingman/defaultplugins/devutils/game/Inventory.java | 3581 | package com.wingman.defaultplugins.devutils.game;
import com.wingman.client.api.generated.GameAPI;
import com.wingman.client.api.generated.Widget;
import java.util.Optional;
/**
* Provides API for getting data about the local player's inventory.
*/
public class Inventory {
/**
* @return an array containing item IDs for item slots, where an "item slot" is an array index;
* or nothing if the inventory can't be looked up
*/
public static Optional<int[]> getItemIds() {
return getWidget()
.map(Widget::getItemIds);
}
/**
* @return an array containing item quantities for item slots, where an "item slot" is an array index;
* or nothing if the inventory can't be looked up
*/
public static Optional<int[]> getItemQuantities() {
return getWidget()
.map(Widget::getItemQuantities);
}
/**
* @param itemId the item ID of the item to lookup
* @return {@code true} if the item was successfully found in the inventory;
* {@code false} if it was not found;
* or nothing if the inventory can't be looked up
*/
public static Optional<Boolean> containsItem(int itemId) {
Optional<int[]> quantities = getItemQuantities();
if (quantities.isPresent()) {
for (int id : quantities.get()) {
if (id == itemId) {
return Optional.of(true);
}
}
return Optional.of(false);
}
return Optional.empty();
}
/**
* @param itemId the item ID of the item to count
* @return the amount of the item ID in the inventory;
* or nothing if the inventory can't be looked up
*/
public static Optional<Integer> countItem(int itemId) {
Optional<int[]> ids = getItemIds();
Optional<int[]> quantities = getItemQuantities();
if (ids.isPresent() && quantities.isPresent()) {
int count = 0;
for (int i = 0; i < ids.get().length; i++) {
if (ids.get()[i] == itemId) {
count += quantities.get()[i];
}
}
return Optional.of(count);
}
return Optional.empty();
}
/**
* @return the amount of slots that are occupied with an item;
* or nothing if the inventory can't be looked up
*/
public static Optional<Integer> getUsedSpace() {
Optional<int[]> ids = getItemIds();
if (ids.isPresent()) {
int count = 0;
for (int id : ids.get()) {
if (id != 0) {
count++;
}
}
return Optional.of(count);
}
return Optional.empty();
}
/**
* @return the amount of slots that aren't occupied with an item;
* or nothing if the inventory can't be looked up
*/
public static Optional<Integer> getFreeSpace() {
return getUsedSpace()
.map(usedSpace -> getCapacity() - usedSpace);
}
/**
* @return the maximum capacity of the inventory
*/
public static int getCapacity() {
return 28;
}
/**
* @return the inventory widget;
* or nothing if the widget couldn't be retrieved
*/
public static Optional<Widget> getWidget() {
try {
return Optional.of(GameAPI.getWidgets()[149][0]);
} catch (Exception e) {
return Optional.empty();
}
}
}
| lgpl-3.0 |
jfucci/PathPointerRPI | app/src/main/java/org/jgrapht/graph/BaseIntrusiveEdgesSpecifics.java | 3716 | /*
* (C) Copyright 2003-2017, by Barak Naveh and Contributors.
*
* JGraphT : a free Java graph-theory library
*
* This program and the accompanying materials are dual-licensed under
* either
*
* (a) the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation, or (at your option) any
* later version.
*
* or (per the licensee's choosing)
*
* (b) the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation.
*/
package org.jgrapht.graph;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.jgrapht.Graph;
import org.jgrapht.util.TypeUtil;
/**
* A base implementation for the intrusive edges specifics.
*
* @author Barak Naveh
* @author Dimitrios Michail
*
* @param <V> the graph vertex type
* @param <E> the graph edge type
* @param <IE> the intrusive edge type
*/
abstract class BaseIntrusiveEdgesSpecifics<V, E, IE extends IntrusiveEdge>
implements Serializable
{
private static final long serialVersionUID = -7498268216742485L;
protected Map<E, IE> edgeMap;
protected transient Set<E> unmodifiableEdgeSet = null;
/**
* Constructor
*/
public BaseIntrusiveEdgesSpecifics()
{
this.edgeMap = new LinkedHashMap<>();
}
/**
* Check if an edge exists
*
* @param e the edge
* @return true if the edge exists, false otherwise
*/
public boolean containsEdge(E e)
{
return edgeMap.containsKey(e);
}
/**
* Get the edge set.
*
* @return an unmodifiable edge set
*/
public Set<E> getEdgeSet()
{
if (unmodifiableEdgeSet == null) {
unmodifiableEdgeSet = Collections.unmodifiableSet(edgeMap.keySet());
}
return unmodifiableEdgeSet;
}
/**
* Remove an edge.
*
* @param e the edge
*/
public void remove(E e)
{
edgeMap.remove(e);
}
/**
* Get the source of an edge.
*
* @param e the edge
* @return the source vertex of an edge
*/
public V getEdgeSource(E e)
{
IntrusiveEdge ie = getIntrusiveEdge(e);
if (ie == null) {
throw new IllegalArgumentException("no such edge in graph: " + e.toString());
}
return TypeUtil.uncheckedCast(ie.source, null);
}
/**
* Get the target of an edge.
*
* @param e the edge
* @return the target vertex of an edge
*/
public V getEdgeTarget(E e)
{
IntrusiveEdge ie = getIntrusiveEdge(e);
if (ie == null) {
throw new IllegalArgumentException("no such edge in graph: " + e.toString());
}
return TypeUtil.uncheckedCast(ie.target, null);
}
/**
* Get the weight of an edge.
*
* @param e the edge
* @return the weight of an edge
*/
public double getEdgeWeight(E e)
{
return Graph.DEFAULT_EDGE_WEIGHT;
}
/**
* Set the weight of an edge
*
* @param e the edge
* @param weight the new weight
*/
public void setEdgeWeight(E e, double weight)
{
throw new UnsupportedOperationException();
}
/**
* Add a new edge
*
* @param e the edge
* @param sourceVertex the source vertex of the edge
* @param targetVertex the target vertex of the edge
*/
public abstract void add(E e, V sourceVertex, V targetVertex);
/**
* Get the intrusive edge of an edge.
*
* @param e the edge
* @return the intrusive edge
*/
protected abstract IE getIntrusiveEdge(E e);
}
| lgpl-3.0 |
anlambert/tulip | library/talipot-core/src/PropertyManager.cpp | 10135 | /**
*
* Copyright (C) 2019-2021 The Talipot developers
*
* Talipot is a fork of Tulip, created by David Auber
* and the Tulip development Team from LaBRI, University of Bordeaux
*
* See the AUTHORS file at the top-level directory of this distribution
* License: GNU General Public License version 3, or any later version
* See top-level LICENSE file for more information
*
*/
#include <talipot/GraphAbstract.h>
#include <talipot/PropertyManager.h>
#include <talipot/GraphProperty.h>
namespace tlp {
using namespace std;
using namespace tlp;
const string metaGraphPropertyName = "viewMetaGraph";
//==============================================================
PropertyManager::PropertyManager(Graph *g) : graph(g) {
// get inherited properties
if (graph != graph->getSuperGraph()) {
for (PropertyInterface *prop : graph->getSuperGraph()->getObjectProperties()) {
inheritedProperties[prop->getName()] = prop;
if (prop->getName() == metaGraphPropertyName) {
static_cast<GraphAbstract *>(graph)->metaGraphProperty = static_cast<GraphProperty *>(prop);
}
}
}
}
//==============================================================
PropertyManager::~PropertyManager() {
for (const auto &[name, property] : localProperties) {
property->graph = nullptr;
delete property;
}
}
//==============================================================
bool PropertyManager::existProperty(const string &str) const {
return existLocalProperty(str) || existInheritedProperty(str);
}
//==============================================================
bool PropertyManager::existLocalProperty(const string &str) const {
return localProperties.find(str) != localProperties.end();
}
//==============================================================
bool PropertyManager::existInheritedProperty(const string &str) const {
return inheritedProperties.find(str) != inheritedProperties.end();
}
//==============================================================
void PropertyManager::setLocalProperty(const string &str, PropertyInterface *p) {
bool hasInheritedProperty = false;
if (existLocalProperty(str)) {
// delete previously existing local property
delete localProperties[str];
} else {
// remove previously existing inherited property
auto it = inheritedProperties.find(str);
hasInheritedProperty = it != inheritedProperties.end();
if (hasInheritedProperty) {
// Notify property destruction old state.
notifyBeforeDelInheritedProperty(str);
// Erase old inherited property
inheritedProperties.erase(it);
}
}
// register property as local
localProperties[str] = p;
// If we had an inherited property notify it's destruction.
if (hasInheritedProperty) {
static_cast<GraphAbstract *>(graph)->notifyAfterDelInheritedProperty(str);
}
// loop on subgraphs
for (Graph *sg : graph->subGraphs()) {
// to set p as inherited property
static_cast<GraphAbstract *>(sg)->propertyContainer->setInheritedProperty(str, p);
}
}
//==============================================================
bool PropertyManager::renameLocalProperty(PropertyInterface *prop, const string &newName) {
assert(prop && prop->getGraph() == graph);
if (existLocalProperty(newName)) {
return false;
}
std::string propName = prop->getName();
auto it = localProperties.find(propName);
if (it == localProperties.end()) {
return false;
}
assert(it->second == prop);
// before rename notification
static_cast<GraphAbstract *>(graph)->notifyBeforeRenameLocalProperty(prop, newName);
// loop in the ascendant hierarchy to get
// an inherited property
PropertyInterface *newProp = nullptr;
Graph *g = graph;
while (g != g->getSuperGraph()) {
g = g->getSuperGraph();
if (g->existLocalProperty(propName)) {
newProp = g->getProperty(propName);
break;
}
}
// Warn subgraphs for deletion.
for (Graph *sg : graph->subGraphs()) {
static_cast<GraphAbstract *>(sg)->propertyContainer->notifyBeforeDelInheritedProperty(propName);
}
// Remove property from map.
localProperties.erase(it);
// Set the inherited property in this graph and all it's subgraphs.
static_cast<GraphAbstract *>(graph)->propertyContainer->setInheritedProperty(propName, newProp);
// remove previously existing inherited property
bool hasInheritedProperty =
((it = inheritedProperties.find(newName)) != inheritedProperties.end());
if (hasInheritedProperty) {
// Notify property destruction old state.
notifyBeforeDelInheritedProperty(newName);
// Erase old inherited property
inheritedProperties.erase(it);
}
// register property as local
localProperties[newName] = prop;
// If we had an inherited property notify it's destruction.
if (hasInheritedProperty) {
static_cast<GraphAbstract *>(graph)->notifyAfterDelInheritedProperty(newName);
}
// loop on subgraphs
for (Graph *sg : graph->subGraphs()) {
// to set p as inherited property
static_cast<GraphAbstract *>(sg)->propertyContainer->setInheritedProperty(newName, prop);
}
// update property name
prop->name = newName;
// after renaming notification
static_cast<GraphAbstract *>(graph)->notifyAfterRenameLocalProperty(prop, propName);
return true;
}
//==============================================================
void PropertyManager::setInheritedProperty(const string &str, PropertyInterface *p) {
if (!existLocalProperty(str)) {
bool hasInheritedProperty = inheritedProperties.find(str) != inheritedProperties.end();
if (p != nullptr) {
static_cast<GraphAbstract *>(graph)->notifyBeforeAddInheritedProperty(str);
inheritedProperties[str] = p;
if (str == metaGraphPropertyName) {
static_cast<GraphAbstract *>(graph)->metaGraphProperty = static_cast<GraphProperty *>(p);
}
} else {
// no need for notification
// already done through notifyBeforeDelInheritedProperty(str);
// see setLocalProperty
inheritedProperties.erase(str);
}
if (hasInheritedProperty) {
static_cast<GraphAbstract *>(graph)->notifyAfterDelInheritedProperty(str);
}
// graph observers notification
if (p != nullptr) {
static_cast<GraphAbstract *>(graph)->notifyAddInheritedProperty(str);
}
// loop on subgraphs
for (Graph *sg : graph->subGraphs()) {
// to set p as inherited property
static_cast<GraphAbstract *>(sg)->propertyContainer->setInheritedProperty(str, p);
}
}
}
//==============================================================
PropertyInterface *PropertyManager::getProperty(const string &str) const {
assert(existProperty(str));
if (existLocalProperty(str)) {
return getLocalProperty(str);
}
if (existInheritedProperty(str)) {
return getInheritedProperty(str);
}
return nullptr;
}
//==============================================================
PropertyInterface *PropertyManager::getLocalProperty(const string &str) const {
assert(existLocalProperty(str));
return const_cast<PropertyManager *>(this)->localProperties[str];
}
//==============================================================
PropertyInterface *PropertyManager::getInheritedProperty(const string &str) const {
assert(existInheritedProperty(str));
return const_cast<PropertyManager *>(this)->inheritedProperties[str];
}
//==============================================================
void PropertyManager::delLocalProperty(const string &str) {
// if found remove from local properties
if (const auto it = localProperties.find(str); it != localProperties.end()) {
auto [name, oldProp] = *it;
// loop in the ascendant hierarchy to get
// an inherited property
PropertyInterface *newProp = nullptr;
Graph *g = graph;
while (g != g->getSuperGraph()) {
g = g->getSuperGraph();
if (g->existLocalProperty(str)) {
newProp = g->getProperty(str);
break;
}
}
// Warn subgraphs.
for (Graph *sg : graph->subGraphs()) {
static_cast<GraphAbstract *>(sg)->propertyContainer->notifyBeforeDelInheritedProperty(str);
}
// Remove property from map.
localProperties.erase(it);
// Set the inherited property in this graph and all it's subgraphs.
static_cast<GraphAbstract *>(graph)->propertyContainer->setInheritedProperty(str, newProp);
// Delete property
// Need to be done after subgraph notification.
if (graph->canDeleteProperty(graph, oldProp)) {
// if (!graph->canPop())
delete oldProp;
} else {
oldProp->notifyDestroy();
}
}
}
//==============================================================
void PropertyManager::notifyBeforeDelInheritedProperty(const string &str) {
// if found remove from inherited properties
if (const auto it = inheritedProperties.find(str); it != inheritedProperties.end()) {
// graph observers notification
static_cast<GraphAbstract *>(graph)->notifyBeforeDelInheritedProperty(str);
// loop on subgraphs
for (Graph *sg : graph->subGraphs()) {
// to remove as inherited property
static_cast<GraphAbstract *>(sg)->propertyContainer->notifyBeforeDelInheritedProperty(str);
}
}
}
Iterator<string> *PropertyManager::getLocalProperties() {
return stlMapKeyIterator(localProperties);
}
Iterator<string> *PropertyManager::getInheritedProperties() {
return stlMapKeyIterator(inheritedProperties);
}
Iterator<PropertyInterface *> *PropertyManager::getLocalObjectProperties() {
return stlMapValueIterator(localProperties);
}
Iterator<PropertyInterface *> *PropertyManager::getInheritedObjectProperties() {
return stlMapValueIterator(inheritedProperties);
}
//===============================================================
void PropertyManager::erase(const node n) {
for (const auto &[name, property] : localProperties) {
property->erase(n);
}
}
//===============================================================
void PropertyManager::erase(const edge e) {
for (const auto &[name, property] : localProperties) {
property->erase(e);
}
}
}
| lgpl-3.0 |
ldelgass/osgearth | src/osgEarth/GeoTransform.cpp | 4630 | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2016 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarth/GeoTransform>
#include <osgEarth/Terrain>
#define LC "[GeoTransform] "
#define OE_TEST OE_DEBUG
using namespace osgEarth;
GeoTransform::GeoTransform() :
_autoRecompute ( false ),
_autoRecomputeReady( false )
{
//nop
}
GeoTransform::GeoTransform(const GeoTransform& rhs,
const osg::CopyOp& op) :
osg::MatrixTransform(rhs, op)
{
_position = rhs._position;
_terrain = rhs._terrain.get();
_autoRecompute = rhs._autoRecompute;
_autoRecomputeReady = false;
}
void
GeoTransform::setTerrain(Terrain* terrain)
{
_terrain = terrain;
// Change in the terrain means we need to recompute the position
// if one is set.
if ( _position.isValid() )
setPosition( _position );
}
void
GeoTransform::setAutoRecomputeHeights(bool value)
{
if (value != _autoRecompute)
{
_autoRecompute = value;
}
}
const GeoPoint&
GeoTransform::getPosition() const
{
return _position;
}
bool
GeoTransform::setPosition(const GeoPoint& position)
{
if ( !position.isValid() )
return false;
_position = position;
// relative Z or reprojection require a terrain:
osg::ref_ptr<Terrain> terrain;
_terrain.lock(terrain);
// relative Z requires a terrain:
if (position.altitudeMode() == ALTMODE_RELATIVE && !terrain.valid())
{
OE_TEST << LC << "setPosition failed condition 1\n";
return false;
}
GeoPoint p;
// transform into terrain SRS if neccesary:
if (terrain.valid() && !terrain->getSRS()->isEquivalentTo(position.getSRS()))
p = position.transform(terrain->getSRS());
else
p = position;
// bail if the transformation failed:
if ( !p.isValid() )
{
OE_TEST << LC << "setPosition failed condition 2\n";
return false;
}
// convert to absolute height:
if ( !p.makeAbsolute(_terrain.get()) )
{
OE_TEST << LC << "setPosition failed condition 3\n";
return false;
}
// assemble the matrix:
osg::Matrixd local2world;
p.createLocalToWorld( local2world );
this->setMatrix( local2world );
// install auto-recompute?
if (_autoRecompute &&
_position.altitudeMode() == ALTMODE_RELATIVE &&
!_autoRecomputeReady)
{
// by using the adapter, there's no need to remove
// the callback then this object destructs.
terrain->addTerrainCallback(
new TerrainCallbackAdapter<GeoTransform>(this) );
_autoRecomputeReady = true;
}
return true;
}
void
GeoTransform::onTileAdded(const TileKey& key,
osg::Node* node,
TerrainCallbackContext& context)
{
if (!_position.isValid() || _position.altitudeMode() != ALTMODE_RELATIVE)
{
OE_TEST << LC << "onTileAdded fail condition 1\n";
return;
}
if (!key.getExtent().contains(_position))
{
OE_DEBUG << LC << "onTileAdded fail condition 2\n";
return;
}
setPosition(_position);
}
void
GeoTransform::setComputeMatrixCallback(GeoTransform::ComputeMatrixCallback* cb)
{
_computeMatrixCallback = cb;
}
bool
GeoTransform::ComputeMatrixCallback::computeLocalToWorldMatrix(const GeoTransform* xform, osg::Matrix& m, osg::NodeVisitor* nv) const
{
if (xform->getReferenceFrame() == xform->RELATIVE_RF)
m.preMult(xform->getMatrix());
else
m = xform->getMatrix();
return true;
}
bool
GeoTransform::ComputeMatrixCallback::computeWorldToLocalMatrix(const GeoTransform* xform, osg::Matrix& m, osg::NodeVisitor* nv) const
{
if (xform->getReferenceFrame() == xform->RELATIVE_RF)
m.postMult(xform->getInverseMatrix());
else
m = xform->getInverseMatrix();
return true;
}
| lgpl-3.0 |
iksaku/PocketMine-MP | src/network/mcpe/protocol/ContainerOpenPacket.php | 2707 | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\network\mcpe\protocol;
#include <rules/DataPacket.h>
use pocketmine\math\Vector3;
use pocketmine\network\mcpe\handler\PacketHandler;
use pocketmine\network\mcpe\serializer\NetworkBinaryStream;
class ContainerOpenPacket extends DataPacket implements ClientboundPacket{
public const NETWORK_ID = ProtocolInfo::CONTAINER_OPEN_PACKET;
/** @var int */
public $windowId;
/** @var int */
public $type;
/** @var int */
public $x;
/** @var int */
public $y;
/** @var int */
public $z;
/** @var int */
public $entityUniqueId = -1;
public static function blockInv(int $windowId, int $windowType, int $x, int $y, int $z) : self{
$result = new self;
$result->windowId = $windowId;
$result->type = $windowType;
[$result->x, $result->y, $result->z] = [$x, $y, $z];
return $result;
}
public static function blockInvVec3(int $windowId, int $windowType, Vector3 $vector3) : self{
return self::blockInv($windowId, $windowType, $vector3->getFloorX(), $vector3->getFloorY(), $vector3->getFloorZ());
}
public static function entityInv(int $windowId, int $windowType, int $entityUniqueId) : self{
$result = new self;
$result->windowId = $windowId;
$result->type = $windowType;
$result->entityUniqueId = $entityUniqueId;
$result->x = $result->y = $result->z = 0; //these have to be set even if they aren't used
return $result;
}
protected function decodePayload(NetworkBinaryStream $in) : void{
$this->windowId = $in->getByte();
$this->type = $in->getByte();
$in->getBlockPosition($this->x, $this->y, $this->z);
$this->entityUniqueId = $in->getEntityUniqueId();
}
protected function encodePayload(NetworkBinaryStream $out) : void{
$out->putByte($this->windowId);
$out->putByte($this->type);
$out->putBlockPosition($this->x, $this->y, $this->z);
$out->putEntityUniqueId($this->entityUniqueId);
}
public function handle(PacketHandler $handler) : bool{
return $handler->handleContainerOpen($this);
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-web/src/main/js/apps/code/components/Component.tsx | 4061 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import classNames from 'classnames';
import * as React from 'react';
import { withScrollTo } from '../../../components/hoc/withScrollTo';
import { WorkspaceContext } from '../../../components/workspace/context';
import { BranchLike } from '../../../types/branch-like';
import { ComponentQualifier } from '../../../types/component';
import { MetricType } from '../../../types/metrics';
import { ComponentMeasure as TypeComponentMeasure, Metric } from '../../../types/types';
import ComponentMeasure from './ComponentMeasure';
import ComponentName from './ComponentName';
import ComponentPin from './ComponentPin';
interface Props {
branchLike?: BranchLike;
canBePinned?: boolean;
canBrowse?: boolean;
component: TypeComponentMeasure;
hasBaseComponent: boolean;
isBaseComponent?: boolean;
metrics: Metric[];
previous?: TypeComponentMeasure;
rootComponent: TypeComponentMeasure;
selected?: boolean;
}
export class Component extends React.PureComponent<Props> {
render() {
const {
branchLike,
canBePinned = true,
canBrowse = false,
component,
hasBaseComponent,
isBaseComponent = false,
metrics,
previous,
rootComponent,
selected = false
} = this.props;
const isFile =
component.qualifier === ComponentQualifier.File ||
component.qualifier === ComponentQualifier.TestFile;
return (
<tr className={classNames({ selected })}>
<td className="blank" />
{canBePinned && (
<td className="thin nowrap">
{isFile && (
<span className="spacer-right">
<WorkspaceContext.Consumer>
{({ openComponent }) => (
<ComponentPin
branchLike={branchLike}
component={component}
openComponent={openComponent}
/>
)}
</WorkspaceContext.Consumer>
</span>
)}
</td>
)}
<td className="code-name-cell">
<div className="display-flex-center">
{hasBaseComponent && <div className="code-child-component-icon" />}
<ComponentName
branchLike={branchLike}
canBrowse={canBrowse}
component={component}
previous={previous}
rootComponent={rootComponent}
unclickable={isBaseComponent}
/>
</div>
</td>
{metrics.map(metric => (
<td
className={classNames('thin', {
'text-center': metric.type === MetricType.Rating,
'nowrap text-right': metric.type !== MetricType.Rating
})}
key={metric.key}>
<div
className={classNames({
'code-components-rating-cell': metric.type === MetricType.Rating,
'code-components-cell': metric.type !== MetricType.Rating
})}>
<ComponentMeasure component={component} metric={metric} />
</div>
</td>
))}
<td className="blank" />
</tr>
);
}
}
export default withScrollTo(Component);
| lgpl-3.0 |
andreasbaumann/sqlitexx | tests/test5.cpp | 1474 | /*
* sqlite3xx - sqlite3 C++ layer, following the ideas of libpqxx
* Copyright (C) 2009 Andreas Baumann
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions of
* the GNU Lesser General Public License, as published by the Free Software
* Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
#include <iostream>
#include "sqlite3xx/sqlite3xx"
/* test needs 'unlink' from 'unistd.h' */
#if !defined _WIN32
#include <unistd.h>
#endif /* !defined _WIN32 */
using namespace sqlite3xx;
using namespace std;
int main( ) {
(void)unlink( "test5.db" );
try {
cout << "creating DB.." << endl;
connection c( "test5.db" );
cout << "connection object is " << c << endl;
// switch of fdatasync to be real fast
cout << "execute pragma synchronous=0.." << endl;
c.exec( "PRAGMA synchronous=0" );
cout << "end." << endl;
} catch( sql_error& e ) {
cerr << e.what( ) << ": " << e.query( ) << endl;
}
}
| lgpl-3.0 |
luismasuelli/django-dynsettings-ritual | grimoire/django/dynsettings/apps.py | 216 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class DefaultAppConfig(AppConfig):
name = 'grimoire.django.dynsettings'
verbose_name = _(u'System Dynamic Settings') | lgpl-3.0 |
consultit/Ely | test/ai/python/os_basic.py | 2182 | '''
Created on Jun 18, 2016
@author: consultit
'''
import panda3d.core
import ely.libtools
from ely.ai import GameAIManager
#
from common import app, startFramework, mask, loadPlane
if __name__ == '__main__':
app = startFramework("'one turning'")
# # here is room for your own code
print("create a steer manager; set root and mask to manage 'kinematic' vehicles")
steerMgr = GameAIManager(0, app.render, mask)
print("reparent the reference node to render")
steerMgr.get_reference_node_path().reparent_to(app.render)
print("get a sceneNP and reparent to the reference node")
sceneNP = loadPlane("SceneNP")
sceneNP.reparent_to(steerMgr.get_reference_node_path())
print("set sceneNP's collide mask")
sceneNP.set_collide_mask(mask)
print("create the default plug-in (attached to the reference node): 'one turning'")
plugInNP = steerMgr.create_steer_plug_in()
plugIn = plugInNP.node()
print("get the model")
modelNP = app.loader.load_model("eve.egg")
modelNP.set_scale(0.25)
print("create the steer vehicle (it is attached to the reference node) and set its position")
vehicleNP = steerMgr.create_steer_vehicle("vehicle")
vehicle = vehicleNP.node()
vehicleNP.set_pos(5.0, -8.0, 0.1)
print("attach the model to steer vehicle")
modelNP.reparent_to(vehicleNP)
print("add the steer vehicle to the plug-in")
plugIn.add_steer_vehicle(vehicleNP)
print("start the default update task for all plug-ins")
steerMgr.start_default_update()
print("DEBUG DRAWING: make the debug reference node paths sibling of the reference node")
steerMgr.get_reference_node_path_debug().reparent_to(app.render)
steerMgr.get_reference_node_path_debug_2d().reparent_to(app.aspect2d)
print("enable debug drawing")
plugIn.enable_debug_drawing(app.camera)
print("toggle debug draw")
plugIn.toggle_debug_drawing(True)
# place camera
trackball = app.trackball.node()
trackball.set_pos(0.0, 30.0, 0.0)
trackball.set_hpr(0.0, 20.0, 0.0)
# app.run(), equals to do the main loop in C++
app.run()
| lgpl-3.0 |
ViniciusCampanha/terrama2 | src/terrama2/services/view/core/Utils.hpp | 2460 | /*
Copyright (C) 2007 National Institute For Space Research (INPE) - Brazil.
This file is part of TerraMA2 - a free and open source computational
platform for analysis, monitoring, and alert of geo-environmental extremes.
TerraMA2 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
TerraMA2 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TerraMA2. See LICENSE. If not, write to
TerraMA2 Team at <terrama2-team@dpi.inpe.br>.
*/
/*!
\file terrama2/services/view/core/View.hpp
\brief Utility functions for view module.
\author Paulo R. M. Oliveira
*/
#ifndef __TERRAMA2_SERVICES_VIEW_CORE_UTILS_HPP__
#define __TERRAMA2_SERVICES_VIEW_CORE_UTILS_HPP__
// TerraMA2
#include "../../../core/Shared.hpp"
#include "../../../core/data-model/Filter.hpp"
#include "../../../core/utility/FileRemover.hpp"
#include "../../../impl/DataAccessorFile.hpp"
// TerraLib
#include <terralib/se/Symbolizer.h>
// STD
#include <memory>
namespace terrama2
{
namespace services
{
namespace view
{
namespace core
{
void registerFactories();
te::se::Symbolizer* getSymbolizer(const te::gm::GeomType& geomType,
const std::string& color,
const std::string& opacity) noexcept;
te::se::Stroke* CreateStroke(const std::string& color,
const std::string& width,
const std::string& opacity,
const std::string& dasharray,
const std::string& linecap,
const std::string& linejoin);
te::se::Fill* CreateFill(const std::string& color,
const std::string& opacity);
} // end namespace core
} // end namespace view
} // end namespace services
} // end namespace terrama2
#endif // __TERRAMA2_SERVICES_VIEW_CORE_UTILS_HPP__
| lgpl-3.0 |
vanatteveldt/delpher_to_amcat | delpher_to_amcat/transfer.py | 4858 | ###########################################################################
# (C) Vrije Universiteit, Amsterdam (the Netherlands) #
# #
# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit #
# #
# AmCAT is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the #
# Free Software Foundation, either version 3 of the License, or (at your #
# option) any later version. #
# #
# AmCAT 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 Lesser General Public #
# License along with AmCAT. If not, see <http://www.gnu.org/licenses/>. #
###########################################################################
from datetime import datetime
import threading
import json
from delpher_to_amcat.logger import log
from settings import amcat, delpher
from amcat.api import AmcatAPI
from delpher.api import DelpherAPI
class DelpherToAmcat(threading.Thread):
set_id = None
def __init__(self, from_date, until_date):
threading.Thread.__init__(self)
self.delpher_api = DelpherAPI(delpher.ppn, from_date, until_date)
self.amcat_api = self.setup_amcat(from_date, until_date)
def run(self):
"""Start the transfer process of articles from kranten.delpher.nl to amcat.vu.nl
"""
for result_page in self.delpher_api.result_pages():
articles = [DelpherToAmcat.convert_article(article) for article in result_page]
self.upload_to_amcat(articles)
log.info('Done. Processed all articles in set {self.set_id}.'.format(**locals()))
def setup_amcat(self, from_date, until_date):
"""Create Amcat API object and save configuration data for later use.
"""
amcat_api = AmcatAPI(amcat.host, amcat.username, amcat.password)
log.info('Setup Amcat API with host {0}, username {1}. Use project {2}'.format(amcat.host, amcat.username,
amcat.project))
now = datetime.now().replace(microsecond=0)
set_name = amcat.set_name_template.format(**locals())
try:
aset = amcat_api.create_set(project=amcat.project, name=set_name, provenance=amcat.data_provenance)
except:
log.exception('Could not create article set')
raise
log.info('Created article set in Amcat. ID: {0}'.format(aset['id']))
self.set_id = aset['id']
return amcat_api
@staticmethod
def convert_article(article):
"""Convert article from KB format to AMCAT format.
Unused keys in AMCAT format are: section, byline, length, externalid, author, addressee, uuid
Args:
article: representation of one article as retrieved from Delpher API. Predicate: Identifier and date are
always set.
Returns:
An article in Amcat's representation. Postcondition: date, headline, text, and medium are always set.
"""
ocr = DelpherAPI.article_ocr(article['identifier'])
page = article.get('page', '')
return {
'date': datetime.strptime(article['date'], '%Y/%m/%d %H:%M:%S').isoformat(),
'headline': article.get('title', '%(ocr).30s...' % {'ocr': ocr}), # headline must not be empty
'medium': article.get('papertitle', 'ppn: {0}'.format(delpher.ppn)),
'text': ocr if len(ocr) > 0 else '<no text>',
'pagenr': int(page) if page.isdigit() else '',
'url': article.get('metadataKey', ''),
'metastring': json.dumps(article) # Just store all available information for potential later use.
}
def upload_to_amcat(self, articles):
"""Create articles in Amcat using AmcatAPI
Args:
articles: List of articles in Amcat's format
"""
try:
self.amcat_api.create_articles(project=amcat.project, articleset=self.set_id, json_data=articles)
except:
log.exception('Could not upload articles to amcat. url: {amcat.project}; set: {self.set_id}; '
'data: {articles}'.format(**locals()))
| lgpl-3.0 |
almondtools/compilerutils | src/main/java/net/amygdalum/util/text/StringUtils.java | 2180 | package net.amygdalum.util.text;
import static net.amygdalum.util.text.ByteEncoding.encode;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public final class StringUtils {
private StringUtils() {
}
public static String reverse(String word) {
char[] chars = word.toCharArray();
int size = word.length();
for (int li = 0, ri = size - 1; li < ri; li++,ri--) {
char swap = chars[li];
chars[li] = chars[ri];
chars[ri] = swap;
}
return new String(chars);
}
public static String join(Iterable<?> objects) {
Iterator<?> iterator = objects.iterator();
if (!iterator.hasNext()) {
return "";
}
StringBuilder buffer = new StringBuilder(iterator.next().toString());
while (iterator.hasNext()) {
buffer.append(iterator.next().toString());
}
return buffer.toString();
}
public static String join(Iterable<?> objects, char c) {
Iterator<?> iterator = objects.iterator();
if (!iterator.hasNext()) {
return "";
}
StringBuilder buffer = new StringBuilder(iterator.next().toString());
while (iterator.hasNext()) {
buffer.append(c);
buffer.append(iterator.next().toString());
}
return buffer.toString();
}
public static String join(Iterable<?> objects, String s) {
Iterator<?> iterator = objects.iterator();
if (!iterator.hasNext()) {
return "";
}
StringBuilder buffer = new StringBuilder(iterator.next().toString());
while (iterator.hasNext()) {
buffer.append(s);
buffer.append(iterator.next().toString());
}
return buffer.toString();
}
public static List<byte[]> toByteArray(Collection<String> patterns, Charset charset) {
List<byte[]> charpatterns = new ArrayList<byte[]>(patterns.size());
for (String pattern : patterns) {
charpatterns.add(encode(pattern, charset));
}
return charpatterns;
}
public static List<char[]> toCharArray(Collection<String> patterns) {
List<char[]> charpatterns = new ArrayList<char[]>(patterns.size());
for (String pattern : patterns) {
charpatterns.add(pattern.toCharArray());
}
return charpatterns;
}
}
| lgpl-3.0 |
contao-bootstrap/tab | src/View/Tab/Navigation.php | 2259 | <?php
/**
* Contao Bootstrap
*
* @package contao-bootstrap
* @subpackage Tab
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2013-2020 netzmacht David Molineus. All rights reserved.
* @license LGPL-3.0-or-later https://github.com/contao-bootstrap/tab/blob/master/LICENSE
* @filesource
*/
declare(strict_types=1);
namespace ContaoBootstrap\Tab\View\Tab;
use Contao\StringUtil;
use ContaoBootstrap\Tab\View\Tab\Item\Dropdown;
use ContaoBootstrap\Tab\View\Tab\Item\NavItem;
/**
* Class Navigation
*/
final class Navigation implements ItemList
{
/**
* Navigation items.
*
* @var array
*/
private $items = [];
/**
* Create instance from a serialized definition
*
* @param string $definition Serialized definition.
* @param string $tabId Tab id as string, used as css id suffix.
*
* @return Navigation
*/
public static function fromSerialized(string $definition, string $tabId): self
{
$navigation = new Navigation();
$current = $navigation;
$definition = StringUtil::deserialize($definition, true);
$cssIds = [];
foreach ($definition as $index => $tab) {
if (!$tab['cssId']) {
$tab['cssId'] = StringUtil::standardize($tab['title']);
$tab['cssId'] .= '-' . $tabId;
if (in_array($tab['cssId'], $cssIds)) {
$tab['cssId'] .= '-' . $index;
}
}
if ($tab['type'] === 'dropdown') {
$item = Dropdown::fromArray($tab);
$current = $item;
$navigation->addItem($item);
} else {
if ($tab['type'] !== 'child') {
$current = $navigation;
}
$item = NavItem::fromArray($tab);
$current->addItem($item);
}
}
return $navigation;
}
/**
* {@inheritdoc}
*/
public function addItem(NavItem $item): ItemList
{
$this->items[] = $item;
return $this;
}
/**
* {@inheritdoc}
*/
public function items(): array
{
return $this->items;
}
}
| lgpl-3.0 |
git-moss/DrivenByMoss | src/main/java/de/mossgrabers/bitwig/framework/daw/data/bank/SlotBankImpl.java | 2192 | // Written by Jürgen Moßgraber - mossgrabers.de
// (c) 2017-2022
// Licensed under LGPLv3 - http://www.gnu.org/licenses/lgpl-3.0.txt
package de.mossgrabers.bitwig.framework.daw.data.bank;
import de.mossgrabers.bitwig.framework.daw.data.SlotImpl;
import de.mossgrabers.framework.controller.valuechanger.IValueChanger;
import de.mossgrabers.framework.daw.IHost;
import de.mossgrabers.framework.daw.data.ISlot;
import de.mossgrabers.framework.daw.data.ITrack;
import de.mossgrabers.framework.daw.data.bank.ISlotBank;
import com.bitwig.extension.controller.api.ClipLauncherSlotBank;
import java.util.Optional;
/**
* Encapsulates the data of a slot bank.
*
* @author Jürgen Moßgraber
*/
public class SlotBankImpl extends AbstractItemBankImpl<ClipLauncherSlotBank, ISlot> implements ISlotBank
{
private final ITrack track;
/**
* Constructor.
*
* @param host The DAW host
* @param valueChanger The value changer
* @param track The track, which contains the slot bank
* @param clipLauncherSlotBank The slot bank
* @param numSlots The number of slots in the page of the bank
*/
public SlotBankImpl (final IHost host, final IValueChanger valueChanger, final ITrack track, final ClipLauncherSlotBank clipLauncherSlotBank, final int numSlots)
{
super (host, valueChanger, clipLauncherSlotBank, numSlots);
this.track = track;
if (this.bank.isEmpty ())
return;
final ClipLauncherSlotBank clsb = this.bank.get ();
for (int i = 0; i < this.getPageSize (); i++)
this.items.add (new SlotImpl (this.track, clsb.getItemAt (i), i));
}
/** {@inheritDoc} */
@Override
public Optional<ISlot> getEmptySlot (final int startFrom)
{
final int start = startFrom >= 0 ? startFrom : 0;
final int size = this.items.size ();
for (int i = 0; i < size; i++)
{
final ISlot item = this.items.get ((start + i) % size);
if (!item.hasContent ())
return Optional.of (item);
}
return Optional.empty ();
}
} | lgpl-3.0 |
c2mon/c2mon | c2mon-server/c2mon-server-configuration/src/main/java/cern/c2mon/server/configuration/handler/transacted/TagConfigTransacted.java | 2217 | /******************************************************************************
* Copyright (C) 2010-2016 CERN. All rights not expressly granted are reserved.
*
* This file is part of the CERN Control and Monitoring Platform 'C2MON'.
* C2MON is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the license.
*
* C2MON is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with C2MON. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package cern.c2mon.server.configuration.handler.transacted;
import cern.c2mon.server.common.tag.Tag;
/**
* Common interface of the ConfigHandlers that
* manages Tag objects.
*
* @author Mark Brightwell
*
* @param <T> cache object type
*/
public interface TagConfigTransacted<T extends Tag> {
/**
* Adds this Rule to the list of Rules that
* need evaluating when this tag changes.
*
* @param tagId the Tag that needs to point to the rule
* @param ruleId the rule that now needs evaluating
*/
void addRuleToTag(Long tagId, Long ruleId);
/**
* Removes this Rule from the list of Rules
* that need evaluating when this Tag changes.
*
* @param tagId the tag pointing to the rule
* @param ruleId the rule that no longer needs evaluating
*/
void removeRuleFromTag(Long tagId, Long ruleId);
/**
* Removes the Alarm from the list of alarms
* attached to the Tag.
*
* @param tagId the Tag id
* @param alarmId the id of the alarm to remove
*/
void removeAlarmFromTag(Long tagId, Long alarmId);
/**
* Adds the alarm to the list of alarms associated to this
* tag (locks tag).
* @param tagId the id of the tag
* @param alarmId the id of the alarm
*/
void addAlarmToTag(Long tagId, Long alarmId);
}
| lgpl-3.0 |
OurGrid/OurGrid | src/main/java/org/ourgrid/discoveryservice/business/requester/DSIsDownRequester.java | 1764 | package org.ourgrid.discoveryservice.business.requester;
import java.util.ArrayList;
import java.util.List;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceDAO;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceDAOFactory;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceInfo;
import org.ourgrid.discoveryservice.business.messages.DiscoveryServiceControlMessages;
import org.ourgrid.discoveryservice.request.DSIsDownRequestTO;
public class DSIsDownRequester implements RequesterIF<DSIsDownRequestTO>{
public List<IResponseTO> execute(DSIsDownRequestTO request) {
List<IResponseTO> responses = new ArrayList<IResponseTO>();
DiscoveryServiceDAO discoveryServiceDAO = DiscoveryServiceDAOFactory.getInstance().getDiscoveryServiceDAO();
DiscoveryServiceInfo dsInfo = discoveryServiceDAO.getDSInfo(request.getDsAddress());
if (dsInfo == null ) {
responses.add(new LoggerResponseTO(
DiscoveryServiceControlMessages.getDSNotMemberOfNetworkMessage(request.getDsAddress()),
LoggerResponseTO.WARN));
return responses;
}
if (! dsInfo.isUp()) {
responses.add(new LoggerResponseTO(
DiscoveryServiceControlMessages.getFailureNotificationFromAFailedDSMessage(request.getDsAddress()),
LoggerResponseTO.WARN));
return responses;
}
discoveryServiceDAO.removeFromNetwork(request.getDsAddress());
responses.add(new LoggerResponseTO(DiscoveryServiceControlMessages.getDiscoveryServiceFailureNotificationMessage(request.getDsAddress()), LoggerResponseTO.INFO));
return responses;
}
}
| lgpl-3.0 |
ecramer89/813Code | tests/org/jgap/impl/RandomFitnessFunction.java | 1122 | /*
* This file is part of JGAP.
*
* JGAP offers a dual license model containing the LGPL as well as the MPL.
*
* For licensing information please see the file license.txt included with JGAP
* or have a look at the top of class org.jgap.Chromosome which representatively
* includes the JGAP license policy applicable for any file delivered with JGAP.
*/
package org.jgap.impl;
import java.util.*;
import org.jgap.*;
/**
* Fitness function returning random values.
* Only for testing purposes!
*
* @author Klaus Meffert
* @since 1.1
*/
public class RandomFitnessFunction
extends FitnessFunction {
/** String containing the CVS revision. Read out via reflection!*/
private final static String CVS_REVISION = "$Revision: 1.7 $";
private Random m_rand;
public RandomFitnessFunction() {
m_rand = new Random();
}
/**
* @param a_chrom ignored: the Chromosome to evaluate
* @return randomized fitness value
* @since 2.0 (until 1.1: return type int)
*/
public double evaluate(IChromosome a_chrom) {
double result;
result = m_rand.nextDouble();
return result;
}
}
| lgpl-3.0 |
PremiumGraphics/DirectView | ThirdParty/wxWidgets-3.0.2/src/propgrid/propgrid.cpp | 192883 | /////////////////////////////////////////////////////////////////////////////
// Name: src/propgrid/propgrid.cpp
// Purpose: wxPropertyGrid
// Author: Jaakko Salli
// Modified by:
// Created: 2004-09-25
// Copyright: (c) Jaakko Salli
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_PROPGRID
#ifndef WX_PRECOMP
#include "wx/defs.h"
#include "wx/object.h"
#include "wx/hash.h"
#include "wx/string.h"
#include "wx/log.h"
#include "wx/event.h"
#include "wx/window.h"
#include "wx/panel.h"
#include "wx/dc.h"
#include "wx/dcmemory.h"
#include "wx/button.h"
#include "wx/pen.h"
#include "wx/brush.h"
#include "wx/cursor.h"
#include "wx/dialog.h"
#include "wx/settings.h"
#include "wx/msgdlg.h"
#include "wx/choice.h"
#include "wx/stattext.h"
#include "wx/scrolwin.h"
#include "wx/dirdlg.h"
#include "wx/sizer.h"
#include "wx/textdlg.h"
#include "wx/filedlg.h"
#include "wx/statusbr.h"
#include "wx/intl.h"
#include "wx/frame.h"
#include "wx/textctrl.h"
#endif
// This define is necessary to prevent macro clearing
#define __wxPG_SOURCE_FILE__
#include "wx/propgrid/propgrid.h"
#include "wx/propgrid/editors.h"
#if wxPG_USE_RENDERER_NATIVE
#include "wx/renderer.h"
#endif
#include "wx/odcombo.h"
#include "wx/timer.h"
#include "wx/dcbuffer.h"
#include "wx/scopeguard.h"
// Two pics for the expand / collapse buttons.
// Files are not supplied with this project (since it is
// recommended to use either custom or native rendering).
// If you want them, get wxTreeMultiCtrl by Jorgen Bodde,
// and copy xpm files from archive to wxPropertyGrid src directory
// (and also comment/undef wxPG_ICON_WIDTH in propGrid.h
// and set wxPG_USE_RENDERER_NATIVE to 0).
#ifndef wxPG_ICON_WIDTH
#if defined(__WXMAC__)
#include "mac_collapse.xpm"
#include "mac_expand.xpm"
#elif defined(__WXGTK__)
#include "linux_collapse.xpm"
#include "linux_expand.xpm"
#else
#include "default_collapse.xpm"
#include "default_expand.xpm"
#endif
#endif
//#define wxPG_TEXT_INDENT 4 // For the wxComboControl
//#define wxPG_ALLOW_CLIPPING 1 // If 1, GetUpdateRegion() in OnPaint event handler is not ignored
#define wxPG_GUTTER_DIV 3 // gutter is max(iconwidth/gutter_div,gutter_min)
#define wxPG_GUTTER_MIN 3 // gutter before and after image of [+] or [-]
#define wxPG_YSPACING_MIN 1
#define wxPG_DEFAULT_VSPACING 2 // This matches .NET propertygrid's value,
// but causes normal combobox to spill out under MSW
//#define wxPG_OPTIMAL_WIDTH 200 // Arbitrary
//#define wxPG_MIN_SCROLLBAR_WIDTH 10 // Smallest scrollbar width on any platform
// Must be larger than largest control border
// width * 2.
#define wxPG_DEFAULT_CURSOR wxNullCursor
//#define wxPG_NAT_CHOICE_BORDER_ANY 0
//#define wxPG_HIDER_BUTTON_HEIGHT 25
#define wxPG_PIXELS_PER_UNIT m_lineHeight
#ifdef wxPG_ICON_WIDTH
#define m_iconHeight m_iconWidth
#endif
//#define wxPG_TOOLTIP_DELAY 1000
// This is the number of pixels the expander button inside
// property cells (i.e. not in the grey margin area are
// adjusted.
#define IN_CELL_EXPANDER_BUTTON_X_ADJUST 2
// -----------------------------------------------------------------------
#if wxUSE_INTL
void wxPropertyGrid::AutoGetTranslation ( bool enable )
{
wxPGGlobalVars->m_autoGetTranslation = enable;
}
#else
void wxPropertyGrid::AutoGetTranslation ( bool ) { }
#endif
// -----------------------------------------------------------------------
const char wxPropertyGridNameStr[] = "wxPropertyGrid";
// -----------------------------------------------------------------------
// Statics in one class for easy destruction.
// -----------------------------------------------------------------------
#include "wx/module.h"
class wxPGGlobalVarsClassManager : public wxModule
{
DECLARE_DYNAMIC_CLASS(wxPGGlobalVarsClassManager)
public:
wxPGGlobalVarsClassManager() {}
virtual bool OnInit() { wxPGGlobalVars = new wxPGGlobalVarsClass(); return true; }
virtual void OnExit() { wxDELETE(wxPGGlobalVars); }
};
IMPLEMENT_DYNAMIC_CLASS(wxPGGlobalVarsClassManager, wxModule)
// When wxPG is loaded dynamically after the application is already running
// then the built-in module system won't pick this one up. Add it manually.
void wxPGInitResourceModule()
{
wxModule* module = new wxPGGlobalVarsClassManager;
wxModule::RegisterModule(module);
wxModule::InitializeModules();
}
wxPGGlobalVarsClass* wxPGGlobalVars = NULL;
wxPGGlobalVarsClass::wxPGGlobalVarsClass()
{
wxPGProperty::sm_wxPG_LABEL = new wxString(wxPG_LABEL_STRING);
m_boolChoices.Add(_("False"));
m_boolChoices.Add(_("True"));
m_fontFamilyChoices = NULL;
m_defaultRenderer = new wxPGDefaultRenderer();
m_autoGetTranslation = false;
m_offline = 0;
m_extraStyle = 0;
wxVariant v;
// Prepare some shared variants
m_vEmptyString = wxString();
m_vZero = (long) 0;
m_vMinusOne = (long) -1;
m_vTrue = true;
m_vFalse = false;
// Prepare cached string constants
m_strstring = wxS("string");
m_strlong = wxS("long");
m_strbool = wxS("bool");
m_strlist = wxS("list");
m_strDefaultValue = wxS("DefaultValue");
m_strMin = wxS("Min");
m_strMax = wxS("Max");
m_strUnits = wxS("Units");
m_strHint = wxS("Hint");
#if wxPG_COMPATIBILITY_1_4
m_strInlineHelp = wxS("InlineHelp");
#endif
m_warnings = 0;
}
wxPGGlobalVarsClass::~wxPGGlobalVarsClass()
{
size_t i;
delete m_defaultRenderer;
// This will always have one ref
delete m_fontFamilyChoices;
#if wxUSE_VALIDATORS
for ( i=0; i<m_arrValidators.size(); i++ )
delete ((wxValidator*)m_arrValidators[i]);
#endif
//
// Destroy value type class instances.
wxPGHashMapS2P::iterator vt_it;
// Destroy editor class instances.
// iterate over all the elements in the class
for( vt_it = m_mapEditorClasses.begin(); vt_it != m_mapEditorClasses.end(); ++vt_it )
{
delete ((wxPGEditor*)vt_it->second);
}
// Make sure the global pointers have been reset
wxASSERT(wxPG_EDITOR(TextCtrl) == NULL);
wxASSERT(wxPG_EDITOR(ChoiceAndButton) == NULL);
delete wxPGProperty::sm_wxPG_LABEL;
}
void wxPropertyGridInitGlobalsIfNeeded()
{
}
// -----------------------------------------------------------------------
// wxPropertyGrid
// -----------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxPropertyGrid, wxControl)
BEGIN_EVENT_TABLE(wxPropertyGrid, wxControl)
EVT_IDLE(wxPropertyGrid::OnIdle)
EVT_PAINT(wxPropertyGrid::OnPaint)
EVT_SIZE(wxPropertyGrid::OnResize)
EVT_ENTER_WINDOW(wxPropertyGrid::OnMouseEntry)
EVT_LEAVE_WINDOW(wxPropertyGrid::OnMouseEntry)
EVT_MOUSE_CAPTURE_CHANGED(wxPropertyGrid::OnCaptureChange)
EVT_SCROLLWIN(wxPropertyGrid::OnScrollEvent)
EVT_CHILD_FOCUS(wxPropertyGrid::OnChildFocusEvent)
EVT_SET_FOCUS(wxPropertyGrid::OnFocusEvent)
EVT_KILL_FOCUS(wxPropertyGrid::OnFocusEvent)
EVT_SYS_COLOUR_CHANGED(wxPropertyGrid::OnSysColourChanged)
EVT_MOTION(wxPropertyGrid::OnMouseMove)
EVT_LEFT_DOWN(wxPropertyGrid::OnMouseClick)
EVT_LEFT_UP(wxPropertyGrid::OnMouseUp)
EVT_RIGHT_UP(wxPropertyGrid::OnMouseRightClick)
EVT_LEFT_DCLICK(wxPropertyGrid::OnMouseDoubleClick)
EVT_KEY_DOWN(wxPropertyGrid::OnKey)
END_EVENT_TABLE()
// -----------------------------------------------------------------------
wxPropertyGrid::wxPropertyGrid()
: wxControl(), wxScrollHelper(this)
{
Init1();
}
// -----------------------------------------------------------------------
wxPropertyGrid::wxPropertyGrid( wxWindow *parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name )
: wxControl(), wxScrollHelper(this)
{
Init1();
Create(parent,id,pos,size,style,name);
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::Create( wxWindow *parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name )
{
if (!(style&wxBORDER_MASK))
{
style |= wxBORDER_THEME;
}
style |= wxVSCROLL;
// Filter out wxTAB_TRAVERSAL - we will handle TABs manually
style &= ~(wxTAB_TRAVERSAL);
style |= wxWANTS_CHARS;
wxControl::Create(parent, id, pos, size,
style | wxScrolledWindowStyle,
wxDefaultValidator,
name);
Init2();
return true;
}
// -----------------------------------------------------------------------
//
// Initialize values to defaults
//
void wxPropertyGrid::Init1()
{
// Register editor classes, if necessary.
if ( wxPGGlobalVars->m_mapEditorClasses.empty() )
wxPropertyGrid::RegisterDefaultEditors();
m_validatingEditor = 0;
m_iFlags = 0;
m_pState = NULL;
m_wndEditor = m_wndEditor2 = NULL;
m_selColumn = 1;
m_colHover = 1;
m_propHover = NULL;
m_labelEditor = NULL;
m_labelEditorProperty = NULL;
m_eventObject = this;
m_curFocused = NULL;
m_processedEvent = NULL;
m_tlp = NULL;
m_sortFunction = NULL;
m_inDoPropertyChanged = false;
m_inCommitChangesFromEditor = false;
m_inDoSelectProperty = false;
m_inOnValidationFailure = false;
m_permanentValidationFailureBehavior = wxPG_VFB_DEFAULT;
m_dragStatus = 0;
m_mouseSide = 16;
m_editorFocused = 0;
// Set up default unspecified value 'colour'
m_unspecifiedAppearance.SetFgCol(*wxLIGHT_GREY);
// Set default keys
AddActionTrigger( wxPG_ACTION_NEXT_PROPERTY, WXK_RIGHT );
AddActionTrigger( wxPG_ACTION_NEXT_PROPERTY, WXK_DOWN );
AddActionTrigger( wxPG_ACTION_PREV_PROPERTY, WXK_LEFT );
AddActionTrigger( wxPG_ACTION_PREV_PROPERTY, WXK_UP );
AddActionTrigger( wxPG_ACTION_EXPAND_PROPERTY, WXK_RIGHT);
AddActionTrigger( wxPG_ACTION_COLLAPSE_PROPERTY, WXK_LEFT);
AddActionTrigger( wxPG_ACTION_CANCEL_EDIT, WXK_ESCAPE );
AddActionTrigger( wxPG_ACTION_PRESS_BUTTON, WXK_DOWN, wxMOD_ALT );
AddActionTrigger( wxPG_ACTION_PRESS_BUTTON, WXK_F4 );
m_coloursCustomized = 0;
m_frozen = 0;
m_doubleBuffer = NULL;
#ifndef wxPG_ICON_WIDTH
m_expandbmp = NULL;
m_collbmp = NULL;
m_iconWidth = 11;
m_iconHeight = 11;
#else
m_iconWidth = wxPG_ICON_WIDTH;
#endif
m_prevVY = -1;
m_gutterWidth = wxPG_GUTTER_MIN;
m_subgroup_extramargin = 10;
m_lineHeight = 0;
m_width = m_height = 0;
m_commonValues.push_back(new wxPGCommonValue(_("Unspecified"), wxPGGlobalVars->m_defaultRenderer) );
m_cvUnspecified = 0;
m_chgInfo_changedProperty = NULL;
}
// -----------------------------------------------------------------------
//
// Initialize after parent etc. set
//
void wxPropertyGrid::Init2()
{
wxASSERT( !(m_iFlags & wxPG_FL_INITIALIZED ) );
#ifdef __WXMAC__
// Smaller controls on Mac
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
// Now create state, if one didn't exist already
// (wxPropertyGridManager might have created it for us).
if ( !m_pState )
{
m_pState = CreateState();
m_pState->m_pPropGrid = this;
m_iFlags |= wxPG_FL_CREATEDSTATE;
}
if ( !(m_windowStyle & wxPG_SPLITTER_AUTO_CENTER) )
m_pState->m_dontCenterSplitter = true;
if ( m_windowStyle & wxPG_HIDE_CATEGORIES )
{
m_pState->InitNonCatMode();
m_pState->m_properties = m_pState->m_abcArray;
}
GetClientSize(&m_width,&m_height);
#ifndef wxPG_ICON_WIDTH
// create two bitmap nodes for drawing
m_expandbmp = new wxBitmap(expand_xpm);
m_collbmp = new wxBitmap(collapse_xpm);
// calculate average font height for bitmap centering
m_iconWidth = m_expandbmp->GetWidth();
m_iconHeight = m_expandbmp->GetHeight();
#endif
m_curcursor = wxCURSOR_ARROW;
m_cursorSizeWE = new wxCursor( wxCURSOR_SIZEWE );
// adjust bitmap icon y position so they are centered
m_vspacing = wxPG_DEFAULT_VSPACING;
CalculateFontAndBitmapStuff( wxPG_DEFAULT_VSPACING );
// Allocate cell datas
m_propertyDefaultCell.SetEmptyData();
m_categoryDefaultCell.SetEmptyData();
RegainColours();
// This helps with flicker
SetBackgroundStyle( wxBG_STYLE_CUSTOM );
// Hook the top-level parent
m_tlpClosed = NULL;
m_tlpClosedTime = 0;
// set virtual size to this window size
wxSize wndsize = GetSize();
SetVirtualSize(wndsize.GetWidth(), wndsize.GetWidth());
m_timeCreated = ::wxGetLocalTimeMillis();
m_iFlags |= wxPG_FL_INITIALIZED;
m_ncWidth = wndsize.GetWidth();
// Need to call OnResize handler or size given in constructor/Create
// will never work.
wxSizeEvent sizeEvent(wndsize,0);
OnResize(sizeEvent);
}
// -----------------------------------------------------------------------
wxPropertyGrid::~wxPropertyGrid()
{
size_t i;
#if wxUSE_THREADS
wxCriticalSectionLocker(wxPGGlobalVars->m_critSect);
#endif
//
// Remove grid and property pointers from live wxPropertyGridEvents.
for ( i=0; i<m_liveEvents.size(); i++ )
{
wxPropertyGridEvent* evt = m_liveEvents[i];
evt->SetPropertyGrid(NULL);
evt->SetProperty(NULL);
}
m_liveEvents.clear();
if ( m_processedEvent )
{
// All right... we are being deleted while wxPropertyGrid event
// is being sent. Make sure that event propagates as little
// as possible (although usually this is not enough to prevent
// a crash).
m_processedEvent->Skip(false);
m_processedEvent->StopPropagation();
// Let's use wxMessageBox to make the message appear more
// reliably (and *before* the crash can happen).
::wxMessageBox("wxPropertyGrid was being destroyed in an event "
"generated by it. This usually leads to a crash "
"so it is recommended to destroy the control "
"at idle time instead.");
}
DoSelectProperty(NULL, wxPG_SEL_NOVALIDATE|wxPG_SEL_DONT_SEND_EVENT);
// This should do prevent things from going too badly wrong
m_iFlags &= ~(wxPG_FL_INITIALIZED);
if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
ReleaseMouse();
// Call with NULL to disconnect event handling
if ( GetExtraStyle() & wxPG_EX_ENABLE_TLP_TRACKING )
{
OnTLPChanging(NULL);
wxASSERT_MSG( !IsEditorsValueModified(),
wxS("Most recent change in property editor was ")
wxS("lost!!! (if you don't want this to happen, ")
wxS("close your frames and dialogs using ")
wxS("Close(false).)") );
}
if ( m_doubleBuffer )
delete m_doubleBuffer;
if ( m_iFlags & wxPG_FL_CREATEDSTATE )
delete m_pState;
delete m_cursorSizeWE;
#ifndef wxPG_ICON_WIDTH
delete m_expandbmp;
delete m_collbmp;
#endif
// Delete common value records
for ( i=0; i<m_commonValues.size(); i++ )
{
// Use temporary variable to work around possible strange VC6 (asserts because m_size is zero)
wxPGCommonValue* value = m_commonValues[i];
delete value;
}
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::Destroy()
{
if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
ReleaseMouse();
return wxControl::Destroy();
}
// -----------------------------------------------------------------------
wxPropertyGridPageState* wxPropertyGrid::CreateState() const
{
return new wxPropertyGridPageState();
}
// -----------------------------------------------------------------------
// wxPropertyGrid overridden wxWindow methods
// -----------------------------------------------------------------------
void wxPropertyGrid::SetWindowStyleFlag( long style )
{
long old_style = m_windowStyle;
if ( m_iFlags & wxPG_FL_INITIALIZED )
{
wxASSERT( m_pState );
if ( !(style & wxPG_HIDE_CATEGORIES) && (old_style & wxPG_HIDE_CATEGORIES) )
{
// Enable categories
EnableCategories( true );
}
else if ( (style & wxPG_HIDE_CATEGORIES) && !(old_style & wxPG_HIDE_CATEGORIES) )
{
// Disable categories
EnableCategories( false );
}
if ( !(old_style & wxPG_AUTO_SORT) && (style & wxPG_AUTO_SORT) )
{
//
// Autosort enabled
//
if ( !m_frozen )
PrepareAfterItemsAdded();
else
m_pState->m_itemsAdded = 1;
}
#if wxPG_SUPPORT_TOOLTIPS
if ( !(old_style & wxPG_TOOLTIPS) && (style & wxPG_TOOLTIPS) )
{
//
// Tooltips enabled
//
/*
wxToolTip* tooltip = new wxToolTip ( wxEmptyString );
SetToolTip ( tooltip );
tooltip->SetDelay ( wxPG_TOOLTIP_DELAY );
*/
}
else if ( (old_style & wxPG_TOOLTIPS) && !(style & wxPG_TOOLTIPS) )
{
//
// Tooltips disabled
//
SetToolTip( NULL );
}
#endif
}
wxControl::SetWindowStyleFlag ( style );
if ( m_iFlags & wxPG_FL_INITIALIZED )
{
if ( (old_style & wxPG_HIDE_MARGIN) != (style & wxPG_HIDE_MARGIN) )
{
CalculateFontAndBitmapStuff( m_vspacing );
Refresh();
}
}
}
// -----------------------------------------------------------------------
void wxPropertyGrid::Freeze()
{
if ( !m_frozen )
{
wxControl::Freeze();
}
m_frozen++;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::Thaw()
{
m_frozen--;
if ( !m_frozen )
{
wxControl::Thaw();
RecalculateVirtualSize();
Refresh();
// Force property re-selection
// NB: We must copy the selection.
wxArrayPGProperty selection = m_pState->m_selection;
DoSetSelection(selection, wxPG_SEL_FORCE | wxPG_SEL_NONVISIBLE);
}
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::DoAddToSelection( wxPGProperty* prop, int selFlags )
{
wxCHECK( prop, false );
if ( !(GetExtraStyle() & wxPG_EX_MULTIPLE_SELECTION) )
return DoSelectProperty(prop, selFlags);
wxArrayPGProperty& selection = m_pState->m_selection;
if ( !selection.size() )
{
return DoSelectProperty(prop, selFlags);
}
else
{
// For categories, only one can be selected at a time
if ( prop->IsCategory() || selection[0]->IsCategory() )
return true;
selection.push_back(prop);
if ( !(selFlags & wxPG_SEL_DONT_SEND_EVENT) )
{
SendEvent( wxEVT_PG_SELECTED, prop, NULL );
}
DrawItem(prop);
}
return true;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::DoRemoveFromSelection( wxPGProperty* prop, int selFlags )
{
wxCHECK( prop, false );
bool res;
wxArrayPGProperty& selection = m_pState->m_selection;
if ( selection.size() <= 1 )
{
res = DoSelectProperty(NULL, selFlags);
}
else
{
m_pState->DoRemoveFromSelection(prop);
DrawItem(prop);
res = true;
}
return res;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::DoSelectAndEdit( wxPGProperty* prop,
unsigned int colIndex,
unsigned int selFlags )
{
//
// NB: Enable following if label editor background colour is
// ever changed to any other than m_colSelBack.
//
// We use this workaround to prevent visible flicker when editing
// a cell. Atleast on wxMSW, there is a difficult to find
// (and perhaps prevent) redraw somewhere between making property
// selected and enabling label editing.
//
//wxColour prevColSelBack = m_colSelBack;
//m_colSelBack = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW );
bool res;
if ( colIndex == 1 )
{
res = DoSelectProperty(prop, selFlags);
}
else
{
// send event
DoClearSelection(false, wxPG_SEL_NO_REFRESH);
if ( m_pState->m_editableColumns.Index(colIndex) == wxNOT_FOUND )
{
res = DoAddToSelection(prop, selFlags);
}
else
{
res = DoAddToSelection(prop, selFlags|wxPG_SEL_NO_REFRESH);
DoBeginLabelEdit(colIndex, selFlags);
}
}
//m_colSelBack = prevColSelBack;
return res;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::AddToSelectionFromInputEvent( wxPGProperty* prop,
unsigned int colIndex,
wxMouseEvent* mouseEvent,
int selFlags )
{
const wxArrayPGProperty& selection = GetSelectedProperties();
bool alreadySelected = m_pState->DoIsPropertySelected(prop);
bool res = true;
// Set to 2 if also add all items in between
int addToExistingSelection = 0;
if ( GetExtraStyle() & wxPG_EX_MULTIPLE_SELECTION )
{
if ( mouseEvent )
{
if ( mouseEvent->GetEventType() == wxEVT_RIGHT_DOWN ||
mouseEvent->GetEventType() == wxEVT_RIGHT_UP )
{
// Allow right-click for context menu without
// disturbing the selection.
if ( GetSelectedProperties().size() <= 1 ||
!alreadySelected )
return DoSelectAndEdit(prop, colIndex, selFlags);
return true;
}
else
{
if ( mouseEvent->ControlDown() )
{
addToExistingSelection = 1;
}
else if ( mouseEvent->ShiftDown() )
{
if ( selection.size() > 0 && !prop->IsCategory() )
addToExistingSelection = 2;
else
addToExistingSelection = 1;
}
}
}
}
if ( addToExistingSelection == 1 )
{
// Add/remove one
if ( !alreadySelected )
{
res = DoAddToSelection(prop, selFlags);
}
else if ( GetSelectedProperties().size() > 1 )
{
res = DoRemoveFromSelection(prop, selFlags);
}
}
else if ( addToExistingSelection == 2 )
{
// Add this, and all in between
// Find top selected property
wxPGProperty* topSelProp = selection[0];
int topSelPropY = topSelProp->GetY();
for ( unsigned int i=1; i<selection.size(); i++ )
{
wxPGProperty* p = selection[i];
int y = p->GetY();
if ( y < topSelPropY )
{
topSelProp = p;
topSelPropY = y;
}
}
wxPGProperty* startFrom;
wxPGProperty* stopAt;
if ( prop->GetY() <= topSelPropY )
{
// Property is above selection (or same)
startFrom = prop;
stopAt = topSelProp;
}
else
{
// Property is below selection
startFrom = topSelProp;
stopAt = prop;
}
// Iterate through properties in-between, and select them
wxPropertyGridIterator it;
for ( it = GetIterator(wxPG_ITERATE_VISIBLE, startFrom);
!it.AtEnd();
it++ )
{
wxPGProperty* p = *it;
if ( !p->IsCategory() &&
!m_pState->DoIsPropertySelected(p) )
{
DoAddToSelection(p, selFlags);
}
if ( p == stopAt )
break;
}
}
else
{
res = DoSelectAndEdit(prop, colIndex, selFlags);
}
return res;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::DoSetSelection( const wxArrayPGProperty& newSelection,
int selFlags )
{
if ( newSelection.size() > 0 )
{
if ( !DoSelectProperty(newSelection[0], selFlags) )
return;
}
else
{
DoClearSelection(false, selFlags);
}
for ( unsigned int i = 1; i < newSelection.size(); i++ )
{
DoAddToSelection(newSelection[i], selFlags);
}
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::MakeColumnEditable( unsigned int column,
bool editable )
{
wxASSERT( column != 1 );
wxArrayInt& cols = m_pState->m_editableColumns;
if ( editable )
{
cols.push_back(column);
}
else
{
for ( int i = cols.size() - 1; i > 0; i-- )
{
if ( cols[i] == (int)column )
cols.erase( cols.begin() + i );
}
}
}
// -----------------------------------------------------------------------
void wxPropertyGrid::DoBeginLabelEdit( unsigned int colIndex,
int selFlags )
{
wxPGProperty* selected = GetSelection();
wxCHECK_RET(selected, wxT("No property selected"));
wxCHECK_RET(colIndex != 1, wxT("Do not use this for column 1"));
if ( !(selFlags & wxPG_SEL_DONT_SEND_EVENT) )
{
if ( SendEvent( wxEVT_PG_LABEL_EDIT_BEGIN,
selected, NULL, 0,
colIndex ) )
return;
}
wxString text;
const wxPGCell* cell = NULL;
if ( selected->HasCell(colIndex) )
{
cell = &selected->GetCell(colIndex);
if ( !cell->HasText() && colIndex == 0 )
text = selected->GetLabel();
}
if ( !cell )
{
if ( colIndex == 0 )
text = selected->GetLabel();
else
cell = &selected->GetOrCreateCell(colIndex);
}
if ( cell && cell->HasText() )
text = cell->GetText();
DoEndLabelEdit(true, wxPG_SEL_NOVALIDATE); // send event
m_selColumn = colIndex;
wxRect r = GetEditorWidgetRect(selected, m_selColumn);
wxWindow* tc = GenerateEditorTextCtrl(r.GetPosition(),
r.GetSize(),
text,
NULL,
wxTE_PROCESS_ENTER,
0,
colIndex);
wxWindowID id = tc->GetId();
tc->Connect(id, wxEVT_TEXT_ENTER,
wxCommandEventHandler(wxPropertyGrid::OnLabelEditorEnterPress),
NULL, this);
tc->Connect(id, wxEVT_KEY_DOWN,
wxKeyEventHandler(wxPropertyGrid::OnLabelEditorKeyPress),
NULL, this);
tc->SetFocus();
m_labelEditor = wxStaticCast(tc, wxTextCtrl);
m_labelEditorProperty = selected;
}
// -----------------------------------------------------------------------
void
wxPropertyGrid::OnLabelEditorEnterPress( wxCommandEvent& WXUNUSED(event) )
{
DoEndLabelEdit(true);
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnLabelEditorKeyPress( wxKeyEvent& event )
{
int keycode = event.GetKeyCode();
if ( keycode == WXK_ESCAPE )
{
DoEndLabelEdit(false);
}
else
{
HandleKeyEvent(event, true);
}
}
// -----------------------------------------------------------------------
void wxPropertyGrid::DoEndLabelEdit( bool commit, int selFlags )
{
if ( !m_labelEditor )
return;
wxPGProperty* prop = m_labelEditorProperty;
wxASSERT(prop);
if ( commit )
{
if ( !(selFlags & wxPG_SEL_DONT_SEND_EVENT) )
{
// wxPG_SEL_NOVALIDATE is passed correctly in selFlags
if ( SendEvent( wxEVT_PG_LABEL_EDIT_ENDING,
prop, NULL, selFlags,
m_selColumn ) )
return;
}
wxString text = m_labelEditor->GetValue();
wxPGCell* cell = NULL;
if ( prop->HasCell(m_selColumn) )
{
cell = &prop->GetCell(m_selColumn);
}
else
{
if ( m_selColumn == 0 )
prop->SetLabel(text);
else
cell = &prop->GetOrCreateCell(m_selColumn);
}
if ( cell )
cell->SetText(text);
}
m_selColumn = 1;
int wasFocused = m_iFlags & wxPG_FL_FOCUSED;
DestroyEditorWnd(m_labelEditor);
m_labelEditor = NULL;
m_labelEditorProperty = NULL;
// Fix focus (needed at least on wxGTK)
if ( wasFocused )
SetFocusOnCanvas();
DrawItem(prop);
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetExtraStyle( long exStyle )
{
if ( exStyle & wxPG_EX_ENABLE_TLP_TRACKING )
OnTLPChanging(::wxGetTopLevelParent(this));
else
OnTLPChanging(NULL);
if ( exStyle & wxPG_EX_NATIVE_DOUBLE_BUFFERING )
{
#if defined(__WXMSW__)
/*
// Don't use WS_EX_COMPOSITED just now.
HWND hWnd;
if ( m_iFlags & wxPG_FL_IN_MANAGER )
hWnd = (HWND)GetParent()->GetHWND();
else
hWnd = (HWND)GetHWND();
::SetWindowLong( hWnd, GWL_EXSTYLE,
::GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_COMPOSITED );
*/
//#elif defined(__WXGTK20__)
#endif
// Only apply wxPG_EX_NATIVE_DOUBLE_BUFFERING if the window
// truly was double-buffered.
if ( !this->IsDoubleBuffered() )
{
exStyle &= ~(wxPG_EX_NATIVE_DOUBLE_BUFFERING);
}
else
{
wxDELETE(m_doubleBuffer);
}
}
wxControl::SetExtraStyle( exStyle );
if ( exStyle & wxPG_EX_INIT_NOCAT )
m_pState->InitNonCatMode();
if ( exStyle & wxPG_EX_HELP_AS_TOOLTIPS )
m_windowStyle |= wxPG_TOOLTIPS;
// Set global style
wxPGGlobalVars->m_extraStyle = exStyle;
}
// -----------------------------------------------------------------------
// returns the best acceptable minimal size
wxSize wxPropertyGrid::DoGetBestSize() const
{
int lineHeight = wxMax(15, m_lineHeight);
// don't make the grid too tall (limit height to 10 items) but don't
// make it too small neither
int numLines = wxMin
(
wxMax(m_pState->m_properties->GetChildCount(), 3),
10
);
wxClientDC dc(const_cast<wxPropertyGrid *>(this));
int width = m_marginWidth;
for ( unsigned int i = 0; i < m_pState->m_colWidths.size(); i++ )
{
width += m_pState->GetColumnFitWidth(dc, m_pState->DoGetRoot(), i, true);
}
const wxSize sz = wxSize(width, lineHeight*numLines + 40);
CacheBestSize(sz);
return sz;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnTLPChanging( wxWindow* newTLP )
{
if ( newTLP == m_tlp )
return;
wxLongLong currentTime = ::wxGetLocalTimeMillis();
//
// Parent changed so let's redetermine and re-hook the
// correct top-level window.
if ( m_tlp )
{
m_tlp->Disconnect( wxEVT_CLOSE_WINDOW,
wxCloseEventHandler(wxPropertyGrid::OnTLPClose),
NULL, this );
m_tlpClosed = m_tlp;
m_tlpClosedTime = currentTime;
}
if ( newTLP )
{
// Only accept new tlp if same one was not just dismissed.
if ( newTLP != m_tlpClosed ||
m_tlpClosedTime+250 < currentTime )
{
newTLP->Connect( wxEVT_CLOSE_WINDOW,
wxCloseEventHandler(wxPropertyGrid::OnTLPClose),
NULL, this );
m_tlpClosed = NULL;
}
else
{
newTLP = NULL;
}
}
m_tlp = newTLP;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnTLPClose( wxCloseEvent& event )
{
// ClearSelection forces value validation/commit.
if ( event.CanVeto() && !DoClearSelection() )
{
event.Veto();
return;
}
// Ok, it can close, set tlp pointer to NULL. Some other event
// handler can of course veto the close, but our OnIdle() should
// then be able to regain the tlp pointer.
OnTLPChanging(NULL);
event.Skip();
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::Reparent( wxWindowBase *newParent )
{
OnTLPChanging((wxWindow*)newParent);
bool res = wxControl::Reparent(newParent);
return res;
}
// -----------------------------------------------------------------------
// wxPropertyGrid Font and Colour Methods
// -----------------------------------------------------------------------
void wxPropertyGrid::CalculateFontAndBitmapStuff( int vspacing )
{
int x = 0, y = 0;
m_captionFont = wxControl::GetFont();
GetTextExtent(wxS("jG"), &x, &y, 0, 0, &m_captionFont);
m_subgroup_extramargin = x + (x/2);
m_fontHeight = y;
#if wxPG_USE_RENDERER_NATIVE
m_iconWidth = wxPG_ICON_WIDTH;
#elif wxPG_ICON_WIDTH
// scale icon
m_iconWidth = (m_fontHeight * wxPG_ICON_WIDTH) / 13;
if ( m_iconWidth < 5 ) m_iconWidth = 5;
else if ( !(m_iconWidth & 0x01) ) m_iconWidth++; // must be odd
#endif
m_gutterWidth = m_iconWidth / wxPG_GUTTER_DIV;
if ( m_gutterWidth < wxPG_GUTTER_MIN )
m_gutterWidth = wxPG_GUTTER_MIN;
int vdiv = 6;
if ( vspacing <= 1 ) vdiv = 12;
else if ( vspacing >= 3 ) vdiv = 3;
m_spacingy = m_fontHeight / vdiv;
if ( m_spacingy < wxPG_YSPACING_MIN )
m_spacingy = wxPG_YSPACING_MIN;
m_marginWidth = 0;
if ( !(m_windowStyle & wxPG_HIDE_MARGIN) )
m_marginWidth = m_gutterWidth*2 + m_iconWidth;
m_captionFont.SetWeight(wxBOLD);
GetTextExtent(wxS("jG"), &x, &y, 0, 0, &m_captionFont);
m_lineHeight = m_fontHeight+(2*m_spacingy)+1;
// button spacing
m_buttonSpacingY = (m_lineHeight - m_iconHeight) / 2;
if ( m_buttonSpacingY < 0 ) m_buttonSpacingY = 0;
if ( m_pState )
m_pState->CalculateFontAndBitmapStuff(vspacing);
if ( m_iFlags & wxPG_FL_INITIALIZED )
RecalculateVirtualSize();
InvalidateBestSize();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnSysColourChanged( wxSysColourChangedEvent &WXUNUSED(event) )
{
if ((m_iFlags & wxPG_FL_INITIALIZED)!=0) {
RegainColours();
Refresh();
}
}
// -----------------------------------------------------------------------
static wxColour wxPGAdjustColour(const wxColour& src, int ra,
int ga = 1000, int ba = 1000,
bool forceDifferent = false)
{
if ( ga >= 1000 )
ga = ra;
if ( ba >= 1000 )
ba = ra;
// Recursion guard (allow 2 max)
static int isinside = 0;
isinside++;
wxCHECK_MSG( isinside < 3,
*wxBLACK,
wxT("wxPGAdjustColour should not be recursively called more than once") );
wxColour dst;
int r = src.Red();
int g = src.Green();
int b = src.Blue();
int r2 = r + ra;
if ( r2>255 ) r2 = 255;
else if ( r2<0) r2 = 0;
int g2 = g + ga;
if ( g2>255 ) g2 = 255;
else if ( g2<0) g2 = 0;
int b2 = b + ba;
if ( b2>255 ) b2 = 255;
else if ( b2<0) b2 = 0;
// Make sure they are somewhat different
if ( forceDifferent && (abs((r+g+b)-(r2+g2+b2)) < abs(ra/2)) )
dst = wxPGAdjustColour(src,-(ra*2));
else
dst = wxColour(r2,g2,b2);
// Recursion guard (allow 2 max)
isinside--;
return dst;
}
static int wxPGGetColAvg( const wxColour& col )
{
return (col.Red() + col.Green() + col.Blue()) / 3;
}
void wxPropertyGrid::RegainColours()
{
if ( !(m_coloursCustomized & 0x0002) )
{
wxColour col = wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE );
// Make sure colour is dark enough
#ifdef __WXGTK__
int colDec = wxPGGetColAvg(col) - 230;
#else
int colDec = wxPGGetColAvg(col) - 200;
#endif
if ( colDec > 0 )
m_colCapBack = wxPGAdjustColour(col,-colDec);
else
m_colCapBack = col;
m_categoryDefaultCell.GetData()->SetBgCol(m_colCapBack);
}
if ( !(m_coloursCustomized & 0x0001) )
m_colMargin = m_colCapBack;
if ( !(m_coloursCustomized & 0x0004) )
{
#ifdef __WXGTK__
int colDec = -90;
#else
int colDec = -72;
#endif
wxColour capForeCol = wxPGAdjustColour(m_colCapBack,colDec,5000,5000,true);
m_colCapFore = capForeCol;
m_categoryDefaultCell.GetData()->SetFgCol(capForeCol);
}
if ( !(m_coloursCustomized & 0x0008) )
{
wxColour bgCol = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW );
m_colPropBack = bgCol;
m_propertyDefaultCell.GetData()->SetBgCol(bgCol);
if ( !m_unspecifiedAppearance.GetBgCol().IsOk() )
m_unspecifiedAppearance.SetBgCol(bgCol);
}
if ( !(m_coloursCustomized & 0x0010) )
{
wxColour fgCol = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
m_colPropFore = fgCol;
m_propertyDefaultCell.GetData()->SetFgCol(fgCol);
if ( !m_unspecifiedAppearance.GetFgCol().IsOk() )
m_unspecifiedAppearance.SetFgCol(fgCol);
}
if ( !(m_coloursCustomized & 0x0020) )
m_colSelBack = wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT );
if ( !(m_coloursCustomized & 0x0040) )
m_colSelFore = wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT );
if ( !(m_coloursCustomized & 0x0080) )
m_colLine = m_colCapBack;
if ( !(m_coloursCustomized & 0x0100) )
m_colDisPropFore = m_colCapFore;
m_colEmptySpace = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW );
}
// -----------------------------------------------------------------------
void wxPropertyGrid::ResetColours()
{
m_coloursCustomized = 0;
RegainColours();
Refresh();
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::SetFont( const wxFont& font )
{
// Must disable active editor.
DoClearSelection();
bool res = wxControl::SetFont( font );
if ( res && GetParent()) // may not have been Create()ed yet if SetFont called from SetWindowVariant
{
CalculateFontAndBitmapStuff( m_vspacing );
Refresh();
}
return res;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetLineColour( const wxColour& col )
{
m_colLine = col;
m_coloursCustomized |= 0x80;
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetMarginColour( const wxColour& col )
{
m_colMargin = col;
m_coloursCustomized |= 0x01;
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetCellBackgroundColour( const wxColour& col )
{
m_colPropBack = col;
m_coloursCustomized |= 0x08;
m_propertyDefaultCell.GetData()->SetBgCol(col);
m_unspecifiedAppearance.SetBgCol(col);
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetCellTextColour( const wxColour& col )
{
m_colPropFore = col;
m_coloursCustomized |= 0x10;
m_propertyDefaultCell.GetData()->SetFgCol(col);
m_unspecifiedAppearance.SetFgCol(col);
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetEmptySpaceColour( const wxColour& col )
{
m_colEmptySpace = col;
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetCellDisabledTextColour( const wxColour& col )
{
m_colDisPropFore = col;
m_coloursCustomized |= 0x100;
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetSelectionBackgroundColour( const wxColour& col )
{
m_colSelBack = col;
m_coloursCustomized |= 0x20;
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetSelectionTextColour( const wxColour& col )
{
m_colSelFore = col;
m_coloursCustomized |= 0x40;
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetCaptionBackgroundColour( const wxColour& col )
{
m_colCapBack = col;
m_coloursCustomized |= 0x02;
m_categoryDefaultCell.GetData()->SetBgCol(col);
Refresh();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetCaptionTextColour( const wxColour& col )
{
m_colCapFore = col;
m_coloursCustomized |= 0x04;
m_categoryDefaultCell.GetData()->SetFgCol(col);
Refresh();
}
// -----------------------------------------------------------------------
// wxPropertyGrid property adding and removal
// -----------------------------------------------------------------------
void wxPropertyGrid::PrepareAfterItemsAdded()
{
if ( !m_pState || !m_pState->m_itemsAdded ) return;
m_pState->m_itemsAdded = 0;
if ( m_windowStyle & wxPG_AUTO_SORT )
Sort(wxPG_SORT_TOP_LEVEL_ONLY);
RecalculateVirtualSize();
// Fix editor position
CorrectEditorWidgetPosY();
}
// -----------------------------------------------------------------------
// wxPropertyGrid property operations
// -----------------------------------------------------------------------
bool wxPropertyGrid::EnsureVisible( wxPGPropArg id )
{
wxPG_PROP_ARG_CALL_PROLOG_RETVAL(false)
Update();
bool changed = false;
// Is it inside collapsed section?
if ( !p->IsVisible() )
{
// expand parents
wxPGProperty* parent = p->GetParent();
wxPGProperty* grandparent = parent->GetParent();
if ( grandparent && grandparent != m_pState->m_properties )
Expand( grandparent );
Expand( parent );
changed = true;
}
// Need to scroll?
int vx, vy;
GetViewStart(&vx,&vy);
vy*=wxPG_PIXELS_PER_UNIT;
int y = p->GetY();
if ( y < vy )
{
Scroll(vx, y/wxPG_PIXELS_PER_UNIT );
m_iFlags |= wxPG_FL_SCROLLED;
changed = true;
}
else if ( (y+m_lineHeight) > (vy+m_height) )
{
Scroll(vx, (y-m_height+(m_lineHeight*2))/wxPG_PIXELS_PER_UNIT );
m_iFlags |= wxPG_FL_SCROLLED;
changed = true;
}
if ( changed )
DrawItems( p, p );
return changed;
}
// -----------------------------------------------------------------------
// wxPropertyGrid helper methods called by properties
// -----------------------------------------------------------------------
// Control font changer helper.
void wxPropertyGrid::SetCurControlBoldFont()
{
wxWindow* editor = GetEditorControl();
editor->SetFont( m_captionFont );
}
// -----------------------------------------------------------------------
wxPoint wxPropertyGrid::GetGoodEditorDialogPosition( wxPGProperty* p,
const wxSize& sz )
{
#if wxPG_SMALL_SCREEN
// On small-screen devices, always show dialogs with default position and size.
return wxDefaultPosition;
#else
int splitterX = GetSplitterPosition();
int x = splitterX;
int y = p->GetY();
wxCHECK_MSG( y >= 0, wxPoint(-1,-1), wxT("invalid y?") );
ImprovedClientToScreen( &x, &y );
int sw = wxSystemSettings::GetMetric( ::wxSYS_SCREEN_X );
int sh = wxSystemSettings::GetMetric( ::wxSYS_SCREEN_Y );
int new_x;
int new_y;
if ( x > (sw/2) )
// left
new_x = x + (m_width-splitterX) - sz.x;
else
// right
new_x = x;
if ( y > (sh/2) )
// above
new_y = y - sz.y;
else
// below
new_y = y + m_lineHeight;
return wxPoint(new_x,new_y);
#endif
}
// -----------------------------------------------------------------------
wxString& wxPropertyGrid::ExpandEscapeSequences( wxString& dst_str, wxString& src_str )
{
if ( src_str.empty() )
{
dst_str = src_str;
return src_str;
}
bool prev_is_slash = false;
wxString::const_iterator i = src_str.begin();
dst_str.clear();
for ( ; i != src_str.end(); ++i )
{
wxUniChar a = *i;
if ( a != wxS('\\') )
{
if ( !prev_is_slash )
{
dst_str << a;
}
else
{
if ( a == wxS('n') )
{
#ifdef __WXMSW__
dst_str << wxS('\n');
#else
dst_str << wxS('\n');
#endif
}
else if ( a == wxS('t') )
dst_str << wxS('\t');
else
dst_str << a;
}
prev_is_slash = false;
}
else
{
if ( prev_is_slash )
{
dst_str << wxS('\\');
prev_is_slash = false;
}
else
{
prev_is_slash = true;
}
}
}
return dst_str;
}
// -----------------------------------------------------------------------
wxString& wxPropertyGrid::CreateEscapeSequences( wxString& dst_str, wxString& src_str )
{
if ( src_str.empty() )
{
dst_str = src_str;
return src_str;
}
wxString::const_iterator i = src_str.begin();
wxUniChar prev_a = wxS('\0');
dst_str.clear();
for ( ; i != src_str.end(); ++i )
{
wxChar a = *i;
if ( a >= wxS(' ') )
{
// This surely is not something that requires an escape sequence.
dst_str << a;
}
else
{
// This might need...
if ( a == wxS('\r') )
{
// DOS style line end.
// Already taken care below
}
else if ( a == wxS('\n') )
// UNIX style line end.
dst_str << wxS("\\n");
else if ( a == wxS('\t') )
// Tab.
dst_str << wxS('\t');
else
{
//wxLogDebug(wxT("WARNING: Could not create escape sequence for character #%i"),(int)a);
dst_str << a;
}
}
prev_a = a;
}
return dst_str;
}
// -----------------------------------------------------------------------
wxPGProperty* wxPropertyGrid::DoGetItemAtY( int y ) const
{
// Outside?
if ( y < 0 )
return NULL;
unsigned int a = 0;
return m_pState->m_properties->GetItemAtY(y, m_lineHeight, &a);
}
// -----------------------------------------------------------------------
// wxPropertyGrid graphics related methods
// -----------------------------------------------------------------------
void wxPropertyGrid::OnPaint( wxPaintEvent& WXUNUSED(event) )
{
wxPaintDC dc(this);
PrepareDC(dc);
// Don't paint after destruction has begun
if ( !HasInternalFlag(wxPG_FL_INITIALIZED) )
return;
// Find out where the window is scrolled to
int vx,vy; // Top left corner of client
GetViewStart(&vx,&vy);
vy *= wxPG_PIXELS_PER_UNIT;
// Update everything inside the box
wxRect r = GetUpdateRegion().GetBox();
r.y += vy;
// FIXME: This is just a workaround for a bug that causes splitters not
// to paint when other windows are being dragged over the grid.
r.x = 0;
r.width = GetClientSize().x;
r.y = vy;
r.height = GetClientSize().y;
// Repaint this rectangle
DrawItems( dc, r.y, r.y + r.height, &r );
// We assume that the size set when grid is shown
// is what is desired.
SetInternalFlag(wxPG_FL_GOOD_SIZE_SET);
}
// -----------------------------------------------------------------------
void wxPropertyGrid::DrawExpanderButton( wxDC& dc, const wxRect& rect,
wxPGProperty* property ) const
{
// Prepare rectangle to be used
wxRect r(rect);
r.x += m_gutterWidth; r.y += m_buttonSpacingY;
r.width = m_iconWidth; r.height = m_iconHeight;
#if (wxPG_USE_RENDERER_NATIVE)
//
#elif wxPG_ICON_WIDTH
// Drawing expand/collapse button manually
dc.SetPen(m_colPropFore);
if ( property->IsCategory() )
dc.SetBrush(*wxTRANSPARENT_BRUSH);
else
dc.SetBrush(m_colPropBack);
dc.DrawRectangle( r );
int _y = r.y+(m_iconWidth/2);
dc.DrawLine(r.x+2,_y,r.x+m_iconWidth-2,_y);
#else
wxBitmap* bmp;
#endif
if ( property->IsExpanded() )
{
// wxRenderer functions are non-mutating in nature, so it
// should be safe to cast "const wxPropertyGrid*" to "wxWindow*".
// Hopefully this does not cause problems.
#if (wxPG_USE_RENDERER_NATIVE)
wxRendererNative::Get().DrawTreeItemButton(
(wxWindow*)this,
dc,
r,
wxCONTROL_EXPANDED
);
#elif wxPG_ICON_WIDTH
//
#else
bmp = m_collbmp;
#endif
}
else
{
#if (wxPG_USE_RENDERER_NATIVE)
wxRendererNative::Get().DrawTreeItemButton(
(wxWindow*)this,
dc,
r,
0
);
#elif wxPG_ICON_WIDTH
int _x = r.x+(m_iconWidth/2);
dc.DrawLine(_x,r.y+2,_x,r.y+m_iconWidth-2);
#else
bmp = m_expandbmp;
#endif
}
#if (wxPG_USE_RENDERER_NATIVE)
//
#elif wxPG_ICON_WIDTH
//
#else
dc.DrawBitmap( *bmp, r.x, r.y, true );
#endif
}
// -----------------------------------------------------------------------
//
// This is the one called by OnPaint event handler and others.
// topy and bottomy are already unscrolled (ie. physical)
//
void wxPropertyGrid::DrawItems( wxDC& dc,
unsigned int topItemY,
unsigned int bottomItemY,
const wxRect* itemsRect )
{
if ( m_frozen ||
m_height < 1 ||
bottomItemY < topItemY ||
!m_pState )
return;
m_pState->EnsureVirtualHeight();
wxRect tempItemsRect;
if ( !itemsRect )
{
tempItemsRect = wxRect(0, topItemY,
m_pState->m_width,
bottomItemY);
itemsRect = &tempItemsRect;
}
int vx, vy;
GetViewStart(&vx, &vy);
vx *= wxPG_PIXELS_PER_UNIT;
vy *= wxPG_PIXELS_PER_UNIT;
// itemRect is in virtual grid space
wxRect drawRect(itemsRect->x - vx,
itemsRect->y - vy,
itemsRect->width,
itemsRect->height);
// items added check
if ( m_pState->m_itemsAdded ) PrepareAfterItemsAdded();
int paintFinishY = 0;
if ( m_pState->m_properties->GetChildCount() > 0 )
{
wxDC* dcPtr = &dc;
bool isBuffered = false;
wxMemoryDC* bufferDC = NULL;
if ( !(GetExtraStyle() & wxPG_EX_NATIVE_DOUBLE_BUFFERING) )
{
if ( !m_doubleBuffer )
{
paintFinishY = itemsRect->y;
dcPtr = NULL;
}
else
{
bufferDC = new wxMemoryDC();
// If nothing was changed, then just copy from double-buffer
bufferDC->SelectObject( *m_doubleBuffer );
dcPtr = bufferDC;
isBuffered = true;
}
}
if ( dcPtr )
{
// paintFinishY and drawBottomY are in buffer/physical space
paintFinishY = DoDrawItems( *dcPtr, itemsRect, isBuffered );
int drawBottomY = itemsRect->y + itemsRect->height - vy;
// Clear area beyond last painted property
if ( paintFinishY < drawBottomY )
{
dcPtr->SetPen(m_colEmptySpace);
dcPtr->SetBrush(m_colEmptySpace);
dcPtr->DrawRectangle(0, paintFinishY,
m_width,
drawBottomY );
}
}
if ( bufferDC )
{
dc.Blit( drawRect.x, drawRect.y, drawRect.width,
drawRect.height,
bufferDC, 0, 0, wxCOPY );
delete bufferDC;
}
}
else
{
// Just clear the area
dc.SetPen(m_colEmptySpace);
dc.SetBrush(m_colEmptySpace);
dc.DrawRectangle(drawRect);
}
}
// -----------------------------------------------------------------------
int wxPropertyGrid::DoDrawItems( wxDC& dc,
const wxRect* itemsRect,
bool isBuffered ) const
{
const wxPGProperty* firstItem;
const wxPGProperty* lastItem;
firstItem = DoGetItemAtY(itemsRect->y);
lastItem = DoGetItemAtY(itemsRect->y+itemsRect->height-1);
if ( !lastItem )
lastItem = GetLastItem( wxPG_ITERATE_VISIBLE );
if ( m_frozen || m_height < 1 || firstItem == NULL )
return itemsRect->y;
wxCHECK_MSG( !m_pState->m_itemsAdded, itemsRect->y,
"no items added" );
wxASSERT( m_pState->m_properties->GetChildCount() );
int lh = m_lineHeight;
int firstItemTopY;
int lastItemBottomY;
firstItemTopY = itemsRect->y;
lastItemBottomY = itemsRect->y + itemsRect->height;
// Align y coordinates to item boundaries
firstItemTopY -= firstItemTopY % lh;
lastItemBottomY += lh - (lastItemBottomY % lh);
lastItemBottomY -= 1;
// Entire range outside scrolled, visible area?
if ( firstItemTopY >= (int)m_pState->GetVirtualHeight() ||
lastItemBottomY <= 0 )
return itemsRect->y;
wxCHECK_MSG( firstItemTopY < lastItemBottomY,
itemsRect->y,
"invalid y values" );
/*
wxLogDebug(" -> DoDrawItems ( \"%s\" -> \"%s\"
"height=%i (ch=%i), itemsRect = 0x%lX )",
firstItem->GetLabel().c_str(),
lastItem->GetLabel().c_str(),
(int)(lastItemBottomY - firstItemTopY),
(int)m_height,
(unsigned long)&itemsRect );
*/
wxRect r;
long windowStyle = m_windowStyle;
int xRelMod = 0;
//
// For now, do some manual calculation for double buffering
// - buffer's y = 0, so align itemsRect and coordinates to that
//
// TODO: In future use wxAutoBufferedPaintDC (for example)
//
int yRelMod = 0;
wxRect cr2;
if ( isBuffered )
{
xRelMod = itemsRect->x;
yRelMod = itemsRect->y;
//
// itemsRect conversion
cr2 = *itemsRect;
cr2.x -= xRelMod;
cr2.y -= yRelMod;
itemsRect = &cr2;
firstItemTopY -= yRelMod;
lastItemBottomY -= yRelMod;
}
int x = m_marginWidth - xRelMod;
wxFont normalFont = GetFont();
bool reallyFocused = (m_iFlags & wxPG_FL_FOCUSED) != 0;
bool isPgEnabled = IsEnabled();
//
// Prepare some pens and brushes that are often changed to.
//
wxBrush marginBrush(m_colMargin);
wxPen marginPen(m_colMargin);
wxBrush capbgbrush(m_colCapBack,wxSOLID);
wxPen linepen(m_colLine,1,wxSOLID);
wxColour selBackCol;
if ( isPgEnabled )
selBackCol = m_colSelBack;
else
selBackCol = m_colMargin;
// pen that has same colour as text
wxPen outlinepen(m_colPropFore,1,wxSOLID);
//
// Clear margin with background colour
//
dc.SetBrush( marginBrush );
if ( !(windowStyle & wxPG_HIDE_MARGIN) )
{
dc.SetPen( *wxTRANSPARENT_PEN );
dc.DrawRectangle(-1-xRelMod,firstItemTopY-1,x+2,lastItemBottomY-firstItemTopY+2);
}
const wxPGProperty* firstSelected = GetSelection();
const wxPropertyGridPageState* state = m_pState;
const wxArrayInt& colWidths = state->m_colWidths;
// TODO: Only render columns that are within clipping region.
dc.SetFont(normalFont);
wxPropertyGridConstIterator it( state, wxPG_ITERATE_VISIBLE, firstItem );
int endScanBottomY = lastItemBottomY + lh;
int y = firstItemTopY;
//
// Pregenerate list of visible properties.
wxArrayPGProperty visPropArray;
visPropArray.reserve((m_height/m_lineHeight)+6);
for ( ; !it.AtEnd(); it.Next() )
{
const wxPGProperty* p = *it;
if ( !p->HasFlag(wxPG_PROP_HIDDEN) )
{
visPropArray.push_back((wxPGProperty*)p);
if ( y > endScanBottomY )
break;
y += lh;
}
}
visPropArray.push_back(NULL);
wxPGProperty* nextP = visPropArray[0];
int gridWidth = state->m_width;
y = firstItemTopY;
for ( unsigned int arrInd=1;
nextP && y <= lastItemBottomY;
arrInd++ )
{
wxPGProperty* p = nextP;
nextP = visPropArray[arrInd];
int rowHeight = m_fontHeight+(m_spacingy*2)+1;
int textMarginHere = x;
int renderFlags = 0;
int greyDepth = m_marginWidth;
if ( !(windowStyle & wxPG_HIDE_CATEGORIES) )
greyDepth = (((int)p->m_depthBgCol)-1) * m_subgroup_extramargin + m_marginWidth;
int greyDepthX = greyDepth - xRelMod;
// Use basic depth if in non-categoric mode and parent is base array.
if ( !(windowStyle & wxPG_HIDE_CATEGORIES) || p->GetParent() != m_pState->m_properties )
{
textMarginHere += ((unsigned int)((p->m_depth-1)*m_subgroup_extramargin));
}
// Paint margin area
dc.SetBrush(marginBrush);
dc.SetPen(marginPen);
dc.DrawRectangle( -xRelMod, y, greyDepth, lh );
dc.SetPen( linepen );
int y2 = y + lh;
#ifdef __WXMSW__
// Margin Edge
// Modified by JACS to not draw a margin if wxPG_HIDE_MARGIN is specified, since it
// looks better, at least under Windows when we have a themed border (the themed-window-specific
// whitespace between the real border and the propgrid margin exacerbates the double-border look).
// Is this or its parent themed?
bool suppressMarginEdge = (GetWindowStyle() & wxPG_HIDE_MARGIN) &&
(((GetWindowStyle() & wxBORDER_MASK) == wxBORDER_THEME) ||
(((GetWindowStyle() & wxBORDER_MASK) == wxBORDER_NONE) && ((GetParent()->GetWindowStyle() & wxBORDER_MASK) == wxBORDER_THEME)));
#else
bool suppressMarginEdge = false;
#endif
if (!suppressMarginEdge)
dc.DrawLine( greyDepthX, y, greyDepthX, y2 );
else
{
// Blank out the margin edge
dc.SetPen(wxPen(GetBackgroundColour()));
dc.DrawLine( greyDepthX, y, greyDepthX, y2 );
dc.SetPen( linepen );
}
// Splitters
unsigned int si;
int sx = x;
for ( si=0; si<colWidths.size(); si++ )
{
sx += colWidths[si];
dc.DrawLine( sx, y, sx, y2 );
}
// Horizontal Line, below
// (not if both this and next is category caption)
if ( p->IsCategory() &&
nextP && nextP->IsCategory() )
dc.SetPen(m_colCapBack);
dc.DrawLine( greyDepthX, y2-1, gridWidth-xRelMod, y2-1 );
//
// Need to override row colours?
wxColour rowFgCol;
wxColour rowBgCol;
bool isSelected = state->DoIsPropertySelected(p);
if ( !isSelected )
{
// Disabled may get different colour.
if ( !p->IsEnabled() )
{
renderFlags |= wxPGCellRenderer::Disabled |
wxPGCellRenderer::DontUseCellFgCol;
rowFgCol = m_colDisPropFore;
}
}
else
{
renderFlags |= wxPGCellRenderer::Selected;
if ( !p->IsCategory() )
{
renderFlags |= wxPGCellRenderer::DontUseCellFgCol |
wxPGCellRenderer::DontUseCellBgCol;
if ( reallyFocused && p == firstSelected )
{
rowFgCol = m_colSelFore;
rowBgCol = selBackCol;
}
else if ( isPgEnabled )
{
rowFgCol = m_colPropFore;
if ( p == firstSelected )
rowBgCol = m_colMargin;
else
rowBgCol = selBackCol;
}
else
{
rowFgCol = m_colDisPropFore;
rowBgCol = selBackCol;
}
}
}
wxBrush rowBgBrush;
if ( rowBgCol.IsOk() )
rowBgBrush = wxBrush(rowBgCol);
if ( HasInternalFlag(wxPG_FL_CELL_OVERRIDES_SEL) )
renderFlags = renderFlags & ~wxPGCellRenderer::DontUseCellColours;
//
// Fill additional margin area with background colour of first cell
if ( greyDepthX < textMarginHere )
{
if ( !(renderFlags & wxPGCellRenderer::DontUseCellBgCol) )
{
wxPGCell& cell = p->GetCell(0);
rowBgCol = cell.GetBgCol();
rowBgBrush = wxBrush(rowBgCol);
}
dc.SetBrush(rowBgBrush);
dc.SetPen(rowBgCol);
dc.DrawRectangle(greyDepthX+1, y,
textMarginHere-greyDepthX, lh-1);
}
bool fontChanged = false;
// Expander button rectangle
wxRect butRect( ((p->m_depth - 1) * m_subgroup_extramargin) - xRelMod,
y,
m_marginWidth,
lh );
// Default cell rect fill the entire row
wxRect cellRect(greyDepthX, y,
gridWidth - greyDepth + 2, rowHeight-1 );
bool isCategory = p->IsCategory();
if ( isCategory )
{
dc.SetFont(m_captionFont);
fontChanged = true;
if ( renderFlags & wxPGCellRenderer::DontUseCellBgCol )
{
dc.SetBrush(rowBgBrush);
dc.SetPen(rowBgCol);
}
if ( renderFlags & wxPGCellRenderer::DontUseCellFgCol )
{
dc.SetTextForeground(rowFgCol);
}
}
else
{
// Fine tune button rectangle to actually fit the cell
if ( butRect.x > 0 )
butRect.x += IN_CELL_EXPANDER_BUTTON_X_ADJUST;
if ( p->m_flags & wxPG_PROP_MODIFIED &&
(windowStyle & wxPG_BOLD_MODIFIED) )
{
dc.SetFont(m_captionFont);
fontChanged = true;
}
// Magic fine-tuning for non-category rows
cellRect.x += 1;
}
int firstCellWidth = colWidths[0] - (greyDepthX - m_marginWidth);
int firstCellX = cellRect.x;
// Calculate cellRect.x for the last cell
unsigned int ci = 0;
int cellX = x + 1;
for ( ci=0; ci<colWidths.size(); ci++ )
cellX += colWidths[ci];
cellRect.x = cellX;
// Draw cells from back to front so that we can easily tell if the
// cell on the right was empty from text
bool prevFilled = true;
ci = colWidths.size();
do
{
ci--;
int textXAdd = 0;
if ( ci == 0 )
{
textXAdd = textMarginHere - greyDepthX;
cellRect.width = firstCellWidth;
cellRect.x = firstCellX;
}
else
{
int colWidth = colWidths[ci];
cellRect.width = colWidth;
cellRect.x -= colWidth;
}
// Merge with column to the right?
if ( !prevFilled && isCategory )
{
cellRect.width += colWidths[ci+1];
}
if ( !isCategory )
cellRect.width -= 1;
wxWindow* cellEditor = NULL;
int cellRenderFlags = renderFlags;
// Tree Item Button (must be drawn before clipping is set up)
if ( ci == 0 && !HasFlag(wxPG_HIDE_MARGIN) && p->HasVisibleChildren() )
DrawExpanderButton( dc, butRect, p );
// Background
if ( isSelected && (ci == 1 || ci == m_selColumn) )
{
if ( p == firstSelected )
{
if ( ci == 1 && m_wndEditor )
cellEditor = m_wndEditor;
else if ( ci == m_selColumn && m_labelEditor )
cellEditor = m_labelEditor;
}
if ( cellEditor )
{
wxColour editorBgCol =
cellEditor->GetBackgroundColour();
dc.SetBrush(editorBgCol);
dc.SetPen(editorBgCol);
dc.SetTextForeground(m_colPropFore);
dc.DrawRectangle(cellRect);
if ( m_dragStatus != 0 ||
(m_iFlags & wxPG_FL_CUR_USES_CUSTOM_IMAGE) )
cellEditor = NULL;
}
else
{
dc.SetBrush(m_colPropBack);
dc.SetPen(m_colPropBack);
if ( p->IsEnabled() )
dc.SetTextForeground(m_colPropFore);
else
dc.SetTextForeground(m_colDisPropFore);
}
}
else
{
if ( renderFlags & wxPGCellRenderer::DontUseCellBgCol )
{
dc.SetBrush(rowBgBrush);
dc.SetPen(rowBgCol);
}
if ( renderFlags & wxPGCellRenderer::DontUseCellFgCol )
{
dc.SetTextForeground(rowFgCol);
}
}
dc.SetClippingRegion(cellRect);
cellRect.x += textXAdd;
cellRect.width -= textXAdd;
// Foreground
if ( !cellEditor )
{
wxPGCellRenderer* renderer;
int cmnVal = p->GetCommonValue();
if ( cmnVal == -1 || ci != 1 )
{
renderer = p->GetCellRenderer(ci);
prevFilled = renderer->Render(dc, cellRect, this,
p, ci, -1,
cellRenderFlags );
}
else
{
renderer = GetCommonValue(cmnVal)->GetRenderer();
prevFilled = renderer->Render(dc, cellRect, this,
p, ci, -1,
cellRenderFlags );
}
}
else
{
prevFilled = true;
}
dc.DestroyClippingRegion(); // Is this really necessary?
}
while ( ci > 0 );
if ( fontChanged )
dc.SetFont(normalFont);
y += rowHeight;
}
return y;
}
// -----------------------------------------------------------------------
wxRect wxPropertyGrid::GetPropertyRect( const wxPGProperty* p1, const wxPGProperty* p2 ) const
{
wxRect r;
if ( m_width < 10 || m_height < 10 ||
!m_pState->m_properties->GetChildCount() ||
p1 == NULL )
return wxRect(0,0,0,0);
int vy = 0;
//
// Return rect which encloses the given property range
// (in logical grid coordinates)
//
int visTop = p1->GetY();
int visBottom;
if ( p2 )
visBottom = p2->GetY() + m_lineHeight;
else
visBottom = m_height + visTop;
// If seleced property is inside the range, we'll extend the range to include
// control's size.
wxPGProperty* selected = GetSelection();
if ( selected )
{
int selectedY = selected->GetY();
if ( selectedY >= visTop && selectedY < visBottom )
{
wxWindow* editor = GetEditorControl();
if ( editor )
{
int visBottom2 = selectedY + editor->GetSize().y;
if ( visBottom2 > visBottom )
visBottom = visBottom2;
}
}
}
return wxRect(0,visTop-vy,m_pState->m_width,visBottom-visTop);
}
// -----------------------------------------------------------------------
void wxPropertyGrid::DrawItems( const wxPGProperty* p1, const wxPGProperty* p2 )
{
if ( m_frozen )
return;
if ( m_pState->m_itemsAdded )
PrepareAfterItemsAdded();
wxRect r = GetPropertyRect(p1, p2);
if ( r.width > 0 )
{
// Convert rectangle from logical grid coordinates to physical ones
int vx, vy;
GetViewStart(&vx, &vy);
vx *= wxPG_PIXELS_PER_UNIT;
vy *= wxPG_PIXELS_PER_UNIT;
r.x -= vx;
r.y -= vy;
RefreshRect(r);
}
}
// -----------------------------------------------------------------------
void wxPropertyGrid::RefreshProperty( wxPGProperty* p )
{
if ( m_pState->DoIsPropertySelected(p) || p->IsChildSelected(true) )
{
// NB: We must copy the selection.
wxArrayPGProperty selection = m_pState->m_selection;
DoSetSelection(selection, wxPG_SEL_FORCE);
}
DrawItemAndChildren(p);
}
// -----------------------------------------------------------------------
void wxPropertyGrid::DrawItemAndValueRelated( wxPGProperty* p )
{
if ( m_frozen )
return;
// Draw item, children, and parent too, if it is not category
wxPGProperty* parent = p->GetParent();
while ( parent &&
!parent->IsCategory() &&
parent->GetParent() )
{
DrawItem(parent);
parent = parent->GetParent();
}
DrawItemAndChildren(p);
}
void wxPropertyGrid::DrawItemAndChildren( wxPGProperty* p )
{
wxCHECK_RET( p, wxT("invalid property id") );
// Do not draw if in non-visible page
if ( p->GetParentState() != m_pState )
return;
// do not draw a single item if multiple pending
if ( m_pState->m_itemsAdded || m_frozen )
return;
// Update child control.
wxPGProperty* selected = GetSelection();
if ( selected && selected->GetParent() == p )
RefreshEditor();
const wxPGProperty* lastDrawn = p->GetLastVisibleSubItem();
DrawItems(p, lastDrawn);
}
// -----------------------------------------------------------------------
void wxPropertyGrid::Refresh( bool WXUNUSED(eraseBackground),
const wxRect *rect )
{
PrepareAfterItemsAdded();
wxWindow::Refresh(false, rect);
#if wxPG_REFRESH_CONTROLS
// I think this really helps only GTK+1.2
if ( m_wndEditor ) m_wndEditor->Refresh();
if ( m_wndEditor2 ) m_wndEditor2->Refresh();
#endif
}
// -----------------------------------------------------------------------
// wxPropertyGrid global operations
// -----------------------------------------------------------------------
void wxPropertyGrid::Clear()
{
m_pState->DoClear();
m_propHover = NULL;
m_prevVY = 0;
RecalculateVirtualSize();
// Need to clear some area at the end
if ( !m_frozen )
RefreshRect(wxRect(0, 0, m_width, m_height));
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::EnableCategories( bool enable )
{
DoClearSelection();
if ( enable )
{
//
// Enable categories
//
m_windowStyle &= ~(wxPG_HIDE_CATEGORIES);
}
else
{
//
// Disable categories
//
m_windowStyle |= wxPG_HIDE_CATEGORIES;
}
if ( !m_pState->EnableCategories(enable) )
return false;
if ( !m_frozen )
{
if ( m_windowStyle & wxPG_AUTO_SORT )
{
m_pState->m_itemsAdded = 1; // force
PrepareAfterItemsAdded();
}
}
else
m_pState->m_itemsAdded = 1;
// No need for RecalculateVirtualSize() here - it is already called in
// wxPropertyGridPageState method above.
Refresh();
return true;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SwitchState( wxPropertyGridPageState* pNewState )
{
wxASSERT( pNewState );
wxASSERT( pNewState->GetGrid() );
if ( pNewState == m_pState )
return;
wxArrayPGProperty oldSelection = m_pState->m_selection;
// Call ClearSelection() instead of DoClearSelection()
// so that selection clear events are not sent.
ClearSelection();
m_pState->m_selection = oldSelection;
bool orig_mode = m_pState->IsInNonCatMode();
bool new_state_mode = pNewState->IsInNonCatMode();
m_pState = pNewState;
// Validate width
int pgWidth = GetClientSize().x;
if ( HasVirtualWidth() )
{
int minWidth = pgWidth;
if ( pNewState->m_width < minWidth )
{
pNewState->m_width = minWidth;
pNewState->CheckColumnWidths();
}
}
else
{
//
// Just in case, fully re-center splitter
//if ( HasFlag( wxPG_SPLITTER_AUTO_CENTER ) )
// pNewState->m_fSplitterX = -1.0;
pNewState->OnClientWidthChange(pgWidth,
pgWidth - pNewState->m_width);
}
m_propHover = NULL;
// If necessary, convert state to correct mode.
if ( orig_mode != new_state_mode )
{
// This should refresh as well.
EnableCategories( orig_mode?false:true );
}
else if ( !m_frozen )
{
// Refresh, if not frozen.
m_pState->PrepareAfterItemsAdded();
// Reselect (Use SetSelection() instead of Do-variant so that
// events won't be sent).
SetSelection(m_pState->m_selection);
RecalculateVirtualSize(0);
Refresh();
}
else
m_pState->m_itemsAdded = 1;
}
// -----------------------------------------------------------------------
// Call to SetSplitterPosition will always disable splitter auto-centering
// if parent window is shown.
void wxPropertyGrid::DoSetSplitterPosition( int newxpos,
int splitterIndex,
int flags )
{
if ( ( newxpos < wxPG_DRAG_MARGIN ) )
return;
wxPropertyGridPageState* state = m_pState;
if ( flags & wxPG_SPLITTER_FROM_EVENT )
state->m_dontCenterSplitter = true;
state->DoSetSplitterPosition(newxpos, splitterIndex, flags);
if ( flags & wxPG_SPLITTER_REFRESH )
{
if ( GetSelection() )
CorrectEditorWidgetSizeX();
Refresh();
}
return;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::ResetColumnSizes( bool enableAutoResizing )
{
wxPropertyGridPageState* state = m_pState;
if ( state )
state->ResetColumnSizes(0);
if ( enableAutoResizing && HasFlag(wxPG_SPLITTER_AUTO_CENTER) )
m_pState->m_dontCenterSplitter = false;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::CenterSplitter( bool enableAutoResizing )
{
SetSplitterPosition( m_width/2 );
if ( enableAutoResizing && HasFlag(wxPG_SPLITTER_AUTO_CENTER) )
m_pState->m_dontCenterSplitter = false;
}
// -----------------------------------------------------------------------
// wxPropertyGrid item iteration (GetNextProperty etc.) methods
// -----------------------------------------------------------------------
// Returns nearest paint visible property (such that will be painted unless
// window is scrolled or resized). If given property is paint visible, then
// it itself will be returned
wxPGProperty* wxPropertyGrid::GetNearestPaintVisible( wxPGProperty* p ) const
{
int vx,vy1;// Top left corner of client
GetViewStart(&vx,&vy1);
vy1 *= wxPG_PIXELS_PER_UNIT;
int vy2 = vy1 + m_height;
int propY = p->GetY2(m_lineHeight);
if ( (propY + m_lineHeight) < vy1 )
{
// Too high
return DoGetItemAtY( vy1 );
}
else if ( propY > vy2 )
{
// Too low
return DoGetItemAtY( vy2 );
}
// Itself paint visible
return p;
}
// -----------------------------------------------------------------------
// Methods related to change in value, value modification and sending events
// -----------------------------------------------------------------------
// commits any changes in editor of selected property
// return true if validation did not fail
// flags are same as with DoSelectProperty
bool wxPropertyGrid::CommitChangesFromEditor( wxUint32 flags )
{
// Committing already?
if ( m_inCommitChangesFromEditor )
return true;
// Don't do this if already processing editor event. It might
// induce recursive dialogs and crap like that.
if ( m_iFlags & wxPG_FL_IN_HANDLECUSTOMEDITOREVENT )
{
if ( m_inDoPropertyChanged )
return true;
return false;
}
wxPGProperty* selected = GetSelection();
if ( m_wndEditor &&
IsEditorsValueModified() &&
(m_iFlags & wxPG_FL_INITIALIZED) &&
selected )
{
m_inCommitChangesFromEditor = true;
wxVariant variant(selected->GetValueRef());
bool valueIsPending = false;
// JACS - necessary to avoid new focus being found spuriously within OnIdle
// due to another window getting focus
wxWindow* oldFocus = m_curFocused;
bool validationFailure = false;
bool forceSuccess = (flags & (wxPG_SEL_NOVALIDATE|wxPG_SEL_FORCE)) ? true : false;
m_chgInfo_changedProperty = NULL;
// If truly modified, schedule value as pending.
if ( selected->GetEditorClass()->
GetValueFromControl( variant,
selected,
GetEditorControl() ) )
{
if ( DoEditorValidate() &&
PerformValidation(selected, variant) )
{
valueIsPending = true;
}
else
{
validationFailure = true;
}
}
else
{
EditorsValueWasNotModified();
}
m_inCommitChangesFromEditor = false;
bool res = true;
if ( validationFailure && !forceSuccess )
{
if (oldFocus)
{
oldFocus->SetFocus();
m_curFocused = oldFocus;
}
res = OnValidationFailure(selected, variant);
// Now prevent further validation failure messages
if ( res )
{
EditorsValueWasNotModified();
OnValidationFailureReset(selected);
}
}
else if ( valueIsPending )
{
DoPropertyChanged( selected, flags );
EditorsValueWasNotModified();
}
return res;
}
return true;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::PerformValidation( wxPGProperty* p, wxVariant& pendingValue,
int flags )
{
//
// Runs all validation functionality.
// Returns true if value passes all tests.
//
m_validationInfo.m_failureBehavior = m_permanentValidationFailureBehavior;
m_validationInfo.m_isFailing = true;
//
// Variant list a special value that cannot be validated
// by normal means.
if ( pendingValue.GetType() != wxPG_VARIANT_TYPE_LIST )
{
if ( !p->ValidateValue(pendingValue, m_validationInfo) )
return false;
}
//
// Adapt list to child values, if necessary
wxVariant listValue = pendingValue;
wxVariant* pPendingValue = &pendingValue;
wxVariant* pList = NULL;
// If parent has wxPG_PROP_AGGREGATE flag, or uses composite
// string value, then we need treat as it was changed instead
// (or, in addition, as is the case with composite string parent).
// This includes creating list variant for child values.
wxPGProperty* pwc = p->GetParent();
wxPGProperty* changedProperty = p;
wxPGProperty* baseChangedProperty = changedProperty;
wxVariant bcpPendingList;
listValue = pendingValue;
listValue.SetName(p->GetBaseName());
while ( pwc &&
(pwc->HasFlag(wxPG_PROP_AGGREGATE) || pwc->HasFlag(wxPG_PROP_COMPOSED_VALUE)) )
{
wxVariantList tempList;
wxVariant lv(tempList, pwc->GetBaseName());
lv.Append(listValue);
listValue = lv;
pPendingValue = &listValue;
if ( pwc->HasFlag(wxPG_PROP_AGGREGATE) )
{
baseChangedProperty = pwc;
bcpPendingList = lv;
}
changedProperty = pwc;
pwc = pwc->GetParent();
}
wxVariant value;
wxPGProperty* evtChangingProperty = changedProperty;
if ( pPendingValue->GetType() != wxPG_VARIANT_TYPE_LIST )
{
value = *pPendingValue;
}
else
{
// Convert list to child values
pList = pPendingValue;
changedProperty->AdaptListToValue( *pPendingValue, &value );
}
wxVariant evtChangingValue = value;
if ( flags & SendEvtChanging )
{
// FIXME: After proper ValueToString()s added, remove
// this. It is just a temporary fix, as evt_changing
// will simply not work for wxPG_PROP_COMPOSED_VALUE
// (unless it is selected, and textctrl editor is open).
if ( changedProperty->HasFlag(wxPG_PROP_COMPOSED_VALUE) )
{
evtChangingProperty = baseChangedProperty;
if ( evtChangingProperty != p )
{
evtChangingProperty->AdaptListToValue( bcpPendingList, &evtChangingValue );
}
else
{
evtChangingValue = pendingValue;
}
}
if ( evtChangingProperty->HasFlag(wxPG_PROP_COMPOSED_VALUE) )
{
if ( changedProperty == GetSelection() )
{
wxWindow* editor = GetEditorControl();
wxASSERT( wxDynamicCast(editor, wxTextCtrl) );
evtChangingValue = wxStaticCast(editor, wxTextCtrl)->GetValue();
}
else
{
wxLogDebug(wxT("WARNING: wxEVT_PG_CHANGING is about to happen with old value."));
}
}
}
wxASSERT( m_chgInfo_changedProperty == NULL );
m_chgInfo_changedProperty = changedProperty;
m_chgInfo_baseChangedProperty = baseChangedProperty;
m_chgInfo_pendingValue = value;
if ( pList )
m_chgInfo_valueList = *pList;
else
m_chgInfo_valueList.MakeNull();
// If changedProperty is not property which value was edited,
// then call wxPGProperty::ValidateValue() for that as well.
if ( p != changedProperty && value.GetType() != wxPG_VARIANT_TYPE_LIST )
{
if ( !changedProperty->ValidateValue(value, m_validationInfo) )
return false;
}
if ( flags & SendEvtChanging )
{
// SendEvent returns true if event was vetoed
if ( SendEvent( wxEVT_PG_CHANGING, evtChangingProperty,
&evtChangingValue ) )
return false;
}
if ( flags & IsStandaloneValidation )
{
// If called in 'generic' context, we need to reset
// m_chgInfo_changedProperty and write back translated value.
m_chgInfo_changedProperty = NULL;
pendingValue = value;
}
m_validationInfo.m_isFailing = false;
return true;
}
// -----------------------------------------------------------------------
#if wxUSE_STATUSBAR
wxStatusBar* wxPropertyGrid::GetStatusBar()
{
wxWindow* topWnd = ::wxGetTopLevelParent(this);
if ( wxDynamicCast(topWnd, wxFrame) )
{
wxFrame* pFrame = wxStaticCast(topWnd, wxFrame);
if ( pFrame )
return pFrame->GetStatusBar();
}
return NULL;
}
#endif
// -----------------------------------------------------------------------
void wxPropertyGrid::DoShowPropertyError( wxPGProperty* WXUNUSED(property), const wxString& msg )
{
if ( msg.empty() )
return;
#if wxUSE_STATUSBAR
if ( !wxPGGlobalVars->m_offline )
{
wxStatusBar* pStatusBar = GetStatusBar();
if ( pStatusBar )
{
pStatusBar->SetStatusText(msg);
return;
}
}
#endif
::wxMessageBox(msg, _("Property Error"));
}
// -----------------------------------------------------------------------
void wxPropertyGrid::DoHidePropertyError( wxPGProperty* WXUNUSED(property) )
{
#if wxUSE_STATUSBAR
if ( !wxPGGlobalVars->m_offline )
{
wxStatusBar* pStatusBar = GetStatusBar();
if ( pStatusBar )
{
pStatusBar->SetStatusText(wxEmptyString);
return;
}
}
#endif
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::OnValidationFailure( wxPGProperty* property,
wxVariant& invalidValue )
{
if ( m_inOnValidationFailure )
return true;
m_inOnValidationFailure = true;
wxON_BLOCK_EXIT_SET(m_inOnValidationFailure, false);
wxWindow* editor = GetEditorControl();
int vfb = m_validationInfo.m_failureBehavior;
if ( m_inDoSelectProperty )
{
// When property selection is being changed, do not display any
// messages, if some were already shown for this property.
if ( property->HasFlag(wxPG_PROP_INVALID_VALUE) )
{
m_validationInfo.m_failureBehavior =
vfb & ~(wxPG_VFB_SHOW_MESSAGE |
wxPG_VFB_SHOW_MESSAGEBOX |
wxPG_VFB_SHOW_MESSAGE_ON_STATUSBAR);
}
}
// First call property's handler
property->OnValidationFailure(invalidValue);
bool res = DoOnValidationFailure(property, invalidValue);
//
// For non-wxTextCtrl editors, we do need to revert the value
if ( !wxDynamicCast(editor, wxTextCtrl) &&
property == GetSelection() )
{
property->GetEditorClass()->UpdateControl(property, editor);
}
property->SetFlag(wxPG_PROP_INVALID_VALUE);
return res;
}
bool wxPropertyGrid::DoOnValidationFailure( wxPGProperty* property, wxVariant& WXUNUSED(invalidValue) )
{
int vfb = m_validationInfo.m_failureBehavior;
if ( vfb & wxPG_VFB_BEEP )
::wxBell();
if ( (vfb & wxPG_VFB_MARK_CELL) &&
!property->HasFlag(wxPG_PROP_INVALID_VALUE) )
{
unsigned int colCount = m_pState->GetColumnCount();
// We need backup marked property's cells
m_propCellsBackup = property->m_cells;
wxColour vfbFg = *wxWHITE;
wxColour vfbBg = *wxRED;
property->EnsureCells(colCount);
for ( unsigned int i=0; i<colCount; i++ )
{
wxPGCell& cell = property->m_cells[i];
cell.SetFgCol(vfbFg);
cell.SetBgCol(vfbBg);
}
DrawItemAndChildren(property);
if ( property == GetSelection() )
{
SetInternalFlag(wxPG_FL_CELL_OVERRIDES_SEL);
wxWindow* editor = GetEditorControl();
if ( editor )
{
editor->SetForegroundColour(vfbFg);
editor->SetBackgroundColour(vfbBg);
}
}
}
if ( vfb & (wxPG_VFB_SHOW_MESSAGE |
wxPG_VFB_SHOW_MESSAGEBOX |
wxPG_VFB_SHOW_MESSAGE_ON_STATUSBAR) )
{
wxString msg = m_validationInfo.m_failureMessage;
if ( msg.empty() )
msg = _("You have entered invalid value. Press ESC to cancel editing.");
#if wxUSE_STATUSBAR
if ( vfb & wxPG_VFB_SHOW_MESSAGE_ON_STATUSBAR )
{
if ( !wxPGGlobalVars->m_offline )
{
wxStatusBar* pStatusBar = GetStatusBar();
if ( pStatusBar )
pStatusBar->SetStatusText(msg);
}
}
#endif
if ( vfb & wxPG_VFB_SHOW_MESSAGE )
DoShowPropertyError(property, msg);
if ( vfb & wxPG_VFB_SHOW_MESSAGEBOX )
::wxMessageBox(msg, _("Property Error"));
}
return (vfb & wxPG_VFB_STAY_IN_PROPERTY) ? false : true;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::DoOnValidationFailureReset( wxPGProperty* property )
{
int vfb = m_validationInfo.m_failureBehavior;
if ( vfb & wxPG_VFB_MARK_CELL )
{
// Revert cells
property->m_cells = m_propCellsBackup;
ClearInternalFlag(wxPG_FL_CELL_OVERRIDES_SEL);
if ( property == GetSelection() && GetEditorControl() )
{
// Calling this will recreate the control, thus resetting its colour
RefreshProperty(property);
}
else
{
DrawItemAndChildren(property);
}
}
#if wxUSE_STATUSBAR
if ( vfb & wxPG_VFB_SHOW_MESSAGE_ON_STATUSBAR )
{
if ( !wxPGGlobalVars->m_offline )
{
wxStatusBar* pStatusBar = GetStatusBar();
if ( pStatusBar )
pStatusBar->SetStatusText(wxEmptyString);
}
}
#endif
if ( vfb & wxPG_VFB_SHOW_MESSAGE )
{
DoHidePropertyError(property);
}
m_validationInfo.m_isFailing = false;
}
// -----------------------------------------------------------------------
// flags are same as with DoSelectProperty
bool wxPropertyGrid::DoPropertyChanged( wxPGProperty* p, unsigned int selFlags )
{
if ( m_inDoPropertyChanged )
return true;
m_inDoPropertyChanged = true;
wxON_BLOCK_EXIT_SET(m_inDoPropertyChanged, false);
wxPGProperty* selected = GetSelection();
m_pState->m_anyModified = 1;
// If property's value is being changed, assume it is valid
OnValidationFailureReset(selected);
// Maybe need to update control
wxASSERT( m_chgInfo_changedProperty != NULL );
// These values were calculated in PerformValidation()
wxPGProperty* changedProperty = m_chgInfo_changedProperty;
wxVariant value = m_chgInfo_pendingValue;
wxPGProperty* topPaintedProperty = changedProperty;
while ( !topPaintedProperty->IsCategory() &&
!topPaintedProperty->IsRoot() )
{
topPaintedProperty = topPaintedProperty->GetParent();
}
changedProperty->SetValue(value, &m_chgInfo_valueList, wxPG_SETVAL_BY_USER);
// NB: Call GetEditorControl() as late as possible, because OnSetValue()
// and perhaps other user-defined virtual functions may change it.
wxWindow* editor = GetEditorControl();
// Set as Modified (not if dragging just began)
if ( !(p->m_flags & wxPG_PROP_MODIFIED) )
{
p->m_flags |= wxPG_PROP_MODIFIED;
if ( p == selected && (m_windowStyle & wxPG_BOLD_MODIFIED) )
{
if ( editor )
SetCurControlBoldFont();
}
}
wxPGProperty* pwc;
// Propagate updates to parent(s)
pwc = p;
wxPGProperty* prevPwc = NULL;
while ( prevPwc != topPaintedProperty )
{
pwc->m_flags |= wxPG_PROP_MODIFIED;
if ( pwc == selected && (m_windowStyle & wxPG_BOLD_MODIFIED) )
{
if ( editor )
SetCurControlBoldFont();
}
prevPwc = pwc;
pwc = pwc->GetParent();
}
// Draw the actual property
DrawItemAndChildren( topPaintedProperty );
//
// If value was set by wxPGProperty::OnEvent, then update the editor
// control.
if ( selFlags & wxPG_SEL_DIALOGVAL )
{
RefreshEditor();
}
else
{
#if wxPG_REFRESH_CONTROLS
if ( m_wndEditor ) m_wndEditor->Refresh();
if ( m_wndEditor2 ) m_wndEditor2->Refresh();
#endif
}
// Sanity check
wxASSERT( !changedProperty->GetParent()->HasFlag(wxPG_PROP_AGGREGATE) );
// If top parent has composite string value, then send to child parents,
// starting from baseChangedProperty.
if ( changedProperty->HasFlag(wxPG_PROP_COMPOSED_VALUE) )
{
pwc = m_chgInfo_baseChangedProperty;
while ( pwc != changedProperty )
{
SendEvent( wxEVT_PG_CHANGED, pwc, NULL );
pwc = pwc->GetParent();
}
}
SendEvent( wxEVT_PG_CHANGED, changedProperty, NULL );
return true;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::ChangePropertyValue( wxPGPropArg id, wxVariant newValue )
{
wxPG_PROP_ARG_CALL_PROLOG_RETVAL(false)
m_chgInfo_changedProperty = NULL;
if ( PerformValidation(p, newValue) )
{
DoPropertyChanged(p);
return true;
}
else
{
OnValidationFailure(p, newValue);
}
return false;
}
// -----------------------------------------------------------------------
wxVariant wxPropertyGrid::GetUncommittedPropertyValue()
{
wxPGProperty* prop = GetSelectedProperty();
if ( !prop )
return wxNullVariant;
wxTextCtrl* tc = GetEditorTextCtrl();
wxVariant value = prop->GetValue();
if ( !tc || !IsEditorsValueModified() )
return value;
if ( !prop->StringToValue(value, tc->GetValue()) )
return value;
if ( !PerformValidation(prop, value, IsStandaloneValidation) )
return prop->GetValue();
return value;
}
// -----------------------------------------------------------------------
// Runs wxValidator for the selected property
bool wxPropertyGrid::DoEditorValidate()
{
#if wxUSE_VALIDATORS
wxRecursionGuard guard(m_validatingEditor);
if ( guard.IsInside() )
return false;
wxPGProperty* selected = GetSelection();
if ( selected )
{
wxWindow* wnd = GetEditorControl();
wxValidator* validator = selected->GetValidator();
if ( validator && wnd )
{
validator->SetWindow(wnd);
if ( !validator->Validate(this) )
return false;
}
}
#endif
return true;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::HandleCustomEditorEvent( wxEvent &event )
{
//
// NB: We should return true if the event was recognized as
// a dedicated wxPropertyGrid event, and as such was
// either properly handled or ignored.
//
// It is possible that this handler receives event even before
// the control has been properly initialized. Let's skip the
// event handling in that case.
if ( !m_pState )
return false;
// Don't care about the event if it originated from the
// 'label editor'. In this function we only care about the
// property value editor.
if ( m_labelEditor && event.GetId() == m_labelEditor->GetId() )
{
event.Skip();
return true;
}
wxPGProperty* selected = GetSelection();
// Somehow, event is handled after property has been deselected.
// Possibly, but very rare.
if ( !selected ||
selected->HasFlag(wxPG_PROP_BEING_DELETED) ||
m_inOnValidationFailure ||
// Also don't handle editor event if wxEVT_PG_CHANGED or
// similar is currently doing something (showing a
// message box, for instance).
m_processedEvent )
return true;
if ( m_iFlags & wxPG_FL_IN_HANDLECUSTOMEDITOREVENT )
return true;
wxVariant pendingValue(selected->GetValueRef());
wxWindow* wnd = GetEditorControl();
wxWindow* editorWnd = wxDynamicCast(event.GetEventObject(), wxWindow);
int selFlags = 0;
bool wasUnspecified = selected->IsValueUnspecified();
int usesAutoUnspecified = selected->UsesAutoUnspecified();
bool valueIsPending = false;
m_chgInfo_changedProperty = NULL;
m_iFlags &= ~wxPG_FL_VALUE_CHANGE_IN_EVENT;
//
// Filter out excess wxTextCtrl modified events
if ( event.GetEventType() == wxEVT_TEXT && wnd )
{
if ( wxDynamicCast(wnd, wxTextCtrl) )
{
wxTextCtrl* tc = (wxTextCtrl*) wnd;
wxString newTcValue = tc->GetValue();
if ( m_prevTcValue == newTcValue )
return true;
m_prevTcValue = newTcValue;
}
else if ( wxDynamicCast(wnd, wxComboCtrl) )
{
// In some cases we might stumble unintentionally on
// wxComboCtrl's embedded wxTextCtrl's events. Let's
// avoid them.
if ( wxDynamicCast(editorWnd, wxTextCtrl) )
return false;
wxComboCtrl* cc = (wxComboCtrl*) wnd;
wxString newTcValue = cc->GetTextCtrl()->GetValue();
if ( m_prevTcValue == newTcValue )
return true;
m_prevTcValue = newTcValue;
}
}
SetInternalFlag(wxPG_FL_IN_HANDLECUSTOMEDITOREVENT);
bool validationFailure = false;
bool buttonWasHandled = false;
bool result = false;
//
// Try common button handling
if ( m_wndEditor2 && event.GetEventType() == wxEVT_BUTTON )
{
wxPGEditorDialogAdapter* adapter = selected->GetEditorDialog();
if ( adapter )
{
buttonWasHandled = true;
// Store as res2, as previously (and still currently alternatively)
// dialogs can be shown by handling wxEVT_BUTTON
// in wxPGProperty::OnEvent().
adapter->ShowDialog( this, selected );
delete adapter;
}
}
if ( !buttonWasHandled )
{
if ( wnd || m_wndEditor2 )
{
// First call editor class' event handler.
const wxPGEditor* editor = selected->GetEditorClass();
if ( editor->OnEvent( this, selected, editorWnd, event ) )
{
result = true;
// If changes, validate them
if ( DoEditorValidate() )
{
if ( editor->GetValueFromControl( pendingValue,
selected,
wnd ) )
valueIsPending = true;
// Mark value always as pending if validation is currently
// failing and value was not unspecified
if ( !valueIsPending &&
!pendingValue.IsNull() &&
m_validationInfo.m_isFailing )
valueIsPending = true;
}
else
{
validationFailure = true;
}
}
}
// Then the property's custom handler (must be always called, unless
// validation failed).
if ( !validationFailure )
buttonWasHandled = selected->OnEvent( this, editorWnd, event );
}
// SetValueInEvent(), as called in one of the functions referred above
// overrides editor's value.
if ( m_iFlags & wxPG_FL_VALUE_CHANGE_IN_EVENT )
{
valueIsPending = true;
pendingValue = m_changeInEventValue;
selFlags |= wxPG_SEL_DIALOGVAL;
}
if ( !validationFailure && valueIsPending )
if ( !PerformValidation(selected, pendingValue) )
validationFailure = true;
if ( validationFailure)
{
OnValidationFailure(selected, pendingValue);
}
else if ( valueIsPending )
{
selFlags |= ( !wasUnspecified && selected->IsValueUnspecified() && usesAutoUnspecified ) ? wxPG_SEL_SETUNSPEC : 0;
DoPropertyChanged(selected, selFlags);
EditorsValueWasNotModified();
// Regardless of editor type, unfocus editor on
// text-editing related enter press.
if ( event.GetEventType() == wxEVT_TEXT_ENTER )
{
SetFocusOnCanvas();
}
}
else
{
// No value after all
// Regardless of editor type, unfocus editor on
// text-editing related enter press.
if ( event.GetEventType() == wxEVT_TEXT_ENTER )
{
SetFocusOnCanvas();
}
// Let unhandled button click events go to the parent
if ( !buttonWasHandled && event.GetEventType() == wxEVT_BUTTON )
{
result = true;
wxCommandEvent evt(wxEVT_BUTTON,GetId());
GetEventHandler()->AddPendingEvent(evt);
}
}
ClearInternalFlag(wxPG_FL_IN_HANDLECUSTOMEDITOREVENT);
return result;
}
// -----------------------------------------------------------------------
// wxPropertyGrid editor control helper methods
// -----------------------------------------------------------------------
wxRect wxPropertyGrid::GetEditorWidgetRect( wxPGProperty* p, int column ) const
{
int itemy = p->GetY2(m_lineHeight);
int splitterX = m_pState->DoGetSplitterPosition(column-1);
int colEnd = splitterX + m_pState->m_colWidths[column];
int imageOffset = 0;
int vx, vy; // Top left corner of client
GetViewStart(&vx, &vy);
vy *= wxPG_PIXELS_PER_UNIT;
if ( column == 1 )
{
// TODO: If custom image detection changes from current, change this.
if ( m_iFlags & wxPG_FL_CUR_USES_CUSTOM_IMAGE )
{
//m_iFlags |= wxPG_FL_CUR_USES_CUSTOM_IMAGE;
int iw = p->OnMeasureImage().x;
if ( iw < 1 )
iw = wxPG_CUSTOM_IMAGE_WIDTH;
imageOffset = p->GetImageOffset(iw);
}
}
else if ( column == 0 )
{
splitterX += (p->m_depth - 1) * m_subgroup_extramargin;
}
return wxRect
(
splitterX+imageOffset+wxPG_XBEFOREWIDGET+wxPG_CONTROL_MARGIN+1,
itemy-vy,
colEnd-splitterX-wxPG_XBEFOREWIDGET-wxPG_CONTROL_MARGIN-imageOffset-1,
m_lineHeight-1
);
}
// -----------------------------------------------------------------------
wxRect wxPropertyGrid::GetImageRect( wxPGProperty* p, int item ) const
{
wxSize sz = GetImageSize(p, item);
return wxRect(wxPG_CONTROL_MARGIN + wxCC_CUSTOM_IMAGE_MARGIN1,
wxPG_CUSTOM_IMAGE_SPACINGY,
sz.x,
sz.y);
}
// return size of custom paint image
wxSize wxPropertyGrid::GetImageSize( wxPGProperty* p, int item ) const
{
// If called with NULL property, then return default image
// size for properties that use image.
if ( !p )
return wxSize(wxPG_CUSTOM_IMAGE_WIDTH,wxPG_STD_CUST_IMAGE_HEIGHT(m_lineHeight));
wxSize cis = p->OnMeasureImage(item);
int choiceCount = p->m_choices.GetCount();
int comVals = p->GetDisplayedCommonValueCount();
if ( item >= choiceCount && comVals > 0 )
{
unsigned int cvi = item-choiceCount;
cis = GetCommonValue(cvi)->GetRenderer()->GetImageSize(NULL, 1, cvi);
}
else if ( item >= 0 && choiceCount == 0 )
return wxSize(0, 0);
if ( cis.x < 0 )
{
if ( cis.x <= -1 )
cis.x = wxPG_CUSTOM_IMAGE_WIDTH;
}
if ( cis.y <= 0 )
{
if ( cis.y >= -1 )
cis.y = wxPG_STD_CUST_IMAGE_HEIGHT(m_lineHeight);
else
cis.y = -cis.y;
}
return cis;
}
// -----------------------------------------------------------------------
// takes scrolling into account
void wxPropertyGrid::ImprovedClientToScreen( int* px, int* py )
{
int vx, vy;
GetViewStart(&vx,&vy);
vy*=wxPG_PIXELS_PER_UNIT;
vx*=wxPG_PIXELS_PER_UNIT;
*px -= vx;
*py -= vy;
ClientToScreen( px, py );
}
// -----------------------------------------------------------------------
wxPropertyGridHitTestResult wxPropertyGrid::HitTest( const wxPoint& pt ) const
{
wxPoint pt2;
GetViewStart(&pt2.x,&pt2.y);
pt2.x *= wxPG_PIXELS_PER_UNIT;
pt2.y *= wxPG_PIXELS_PER_UNIT;
pt2.x += pt.x;
pt2.y += pt.y;
return m_pState->HitTest(pt2);
}
// -----------------------------------------------------------------------
// custom set cursor
void wxPropertyGrid::CustomSetCursor( int type, bool override )
{
if ( type == m_curcursor && !override ) return;
wxCursor* cursor = &wxPG_DEFAULT_CURSOR;
if ( type == wxCURSOR_SIZEWE )
cursor = m_cursorSizeWE;
SetCursor( *cursor );
m_curcursor = type;
}
// -----------------------------------------------------------------------
wxString
wxPropertyGrid::GetUnspecifiedValueText( int argFlags ) const
{
const wxPGCell& ua = GetUnspecifiedValueAppearance();
if ( ua.HasText() &&
!(argFlags & wxPG_FULL_VALUE) &&
!(argFlags & wxPG_EDITABLE_VALUE) )
return ua.GetText();
return wxEmptyString;
}
// -----------------------------------------------------------------------
// wxPropertyGrid property selection, editor creation
// -----------------------------------------------------------------------
//
// This class forwards events from property editor controls to wxPropertyGrid.
class wxPropertyGridEditorEventForwarder : public wxEvtHandler
{
public:
wxPropertyGridEditorEventForwarder( wxPropertyGrid* propGrid )
: wxEvtHandler(), m_propGrid(propGrid)
{
}
virtual ~wxPropertyGridEditorEventForwarder()
{
}
private:
bool ProcessEvent( wxEvent& event )
{
// Always skip
event.Skip();
m_propGrid->HandleCustomEditorEvent(event);
//
// NB: We should return true if the event was recognized as
// a dedicated wxPropertyGrid event, and as such was
// either properly handled or ignored.
//
if ( m_propGrid->IsMainButtonEvent(event) )
return true;
//
// NB: On wxMSW, a wxTextCtrl with wxTE_PROCESS_ENTER
// may beep annoyingly if that event is skipped
// and passed to parent event handler.
if ( event.GetEventType() == wxEVT_TEXT_ENTER )
return true;
return wxEvtHandler::ProcessEvent(event);
}
wxPropertyGrid* m_propGrid;
};
// Setups event handling for child control
void wxPropertyGrid::SetupChildEventHandling( wxWindow* argWnd )
{
wxWindowID id = argWnd->GetId();
if ( argWnd == m_wndEditor )
{
argWnd->Connect(id, wxEVT_MOTION,
wxMouseEventHandler(wxPropertyGrid::OnMouseMoveChild),
NULL, this);
argWnd->Connect(id, wxEVT_LEFT_UP,
wxMouseEventHandler(wxPropertyGrid::OnMouseUpChild),
NULL, this);
argWnd->Connect(id, wxEVT_LEFT_DOWN,
wxMouseEventHandler(wxPropertyGrid::OnMouseClickChild),
NULL, this);
argWnd->Connect(id, wxEVT_RIGHT_UP,
wxMouseEventHandler(wxPropertyGrid::OnMouseRightClickChild),
NULL, this);
argWnd->Connect(id, wxEVT_ENTER_WINDOW,
wxMouseEventHandler(wxPropertyGrid::OnMouseEntry),
NULL, this);
argWnd->Connect(id, wxEVT_LEAVE_WINDOW,
wxMouseEventHandler(wxPropertyGrid::OnMouseEntry),
NULL, this);
}
wxPropertyGridEditorEventForwarder* forwarder;
forwarder = new wxPropertyGridEditorEventForwarder(this);
argWnd->PushEventHandler(forwarder);
argWnd->Connect(id, wxEVT_KEY_DOWN,
wxCharEventHandler(wxPropertyGrid::OnChildKeyDown),
NULL, this);
}
void wxPropertyGrid::DestroyEditorWnd( wxWindow* wnd )
{
if ( !wnd )
return;
wnd->Hide();
// Do not free editors immediately (for sake of processing events)
wxPendingDelete.Append(wnd);
}
void wxPropertyGrid::FreeEditors()
{
//
// Return focus back to canvas from children (this is required at least for
// GTK+, which, unlike Windows, clears focus when control is destroyed
// instead of moving it to closest parent).
SetFocusOnCanvas();
// Do not free editors immediately if processing events
if ( m_wndEditor2 )
{
wxEvtHandler* handler = m_wndEditor2->PopEventHandler(false);
m_wndEditor2->Hide();
wxPendingDelete.Append( handler );
DestroyEditorWnd(m_wndEditor2);
m_wndEditor2 = NULL;
}
if ( m_wndEditor )
{
wxEvtHandler* handler = m_wndEditor->PopEventHandler(false);
m_wndEditor->Hide();
wxPendingDelete.Append( handler );
DestroyEditorWnd(m_wndEditor);
m_wndEditor = NULL;
}
}
// Call with NULL to de-select property
bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
{
/*
if (p)
{
wxLogDebug(wxT("SelectProperty( %s (%s[%i]) )"),p->m_label.c_str(),
p->m_parent->m_label.c_str(),p->GetIndexInParent());
}
else
{
wxLogDebug(wxT("SelectProperty( NULL, -1 )"));
}
*/
if ( m_inDoSelectProperty )
return true;
m_inDoSelectProperty = true;
wxON_BLOCK_EXIT_SET(m_inDoSelectProperty, false);
if ( !m_pState )
return false;
wxArrayPGProperty prevSelection = m_pState->m_selection;
wxPGProperty* prevFirstSel;
if ( prevSelection.size() > 0 )
prevFirstSel = prevSelection[0];
else
prevFirstSel = NULL;
if ( prevFirstSel && prevFirstSel->HasFlag(wxPG_PROP_BEING_DELETED) )
prevFirstSel = NULL;
// Always send event, as this is indirect call
DoEndLabelEdit(true, wxPG_SEL_NOVALIDATE);
/*
if ( prevFirstSel )
wxPrintf( "Selected %s\n", prevFirstSel->GetClassInfo()->GetClassName() );
else
wxPrintf( "None selected\n" );
if (p)
wxPrintf( "P = %s\n", p->GetClassInfo()->GetClassName() );
else
wxPrintf( "P = NULL\n" );
*/
wxWindow* primaryCtrl = NULL;
// If we are frozen, then just set the values.
if ( m_frozen )
{
m_iFlags &= ~(wxPG_FL_ABNORMAL_EDITOR);
m_editorFocused = 0;
m_pState->DoSetSelection(p);
// If frozen, always free controls. But don't worry, as Thaw will
// recall SelectProperty to recreate them.
FreeEditors();
// Prevent any further selection measures in this call
p = NULL;
}
else
{
// Is it the same?
if ( prevFirstSel == p &&
prevSelection.size() <= 1 &&
!(flags & wxPG_SEL_FORCE) )
{
// Only set focus if not deselecting
if ( p )
{
if ( flags & wxPG_SEL_FOCUS )
{
if ( m_wndEditor )
{
m_wndEditor->SetFocus();
m_editorFocused = 1;
}
}
else
{
SetFocusOnCanvas();
}
}
return true;
}
//
// First, deactivate previous
if ( prevFirstSel )
{
// Must double-check if this is an selected in case of forceswitch
if ( p != prevFirstSel )
{
if ( !CommitChangesFromEditor(flags) )
{
// Validation has failed, so we can't exit the previous editor
//::wxMessageBox(_("Please correct the value or press ESC to cancel the edit."),
// _("Invalid Value"),wxOK|wxICON_ERROR);
return false;
}
}
// This should be called after CommitChangesFromEditor(), so that
// OnValidationFailure() still has information on property's
// validation state.
OnValidationFailureReset(prevFirstSel);
FreeEditors();
m_iFlags &= ~(wxPG_FL_ABNORMAL_EDITOR);
EditorsValueWasNotModified();
}
SetInternalFlag(wxPG_FL_IN_SELECT_PROPERTY);
m_pState->DoSetSelection(p);
// Redraw unselected
for ( unsigned int i=0; i<prevSelection.size(); i++ )
{
DrawItem(prevSelection[i]);
}
//
// Then, activate the one given.
if ( p )
{
int propY = p->GetY2(m_lineHeight);
int splitterX = GetSplitterPosition();
m_editorFocused = 0;
m_iFlags |= wxPG_FL_PRIMARY_FILLS_ENTIRE;
wxASSERT( m_wndEditor == NULL );
//
// Only create editor for non-disabled non-caption
if ( !p->IsCategory() && !(p->m_flags & wxPG_PROP_DISABLED) )
{
// do this for non-caption items
m_selColumn = 1;
// Do we need to paint the custom image, if any?
m_iFlags &= ~(wxPG_FL_CUR_USES_CUSTOM_IMAGE);
if ( (p->m_flags & wxPG_PROP_CUSTOMIMAGE) &&
!p->GetEditorClass()->CanContainCustomImage()
)
m_iFlags |= wxPG_FL_CUR_USES_CUSTOM_IMAGE;
wxRect grect = GetEditorWidgetRect(p, m_selColumn);
wxPoint goodPos = grect.GetPosition();
// Editor appearance can now be considered clear
m_editorAppearance.SetEmptyData();
const wxPGEditor* editor = p->GetEditorClass();
wxCHECK_MSG(editor, false,
wxT("NULL editor class not allowed"));
m_iFlags &= ~wxPG_FL_FIXED_WIDTH_EDITOR;
wxPGWindowList wndList =
editor->CreateControls(this,
p,
goodPos,
grect.GetSize());
m_wndEditor = wndList.m_primary;
m_wndEditor2 = wndList.m_secondary;
primaryCtrl = GetEditorControl();
//
// Essentially, primaryCtrl == m_wndEditor
//
// NOTE: It is allowed for m_wndEditor to be NULL - in this
// case value is drawn as normal, and m_wndEditor2 is
// assumed to be a right-aligned button that triggers
// a separate editorCtrl window.
if ( m_wndEditor )
{
wxASSERT_MSG( m_wndEditor->GetParent() == GetPanel(),
"CreateControls must use result of "
"wxPropertyGrid::GetPanel() as parent "
"of controls." );
// Set validator, if any
#if wxUSE_VALIDATORS
wxValidator* validator = p->GetValidator();
if ( validator )
primaryCtrl->SetValidator(*validator);
#endif
if ( m_wndEditor->GetSize().y > (m_lineHeight+6) )
m_iFlags |= wxPG_FL_ABNORMAL_EDITOR;
// If it has modified status, use bold font
// (must be done before capturing m_ctrlXAdjust)
if ( (p->m_flags & wxPG_PROP_MODIFIED) &&
(m_windowStyle & wxPG_BOLD_MODIFIED) )
SetCurControlBoldFont();
// Store x relative to splitter (we'll need it).
m_ctrlXAdjust = m_wndEditor->GetPosition().x - splitterX;
// Check if background clear is not necessary
wxPoint pos = m_wndEditor->GetPosition();
if ( pos.x > (splitterX+1) || pos.y > propY )
{
m_iFlags &= ~(wxPG_FL_PRIMARY_FILLS_ENTIRE);
}
m_wndEditor->SetSizeHints(3, 3);
SetupChildEventHandling(primaryCtrl);
// Focus and select all (wxTextCtrl, wxComboBox etc)
if ( flags & wxPG_SEL_FOCUS )
{
primaryCtrl->SetFocus();
p->GetEditorClass()->OnFocus(p, primaryCtrl);
}
else
{
if ( p->IsValueUnspecified() )
SetEditorAppearance(m_unspecifiedAppearance,
true);
}
}
if ( m_wndEditor2 )
{
wxASSERT_MSG( m_wndEditor2->GetParent() == GetPanel(),
"CreateControls must use result of "
"wxPropertyGrid::GetPanel() as parent "
"of controls." );
// Get proper id for wndSecondary
m_wndSecId = m_wndEditor2->GetId();
wxWindowList children = m_wndEditor2->GetChildren();
wxWindowList::iterator node = children.begin();
if ( node != children.end() )
m_wndSecId = ((wxWindow*)*node)->GetId();
m_wndEditor2->SetSizeHints(3,3);
m_wndEditor2->Show();
SetupChildEventHandling(m_wndEditor2);
// If no primary editor, focus to button to allow
// it to interprete ENTER etc.
// NOTE: Due to problems focusing away from it, this
// has been disabled.
/*
if ( (flags & wxPG_SEL_FOCUS) && !m_wndEditor )
m_wndEditor2->SetFocus();
*/
}
if ( flags & wxPG_SEL_FOCUS )
m_editorFocused = 1;
}
else
{
// Make sure focus is in grid canvas (important for wxGTK,
// at least)
SetFocusOnCanvas();
}
EditorsValueWasNotModified();
// If it's inside collapsed section, expand parent, scroll, etc.
// Also, if it was partially visible, scroll it into view.
if ( !(flags & wxPG_SEL_NONVISIBLE) )
EnsureVisible( p );
if ( m_wndEditor )
{
m_wndEditor->Show(true);
}
if ( !(flags & wxPG_SEL_NO_REFRESH) )
DrawItem(p);
}
else
{
// Make sure focus is in grid canvas
SetFocusOnCanvas();
}
ClearInternalFlag(wxPG_FL_IN_SELECT_PROPERTY);
}
const wxString* pHelpString = NULL;
if ( p )
pHelpString = &p->GetHelpString();
if ( !(GetExtraStyle() & wxPG_EX_HELP_AS_TOOLTIPS) )
{
#if wxUSE_STATUSBAR
//
// Show help text in status bar.
// (if found and grid not embedded in manager with help box and
// style wxPG_EX_HELP_AS_TOOLTIPS is not used).
//
wxStatusBar* statusbar = GetStatusBar();
if ( statusbar )
{
if ( pHelpString && !pHelpString->empty() )
{
// Set help box text.
statusbar->SetStatusText( *pHelpString );
m_iFlags |= wxPG_FL_STRING_IN_STATUSBAR;
}
else if ( m_iFlags & wxPG_FL_STRING_IN_STATUSBAR )
{
// Clear help box - but only if it was written
// by us at previous time.
statusbar->SetStatusText( m_emptyString );
m_iFlags &= ~(wxPG_FL_STRING_IN_STATUSBAR);
}
}
#endif
}
else
{
#if wxPG_SUPPORT_TOOLTIPS
//
// Show help as a tool tip on the editor control.
//
if ( pHelpString && !pHelpString->empty() &&
primaryCtrl )
{
primaryCtrl->SetToolTip(*pHelpString);
}
#endif
}
// call wx event handler (here so that it also occurs on deselection)
if ( !(flags & wxPG_SEL_DONT_SEND_EVENT) )
SendEvent( wxEVT_PG_SELECTED, p, NULL );
return true;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::UnfocusEditor()
{
wxPGProperty* selected = GetSelection();
if ( !selected || !m_wndEditor || m_frozen )
return true;
if ( !CommitChangesFromEditor(0) )
return false;
SetFocusOnCanvas();
DrawItem(selected);
return true;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::RefreshEditor()
{
wxPGProperty* p = GetSelection();
if ( !p )
return;
wxWindow* wnd = GetEditorControl();
if ( !wnd )
return;
// Set editor font boldness - must do this before
// calling UpdateControl().
if ( HasFlag(wxPG_BOLD_MODIFIED) )
{
if ( p->HasFlag(wxPG_PROP_MODIFIED) )
wnd->SetFont(GetCaptionFont());
else
wnd->SetFont(GetFont());
}
const wxPGEditor* editorClass = p->GetEditorClass();
editorClass->UpdateControl(p, wnd);
if ( p->IsValueUnspecified() )
SetEditorAppearance(m_unspecifiedAppearance, true);
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::SelectProperty( wxPGPropArg id, bool focus )
{
wxPG_PROP_ARG_CALL_PROLOG_RETVAL(false)
int flags = wxPG_SEL_DONT_SEND_EVENT;
if ( focus )
flags |= wxPG_SEL_FOCUS;
return DoSelectProperty(p, flags);
}
// -----------------------------------------------------------------------
// wxPropertyGrid expand/collapse state
// -----------------------------------------------------------------------
bool wxPropertyGrid::DoCollapse( wxPGProperty* p, bool sendEvents )
{
wxPGProperty* pwc = wxStaticCast(p, wxPGProperty);
wxPGProperty* selected = GetSelection();
// If active editor was inside collapsed section, then disable it
if ( selected && selected->IsSomeParent(p) )
{
DoClearSelection();
}
// Store dont-center-splitter flag 'cause we need to temporarily set it
bool prevDontCenterSplitter = m_pState->m_dontCenterSplitter;
m_pState->m_dontCenterSplitter = true;
bool res = m_pState->DoCollapse(pwc);
if ( res )
{
if ( sendEvents )
SendEvent( wxEVT_PG_ITEM_COLLAPSED, p );
RecalculateVirtualSize();
Refresh();
}
m_pState->m_dontCenterSplitter = prevDontCenterSplitter;
return res;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::DoExpand( wxPGProperty* p, bool sendEvents )
{
wxCHECK_MSG( p, false, wxT("invalid property id") );
wxPGProperty* pwc = (wxPGProperty*)p;
// Store dont-center-splitter flag 'cause we need to temporarily set it
bool prevDontCenterSplitter = m_pState->m_dontCenterSplitter;
m_pState->m_dontCenterSplitter = true;
bool res = m_pState->DoExpand(pwc);
if ( res )
{
if ( sendEvents )
SendEvent( wxEVT_PG_ITEM_EXPANDED, p );
RecalculateVirtualSize();
Refresh();
}
m_pState->m_dontCenterSplitter = prevDontCenterSplitter;
return res;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::DoHideProperty( wxPGProperty* p, bool hide, int flags )
{
if ( m_frozen )
return m_pState->DoHideProperty(p, hide, flags);
wxArrayPGProperty selection = m_pState->m_selection; // Must use a copy
int selRemoveCount = 0;
for ( unsigned int i=0; i<selection.size(); i++ )
{
wxPGProperty* selected = selection[i];
if ( selected == p || selected->IsSomeParent(p) )
{
if ( !DoRemoveFromSelection(p, flags) )
return false;
selRemoveCount += 1;
}
}
m_pState->DoHideProperty(p, hide, flags);
RecalculateVirtualSize();
Refresh();
return true;
}
// -----------------------------------------------------------------------
// wxPropertyGrid size related methods
// -----------------------------------------------------------------------
void wxPropertyGrid::RecalculateVirtualSize( int forceXPos )
{
// Don't check for !HasInternalFlag(wxPG_FL_INITIALIZED) here. Otherwise
// virtual size calculation may go wrong.
if ( HasInternalFlag(wxPG_FL_RECALCULATING_VIRTUAL_SIZE) ||
m_frozen ||
!m_pState )
return;
//
// If virtual height was changed, then recalculate editor control position(s)
if ( m_pState->m_vhCalcPending )
CorrectEditorWidgetPosY();
m_pState->EnsureVirtualHeight();
wxASSERT_LEVEL_2_MSG(
m_pState->GetVirtualHeight() == m_pState->GetActualVirtualHeight(),
"VirtualHeight and ActualVirtualHeight should match"
);
m_iFlags |= wxPG_FL_RECALCULATING_VIRTUAL_SIZE;
int x = m_pState->m_width;
int y = m_pState->m_virtualHeight;
int width, height;
GetClientSize(&width,&height);
// Now adjust virtual size.
SetVirtualSize(x, y);
int xAmount = 0;
int xPos = 0;
//
// Adjust scrollbars
if ( HasVirtualWidth() )
{
xAmount = x/wxPG_PIXELS_PER_UNIT;
xPos = GetScrollPos( wxHORIZONTAL );
}
if ( forceXPos != -1 )
xPos = forceXPos;
// xPos too high?
else if ( xPos > (xAmount-(width/wxPG_PIXELS_PER_UNIT)) )
xPos = 0;
int yAmount = y / wxPG_PIXELS_PER_UNIT;
int yPos = GetScrollPos( wxVERTICAL );
SetScrollbars( wxPG_PIXELS_PER_UNIT, wxPG_PIXELS_PER_UNIT,
xAmount, yAmount, xPos, yPos, true );
// This may be needed in addition to calling SetScrollbars()
// when class inherits from wxScrollHelper instead of
// actual wxScrolled<T>.
AdjustScrollbars();
// Must re-get size now
GetClientSize(&width,&height);
if ( !HasVirtualWidth() )
{
m_pState->SetVirtualWidth(width);
}
m_width = width;
m_height = height;
m_pState->CheckColumnWidths();
if ( GetSelection() )
CorrectEditorWidgetSizeX();
m_iFlags &= ~wxPG_FL_RECALCULATING_VIRTUAL_SIZE;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnResize( wxSizeEvent& event )
{
if ( !(m_iFlags & wxPG_FL_INITIALIZED) )
return;
int width, height;
GetClientSize(&width, &height);
m_width = width;
m_height = height;
if ( !(GetExtraStyle() & wxPG_EX_NATIVE_DOUBLE_BUFFERING) )
{
int dblh = (m_lineHeight*2);
if ( !m_doubleBuffer )
{
// Create double buffer bitmap to draw on, if none
int w = (width>250)?width:250;
int h = height + dblh;
h = (h>400)?h:400;
m_doubleBuffer = new wxBitmap( w, h );
}
else
{
int w = m_doubleBuffer->GetWidth();
int h = m_doubleBuffer->GetHeight();
// Double buffer must be large enough
if ( w < width || h < (height+dblh) )
{
if ( w < width ) w = width;
if ( h < (height+dblh) ) h = height + dblh;
delete m_doubleBuffer;
m_doubleBuffer = new wxBitmap( w, h );
}
}
}
m_pState->OnClientWidthChange( width, event.GetSize().x - m_ncWidth, true );
m_ncWidth = event.GetSize().x;
if ( !m_frozen )
{
if ( m_pState->m_itemsAdded )
PrepareAfterItemsAdded();
else
// Without this, virtual size (atleast under wxGTK) will be skewed
RecalculateVirtualSize();
Refresh();
}
}
// -----------------------------------------------------------------------
void wxPropertyGrid::SetVirtualWidth( int width )
{
if ( width == -1 )
{
// Disable virtual width
width = GetClientSize().x;
ClearInternalFlag(wxPG_FL_HAS_VIRTUAL_WIDTH);
}
else
{
// Enable virtual width
SetInternalFlag(wxPG_FL_HAS_VIRTUAL_WIDTH);
}
m_pState->SetVirtualWidth( width );
}
void wxPropertyGrid::SetFocusOnCanvas()
{
// To prevent wxPropertyGrid from stealing focus from other controls,
// only move focus to the grid if it was already in one if its child
// controls.
wxWindow* focus = wxWindow::FindFocus();
if ( focus )
{
wxWindow* parent = focus->GetParent();
while ( parent )
{
if ( parent == this )
{
SetFocus();
break;
}
parent = parent->GetParent();
}
}
m_editorFocused = 0;
}
// -----------------------------------------------------------------------
// wxPropertyGrid mouse event handling
// -----------------------------------------------------------------------
// selFlags uses same values DoSelectProperty's flags
// Returns true if event was vetoed.
bool wxPropertyGrid::SendEvent( int eventType, wxPGProperty* p,
wxVariant* pValue,
unsigned int selFlags,
unsigned int column )
{
// selFlags should have wxPG_SEL_NOVALIDATE if event is not
// vetoable.
// Send property grid event of specific type and with specific property
wxPropertyGridEvent evt( eventType, m_eventObject->GetId() );
evt.SetPropertyGrid(this);
evt.SetEventObject(m_eventObject);
evt.SetProperty(p);
evt.SetColumn(column);
if ( eventType == wxEVT_PG_CHANGING )
{
wxASSERT( pValue );
evt.SetCanVeto(true);
m_validationInfo.m_pValue = pValue;
evt.SetupValidationInfo();
}
else
{
if ( p )
evt.SetPropertyValue(p->GetValue());
if ( !(selFlags & wxPG_SEL_NOVALIDATE) )
evt.SetCanVeto(true);
}
wxPropertyGridEvent* prevProcessedEvent = m_processedEvent;
m_processedEvent = &evt;
m_eventObject->HandleWindowEvent(evt);
m_processedEvent = prevProcessedEvent;
return evt.WasVetoed();
}
// -----------------------------------------------------------------------
// Return false if should be skipped
bool wxPropertyGrid::HandleMouseClick( int x, unsigned int y, wxMouseEvent &event )
{
bool res = true;
// Need to set focus?
if ( !(m_iFlags & wxPG_FL_FOCUSED) )
{
SetFocusOnCanvas();
}
wxPropertyGridPageState* state = m_pState;
int splitterHit;
int splitterHitOffset;
int columnHit = state->HitTestH( x, &splitterHit, &splitterHitOffset );
wxPGProperty* p = DoGetItemAtY(y);
if ( p )
{
int depth = (int)p->GetDepth() - 1;
int marginEnds = m_marginWidth + ( depth * m_subgroup_extramargin );
if ( x >= marginEnds )
{
// Outside margin.
if ( p->IsCategory() )
{
// This is category.
wxPropertyCategory* pwc = (wxPropertyCategory*)p;
int textX = m_marginWidth + ((unsigned int)((pwc->m_depth-1)*m_subgroup_extramargin));
// Expand, collapse, activate etc. if click on text or left of splitter.
if ( x >= textX
&&
( x < (textX+pwc->GetTextExtent(this, m_captionFont)+(wxPG_CAPRECTXMARGIN*2)) ||
columnHit == 0
)
)
{
if ( !AddToSelectionFromInputEvent( p,
columnHit,
&event ) )
return res;
// On double-click, expand/collapse.
if ( event.ButtonDClick() && !(m_windowStyle & wxPG_HIDE_MARGIN) )
{
if ( pwc->IsExpanded() ) DoCollapse( p, true );
else DoExpand( p, true );
}
}
}
else if ( splitterHit == -1 )
{
// Click on value.
unsigned int selFlag = 0;
if ( columnHit == 1 )
{
m_iFlags |= wxPG_FL_ACTIVATION_BY_CLICK;
selFlag = wxPG_SEL_FOCUS;
}
if ( !AddToSelectionFromInputEvent( p,
columnHit,
&event,
selFlag ) )
return res;
m_iFlags &= ~(wxPG_FL_ACTIVATION_BY_CLICK);
if ( p->GetChildCount() && !p->IsCategory() )
// On double-click, expand/collapse.
if ( event.ButtonDClick() && !(m_windowStyle & wxPG_HIDE_MARGIN) )
{
wxPGProperty* pwc = (wxPGProperty*)p;
if ( pwc->IsExpanded() ) DoCollapse( p, true );
else DoExpand( p, true );
}
// Do not Skip() the event after selection has been made.
// Otherwise default event handling behaviour kicks in
// and may revert focus back to the main canvas.
res = true;
}
else
{
// click on splitter
if ( !(m_windowStyle & wxPG_STATIC_SPLITTER) )
{
if ( event.GetEventType() == wxEVT_LEFT_DCLICK )
{
// Double-clicking the splitter causes auto-centering
if ( m_pState->GetColumnCount() <= 2 )
{
ResetColumnSizes( true );
SendEvent(wxEVT_PG_COL_DRAGGING,
m_propHover,
NULL,
wxPG_SEL_NOVALIDATE,
(unsigned int)m_draggedSplitter);
}
}
else if ( m_dragStatus == 0 )
{
//
// Begin draggin the splitter
//
// send event
DoEndLabelEdit(true, wxPG_SEL_NOVALIDATE);
// Allow application to veto dragging
if ( !SendEvent(wxEVT_PG_COL_BEGIN_DRAG,
p, NULL, 0,
(unsigned int)splitterHit) )
{
if ( m_wndEditor )
{
// Changes must be committed here or the
// value won't be drawn correctly
if ( !CommitChangesFromEditor() )
return res;
m_wndEditor->Show ( false );
}
if ( !(m_iFlags & wxPG_FL_MOUSE_CAPTURED) )
{
CaptureMouse();
m_iFlags |= wxPG_FL_MOUSE_CAPTURED;
}
m_dragStatus = 1;
m_draggedSplitter = splitterHit;
m_dragOffset = splitterHitOffset;
#if wxPG_REFRESH_CONTROLS
// Fixes button disappearance bug
if ( m_wndEditor2 )
m_wndEditor2->Show ( false );
#endif
m_startingSplitterX = x - splitterHitOffset;
}
}
}
}
}
else
{
// Click on margin.
if ( p->GetChildCount() )
{
int nx = x + m_marginWidth - marginEnds; // Normalize x.
// Fine tune cell button x
if ( !p->IsCategory() )
nx -= IN_CELL_EXPANDER_BUTTON_X_ADJUST;
if ( (nx >= m_gutterWidth && nx < (m_gutterWidth+m_iconWidth)) )
{
int y2 = y % m_lineHeight;
if ( (y2 >= m_buttonSpacingY && y2 < (m_buttonSpacingY+m_iconHeight)) )
{
// On click on expander button, expand/collapse
if ( ((wxPGProperty*)p)->IsExpanded() )
DoCollapse( p, true );
else
DoExpand( p, true );
}
}
}
}
}
return res;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::HandleMouseRightClick( int WXUNUSED(x),
unsigned int WXUNUSED(y),
wxMouseEvent& event )
{
if ( m_propHover )
{
// Select property here as well
wxPGProperty* p = m_propHover;
AddToSelectionFromInputEvent(p, m_colHover, &event);
// Send right click event.
SendEvent( wxEVT_PG_RIGHT_CLICK, p );
return true;
}
return false;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::HandleMouseDoubleClick( int WXUNUSED(x),
unsigned int WXUNUSED(y),
wxMouseEvent& event )
{
if ( m_propHover )
{
// Select property here as well
wxPGProperty* p = m_propHover;
AddToSelectionFromInputEvent(p, m_colHover, &event);
// Send double-click event.
SendEvent( wxEVT_PG_DOUBLE_CLICK, m_propHover );
return true;
}
return false;
}
// -----------------------------------------------------------------------
// Return false if should be skipped
bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y,
wxMouseEvent &event )
{
// Safety check (needed because mouse capturing may
// otherwise freeze the control)
if ( m_dragStatus > 0 && !event.Dragging() )
{
HandleMouseUp(x, y, event);
}
wxPropertyGridPageState* state = m_pState;
int splitterHit;
int splitterHitOffset;
int columnHit = state->HitTestH( x, &splitterHit, &splitterHitOffset );
int splitterX = x - splitterHitOffset;
m_colHover = columnHit;
if ( m_dragStatus > 0 )
{
if ( x > (m_marginWidth + wxPG_DRAG_MARGIN) &&
x < (m_pState->m_width - wxPG_DRAG_MARGIN) )
{
int newSplitterX = x - m_dragOffset;
// Splitter redraw required?
if ( newSplitterX != splitterX )
{
// Move everything
DoSetSplitterPosition(newSplitterX,
m_draggedSplitter,
wxPG_SPLITTER_REFRESH |
wxPG_SPLITTER_FROM_EVENT);
SendEvent(wxEVT_PG_COL_DRAGGING,
m_propHover,
NULL,
wxPG_SEL_NOVALIDATE,
(unsigned int)m_draggedSplitter);
}
m_dragStatus = 2;
}
return false;
}
else
{
int ih = m_lineHeight;
int sy = y;
#if wxPG_SUPPORT_TOOLTIPS
wxPGProperty* prevHover = m_propHover;
unsigned char prevSide = m_mouseSide;
#endif
int curPropHoverY = y - (y % ih);
// On which item it hovers
if ( !m_propHover
||
( sy < m_propHoverY || sy >= (m_propHoverY+ih) )
)
{
// Mouse moves on another property
m_propHover = DoGetItemAtY(y);
m_propHoverY = curPropHoverY;
// Send hover event
SendEvent( wxEVT_PG_HIGHLIGHTED, m_propHover );
}
#if wxPG_SUPPORT_TOOLTIPS
// Store which side we are on
m_mouseSide = 0;
if ( columnHit == 1 )
m_mouseSide = 2;
else if ( columnHit == 0 )
m_mouseSide = 1;
//
// If tooltips are enabled, show label or value as a tip
// in case it doesn't otherwise show in full length.
//
if ( m_windowStyle & wxPG_TOOLTIPS )
{
if ( m_propHover != prevHover || prevSide != m_mouseSide )
{
if ( m_propHover && !m_propHover->IsCategory() )
{
if ( GetExtraStyle() & wxPG_EX_HELP_AS_TOOLTIPS )
{
// Show help string as a tooltip
wxString tipString = m_propHover->GetHelpString();
SetToolTip(tipString);
}
else
{
// Show cropped value string as a tooltip
wxString tipString;
int space = 0;
if ( m_mouseSide == 1 )
{
tipString = m_propHover->m_label;
space = splitterX-m_marginWidth-3;
}
else if ( m_mouseSide == 2 )
{
tipString = m_propHover->GetDisplayedString();
space = m_width - splitterX;
if ( m_propHover->m_flags & wxPG_PROP_CUSTOMIMAGE )
space -= wxPG_CUSTOM_IMAGE_WIDTH +
wxCC_CUSTOM_IMAGE_MARGIN1 +
wxCC_CUSTOM_IMAGE_MARGIN2;
}
if ( space )
{
int tw, th;
GetTextExtent( tipString, &tw, &th, 0, 0 );
if ( tw > space )
SetToolTip( tipString );
}
else
{
SetToolTip( m_emptyString );
}
}
}
else
{
SetToolTip( m_emptyString );
}
}
}
#endif
if ( splitterHit == -1 ||
!m_propHover ||
HasFlag(wxPG_STATIC_SPLITTER) )
{
// hovering on something else
if ( m_curcursor != wxCURSOR_ARROW )
CustomSetCursor( wxCURSOR_ARROW );
}
else
{
// Do not allow splitter cursor on caption items.
// (also not if we were dragging and its started
// outside the splitter region)
if ( !m_propHover->IsCategory() &&
!event.Dragging() )
{
// hovering on splitter
// NB: Condition disabled since MouseLeave event (from the
// editor control) cannot be reliably detected.
//if ( m_curcursor != wxCURSOR_SIZEWE )
CustomSetCursor( wxCURSOR_SIZEWE, true );
return false;
}
else
{
// hovering on something else
if ( m_curcursor != wxCURSOR_ARROW )
CustomSetCursor( wxCURSOR_ARROW );
}
}
//
// Multi select by dragging
//
if ( (GetExtraStyle() & wxPG_EX_MULTIPLE_SELECTION) &&
event.LeftIsDown() &&
m_propHover &&
GetSelection() &&
columnHit != 1 &&
!state->DoIsPropertySelected(m_propHover) )
{
// Additional requirement is that the hovered property
// is adjacent to edges of selection.
const wxArrayPGProperty& selection = GetSelectedProperties();
// Since categories cannot be selected along with 'other'
// properties, exclude them from iterator flags.
int iterFlags = wxPG_ITERATE_VISIBLE & (~wxPG_PROP_CATEGORY);
for ( int i=(selection.size()-1); i>=0; i-- )
{
// TODO: This could be optimized by keeping track of
// which properties are at the edges of selection.
wxPGProperty* selProp = selection[i];
if ( state->ArePropertiesAdjacent(m_propHover, selProp,
iterFlags) )
{
DoAddToSelection(m_propHover);
break;
}
}
}
}
return true;
}
// -----------------------------------------------------------------------
// Also handles Leaving event
bool wxPropertyGrid::HandleMouseUp( int x, unsigned int WXUNUSED(y),
wxMouseEvent &WXUNUSED(event) )
{
wxPropertyGridPageState* state = m_pState;
bool res = false;
int splitterHit;
int splitterHitOffset;
state->HitTestH( x, &splitterHit, &splitterHitOffset );
// No event type check - basically calling this method should
// just stop dragging.
// Left up after dragged?
if ( m_dragStatus >= 1 )
{
//
// End Splitter Dragging
//
// DO NOT ENABLE FOLLOWING LINE!
// (it is only here as a reminder to not to do it)
//splitterX = x;
SendEvent(wxEVT_PG_COL_END_DRAG,
m_propHover,
NULL,
wxPG_SEL_NOVALIDATE,
(unsigned int)m_draggedSplitter);
// Disable splitter auto-centering (but only if moved any -
// otherwise we end up disabling auto-center even after a
// recentering double-click).
int posDiff = abs(m_startingSplitterX -
GetSplitterPosition(m_draggedSplitter));
if ( posDiff > 1 )
state->m_dontCenterSplitter = true;
// This is necessary to return cursor
if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
{
ReleaseMouse();
m_iFlags &= ~(wxPG_FL_MOUSE_CAPTURED);
}
// Set back the default cursor, if necessary
if ( splitterHit == -1 ||
!m_propHover )
{
CustomSetCursor( wxCURSOR_ARROW );
}
m_dragStatus = 0;
// Control background needs to be cleared
wxPGProperty* selected = GetSelection();
if ( !(m_iFlags & wxPG_FL_PRIMARY_FILLS_ENTIRE) && selected )
DrawItem( selected );
if ( m_wndEditor )
{
m_wndEditor->Show ( true );
}
#if wxPG_REFRESH_CONTROLS
// Fixes button disappearance bug
if ( m_wndEditor2 )
m_wndEditor2->Show ( true );
#endif
// This clears the focus.
m_editorFocused = 0;
}
return res;
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::OnMouseCommon( wxMouseEvent& event, int* px, int* py )
{
int splitterX = GetSplitterPosition();
int ux, uy;
CalcUnscrolledPosition( event.m_x, event.m_y, &ux, &uy );
wxWindow* wnd = GetEditorControl();
// Hide popup on clicks
if ( event.GetEventType() != wxEVT_MOTION )
if ( wxDynamicCast(wnd, wxOwnerDrawnComboBox) )
{
((wxOwnerDrawnComboBox*)wnd)->HidePopup();
}
wxRect r;
if ( wnd )
r = wnd->GetRect();
if ( wnd == NULL || m_dragStatus ||
(
ux <= (splitterX + wxPG_SPLITTERX_DETECTMARGIN2) ||
ux >= (r.x+r.width) ||
event.m_y < r.y ||
event.m_y >= (r.y+r.height)
)
)
{
*px = ux;
*py = uy;
return true;
}
else
{
if ( m_curcursor != wxCURSOR_ARROW ) CustomSetCursor ( wxCURSOR_ARROW );
}
return false;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnMouseClick( wxMouseEvent &event )
{
int x, y;
if ( OnMouseCommon( event, &x, &y ) )
{
if ( !HandleMouseClick(x, y, event) )
event.Skip();
}
else
{
event.Skip();
}
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnMouseRightClick( wxMouseEvent &event )
{
int x, y;
CalcUnscrolledPosition( event.m_x, event.m_y, &x, &y );
HandleMouseRightClick(x,y,event);
event.Skip();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnMouseDoubleClick( wxMouseEvent &event )
{
// Always run standard mouse-down handler as well
OnMouseClick(event);
int x, y;
CalcUnscrolledPosition( event.m_x, event.m_y, &x, &y );
HandleMouseDoubleClick(x,y,event);
// Do not Skip() event here - OnMouseClick() call above
// should have already taken care of it.
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnMouseMove( wxMouseEvent &event )
{
int x, y;
if ( OnMouseCommon( event, &x, &y ) )
{
HandleMouseMove(x,y,event);
}
event.Skip();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnMouseUp( wxMouseEvent &event )
{
int x, y;
if ( OnMouseCommon( event, &x, &y ) )
{
if ( !HandleMouseUp(x, y, event) )
event.Skip();
}
else
{
event.Skip();
}
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnMouseEntry( wxMouseEvent &event )
{
// This may get called from child control as well, so event's
// mouse position cannot be relied on.
if ( event.Entering() )
{
if ( !(m_iFlags & wxPG_FL_MOUSE_INSIDE) )
{
// TODO: Fix this (detect parent and only do
// cursor trick if it is a manager).
wxASSERT( GetParent() );
GetParent()->SetCursor(wxNullCursor);
m_iFlags |= wxPG_FL_MOUSE_INSIDE;
}
else
GetParent()->SetCursor(wxNullCursor);
}
else if ( event.Leaving() )
{
// Without this, wxSpinCtrl editor will sometimes have wrong cursor
SetCursor( wxNullCursor );
// Get real cursor position
wxPoint pt = ScreenToClient(::wxGetMousePosition());
if ( ( pt.x <= 0 || pt.y <= 0 || pt.x >= m_width || pt.y >= m_height ) )
{
{
if ( (m_iFlags & wxPG_FL_MOUSE_INSIDE) )
{
m_iFlags &= ~(wxPG_FL_MOUSE_INSIDE);
}
if ( m_dragStatus )
wxPropertyGrid::HandleMouseUp ( -1, 10000, event );
}
}
}
event.Skip();
}
// -----------------------------------------------------------------------
// Common code used by various OnMouseXXXChild methods.
bool wxPropertyGrid::OnMouseChildCommon( wxMouseEvent &event, int* px, int *py )
{
wxWindow* topCtrlWnd = (wxWindow*)event.GetEventObject();
wxASSERT( topCtrlWnd );
int x, y;
event.GetPosition(&x,&y);
int splitterX = GetSplitterPosition();
wxRect r = topCtrlWnd->GetRect();
if ( !m_dragStatus &&
x > (splitterX-r.x+wxPG_SPLITTERX_DETECTMARGIN2) &&
y >= 0 && y < r.height \
)
{
if ( m_curcursor != wxCURSOR_ARROW ) CustomSetCursor ( wxCURSOR_ARROW );
event.Skip();
}
else
{
CalcUnscrolledPosition( event.m_x + r.x, event.m_y + r.y, \
px, py );
return true;
}
return false;
}
void wxPropertyGrid::OnMouseClickChild( wxMouseEvent &event )
{
int x,y;
if ( OnMouseChildCommon(event,&x,&y) )
{
bool res = HandleMouseClick(x,y,event);
if ( !res ) event.Skip();
}
}
void wxPropertyGrid::OnMouseRightClickChild( wxMouseEvent &event )
{
int x,y;
wxASSERT( m_wndEditor );
// These coords may not be exact (about +-2),
// but that should not matter (right click is about item, not position).
wxPoint pt = m_wndEditor->GetPosition();
CalcUnscrolledPosition( event.m_x + pt.x, event.m_y + pt.y, &x, &y );
// FIXME: Used to set m_propHover to selection here. Was it really
// necessary?
bool res = HandleMouseRightClick(x,y,event);
if ( !res ) event.Skip();
}
void wxPropertyGrid::OnMouseMoveChild( wxMouseEvent &event )
{
int x,y;
if ( OnMouseChildCommon(event,&x,&y) )
{
bool res = HandleMouseMove(x,y,event);
if ( !res ) event.Skip();
}
}
void wxPropertyGrid::OnMouseUpChild( wxMouseEvent &event )
{
int x,y;
if ( OnMouseChildCommon(event,&x,&y) )
{
bool res = HandleMouseUp(x,y,event);
if ( !res ) event.Skip();
}
}
// -----------------------------------------------------------------------
// wxPropertyGrid keyboard event handling
// -----------------------------------------------------------------------
int wxPropertyGrid::KeyEventToActions(wxKeyEvent &event, int* pSecond) const
{
// Translates wxKeyEvent to wxPG_ACTION_XXX
int keycode = event.GetKeyCode();
int modifiers = event.GetModifiers();
wxASSERT( !(modifiers&~(0xFFFF)) );
int hashMapKey = (keycode & 0xFFFF) | ((modifiers & 0xFFFF) << 16);
wxPGHashMapI2I::const_iterator it = m_actionTriggers.find(hashMapKey);
if ( it == m_actionTriggers.end() )
return 0;
if ( pSecond )
{
int second = (it->second>>16) & 0xFFFF;
*pSecond = second;
}
return (it->second & 0xFFFF);
}
void wxPropertyGrid::AddActionTrigger( int action, int keycode, int modifiers )
{
wxASSERT( !(modifiers&~(0xFFFF)) );
int hashMapKey = (keycode & 0xFFFF) | ((modifiers & 0xFFFF) << 16);
wxPGHashMapI2I::iterator it = m_actionTriggers.find(hashMapKey);
if ( it != m_actionTriggers.end() )
{
// This key combination is already used
// Can add secondary?
wxASSERT_MSG( !(it->second&~(0xFFFF)),
wxT("You can only add up to two separate actions per key combination.") );
action = it->second | (action<<16);
}
m_actionTriggers[hashMapKey] = action;
}
void wxPropertyGrid::ClearActionTriggers( int action )
{
wxPGHashMapI2I::iterator it;
bool didSomething;
do
{
didSomething = false;
for ( it = m_actionTriggers.begin();
it != m_actionTriggers.end();
it++ )
{
if ( it->second == action )
{
m_actionTriggers.erase(it);
didSomething = true;
break;
}
}
}
while ( didSomething );
}
void wxPropertyGrid::HandleKeyEvent( wxKeyEvent &event, bool fromChild )
{
//
// Handles key event when editor control is not focused.
//
wxCHECK2(!m_frozen, return);
// Travelsal between items, collapsing/expanding, etc.
wxPGProperty* selected = GetSelection();
int keycode = event.GetKeyCode();
bool editorFocused = IsEditorFocused();
if ( keycode == WXK_TAB )
{
#if defined(__WXGTK__)
wxWindow* mainControl;
if ( HasInternalFlag(wxPG_FL_IN_MANAGER) )
mainControl = GetParent();
else
mainControl = this;
#endif
if ( !event.ShiftDown() )
{
if ( !editorFocused && m_wndEditor )
{
DoSelectProperty( selected, wxPG_SEL_FOCUS );
}
else
{
// Tab traversal workaround for platforms on which
// wxWindow::Navigate() may navigate into first child
// instead of next sibling. Does not work perfectly
// in every scenario (for instance, when property grid
// is either first or last control).
#if defined(__WXGTK__)
wxWindow* sibling = mainControl->GetNextSibling();
if ( sibling )
sibling->SetFocusFromKbd();
#else
Navigate(wxNavigationKeyEvent::IsForward);
#endif
}
}
else
{
if ( editorFocused )
{
UnfocusEditor();
}
else
{
#if defined(__WXGTK__)
wxWindow* sibling = mainControl->GetPrevSibling();
if ( sibling )
sibling->SetFocusFromKbd();
#else
Navigate(wxNavigationKeyEvent::IsBackward);
#endif
}
}
return;
}
// Ignore Alt and Control when they are down alone
if ( keycode == WXK_ALT ||
keycode == WXK_CONTROL )
{
event.Skip();
return;
}
int secondAction;
int action = KeyEventToActions(event, &secondAction);
if ( editorFocused && action == wxPG_ACTION_CANCEL_EDIT )
{
//
// Esc cancels any changes
if ( IsEditorsValueModified() )
{
EditorsValueWasNotModified();
// Update the control as well
selected->GetEditorClass()->
SetControlStringValue( selected,
GetEditorControl(),
selected->GetDisplayedString() );
}
OnValidationFailureReset(selected);
UnfocusEditor();
return;
}
// Except for TAB, ESC, and any keys specifically dedicated to
// wxPropertyGrid itself, handle child control events in child control.
if ( fromChild &&
wxPGFindInVector(m_dedicatedKeys, keycode) == wxNOT_FOUND )
{
// Only propagate event if it had modifiers
if ( !event.HasModifiers() )
{
event.StopPropagation();
}
event.Skip();
return;
}
bool wasHandled = false;
if ( selected )
{
// Show dialog?
if ( ButtonTriggerKeyTest(action, event) )
return;
wxPGProperty* p = selected;
if ( action == wxPG_ACTION_EDIT && !editorFocused )
{
DoSelectProperty( p, wxPG_SEL_FOCUS );
wasHandled = true;
}
// Travel and expand/collapse
int selectDir = -2;
if ( p->GetChildCount() )
{
if ( action == wxPG_ACTION_COLLAPSE_PROPERTY || secondAction == wxPG_ACTION_COLLAPSE_PROPERTY )
{
if ( (m_windowStyle & wxPG_HIDE_MARGIN) || DoCollapse(p, true) )
wasHandled = true;
}
else if ( action == wxPG_ACTION_EXPAND_PROPERTY || secondAction == wxPG_ACTION_EXPAND_PROPERTY )
{
if ( (m_windowStyle & wxPG_HIDE_MARGIN) || DoExpand(p, true) )
wasHandled = true;
}
}
if ( !wasHandled )
{
if ( action == wxPG_ACTION_PREV_PROPERTY || secondAction == wxPG_ACTION_PREV_PROPERTY )
{
selectDir = -1;
}
else if ( action == wxPG_ACTION_NEXT_PROPERTY || secondAction == wxPG_ACTION_NEXT_PROPERTY )
{
selectDir = 1;
}
}
if ( selectDir >= -1 )
{
p = wxPropertyGridIterator::OneStep( m_pState, wxPG_ITERATE_VISIBLE, p, selectDir );
if ( p )
{
int selFlags = 0;
int reopenLabelEditorCol = -1;
if ( editorFocused )
{
// If editor was focused, then make the next editor
// focused as well
selFlags |= wxPG_SEL_FOCUS;
}
else
{
// Also maintain the same label editor focus state
if ( m_labelEditor )
reopenLabelEditorCol = m_selColumn;
}
DoSelectProperty(p, selFlags);
if ( reopenLabelEditorCol >= 0 )
DoBeginLabelEdit(reopenLabelEditorCol);
}
wasHandled = true;
}
}
else
{
// If nothing was selected, select the first item now
// (or navigate out of tab).
if ( action != wxPG_ACTION_CANCEL_EDIT && secondAction != wxPG_ACTION_CANCEL_EDIT )
{
wxPGProperty* p = wxPropertyGridInterface::GetFirst();
if ( p ) DoSelectProperty(p);
wasHandled = true;
}
}
if ( !wasHandled )
event.Skip();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnKey( wxKeyEvent &event )
{
// If there was editor open and focused, then this event should not
// really be processed here.
if ( IsEditorFocused() )
{
// However, if event had modifiers, it is probably still best
// to skip it.
if ( event.HasModifiers() )
event.Skip();
else
event.StopPropagation();
return;
}
HandleKeyEvent(event, false);
}
// -----------------------------------------------------------------------
bool wxPropertyGrid::ButtonTriggerKeyTest( int action, wxKeyEvent& event )
{
if ( action == -1 )
{
int secondAction;
action = KeyEventToActions(event, &secondAction);
}
// Does the keycode trigger button?
if ( action == wxPG_ACTION_PRESS_BUTTON &&
m_wndEditor2 )
{
wxCommandEvent evt(wxEVT_BUTTON, m_wndEditor2->GetId());
GetEventHandler()->AddPendingEvent(evt);
return true;
}
return false;
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnChildKeyDown( wxKeyEvent &event )
{
HandleKeyEvent(event, true);
}
// -----------------------------------------------------------------------
// wxPropertyGrid miscellaneous event handling
// -----------------------------------------------------------------------
void wxPropertyGrid::OnIdle( wxIdleEvent& WXUNUSED(event) )
{
//
// Check if the focus is in this control or one of its children
wxWindow* newFocused = wxWindow::FindFocus();
if ( newFocused != m_curFocused )
HandleFocusChange( newFocused );
//
// Check if top-level parent has changed
if ( GetExtraStyle() & wxPG_EX_ENABLE_TLP_TRACKING )
{
wxWindow* tlp = ::wxGetTopLevelParent(this);
if ( tlp != m_tlp )
OnTLPChanging(tlp);
}
//
// Resolve pending property removals
if ( m_deletedProperties.size() > 0 )
{
wxArrayPGProperty& arr = m_deletedProperties;
for ( unsigned int i=0; i<arr.size(); i++ )
{
DeleteProperty(arr[i]);
}
arr.clear();
}
if ( m_removedProperties.size() > 0 )
{
wxArrayPGProperty& arr = m_removedProperties;
for ( unsigned int i=0; i<arr.size(); i++ )
{
RemoveProperty(arr[i]);
}
arr.clear();
}
}
bool wxPropertyGrid::IsEditorFocused() const
{
wxWindow* focus = wxWindow::FindFocus();
if ( focus == m_wndEditor || focus == m_wndEditor2 ||
focus == GetEditorControl() )
return true;
return false;
}
// Called by focus event handlers. newFocused is the window that becomes focused.
void wxPropertyGrid::HandleFocusChange( wxWindow* newFocused )
{
//
// Never allow focus to be changed when handling editor event.
// Especially because they may be displaing a dialog which
// could cause all kinds of weird (native) focus changes.
if ( HasInternalFlag(wxPG_FL_IN_HANDLECUSTOMEDITOREVENT) )
return;
unsigned int oldFlags = m_iFlags;
bool wasEditorFocused = false;
wxWindow* wndEditor = m_wndEditor;
m_iFlags &= ~(wxPG_FL_FOCUSED);
wxWindow* parent = newFocused;
// This must be one of nextFocus' parents.
while ( parent )
{
if ( parent == wndEditor )
{
wasEditorFocused = true;
}
// Use m_eventObject, which is either wxPropertyGrid or
// wxPropertyGridManager, as appropriate.
else if ( parent == m_eventObject )
{
m_iFlags |= wxPG_FL_FOCUSED;
break;
}
parent = parent->GetParent();
}
// Notify editor control when it receives a focus
if ( wasEditorFocused && m_curFocused != newFocused )
{
wxPGProperty* p = GetSelection();
if ( p )
{
const wxPGEditor* editor = p->GetEditorClass();
ResetEditorAppearance();
editor->OnFocus(p, GetEditorControl());
}
}
m_curFocused = newFocused;
if ( (m_iFlags & wxPG_FL_FOCUSED) !=
(oldFlags & wxPG_FL_FOCUSED) )
{
if ( !(m_iFlags & wxPG_FL_FOCUSED) )
{
// Need to store changed value
CommitChangesFromEditor();
}
else
{
/*
//
// Preliminary code for tab-order respecting
// tab-traversal (but should be moved to
// OnNav handler)
//
wxWindow* prevFocus = event.GetWindow();
wxWindow* useThis = this;
if ( m_iFlags & wxPG_FL_IN_MANAGER )
useThis = GetParent();
if ( prevFocus &&
prevFocus->GetParent() == useThis->GetParent() )
{
wxList& children = useThis->GetParent()->GetChildren();
wxNode* node = children.Find(prevFocus);
if ( node->GetNext() &&
useThis == node->GetNext()->GetData() )
DoSelectProperty(GetFirst());
else if ( node->GetPrevious () &&
useThis == node->GetPrevious()->GetData() )
DoSelectProperty(GetLastProperty());
}
*/
}
// Redraw selected
wxPGProperty* selected = GetSelection();
if ( selected && (m_iFlags & wxPG_FL_INITIALIZED) )
DrawItem( selected );
}
}
void wxPropertyGrid::OnFocusEvent( wxFocusEvent& event )
{
if ( event.GetEventType() == wxEVT_SET_FOCUS )
HandleFocusChange((wxWindow*)event.GetEventObject());
// Line changed to "else" when applying wxPropertyGrid patch #1675902
//else if ( event.GetWindow() )
else
HandleFocusChange(event.GetWindow());
event.Skip();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnChildFocusEvent( wxChildFocusEvent& event )
{
HandleFocusChange((wxWindow*)event.GetEventObject());
event.Skip();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnScrollEvent( wxScrollWinEvent &event )
{
m_iFlags |= wxPG_FL_SCROLLED;
event.Skip();
}
// -----------------------------------------------------------------------
void wxPropertyGrid::OnCaptureChange( wxMouseCaptureChangedEvent& WXUNUSED(event) )
{
if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
{
m_iFlags &= ~(wxPG_FL_MOUSE_CAPTURED);
}
}
// -----------------------------------------------------------------------
// Property editor related functions
// -----------------------------------------------------------------------
// noDefCheck = true prevents infinite recursion.
wxPGEditor* wxPropertyGrid::DoRegisterEditorClass( wxPGEditor* editorClass,
const wxString& editorName,
bool noDefCheck )
{
wxASSERT( editorClass );
if ( !noDefCheck && wxPGGlobalVars->m_mapEditorClasses.empty() )
RegisterDefaultEditors();
wxString name = editorName;
if ( name.empty() )
name = editorClass->GetName();
// Existing editor under this name?
wxPGHashMapS2P::iterator vt_it = wxPGGlobalVars->m_mapEditorClasses.find(name);
if ( vt_it != wxPGGlobalVars->m_mapEditorClasses.end() )
{
// If this name was already used, try class name.
name = editorClass->GetClassInfo()->GetClassName();
vt_it = wxPGGlobalVars->m_mapEditorClasses.find(name);
}
wxCHECK_MSG( vt_it == wxPGGlobalVars->m_mapEditorClasses.end(),
(wxPGEditor*) vt_it->second,
"Editor with given name was already registered" );
wxPGGlobalVars->m_mapEditorClasses[name] = (void*)editorClass;
return editorClass;
}
// Use this in RegisterDefaultEditors.
#define wxPGRegisterDefaultEditorClass(EDITOR) \
if ( wxPGEditor_##EDITOR == NULL ) \
{ \
wxPGEditor_##EDITOR = wxPropertyGrid::RegisterEditorClass( \
new wxPG##EDITOR##Editor, true ); \
}
// Registers all default editor classes
void wxPropertyGrid::RegisterDefaultEditors()
{
wxPGRegisterDefaultEditorClass( TextCtrl );
wxPGRegisterDefaultEditorClass( Choice );
wxPGRegisterDefaultEditorClass( ComboBox );
wxPGRegisterDefaultEditorClass( TextCtrlAndButton );
#if wxPG_INCLUDE_CHECKBOX
wxPGRegisterDefaultEditorClass( CheckBox );
#endif
wxPGRegisterDefaultEditorClass( ChoiceAndButton );
// Register SpinCtrl etc. editors before use
RegisterAdditionalEditors();
}
// -----------------------------------------------------------------------
// wxPGStringTokenizer
// Needed to handle C-style string lists (e.g. "str1" "str2")
// -----------------------------------------------------------------------
wxPGStringTokenizer::wxPGStringTokenizer( const wxString& str, wxChar delimeter )
: m_str(&str), m_curPos(str.begin()), m_delimeter(delimeter)
{
}
wxPGStringTokenizer::~wxPGStringTokenizer()
{
}
bool wxPGStringTokenizer::HasMoreTokens()
{
const wxString& str = *m_str;
wxString::const_iterator i = m_curPos;
wxUniChar delim = m_delimeter;
wxUniChar a;
wxUniChar prev_a = wxT('\0');
bool inToken = false;
while ( i != str.end() )
{
a = *i;
if ( !inToken )
{
if ( a == delim )
{
inToken = true;
m_readyToken.clear();
}
}
else
{
if ( prev_a != wxT('\\') )
{
if ( a != delim )
{
if ( a != wxT('\\') )
m_readyToken << a;
}
else
{
++i;
m_curPos = i;
return true;
}
prev_a = a;
}
else
{
m_readyToken << a;
prev_a = wxT('\0');
}
}
++i;
}
m_curPos = str.end();
if ( inToken )
return true;
return false;
}
wxString wxPGStringTokenizer::GetNextToken()
{
return m_readyToken;
}
// -----------------------------------------------------------------------
// wxPGChoiceEntry
// -----------------------------------------------------------------------
wxPGChoiceEntry::wxPGChoiceEntry()
: wxPGCell(), m_value(wxPG_INVALID_VALUE)
{
}
// -----------------------------------------------------------------------
// wxPGChoicesData
// -----------------------------------------------------------------------
wxPGChoicesData::wxPGChoicesData()
{
}
wxPGChoicesData::~wxPGChoicesData()
{
Clear();
}
void wxPGChoicesData::Clear()
{
m_items.clear();
}
void wxPGChoicesData::CopyDataFrom( wxPGChoicesData* data )
{
wxASSERT( m_items.size() == 0 );
m_items = data->m_items;
}
wxPGChoiceEntry& wxPGChoicesData::Insert( int index,
const wxPGChoiceEntry& item )
{
wxVector<wxPGChoiceEntry>::iterator it;
if ( index == -1 )
{
it = m_items.end();
index = (int) m_items.size();
}
else
{
it = m_items.begin() + index;
}
m_items.insert(it, item);
wxPGChoiceEntry& ownEntry = m_items[index];
// Need to fix value?
if ( ownEntry.GetValue() == wxPG_INVALID_VALUE )
ownEntry.SetValue(index);
return ownEntry;
}
// -----------------------------------------------------------------------
// wxPropertyGridEvent
// -----------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxPropertyGridEvent, wxCommandEvent)
wxDEFINE_EVENT( wxEVT_PG_SELECTED, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_CHANGING, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_CHANGED, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_HIGHLIGHTED, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_RIGHT_CLICK, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_PAGE_CHANGED, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_ITEM_EXPANDED, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_ITEM_COLLAPSED, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_DOUBLE_CLICK, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_LABEL_EDIT_BEGIN, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_LABEL_EDIT_ENDING, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_COL_BEGIN_DRAG, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_COL_DRAGGING, wxPropertyGridEvent );
wxDEFINE_EVENT( wxEVT_PG_COL_END_DRAG, wxPropertyGridEvent );
// -----------------------------------------------------------------------
void wxPropertyGridEvent::Init()
{
m_validationInfo = NULL;
m_column = 1;
m_canVeto = false;
m_wasVetoed = false;
m_pg = NULL;
}
// -----------------------------------------------------------------------
wxPropertyGridEvent::wxPropertyGridEvent(wxEventType commandType, int id)
: wxCommandEvent(commandType,id)
{
m_property = NULL;
Init();
}
// -----------------------------------------------------------------------
wxPropertyGridEvent::wxPropertyGridEvent(const wxPropertyGridEvent& event)
: wxCommandEvent(event)
{
m_eventType = event.GetEventType();
m_eventObject = event.m_eventObject;
m_pg = event.m_pg;
OnPropertyGridSet();
m_property = event.m_property;
m_validationInfo = event.m_validationInfo;
m_canVeto = event.m_canVeto;
m_wasVetoed = event.m_wasVetoed;
}
// -----------------------------------------------------------------------
void wxPropertyGridEvent::OnPropertyGridSet()
{
if ( !m_pg )
return;
#if wxUSE_THREADS
wxCriticalSectionLocker(wxPGGlobalVars->m_critSect);
#endif
m_pg->m_liveEvents.push_back(this);
}
// -----------------------------------------------------------------------
wxPropertyGridEvent::~wxPropertyGridEvent()
{
if ( m_pg )
{
#if wxUSE_THREADS
wxCriticalSectionLocker(wxPGGlobalVars->m_critSect);
#endif
// Use iterate from the back since it is more likely that the event
// being desroyed is at the end of the array.
wxVector<wxPropertyGridEvent*>& liveEvents = m_pg->m_liveEvents;
for ( int i = liveEvents.size()-1; i >= 0; i-- )
{
if ( liveEvents[i] == this )
{
liveEvents.erase(liveEvents.begin() + i);
break;
}
}
}
}
// -----------------------------------------------------------------------
wxEvent* wxPropertyGridEvent::Clone() const
{
return new wxPropertyGridEvent( *this );
}
// -----------------------------------------------------------------------
// wxPropertyGridPopulator
// -----------------------------------------------------------------------
wxPropertyGridPopulator::wxPropertyGridPopulator()
{
m_state = NULL;
m_pg = NULL;
wxPGGlobalVars->m_offline++;
}
// -----------------------------------------------------------------------
void wxPropertyGridPopulator::SetState( wxPropertyGridPageState* state )
{
m_state = state;
m_propHierarchy.clear();
}
// -----------------------------------------------------------------------
void wxPropertyGridPopulator::SetGrid( wxPropertyGrid* pg )
{
m_pg = pg;
pg->Freeze();
}
// -----------------------------------------------------------------------
wxPropertyGridPopulator::~wxPropertyGridPopulator()
{
//
// Free unused sets of choices
wxPGHashMapS2P::iterator it;
for( it = m_dictIdChoices.begin(); it != m_dictIdChoices.end(); ++it )
{
wxPGChoicesData* data = (wxPGChoicesData*) it->second;
data->DecRef();
}
if ( m_pg )
{
m_pg->Thaw();
m_pg->GetPanel()->Refresh();
}
wxPGGlobalVars->m_offline--;
}
// -----------------------------------------------------------------------
wxPGProperty* wxPropertyGridPopulator::Add( const wxString& propClass,
const wxString& propLabel,
const wxString& propName,
const wxString* propValue,
wxPGChoices* pChoices )
{
wxClassInfo* classInfo = wxClassInfo::FindClass(propClass);
wxPGProperty* parent = GetCurParent();
if ( parent->HasFlag(wxPG_PROP_AGGREGATE) )
{
ProcessError(wxString::Format(wxT("new children cannot be added to '%s'"),parent->GetName().c_str()));
return NULL;
}
if ( !classInfo || !classInfo->IsKindOf(wxCLASSINFO(wxPGProperty)) )
{
ProcessError(wxString::Format(wxT("'%s' is not valid property class"),propClass.c_str()));
return NULL;
}
wxPGProperty* property = (wxPGProperty*) classInfo->CreateObject();
property->SetLabel(propLabel);
property->DoSetName(propName);
if ( pChoices && pChoices->IsOk() )
property->SetChoices(*pChoices);
m_state->DoInsert(parent, -1, property);
if ( propValue )
property->SetValueFromString( *propValue, wxPG_FULL_VALUE|
wxPG_PROGRAMMATIC_VALUE );
return property;
}
// -----------------------------------------------------------------------
void wxPropertyGridPopulator::AddChildren( wxPGProperty* property )
{
m_propHierarchy.push_back(property);
DoScanForChildren();
m_propHierarchy.pop_back();
}
// -----------------------------------------------------------------------
wxPGChoices wxPropertyGridPopulator::ParseChoices( const wxString& choicesString,
const wxString& idString )
{
wxPGChoices choices;
// Using id?
if ( choicesString[0] == wxT('@') )
{
wxString ids = choicesString.substr(1);
wxPGHashMapS2P::iterator it = m_dictIdChoices.find(ids);
if ( it == m_dictIdChoices.end() )
ProcessError(wxString::Format(wxT("No choices defined for id '%s'"),ids.c_str()));
else
choices.AssignData((wxPGChoicesData*)it->second);
}
else
{
bool found = false;
if ( !idString.empty() )
{
wxPGHashMapS2P::iterator it = m_dictIdChoices.find(idString);
if ( it != m_dictIdChoices.end() )
{
choices.AssignData((wxPGChoicesData*)it->second);
found = true;
}
}
if ( !found )
{
// Parse choices string
wxString::const_iterator it = choicesString.begin();
wxString label;
wxString value;
int state = 0;
bool labelValid = false;
for ( ; it != choicesString.end(); ++it )
{
wxChar c = *it;
if ( state != 1 )
{
if ( c == wxT('"') )
{
if ( labelValid )
{
long l;
if ( !value.ToLong(&l, 0) ) l = wxPG_INVALID_VALUE;
choices.Add(label, l);
}
labelValid = false;
//wxLogDebug(wxT("%s, %s"),label.c_str(),value.c_str());
value.clear();
label.clear();
state = 1;
}
else if ( c == wxT('=') )
{
if ( labelValid )
{
state = 2;
}
}
else if ( state == 2 && (wxIsalnum(c) || c == wxT('x')) )
{
value << c;
}
}
else
{
if ( c == wxT('"') )
{
state = 0;
labelValid = true;
}
else
label << c;
}
}
if ( labelValid )
{
long l;
if ( !value.ToLong(&l, 0) ) l = wxPG_INVALID_VALUE;
choices.Add(label, l);
}
if ( !choices.IsOk() )
{
choices.EnsureData();
}
// Assign to id
if ( !idString.empty() )
m_dictIdChoices[idString] = choices.GetData();
}
}
return choices;
}
// -----------------------------------------------------------------------
bool wxPropertyGridPopulator::ToLongPCT( const wxString& s, long* pval, long max )
{
if ( s.Last() == wxT('%') )
{
wxString s2 = s.substr(0,s.length()-1);
long val;
if ( s2.ToLong(&val, 10) )
{
*pval = (val*max)/100;
return true;
}
return false;
}
return s.ToLong(pval, 10);
}
// -----------------------------------------------------------------------
bool wxPropertyGridPopulator::AddAttribute( const wxString& name,
const wxString& type,
const wxString& value )
{
int l = m_propHierarchy.size();
if ( !l )
return false;
wxPGProperty* p = m_propHierarchy[l-1];
wxString valuel = value.Lower();
wxVariant variant;
if ( type.empty() )
{
long v;
// Auto-detect type
if ( valuel == wxT("true") || valuel == wxT("yes") || valuel == wxT("1") )
variant = true;
else if ( valuel == wxT("false") || valuel == wxT("no") || valuel == wxT("0") )
variant = false;
else if ( value.ToLong(&v, 0) )
variant = v;
else
variant = value;
}
else
{
if ( type == wxT("string") )
{
variant = value;
}
else if ( type == wxT("int") )
{
long v = 0;
value.ToLong(&v, 0);
variant = v;
}
else if ( type == wxT("bool") )
{
if ( valuel == wxT("true") || valuel == wxT("yes") || valuel == wxT("1") )
variant = true;
else
variant = false;
}
else
{
ProcessError(wxString::Format(wxT("Invalid attribute type '%s'"),type.c_str()));
return false;
}
}
p->SetAttribute( name, variant );
return true;
}
// -----------------------------------------------------------------------
void wxPropertyGridPopulator::ProcessError( const wxString& msg )
{
wxLogError(_("Error in resource: %s"),msg.c_str());
}
// -----------------------------------------------------------------------
#endif // wxUSE_PROPGRID
| lgpl-3.0 |
kejace/go-ethereum | crypto/encrypt_decrypt_test.go | 1754 | // Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package crypto
import (
"bytes"
"fmt"
"testing"
"github.com/kejace/go-ethereum/common"
)
func TestBox(t *testing.T) {
prv1 := ToECDSA(common.Hex2Bytes("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f"))
prv2 := ToECDSA(common.Hex2Bytes("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a"))
pub2 := ToECDSAPub(common.Hex2Bytes("04bd27a63c91fe3233c5777e6d3d7b39204d398c8f92655947eb5a373d46e1688f022a1632d264725cbc7dc43ee1cfebde42fa0a86d08b55d2acfbb5e9b3b48dc5"))
message := []byte("Hello, world.")
ct, err := Encrypt(pub2, message)
if err != nil {
fmt.Println(err.Error())
t.FailNow()
}
pt, err := Decrypt(prv2, ct)
if err != nil {
fmt.Println(err.Error())
t.FailNow()
}
if !bytes.Equal(pt, message) {
fmt.Println("ecies: plaintext doesn't match message")
t.FailNow()
}
_, err = Decrypt(prv1, pt)
if err == nil {
fmt.Println("ecies: encryption should not have succeeded")
t.FailNow()
}
}
| lgpl-3.0 |
R3ap3rG/ModularDrones | src/main/java/com/R3ap3rG/modulardrones/block/BlockTin.java | 220 | package com.R3ap3rG.modulardrones.block;
import com.R3ap3rG.modulardrones.handler.BlockMD;
public class BlockTin extends BlockMD {
public BlockTin(){
super();
this.setBlockName("blockTin");
}
}
| lgpl-3.0 |
MProbe/mprobe | src/standaloneexample/standaloneexample.cpp | 9958 | /*
Copyright (C) 2011 Walter Waldron
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 <mprobe.h>
#include <iostream>
std::string stripCRLF(std::string str)
{
size_t firstCRLF = str.find_first_of('\r');
while (firstCRLF != std::string::npos)
{
str = str.erase(firstCRLF, 1);
firstCRLF = str.find_first_of('\r');
}
firstCRLF = str.find_first_of('\n');
while (firstCRLF != std::string::npos)
{
str = str.erase(firstCRLF, 1);
firstCRLF = str.find_first_of('\n');
}
return str;
}
std::string empShapeToStr(uint8_t empShape)
{
switch (empShape) {
case ESShapeError:
return "Error";
case ESTooManyMathErrors:
return "MathErrs";
case ESNotAvailable:
return "NotAvail";
case ESLinear:
return "Linear";
case ESAlmostLinBoth:
return "AlmostLinear(Both)";
case ESAlmostConcave:
return "AlmostConcave";
case ESAlmostConvex:
return "AlmostConvex";
case ESConvex:
return "Convex";
case ESConcave:
return "Concave";
case ESBothConc:
return "Conc.&Conv.";
}
return "";
}
int main(int argc, const char** argv)
{
if (argc < 3)
{
std::cerr << "Usage: " << argv[0] << "pluginfile modelfiles...\n";
return 0;
}
mprobe_init();
mp_loadPlugins(argv[1]);
if (mp_loadedPlugins() <= 0)
{
std::cerr << "No plugins loaded from file: " << argv[1];
std::cerr << "\n Exiting...\n";
mprobe_deinit();
return 1;
}
else
{
std::cout << "Loaded " << mp_loadedPlugins() << " plugins.\n\n";
}
MPHandle model = mp_load( argc - 2, argv + 2);
if (model == MPNULL)
{
std::cerr << "Failed to load model from files:\n";
for (int i = 0; i < argc - 2; ++i)
{
std::cerr << "\t" << argv[2 + i];
}
std::cerr << "\n Exiting...\n";
mprobe_deinit();
return 2;
}
const char* name = mp_instanceName(model);
std::cout << "Loaded model: " << name << std::endl;
mp_releaseName(model, name);
int totvars;
int rvars = 0, ivars = 0, bvars = 0;
totvars = mp_variables(model);
for (int i = 0; i < totvars; i++)
{
switch (mp_variableType(model, i))
{
case 'r':
rvars++;
break;
case 'b':
bvars++;
break;
case 'i':
ivars++;
break;
}
}
std::cout << "Variables: " << totvars << std::endl;
std::cout << "\tReal: " << rvars << std::endl;
std::cout << "\tInteger: " << ivars << std::endl;
std::cout << "\tBinary: " << bvars << std::endl;
int totobjs = 0, linobjs = 0, quadobjs = 0, nonlinobjs = 0;
int nzinobjs = 0;
int* presences = new int[totvars];
totobjs = mp_objectives(model);
for (int i = 0; i < totobjs; i++)
{
switch (mp_functionType(model, 'o', i))
{
case 'l':
linobjs++;
break;
case 'q':
quadobjs++;
break;
case 'n':
nonlinobjs++;
break;
}
nzinobjs += mp_objectiveVariables(model, i, presences);
}
std::cout << "Objectives: " << totobjs << std::endl;
std::cout << "\tLinear: " << linobjs << std::endl;
std::cout << "\tQuadratic: " << quadobjs << std::endl;
std::cout << "\tNonlinear: " << nonlinobjs << std::endl;
int totconst = 0, linconst = 0, quadconst = 0, nonlinconst = 0;
int linrng = 0, lineq = 0, linineq = 0;
int quadrng = 0, quadeq = 0, quadineq = 0;
int nonlinrng = 0, nonlineq = 0, nonlinineq = 0;
int nzsinconstrs = 0;
totconst = mp_constraints(model);
for (int i = 0; i < totconst; i++)
{
int ftype = mp_functionType(model, 'c', i);
int constrType = mp_constraintType(model, i);
if (ftype == 'l' && constrType == 'r')
linconst++, linrng++;
else if (ftype == 'l' && constrType == 'e')
linconst++, lineq++;
else if (ftype == 'l' && constrType != 'u')
linconst++, linineq++;
else if (ftype == 'q' && constrType == 'r')
quadconst++, quadrng++;
else if (ftype == 'q' && constrType == 'e')
quadconst++, quadeq++;
else if (ftype == 'q' && constrType != 'u')
quadconst++, quadineq++;
else if (ftype == 'n' && constrType == 'r')
nonlinconst++, nonlinrng++;
else if (ftype == 'n' && constrType == 'e')
nonlinconst++, nonlineq++;
else if (ftype == 'n' && constrType != 'u')
nonlinconst++, nonlinineq++;
nzsinconstrs += mp_constraintVariables(model, i, presences);
}
std::cout << "Constraints: " << totconst << std::endl;
std::cout << "\tLinear: " << linconst << std::endl;
std::cout << "\t\tinequalities: " << linineq << std::endl;
std::cout << "\t\tranges: " << linrng << std::endl;
std::cout << "\t\tequalites: " << lineq << std::endl;
std::cout << "\tQuadratic: " << quadconst << std::endl;
std::cout << "\t\tinequalities: " << quadineq << std::endl;
std::cout << "\t\tranges: " << quadrng << std::endl;
std::cout << "\t\tequalites: " << quadeq << std::endl;
std::cout << "\tNonlinear: " << nonlinconst << std::endl;
std::cout << "\t\tinequalities: " << nonlinineq << std::endl;
std::cout << "\t\tranges: " << nonlinrng << std::endl;
std::cout << "\t\tequalites: " << nonlineq << std::endl;
std::cout << "Non-zeros:\n";
std::cout << "\tIn objectives: " << nzinobjs << std::endl;
std::cout << "\tIn constraints: " << nzsinconstrs << std::endl;
std::cout << "\nPresences:\n";
for (int i = 0; i < totconst; ++i)
{
const int numVarPerLine = 4;
int j;
int varsInConstr = mp_constraintVariables(model, i, presences);
name = mp_constraintName(model, i);
std::string tmp1 = stripCRLF(name);
mp_releaseName(model, name);
std::cout << "Constraint " << tmp1 << " uses variables: \n";
for (j = 0; j < varsInConstr; ++j)
{
if (j % numVarPerLine == 0)
std::cout << '\t';
name = mp_variableName(model, presences[j]);
std::string tmp2 = stripCRLF(name);
mp_releaseName(model, name);
std::cout << tmp2;
if (j + 1 < varsInConstr)
{
if (j % numVarPerLine < numVarPerLine - 1)
{
std::cout << ", ";
}
else
{
std::cout << '\n';
}
}
}
std::cout << '\n';
}
for (int i = 0; i < totobjs; ++i)
{
const int numVarPerLine = 4;
int j;
int varsInObjs = mp_objectiveVariables(model, i, presences);
name = mp_objectiveName(model, i);
std::string tmp1 = stripCRLF(name);
mp_releaseName(model, name);
std::cout << "Objective " << tmp1 << " uses variables: \n";
for (j = 0; j < varsInObjs; ++j)
{
if (j % numVarPerLine == 0)
std::cout << '\t';
name = mp_variableName(model, presences[j]);
std::string tmp2 = stripCRLF(name);
mp_releaseName(model, name);
std::cout << tmp2;
if (j + 1 < varsInObjs)
{
if (j % numVarPerLine < numVarPerLine - 1)
{
std::cout << ", ";
}
else
{
std::cout << '\n';
}
}
}
std::cout << '\n';
}
delete [] presences;
MPHandle analysis = mp_createAnalysis(model);
std::cout << "\nBeginning automated analysis:\n";
std::cout << "\nUsing default settings:\n";
std::cout << "Line length maximum: " << mp_aLineLengthMax(analysis) << std::endl;
std::cout << "Line length minimum: " << mp_aLineLengthMin(analysis) << std::endl;
std::cout << "Snapping discrete components: " << (mp_aSnapDiscreteComponents(analysis) ? "true": "false") << std::endl;
std::cout << "Number of line segments: " << mp_aNumLineSegments(analysis) << std::endl;
std::cout << "Interior line points: " << mp_aInteriorLinePoints(analysis) << std::endl;
std::cout << "Minimum points needed for conclusions: " << mp_aMinimumPointsNeeded(analysis) << std::endl;
std::cout << "Evaluation error tolerance: " << mp_aEvalErrorTolerance(analysis) << std::endl;
std::cout << "Infinity: " << mp_aInfinity(analysis) << std::endl;
std::cout << "Equality tolerance: " << mp_aEqualityTolerance(analysis) << std::endl;
std::cout << "Almost equal tolerance: " << mp_aAlmostEqualTolerance(analysis) << std::endl;
for (int i = 0; i < totconst; ++i)
{
mp_aVariableBoundLineSample(analysis, 'c', i, false);
}
for (int i = 0; i < totobjs; ++i)
{
mp_aVariableBoundLineSample(analysis, 'o', i, false);
}
std::cout << "\nAnalysis results:\n";
std::cout << "Constraints:\n";
std::cout << "Name\t" << "Emp.Shape\t" << "Reg.Effect\t" << "Tot.Eff\t" << "LB.Eff\t" << "UB.Eff\n";
for (int i = 0; i < totconst; ++i)
{
Real lbEff, ubEff;
name = mp_constraintName(model, i);
std::cout << stripCRLF(name) << '\t';
mp_releaseName(model, name);
std::cout << empShapeToStr(mp_aGetEmpiricalShape(analysis, i, 'c')) << "\t";
switch(mp_aGetRegionEffect(analysis, i))
{
case REConvex:
std::cout << "Convex\t"; break;
case RENonconvex:
std::cout << "Nonconvex\t"; break;
case REAlmost:
std::cout << "Almost\t"; break;
}
mp_aEffectiveness(analysis, i, &lbEff, &ubEff);
std::cout << lbEff + ubEff << "\t" << lbEff << "\t" << ubEff << "\n";
}
std::cout << "Objectives:\n";
std::cout << "Name\t" << "Emp.Shape\t" << "BestPt.\t" << "Opt.Eff\n";
for (int i = 0; i < totobjs; ++i)
{
Real extremum;
name = mp_objectiveName(model, i);
std::cout << stripCRLF(name) << '\t';
mp_releaseName(model, name);
std::cout << empShapeToStr(mp_aGetEmpiricalShape(analysis, i, 'o')) << "\t";
mp_aExtremum(analysis, i, &extremum);
std::cout << extremum << "\t";
switch (mp_aGetOptimumEffect(analysis, i)) {
case ObjectiveLocal:
std::cout << "Local"; break;
case ObjectiveGlobal:
std::cout << "Global"; break;
case ObjectiveAlmostGlobal:
std::cout << "AlmostGlobal"; break;
}
std::cout << std::endl;
}
mp_releaseAnalysis(analysis);
mp_unload(model);
mprobe_deinit();
return 0;
} | lgpl-3.0 |
daa84/neovim-lib | src/rpc/model.rs | 6818 | use rmpv::decode::read_value;
use rmpv::encode::write_value;
use rmpv::Value;
use std::error::Error;
use std::io;
use std::io::{Read, Write};
#[derive(Debug, PartialEq, Clone)]
pub enum RpcMessage {
RpcRequest {
msgid: u64,
method: String,
params: Vec<Value>,
}, // 0
RpcResponse {
msgid: u64,
error: Value,
result: Value,
}, // 1
RpcNotification {
method: String,
params: Vec<Value>,
}, // 2
}
macro_rules! try_str {
($exp:expr, $msg:expr) => {
match $exp {
Value::String(val) => match val.into_str() {
Some(s) => s,
None => return Err(Box::new(io::Error::new(io::ErrorKind::Other, $msg))),
},
_ => return Err(Box::new(io::Error::new(io::ErrorKind::Other, $msg))),
}
};
}
macro_rules! try_int {
($exp:expr, $msg:expr) => {
match $exp.as_u64() {
Some(val) => val,
_ => return Err(Box::new(io::Error::new(io::ErrorKind::Other, $msg))),
}
};
}
macro_rules! try_arr {
($exp:expr, $msg:expr) => {
match $exp {
Value::Array(arr) => arr,
_ => return Err(Box::new(io::Error::new(io::ErrorKind::Other, $msg))),
}
};
}
macro_rules! rpc_args {
($($e:expr), *) => {{
let mut vec = Vec::new();
$(
vec.push(Value::from($e));
)*
Value::from(vec)
}}
}
pub fn decode<R: Read>(reader: &mut R) -> Result<RpcMessage, Box<dyn Error>> {
let mut arr = try_arr!(read_value(reader)?, "Rpc message must be array");
match try_int!(arr[0], "Can't find message type") {
0 => {
arr.truncate(4);
let params = try_arr!(arr.pop().unwrap(), "params not found"); // [3]
let method = try_str!(arr.pop().unwrap(), "method not found"); // [2]
let msgid = try_int!(arr.pop().unwrap(), "msgid not found"); // [1]
Ok(RpcMessage::RpcRequest {
msgid,
method,
params,
})
}
1 => {
arr.truncate(4);
let msgid = try_int!(arr[1], "msgid not found");
let result = arr.pop().unwrap(); // [3]
let error = arr.pop().unwrap(); // [2]
Ok(RpcMessage::RpcResponse {
msgid,
error,
result,
})
}
2 => {
arr.truncate(3);
let params = try_arr!(arr.pop().unwrap(), "params not found"); // [2]
let method = try_str!(arr.pop().unwrap(), "method not found"); // [1]
Ok(RpcMessage::RpcNotification { method, params })
}
_ => Err(Box::new(io::Error::new(
io::ErrorKind::Other,
"Not nown type",
))),
}
}
pub fn encode<W: Write>(writer: &mut W, msg: RpcMessage) -> Result<(), Box<dyn Error>> {
match msg {
RpcMessage::RpcRequest {
msgid,
method,
params,
} => {
let val = rpc_args!(0, msgid, method, params);
write_value(writer, &val)?;
}
RpcMessage::RpcResponse {
msgid,
error,
result,
} => {
let val = rpc_args!(1, msgid, error, result);
write_value(writer, &val)?;
}
RpcMessage::RpcNotification { method, params } => {
let val = rpc_args!(2, method, params);
write_value(writer, &val)?;
}
};
writer.flush()?;
Ok(())
}
pub trait FromVal<T> {
fn from_val(_: T) -> Self;
}
impl FromVal<Value> for () {
fn from_val(_: Value) -> Self {
()
}
}
impl FromVal<Value> for Value {
fn from_val(val: Value) -> Self {
val
}
}
impl FromVal<Value> for Vec<(Value, Value)> {
fn from_val(val: Value) -> Self {
if let Value::Map(vec) = val {
return vec;
}
panic!("Not supported value for map");
}
}
impl<T: FromVal<Value>> FromVal<Value> for Vec<T> {
fn from_val(val: Value) -> Self {
if let Value::Array(arr) = val {
return arr.into_iter().map(T::from_val).collect();
}
panic!("Can't convert to array");
}
}
impl FromVal<Value> for (i64, i64) {
fn from_val(val: Value) -> Self {
let res = val
.as_array()
.expect("Can't convert to point(i64,i64) value");
if res.len() != 2 {
panic!("Array length must be 2");
}
(
res[0].as_i64().expect("Can't get i64 value at position 0"),
res[1].as_i64().expect("Can't get i64 value at position 1"),
)
}
}
impl FromVal<Value> for bool {
fn from_val(val: Value) -> Self {
if let Value::Boolean(res) = val {
return res;
}
panic!("Can't convert to bool");
}
}
impl FromVal<Value> for String {
fn from_val(val: Value) -> Self {
val.as_str().expect("Can't convert to string").to_owned()
}
}
impl FromVal<Value> for i64 {
fn from_val(val: Value) -> Self {
val.as_i64().expect("Can't convert to i64")
}
}
pub trait IntoVal<T> {
fn into_val(self) -> T;
}
impl<'a> IntoVal<Value> for &'a str {
fn into_val(self) -> Value {
Value::from(self)
}
}
impl IntoVal<Value> for Vec<String> {
fn into_val(self) -> Value {
let vec: Vec<Value> = self.into_iter().map(Value::from).collect();
Value::from(vec)
}
}
impl IntoVal<Value> for Vec<Value> {
fn into_val(self) -> Value {
Value::from(self)
}
}
impl IntoVal<Value> for (i64, i64) {
fn into_val(self) -> Value {
Value::from(vec![Value::from(self.0), Value::from(self.1)])
}
}
impl IntoVal<Value> for bool {
fn into_val(self) -> Value {
Value::from(self)
}
}
impl IntoVal<Value> for i64 {
fn into_val(self) -> Value {
Value::from(self)
}
}
impl IntoVal<Value> for String {
fn into_val(self) -> Value {
Value::from(self)
}
}
impl IntoVal<Value> for Value {
fn into_val(self) -> Value {
self
}
}
impl IntoVal<Value> for Vec<(Value, Value)> {
fn into_val(self) -> Value {
Value::from(self)
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::{Cursor, Seek, SeekFrom};
#[test]
fn request_test() {
let msg = RpcMessage::RpcRequest {
msgid: 1,
method: "test_method".to_owned(),
params: vec![],
};
let mut buff = Cursor::new(vec![]);
encode(&mut buff, msg.clone()).unwrap();
buff.seek(SeekFrom::Start(0)).unwrap();
let msg_dest = decode(&mut buff).unwrap();
assert_eq!(msg, msg_dest);
}
}
| lgpl-3.0 |
efreesen/active_repository | lib/active_repository/adapters/default_adapter.rb | 1532 | class DefaultAdapter
class << self
def all(klass)
klass.persistence_class.all
end
def delete(klass, id)
object = klass.persistence_class.where(id: id).first
object.delete if object
end
def delete_all(klass)
klass.persistence_class.delete_all
end
def exists?(klass, id)
klass.persistence_class.exists?(id)
end
def find(klass, id)
id = normalize_id(id) if id
klass.persistence_class.find(id)
end
def first(klass)
klass.persistence_class.first
end
def last(klass)
klass.persistence_class.last
end
def create(klass, attributes)
object = klass.persistence_class.create(attributes)
end
def update_attribute(klass, id, key, value)
object = id.nil? ? klass.persistence_class.new(key.to_sym => value) : klass.persistence_class.find(id)
ret = object.update_attribute(key, value)
[ret, object]
end
def update_attributes(klass, id, attributes)
object = id.nil? ? klass.persistence_class.new : klass.persistence_class.find(id)
ret = object.update_attributes(attributes)
[ret, object]
end
def where(klass, query)
klass.persistence_class.where(query.to_sql)
end
private
def normalize_id(args)
return args if args.is_a?(Array)
id = (args.is_a?(Hash) ? args[:id] : args)
convertable?(id) ? id.to_i : id
end
def convertable?(id)
id.respond_to?(:to_i) && id.to_s == id.to_i.to_s
end
end
end | lgpl-3.0 |
MarkAYoder/bone101 | examples/Grove_BBG/Software/Python/Grove_3_Axis_Digital_Accelerometer_lib.py | 2319 | import smbus
import time
bus = smbus.SMBus(1)
class MMA7660():
def __init__(self):
self.MMA7660_ADDR = 0x4c
self.MMA7660_X = 0x00
self.MMA7660_Y = 0x01
self.MMA7660_Z = 0x02
self.MMA7660_TILT = 0x03
self.MMA7660_SRST = 0x04
self.MMA7660_SPCNT = 0x05
self.MMA7660_INTSU = 0x06
self.MMA7660_MODE = 0x07
self.MMA7660_STAND_BY = 0x00
self.MMA7660_ACTIVE = 0x01
self.MMA7660_SR = 0x08 #sample rate register
self.AUTO_SLEEP_120 = 0X00 #120 sample per second
self.AUTO_SLEEP_64 = 0X01
self.AUTO_SLEEP_32 = 0X02
self.AUTO_SLEEP_16 = 0X03
self.AUTO_SLEEP_8 = 0X04
self.AUTO_SLEEP_4 = 0X05
self.AUTO_SLEEP_2 = 0X06
self.AUTO_SLEEP_1 = 0X07
self.MMA7660_PDET = 0x09
self.MMA7660_PD = 0x0A
self.setMode(self.MMA7660_STAND_BY)
self.setSample(self.AUTO_SLEEP_32)
self.setMode(self.MMA7660_ACTIVE)
def setMode(self, mode):
bus.write_byte_data(self.MMA7660_ADDR, self.MMA7660_MODE, mode)
def setSample(self, rate):
bus.write_byte_data(self.MMA7660_ADDR, self.MMA7660_SR, rate)
def getXYZ(self):
val = [0 for i in range(3)]
val[0] = val[1] = val[2] = 64
count = 0
#while i2c avaliable
# while True:
# if count < 3:
# while val[count] > 63:
# val[count] = bus.read_byte(self.MMA7660_ADDR)
# count += 1
# else:
# break
val = bus.read_i2c_block_data(self.MMA7660_ADDR,0x00)
# print val
return val
def getAccelerometer(self):
x,y,z = self.getXYZ()[:3]
x, y, z = x*4,y*4,z*4
if x>127:
x = x-256
if y>127:
y=y-256
if z>127:
z=z-256
return x/4/21.0, y/4/21.0, z/4/21.0
if __name__=="__main__":
acc = MMA7660()
while True:
ax,ay,az = acc.getAccelerometer()
print 'ax=%.2f'%(ax),'ay=%.2f'%(ay),'az=%.2f'%(az)
time.sleep(.1)
| lgpl-3.0 |
jussenadv/ij1Android | src/ij/gui/PointRoi.java | 6032 | package ij.gui;
import java.awt.*;
import java.awt.image.*;
import ij.*;
import ij.process.*;
import ij.measure.*;
import ij.plugin.filter.Analyzer;
import java.awt.event.KeyEvent;
import ij.plugin.frame.Recorder;
import ij.util.Java2;
/** This class represents a collection of points. */
public class PointRoi extends PolygonRoi {
private static Font font;
private static int fontSize = 9;
private double saveMag;
private boolean hideLabels;
/** Creates a new PointRoi using the specified int arrays of offscreen coordinates. */
public PointRoi(int[] ox, int[] oy, int points) {
super(itof(ox), itof(oy), points, POINT);
width+=1; height+=1;
}
/** Creates a new PointRoi using the specified float arrays of offscreen coordinates. */
public PointRoi(float[] ox, float[] oy, int points) {
super(ox, oy, points, POINT);
width+=1; height+=1;
}
/** Creates a new PointRoi from a FloatPolygon. */
public PointRoi(FloatPolygon poly) {
this(poly.xpoints, poly.ypoints, poly.npoints);
}
/** Creates a new PointRoi from a Polygon. */
public PointRoi(Polygon poly) {
this(itof(poly.xpoints), itof(poly.ypoints), poly.npoints);
}
/** Creates a new PointRoi using the specified offscreen int coordinates. */
public PointRoi(int ox, int oy) {
super(makeXArray(ox, null), makeYArray(oy, null), 1, POINT);
width=1; height=1;
}
/** Creates a new PointRoi using the specified offscreen double coordinates. */
public PointRoi(double ox, double oy) {
super(makeXArray(ox, null), makeYArray(oy, null), 1, POINT);
width=1; height=1;
}
/** Creates a new PointRoi using the specified screen coordinates. */
public PointRoi(int sx, int sy, ImagePlus imp) {
super(makeXArray(sx, imp), makeYArray(sy, imp), 1, POINT);
setImage(imp);
width=1; height=1;
if (imp!=null) imp.draw(x-5, y-5, width+10, height+10);
if (Recorder.record && !Recorder.scriptMode())
Recorder.record("makePoint", x, y);
}
static float[] itof(int[] arr) {
if (arr==null)
return null;
int n = arr.length;
float[] temp = new float[n];
for (int i=0; i<n; i++)
temp[i] = arr[i];
return temp;
}
static float[] makeXArray(double value, ImagePlus imp) {
float[] array = new float[1];
array[0] = (float)(imp!=null?imp.getCanvas().offScreenXD((int)value):value);
return array;
}
static float[] makeYArray(double value, ImagePlus imp) {
float[] array = new float[1];
array[0] = (float)(imp!=null?imp.getCanvas().offScreenYD((int)value):value);
return array;
}
void handleMouseMove(int ox, int oy) {
//IJ.log("handleMouseMove");
}
protected void handleMouseUp(int sx, int sy) {
super.handleMouseUp(sx, sy);
modifyRoi(); //adds this point to previous points if shift key down
}
/** Draws the points on the image. */
public void draw(Graphics g) {
//IJ.log("draw: " + nPoints+" "+width+" "+height);
updatePolygon();
//IJ.log("draw: "+ xpf[0]+" "+ypf[0]+" "+xp2[0]+" "+yp2[0]);
if (ic!=null) mag = ic.getMagnification();
int size2 = HANDLE_SIZE/2;
if (!Prefs.noPointLabels && !hideLabels && nPoints>1) {
fontSize = 9;
if (mag>1.0)
fontSize = (int)(((mag-1.0)/3.0+1.0)*9.0);
if (fontSize>18) fontSize = 18;
if (font==null || mag!=saveMag)
font = new Font("SansSerif", Font.PLAIN, fontSize);
g.setFont(font);
if (fontSize>9)
Java2.setAntialiasedText(g, true);
saveMag = mag;
}
for (int i=0; i<nPoints; i++)
drawPoint(g, xp2[i]-size2, yp2[i]-size2, i+1);
//showStatus();
if (updateFullWindow)
{updateFullWindow = false; imp.draw();}
}
void drawPoint(Graphics g, int x, int y, int n) {
g.setColor(fillColor!=null?fillColor:Color.white);
g.drawLine(x-4, y+2, x+8, y+2);
g.drawLine(x+2, y-4, x+2, y+8);
g.setColor(strokeColor!=null?strokeColor:ROIColor);
g.fillRect(x+1,y+1,3,3);
if (!Prefs.noPointLabels && !hideLabels && nPoints>1)
g.drawString(""+n, x+6, y+fontSize+4);
g.setColor(Color.black);
g.drawRect(x, y, 4, 4);
}
public void drawPixels(ImageProcessor ip) {
ip.setLineWidth(Analyzer.markWidth);
for (int i=0; i<nPoints; i++) {
ip.moveTo(x+(int)xpf[i], y+(int)ypf[i]);
ip.lineTo(x+(int)xpf[i], y+(int)ypf[i]);
}
}
/** Returns a copy of this PointRoi with a point at (x,y) added. */
public PointRoi addPoint(double x, double y) {
FloatPolygon poly = getFloatPolygon();
poly.addPoint(x, y);
PointRoi p = new PointRoi(poly.xpoints, poly.ypoints, poly.npoints);
p.setHideLabels(hideLabels);
IJ.showStatus("count="+poly.npoints);
return p;
}
public PointRoi addPoint(int x, int y) {
return addPoint((double)x, (double)y);
}
/** Subtract the points that intersect the specified ROI and return
the result. Returns null if there are no resulting points. */
public PointRoi subtractPoints(Roi roi) {
Polygon points = getPolygon();
Polygon poly = roi.getPolygon();
Polygon points2 = new Polygon();
for (int i=0; i<points.npoints; i++) {
if (!poly.contains(points.xpoints[i], points.ypoints[i]))
points2.addPoint(points.xpoints[i], points.ypoints[i]);
}
if (points2.npoints==0)
return null;
else
return new PointRoi(points2.xpoints, points2.ypoints, points2.npoints);
}
public ImageProcessor getMask() {
if (cachedMask!=null && cachedMask.getPixels()!=null)
return cachedMask;
ImageProcessor mask = new ByteProcessor(width, height);
for (int i=0; i<nPoints; i++) {
mask.putPixel((int)xpf[i], (int)ypf[i], 255);
}
cachedMask = mask;
return mask;
}
/** Returns true if (x,y) is one of the points in this collection. */
public boolean contains(int x, int y) {
for (int i=0; i<nPoints; i++) {
if (x==this.x+xpf[i] && y==this.y+ypf[i]) return true;
}
return false;
}
public void setHideLabels(boolean hideLabels) {
this.hideLabels = hideLabels;
}
/** Always returns true. */
public boolean subPixelResolution() {
return true;
}
public String toString() {
if (nPoints>1)
return ("Roi[Points, count="+nPoints+"]");
else
return ("Roi[Point, x="+x+", y="+y+"]");
}
}
| lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/VendorQueryRs.java | 3297 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: VendorQueryRs.java,v 1.1.1.1 2010-05-04 22:06:00 ryan Exp $
*/
package org.chocolate_milk.model;
/**
* Class VendorQueryRs.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:00 $
*/
@SuppressWarnings("serial")
public class VendorQueryRs extends VendorQueryRsType
implements java.io.Serializable
{
//----------------/
//- Constructors -/
//----------------/
public VendorQueryRs() {
super();
}
//-----------/
//- Methods -/
//-----------/
/**
* Method isValid.
*
* @return true if this object is valid according to the schema
*/
public boolean isValid(
) {
try {
validate();
} catch (org.exolab.castor.xml.ValidationException vex) {
return false;
}
return true;
}
/**
*
*
* @param out
* @throws org.exolab.castor.xml.MarshalException if object is
* null or if any SAXException is thrown during marshaling
* @throws org.exolab.castor.xml.ValidationException if this
* object is an invalid instance according to the schema
*/
public void marshal(
final java.io.Writer out)
throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
org.exolab.castor.xml.Marshaller.marshal(this, out);
}
/**
*
*
* @param handler
* @throws java.io.IOException if an IOException occurs during
* marshaling
* @throws org.exolab.castor.xml.ValidationException if this
* object is an invalid instance according to the schema
* @throws org.exolab.castor.xml.MarshalException if object is
* null or if any SAXException is thrown during marshaling
*/
public void marshal(
final org.xml.sax.ContentHandler handler)
throws java.io.IOException, org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
org.exolab.castor.xml.Marshaller.marshal(this, handler);
}
/**
* Method unmarshal.
*
* @param reader
* @throws org.exolab.castor.xml.MarshalException if object is
* null or if any SAXException is thrown during marshaling
* @throws org.exolab.castor.xml.ValidationException if this
* object is an invalid instance according to the schema
* @return the unmarshaled org.chocolate_milk.model.VendorQueryR
*/
public static org.chocolate_milk.model.VendorQueryRs unmarshal(
final java.io.Reader reader)
throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
return (org.chocolate_milk.model.VendorQueryRs) org.exolab.castor.xml.Unmarshaller.unmarshal(org.chocolate_milk.model.VendorQueryRs.class, reader);
}
/**
*
*
* @throws org.exolab.castor.xml.ValidationException if this
* object is an invalid instance according to the schema
*/
public void validate(
)
throws org.exolab.castor.xml.ValidationException {
org.exolab.castor.xml.Validator validator = new org.exolab.castor.xml.Validator();
validator.validate(this);
}
}
| lgpl-3.0 |
delphiprogramming/gisgraphy | src/main/java/com/gisgraphy/importer/OpenStreetMapCitiesSimpleImporter.java | 17412 | /*******************************************************************************
* Gisgraphy Project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
*
* Copyright 2008 Gisgraphy project
* David Masclet <davidmasclet@gisgraphy.com>
*
*
*******************************************************************************/
package com.gisgraphy.importer;
import static com.gisgraphy.domain.geoloc.entity.GisFeature.NAME_MAX_LENGTH;
import static com.gisgraphy.fulltext.Constants.ONLY_ADM_PLACETYPE;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.hibernate.FlushMode;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import com.gisgraphy.domain.geoloc.entity.Adm;
import com.gisgraphy.domain.geoloc.entity.AlternateName;
import com.gisgraphy.domain.geoloc.entity.City;
import com.gisgraphy.domain.geoloc.entity.CitySubdivision;
import com.gisgraphy.domain.geoloc.entity.GisFeature;
import com.gisgraphy.domain.geoloc.entity.ZipCode;
import com.gisgraphy.domain.repository.CitySubdivisionDao;
import com.gisgraphy.domain.repository.IAdmDao;
import com.gisgraphy.domain.repository.ICityDao;
import com.gisgraphy.domain.repository.IIdGenerator;
import com.gisgraphy.domain.repository.ISolRSynchroniser;
import com.gisgraphy.domain.valueobject.AlternateNameSource;
import com.gisgraphy.domain.valueobject.GISSource;
import com.gisgraphy.domain.valueobject.NameValueDTO;
import com.gisgraphy.domain.valueobject.Output;
import com.gisgraphy.domain.valueobject.Output.OutputStyle;
import com.gisgraphy.domain.valueobject.Pagination;
import com.gisgraphy.fulltext.Constants;
import com.gisgraphy.fulltext.FullTextSearchEngine;
import com.gisgraphy.fulltext.FulltextQuery;
import com.gisgraphy.fulltext.FulltextResultsDto;
import com.gisgraphy.fulltext.IFullTextSearchEngine;
import com.gisgraphy.fulltext.SolrResponseDto;
import com.gisgraphy.helper.GeolocHelper;
import com.gisgraphy.util.StringUtil;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
/**
* Import the cities from an (pre-processed) openStreet map data file.
* The goal of this importer is to cross information between geonames and Openstreetmap.
* Geonames has no concept of city but of populated place (That can be a city, suburb or other)
* By cross the informations we can add shape and set a 'municipality' flag to identify city.
*
*
* @author <a href="mailto:david.masclet@gisgraphy.com">David Masclet</a>
*/
public class OpenStreetMapCitiesSimpleImporter extends AbstractSimpleImporterProcessor {
public static final int SCORE_LIMIT = 1;
protected static final Logger logger = LoggerFactory.getLogger(OpenStreetMapCitiesSimpleImporter.class);
public static final Output MINIMUM_OUTPUT_STYLE = Output.withDefaultFormat().withStyle(OutputStyle.SHORT);
public static final String ALTERNATENAMES_EXTRACTION_REGEXP = "((?:(?!___).)+)(?:(?:___)|(?:$))";
public static final Pattern ALTERNATENAMES_EXTRACTION_PATTERN = Pattern.compile(ALTERNATENAMES_EXTRACTION_REGEXP);
protected IIdGenerator idGenerator;
protected ICityDao cityDao;
protected CitySubdivisionDao citySubdivisionDao;
protected IAdmDao admDao;
protected ISolRSynchroniser solRSynchroniser;
protected IFullTextSearchEngine fullTextSearchEngine;
protected IMunicipalityDetector municipalityDetector;
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.AbstractImporterProcessor#flushAndClear()
*/
@Override
protected void flushAndClear() {
cityDao.flushAndClear();
}
@Override
protected void setup() {
super.setup();
//temporary disable logging when importing
FullTextSearchEngine.disableLogging=true;
logger.info("reseting Openstreetmap generatedId");
idGenerator.sync();
}
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.AbstractImporterProcessor#getFiles()
*/
@Override
protected File[] getFiles() {
return ImporterHelper.listCountryFilesToImport(importerConfig.getOpenStreetMapCitiesDir());
}
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.AbstractImporterProcessor#getNumberOfColumns()
*/
@Override
protected int getNumberOfColumns() {
return 11;
}
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.AbstractImporterProcessor#processData(java.lang.String)
*/
@Override
protected void processData(String line) throws ImporterException {
String[] fields = line.split("\t");
String countrycode=null;
String name=null;
Point location=null;
//
// Line table has the following fields :
// ---------------------------------------------------
//0: N|W|R; 1 id; 2 name; 3 countrycode; 4 :postcode
//5:population 6:location; 7 : shape ;8: place tag; 9 : is_in;
// 10 : alternatenames
//
checkNumberOfColumn(fields);
// name
if (!isEmptyField(fields, 2, false)) {
name=fields[2].trim();
if (name.length() > NAME_MAX_LENGTH){
logger.warn(name + "is too long");
name= name.substring(0, NAME_MAX_LENGTH-1);
}
}
if (name==null){
return;
}
//countrycode
if (!isEmptyField(fields, 3, true)) {
countrycode=fields[3].trim().toUpperCase();
}
//location
if (!isEmptyField(fields, 6, false)) {
try {
location = (Point) GeolocHelper.convertFromHEXEWKBToGeometry(fields[6]);
} catch (RuntimeException e) {
logger.warn("can not parse location for "+fields[6]+" : "+e);
return;
}
}
GisFeature city=null;
if (StringUtil.containsDigit(name)){
SolrResponseDto nearestCity = getNearestCity(location, name, countrycode,Constants.ONLY_CITYSUBDIVISION_PLACETYPE);
if (nearestCity != null ){
city = citySubdivisionDao.getByFeatureId(nearestCity.getFeature_id());
if (city==null){
city = createNewCitySubdivision(name,countrycode,location);
} else{
city.setSource(GISSource.GEONAMES_OSM);
}
} else {
city = createNewCitySubdivision(name,countrycode,location);
}
} else {
SolrResponseDto nearestCity = getNearestCity(location, name, countrycode, Constants.ONLY_CITY_PLACETYPE);
if (nearestCity != null ){
city = cityDao.getByFeatureId(nearestCity.getFeature_id());
if (city==null){
city = createNewCity(name,countrycode,location);
} else{
city.setSource(GISSource.GEONAMES_OSM);
}
} else {
city = createNewCity(name,countrycode,location);
}
//set municipality if needed
if ( !((City)city).isMunicipality()){
//only if not already a city, because, a node can be after a relation and then node set the municipality to false
((City)city).setMunicipality(municipalityDetector.isMunicipality(countrycode, fields[8], fields[0], GISSource.OSM));
}
}
//populate new fields
//population
if(city.getPopulation()==null && !isEmptyField(fields, 5, false)){
try {
int population = Integer.parseInt(fields[5].replaceAll("\\s+", ""));
city.setPopulation(population);
} catch (NumberFormatException e) {
logger.error("can not parse population :"+fields[5]);
}
}
//zip code
if(!isEmptyField(fields, 4, false) && (city.getZipCodes()==null || !city.getZipCodes().contains(new ZipCode(fields[4])))){
populateZip(fields[4], city);
}
//place tag/amenity
if(!isEmptyField(fields, 8, false)){
city.setAmenity(fields[8]);
}
//shape
if(!isEmptyField(fields, 7, false)){
try {
Geometry shape = (Geometry) GeolocHelper.convertFromHEXEWKBToGeometry(fields[7]);
city.setShape(shape);
} catch (RuntimeException e) {
logger.warn("can not parse shape for id "+fields[1]+" : "+e);
}
}
//osmId
if (!isEmptyField(fields, 1, true)) {
String osmIdAsString =fields[1].trim();
Long osmId;
try {
osmId = Long.parseLong(osmIdAsString);
city.setOpenstreetmapId(osmId);
} catch (NumberFormatException e) {
logger.error("can not parse openstreetmap id "+osmIdAsString);
}
}
//populate alternatenames
if (!isEmptyField(fields, 10, false)) {
String alternateNamesAsString=fields[10].trim();
populateAlternateNames(city,alternateNamesAsString);
}
//adm
if(!isEmptyField(fields, 9, false)){
if (city.getAdm()==null){
String admname =fields[9];
SolrResponseDto solrResponseDto= getAdm(admname,countrycode);
if (solrResponseDto!=null){
Adm adm = admDao.getByFeatureId(solrResponseDto.getFeature_id());
if (adm!=null){
city.setAdm(adm);
}
}
}
}
try {
savecity(city);
} catch (ConstraintViolationException e) {
logger.error("Can not save "+dumpFields(fields)+"(ConstraintViolationException) we continue anyway but you should consider this",e);
}catch (Exception e) {
logger.error("Can not save "+dumpFields(fields)+" we continue anyway but you should consider this",e);
}
}
/**
* @param fields
* The array to process
* @return a string which represent a human readable string of the Array but without shape because it is useless in logs
*/
protected static String dumpFields(String[] fields) {
String result = "[";
for (int i=0;i<fields.length;i++) {
if (i==7){
result= result+"THE_SHAPE;";
}else {
result = result + fields[i] + ";";
}
}
return result + "]";
}
protected void populateZip(String zipAsString, GisFeature city) {
if (zipAsString.contains(";")){
String[] zips = zipAsString.split(";");
for (int i = 0;i<zips.length;i++){
String zipTrimed = zips[i].trim();
if (!"".equals(zipTrimed)){
city.addZipCode(new ZipCode(zipTrimed));
}
}
} else if (zipAsString.contains(",")){
String[] zips = zipAsString.split(",");
for (int i = 0;i<zips.length;i++){
String zipTrimed = zips[i].trim();
if (!"".equals(zipTrimed)){
city.addZipCode(new ZipCode(zipTrimed));
}
}
} else {
city.addZipCode(new ZipCode(zipAsString));
}
}
void savecity(GisFeature city) {
if (city!=null){
if (city instanceof City){
cityDao.save((City)city);
} else if (city instanceof CitySubdivision){
citySubdivisionDao.save((CitySubdivision)city);
}
}
}
City createNewCity(String name,String countryCode,Point location) {
City city = new City();
city.setFeatureId(idGenerator.getNextFeatureId());
city.setSource(GISSource.OSM);
city.setName(name);
city.setLocation(location);
city.setCountryCode(countryCode);
return city;
}
CitySubdivision createNewCitySubdivision(String name,String countryCode,Point location) {
CitySubdivision city = new CitySubdivision();
city.setFeatureId(idGenerator.getNextFeatureId());
city.setSource(GISSource.OSM);
city.setName(name);
city.setLocation(location);
city.setCountryCode(countryCode);
return city;
}
GisFeature populateAlternateNames(GisFeature feature,
String alternateNamesAsString) {
if (feature ==null || alternateNamesAsString ==null){
return feature;
}
Matcher matcher = ALTERNATENAMES_EXTRACTION_PATTERN.matcher(alternateNamesAsString);
int i = 0;
while (matcher.find()){
if (matcher.groupCount() != 1) {
logger.warn("wrong number of fields for alternatename no " + i + "for line " + alternateNamesAsString);
continue;
}
String alternateName = matcher.group(1);
if (alternateName!= null && !"".equals(alternateName.trim())){
if (alternateName.contains(",")|| alternateName.contains(";")|| alternateName.contains(":")){
String[] alternateNames = alternateName.split("[;\\:,]");
for (String name:alternateNames){
feature.addAlternateName(new AlternateName(name.trim(),AlternateNameSource.OPENSTREETMAP));
}
} else {
feature.addAlternateName(new AlternateName(alternateName.trim(),AlternateNameSource.OPENSTREETMAP));
}
}
}
return feature;
}
protected SolrResponseDto getNearestCity(Point location, String name,String countryCode,Class[] placetypes) {
if (location ==null || name==null || "".equals(name.trim())){
return null;
}
FulltextQuery query;
try {
query = (FulltextQuery) new FulltextQuery(name).withPlaceTypes(placetypes).around(location).withoutSpellChecking().withPagination(Pagination.ONE_RESULT).withOutput(MINIMUM_OUTPUT_STYLE);
} catch (IllegalArgumentException e) {
logger.error("can not create a fulltext query for "+name);
return null;
}
if (countryCode != null){
query.limitToCountryCode(countryCode);
}
FulltextResultsDto results = fullTextSearchEngine.executeQuery(query);
if (results != null){
for (SolrResponseDto solrResponseDto : results.getResults()) {
if (solrResponseDto!=null && solrResponseDto.getScore() >= SCORE_LIMIT
&& solrResponseDto.getOpenstreetmap_id()== null){
//if fopenstreetmapid is not null it is because the shape has already been set
//(R are before nodes)
return solrResponseDto;
} else {
return null;
}
}
}
return null;
}
protected SolrResponseDto getAdm(String name, String countryCode) {
if (name==null){
return null;
}
FulltextQuery query;
try {
query = (FulltextQuery)new FulltextQuery(name).withAllWordsRequired(false).withoutSpellChecking().
withPlaceTypes(ONLY_ADM_PLACETYPE).withOutput(MINIMUM_OUTPUT_STYLE).withPagination(Pagination.ONE_RESULT);
} catch (IllegalArgumentException e) {
logger.error("can not create a fulltext query for "+name);
return null;
}
if (countryCode != null){
query.limitToCountryCode(countryCode);
}
FulltextResultsDto results = fullTextSearchEngine.executeQuery(query);
if (results != null){
for (SolrResponseDto solrResponseDto : results.getResults()) {
return solrResponseDto;
}
}
return null;
}
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.AbstractImporterProcessor#shouldBeSkiped()
*/
@Override
public boolean shouldBeSkipped() {
return !importerConfig.isOpenstreetmapImporterEnabled();
}
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.AbstractImporterProcessor#setCommitFlushMode()
*/
@Override
protected void setCommitFlushMode() {
this.cityDao.setFlushMode(FlushMode.COMMIT);
}
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.AbstractImporterProcessor#shouldIgnoreComments()
*/
@Override
protected boolean shouldIgnoreComments() {
return true;
}
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.AbstractImporterProcessor#shouldIgnoreFirstLine()
*/
@Override
protected boolean shouldIgnoreFirstLine() {
return false;
}
/* (non-Javadoc)
* @see com.gisgraphy.domain.geoloc.importer.IGeonamesProcessor#rollback()
*/
public List<NameValueDTO<Integer>> rollback() {
List<NameValueDTO<Integer>> deletedObjectInfo = new ArrayList<NameValueDTO<Integer>>();
logger.info("reseting openstreetmap cities...");
//TODO only cities that have source openstreetmap
deletedObjectInfo
.add(new NameValueDTO<Integer>(City.class.getSimpleName(), 0));
resetStatus();
return deletedObjectInfo;
}
@Override
//TODO test
protected void tearDown() {
super.tearDown();
FullTextSearchEngine.disableLogging=false;
String savedMessage = this.statusMessage;
try {
this.statusMessage = internationalisationService.getString("import.fulltext.optimize");
solRSynchroniser.optimize();
} finally {
// we restore message in case of error
this.statusMessage = savedMessage;
}
}
@Required
public void setSolRSynchroniser(ISolRSynchroniser solRSynchroniser) {
this.solRSynchroniser = solRSynchroniser;
}
@Required
public void setIdGenerator(IIdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
@Required
public void setCityDao(ICityDao cityDao) {
this.cityDao = cityDao;
}
@Required
public void setFullTextSearchEngine(IFullTextSearchEngine fullTextSearchEngine) {
this.fullTextSearchEngine = fullTextSearchEngine;
}
@Required
public void setAdmDao(IAdmDao admDao) {
this.admDao = admDao;
}
@Required
public void setMunicipalityDetector(IMunicipalityDetector municipalityDetector) {
this.municipalityDetector = municipalityDetector;
}
@Required
public void setCitySubdivisionDao(CitySubdivisionDao citySubdivisionDao) {
this.citySubdivisionDao = citySubdivisionDao;
}
}
| lgpl-3.0 |
Kelvinli1988/mysqlmv | src/main/java/org/mysqlmv/cd/logevent/eventdef/header/AbstractIEventHeader.java | 3220 | package org.mysqlmv.cd.logevent.eventdef.header;
import org.mysqlmv.cd.logevent.IEventHeader;
import org.mysqlmv.cd.logevent.LogEventType;
/**
* Created by Kelvin Li on 11/13/2014 10:25 AM.
*/
public abstract class AbstractIEventHeader implements IEventHeader {
// v1 (MySQL 3.23)
/**
* 4 bytes. This is the time at which the statement began executing.
* It is represented as the number of seconds since 1970 (UTC), like the TIMESTAMP SQL data type.
*/
private long timestamp;
/**
* 1 byte. The type of event. 1 means START_EVENT_V3, 2 means QUERY_EVENT, and so forth.
* These numbers are defined in the enum Log_event_type enumeration in log_event.h.
* (See Event Classes and Types.)
*/
private LogEventType eventType;
/**
* 4 bytes. The ID of the mysqld server that originally created the event.
*/
private long serverId;
/**
* 4 bytes. The total size of this event. This includes both the header and data parts.
* Most events are less than 1000 bytes, except when using LOAD DATA INFILE (where events
* contain the loaded file, so they can be big).
*/
private int eventLength;
// v3 (MySQL 4.0.2-4.1)
private long nextPosition;
/**
* 2 bytes. The possible flag values are described at Event Flags.
*/
private int flag;
// V4 (MYSQL 5.0+) usually it is empty.
/**
* Variable-sized. The size of this field is determined by the format description event
* that occurs as the first event in the file. Currently, the size is 0, so, in effect,
* this field never actually occurs in any event. At such time as the size becomes nonzero,
* this field still will not appear in events of type FORMAT_DESCRIPTION_EVENT or ROTATE_EVENT.
*/
private byte[] extraHeader;
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public LogEventType getEventType() {
return eventType;
}
public void setEventType(LogEventType eventType) {
this.eventType = eventType;
}
public long getServerId() {
return serverId;
}
public void setServerId(long serverId) {
this.serverId = serverId;
}
public int getEventLength() {
return eventLength;
}
public void setEventLength(int eventLength) {
this.eventLength = eventLength;
}
public long getNextPosition() {
return nextPosition;
}
public void setNextPosition(long nextPosition) {
this.nextPosition = nextPosition;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public byte[] getExtraHeader() {
return extraHeader;
}
public void setExtraHeader(byte[] extraHeader) {
this.extraHeader = extraHeader;
}
public EventVersion getVersion() {
throw new UnsupportedOperationException();
}
@Override
public int getHeaderLength() {
return 19;
}
@Override
public int getDataLength() {
return getEventLength() - getHeaderLength();
}
}
| lgpl-3.0 |
MastekLtd/JBEAM | supporting_libraries/AdvancedPRE/pre/src/main/java/admin/InsertScripts.java | 19533 | /**
* Copyright (c) 2014 Mastek Ltd. All rights reserved.
*
* This file is part of JBEAM. JBEAM is free software: you can
* redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation.
*
* JBEAM is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
* Public License for the specific language governing permissions and
* limitations.
*
*/
package admin;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import javax.naming.Context;
import javax.naming.InitialContext;
import stg.utils.CDate;
/**
Creates Insert Scripts for a given table. It generates files for Oracle & Microsoft SQL Server.
*/
public class InsertScripts {
private Connection cn = null;
private String dbType = "";
private LinkedList<String> insertList = null;
private LinkedList<String> valuesList = null;
private PrintWriter writer = null;
private LinkedList<String> deleteList = null;
private String path = ""; //Path for crearing Bean File
private boolean isUnableToCreate = false;
private boolean isAppendToFile = false;
private String fileName = "";
private boolean bRollbackStatement = false;
private String strRollbackFileName_ = "";
private Integer lastTableRowCount;
/**
* Constructs an object for the supplied connection.
*
* @param con Connection
* @throws Exception
*/
public InsertScripts(Connection con) throws Exception {
if (con == null) {
throw new Exception("Connection not established");
}
cn = con;
dbType = getDatabase(cn);
}
/** Set the database type other than the connection. Valid are ORACLE & MSSQL
@param type String ORACLE or MSSQL
@throws Exception
*/
public void setDatabaseType(String type) throws Exception {
if ( (!type.equals("ORACLE")) && (!type.equals("MSSQL")) ) {
throw new Exception ("Invalid Database Type Specified. Valid Types are ORACLE & MSSQL" );
}
dbType = type;
}
/**
* Set the path in which the files are to be generated.
* Use this either this method or {@link #setFile(String, boolean)}. Both will not work.
* In case this method is used then simply calling {@link #onTable(String)} methods will
* generate the file name as per the table name and store it in the given path.
*
* @param path String
*/
public void setPath(String path){
if( path == null ) path = "";
this.path = path;
}
/**
* Sets the file in which the insert scripts are to be generated.
*
* @param file output file.
* @param brollback in case the rollback script is to be created.
* @throws Exception
*/
public void setFile(String file, boolean brollback) throws Exception{
bRollbackStatement = brollback;
if (bRollbackStatement)
deleteList = new LinkedList<String>();
fileName = file;
writer = createFile(file);
}
/**
* Set true to append to the file.
*
* @param b boolean
*/
public void setAppendToFile( boolean b ){
isAppendToFile = b;
}
/**
* Generates the scripts on the given table name.
* @param tableName
* @throws Exception
*/
public void onTable(String tableName) throws Exception{
onTable(tableName, null);
}
/**
* Generates the insert script on the given table with the given where clause.
*
* @param tableName
* @param whereClause
* @throws Exception
*/
public void onTable(String tableName, String whereClause) throws Exception{
if (whereClause == null) whereClause = "";
if (writer == null)
{
writer = createFile(tableName);
}
System.out.print(tableName + " " + whereClause);
if (bRollbackStatement)
{
deleteList.addFirst("DELETE FROM " + tableName + " " + whereClause + " ;");
}
lastTableRowCount = 0;
Statement st = null;
ResultSet rs = null;
try{
st = cn.createStatement();
rs = st.executeQuery("Select * from " + tableName + " " + whereClause);
ResultSetMetaData rsmd = rs.getMetaData();
int totalColumns = rsmd.getColumnCount();
insertList = new LinkedList<String>();
String insertInto = "Insert Into " + tableName + "(";
for (int i = 1; i <= totalColumns; i++) {
insertInto += rsmd.getColumnName(i) + ((i < totalColumns)?", ":"");
if (insertInto.length() > 80 ){
insertList.addLast(insertInto);
insertInto = "";
}
}
insertInto += ") values ( ";
insertList.addLast(insertInto);
valuesList = new LinkedList<String>();
String values = "";
while (rs.next()) {
lastTableRowCount++;
for (int i = 1; i <= totalColumns; i++) {
String type = getDataType( rsmd.getColumnType(i) );
if (type.equals("String")) {
String output = rs.getString(i);
if (output != null) values += characterTerminator_ + rectifyData(output) + characterTerminator_;
else values += "null";
}
else if (type.equals("Date")) {
String output = CDate.getUDFDateString(rs.getDate(i), getDateFormat());
if (output != null ) values += getDateTypeSQLSyntaxPrefix() + characterTerminator_ + output + characterTerminator_ + getDateTypeSQLSyntaxSuffix();
else values += "null";
}
else if (type.equals("Timestamp")) {
String output = CDate.getUDFDateString(rs.getDate(i), getTimestampFormat());
if (output != null ) values += getTimestampTypeSQLSyntaxPrefix() + characterTerminator_ + output + characterTerminator_ + getTimestampTypeSQLSyntaxSuffix();
else values += "null";
} else {
values += "" + rs.getString(i);
}
if (i < totalColumns) values += ", ";
if (values.length() > 80) {
valuesList.addLast( values );
values = "";
}
}
values += ")" + getSQLTerminator();
valuesList.addLast( values );
ListIterator<String> i = insertList.listIterator(0);
while (i.hasNext()) {
print( i.next() );
}
i = valuesList.listIterator();
while (i.hasNext()) {
print( i.next() );
}
print("");
values = "";
valuesList.clear();
}
writer.flush();
}
catch(Exception e){
e.printStackTrace();
isUnableToCreate = true;
}
finally{
insertList.clear();
insertList = null;
try {
if (rs != null) rs.close();
} catch (SQLException e) {
// do nothing
}
try {
if (st != null) st.close();
} catch (Exception e) {
// Do nothing
}
if(!isUnableToCreate) {
System.out.println("\t.........Done.");
} else {
deleteFile(new File(fileName));
if (bRollbackStatement)
{
deleteFile(new File(strRollbackFileName_));
}
}
}
}
public Integer lastTableRowCount() {
return lastTableRowCount;
}
/**
* Closes the file.
*
* @throws Exception
*/
public void close() throws Exception
{
if (writer != null) writer.close();
if (bRollbackStatement)
{
createRollbackFile();
if (writer != null) writer.close();
}
}
private String getDataType(int dataType ) throws SQLException{
String returnValue = "";
switch (dataType) {
case java.sql.Types.VARCHAR:
returnValue="String";
break;
case java.sql.Types.TIMESTAMP:
returnValue="Timestamp";
break;
case java.sql.Types.DATE:
returnValue="Date";
break;
case java.sql.Types.NUMERIC:
returnValue="double";
break;
case java.sql.Types.BIGINT:
returnValue="String";
break;
case java.sql.Types.LONGVARCHAR:
returnValue="long";
break;
case java.sql.Types.VARBINARY:
returnValue="long";
break;
case java.sql.Types.LONGVARBINARY:
returnValue="long";
break;
case java.sql.Types.TIME:
returnValue="Timestamp";
break;
case java.sql.Types.CHAR:
returnValue="String";
break;
case java.sql.Types.TINYINT:
returnValue="int";
break;
case java.sql.Types.INTEGER:
returnValue="int";
break;
default:
System.out.println("Defaulted to String. Data Type #" + dataType + " could not be recognized.");
returnValue="String";
break;
}
return returnValue;
}
private PrintWriter createFile(String tableFileName) throws Exception{
String fileSufix = dbType.equals("ORACLE")?"_ORA":"_MSQ";
// if(isWriteBeanClosed) throw new Exception( "Object is Closed" );
if(fileName.equals("")) fileName = path + tableFileName + fileSufix + ".sql";
File f = new File(fileName);
if (f.exists() && isAppendToFile) System.out.println("Appending to File " + fileName);
else if ( f.exists() && !isAppendToFile) throw new Exception(".....File Already Exists.");
else System.out.println("Creating File " + fileName);
isUnableToCreate = false;
return new PrintWriter(new BufferedWriter(new FileWriter(fileName, isAppendToFile)), true);
}
private void print(Object s) throws Exception{
if (writer != null) writer.println(s);
}
/**
* Prints the comment in the file.
*
* @param s
* @throws Exception
*/
public void printComment(String s) throws Exception{
print("/****************************************************************");
print("** " + s);
print("****************************************************************/");
print(" ");
}
/**
* Prints the given string.
* @param s
* @throws Exception
*/
public void println(String s) throws Exception
{
print(s);
print("");
}
/**
* Adds prompt in the insert scripts.
*
* @param s
* @throws Exception
*/
public void echo(String s) throws Exception
{
print("");
print("prompt " + s);
print("");
}
private String getDatabase(Connection cn ) throws SQLException{
DatabaseMetaData dmd = cn.getMetaData();
String dbProductName = dmd.getDatabaseProductName();
if( dbProductName.indexOf("Oracle") >= 0 ) return "ORACLE";
else if( dbProductName.indexOf("Microsoft SQL Server") >= 0 ) return "MSSQL";
return "";
}
/**
* Main method for testing.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
Connection con = null;
Context ctx = null;
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://10.84.133.155:7023");
try
{
ctx = new InitialContext(ht);
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup ("RENAISSANCE");
con = ds.getConnection();
InsertScripts objIs = new InsertScripts(con);
if (args.length == 1)
{
objIs.onTable(args[0]);
}
else if (args.length == 2)
{
objIs.onTable(args[0], args[1]);
}
else
{
throw new IllegalArgumentException("Call InsertScripts <tablename> <wherecondition>");
}
objIs.close();
}
finally
{
try
{
if (con != null)
{
con.close();
}
}
catch (SQLException e)
{
//dummy catch
}
}
}
private String rectifyData(String data)
{
StringBuffer sbuffer = new StringBuffer(data);
int iIndex = -2;
while ((iIndex = sbuffer.indexOf(characterTerminator_+"", iIndex+2)) > -1)
{
sbuffer.replace(iIndex,iIndex, characterTerminator_+"");
}
return sbuffer.toString();
} // end of rectifyData
private void createRollbackFile() throws Exception
{
if (bRollbackStatement)
{
System.out.println("Creating Rollback Statements...");
fileName = fileName + ".ROLLBACK";
writer = createFile(fileName);
System.out.println("Rollback");
for (Iterator<String> iter = deleteList.iterator(); iter.hasNext();)
{
String strDeleteStatement = (String) iter.next();
System.out.println(strDeleteStatement);
writer.println(strDeleteStatement);
}
writer.flush();
}
}
/**
* Stores the REVISION number of the class from the configuration management tool.
*/
private static final String REVISION = "$Revision:: 2726 $";
private String strSQLTerminator_;
private String strDateTypeSQLSyntaxPrefix_;
private String strDateTypeSQLSyntaxSuffix_;
private String strTimestampTypeSQLSyntaxPrefix_;
private String strTimestampTypeSQLSyntaxSuffix_;
private String strDateFormat_;
private String strTimestampFormat_;
private char characterTerminator_ = '\'';
/**
* Returns the Revision number of the class.
* Identifies the version number of the source code that generated this class file stored
* in the configuration management tool.
*
* @return String
*/
public String getRevision() {
return REVISION;
}
/**
* Set the SQL terminator.
* Most of the cases the SQL terminator is a ;.
* @param pstrSQLTerminator
*/
public void setSQLTerminator(String pstrSQLTerminator) {
this.strSQLTerminator_ = pstrSQLTerminator;
}
/**
* Returns the SQL terminator.
* Default returns ;.
* @return String
*/
public String getSQLTerminator() {
return ((strSQLTerminator_ == null)?";":strSQLTerminator_);
}
/**
* Define the prefix and suffix of the SQL Date syntax.
* In case of Oracle prefix would be <b<to_date(</b> and suffix would be <b>, 'mm/dd/yyyy')</b>
* @param prefix
* @param suffix
*/
public void setDateTypeSQLSyntax(String prefix, String suffix) {
this.strDateTypeSQLSyntaxPrefix_ = prefix;
this.strDateTypeSQLSyntaxSuffix_ = suffix;
}
/**
* Return the prefix for SQL date syntax.
* Defaults to <b>to_date(</b>.
* @return String
*/
public String getDateTypeSQLSyntaxPrefix() {
return ((strDateTypeSQLSyntaxPrefix_ == null)?"to_date(":strDateTypeSQLSyntaxPrefix_);
}
/**
* Return the suffix for SQL date syntax.
* Defaults to <b>, 'mm/dd/yyyy')</b>.
* @return String
*/
public String getDateTypeSQLSyntaxSuffix() {
return ((strDateTypeSQLSyntaxSuffix_ == null)?", 'mm/dd/yyyy')":strDateTypeSQLSyntaxSuffix_);
}
/**
* Define the prefix and suffix of the SQL Timestamp syntax.
* In case of Oracle prefix would be <b<to_date(</b> and suffix would be <b>, 'mm/dd/yyyy')</b>
* @param prefix
* @param suffix
*/
public void setTimestampTypeSQLSyntax(String prefix, String suffix) {
this.strTimestampTypeSQLSyntaxPrefix_ = prefix;
this.strTimestampTypeSQLSyntaxSuffix_ = suffix;
}
/**
* Return the prefix for SQL Timestamp syntax.
* Defaults to <b>to_date(</b>.
* @return String
*/
public String getTimestampTypeSQLSyntaxPrefix() {
return ((strTimestampTypeSQLSyntaxPrefix_ == null)?"to_date(":strTimestampTypeSQLSyntaxPrefix_);
}
/**
* Return the suffix for SQL Timestamp syntax.
* Defaults to <b>, 'mm/dd/yyyy hh24:mi:ss')</b>.
* @return String
*/
public String getTimestampTypeSQLSyntaxSuffix() {
return ((strTimestampTypeSQLSyntaxSuffix_ == null)?", 'mm/dd/yyyy hh24:mi:ss')":strTimestampTypeSQLSyntaxSuffix_);
}
/**
* Set the SimpleDateFormat format for converting SQL Date to a java literal.
* @param format
*/
public void setDateFormat(String format) {
this.strDateFormat_ = format;
}
/**
* Returns the Date format.
* Defaults to <b>MM/dd/yyyy</b>.
* @return String
*/
public String getDateFormat() {
return ((strDateFormat_ == null)?"MM/dd/yyyy":strDateFormat_);
}
/**
* Set the SimpleDateFormat format for converting SQL Timestamp to a java literal.
* @param format
*/
public void setTimestampFormat(String format) {
this.strTimestampFormat_ = format;
}
/**
* Returns the Timestamp format.
* Defaults to <b>MM/dd/yyyy HH:mm:ss</b>.
* @return String
*/
public String getTimestampFormat() {
return ((strTimestampFormat_ == null)?"MM/dd/yyyy HH:mm:ss":strTimestampFormat_);
}
/**
* Set the character terminator of an SQL.
* Most of the cases it is a single quote <b>'</b>.
* @param c
*/
public void setCharacterTerminator(char c) {
this.characterTerminator_ = c;
}
/**
* Returns the character terminator.
* Defaults to <b>'</b>.
* @return char
*/
public char getCharacterTerminator() {
return characterTerminator_;
}
private void deleteFile(File file) {
if (file.delete()) {
System.out.println("Deleted file " + file.getName());
} else {
System.out.println("Unable to delete the file " + file.getName() + ". Please delete it manually.");
}
}
}
| lgpl-3.0 |
mogria/mforms | src/input/Textbox.php | 791 | <?php
class Textbox extends Inputfield {
protected $size;
protected $maxlength;
final public function getMaxlength()
{
return $this->maxlength;
}
protected function addAttributes() {
parent::addAttributes();
$this->attributes[] = 'size';
$this->attributes[] = 'maxlength';
}
public function setMaxlength($value)
{
$this->maxlength = $value;
}
public function getSize()
{
return $this->size;
}
public function setSize($value)
{
$this->size = $value;
}
public function getType()
{
return "text";
}
public function isValid()
{
$valid = parent::isValid();
if($this->getMaxlength() !== null && strlen($this->getValue()) > $this->getMaxlength()) {
$valid = false;
}
return $valid;
}
}
| lgpl-3.0 |
bjornblomqvist/burp | app/assets/packages/gritter/gritter.js | 43 | //
//= require ./js/jquery.gritter.min.js
| lgpl-3.0 |