repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
kagucho/tsubonesystem3 | webapp/loader/extract.js | 2410 | /*
Copyright (C) 2017 Kagucho <kagucho.net@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const LibraryTemplatePlugin = require("webpack/lib/LibraryTemplatePlugin");
const NodeTemplatePlugin = require("webpack/lib/node/NodeTemplatePlugin");
const NodeTargetPlugin = require("webpack/lib/node/NodeTargetPlugin");
const SingleEntryPlugin = require("webpack/lib/SingleEntryPlugin");
const compilers = {};
module.exports = function() {
};
module.exports.pitch = function(request) {
if (!compilers[request]) {
// eslint-disable-next-line no-underscore-dangle
const compilation = this._compilation;
const options = {
filename: "entry",
publicPath: compilation.outputOptions.publicPath,
};
compilers[request] = compilation.createChildCompiler(request, options);
compilers[request].apply(new LibraryTemplatePlugin(null, "commonjs2"));
compilers[request].apply(new NodeTargetPlugin());
compilers[request].apply(new NodeTemplatePlugin(options));
compilers[request].apply(new SingleEntryPlugin(
this.context, "!!" + request, "entry"));
}
const sync = this.async();
compilers[request].compile((error, compilation) => {
if (error) {
return sync(error);
}
compilation.fileDependencies.forEach(this.addDependency);
compilation.contextDependencies.forEach(this.addContextDependency);
this._module.errors.push(...compilation.errors);
this._module.warnings.push(...compilation.warnings);
if (compilation.errors.length) {
sync("child compiler failed");
return;
}
for (const name in compilation.assets) {
if (name != "entry") {
// eslint-disable-next-line no-underscore-dangle
this._compilation.assets[name] = compilation.assets[name];
}
}
sync(null, this.exec(compilation.assets.entry.source(), request).toString());
});
};
| agpl-3.0 |
miltonruelas/cursotecnico | branch/procurement_supply/__openerp__.py | 1555 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Cubic ERP - Teradata SAC (<http://cubicerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Supply Procurement",
"version": "1.0",
"author": "Cubic ERP",
"category": "Purchase Management",
"description": """
Add supply information on procurement orders in order to generate the purchase order with the correcly information. And add a supply check to verify teh correct supply of a procurement.
""",
"depends": [
"procurement",
"purchase",
],
"demo_xml": [
],
"data": [
"procurement_view.xml",
],
"active": False,
"installable": True
} | agpl-3.0 |
DaTa-/Hypersomnia | src/game/resource_setups/standard_behaviour_trees.cpp | 1353 | #include "all.h"
#include "game/transcendental/cosmos.h"
#include "game/assets/behaviour_tree.h"
#include "game/detail/ai/behaviours.h"
void set_standard_behaviour_trees(cosmos& manager) {
auto& soldier_movement = manager[assets::behaviour_tree_id::SOLDIER_MOVEMENT];
soldier_movement.root.mode = behaviour_tree::node::type::SELECTOR;
soldier_movement.root.create_branches(
new behaviours::immediate_evasion,
new behaviours::minimize_recoil_through_movement,
new behaviours::navigate_to_last_seen_position_of_target,
new behaviours::explore_in_search_for_last_seen_target
);
soldier_movement.build_tree();
auto& hands_actor = manager[assets::behaviour_tree_id::HANDS_ACTOR];
hands_actor.root.create_branches(new behaviours::pull_trigger);
hands_actor.root;
hands_actor.build_tree();
auto& item_picker = manager[assets::behaviour_tree_id::ITEM_PICKER];
//item_picker.root.branch(new behaviours::usable_item_marker);
item_picker.build_tree();
auto& inventory_actor = manager[assets::behaviour_tree_id::INVENTORY_ACTOR];
inventory_actor.root;
inventory_actor.build_tree();
auto& hostile_target_prioritization = manager[assets::behaviour_tree_id::HOSTILE_TARGET_PRIORITIZATION];
hostile_target_prioritization.root.create_branches(new behaviours::target_closest_enemy);
hostile_target_prioritization.build_tree();
}
| agpl-3.0 |
bernatmv/thegame | server/server-engine/src/main/java/com/thegame/server/engine/intern/data/beans/Stat.java | 315 | package com.thegame.server.engine.intern.data.beans;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author afarre
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Stat{
private Integer current;
private Integer max;
}
| agpl-3.0 |
Tanaguru/Tanaguru | rules/accessiweb2.1/src/main/java/org/tanaguru/rules/accessiweb21/Aw21Rule03013.java | 2375 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.accessiweb21;
import java.util.ArrayList;
import java.util.Collection;
import org.tanaguru.entity.audit.DefiniteResult;
import org.tanaguru.entity.audit.ProcessRemark;
import org.tanaguru.entity.audit.ProcessResult;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.processor.SSPHandler;
import org.tanaguru.ruleimplementation.AbstractPageRuleImplementation;
/**
* Implementation of the rule 3.1.3 of the referential Accessiweb 2.1.
* <br>
* For more details about the implementation, refer to <a href="http://www.tanaguru.org/en/content/aw21-rule-3-1-3">the rule 3.1.3 design page.</a>
* @see <a href="http://www.braillenet.org/accessibilite/referentiel-aw21-en/index.php#test-3-1-3"> 3.1.3 rule specification</a>
*
* @author jkowalczyk
*/
public class Aw21Rule03013 extends AbstractPageRuleImplementation {
/**
* Default constructor
*/
public Aw21Rule03013 () {
super();
}
/**
* Concrete implementation of the 3.1.3 rule.
* @param sspHandler
* @return
* the processResult of the test
*/
@Override
protected ProcessResult processImpl(SSPHandler sspHandler) {
TestSolution testSolution = TestSolution.NOT_TESTED;
Collection<ProcessRemark> remarkList = new ArrayList<ProcessRemark>();
DefiniteResult result = definiteResultFactory.create(
test,
sspHandler.getSSP().getPage(),
testSolution,
remarkList);
return result;
}
} | agpl-3.0 |
fakena/myoc4078 | opencog/persist/file/CompositeRenumber.cc | 1591 | /*
* opencog/persist/file/CompositeRenumber.cc
*
* Copyright (C) 2002-2007 Novamente LLC
* All Rights Reserved
*
* Written by Welter Silva <welter@vettalabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdlib.h>
#include <opencog/util/platform.h>
#include "CompositeRenumber.h"
#include "CoreUtils.h"
#include <opencog/atomspace/TLB.h>
using namespace opencog;
void CompositeRenumber::updateVersionHandles(CompositeTruthValue &ctv,
HandleMap<Atom *> *handles)
{
VersionedTruthValueMap newVersionedTVs;
for (VersionedTruthValueMap::const_iterator itr = ctv.versionedTVs.begin();
itr != ctv.versionedTVs.end(); itr++) {
VersionHandle key = itr->first;
CoreUtils::updateHandle(&(key.substantive), handles);
newVersionedTVs[key] = itr->second;
}
ctv.versionedTVs = newVersionedTVs;
}
| agpl-3.0 |
Creamfinance/clashing-coders-rpg | controllers/AuthenticationController.js | 4741 | /*
Clashing Coders RPG Platform - The platform used for Creamfinance's first coding contest.
Copyright (C) 2016 Florian Proksch
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var Class = require('class'),
bcrypt = require('bcrypt'),
crypto = require('crypto'),
pool = require('../pool'),
redis = require('../redis'),
users = require('../repositories/UserRepository');
var AuthenticationController = Class.bind(null, 'AuthenticationController', Object);
module.exports = AuthenticationController({
constructor: function () {
},
/**
* TODO: document
*
*/
registerRouter: function registerRouter(router) {
router.registerPath('POST', '/authenticate',
{
requests: [
{
headers: new Validator({
'content-type': new EnumRule([ 'application/json' ]),
}),
body: new Validator({
'username': new RequiredRule(),
'password': new RequiredRule(),
}),
callback: this.handleAuthentication.bind(this)
},
],
}
);
},
/**
* TODO: document
*
* @param request @todo
* @param data @todo
*/
handleAuthentication: function handleAuthentication(request) {
var data = request.post;
redis.get('open-registration', function (err, result) {
if (err) {
request.log(err);
request.appendInfo('Redis error');
return request.sendUnauthorized();
}
if (!data) {
request.appendInfo('Token not found');
return request.sendUnauthorized();
}
console.log(result);
if (result == 'true') {
pool.connect(function (err, client, done) {
client.query('SELECT * FROM users WHERE username = $1',
[ data.username ], function (err, result) {
var user = result.rows[0];
done();
if (user) {
if (data.password === user.password) {
if (! (user.id in users.users)) {
users.users[user.id] = user;
user.level_metadata = {};
}
var access_token = new Buffer(
user.id + '-'
+ Date.now()
+ '-' + crypto.randomBytes(16).toString('hex')
).toString('base64');
// save access token to redis
redis.set(access_token, user.id, function (err, result) {
if (err) {
console.log('ERROR')
request.log(err);
request.appendInfo('Redis error: ' + err);
return request.sendInternalServerError();
}
request.sendResponse({
access_token: access_token
});
});
} else {
return request.sendUnauthorized();
}
} else {
return request.sendUnauthorized();
}
});
});
} else {
return request.sendUnauthorized();
}
});
},
});
| agpl-3.0 |
xavoctechnocratspvtltd/xbank2 | lib/Model/Comment.php | 773 | <?php
class Model_Comment extends Model_Table{
public $table="Comment";
function init(){
parent::init();
$this->hasOne('Member','member_id');
$this->hasOne('Account','account_id');
$this->addField('narration')->type('text');
$this->addField('created_at')->type('datetime');
$this->addField('updated_at')->type('datetime');
$this->add('dynamic_model/Controller_AutoCreator');
}
function createNew($narration,$member=null,$account=null){
if($this->loaded())
throw new Exception("Please call on empty model");
if($member)
$this['member_id']=$member->id;
if($account)
$this['account_id']=$account->id;
$this['narration']=$narration;
$this['created_at']=$this->api->now;
$this['updated_at']=$this->api->now;
$this->save();
}
} | agpl-3.0 |
CatoTH/antragsgruen | migrations/m160605_104819_remove_consultation_type.php | 335 | <?php
use yii\db\Migration;
class m160605_104819_remove_consultation_type extends Migration
{
public function safeUp()
{
$this->dropColumn('consultation', 'type');
}
public function safeDown()
{
echo "m160605_104819_remove_consultation_type cannot be reverted.\n";
return false;
}
}
| agpl-3.0 |
Fearful/Workend | test/unit/dopplerDirectivesSpec.js | 805 | 'use strict';
describe('Doppler Suite Directives', function(){
// var element;
// beforeEach(function(){
// module('doppler');
// element = angular.element('<li cp-open="testMode"></li>');
// inject(function($rootScope, $compile, $timeout){
// var scope = $rootScope.$new();
// scope.name = name;
// $compile(element)(scope);
// $timeout(function(){
// scope.$apply();
// console.log(element.data('events'));
// });
// console.log(element.data('events'));
// });
// });
// it('should be true', function() {
// console.log(element.data('events'))
// // console.log(element[0].onclick);
// expect(true).toBe(true);
// });
}); | agpl-3.0 |
aborg0/rapidminer-studio | src/main/java/com/rapidminer/gui/viewer/metadata/actions/CopyAttributeNameAction.java | 1850 | /**
* Copyright (C) 2001-2019 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.viewer.metadata.actions;
import com.rapidminer.gui.tools.ResourceAction;
import com.rapidminer.gui.viewer.metadata.AttributeStatisticsPanel;
import com.rapidminer.tools.Tools;
import java.awt.event.ActionEvent;
import javax.swing.JComponent;
/**
* This action is only to be used by the {@link AttributePopupMenu}.
*
* @author Marco Boeck
*
*/
public class CopyAttributeNameAction extends ResourceAction {
private static final long serialVersionUID = 1L;
/**
* Creates a new {@link CopyAttributeNameAction} instance.
*/
public CopyAttributeNameAction() {
super(true, "meta_data_stats.copy_att_name");
}
@Override
public void loggedActionPerformed(ActionEvent e) {
if (!(((JComponent) e.getSource()).getParent() instanceof AttributePopupMenu)) {
return;
}
AttributeStatisticsPanel asp = ((AttributePopupMenu) ((JComponent) e.getSource()).getParent())
.getAttributeStatisticsPanel();
Tools.copyStringToClipboard(asp.getModel().getAttribute().getName());
}
}
| agpl-3.0 |
eXtreme-Fusion/EF5-Online | system/helpers/main.php | 29997 | <?php
/*********************************************************
| eXtreme-Fusion 5
| Content Management System
|
| Copyright (c) 2005-2013 eXtreme-Fusion Crew
| http://extreme-fusion.org/
|
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
**********************************************************
Some open-source code comes from
---------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) 2002 - 2011 Nick Jones
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Author: Nick Jones (Digitanium)
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
defined('EF5_SYSTEM') || exit;
/**
* URL parser for template files.
*
* Code to parsing: {url('controller=>', 'login', 'action=>', 'redirect', 'param')}
*/
function optUrl(optClass &$_tpl)
{
$value = array_slice(func_get_args(), 1);
if ($value)
{
$ret = array(); $id = NULL;
foreach($value as $array)
{
// Czyszczenie danych wejściowych
$data = array_map('trim', explode('=>', $array));
// Kontrola danych wejściowych
if ($data[0] !== '')
{
// Sprawdzanie, czy element ma przypisany klucz.
if (count($data) == 2)
{
// Zapisujemy klucz. Wartości na razie nie znamy.
$id = $data[0];
}
else
{
if ($id)
{
// Zapis wartości o kluczu zapisanym wcześniej.
$ret[$id] = $data[0];
}
else
{
// Parametr.
$ret[] = $data[0];
}
// Resetowanie zmiennej, by nie było konfliktu w razie wystąpienia parametru.
$id = NULL;
}
}
}
$value = $ret;
}
if ($_tpl->funcExists('url', 'path'))
{
return $_tpl->getFunc('url', 'path', $value);
}
if ($value)
{
if (method_exists($_tpl, 'route'))
{
return $_tpl->route()->path($value);
}
}
throw new systemException('Routing is not available.');
}
// Function for AJAX response
function _e($val)
{
echo $val; exit;
}
function arrLast($src)
{
return $src[count($src)-1];
}
// Sprawdza, czy element istnieje w tablicy dwuwymiarowej
// o indeksie drugiego poziomu podanym trzecim parametrem
function inArray($value, $array, $id = NULL)
{
if ( ! $id)
{
return in_array($value, $array);
}
if ($array)
{
foreach($array as $a_val)
{
if (isset($a_val[$id]) && $a_val[$id] === $value)
{
return TRUE;
}
}
}
return FALSE;
}
function isNum($var, $exception = TRUE, $return_value = TRUE)
{
$_validator = new Edit($var);
return $_validator->isNum($return_value, $exception);
}
function __autoload($class_name)
{
$data = explode('_', $class_name);
if (count($data) > 1)
{
$name = implode(DIRECTORY_SEPARATOR, $data);
}
else
{
$name = $class_name;
}
$tmp_path = array(DIR_CLASS.$name.'.php');
foreach (new DirectoryIterator(DIR_MODULES) as $file)
{
if ( ! in_array($file->getFilename(), array('..', '.', '.svn', '.gitignore')))
{
if (file_exists(DIR_MODULES.$file->getFilename().DS.'class'.DS.$name.'.php'))
{
$tmp_path[] = DIR_MODULES.$file->getFilename().DS.'class'.DS.$name.'.php';
}
}
}
foreach($tmp_path as $path)
{
if (file_exists($path))
{
include $path;
}
}
}
// Helper class
Class HELP
{
protected static
$_pdo,
$_sett,
$_user,
$_url;
public static function init($pdo, $sett, $user, $url)
{
self::$_pdo = $pdo;
self::$_sett = $sett;
self::$_user = $user;
self::$_url = $url;
}
public static function wordsProtect($string)
{
if (self::$_sett->get('bad_words_enabled'))
{
$to_replace = explode(PHP_EOL, self::$_sett->get('bad_words'));
foreach($to_replace as $key => $val)
{
if ($val)
{
$new = '';
if ($val[strlen($val)-1] === ' ')
{
$new = ' ';
}
$to_replace[$key] = trim($val).$new;
}
}
return str_replace($to_replace, self::$_sett->get('bad_word_replace'), $string);
}
return $string;
}
public static function validUpVersion($current, $new)
{
$current = (int) str_replace('.', '', $current);
$new = (int) str_replace('.', '', $new);
return $current === ($new-1);
}
public static function cleanSelectOptions($data)
{
// Rzutowanie typów w celu konwersji stringa na tablicę.
$data = (array) $data;
// Zapisywanie typu danych wejściowych w celu zwrócenia return w odpowiednim.
$type = (int) is_array($data);
$option_new = array();
foreach($data as $val)
{
$val = trim($val);
if ($val)
{
// Usuwanie spacji pomiędzy wyrazami
$val_new = array();
for($i = 0, $c = strlen($val); $i < $c; $i++)
{
if ($val[$i] === ' ' && isset($val[$i+1]) && $val[$i+1] === ' ')
{
continue;
}
$val_new[] = $val[$i];
}
$option_new[] = implode('', $val_new);
}
}
if ($type === 1)
{
return $option_new;
}
return isset($option_new[0]) ? $option_new[0] : array();
}
/** METODY NAPISANE PRZEZ EF TEAM: **/
public static function daysToSeconds($time, $conv = FALSE)
{
if (isNum($time, TRUE))
{
if ( ! $conv)
{
return 60*60*24*$time;
}
return $time/(60*60*24);
}
}
// Zwraca tę część stringa, która wystąpi przed $needle.
public static function strstr_before($haystack, $needle) {
$haystack = strrev($haystack);
$haystack = strrev(strstr($haystack, '.'));
return substr($haystack, 0, -1);
}
public static function truncate($data, $limit = 20)
{
if (str_word_count($data) > $limit)
{
$body = explode(' ', $data);
$short_content = array();
for ($n = 0; $n < $limit; $n++)
{
$short_content[] = $body[$n];
}
return implode(' ', $short_content);
}
return $data;
}
// TODO:: Przerobic na metodę routera
public static function createNaviLink($url, $not_parse = FALSE)
{
if (!preg_match('/^http:/i', $url))
{
if ($url)
{
return ADDR_SITE.self::$_url->getPathPrefix($not_parse).$url;
}
return ADDR_SITE;
}
return $url;
}
public static function hoursToSeconds($time, $conv = FALSE)
{
if (isNum($time, TRUE))
{
if ( ! $conv)
{
return 60*60*$time;
}
return $time/(60*60);
}
}
public static function minutesToSeconds($time, $conv = FALSE)
{
if (isNum($time, TRUE))
{
if ( ! $conv)
{
return 60*$time;
}
return $time/60;
}
}
public static function implode(array $data, $sep = DBS)
{
return implode($sep, $data);
}
public static function explode($data, $sep = DBS)
{
return explode($sep, $data);
}
public static function arrayUnshift(&$array, $key, $value)
{
$data[$key] = $value;
foreach($array as $x => $y)
{
$data[$x] = $y;
}
$array = $data;
}
// Usuwa z tablicy element o numerycznym indeksie, po czym przesuwa pozostałe indeksy
public static function arrayRemoveElement($key, &$array)
{
if (isNum($key))
{
unset($array[$key]);
for ($i = $key + 1, $c = count($array); $i < $c; $i++)
{
if (isset($array[$i]))
{
$array[$i-1] = $array[$i];
$to_remove = $i;
}
}
if (isset($to_remove))
{
unset($array[$to_remove]);
}
}
return FALSE;
}
/**
* Konwertuje znaki językowe w nazwach miesięcy
* i innych wyrażeniach na UTF-8.
*
*
*
* @param string $keys
* @param type $time
* @return type
*/
public static function strfTimeInUTF($keys, $time)
{
// Zmiana kodowania na UTF-8
return iconv('ISO-8859-2', 'UTF-8', strftime($keys, $time));
}
//==================================
//PL: Ustalenie dni
//EN: Determin day
//==================================
public static function DayExport($di_value)
{
$day_export = 60 * 60 * 24 * $di_value;
return $day_export;
}
public static function DayImport($de_value)
{
$day_import = (($de_value / 24) / 60) / 60;
return $day_import;
}
//==================================
// Strip Input public static function, prevents HTML in unwanted places
//==================================
public static function strip(&$text)
{
if ($text)
{
if (!is_array($text))
{
$search = array("&", "\"", "'", "\\", '\"', "\'", "<", ">", " ");
$replace = array("&", """, "'", "\", """, "'", "<", ">", " ");
$text = str_replace($search, $replace, $text);
}
else
{
foreach($text as $key => $val)
{
$text[$key] = HELP::strip($val);
}
}
}
return $text;
}
//==================================
//PL: Przeładowanie strony
//EN: Site reload
//==================================
public static function reload($time)
{
if (isNum($time))
{
header('Refresh: '.$time);
exit;
}
}
/**
* Wyświetlanie linku do profilu użytkownika
*
* @return bool
*/
public static function profileLink($username = NULL, $user = NULL, $text = NULL)
{
if ($user === NULL && $username === NULL)
{
$link = '<a href="'.self::$_url->path(array('controller' => 'profile', 'action' => self::$_user->get('id'), HELP::Title2Link(self::$_user->get('username')))).'">'.($text ? $text : self::$_user->getUsername()).'</a>';
}
elseif ($username === NULL)
{
$username = self::$_user->getByID($user, 'username');
$link = '<a href="'.self::$_url->path(array('controller' => 'profile', 'action' => $user, HELP::Title2Link($username))).'">'.($text ? $text : self::$_user->getUsername($user)).'</a>';
}
elseif ($user === NULL)
{
$user = self::$_user->getByUsername($username, 'id');
$link = '<a href="'.self::$_url->path(array('controller' => 'profile', 'action' => $user, HELP::Title2Link($username))).'">'.($text ? $text : self::$_user->getUsername($user)).'</a>';
}
else
{
$link = '<a href="'.self::$_url->path(array('controller' => 'profile', 'action' => $user, HELP::Title2Link($username))).'">'.($text ? $text : self::$_user->getUsername($user)).'</a>';
}
return $link;
}
public static function randArrayKey($array)
{
return rand(0, count($array)-1);
}
//==================================
//PL: Oznaczenie kolorem znalezionego wyrażenia w ciągu
//==================================
public static function highlight($text, $search, $color = '#99bb00')
{
$txt = str_ireplace($search, '<span style="background: '.$color.'; font-weight: bold;">'.$search.'</span>', $text);
return $txt;
}
//==================================
//PL: Rozkodowywanie adresów URL
//EN: Decoding URL
//==================================
public static function decodingURL($text)
{
$coding = array(
'%C4%85', '%C4%84', '%C4%87', '%C4%86', '%C4%99', '%C4%98', '%C5%82', '%C5%81', '%C5%84', '%C5%83',
'%C3%B3', '%C3%93', '%C5%9B', '%C5%9A', '%C5%BA', '%C5%B9', '%C5%BC', '%C5%BB', '%20', '%22',
'%3C', '%3E', '%7B', '%7D', '%7C', '%60', '%5E', '%E2%82%AC', '%E2%80%B0', '%C6%92',
'%CE%94', '%CE%A0', '%CE%A9', '%CE%B1', '%CE%B2', '%C2%A3', '%C2%A7', '%C2%A9', '%C2%B5', '%E2%88%9E'
);
$encoding = array(
'ą', 'Ą', 'ć', 'Ć', 'ę', 'Ę', 'ł', 'Ł', 'ń', 'Ń',
'ó', 'Ó', 'ś', 'Ś', 'ź', 'Ź', 'ż', 'Ż', ' ', '"',
'<', '>', '{', '}', '|', '`', '^', '€', '‰', 'ƒ',
'Δ', 'Π', 'Ω', 'α', 'β', '£', '§', '©', 'µ', '∞'
);
$txt = str_replace($coding, $encoding, $text);
return $txt;
}
//==================================
//PL: Aliasy dla klas parsującej BBCode
//==================================
public static function parseBBCode($text)
{
return self::$_sbb->parseBBCode($text);
}
//==================================
//PL: Aliasy dla klas parsującej Uśmieszki
//==================================
public static function parseSmiley($text)
{
return self::$_sbb->parseSmiley($text);
}
//==================================
//PL: Aliasy dla klas parsującej BBCode i Uśmieszki
//==================================
public static function parseAllTags($text)
{
return self::$_sbb->parseAllTags($text);
}
/** koniec METODY NAPISANE PRZEZ EF TEAM **/
// Javascript email encoder by Maurits van der Schee
// http://www.maurits.vdschee.nl/php_hide_email/
public static function hide_email($email)
{
if (strpos($email, "@"))
{
$character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
$key = str_shuffle($character_set);
$cipher_text = '';
$id = 'e'.rand(1,999999999);
for ($i=0;$i<strlen($email);$i+=1)
$cipher_text.= $key[strpos($character_set, $email[$i])];
$script = 'var a="'.$key.'";var b=a.split("").sort().join("");var c="'.$cipher_text.'";var d="";';
$script.= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
$script.= 'document.getElementById("'.$id.'").innerHTML="<a href=\\"mailto:"+d+"\\">"+d+"</a>"';
$script = "eval(\"".str_replace(array("\\", '"'),array("\\\\", '\"'), $script)."\")";
$script = '<script type="text/javascript">/*<![CDATA[*/'.$script.'/*]]>*/</script>';
return '<span id="'.$id.'">[N/A]</span>'.$script;
}
else
{
return $email;
}
}
// Create a list of files or folders and store them in an array
// You may filter out extensions by adding them to $extfilter as:
// $ext_filter = "gif|jpg"
public static function getFileList($folder, $filter = array(), $sort = TRUE, $type = 'files', $ext_filter = '')
{
$res = array();
if ($type === 'files' && ! empty($ext_filter))
{
$ext_filter = explode('|', strtolower($ext_filter));
}
$temp = opendir($folder);
while ($file = readdir($temp))
{
if ($type === 'files' && ! in_array($file, $filter))
{
if (! empty($ext_filter))
{
if (!in_array(substr(strtolower(stristr($file, '.')), +1), $ext_filter) && ! is_dir($folder.$file))
{
$res[] = $file;
}
}
else
{
if (!is_dir($folder.$file))
{
$res[] = $file;
}
}
}
elseif ($type === 'folders' && !in_array($file, $filter))
{
if (! empty($ext_filter))
{
if (strstr($file, $ext_filter) && is_dir($folder.$file))
{
$res[] = $file;
}
}
else
{
if (is_dir($folder.$file))
{
$res[] = $file;
}
}
}
}
closedir($temp);
if ($sort)
{
sort($res);
}
return $res;
}
// This public static function sanitises news & article submissions
public static function descript($text, $striptags = TRUE)
{
// Convert problematic ascii characters to their TRUE values
$search = array("40","41","58","65","66","67","68","69","70",
"71","72","73","74","75","76","77","78","79","80","81",
"82","83","84","85","86","87","88","89","90","97","98",
"99","100","101","102","103","104","105","106","107",
"108","109","110","111","112","113","114","115","116",
"117","118","119","120","121","122"
);
$replace = array("(",")",":","a","b","c","d","e","f","g","h",
"i","j","k","l","m","n","o","p","q","r","s","t","u",
"v","w","x","y","z","a","b","c","d","e","f","g","h",
"i","j","k","l","m","n","o","p","q","r","s","t","u",
"v","w","x","y","z"
);
$entities = count($search);
for ($i=0; $i < $entities; $i++)
{
$text = preg_replace("#(&\#)(0*".$search[$i]."+);*#si", $replace[$i], $text);
}
$text = preg_replace('#(&\#x)([0-9A-F]+);*#si', "", $text);
$text = preg_replace('#(<[^>]+[/\"\'\s])(onmouseover|onmousedown|onmouseup|onmouseout|onmousemove|onclick|ondblclick|onfocus|onload|xmlns)[^>]*>#iU', ">", $text);
$text = preg_replace('#([a-z]*)=([\`\'\"]*)script:#iU', '$1=$2nojscript...', $text);
$text = preg_replace('#([a-z]*)=([\`\'\"]*)javascript:#iU', '$1=$2nojavascript...', $text);
$text = preg_replace('#([a-z]*)=([\'\"]*)vbscript:#iU', '$1=$2novbscript...', $text);
$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU', "$1>", $text);
$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU', "$1>", $text);
if ($striptags)
{
do
{
$thistext = $text;
$text = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $text);
} while ($thistext != $text);
}
return $text;
}
//==================================
//PL: Konwertowanie sekund na czas
//EN: Convert seconds to time
//==================================
public static function sec2hms($num_secs)
{
$str = '';
$hours = intval(intval($num_secs) / 3600);
$str .= $hours.':';
$minutes = intval(((intval($num_secs) / 60) % 60));
if ($minutes < 10) $str .= '0';
$str .= $minutes.':';
$seconds = intval(intval(($num_secs % 60)));
if ($seconds < 10) $str .= '0';
$str .= $seconds;
return($str);
}
public static function arrDisplay($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
//==================================
//PL: Funkcja pobierania danych z XML
//EN: Fetches data from XML
//==================================
public static function GetXmlValue($str,$parse)
{
$str1 = explode('<'.$parse.'>',$str);
$str2 = explode('</'.$parse.'>',$str1[1]);
return $str2[0];
}
//==================================
//PL: Przekierowania
//EN: Redirects
//==================================
public static function redirect($location)
{
header('Location: '.$location);
exit;
}
//==================================
//PL: Usuwanie sesji o podanej nazwie
//EN: Removing session by name
//==================================
public static function removeSession()
{
foreach(func_get_args() as $key)
{
if (isset($_SESSION[$key]))
{
unset($_SESSION[$key]);
}
}
}
//==================================
//PL: Usuwanie ciasteczka po nazwie
//EN: Removing cookie by name
//==================================
public static function removeCookie()
{
foreach(func_get_args() as $key)
{
if (isset($_COOKIE[$key]))
{
unset($_COOKIE[$key]);
setcookie($key, NULL, -1, '/', '', '0');
}
}
}
//==================================
//PL: Tworzenie nowego ciasteczka
//EN: Cookie setter
//==================================
public static function setCookie($name, $value, $time)
{
setcookie($name, $value, $time, '/', '', '0');
}
//==================================
//PL: Pobieranie obrazków ze wskazanego folderu
//EN: Downloading images from the folder
//==================================
public static function GetImages($GetDir = '')
{
$HomeDIR = DIR_SITE.'templates'.DS.'images'.$GetDir ? $GetDir.DS : '';
$Images = array();
if ($DirHandle = opendir($HomeDIR))
{
while (($File = readdir($DirHandle)) !== FALSE)
{
if (!is_dir($File) && preg_match("/\.(bmp|jpe?g|gif|png)$/", $File))
{
array_push($Images, $File);
}
}
closedir($DirHandle);
}
return $Images;
}
//==================================
//PL: Skracanie linków
//EN: Shortening links
//==================================
public static function trimlink($text, $length)
{
$dec = array("&", "\"", "'", "\\", '\"', "\'", "<", ">");
$enc = array("&", """, "'", "\", """, "'", "<", ">");
$text = str_replace($enc, $dec, $text);
if (strlen($text) > $length) $text = mb_substr($text, 0, ($length-3))."...";
$text = str_replace($dec, $enc, $text);
return $text;
}
//==================================
// Clean URL public static function, prevents entities in server globals
//==================================
public static function cleanurl($url)
{
$bad_entities = array("&", "\"", "'", '\"', "\'", "<", ">", "(", ")", "*");
$safe_entities = array("&", "", "", "", "", "", "", "", "", "");
$url = str_replace($bad_entities, $safe_entities, $url);
return $url;
}
//==================================
// Strip Input public static function, prevents HTML in unwanted places for Login fields
//==================================
public static function striplogin($text)
{
$search = array("&", "\"", "'", "\\", '\"', "\'", "<", ">", " ");
$replace = array("&", """, "'", "\", """, "'", "<", ">", " ");
$text = str_replace($search, $replace, $text);
return $text;
}
//==================================
// Prevent any possible XSS attacks via $_GET.
//==================================
public static function stripget($_dbconfig)
{
$request = strtolower(urldecode($_SERVER['QUERY_STRING']));
$protarray = array('union','drop','select','into','where','update','from','/*','set ',$_dbconfig['prefix'].'users',$_dbconfig['prefix'].'users(',$_dbconfig['prefix'].'groups','phpinfo','escapeshellarg','exec','fopen','fwrite','escapeshellcmd','passthru','proc_close','proc_get_status','proc_nice','proc_open','proc_terminate','shell_exec','system','telnet','ssh','cmd','mv','chmod','chdir','locate','killall','passwd','kill','script','bash','perl','mysql','~root','.history','~nobody','getenv');
$check = str_replace($protarray, '*', $request);
if ($request !== $check)
{
throw new systemException(die('Podejrzewany atak XSS!'));
}
}
public static function quotes_gpc()
{
if (ini_get('magic_quotes_gpc'))
{
return TRUE;
}
return FALSE;
}
//==================================
// htmlentities is too agressive so we use this public static function
//==================================
public static function phpentities($text)
{
$search = array("&", "\"", "'", "\\", "<", ">");
$replace = array("&", """, "'", "\", "<", ">");
$text = str_replace($search, $replace, $text);
return $text;
}
//==================================
//PL: Zmiana polskich znaków
//EN: Change of Polish characters
// Mordak " Maybe remove this in UK Verison or move in the polish lang file. "
//==================================
public static function PLznaki($text)
{
$a = array("Ą","Ś","Ę","Ó","Ł","Ż","Ź","Ć","Ń","ą","ś","ę","ó","ł","ż","ź","ć","ń");
$b = array("A","S","E","O","L","Z","Z","C","N","a","s","e","o","l","z","z","c","n");
$text = str_replace($a,$b,$text);
return $text;
}
public static function PL($text)
{
$text = iconv('utf-8', 'iso-8859-2', $text);
return $text;
}
public static function PL2($text)
{
$text = iconv('iso-8859-2', 'utf-8', $text);
return $text;
}
//==================================
//PL: Polskie miesiące
//EN: Polish months
// Mordak " Maybe remove this in UK Verison or move in the polish lang file. "
//==================================
public static function MonthsPL($months)
{
$en = array("January","February","March","April","May","June","July","August","September","October","November","December","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$pl = array("Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień","poniedziałek","wtorek","środa","czwartek","piątek","sobota","niedziela");
$months = str_replace($en,$pl,$months);
return $months;
}
//==================================
//PL: Zmiana tytułów dla linków
//EN: Changing the title for links
//==================================
public static function Title2Link($text)
{
if( ! is_array($text))
{
$a = array("Ą","Ś","Ę","Ó","Ł","Ż","Ź","Ć","Ń","ą","ś","ę","ó","ł","ż","ź","ć","ń","ü","""," - "," ",".","!",";",":","(",")","[","]","{","}","|","?",",","+","=","#","@","$","%","^","&","*");
$b = array("A","S","E","O","L","Z","Z","C","N","a","s","e","o","l","z","z","c","n","u","","-","_","","","","","","","","","","","","","","","","","","","","","","");
$c = array("--","---","__","___");
$d = array("-","-","_","_");
$textreplaced = strtolower(str_replace($a,$b,$text));
$textdoublereplaced = str_replace($c,$d,$textreplaced);
return $textdoublereplaced;
}
throw new systemException('Przesłana tablica nie może być przetworzona.');
}
// Strip file name
public static function stripfilename($filename)
{
$a = array("Ą","Ś","Ę","Ó","Ł","Ż","Ź","Ć","Ń","ą","ś","ę","ó","ł","ż","ź","ć","ń","ü","""," - "," ",".","!",";",":","(",")","[","]","{","}","|","?",",","+","=","#","@","$","%","^","&","*");
$b = array("A","S","E","O","L","Z","Z","C","N","a","s","e","o","l","z","z","c","n","u","","-","_","","","","","","","","","","","","","","","","","","","","","","");
$filename = strtolower(str_replace($a,$b,$filename));
$filename = preg_replace("/[^a-zA-Z0-9_-]/", "", $filename);
$filename = preg_replace("/^\W/", "", $filename);
$filename = preg_replace('/([_-])\1+/', '$1', $filename);
if ($filename == "") { $filename = time(); }
return $filename;
}
// Check that site or user theme exists
public static function theme_exists($theme)
{
if (file_exists(DIR_THEMES.$theme.DS.'view.php'))
{
defined('ADDR_THEME') || define('ADDR_THEME', ADDR_THEMES.$theme.'/');
defined('DIR_THEME') || define('DIR_THEME', DIR_THEMES.$theme.DS);
defined('THEME_CSS') || define('THEME_CSS', ADDR_THEME.'templates/stylesheet/');
defined('THEME_JS') || define('THEME_JS', ADDR_THEME.'templates/javascripts/');
defined('THEME_IMAGES') || define('THEME_IMAGES', ADDR_THEME.'templates/images/');
return TRUE;
}
/*else
{
$dh = opendir(DIR_THEMES);
while (FALSE !== ($entry = readdir($dh)))
{
if ($entry != "." && $entry != ".." && is_dir(DIR_THEMES.$entry))
{
if (file_exists(DIR_THEMES.$entry.DS.'core'.DS.'theme.php'))
{
if ($entry === $theme)
{
defined('ADDR_THEME') || define('ADDR_THEME', ADDR_THEMES.$theme.'/');
defined('DIR_THEME') || define('DIR_THEME', DIR_THEMES.$theme.DS);
defined('THEME_CSS') || define('THEME_CSS', ADDR_THEME.'templates/stylesheet/');
defined('THEME_JS') || define('THEME_JS', ADDR_THEME.'templates/javascripts/');
defined('THEME_IMAGES') || define('THEME_IMAGES', ADDR_THEME.'templates/images/');
return TRUE;
}
else
{
return FALSE;
}
}
}
}
closedir($dh);
if ( ! defined('DIR_THEME'))
{
return FALSE;
}
}*/
return FALSE;
}
public static function formatOrphan($content)
{
return $content = preg_replace("/\s([aiouwzAIOUWZ])\s/", " $1 ", $content);
$content = explode(chr(32), $content);
$count = count($content);
$output = '';
for($i=0; $i < $count; $i++)
{
$res = $content[$i];
if (strlen($res) === 1)
{
return $output=$output.$res." ";
}
else
{
return $output.$res." ";
}
}
}
// Format the date & time accordingly
public static function showDate($format, $val)
{
$val += intval(self::$_sett->get('offset_timezone')) * 3600;
if ($format === 'shortdate' || $format == 'longdate')
{
$format = self::$_sett->get($format);
}
else
{
$format = self::$_sett->get('shortdate');
}
$strftime = strftime($format, $val);
return self::toUTF($strftime);
}
public static function date2UTF($date)
{
return self::toUTF($date);
}
public static function toUTF($src)
{
$encoding = mb_detect_encoding($src);
// Sprawdzamy czy znaki są kodowane w UTF-8
if ($encoding === 'UTF-8')
{
// Jeśli tak wyświetlamy je bez zmiany kodowania
return $src;
}
// Zmiana kodowania na UTF-8
return iconv($encoding, 'UTF-8', $src);
}
// Przetwarza ciąg znaków, który ma trafić do meta tagu Desciption
// Usuwanie białych znaków
public static function cleanDescription($data, $length = 135)
{
$data = str_replace(array("\r\n", "\ht"), ' ', trim($data));
$clean = array();
foreach(explode(' ', $data) as $val)
{
if ($val !== '')
{
$clean[] = $val;
}
}
$return = implode(' ', $clean);
if (strlen($return) > $length)
{
$break = $length;
for ($i = $length, $c = $length+80; $i < $c; $i++)
{
if ($return[$i] === '.')
{
$break = $i+1;
break;
}
}
if ($break === $length)
{
for ($i = $length, $c = $length+80; $i < $c; $i++)
{
if ($return[$i] === ' ')
{
$break = $i;
break;
}
}
}
return substr($return, 0, $break);
}
return $return;
}
// http://www.php.net/manual/en/function.str-replace.php#95198
public static function strReplaceAssoc(array $replace, $text)
{
return str_replace(array_keys($replace), array_values($replace), $text);
}
}
| agpl-3.0 |
automenta/netentionj-desktop | src/jnetention/run/WebBrowser.java | 23653 | /*
* Copyright 2013 John Smith
*
* This file is part of Willow.
*
* Willow 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.
*
* Willow 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 Willow. If not, see <http://www.gnu.org/licenses/>.
*
* Contact details: http://jewelsea.wordpress.com
*/
package jnetention.run;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.embed.swing.SwingNode;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyCode;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.text.FontSmoothingType;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import javax.swing.JComponent;
import jnetention.Core;
import jnetention.NObject;
import jnetention.gui.IndexTreePane;
import jnetention.gui.NodeControlPane;
import org.jewelsea.willow.browser.BrowserTab;
import org.jewelsea.willow.browser.BrowserWindow;
import org.jewelsea.willow.browser.LoadingProgressDisplay;
import org.jewelsea.willow.browser.StatusDisplay;
import org.jewelsea.willow.browser.TabManager;
import org.jewelsea.willow.browser.UITab;
import org.jewelsea.willow.navigation.NavTools;
import org.jewelsea.willow.util.DebugUtil;
import org.jewelsea.willow.util.ResourceUtil;
import static org.jewelsea.willow.util.ResourceUtil.getString;
public class WebBrowser extends Application {
@Deprecated final public static long start = System.currentTimeMillis();
private AnchorPane overlayLayer;
private BorderPane underlayLayer;
public static abstract class Route {
public final String url;
public final String name;
public Route(String url, String name) {
this.url = url;
this.name = name;
}
abstract public Object handle(Map<String,String> parameters);
}
public static class Router {
public final Map<String, Route> routes = new HashMap();
public void add(Route r) {
routes.put(r.url, r);
}
public Route get(String url) {
for (String s : routes.keySet()) {
if (s.equals(url))
return routes.get(s);
}
return null;
}
}
public final Router router = new Router();
public static final String APPLICATION_ICON =
"WillowTreeIcon.png";
public static final String DEFAULT_HOME_LOCATION =
"about:";
public static final String STYLESHEET =
"/resources/browser.css";
public StringProperty homeLocationProperty = new SimpleStringProperty(DEFAULT_HOME_LOCATION);
private static final double INITIAL_SCENE_HEIGHT = 600;
private static final double INITIAL_SCENE_WIDTH = 1121;
private Node sidebar; // sidebar for controlling the app.
private TabManager tabManager; // tab manager for managing browser tabs.
private BorderPane mainLayout = new BorderPane(); // layout of the browser application.
private TextField chromeLocField = new TextField(); // current location of the current browser or a value being updated by the user to change the current browser's location.
// change listeners to tie the location of the current browser to the chromeLocField and vice versa (binding cannot be used because both these values must be read/write).
private ChangeListener<String> browserLocFieldChangeListener;
private ChangeListener<String> chromeLocFieldChangeListener;
private Core core;
public WebBrowser(Core c) {
this.core = c;
}
public NObject newBrowserState() {
List<String> urls = new ArrayList();
for (Tab t : tabManager.tabPane.getTabs()) {
if (t instanceof BrowserTab) {
BrowserTab bt = (BrowserTab)t;
urls.add(bt.getLocation());
}
}
NObject o = core.newObject("Web Browsing @ " + new Date().toString());
o.add("Web");
for (String u : urls)
o.add(u);
return o;
}
@Override
public void start(final Stage stage) throws MalformedURLException, UnsupportedEncodingException {
System.out.println("WebBrowser.start()" + (System.currentTimeMillis() - start)/1000.0);
/*
try {
new SchemaOrg(core);
} catch (IOException ex) {
Logger.getLogger(WebBrowser.class.getName()).log(Level.SEVERE, null, ex);
}
*/
initRoutes();
// set the title bar to the title of the web page (if there is one).
stage.setTitle(getString("browser.name"));
// initialize the stuff which can't be initialized in the init method due to stupid threading issues.
tabManager = new TabManager(core, chromeLocField);
System.out.println("created tabs" + (System.currentTimeMillis() - start)/1000.0);
//sidebar = SideBar.createSidebar(this);
sidebar = new NodeControlPane(core);
//System.out.println("created sidebar" + (System.currentTimeMillis() - start)/1000.0);
// initialize the location field in the Chrome.
chromeLocField.setPromptText(getString("location.prompt"));
chromeLocField.setTooltip(new Tooltip(getString("location.tooltip")));
chromeLocField.setOnKeyReleased(keyEvent -> {
if (keyEvent.getCode().equals(KeyCode.ENTER)) {
go(chromeLocField.getText());
}
});
// setup the main layout.
HBox.setHgrow(chromeLocField, Priority.ALWAYS);
final Pane navPane = NavTools.createNavPane(this);
mainLayout.setTop(navPane);
//System.out.println("navpane added " + (System.currentTimeMillis() - start)/1000.0);
// add an overlay layer over the main layout for effects and status messages.
overlayLayer = new AnchorPane();
underlayLayer = new BorderPane();
final StackPane overlaidLayout = new StackPane();
overlaidLayout.getChildren().addAll(underlayLayer, mainLayout, overlayLayer);
overlayLayer.setPickOnBounds(false);
underlayLayer.setPrefWidth(Double.MAX_VALUE);
underlayLayer.setPrefHeight(Double.MAX_VALUE);
underlayLayer.setFocusTraversable(false);
// monitor the tab manager for a change in the browser window and update the display appropriately.
tabManager.browserProperty().addListener((observableValue, oldBrowser, newBrowser) ->
browserChanged(oldBrowser, newBrowser, stage, overlayLayer)
);
//System.out.println("creating scene " + (System.currentTimeMillis() - start)/1000.0);
// create the scene.
final Scene scene = new Scene(
overlaidLayout,
INITIAL_SCENE_WIDTH,
INITIAL_SCENE_HEIGHT
);
scene.getStylesheets().add(STYLESHEET);
//overlaidLayout.setStyle("-fx-background: rgba(100, 0, 0, 0)");
// set some sizing constraints on the scene.
overlayLayer.prefHeightProperty().bind(scene.heightProperty());
overlayLayer.prefWidthProperty().bind(scene.widthProperty());
addOverlayLog();
ScrollPane sidebarScroll = new ScrollPane(sidebar);
sidebarScroll.setFitToHeight(true);
sidebarScroll.setFitToWidth(true);
sidebarScroll.setMinWidth(250);
sidebarScroll.setMaxWidth(250);
//mainLayout.setLeft(sidebarScroll);
//System.out.println("sidebar added " + (System.currentTimeMillis() - start)/1000.0);
// highlight the entire text if we click on the chromeLocField so that it can be easily changed.
chromeLocField.focusedProperty().addListener((observableValue, from, to) -> {
if (to) {
// run later used here to override the default selection rules for the textfield.
Platform.runLater(chromeLocField::selectAll);
}
});
// make the chrome location field draggable.
chromeLocField.getStyleClass().add("location-field");
chromeLocField.setOnDragDetected(mouseEvent -> {
Dragboard db = chromeLocField.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putString(chromeLocField.getText());
db.setContent(content);
});
// automatically hide and show the sidebar and navbar as we transition in and out of fullscreen.
/*
final Button navPaneButton = createNavPaneButton(navPane);
stage.fullScreenProperty().addListener((observableValue, oldValue, newValue) -> {
if ((stage.isFullScreen() && getSidebar().getScroll().isVisible()) ||
(!stage.isFullScreen() && !getSidebar().getScroll().isVisible())) {
((Button) scene.lookup("#sidebarButton")).fire();
}
if ((stage.isFullScreen() && navPane.isVisible()) ||
(!stage.isFullScreen() && !navPane.isVisible())) {
navPaneButton.fire();
}
});
*/
// create a new tab when the user presses Ctrl+T
scene.setOnKeyPressed(keyEvent -> {
if (keyEvent.isControlDown() && keyEvent.getCode().equals(KeyCode.T)) {
tabManager.getNewTabButton().fire();
}
});
//getSidebarDisplay().setMaxWidth(getSidebarDisplay().getWidth());
// add an icon for the application.
stage.getIcons().add(ResourceUtil.getImage(APPLICATION_ICON));
//sidebar.getScroll().setPrefViewportWidth(sidebar.getBarDisplay().getWidth());
// debugging routine.
//debug(scene);
// nav to the home location
go(homeLocationProperty.get());
// we need to manually handle the change from no browser at all to an initial browser.
//browserChanged(null, getBrowser(), stage, overlayLayer);
System.out.println("WebBrowser.start() finished " + (System.currentTimeMillis() - start)/1000.0);
// show the scene.
stage.setScene(scene);
stage.show();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override public void handle(WindowEvent e) {
core.publish(newBrowserState());
}
});
}
private void debug(final Scene scene) {
System.getProperties().list(System.out);
//ScenicView.show(scene);
Platform.runLater(new Runnable() {
@Override
public void run() {
DebugUtil.dump(scene.getRoot());
}
});
}
// creates a button to hide and show the navigation pane.
private Button createNavPaneButton(final Pane navPane) {
final Button navPaneButton = new Button();
final DoubleProperty startHeight = new SimpleDoubleProperty();
// todo java 8 has a weird background issue on resize.
// hide sidebar.
final Animation hideNavPane = new Transition() {
{
setCycleDuration(Duration.millis(250));
}
protected void interpolate(double frac) {
final double curHeight = startHeight.get() * (1.0 - frac);
navPane.setPrefHeight(curHeight); // todo resize a spacing underlay to allow the scene to adjust.
navPane.setTranslateY(-startHeight.get() + curHeight);
}
};
hideNavPane.onFinishedProperty().set(actionEvent -> navPane.setVisible(false));
// show sidebar.
final Animation showNavPane = new Transition() {
{
setCycleDuration(Duration.millis(250));
}
protected void interpolate(double frac) {
final double curHeight = startHeight.get() * frac;
navPane.setPrefHeight(curHeight);
navPane.setTranslateY(-startHeight.get() + curHeight);
}
};
navPaneButton.setOnAction(actionEvent -> {
navPane.setMinHeight(Control.USE_PREF_SIZE);
if (showNavPane.statusProperty().get().equals(Animation.Status.STOPPED) && hideNavPane.statusProperty().get().equals(Animation.Status.STOPPED)) {
if (navPane.isVisible()) {
startHeight.set(navPane.getHeight());
hideNavPane.play();
} else {
navPane.setVisible(true);
showNavPane.play();
}
}
});
return navPaneButton;
}
/**
* Handler for when a new browser is switched into the chrome.
*
* @param oldBrowser the old browser we were to displaying (or none if there is no such thing).
* @param newBrowser the new browser we are to display.
* @param stage the stage displaying the chrome.
* @param overlayLayer the overlay layer for status and other information in the chrome.
*/
private void browserChanged(final UITab oldTab, final UITab newTab, final Stage stage, AnchorPane overlayLayer) {
if (oldTab instanceof BrowserTab) {
BrowserTab oldBrowserTab = (BrowserTab)oldTab;
BrowserWindow oldBrowser = oldBrowserTab.getBrowser();
// cleanup the links between the chrome's location field and the old browser's location field.
if (oldBrowser != null && browserLocFieldChangeListener != null) {
oldBrowser.getLocField().textProperty().removeListener(browserLocFieldChangeListener);
}
if (chromeLocFieldChangeListener != null) {
chromeLocField.textProperty().removeListener(chromeLocFieldChangeListener);
}
}
if (newTab instanceof BrowserTab) {
BrowserTab newBrowserTab = (BrowserTab)newTab;
BrowserWindow newBrowser = newBrowserTab.getBrowser();
// update the stage title to monitor the page displayed in the selected browser.
// todo hmm I wonder how the listeners ever get removed...
newBrowser.getView().getEngine().titleProperty().addListener((observableValue, oldTitle, newTitle) -> {
if (newTitle != null && !"".equals(newTitle)) {
stage.setTitle(getString("browser.name") + " - " + newTitle);
} else {
// necessary because when the browser is in the process of loading a new page, the title will be empty. todo I wonder if the title would be reset correctly if the page has no title.
if (!newBrowser.getView().getEngine().getLoadWorker().isRunning()) {
stage.setTitle(getString("browser.name") );
}
}
});
// monitor the status of the selected browser.
//overlayLayer.getChildren().clear();
final StatusDisplay statusDisplay = new StatusDisplay(newBrowser.statusProperty());
//statusDisplay.translateXProperty().bind(getSidebarDisplay().widthProperty().add(20).add(getSidebarDisplay().translateXProperty()));
//statusDisplay.translateYProperty().bind(overlayLayer.heightProperty().subtract(50));
//overlayLayer.getChildren().add(statusDisplay);
// monitor the loading progress of the selected browser.
statusDisplay.setLoadControl(
new LoadingProgressDisplay(
newBrowser.getView().getEngine().getLoadWorker()
)
);
// make the chrome's location field respond to changes in the new browser's location.
browserLocFieldChangeListener = (observableValue, oldLoc, newLoc) -> {
if (!chromeLocField.getText().equals(newLoc)) {
chromeLocField.setText(newLoc);
}
};
newBrowser.getLocField().textProperty().addListener(browserLocFieldChangeListener);
// make the new browser respond to changes the user makes to the chrome's location.
chromeLocFieldChangeListener = (observableValue, oldLoc, newLoc) -> {
if (!newBrowser.getLocField().getText().equals(newLoc)) {
newBrowser.getLocField().setText(newLoc);
}
};
chromeLocField.textProperty().addListener(chromeLocFieldChangeListener);
chromeLocField.setText(newBrowser.getLocField().getText());
// enable forward and backward buttons as appropriate.
Button forwardButton = (Button) mainLayout.lookup("#forwardButton");
if (forwardButton != null) {
forwardButton.disableProperty().unbind();
forwardButton.disableProperty().bind(newBrowser.getHistory().canNavForwardProperty().not());
}
Button backButton = (Button)mainLayout.lookup("#backButton");
if (forwardButton != null) {
backButton.disableProperty().unbind();
backButton.disableProperty().bind(newBrowser.getHistory().canNavBackwardProperty().not());
}
// display the selected browser.
mainLayout.setCenter(newBrowser.getView());
mainLayout.setBottom(statusDisplay);
}
else if (newTab instanceof UITab) {
mainLayout.setCenter(newTab.content());
}
}
public UITab getBrowser() {
return tabManager.getBrowser();
}
public Node getSidebar() {
return sidebar;
}
public Node getSidebarDisplay() {
return sidebar;
}
public TextField getChromeLocField() {
return chromeLocField;
}
public TabManager getTabManager() {
return tabManager;
}
/** URL router */
private void go(String url) {
Route rr = router.get(url);
if (rr!=null) {
Object r = rr.handle(new HashMap());
if (r!=null) {
Node c;
if (r instanceof String) {
//html
c = new WebView();
((WebView)c).setFontSmoothingType(FontSmoothingType.GRAY);
((WebView)c).getEngine().loadContent((String)r);
}
else if (r instanceof Node) {
//javafx component
c = (Node)r;
}
else if (r instanceof JComponent) {
//swing
c = new SwingNode();
((SwingNode)c).setContent((JComponent)r);
}
else {
c = new Label(r.toString());
}
UITab u = new UITab(core, c);
u.setText(rr.name);
getTabManager().addTab(u);
return;
}
}
//Load URL in BrowserTab
if (getBrowser() instanceof BrowserTab)
((BrowserTab)getBrowser()).getBrowser().go(url);
else {
//create a new tab because we were in a UITab (not BrowserTab)
BrowserTab bt = new BrowserTab(core, tabManager);
getTabManager().addTab(bt);
bt.getBrowser().go(url);
}
}
protected void initRoutes() {
router.add(new Route("about:ontology", "Ontology") {
@Override public Object handle(Map<String, String> parameters) {
return new IndexTreePane(core, null);
}
});
router.add(new Route("about:", "System") {
@Override public Object handle(Map<String, String> parameters) {
String html = "";
html += router.routes.toString();
return html;
}
});
/*
router.add(new Route("about:logic/memory", "Logic Memory") {
@Override public Object handle(Map<String, String> parameters) {
return new MemoryView(core.logic);
}
});
*/
/*router.add(new Route("about:logic", "Logic") {
@Override public Object handle(Map<String, String> parameters) {
return new NARControls(core.logic);
}
});*/
}
protected void addOverlayLog() {
/*TextArea logoutput = new TextArea();
logoutput.setPrefRowCount(10);
logoutput.setEditable(false);
new TextOutput(core.logic) {
@Override
protected void outputString(String s) {
Platform.runLater(new Runnable() {
@Override public void run() {
logoutput.appendText(s+"\n");
}
});
}
};
mainLayout.setOpacity(0.9);
underlayLayer.setCenter(logoutput);*/
}
}
| agpl-3.0 |
abetusk/dev | notes/src/node_modules/midi-json-parser-broker/build/es2019/module.js | 574 | import { createBroker } from 'broker-factory';
/*
* @todo Explicitly referencing the barrel file seems to be necessary when enabling the
* isolatedModules compiler option.
*/
export * from './interfaces/index';
export * from './types/index';
export const wrap = createBroker({
parseArrayBuffer: ({ call }) => {
return async (arrayBuffer) => {
return call('parse', { arrayBuffer }, [arrayBuffer]);
};
}
});
export const load = (url) => {
const worker = new Worker(url);
return wrap(worker);
};
//# sourceMappingURL=module.js.map | agpl-3.0 |
renderpci/dedalo-4 | lib/dedalo/common/class.label.php | 6379 | <?php
#require_once( dirname(dirname(__FILE__)) .'/config/config4.php');
#require_once(DEDALO_LIB_BASE_PATH . '/db/class.RecordObj_dd.php');
/**
* LABEL
* Manage all labels and messages of Dedalo
* Get all labels from file or data base and convert all variables to static vars
*/
# LABEL
abstract class label {
static $ar_label;
/**
* GET AR LABEL
* @return $ar_label
* Class static array
* Priority:
* 1 - Class static
* 2 - Session ['config4']['ar_label']
* 3 - Calculate method 'set_static_label_vars'
*/
public static function get_ar_label( $lang=DEDALO_APPLICATION_LANG ) {
if ($lang==='lg-vlca') {
$lang = 'lg-cat';
}
# DEBUG NOT STORE SESSION LABELS
#if(SHOW_DEBUG===true) unset($ar_label);
if(isset(label::$ar_label[$lang])) return label::$ar_label[$lang];
switch (true) {
# using DEDALO_CACHE_MANAGER as cache
case (DEDALO_CACHE_MANAGER===true && CACHE_LABELS===true) :
$cache_key_name = DEDALO_DATABASE_CONN.'_label_'.$lang;;
if (cache::exists($cache_key_name)) {
#error_log("INFO: readed data from label cache key: $cache_key_name");
label::$ar_label[$lang] = unserialize(cache::get($cache_key_name));
}else{
# Calculate label for current lang and store
label::$ar_label[$lang] = self::set_static_label_vars( $lang );
cache::set($cache_key_name, serialize( label::$ar_label[$lang] ));
}
break;
# Using php session as cache
default:
if( isset($_SESSION['dedalo4']['config']['ar_label'][$lang]) ) {
# Get from session
label::$ar_label[$lang] = $_SESSION['dedalo4']['config']['ar_label'][$lang];
}else{
# Calculate label for current lang and store
label::$ar_label[$lang] = self::set_static_label_vars( $lang );
$_SESSION['dedalo4']['config']['ar_label'][$lang] = label::$ar_label[$lang];
}
}
$ar_label = label::$ar_label[$lang];
return $ar_label;
}//end get_ar_label
/**
* GET_LABEL_CACHE_KEY_NAME
*//*
public function get_label_cache_key_name() {
return DEDALO_DATABASE_CONN.'_label_'.DEDALO_APPLICATION_LANG;
}
*/
/**
* GET LABEL
* @param $name
* String var name like 'quit'
* Get label data static
*/
public static function get_label($name, $lang=DEDALO_APPLICATION_LANG) {
if ($lang==='lg-vlca') {
$lang = 'lg-cat';
}
# Calculate values (is calculated once)
self::get_ar_label($lang);
if(!isset(label::$ar_label[$lang][$name])) {
#return "Sorry, $name is untranslated";
#return '<span class="untranslated">'.$name .'</span>';
return component_common::decore_untranslated($name);
}
#dump(label::$ar_label,'label::$ar_label');
return label::$ar_label[$lang][$name];
}
/**
* GET VAR FROM LABEL
* @param $label
* String label like 'Relaciones'
* Resolve inverse label
*/
public static function get_var_from_label($label, $lang=DEDALO_APPLICATION_LANG) {
if ($lang==='lg-vlca') {
$lang = 'lg-cat';
}
# Calculate values (is calculated once)
self::get_ar_label($lang);
if(!isset(label::$ar_label[$lang])) return NULL;
# Search in array to resolve
foreach (label::$ar_label[$lang] as $key => $value) {
#echo $key .'<br>';
if ( strtolower($value) === strtolower($label) ) {
return $key;
}
}
}
/**
* SET STATIC VARS
* Calculate an fix all labels values from structure (all terms with model 'label')
*/
protected static function set_static_label_vars( $lang=DEDALO_APPLICATION_LANG ) {
if(SHOW_DEBUG===true) $start_time=microtime(1);
if ($lang==='lg-vlca') {
$lang = 'lg-cat';
}
if(SHOW_DEBUG===true) {
global$TIMER;$TIMER[__METHOD__.'_IN_'.microtime(1)]=microtime(1);
}
$ar_terminoID_by_modelo_name = (array)RecordObj_dd::get_ar_terminoID_by_modelo_name($modelo_name='label');
#dump($ar_terminoID_by_modelo_name,'$ar_terminoID_by_modelo_name',"label: label ");
$ar_label = array();
$cached = true;
$fallback = true;
if(SHOW_DEBUG===true) {
#$cached=false;
}
foreach ($ar_terminoID_by_modelo_name as $current_terminoID) {
$RecordObj_dd = new RecordObj_dd($current_terminoID);
$propiedades = $RecordObj_dd->get_propiedades();
$vars_obj = json_decode($propiedades);
# No data in field 'propiedades'
if(empty($vars_obj) || empty($vars_obj->name)) {
trigger_error("Term $current_terminoID with model 'label' dont't have properly configurated 'propiedades'. Please solve this ASAP");
continue;
}
# Set value
$ar_label[$vars_obj->name] = RecordObj_dd::get_termino_by_tipo($current_terminoID, $lang, $cached, $fallback);
}
if(SHOW_DEBUG===true) {
global$TIMER;$TIMER[__METHOD__.'_OUT_'.microtime(1)]=microtime(1);
#error_log("Calculated labels ".count($ar_terminoID_by_modelo_name));
debug_log(__METHOD__." for lang: $lang ".exec_time_unit($start_time,'ms').' ms');
}
return $ar_label;
}//end set_static_label_vars
/**
* GET_TERMINOID_FROM_LABEL
* Resolve terminoID from label propiedades property 'label'
*/
public static function get_terminoID_from_label( $label ) {
if(SHOW_DEBUG===true) $start_time=microtime(1);
$terminoID = null;
if(SHOW_DEBUG===true) {
global$TIMER;$TIMER[__METHOD__.'_IN_'.microtime(1)]=microtime(1);
}
$ar_terminoID_by_modelo_name = (array)RecordObj_dd::get_ar_terminoID_by_modelo_name($modelo_name='label');
#dump($ar_terminoID_by_modelo_name,'$ar_terminoID_by_modelo_name',"label: label ");
foreach ($ar_terminoID_by_modelo_name as $current_terminoID) {
$RecordObj_dd = new RecordObj_dd($current_terminoID);
$propiedades = $RecordObj_dd->get_propiedades();
$vars_obj = json_decode($propiedades);
# No data in field 'propiedades'
if(empty($vars_obj) || empty($vars_obj->name)) {
trigger_error("Term $current_terminoID with model 'label' dont't have properly configurated 'propiedades'. Please solve this ASAP");
continue;
}
if ($vars_obj->name===$label) {
$terminoID = $current_terminoID;
break;
}
}
if(SHOW_DEBUG===true) {
global$TIMER;$TIMER[__METHOD__.'_OUT_'.microtime(1)]=microtime(1);
#error_log("Calculated labels ".count($ar_terminoID_by_modelo_name));
debug_log(__METHOD__." Total ".exec_time_unit($start_time,'ms').' ms');
}
return $terminoID;
}//end get_terminoID_from_label
}
?> | agpl-3.0 |
xkfz007/vlc | build/win32/include/qt4/src/corelib/thread/qthreadstorage.cpp | 10115 | /****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qthreadstorage.h"
#ifndef QT_NO_THREAD
#include "qthread.h"
#include "qthread_p.h"
#include "qmutex.h"
#include <string.h>
QT_BEGIN_NAMESPACE
// #define THREADSTORAGE_DEBUG
#ifdef THREADSTORAGE_DEBUG
# define DEBUG_MSG qtsDebug
# include <stdio.h>
# include <stdarg.h>
void qtsDebug(const char *fmt, ...)
{
va_list va;
va_start(va, fmt);
fprintf(stderr, "QThreadStorage: ");
vfprintf(stderr, fmt, va);
fprintf(stderr, "\n");
va_end(va);
}
#else
# define DEBUG_MSG if(false)qDebug
#endif
Q_GLOBAL_STATIC(QMutex, mutex)
typedef QVector<void (*)(void *)> DestructorMap;
Q_GLOBAL_STATIC(DestructorMap, destructors)
QThreadStorageData::QThreadStorageData(void (*func)(void *))
{
QMutexLocker locker(mutex());
DestructorMap *destr = destructors();
if (!destr) {
/*
the destructors vector has already been destroyed, yet a new
QThreadStorage is being allocated. this can only happen during global
destruction, at which point we assume that there is only one thread.
in order to keep QThreadStorage working, we need somewhere to store
the data, best place we have in this situation is at the tail of the
current thread's tls vector. the destructor is ignored, since we have
no where to store it, and no way to actually call it.
*/
QThreadData *data = QThreadData::current();
id = data->tls.count();
DEBUG_MSG("QThreadStorageData: Allocated id %d, destructor %p cannot be stored", id, func);
return;
}
for (id = 0; id < destr->count(); id++) {
if (destr->at(id) == 0)
break;
}
if (id == destr->count()) {
destr->append(func);
} else {
(*destr)[id] = func;
}
DEBUG_MSG("QThreadStorageData: Allocated id %d, destructor %p", id, func);
}
QThreadStorageData::~QThreadStorageData()
{
DEBUG_MSG("QThreadStorageData: Released id %d", id);
QMutexLocker locker(mutex());
if (destructors())
(*destructors())[id] = 0;
}
void **QThreadStorageData::get() const
{
QThreadData *data = QThreadData::current();
if (!data) {
qWarning("QThreadStorage::get: QThreadStorage can only be used with threads started with QThread");
return 0;
}
QVector<void *> &tls = data->tls;
if (tls.size() <= id)
tls.resize(id + 1);
void **v = &tls[id];
DEBUG_MSG("QThreadStorageData: Returning storage %d, data %p, for thread %p",
id,
*v,
data->thread);
return *v ? v : 0;
}
void **QThreadStorageData::set(void *p)
{
QThreadData *data = QThreadData::current();
if (!data) {
qWarning("QThreadStorage::set: QThreadStorage can only be used with threads started with QThread");
return 0;
}
QVector<void *> &tls = data->tls;
if (tls.size() <= id)
tls.resize(id + 1);
void *&value = tls[id];
// delete any previous data
if (value != 0) {
DEBUG_MSG("QThreadStorageData: Deleting previous storage %d, data %p, for thread %p",
id,
value,
data->thread);
QMutexLocker locker(mutex());
DestructorMap *destr = destructors();
void (*destructor)(void *) = destr ? destr->value(id) : 0;
locker.unlock();
void *q = value;
value = 0;
if (destructor)
destructor(q);
}
// store new data
value = p;
DEBUG_MSG("QThreadStorageData: Set storage %d for thread %p to %p", id, data->thread, p);
return &value;
}
void QThreadStorageData::finish(void **p)
{
QVector<void *> *tls = reinterpret_cast<QVector<void *> *>(p);
if (!tls || tls->isEmpty() || !mutex())
return; // nothing to do
DEBUG_MSG("QThreadStorageData: Destroying storage for thread %p", QThread::currentThread());
while (!tls->isEmpty()) {
void *&value = tls->last();
void *q = value;
value = 0;
int i = tls->size() - 1;
tls->resize(i);
if (!q) {
// data already deleted
continue;
}
QMutexLocker locker(mutex());
void (*destructor)(void *) = destructors()->value(i);
locker.unlock();
if (!destructor) {
if (QThread::currentThread())
qWarning("QThreadStorage: Thread %p exited after QThreadStorage %d destroyed",
QThread::currentThread(), i);
continue;
}
destructor(q); //crash here might mean the thread exited after qthreadstorage was destroyed
if (tls->size() > i) {
//re reset the tls in case it has been recreated by its own destructor.
(*tls)[i] = 0;
}
}
tls->clear();
}
/*!
\class QThreadStorage
\brief The QThreadStorage class provides per-thread data storage.
\threadsafe
\ingroup thread
QThreadStorage is a template class that provides per-thread data
storage.
The setLocalData() function stores a single thread-specific value
for the calling thread. The data can be accessed later using
localData().
The hasLocalData() function allows the programmer to determine if
data has previously been set using the setLocalData() function.
This is also useful for lazy initializiation.
If T is a pointer type, QThreadStorage takes ownership of the data
(which must be created on the heap with \c new) and deletes it when
the thread exits, either normally or via termination.
For example, the following code uses QThreadStorage to store a
single cache for each thread that calls the cacheObject() and
removeFromCache() functions. The cache is automatically
deleted when the calling thread exits.
\snippet doc/src/snippets/threads/threads.cpp 7
\snippet doc/src/snippets/threads/threads.cpp 8
\snippet doc/src/snippets/threads/threads.cpp 9
\section1 Caveats
\list
\o The QThreadStorage destructor does not delete per-thread data.
QThreadStorage only deletes per-thread data when the thread exits
or when setLocalData() is called multiple times.
\o QThreadStorage can be used to store data for the \c main()
thread. QThreadStorage deletes all data set for the \c main()
thread when QApplication is destroyed, regardless of whether or
not the \c main() thread has actually finished.
\endlist
\sa QThread
*/
/*!
\fn QThreadStorage::QThreadStorage()
Constructs a new per-thread data storage object.
*/
/*!
\fn QThreadStorage::~QThreadStorage()
Destroys the per-thread data storage object.
Note: The per-thread data stored is not deleted. Any data left
in QThreadStorage is leaked. Make sure that all threads using
QThreadStorage have exited before deleting the QThreadStorage.
\sa hasLocalData()
*/
/*!
\fn bool QThreadStorage::hasLocalData() const
If T is a pointer type, returns true if the calling thread has
non-zero data available.
If T is a value type, returns whether the data has already been
constructed by calling setLocalData or localData.
\sa localData()
*/
/*!
\fn T &QThreadStorage::localData()
Returns a reference to the data that was set by the calling
thread.
If no data has been set, this will create a default constructed
instance of type T.
\sa hasLocalData()
*/
/*!
\fn const T QThreadStorage::localData() const
\overload
Returns a copy of the data that was set by the calling thread.
\sa hasLocalData()
*/
/*!
\fn void QThreadStorage::setLocalData(T data)
Sets the local data for the calling thread to \a data. It can be
accessed later using the localData() functions.
If T is a pointer type, QThreadStorage takes ownership of the data
and deletes it automatically either when the thread exits (either
normally or via termination) or when setLocalData() is called again.
\sa localData(), hasLocalData()
*/
#endif // QT_NO_THREAD
QT_END_NAMESPACE
| lgpl-2.1 |
beast-dev/beast-mcmc | src/dr/evomodel/operators/ScaleNodeHeightOperator.java | 5613 | /*
* SubtreeLeapOperator.java
*
* Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST 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.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.operators;
import dr.evolution.tree.NodeRef;
import dr.evomodel.tree.TreeChangedEvent;
import dr.evomodel.tree.TreeModel;
import dr.evomodelxml.operators.NodeHeightOperatorParser;
import dr.inference.operators.AdaptationMode;
import dr.inference.operators.RandomWalkOperator;
import dr.math.MathUtils;
import dr.util.Transform;
/**
* Implements moves that changes node heights - Scale version
*
* Created to allow these operations on TreeModels that can't expose node heights as parameters for efficiency
* reasons such as BigFastTreeModel.
*
* @author Andrew Rambaut
* @version $Id$
*/
public class ScaleNodeHeightOperator extends AbstractAdaptableTreeOperator {
private double tunableParameter;
private final TreeModel tree;
private final NodeHeightOperatorParser.OperatorType operatorType;
/**
* Constructor
*
* @param tree the tree
* @param weight the weight
* @param tunableParameter size of move for types that need it
* @param targetAcceptance the desired acceptance probability
* @param operatorType the type of move to make
* @param mode coercion mode
*/
public ScaleNodeHeightOperator(TreeModel tree, double weight, double tunableParameter, NodeHeightOperatorParser.OperatorType operatorType, AdaptationMode mode, double targetAcceptance) {
super(mode, targetAcceptance);
if (operatorType != NodeHeightOperatorParser.OperatorType.SCALEALL && operatorType != NodeHeightOperatorParser.OperatorType.SCALEROOT) {
throw new UnsupportedOperationException("ScaleNodeHeightOperator can only perform SCALEALL or SCALEROOT operator types");
}
this.tree = tree;
setWeight(weight);
this.tunableParameter = tunableParameter;
this.operatorType = operatorType;
}
/**
* Do a subtree leap move.
*
* @return the log-transformed hastings ratio
*/
public double doOperation() {
final NodeRef root = tree.getRoot();
double logq;
if (operatorType == NodeHeightOperatorParser.OperatorType.SCALEALL) {
logq = doScaleAll();
} else {
//if (operatorType == OperatorType.SCALEROOT) {
final double lowerHeight = Math.max(
tree.getNodeHeight(tree.getChild(root, 0)),
tree.getNodeHeight(tree.getChild(root, 1)));
final double oldHeight = tree.getNodeHeight(root);
logq = doScaleRoot(root, oldHeight, lowerHeight);
}
return logq;
}
private double doScaleAll() {
final double scaleFactor = tunableParameter;
final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
for (NodeRef node : tree.getNodes()) {
if (!tree.isExternal(node)) {
double h = tree.getNodeHeight(node);
// set quietly so a single update message is sent at the end
tree.setNodeHeightQuietly(node, h * scale);
}
}
if (!tree.isTreeValid()) {
// node heights are no long valid (i.e. may be below tips) so force a move reject
return Double.NEGATIVE_INFINITY;
}
tree.pushTreeChangedEvent(TreeChangedEvent.create(false, true));
return (tree.getInternalNodeCount() - 2) * Math.log(scale);
}
private double doScaleRoot(NodeRef node, double oldValue, double lower) {
final double scaleFactor = tunableParameter;
final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
double h = oldValue - lower;
tree.setNodeHeight(node, h * scale + lower);
return -Math.log(scale);
}
@Override
protected void setAdaptableParameterValue(double value) {
tunableParameter = 1.0 / (Math.exp(value) + 1.0);
}
@Override
protected double getAdaptableParameterValue() {
return Math.log(1.0 / tunableParameter - 1.0);
}
@Override
public double getRawParameter() {
return tunableParameter;
}
public String getAdaptableParameterName() {
return "scaleFactor";
}
public String getOperatorName() {
switch (operatorType) {
case SCALEROOT:
return "scale(" + tree.getId() + " root height)";
case SCALEALL:
return "scaleAll(" + tree.getId() + " internal nodes)";
default:
throw new IllegalArgumentException("Unsupported OperatorType");
}
}
}
| lgpl-2.1 |
MenesesEvandro/WCF | wcfsetup/install/files/lib/system/session/AbstractSessionHandler.class.php | 978 | <?php
namespace wcf\system\session;
use wcf\system\SingletonFactory;
/**
* Abstract implementation for application-specific session handlers.
*
* @author Alexander Ebert
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Session
*/
abstract class AbstractSessionHandler extends SingletonFactory {
/**
* SessionHandler object
* @var SessionHandler
*/
protected $sessionHandler = null;
/**
* @inheritDoc
*/
protected final function init() {
$this->sessionHandler = SessionHandler::getInstance();
// initialize session
$this->initSession();
}
/**
* Forwards calls on unknown properties to stored SessionHandler
*
* @param string $key
* @return mixed
*/
public function __get($key) {
return $this->sessionHandler->{$key};
}
/**
* Initializes this session.
*/
abstract protected function initSession();
}
| lgpl-2.1 |
bd2kccd/ccd-annotations | src/main/java/edu/pitt/dbmi/ccd/anno/vocabulary/VocabularyResourceAssembler.java | 3412 | /*
* Copyright (C) 2015 University of Pittsburgh.
*
* 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 edu.pitt.dbmi.ccd.anno.vocabulary;
import edu.pitt.dbmi.ccd.db.entity.Vocabulary;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.mvc.ResourceAssemblerSupport;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* Assembles Vocabulary into VocabularyResource
*
* @author Mark Silvis (marksilvis@pitt.edu)
*/
@Component
public class VocabularyResourceAssembler extends ResourceAssemblerSupport<Vocabulary, VocabularyResource> {
private final VocabularyLinks vocabularyLinks;
@Autowired(required = true)
public VocabularyResourceAssembler(VocabularyLinks vocabularyLinks) {
super(VocabularyController.class, VocabularyResource.class);
this.vocabularyLinks = vocabularyLinks;
}
/**
* convert Vocabulary to VocabularyResource
*
* @param vocabulary entity
* @return resource
*/
@Override
public VocabularyResource toResource(Vocabulary vocabulary) throws IllegalArgumentException {
Assert.notNull(vocabulary);
VocabularyResource resource = createResourceWithId(vocabulary.getId(), vocabulary);
resource.add(vocabularyLinks.attributes(vocabulary));
resource.add(vocabularyLinks.annotations(vocabulary));
return resource;
}
/**
* convert Vocabularies to VocabularyResources
*
* @param vocabularies entities
* @return List of resources
*/
@Override
public List<VocabularyResource> toResources(Iterable<? extends Vocabulary> vocabularies) throws IllegalArgumentException {
// Assert vocabularies is not empty
Assert.isTrue(vocabularies.iterator().hasNext());
return StreamSupport.stream(vocabularies.spliterator(), false)
.map(this::toResource)
.collect(Collectors.toList());
}
/**
* Instantiate VocabularyResource with non-default constructor
*
* @param vocabulary entity
* @return resource
*/
@Override
protected VocabularyResource instantiateResource(Vocabulary vocabulary) throws IllegalArgumentException {
Assert.notNull(vocabulary);
try {
return BeanUtils.instantiateClass(VocabularyResource.class.getConstructor(Vocabulary.class), vocabulary);
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
return new VocabularyResource();
}
}
}
| lgpl-2.1 |
thuliumcc/javaforce | src/javaforce/media/MediaCoder.java | 9262 | package javaforce.media;
/** Base class for Media Coders.
*
* @author pquiring
*/
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.zip.*;
import javaforce.*;
import javaforce.jni.*;
public class MediaCoder {
private long ctx = 0;
private static boolean inited = false;
public static boolean loaded = false;
static {
if (!inited) {
JFNative.load();
init();
inited = true;
}
}
/** Loads the media framework native libraries. */
public static boolean init() {
if (loaded) return true;
boolean libav_org = false;
File sysFolder;
String ext = "";
if (JF.isWindows()) {
sysFolder = new File(".");
ext = ".dll";
} else {
sysFolder = new File("/usr/lib");
if (JF.isMac()) {
ext = ".dylib";
} else {
ext = ".so";
}
}
Library libs[] = {
new Library("avcodec")
, new Library("avdevice")
, new Library("avfilter")
, new Library("avformat")
, new Library("avutil")
, new Library("swscale")
, new Library("swresample", true) //(ffmpeg)
, new Library("avresample", true) //(libav_org)
};
JFNative.findLibraries(sysFolder, libs, ext, libs.length-1);
if (libs[6].path != null) {
libav_org = false;
} else if (libs[7].path != null) {
libav_org = true;
}
if (!haveLibs(libs)) {
for(int a=0;a<libs.length;a++) {
if (a == 6 && libav_org) continue;
if (a == 7 && !libav_org) continue;
if (libs[a].path == null) {
System.out.println("Error:Unable to load library:" + libs[a].name + ext);
}
}
// JFLog.logTrace("MediaCoder.init() failed");
return false;
}
loaded = ffmpeg_init(libs[0].path, libs[1].path, libs[2].path, libs[3].path
, libs[4].path, libs[5].path, libav_org ? libs[7].path : libs[6].path, libav_org);
return loaded;
}
private static native boolean ffmpeg_init(String codec, String device, String filter, String format, String util, String scale, String resample, boolean libav_org);
private static boolean haveLibs(Library libs[]) {
int cnt = 0;
for(int a=0;a<6;a++) {
if (libs[a].path != null) cnt++;
}
if (libs[6].path != null) cnt++;
else if (libs[7].path != null) cnt++;
return cnt == 7;
}
//constants
//constants
public static final int SEEK_SET = 0;
public static final int SEEK_CUR = 1;
public static final int SEEK_END = 2;
//for use with VideoDecoder
public static final int AV_CODEC_ID_NONE = 0;
public static final int AV_CODEC_ID_MPEG1VIDEO = 1;
public static final int AV_CODEC_ID_MPEG2VIDEO = 2;
public static final int AV_CODEC_ID_H263 = 5;
public static final int AV_CODEC_ID_MPEG4 = 13;
public static final int AV_CODEC_ID_H264 = 28;
public static final int AV_CODEC_ID_THEORA = 31;
public static final int AV_CODEC_ID_VP8 = 141;
//a few audio codecs
public static final int AV_CODEC_ID_PCM_S16LE = 0x10000; //wav file
public static final int AV_CODEC_ID_FLAC = 0x1500c;
//returned by MediaDecoder.read()
public static final int END_FRAME = -1;
public static final int NULL_FRAME = 0; //could be metadata frame
public static final int AUDIO_FRAME = 1;
public static final int VIDEO_FRAME = 2;
/** Downloads the codec pack for Windows (supports .zip or .7z) */
public static boolean download() {
if (!JF.isWindows()) {
JF.showError("Notice", "This application requires the codecpack which was not detected.\n"
+ "Please visit http://javaforce.sourceforge.net/codecpack.php for more info.\n"
+ "Press OK to visit this page now");
JF.openURL("http://javaforce.sourceforge.net/codecpack.php");
return false;
}
if (!JF.showConfirm("Notice", "This application requires the codecpack which was not detected.\n"
+ "Please visit http://javaforce.sourceforge.net/codecpack.php for more info.\n"
+ "NOTE:To install the codecpack this app may require administrative rights.\n"
+ "To run with admin rights, right click this app and select 'Run as Administrator'.\n"
+ "Press OK to download and install now.\n"
+ "Press CANCEL to visit website now.\n"))
{
JF.openURL("http://javaforce.sourceforge.net/codecpack.php");
return false;
}
JFTask task = new JFTask() {
public boolean work() {
this.setTitle("Downloading CodecPack");
this.setLabel("Downloading CodecPack...");
this.setProgress(-1);
String destFolder = ".";
//find best place to extract to
try {
File file = new File(destFolder + "\\$testfile$.tmp");
FileOutputStream fos = new FileOutputStream(file);
fos.close();
file.delete();
} catch (Exception e) {
this.setLabel("Download failed (no write access to folder)");
return false;
}
//first download latest URL from javaforce.sf.net
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new URL("http://javaforce.sourceforge.net/codecpackwin"
+ (JF.is64Bit() ? "64" : "32") + ".php").openStream()));
String url = reader.readLine();
int zLength = JF.atoi(reader.readLine());
byte buf[] = new byte[64 * 1024];
int length = 0;
File zfile;
boolean z7;
int z7Length = 0;
String url7 = null;
String filename = null;
if (url.endsWith(".zip")) {
zfile = new File(destFolder + "\\codecpack.zip");
z7 = false;
} else if (url.endsWith(".7z")) {
zfile = new File(destFolder + "\\codecpack.7z");
z7 = true;
url7 = reader.readLine();
z7Length = JF.atoi(reader.readLine());
int i1 = url.lastIndexOf("/")+1;
int i2 = url.lastIndexOf(".");
filename = url.substring(i1,i2);
} else {
JF.showError("Error", "Unsupported file type");
return false;
}
{
InputStream is = new URL(url).openStream();
FileOutputStream fos = new FileOutputStream(zfile);
System.out.println("Downloading:" + url);
while (true) {
int read = is.read(buf);
if (read == -1) break;
if (read == 0) {
JF.sleep(10);
continue;
}
fos.write(buf, 0, read);
length += read;
this.setProgress(length * 100 / zLength);
}
fos.close();
if (length != zLength) {
this.setLabel("Download failed...");
return false;
}
}
if (z7) {
//download 7za.exe (~500KB)
InputStream is = new URL(url7).openStream();
FileOutputStream fos = new FileOutputStream(new File(destFolder + "/7za.exe"));
length = 0;
System.out.println("Downloading:" + url7);
while (true) {
int read = is.read(buf);
if (read == -1) break;
if (read == 0) {
JF.sleep(10);
continue;
}
fos.write(buf, 0, read);
length += read;
}
fos.close();
if (length != z7Length) {
this.setLabel("Download failed (7za.exe)...");
return false;
}
}
this.setLabel("Download complete, now installing...");
this.setProgress(0);
if (z7) {
ShellProcess sp = new ShellProcess();
// sp.setFolder(new File(destFolder));
System.out.println("Exec:7za e " + zfile.getName()+ " " + filename+"/bin/*.dll");
sp.run(new String[]{"7za.exe", "e", zfile.getName(), filename+"\\bin\\*.dll"}, false);
} else {
ZipFile zf = new ZipFile(zfile);
int cnt = 0;
FileOutputStream fos;
for (Enumeration e = zf.entries(); e.hasMoreElements();) {
ZipEntry ze = (ZipEntry)e.nextElement();
String name = ze.getName().toLowerCase();
if (!name.endsWith(".dll")) continue;
int idx = name.lastIndexOf("/");
if (idx != -1) {
name = name.substring(idx+1); //remove any path
}
fos = new FileOutputStream(destFolder + "\\" + name);
InputStream zis = zf.getInputStream(ze);
JFLog.log("extracting:" + name + ",length=" + ze.getSize());
JF.copyAll(zis, fos, ze.getSize());
zis.close();
fos.close();
cnt++;
this.setProgress(cnt * 100 / 8);
}
}
this.setProgress(100);
this.setLabel("Install complete");
return true;
} catch (Exception e) {
this.setLabel("An error occured, see console output for details.");
JFLog.log(e);
return false;
}
}
};
new ProgressDialog(null, true, task).setVisible(true);
return task.getStatus();
}
}
| lgpl-2.1 |
jzuijlek/Lucee | core/src/main/java/org/apache/taglibs/datetime/FormatTag.java | 7393 | /**
*
* Copyright (c) 2014, the Railo Company Ltd. 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 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, see <http://www.gnu.org/licenses/>.
*
**/
package org.apache.taglibs.datetime;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
public final class FormatTag extends BodyTagSupport {
// format tag attributes
// Optional attribute, use users locale if known when formatting date
private boolean locale_flag = false;
// Optional attribute, time pattern string to use when formatting date
private String pattern = null;
// Optional attribute, name of script variable to use as pattern
private String patternid = null;
// Optional attribute, timeZone script variable id to use when formatting date
private String timeZone_string;
// Optional attribute, date object from rtexprvalue
private Date date = null;
// Optional attribute, the default text if the tag body or date given is invalid/null
private String default_text = "Invalid Date";
// Optional attribute, the name of an attribute which contains the Locale
private String localeRef = null;
// Optional attribute, name of script variable to use as date symbols source
private String symbolsRef = null;
// format tag invocation variables
// The symbols object
private DateFormatSymbols symbols = null;
// The date to be formatted an output by tag
private Date output_date = null;
/**
* Method called at start of tag, always returns EVAL_BODY_TAG
*
* @return EVAL_BODY_TAG
*/
@Override
public final int doStartTag() throws JspException {
output_date = date;
return EVAL_BODY_TAG;
}
/**
* Method called at end of format tag body.
*
* @return SKIP_BODY
*/
@Override
public final int doAfterBody() throws JspException {
// Use the body of the tag as input for the date
BodyContent body = getBodyContent();
String s = body.getString().trim();
// Clear the body since we will output only the formatted date
body.clearBody();
if (output_date == null) {
long time;
try {
time = Long.valueOf(s).longValue();
output_date = new Date(time);
}
catch (NumberFormatException nfe) {}
}
return SKIP_BODY;
}
/**
* Method called at end of Tag
*
* @return EVAL_PAGE
*/
@Override
public final int doEndTag() throws JspException {
String date_formatted = default_text;
if (output_date != null) {
// Get the pattern to use
SimpleDateFormat sdf;
String pat = pattern;
if (pat == null && patternid != null) {
Object attr = pageContext.findAttribute(patternid);
if (attr != null) pat = attr.toString();
}
if (pat == null) {
sdf = new SimpleDateFormat();
pat = sdf.toPattern();
}
// Get a DateFormatSymbols
if (symbolsRef != null) {
symbols = (DateFormatSymbols) pageContext.findAttribute(symbolsRef);
if (symbols == null) {
throw new JspException("datetime format tag could not find dateFormatSymbols for symbolsRef \"" + symbolsRef + "\".");
}
}
// Get a SimpleDateFormat using locale if necessary
if (localeRef != null) {
Locale locale = (Locale) pageContext.findAttribute(localeRef);
if (locale == null) {
throw new JspException("datetime format tag could not find locale for localeRef \"" + localeRef + "\".");
}
sdf = new SimpleDateFormat(pat, locale);
}
else if (locale_flag) {
sdf = new SimpleDateFormat(pat, pageContext.getRequest().getLocale());
}
else if (symbols != null) {
sdf = new SimpleDateFormat(pat, symbols);
}
else {
sdf = new SimpleDateFormat(pat);
}
// See if there is a timeZone
if (timeZone_string != null) {
TimeZone timeZone = (TimeZone) pageContext.getAttribute(timeZone_string, PageContext.SESSION_SCOPE);
if (timeZone == null) {
throw new JspTagException("Datetime format tag timeZone " + "script variable \"" + timeZone_string + " \" does not exist");
}
sdf.setTimeZone(timeZone);
}
// Format the date for display
date_formatted = sdf.format(output_date);
}
try {
pageContext.getOut().write(date_formatted);
}
catch (Exception e) {
throw new JspException("IO Error: " + e.getMessage());
}
return EVAL_PAGE;
}
@Override
public void release() {
// lucee.print.ln("release FormatTag");
super.release();
locale_flag = false;
pattern = null;
patternid = null;
date = null;
localeRef = null;
symbolsRef = null;
symbols = null;
}
/**
* Locale flag, if set to true, format date for client's preferred locale if known.
*
* @param boolean use users locale, true or false
*/
public final void setLocale(short flag) {
// locale_flag = flag;
}
/**
* Set the time zone to use when formatting date.
*
* Value must be the name of a <b>timeZone</b> tag script variable ID.
*
* @param String name of timeZone to use
*/
public final void setTimeZone(String tz) {
timeZone_string = tz;
}
/**
* Set the pattern to use when formatting Date.
*
* @param String SimpleDateFormat style time pattern format string
*/
public final void setPattern(String str) {
pattern = str;
}
/**
* Set the pattern to use when parsing Date using a script variable attribute.
*
* @param String name of script variable attribute id
*/
public final void setPatternId(String str) {
patternid = str;
}
/**
* Set the date to use (overrides tag body) for formatting
*
* @param Date to use for formatting (could be null)
*/
public final void setDate(Date date) {
this.date = date;
}
/**
* Set the default text if an invalid date or no tag body is given
*
* @param String to use as default text
*/
public final void setDefault(String default_text) {
this.default_text = default_text;
}
/**
* Provides a key to search the page context for in order to get the java.util.Locale to use.
*
* @param String name of locale attribute to use
*/
public void setLocaleRef(String value) {
localeRef = value;
}
/**
* Provides a key to search the page context for in order to get the java.text.DateFormatSymbols to
* use
*
* @param symbolsRef
*/
public void setSymbolsRef(String symbolsRef) {
this.symbolsRef = symbolsRef;
}
} | lgpl-2.1 |
rspavel/spack | var/spack/repos/builtin/packages/braker/package.py | 2727 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import os
import glob
class Braker(Package):
"""BRAKER is a pipeline for unsupervised RNA-Seq-based genome annotation
that combines the advantages of GeneMark-ET and AUGUSTUS"""
homepage = "http://exon.gatech.edu/braker1.html"
url = "https://github.com/Gaius-Augustus/BRAKER/archive/v2.1.4.tar.gz"
list_url = "http://bioinf.uni-greifswald.de/augustus/binaries/old"
version('2.1.4', sha256='d48af5649cc879343046f9ddf180fe2c709b5810e0b78cf314bf298514d31d52')
version('1.11', sha256='cb2d9abe1720ed58753d362eee4af3791007efc617754804882d31f9fe2eab00',
url='http://bioinf.uni-greifswald.de/augustus/binaries/old/BRAKER1_v1.11.tar.gz')
depends_on('perl', type=('build', 'run'))
depends_on('perl-scalar-util-numeric', type=('build', 'run'))
depends_on('perl-parallel-forkmanager', type=('build', 'run'))
depends_on('perl-file-which', type=('build', 'run'))
depends_on('perl-yaml', type=('build', 'run'))
depends_on('perl-hash-merge', type=('build', 'run'))
depends_on('perl-logger-simple', type=('build', 'run'))
depends_on('perl-file-homedir', when='@2.1.4:', type=('build', 'run'))
depends_on('augustus')
depends_on('augustus@3.2.3', when='@:2.1.0')
depends_on('genemark-et')
depends_on('bamtools')
depends_on('samtools')
depends_on('diamond')
def install(self, spec, prefix):
mkdirp(prefix.bin)
mkdirp(prefix.lib)
if self.version < Version('2.1.2'):
install('braker.pl', prefix.bin)
install('filterGenemark.pl', prefix.bin)
install('filterIntronsFindStrand.pl', prefix.bin)
install('helpMod.pm', prefix.lib)
else:
install_tree('docs', prefix.docs)
install_tree('example', prefix.example)
with working_dir('scripts'):
install('helpMod.pm', prefix.lib)
files = glob.iglob('*.pl')
for file in files:
if os.path.isfile(file):
install(file, prefix.bin)
@run_after('install')
def filter_sbang(self):
with working_dir(self.prefix.bin):
pattern = '^#!.*/usr/bin/env perl'
repl = '#!{0}'.format(self.spec['perl'].command.path)
files = glob.iglob("*.pl")
for file in files:
filter_file(pattern, repl, *files, backup=False)
def setup_run_environment(self, env):
env.prepend_path('PERL5LIB', self.prefix.lib)
| lgpl-2.1 |
the-realest-stu/Rustic | src/main/java/rustic/common/world/WorldGenWildberries.java | 2089 | package rustic.common.world;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraftforge.common.BiomeDictionary;
import net.minecraftforge.common.BiomeDictionary.Type;
import rustic.common.Config;
import rustic.common.blocks.ModBlocks;
import rustic.common.blocks.crops.BlockBerryBush;
public class WorldGenWildberries extends WorldGenerator {
public static List<Type> biomeBlacklist = new ArrayList<Type>();
static {
biomeBlacklist.add(Type.COLD);
biomeBlacklist.add(Type.SNOWY);
biomeBlacklist.add(Type.SANDY);
biomeBlacklist.add(Type.SAVANNA);
biomeBlacklist.add(Type.MESA);
biomeBlacklist.add(Type.MUSHROOM);
biomeBlacklist.add(Type.NETHER);
biomeBlacklist.add(Type.END);
biomeBlacklist.add(Type.DEAD);
biomeBlacklist.add(Type.WASTELAND);
}
@Override
public boolean generate(World world, Random rand, BlockPos pos) {
Biome biome = world.getBiome(pos);
for (Type type : biomeBlacklist) {
if (BiomeDictionary.hasType(biome, type)) {
return false;
}
}
boolean ret = false;
for (int i = 0; i < Config.MAX_WILDBERRY_ATTEMPTS; i++) {
int x = pos.getX() + rand.nextInt(7) - rand.nextInt(7);
int z = pos.getZ() + rand.nextInt(7) - rand.nextInt(7);
BlockPos genPos = world.getTopSolidOrLiquidBlock(new BlockPos(x, 0, z));
if (generateBush(world, rand, genPos)) {
ret = true;
}
}
return ret;
}
private boolean generateBush(World world, Random rand, BlockPos pos) {
IBlockState state = world.getBlockState(pos);
if (state.getMaterial().isLiquid()) return false;
if (ModBlocks.WILDBERRY_BUSH.canPlaceBlockAt(world, pos)) {
world.setBlockState(pos, ModBlocks.WILDBERRY_BUSH.getDefaultState().withProperty(BlockBerryBush.BERRIES, rand.nextBoolean()));
return true;
}
return false;
}
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | libraries/libcss/src/main/java/org/pentaho/reporting/libraries/css/parser/stylehandler/font/FontEmphasizeReadHandler.java | 2573 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.reporting.libraries.css.parser.stylehandler.font;
import org.pentaho.reporting.libraries.css.keys.font.FontStyleKeys;
import org.pentaho.reporting.libraries.css.model.StyleKey;
import org.pentaho.reporting.libraries.css.parser.CSSCompoundValueReadHandler;
import org.pentaho.reporting.libraries.css.values.CSSValue;
import org.w3c.css.sac.LexicalUnit;
import java.util.HashMap;
import java.util.Map;
/**
* Creation-Date: 28.11.2005, 17:52:55
*
* @author Thomas Morgner
*/
public class FontEmphasizeReadHandler
implements CSSCompoundValueReadHandler {
private FontEmphasizePositionReadHandler positionReadHandler;
private FontEmphasizeStyleReadHandler styleReadHandler;
public FontEmphasizeReadHandler() {
positionReadHandler = new FontEmphasizePositionReadHandler();
styleReadHandler = new FontEmphasizeStyleReadHandler();
}
/**
* Parses the LexicalUnit and returns a map of (StyleKey, CSSValue) pairs.
*
* @param unit
* @return
*/
public Map createValues( LexicalUnit unit ) {
CSSValue style = styleReadHandler.createValue( null, unit );
if ( style != null ) {
unit = unit.getNextLexicalUnit();
}
CSSValue position;
if ( unit != null ) {
position = positionReadHandler.createValue( null, unit );
} else {
position = null;
}
final Map map = new HashMap();
if ( position != null ) {
map.put( FontStyleKeys.FONT_EMPHASIZE_POSITION, position );
}
if ( style != null ) {
map.put( FontStyleKeys.FONT_EMPHASIZE_STYLE, style );
}
return map;
}
public StyleKey[] getAffectedKeys() {
return new StyleKey[] {
FontStyleKeys.FONT_EMPHASIZE_POSITION,
FontStyleKeys.FONT_EMPHASIZE_STYLE
};
}
}
| lgpl-2.1 |
felixion/flxsmb | src/jcifs/smb/SecurityDescriptor.java | 3340 | /* jcifs smb client library in Java
* Copyright (C) 2005 "Michael B. Allen" <jcifs at samba dot org>
*
* 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
*/
package jcifs.smb;
import java.io.IOException;
public class SecurityDescriptor {
SID owner_user, owner_group;
public int type;
public ACE[] aces;
public SecurityDescriptor() {
}
public SecurityDescriptor(byte[] buffer, int bufferIndex, int len) throws IOException {
this.decode(buffer, bufferIndex, len);
}
public int decode(byte[] buffer, int bufferIndex, int len) throws IOException {
int start = bufferIndex;
bufferIndex++; // revision
bufferIndex++;
type = ServerMessageBlock.readInt2(buffer, bufferIndex);
bufferIndex += 2;
int ownerUOffset = ServerMessageBlock.readInt4(buffer, bufferIndex); // offset to owner sid
bufferIndex += 4;
int ownerGOffset = ServerMessageBlock.readInt4(buffer, bufferIndex); // offset to group sid
bufferIndex += 4;
int saclOffset = ServerMessageBlock.readInt4(buffer, bufferIndex); // offset to sacl
bufferIndex += 4;
int daclOffset = ServerMessageBlock.readInt4(buffer, bufferIndex);
if (ownerUOffset > 0) {
bufferIndex = start + ownerUOffset;
owner_user = new SID(buffer, bufferIndex);
bufferIndex += 28; // ???
}
if (ownerGOffset > 0) {
bufferIndex = start + ownerGOffset;
owner_group = new SID(buffer, bufferIndex);
bufferIndex += 28; // ???
}
bufferIndex = start + daclOffset;
if (daclOffset != 0) {
bufferIndex++; // revision
bufferIndex++;
int size = ServerMessageBlock.readInt2(buffer, bufferIndex);
bufferIndex += 2;
int numAces = ServerMessageBlock.readInt4(buffer, bufferIndex);
bufferIndex += 4;
if (numAces > 4096)
throw new IOException( "Invalid SecurityDescriptor" );
aces = new ACE[numAces];
for (int i = 0; i < numAces; i++) {
aces[i] = new ACE();
bufferIndex += aces[i].decode(buffer, bufferIndex);
}
} else {
aces = null;
}
return bufferIndex - start;
}
public String toString() {
String ret = "SecurityDescriptor:\n";
if (aces != null) {
for (int ai = 0; ai < aces.length; ai++) {
ret += aces[ai].toString() + "\n";
}
} else {
ret += "NULL";
}
return ret;
}
}
| lgpl-2.1 |
dowobeha/joshua-multilingual | src/joshua/decoder/DefaultSymbol.java | 7957 | package joshua.decoder;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.List;
import joshua.util.FileUtility;
/**
* this class implement
* (1) initialize the symbol table
* (2) provide conversion between symbol and integers
*
* How to initialize the Symbol
* Having multiple LM modes complicate the class, we have four LM mode: JAVA_LM, SRILM, Distributed_LM, and NONE_LM. The NONE_LM and JAVA_LM will be treated as same.
*JAVA_LM and NONE_LM: call add_global_symbols(true) to initialize
*SRILM: the SRILM must first be initialized, then call add_global_symbols(false)
*DistributedLM (from decoder): call init_sym_tbl_from_file(true)
*DistributedLM (from LMServer): call init_sym_tbl_from_file(true/false)
*
* @author Zhifei Li, <zhifei.work@gmail.com>
* @version $LastChangedDate: 2008-10-31 08:56:14 -0400 (Fri, 31 Oct 2008) $
*/
/*############# How to initialize the Symbol
* Having multiple LM modes complicate the class, we have four LM mode: JAVA_LM, SRILM, Distributed_LM, and NONE_LM. The NONE_LM and JAVA_LM will be treated as same.
*JAVA_LM and NONE_LM: call add_global_symbols(true) to initialize
*SRILM: the SRILM must first be initialized, then call add_global_symbols(false)
*DistributedLM (from decoder): call init_sym_tbl_from_file(true)
*DistributedLM (from LMServer): call init_sym_tbl_from_file(true/false)
* */
public abstract class DefaultSymbol implements Symbol {
//terminal symbol may get from a tbl file, srilm, or a lm file
//**non-terminal symbol is always from myself, and the integer should always be negative
private HashMap<String,Integer> nonterminal_str_2_num_tbl = new HashMap<String,Integer>();
private HashMap<Integer,String> nonterminal_num_2_str_tbl = new HashMap<Integer,String>();
private int nonterminal_cur_id=-1;//start from -1
protected int lm_start_sym_id = 10000;//1-10000 reserved for special purpose
protected int lm_end_sym_id = 5000001;//max vocab 1000k
public boolean is_reading_from_file = false;
protected abstract String getTerminalWord(int id);
public DefaultSymbol(){
//do nothing here, because we want the sub-class doing specific things
}
final public String getWord(int id) {
if ( isNonterminal(id)) {
return getNonTerminalWord(id);
}else{
return getTerminalWord(id);
}
}
final public int getLMStartID(){
return lm_start_sym_id;
}
final public int getLMEndID(){
return lm_end_sym_id;
}
final public String getNonTerminalWord(int id){
String res = (String)nonterminal_num_2_str_tbl.get(id);
if(res == null){
System.out.println("try to query the string for non exist id, must exit");
System.exit(0);
}
return res;
}
final public String getWords(Integer[] ids){
String res = "";
for(int t=0; t<ids.length; t++){
if(t==0)
res += getWord(ids[t]);
else
res += " " + getWord(ids[t]);
}
return res;
}
final public String getWords(int[] ids){
String res = "";
for(int t=0; t<ids.length; t++){
if(t==0)
res += getWord(ids[t]);
else
res += " " + getWord(ids[t]);
}
return res;
}
final public String getWords(List<Integer> ids){
String res = "";
for(int t=0; t<ids.size(); t++){
if(t==0)
res += getWord(ids.get(t));
else
res += " " + getWord(ids.get(t));
}
return res;
}
final public int[] addTerminalSymbols(String sentence){
String[] sent_wrds = sentence.split("\\s+");
return addTerminalSymbols(sent_wrds);
}
final public int[] addTerminalSymbols(String[] strings){
int[] res =new int[strings.length];
for(int t=0; t<strings.length; t++)
res[t]=addTerminalSymbol(strings[t]);
return res;
}
// ####### following functions used for TM only
final public int addNonTerminalSymbol(String str){
Integer res_id = (Integer)nonterminal_str_2_num_tbl.get(str);
if (null != res_id) { // already have this symbol
if (! isNonterminal(res_id)) {
System.out.println("Error, NONTSym: " + str + "; id: " + res_id);
System.exit(1);
}
return res_id;
} else {
nonterminal_str_2_num_tbl.put(str, nonterminal_cur_id);
nonterminal_num_2_str_tbl.put(nonterminal_cur_id, str);
nonterminal_cur_id--;
//System.out.println("Sym: " + str + "; id: " + negative_id);
return (nonterminal_cur_id+1);
}
}
final public boolean isNonterminal(int id) {
return (id < 0);
}
final public int getEngNonTerminalIndex(int id) {
if (! isNonterminal(id)) {
return -1;
} else {
// TODO: get rid of this expensive interim object
String symbol = getWord(id);
return getEngNonTerminalIndex(symbol);
}
}
final public int getEngNonTerminalIndex(String wrd) {
// Assumes the last character is a digit
// and extracts it, starting from one.
// Assumes the whole prefix is the
// nonterminal-ID portion of the string
return Integer.parseInt( wrd.substring(wrd.length() - 2, wrd.length() - 1) ) - 1;
}
protected void initializeSymTblFromFile(String fname){
is_reading_from_file =true;
//### read file into tbls
HashMap<String, Integer> tbl_str_2_id = new HashMap<String, Integer>();
HashMap<Integer, String> tbl_id_2_str = new HashMap<Integer, String>();
BufferedReader t_reader_sym = FileUtility.getReadFileStream(fname);
String line;
while((line=FileUtility.read_line_lzf(t_reader_sym))!=null){
String[] fds = line.split("\\s+");
if(fds.length!=2){
System.out.println("Warning: read index, bad line: " + line);
continue;
}
String str = fds[0].trim();
int id = new Integer(fds[1]);
String uqniue_str;
if (null != tbl_str_2_id.get(str)) { // it is quite possible that java will treat two stings as the same when other language (e.g., C or perl) treat them differently, due to unprintable symbols
System.out.println("Warning: duplicate string (add fake): " + line);
uqniue_str = str + id;//fake string
//System.exit(1);//TODO
} else {
uqniue_str = str;
}
tbl_str_2_id.put(uqniue_str,id);
//it is guranteed that the strings in tbl_id_2_str are different
if (null != tbl_id_2_str.get(id)) {
System.out.println("Error: duplicate id, have to exit; " + line);
System.exit(1);
} else {
tbl_id_2_str.put(id, uqniue_str);
}
}
FileUtility.close_read_file(t_reader_sym);
/*if (tbl_id_2_str.size() >= lm_end_sym_id - lm_start_sym_id) {
System.out.println("Error: read symbol tbl, tlb is too big");
System.exit(1);
}*/
//#### now add the tbl into srilm/java-tbl
/*int n_added = 0;
int i=0;
while (n_added < tbl_id_2_str.size()) {
String str = (String) tbl_id_2_str.get(i); // it is guaranteed that the strings in tbl_id_2_str are different
int res_id;
if (null != str) {
res_id = addTerminalSymbol(str);
n_added++;
} else { // non-continuous index
System.out.println("Warning: add fake symbol, be alert");
res_id = addTerminalSymbol("lzf"+i);
}
if (res_id != i) {
System.out.println("id supposed: " + i +" != assinged " + res_id + " symbol:" + str);
System.exit(1);
}
i++;
}*/
int n_added=0;
for(int i=lm_start_sym_id; i<lm_end_sym_id; i++){
String str = (String) tbl_id_2_str.get(i);//it is guranteed that the strings in tbl_id_2_str are different
int res_id;
if(str!=null){
res_id = addTerminalSymbol(str);
n_added++;
}else{//non-continous index
System.out.println("Warning: add fake symbol, be alert");
res_id = addTerminalSymbol("lzf"+i);
}
if(res_id!=i){
System.out.println("id supposed: " + i +" != assinged " + res_id + " symbol:" + str);
System.exit(0);
}
if(n_added>=tbl_id_2_str.size())
break;
}
}
}
| lgpl-2.1 |
needle4j/needle4j | src/test/java/org/needle4j/postconstruct/injection/DependentComponent.java | 186 | package org.needle4j.postconstruct.injection;
public class DependentComponent {
private int i;
public void count() {
i++;
}
public int getCounter() {
return i;
}
}
| lgpl-2.1 |
awltech/eclipse-i18ntools | com.worldline.awltech.i18ntools.parent/com.worldline.awltech.i18ntools.wizard.core/src/main/java/com/worldline/awltech/i18ntools/wizard/core/ui/RefactoringWizard.java | 14822 | /**
* I18N Tools
*
* Copyright (C) 2014 Worldline or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* 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.
*
* 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 com.worldline.awltech.i18ntools.wizard.core.ui;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.SelectionDialog;
import com.worldline.awltech.i18ntools.wizard.core.Activator;
import com.worldline.awltech.i18ntools.wizard.core.RefactoringWizardMessages;
import com.worldline.awltech.i18ntools.wizard.core.ui.validation.FieldTextValidator;
import com.worldline.awltech.i18ntools.wizard.core.ui.validation.PackageTextValidator;
import com.worldline.awltech.i18ntools.wizard.core.ui.validation.SWTDialogValidator;
import com.worldline.awltech.i18ntools.wizard.core.ui.validation.TypeTextValidator;
/**
* Refactoring graphical wizard implementation.
*
* @author mvanbesien
*
*/
public class RefactoringWizard {
private static final String IMAGE_PATH = "icons/i18ntools.png";
private static final int LABEL_WIDTH = 150;
private static final int TEXT_WIDTH = 400;
private Shell shell;
private boolean keepOpen = true;
private boolean isOK = false;
private String literalPrefix = null;
private String resourceBundleName = null;
private String packageName = null;
private final IJavaProject javaProject;
private Display display;
private String javaSourceFolder;
private String resourceFolder;
private boolean prefixMessageByKey;
public boolean open() {
this.display = Display.getCurrent() != null ? Display.getCurrent() : Display.getDefault();
this.display.syncExec(new Runnable() {
@Override
public void run() {
RefactoringWizard.this.internalOpen();
}
});
return this.isOK;
}
private void internalOpen() {
final RefactoringWizardConfiguration configuration = new RefactoringWizardConfiguration(
this.javaProject.getProject());
// Create the background of the dialog
this.shell = new Shell(this.display, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM | SWT.RESIZE);
this.shell.setLayout(new FormLayout());
this.shell.setText(RefactoringWizardMessages.WIZARD_TITLE.value());
this.shell.setImage(Activator.getDefault().getImage(RefactoringWizard.IMAGE_PATH));
// Message group
final Group messageGroup = new Group(this.shell, SWT.NONE);
messageGroup.setText(RefactoringWizardMessages.GROUP_MESSAGE_TITLE.value());
messageGroup.setLayout(new FormLayout());
FormDataBuilder.on(messageGroup).top().horizontal();
final Label resourceBundlePackageLabel = new Label(messageGroup, SWT.NONE);
resourceBundlePackageLabel.setText(RefactoringWizardMessages.WIZARD_LABEL_ENUM_PACKAGE.value());
resourceBundlePackageLabel.setToolTipText(RefactoringWizardMessages.WIZARD_TOOLTIP_ENUM_PACKAGE.value());
FormDataBuilder.on(resourceBundlePackageLabel).top().left().width(RefactoringWizard.LABEL_WIDTH);
final Button resourceBundlePackageButton = new Button(messageGroup, SWT.PUSH);
resourceBundlePackageButton.setText(RefactoringWizardMessages.WIZARD_BUTTON_SELECT.value());
FormDataBuilder.on(resourceBundlePackageButton).top().right().width(80).height(25);
final Text resourceBundlePackageText = new Text(messageGroup, SWT.BORDER);
resourceBundlePackageText.setText(configuration.getResourceBundlePackage());
FormDataBuilder.on(resourceBundlePackageText).top().right(resourceBundlePackageButton)
.left(resourceBundlePackageLabel);
resourceBundlePackageButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final IPackageFragment packageFragment = this.openAndGetPackage();
if (packageFragment != null) {
resourceBundlePackageText.setText(packageFragment.getElementName());
resourceBundlePackageText.update();
}
}
private IPackageFragment openAndGetPackage() {
try {
final SelectionDialog createPackageDialog = JavaUI.createPackageDialog(
RefactoringWizard.this.shell, RefactoringWizard.this.javaProject,
IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS);
if (createPackageDialog.open() == Window.OK) {
final Object[] result = createPackageDialog.getResult();
if (result.length > 0 && result[0] instanceof IPackageFragment) {
return (IPackageFragment) createPackageDialog.getResult()[0];
}
}
} catch (final JavaModelException e) {
Activator
.getDefault()
.getLog()
.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
RefactoringWizardMessages.ERROR_SEEK_PACKAGE.value(), e));
}
return null;
}
});
final Label resourceBundleLabel = new Label(messageGroup, SWT.NONE);
resourceBundleLabel.setText(RefactoringWizardMessages.WIZARD_LABEL_ENUM_NAME.value());
resourceBundleLabel.setToolTipText(RefactoringWizardMessages.WIZARD_TOOLTIP_ENUM_NAME.value());
FormDataBuilder.on(resourceBundleLabel).top(resourceBundlePackageText).left()
.width(RefactoringWizard.LABEL_WIDTH);
final Text resourceBundleText = new Text(messageGroup, SWT.BORDER);
resourceBundleText.setText(configuration.getResourceBundleName());
FormDataBuilder.on(resourceBundleText).top(resourceBundlePackageText).right().left(resourceBundleLabel)
.width(RefactoringWizard.TEXT_WIDTH);
final Label enumPrefixLabel = new Label(messageGroup, SWT.NONE);
enumPrefixLabel.setText(RefactoringWizardMessages.WIZARD_LABEL_ENUM_LITERAL.value());
enumPrefixLabel.setToolTipText(RefactoringWizardMessages.WIZARD_TOOLTIP_ENUM_LITERAL.value());
FormDataBuilder.on(enumPrefixLabel).top(resourceBundleText).left().width(RefactoringWizard.LABEL_WIDTH);
final Text enumPrefixText = new Text(messageGroup, SWT.BORDER);
enumPrefixText.setText(configuration.getLastLiteralPrefix());
FormDataBuilder.on(enumPrefixText).top(resourceBundleText).left(enumPrefixLabel)
.width(RefactoringWizard.TEXT_WIDTH);
final Button prefixMessageByKeyButton = new Button(messageGroup, SWT.CHECK);
prefixMessageByKeyButton.setText("Prefix message by its key");
prefixMessageByKeyButton.setToolTipText("When enabled, the message in the Resource Bundle properties file will be prefixed by the message identifier.");
FormDataBuilder.on(prefixMessageByKeyButton).left().right().top(enumPrefixText).bottom();
prefixMessageByKeyButton.setSelection(configuration.getPrefixMessageByKey());
// Advanced Group
final Group advancedGroup = new Group(this.shell, SWT.NONE);
advancedGroup.setText(RefactoringWizardMessages.GROUP_ADVANCED_TITLE.value());
advancedGroup.setLayout(new FormLayout());
FormDataBuilder.on(advancedGroup).top(messageGroup).horizontal();
final Label sourceFolderLabel = new Label(advancedGroup, SWT.NONE);
sourceFolderLabel.setText(RefactoringWizardMessages.LABEL_SOURCE_FOLDER.value());
sourceFolderLabel.setToolTipText(RefactoringWizardMessages.TOOLTIP_SOURCE_FOLDER.value());
FormDataBuilder.on(sourceFolderLabel).left().top().width(RefactoringWizard.LABEL_WIDTH);
final Text sourceFolderText = new Text(advancedGroup, SWT.BORDER);
sourceFolderText.setText(configuration.getJavaSourceFolder());
FormDataBuilder.on(sourceFolderText).top().left(sourceFolderLabel).right().width(RefactoringWizard.TEXT_WIDTH);
final Label resourceFolderLabel = new Label(advancedGroup, SWT.NONE);
resourceFolderLabel.setText(RefactoringWizardMessages.LABEL_RESOURCE_FOLDER.value());
resourceFolderLabel.setToolTipText(RefactoringWizardMessages.TOOLTIP_RESOURCE_FOLDER.value());
FormDataBuilder.on(resourceFolderLabel).left().top(sourceFolderText).width(RefactoringWizard.LABEL_WIDTH);
final Text resourceFolderText = new Text(advancedGroup, SWT.BORDER);
resourceFolderText.setText(configuration.getResourceSourceFolder());
FormDataBuilder.on(resourceFolderText).left(resourceFolderLabel).top(sourceFolderText)
.width(RefactoringWizard.TEXT_WIDTH).right().bottom();
final Label errorMessage = new Label(this.shell, SWT.NONE);
FormDataBuilder.on(errorMessage).top(advancedGroup).left().right();
final Button okButton = new Button(this.shell, SWT.PUSH);
okButton.setText(RefactoringWizardMessages.WIZARD_BUTTON_OK.value());
FormDataBuilder.on(okButton).bottom().right().width(80).top(errorMessage).height(25);
okButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final String enumPrefixValue = enumPrefixText.getText().trim();
RefactoringWizard.this.literalPrefix = "RESOURCE_BUNDLE".equals(enumPrefixValue) ? "RESOURCE__BUNDLE"
: enumPrefixValue.replace(" ", "_");
RefactoringWizard.this.resourceBundleName = resourceBundleText.getText().trim();
RefactoringWizard.this.packageName = resourceBundlePackageText.getText().trim();
RefactoringWizard.this.javaSourceFolder = sourceFolderText.getText().trim();
RefactoringWizard.this.resourceFolder = resourceFolderText.getText().trim();
RefactoringWizard.this.prefixMessageByKey = prefixMessageByKeyButton.getSelection();
configuration.setLastLiteralPrefix(RefactoringWizard.this.literalPrefix);
configuration.setResourceBundleName(RefactoringWizard.this.resourceBundleName);
configuration.setResourceBundlePackage(RefactoringWizard.this.packageName);
configuration.setJavaSourceFolder(RefactoringWizard.this.javaSourceFolder);
configuration.setResourceSourceFolder(RefactoringWizard.this.resourceFolder);
configuration.setPrefixMessageByKey(RefactoringWizard.this.prefixMessageByKey);
RefactoringWizard.this.isOK = true;
RefactoringWizard.this.keepOpen = false;
}
});
final Button cancelButton = new Button(this.shell, SWT.PUSH);
cancelButton.setText(RefactoringWizardMessages.WIZARD_BUTTON_CANCEL.value());
FormDataBuilder.on(cancelButton).bottom().right(okButton).top(errorMessage).width(80).height(25);
cancelButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
RefactoringWizard.this.keepOpen = false;
}
});
final Label versionLabel = new Label(this.shell, SWT.NONE);
versionLabel.setForeground(this.shell.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
versionLabel.setText(RefactoringWizardMessages.LABEL_VERSION.value(Activator.getDefault().getVersion()));
FormDataBuilder.on(versionLabel).top(errorMessage).left().right(cancelButton);
this.shell.addListener(SWT.Close, new Listener() {
@Override
public void handleEvent(final Event event) {
RefactoringWizard.this.keepOpen = false;
}
});
this.shell.addListener(SWT.Traverse, new Listener() {
@Override
public void handleEvent(final Event event) {
if (event.detail == SWT.TRAVERSE_ESCAPE) {
event.doit = false;
RefactoringWizard.this.keepOpen = false;
} else if (event.detail == SWT.TRAVERSE_RETURN) {
event.doit = false;
RefactoringWizard.this.literalPrefix = enumPrefixText.getText().trim();
RefactoringWizard.this.resourceBundleName = resourceBundleText.getText().trim();
RefactoringWizard.this.packageName = resourceBundlePackageText.getText().trim();
RefactoringWizard.this.javaSourceFolder = sourceFolderText.getText().trim();
RefactoringWizard.this.resourceFolder = resourceFolderText.getText().trim();
RefactoringWizard.this.prefixMessageByKey = prefixMessageByKeyButton.getSelection();
configuration.setLastLiteralPrefix(RefactoringWizard.this.literalPrefix);
configuration.setResourceBundleName(RefactoringWizard.this.resourceBundleName);
configuration.setResourceBundlePackage(RefactoringWizard.this.packageName);
configuration.setJavaSourceFolder(RefactoringWizard.this.javaSourceFolder);
configuration.setResourceSourceFolder(RefactoringWizard.this.resourceFolder);
configuration.setPrefixMessageByKey(RefactoringWizard.this.prefixMessageByKey);
RefactoringWizard.this.isOK = true;
RefactoringWizard.this.keepOpen = false;
}
}
});
new SWTDialogValidator(errorMessage, okButton).on(enumPrefixText, new FieldTextValidator())
.on(resourceBundlePackageText, new PackageTextValidator())
.on(resourceBundleText, new TypeTextValidator());
enumPrefixText.setFocus();
this.shell.pack();
Rectangle bounds;
try {
bounds = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getBounds();
} catch (final NullPointerException npe) {
bounds = this.shell.getDisplay().getPrimaryMonitor().getBounds();
}
final Rectangle rect = this.shell.getBounds();
this.shell
.setLocation(bounds.x + (bounds.width - rect.width) / 2, bounds.y + (bounds.height - rect.height) / 2);
this.shell.open();
while (this.keepOpen && !this.shell.isDisposed()) {
if (!this.shell.getDisplay().readAndDispatch()) {
this.shell.getDisplay().sleep();
}
}
this.shell.dispose();
}
public RefactoringWizard(final IJavaProject javaProject) {
this.javaProject = javaProject;
}
public String getLiteralPrefix() {
return this.literalPrefix;
}
public String getResourceBundleName() {
return this.resourceBundleName;
}
public String getResourceBundlePackage() {
return this.packageName;
}
public boolean getPrefixMessageByKey() {
return this.prefixMessageByKey;
}
}
| lgpl-2.1 |
thobens/PHPlug | plugins/phplug_ui_processor/templates_c/%%15^150^1508C8C8%%container.tpl.php | 286 | <?php /* Smarty version 2.6.22, created on 2012-08-07 01:25:59
compiled from C:/xampp/htdocs/trapadoo/PHPlug/plugins/phplug_ui/templates/container.tpl */ ?>
<div class="Container" id="<?php echo $this->_tpl_vars['id']; ?>
">
<?php echo $this->_tpl_vars['content']; ?>
</div> | lgpl-2.1 |
SensorsINI/jaer | src/ch/unizh/ini/jaer/projects/apsdvsfusion/mathexpression/FunctionETNode.java | 2552 | /**
*
*/
package ch.unizh.ini.jaer.projects.apsdvsfusion.mathexpression;
import java.util.HashMap;
/**
* @author Dennis
*
*/
public abstract class FunctionETNode implements ExpressionTreeNode {
ExpressionTreeNode[] argumentNodes;
double[] results;
abstract static class SimpleFunctionETNodeCreator implements FunctionETNodeCreator {
private int arguments;
private int priority;
private String symbol;
public SimpleFunctionETNodeCreator(String symbol, int priority, int arguments) {
this.priority = priority;
this.symbol = symbol;
this.arguments = arguments;
}
@Override
public FunctionETNode createExpressionTreeNode(
ExpressionTreeNode[] arguments)
throws IllegalExpressionException {
if (arguments.length > this.arguments)
throw new IllegalExpressionException("Could not evaluate Expression, too many arguments for function "+symbol+"!");
else if (arguments.length < this.arguments)
throw new IllegalExpressionException("Could not evaluate Expression, not enought arguments for function "+symbol+"!");
return new FunctionETNode(arguments) {
protected double compute(double[] arguments) {
return SimpleFunctionETNodeCreator.this.compute(arguments);
}
};
}
public int getNumberOfArguments() {
return arguments;
}
public int priority() {
return this.priority;
}
public String symbol() {
return this.symbol;
}
protected abstract double compute(double[] arguments);
}
/**
*
*/
public FunctionETNode(ExpressionTreeNode[] argumentNodes) {
this.argumentNodes = argumentNodes;
this.results = new double[argumentNodes.length];
}
public FunctionETNode(ExpressionTreeNode argumentA, ExpressionTreeNode argumentB, ExpressionTreeNode argumentC) {
this(new ExpressionTreeNode[] { argumentA, argumentB, argumentC });
}
public FunctionETNode(ExpressionTreeNode argumentA, ExpressionTreeNode argumentB) {
this(new ExpressionTreeNode[] { argumentA, argumentB});
}
public FunctionETNode(ExpressionTreeNode argumentA) {
this(new ExpressionTreeNode[] { argumentA });
}
public FunctionETNode() {
this(new ExpressionTreeNode[] { });
}
/* (non-Javadoc)
* @see ch.unizh.ini.jaer.projects.apsdvsfusion.mathexpression.ExpressionTreeNode#evaluate(java.util.HashMap)
*/
@Override
public double evaluate(HashMap<String, Double> values) {
for (int i = 0; i < argumentNodes.length; i++) {
results[i] = argumentNodes[i].evaluate(values);
}
return compute(results);
}
abstract protected double compute(double[] arguments);
}
| lgpl-2.1 |
amolenaar/gaphor | gaphor/diagram/text.py | 7850 | """Support classes for dealing with text."""
from __future__ import annotations
from gaphas.canvas import instant_cairo_context
from gaphas.painter.freehand import FreeHandCairoContext
from gi.repository import GLib, Pango, PangoCairo
from gaphor.core.styling import FontStyle, FontWeight, Style, TextAlign, TextDecoration
class Layout:
def __init__(
self,
text: str = "",
font: Style | None = None,
text_align: TextAlign = TextAlign.CENTER,
default_size: tuple[int, int] = (0, 0),
):
self.layout = PangoCairo.create_layout(instant_cairo_context())
self.underline = False
self.font_id: tuple[
str, float | str, FontWeight | None, FontStyle | None
] | None = None
self.text = ""
self.width = -1
self.default_size = default_size
if font:
self.set_font(font)
if text:
self.set_text(text)
self.set_alignment(text_align)
def set(self, text=None, font=None, width=None, text_align=None):
# Since text expressions can return False, we should also accommodate for that
if text not in (None, False):
self.set_text(text)
if font:
self.set_font(font)
if width is not None:
self.set_width(width)
if text_align:
self.set_alignment(text_align)
def set_font(self, font: Style) -> None:
font_family = font.get("font-family")
font_size = font.get("font-size")
font_weight = font.get("font-weight")
font_style = font.get("font-style")
assert font_family, "Font family should be set"
assert font_size, "Font size should be set"
font_id = (font_family, font_size, font_weight, font_style)
if font_id == self.font_id:
return
self.font_id = font_id
fd = Pango.FontDescription.new()
fd.set_family(font_family)
fd.set_absolute_size(font_size * Pango.SCALE)
if font_weight:
assert isinstance(font_weight, FontWeight)
fd.set_weight(getattr(Pango.Weight, font_weight.name))
if font_style:
assert isinstance(font_style, FontStyle)
fd.set_style(getattr(Pango.Style, font_style.name))
self.layout.set_font_description(fd)
underline = (
font.get("text-decoration", TextDecoration.NONE) == TextDecoration.UNDERLINE
)
if self.underline != underline:
self.underline = underline
self.update_text()
def set_text(self, text: str) -> None:
if text != self.text:
self.text = text
self.update_text()
def update_text(self) -> None:
if self.underline:
# TODO: can this be done via Pango attributes instead?
self.layout.set_markup(
f"<u>{GLib.markup_escape_text(self.text)}</u>", length=-1
)
else:
self.layout.set_text(self.text, length=-1)
def set_width(self, width: int) -> None:
self.width = width
if width == -1:
self.layout.set_width(-1)
else:
self.layout.set_width(int(width * Pango.SCALE))
def set_alignment(self, text_align: TextAlign) -> None:
self.layout.set_alignment(getattr(Pango.Alignment, text_align.name))
def size(self) -> tuple[int, int]:
if not self.text:
return self.default_size
self.set_width(self.width)
return self.layout.get_pixel_size() # type: ignore[no-any-return]
def show_layout(self, cr, width=None, default_size=None):
layout = self.layout
if not self.text:
return default_size or self.default_size
if width is not None:
layout.set_width(int(width * Pango.SCALE))
if isinstance(cr, FreeHandCairoContext):
PangoCairo.show_layout(cr.cr, layout)
else:
PangoCairo.show_layout(cr, layout)
def text_point_at_line(points, size, text_align):
"""Provide a position (x, y) to draw a text close to a line.
Parameters:
- points: the line points, a list of (x, y) points
- size: size of the text, a (width, height) tuple
- text_align: alignment to the line: left, beginning of the line, center, middle and right: end of the line
"""
if text_align == TextAlign.LEFT:
p0 = points[0]
p1 = points[1]
x, y = _text_point_at_line_end(size, p0, p1)
elif text_align == TextAlign.CENTER:
p0, p1 = middle_segment(points)
x, y = _text_point_at_line_center(size, p0, p1)
elif text_align == TextAlign.RIGHT:
p0 = points[-1]
p1 = points[-2]
x, y = _text_point_at_line_end(size, p0, p1)
return x, y
def middle_segment(points):
"""Get middle line segment."""
m = len(points) // 2
assert m >= 1 and m < len(points)
return points[m - 1], points[m]
def _text_point_at_line_end(size, p1, p2):
"""Calculate position of the text relative to a line defined by points p1
and p2.
Parameters:
- size: text size, a (width, height) tuple
- p1: beginning of line segment
- p2: end of line segment
"""
ofs = 5
dx = float(p2[0]) - float(p1[0])
dy = float(p2[1]) - float(p1[1])
name_w, name_h = size
if dy == 0:
rc = 1000.0 # quite a lot...
else:
rc = dx / dy
abs_rc = abs(rc)
h = dx > 0 # right side of the box
v = dy > 0 # bottom side
if abs_rc > 6:
# horizontal line
if h:
name_dx = ofs
name_dy = -ofs - name_h
else:
name_dx = -ofs - name_w
name_dy = -ofs - name_h
elif 0 <= abs_rc <= 0.2:
# vertical line
if v:
name_dx = -ofs - name_w
name_dy = ofs
else:
name_dx = -ofs - name_w
name_dy = -ofs - name_h
else:
# Should both items be placed on the same side of the line?
r = abs_rc < 1.0
# Find out alignment of text (depends on the direction of the line)
align_left = h ^ r
align_bottom = v ^ r
if align_left:
name_dx = ofs
else:
name_dx = -ofs - name_w
if align_bottom:
name_dy = -ofs - name_h
else:
name_dy = ofs
return p1[0] + name_dx, p1[1] + name_dy
# hint tuples to move text depending on quadrant
WIDTH_HINT = (-1, -1, 0)
PADDING_HINT = (1, 1, -1)
EPSILON = 1e-6
def _text_point_at_line_center(size, p1, p2):
"""Calculate position of the text relative to a line defined by points p1
and p2.
Parameters:
- size: text size, a (width, height) tuple
- p1: beginning of line
- p2: end of line
"""
x0 = (p1[0] + p2[0]) / 2.0
y0 = (p1[1] + p2[1]) / 2.0
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
ofs = 3
if abs(dx) < EPSILON:
d1 = -1.0
d2 = 1.0
elif abs(dy) < EPSILON:
d1 = 0.0
d2 = 0.0
else:
d1 = dy / dx
d2 = abs(d1)
width, height = size
# move to center and move by delta depending on line angle
if d2 < 0.5774: # <0, 30>, <150, 180>, <-180, -150>, <-30, 0>
# horizontal mode
w2 = width / 2.0
hint = w2 * d2
x = x0 - w2
y = y0 + hint + ofs
else:
# much better in case of vertical lines
# determine quadrant, we are interested in 1 or 3 and 2 or 4
# see hint tuples below
h2 = height / 2.0
q = (d1 > 0) - (d1 < 0)
hint = 0 if abs(dx) < EPSILON else h2 / d2
x = x0 - hint + width * WIDTH_HINT[q]
x = x0 - (ofs + hint) * PADDING_HINT[q] + width * WIDTH_HINT[q]
y = y0 - h2
return x, y
| lgpl-2.1 |
roystgnr/libmesh | src/base/sibling_coupling.C | 1840 | // The libMesh Finite Element Library.
// Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local Includes
#include "libmesh/sibling_coupling.h"
#include "libmesh/elem.h"
#include "libmesh/remote_elem.h"
#include "libmesh/libmesh_logging.h"
namespace libMesh
{
void SiblingCoupling::operator()
(const MeshBase::const_element_iterator & range_begin,
const MeshBase::const_element_iterator & range_end,
processor_id_type p,
map_type & coupled_elements)
{
LOG_SCOPE("operator()", "SiblingCoupling");
libmesh_assert(_mesh);
for (const auto & elem : as_range(range_begin, range_end))
{
std::vector<const Elem *> active_siblings;
libmesh_assert(_mesh->query_elem_ptr(elem->id()) == elem);
const Elem * parent = elem->parent();
if (!parent)
continue;
#ifdef LIBMESH_ENABLE_AMR
parent->active_family_tree(active_siblings);
#endif
for (const Elem * sibling : active_siblings)
if (sibling->processor_id() != p)
coupled_elements.emplace(sibling, _dof_coupling);
}
}
} // namespace libMesh
| lgpl-2.1 |
alkacon/opencms-core | src/org/opencms/file/types/CmsResourceTypeUnknownFile.java | 4465 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH & Co. KG, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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
*/
package org.opencms.file.types;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.loader.CmsDumpLoader;
import org.opencms.main.OpenCms;
/**
* Resource type descriptor for unknown file types.<p>
*
* This will be used for file corpses when the resource type is not configured.<p>
*
* The most common use case is when deleting a module with the resource type definition,
* but not the content that uses that resource type definition.<p>
*
* @since 7.0.0
*/
public class CmsResourceTypeUnknownFile extends A_CmsResourceType {
/** The type id of this resource type. */
public static final int RESOURCE_TYPE_ID = -1;
/** The name of this resource type. */
public static final String RESOURCE_TYPE_NAME = "unknown_file";
/** Indicates that the static configuration of the resource type has been frozen. */
private static boolean m_staticFrozen;
/** The static type id of this resource type. */
private static int m_staticTypeId;
/** The serial version id. */
private static final long serialVersionUID = -2985191622939935673L;
/**
* Default constructor, used to initialize member variables.<p>
*/
public CmsResourceTypeUnknownFile() {
super();
m_typeId = RESOURCE_TYPE_ID;
m_typeName = RESOURCE_TYPE_NAME;
}
/**
* Returns the static type id of this (default) resource type.<p>
*
* @return the static type id of this (default) resource type
*/
public static int getStaticTypeId() {
return m_staticTypeId;
}
/**
* Returns the static type name of this (default) resource type.<p>
*
* @return the static type name of this (default) resource type
*/
public static String getStaticTypeName() {
return RESOURCE_TYPE_NAME;
}
/**
* @see org.opencms.file.types.I_CmsResourceType#getLoaderId()
*/
@Override
public int getLoaderId() {
return CmsDumpLoader.RESOURCE_LOADER_ID;
}
/**
* @see org.opencms.file.types.A_CmsResourceType#initConfiguration(java.lang.String, java.lang.String, String)
*/
@Override
public void initConfiguration(String name, String id, String className) throws CmsConfigurationException {
if ((OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) && m_staticFrozen) {
// configuration already frozen
throw new CmsConfigurationException(
Messages.get().container(
Messages.ERR_CONFIG_FROZEN_3,
this.getClass().getName(),
getStaticTypeName(),
new Integer(getStaticTypeId())));
}
if (!RESOURCE_TYPE_NAME.equals(name)) {
// default resource type MUST have default name
throw new CmsConfigurationException(
Messages.get().container(
Messages.ERR_INVALID_RESTYPE_CONFIG_NAME_3,
this.getClass().getName(),
RESOURCE_TYPE_NAME,
name));
}
// freeze the configuration
m_staticFrozen = true;
super.initConfiguration(RESOURCE_TYPE_NAME, id, className);
// set static members with values from the configuration
m_staticTypeId = m_typeId;
}
} | lgpl-2.1 |
hyyh619/OpenSceneGraph-3.4.0 | src/osgWrappers/deprecated-dotosg/osgParticle/IO_FluidProgram.cpp | 2350 |
#include <osgParticle/FluidProgram>
#include <osgParticle/Operator>
#include <iostream>
#include <osg/Vec3>
#include <osg/io_utils>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
bool FluidProgram_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool FluidProgram_writeLocalData(const osg::Object &obj, osgDB::Output &fw);
REGISTER_DOTOSGWRAPPER(FluidProgram_Proxy)
(
new osgParticle::FluidProgram,
"FluidProgram",
"Object Node ParticleProcessor osgParticle::Program FluidProgram",
FluidProgram_readLocalData,
FluidProgram_writeLocalData
);
bool FluidProgram_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osgParticle::FluidProgram &myobj = static_cast<osgParticle::FluidProgram&>(obj);
bool itAdvanced = false;
osg::Vec3 vec;
float f;
if (fr[0].matchWord("acceleration"))
{
if (fr[1].getFloat(vec.x()) && fr[2].getFloat(vec.y()) && fr[3].getFloat(vec.z()))
{
myobj.setAcceleration(vec);
fr += 4;
itAdvanced = true;
}
}
if (fr[0].matchWord("viscosity"))
{
if (fr[1].getFloat(f))
{
myobj.setFluidViscosity(f);
fr += 2;
itAdvanced = true;
}
}
if (fr[0].matchWord("density"))
{
if (fr[1].getFloat(f))
{
myobj.setFluidDensity(f);
fr += 2;
itAdvanced = true;
}
}
if (fr[0].matchWord("wind"))
{
if (fr[1].getFloat(vec.x()) && fr[2].getFloat(vec.y()) && fr[3].getFloat(vec.z()))
{
myobj.setWind(vec);
fr += 4;
itAdvanced = true;
}
}
return itAdvanced;
}
bool FluidProgram_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osgParticle::FluidProgram &myobj = static_cast<const osgParticle::FluidProgram&>(obj);
osg::Vec3 vec;
float f;
vec = myobj.getAcceleration();
fw.indent() << "acceleration " << vec << std::endl;
f = myobj.getFluidViscosity();
fw.indent() << "viscosity " << f << std::endl;
f = myobj.getFluidDensity();
fw.indent() << "density " << f << std::endl;
vec = myobj.getWind();
fw.indent() << "wind " << vec << std::endl;
return true;
} | lgpl-2.1 |
esig/dss | specs-validation-report/src/main/java/eu/europa/esig/validationreport/enums/ObjectType.java | 1989 | /**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package eu.europa.esig.validationreport.enums;
import eu.europa.esig.dss.enumerations.UriBasedEnum;
/**
* Defines object types
*/
public enum ObjectType implements UriBasedEnum {
/** Certificate */
CERTIFICATE("urn:etsi:019102:validationObject:certificate"),
/** CRL */
CRL("urn:etsi:019102:validationObject:CRL"),
/** OCSP response */
OCSP_RESPONSE("urn:etsi:019102:validationObject:OCSPResponse"),
/** TimeStamp */
TIMESTAMP("urn:etsi:019102:validationObject:timestamp"),
/** Evidence record */
EVIDENCE_RECORD("urn:etsi:019102:validationObject:evidencerecord"),
/** Public Key */
PUBLIC_KEY("urn:etsi:019102:validationObject:publicKey"),
/** Signed data */
SIGNED_DATA("urn:etsi:019102:validationObject:signedData"),
/** Other */
OTHER("urn:etsi:019102:validationObject:other");
/** VR URI of the object type */
private final String uri;
/**
* Default constructor
*
* @param uri {@link String}
*/
ObjectType(String uri) {
this.uri = uri;
}
@Override
public String getUri() {
return uri;
}
}
| lgpl-2.1 |
aldocuevas/test | pos/source_code/src/com/boutique/view/FrmHistorialCliente.java | 4946 | package com.boutique.view;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import com.boutique.engine.impl.AppInstance;
import com.boutique.engine.impl.HistorialClienteEngine;
public class FrmHistorialCliente
extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
BorderLayout borderLayout1 = new BorderLayout();
PnlDatosVenta pnlDatosVenta1 = new PnlDatosVenta();
public PnlHistorialCliente pnlHistorialCliente1 = new PnlHistorialCliente(pnlDatosVenta1);
HistorialClienteEngine engine = new HistorialClienteEngine();
FrmBuscarCliente frmBuscarCliente = new FrmBuscarCliente(false);
JPanel jPanel1 = new JPanel();
JButton cmdSalir = new JButton();
JButton cmdBuscarOtroCliente = new JButton();
public FrmHistorialCliente() {
try {
jbInit();
}
catch (Exception exception) {
exception.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setCursor(com.boutique.engine.impl.AppInstance.waitCursor);
setTitle("HISTORIAL DEL CLIENTE");
getContentPane().setLayout(borderLayout1);
pnlHistorialCliente1.engine = engine;
pnlHistorialCliente1.setPreferredSize(new Dimension(400, 250));
cmdBuscarOtroCliente.addActionListener(new
FrmHistorialCliente_cmdBuscarOtroCliente_actionAdapter(this));
cmdSalir.addActionListener(new FrmHistorialCliente_cmdSalir_actionAdapter(this));
this.addWindowListener(new FrmHistorialCliente_this_windowAdapter(this));
this.getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
jPanel1.add(cmdBuscarOtroCliente);
jPanel1.add(cmdSalir);
cmdBuscarOtroCliente.setText("OTRO CLIENTE");
cmdSalir.setText("SALIR");
frmBuscarCliente.setModal(true);
frmBuscarCliente.setSize(900, 600);
frmBuscarCliente.setLocationRelativeTo(this);
this.getContentPane().add(pnlDatosVenta1, java.awt.BorderLayout.CENTER);
this.getContentPane().add(pnlHistorialCliente1, java.awt.BorderLayout.NORTH);
this.setCursor(com.boutique.engine.impl.AppInstance.defCursor);
}
public void cmdBuscarOtroCliente_actionPerformed(ActionEvent e) {
this.setCursor(AppInstance.waitCursor);
frmBuscarCliente.setVisible(true);
engine.cliente = frmBuscarCliente.cliente;
if (engine.cliente != null) {
pnlHistorialCliente1.setHistorialCliente();
}
else {
JOptionPane.showMessageDialog(this, "Debes seleccionar un cliente",
com.boutique.engine.impl.AppInstance.nombreNegocio,
JOptionPane.WARNING_MESSAGE);
}
this.setCursor(AppInstance.defCursor);
}
public void cmdSalir_actionPerformed(ActionEvent e) {
this.setVisible(false);
}
public void this_windowOpened(WindowEvent e) {
int i;
while (frmBuscarCliente.cliente == null) {
frmBuscarCliente.setVisible(true);
if (frmBuscarCliente.cliente == null) {
i = JOptionPane.showConfirmDialog(this,
"No has elegido un cliente, ¿Deseas salir de la opción?",
com.boutique.engine.impl.AppInstance.nombreNegocio,
JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION) {
this.setVisible(false);
return;
}
}
}
this.setCursor(com.boutique.engine.impl.AppInstance.waitCursor);
engine.cliente = frmBuscarCliente.cliente;
if (engine.cliente != null) {
pnlHistorialCliente1.setHistorialCliente();
}
this.setCursor(com.boutique.engine.impl.AppInstance.defCursor);
}
}
class FrmHistorialCliente_this_windowAdapter
extends WindowAdapter {
private FrmHistorialCliente adaptee;
FrmHistorialCliente_this_windowAdapter(FrmHistorialCliente adaptee) {
this.adaptee = adaptee;
}
public void windowOpened(WindowEvent e) {
adaptee.this_windowOpened(e);
}
}
class FrmHistorialCliente_cmdSalir_actionAdapter
implements ActionListener {
private FrmHistorialCliente adaptee;
FrmHistorialCliente_cmdSalir_actionAdapter(FrmHistorialCliente adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.cmdSalir_actionPerformed(e);
}
}
class FrmHistorialCliente_cmdBuscarOtroCliente_actionAdapter
implements ActionListener {
private FrmHistorialCliente adaptee;
FrmHistorialCliente_cmdBuscarOtroCliente_actionAdapter(FrmHistorialCliente adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.cmdBuscarOtroCliente_actionPerformed(e);
}
}
| lgpl-2.1 |
FedoraScientific/salome-smesh | src/Tools/smesh_plugins.py | 2463 | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2011-2014 EDF R&D
#
# 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
#
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
# Author : Guillaume Boulant (EDF)
#
import salome_pluginsmanager
from spadderPlugin import runSpadderPlugin
from meshcut_plugin import MeshCut
from yamsplug_plugin import YamsLct
from MGCleanerplug_plugin import MGCleanerLct
from blocFissure.ihm.fissureCoude_plugin import fissureCoudeDlg
salome_pluginsmanager.AddFunction('PADDER mesher',
'Create a mesh with PADDER',
runSpadderPlugin)
salome_pluginsmanager.AddFunction('MeshCut',
'Cut a tetrahedron mesh by a plane',
MeshCut)
salome_pluginsmanager.AddFunction('ReMesh with MGSurfOpt ( formerly Yams )',
'Run Yams',
YamsLct)
salome_pluginsmanager.AddFunction('ReMesh with MGCleaner',
'Run MGCleaner',
MGCleanerLct)
salome_pluginsmanager.AddFunction('Meshed Pipe with a crack',
'Create a mesh with blocFissure tool',
fissureCoudeDlg)
# ZCracks plugin requires the module EFICAS to be installed
# thus it is first tested if this module is available before
# adding the plugin to salome_pluginsmanager
enable_zcracks = True
try:
import eficasSalome
except:
enable_zcracks = False
if enable_zcracks:
from zcracks_plugin import ZcracksLct
salome_pluginsmanager.AddFunction('Run Zcrack',
'Run Zcrack',
ZcracksLct)
| lgpl-2.1 |
kolibre/Kolibre-KADOS | include/types/supportedOptionalOperations.class.php | 3542 | <?php
/*
* Copyright (C) 2013 Kolibre
*
* This file is part of Kolibre-KADOS.
* Kolibre-KADOS 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.
*
* Kolibre-KADOS 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 Kolibre-KADOS. If not, see <http://www.gnu.org/licenses/>.
*/
require_once('AbstractType.class.php');
class supportedOptionalOperations extends AbstractType {
/**
* @var array[0, unbounded] of string
* NOTE: operation should follow the following restrictions
* You can have one of the following value
* SET_BOOKMARKS
* GET_BOOKMARKS
* DYNAMIC_MENUS
* SERVICE_ANNOUNCEMENTS
* PDTB2_KEY_PROVISION
*/
public $operation;
/******************** public functions ********************/
/**
* constructor for class supportedOptionalOperations
*/
function __construct($_operation = NULL) {
if (is_array($_operation)) $this->setOperation($_operation);
}
/******************** class get set methods ********************/
/**
* getter for operation
*/
function getOperation() {
return $this->operation;
}
/**
* setter for operation
*/
function setOperation($_operation) {
$this->operation = $_operation;
}
/**
* resetter for operation
*/
function resetOperation() {
$this->operation = NULL;
}
/****************************** get set methods for arrays **********************************/
/**
* get the ith element of operation
*/
function getOperationAt($i) {
if ($this->sizeofOperation() > $i)
return $this->operation[$i];
else return NULL;
}
/**
* set the ith element of operation
*/
function setOperationAt($i, $_operation) {
$this->operation[$i] = $_operation;
}
/**
* add to operation
*/
function addOperation($_operation) {
if (is_array($this->operation))
array_push($this->operation, $_operation);
else {
$this->operation = array();
$this->addOperation($_operation);
}
}
/**
* get the size of the operation array
*/
function sizeofOperation() {
return sizeof($this->operation);
}
/**
* remove the ith element of operation
*/
function removeOperationAt($i) {
if ($this->sizeofOperation() > $i)
unset($this->operation[$i]);
}
/******************** validator methods ********************/
/**
* validator for class supportedOptionalOperations
*/
function validate() {
// operation must occur zero or more times
if (!is_null($this->operation)) {
$allowedValues = array('SET_BOOKMARKS', 'GET_BOOKMARKS', 'DYNAMIC_MENUS', 'SERVICE_ANNOUNCEMENTS', 'PDTB2_KEY_PROVISION');
if ($this->isArrayOfString($this->operation, 'operation', $allowedValues) === false)
return false;
}
return true;
}
}
?>
| lgpl-2.1 |
camaradosdeputadosoficial/edemocracia | cd-guiadiscussao-portlet/src/main/java/br/gov/camara/edemocracia/portlets/guiadiscussao/service/base/AcaoLocalServiceClpInvoker.java | 11389 | /**
* Copyright (c) 2009-2014 Câmara dos Deputados. Todos os direitos reservados.
*
* e-Democracia é um software livre; você pode redistribuí-lo e/ou modificá-lo dentro
* dos termos da Licença Pública Geral Menor GNU como publicada pela Fundação do
* Software Livre (FSF); na versão 2.1 da Licença, ou (na sua opinião) qualquer versão.
*
* Este programa é distribuído na esperança de que possa ser útil, mas SEM NENHUMA GARANTIA;
* sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR.
* Veja a Licença Pública Geral Menor GNU para maiores detalhes.
*/
package br.gov.camara.edemocracia.portlets.guiadiscussao.service.base;
import br.gov.camara.edemocracia.portlets.guiadiscussao.service.AcaoLocalServiceUtil;
import java.util.Arrays;
public class AcaoLocalServiceClpInvoker {
private String _methodName0;
private String[] _methodParameterTypes0;
private String _methodName1;
private String[] _methodParameterTypes1;
private String _methodName2;
private String[] _methodParameterTypes2;
private String _methodName3;
private String[] _methodParameterTypes3;
private String _methodName4;
private String[] _methodParameterTypes4;
private String _methodName5;
private String[] _methodParameterTypes5;
private String _methodName6;
private String[] _methodParameterTypes6;
private String _methodName7;
private String[] _methodParameterTypes7;
private String _methodName8;
private String[] _methodParameterTypes8;
private String _methodName9;
private String[] _methodParameterTypes9;
private String _methodName10;
private String[] _methodParameterTypes10;
private String _methodName11;
private String[] _methodParameterTypes11;
private String _methodName12;
private String[] _methodParameterTypes12;
private String _methodName13;
private String[] _methodParameterTypes13;
private String _methodName14;
private String[] _methodParameterTypes14;
private String _methodName15;
private String[] _methodParameterTypes15;
private String _methodName44;
private String[] _methodParameterTypes44;
private String _methodName45;
private String[] _methodParameterTypes45;
private String _methodName50;
private String[] _methodParameterTypes50;
private String _methodName51;
private String[] _methodParameterTypes51;
private String _methodName52;
private String[] _methodParameterTypes52;
private String _methodName53;
private String[] _methodParameterTypes53;
public AcaoLocalServiceClpInvoker() {
_methodName0 = "addAcao";
_methodParameterTypes0 = new String[] {
"br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao"
};
_methodName1 = "createAcao";
_methodParameterTypes1 = new String[] { "long" };
_methodName2 = "deleteAcao";
_methodParameterTypes2 = new String[] { "long" };
_methodName3 = "deleteAcao";
_methodParameterTypes3 = new String[] {
"br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao"
};
_methodName4 = "dynamicQuery";
_methodParameterTypes4 = new String[] { };
_methodName5 = "dynamicQuery";
_methodParameterTypes5 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery"
};
_methodName6 = "dynamicQuery";
_methodParameterTypes6 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int"
};
_methodName7 = "dynamicQuery";
_methodParameterTypes7 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int",
"com.liferay.portal.kernel.util.OrderByComparator"
};
_methodName8 = "dynamicQueryCount";
_methodParameterTypes8 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery"
};
_methodName9 = "fetchAcao";
_methodParameterTypes9 = new String[] { "long" };
_methodName10 = "getAcao";
_methodParameterTypes10 = new String[] { "long" };
_methodName11 = "getPersistedModel";
_methodParameterTypes11 = new String[] { "java.io.Serializable" };
_methodName12 = "getAcaos";
_methodParameterTypes12 = new String[] { "int", "int" };
_methodName13 = "getAcaosCount";
_methodParameterTypes13 = new String[] { };
_methodName14 = "updateAcao";
_methodParameterTypes14 = new String[] {
"br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao"
};
_methodName15 = "updateAcao";
_methodParameterTypes15 = new String[] {
"br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao",
"boolean"
};
_methodName44 = "getBeanIdentifier";
_methodParameterTypes44 = new String[] { };
_methodName45 = "setBeanIdentifier";
_methodParameterTypes45 = new String[] { "java.lang.String" };
_methodName50 = "addAcao";
_methodParameterTypes50 = new String[] {
"br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao"
};
_methodName51 = "excluirAcao";
_methodParameterTypes51 = new String[] { "long" };
_methodName52 = "getAcoesByFaseId";
_methodParameterTypes52 = new String[] { "long" };
_methodName53 = "atualizarOrdenacaoDasAcoes";
_methodParameterTypes53 = new String[] { "java.lang.Long", "java.util.Map" };
}
public Object invokeMethod(String name, String[] parameterTypes,
Object[] arguments) throws Throwable {
if (_methodName0.equals(name) &&
Arrays.deepEquals(_methodParameterTypes0, parameterTypes)) {
return AcaoLocalServiceUtil.addAcao((br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao) arguments[0]);
}
if (_methodName1.equals(name) &&
Arrays.deepEquals(_methodParameterTypes1, parameterTypes)) {
return AcaoLocalServiceUtil.createAcao(((Long) arguments[0]).longValue());
}
if (_methodName2.equals(name) &&
Arrays.deepEquals(_methodParameterTypes2, parameterTypes)) {
return AcaoLocalServiceUtil.deleteAcao(((Long) arguments[0]).longValue());
}
if (_methodName3.equals(name) &&
Arrays.deepEquals(_methodParameterTypes3, parameterTypes)) {
return AcaoLocalServiceUtil.deleteAcao((br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao) arguments[0]);
}
if (_methodName4.equals(name) &&
Arrays.deepEquals(_methodParameterTypes4, parameterTypes)) {
return AcaoLocalServiceUtil.dynamicQuery();
}
if (_methodName5.equals(name) &&
Arrays.deepEquals(_methodParameterTypes5, parameterTypes)) {
return AcaoLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0]);
}
if (_methodName6.equals(name) &&
Arrays.deepEquals(_methodParameterTypes6, parameterTypes)) {
return AcaoLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0],
((Integer) arguments[1]).intValue(),
((Integer) arguments[2]).intValue());
}
if (_methodName7.equals(name) &&
Arrays.deepEquals(_methodParameterTypes7, parameterTypes)) {
return AcaoLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0],
((Integer) arguments[1]).intValue(),
((Integer) arguments[2]).intValue(),
(com.liferay.portal.kernel.util.OrderByComparator) arguments[3]);
}
if (_methodName8.equals(name) &&
Arrays.deepEquals(_methodParameterTypes8, parameterTypes)) {
return AcaoLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0]);
}
if (_methodName9.equals(name) &&
Arrays.deepEquals(_methodParameterTypes9, parameterTypes)) {
return AcaoLocalServiceUtil.fetchAcao(((Long) arguments[0]).longValue());
}
if (_methodName10.equals(name) &&
Arrays.deepEquals(_methodParameterTypes10, parameterTypes)) {
return AcaoLocalServiceUtil.getAcao(((Long) arguments[0]).longValue());
}
if (_methodName11.equals(name) &&
Arrays.deepEquals(_methodParameterTypes11, parameterTypes)) {
return AcaoLocalServiceUtil.getPersistedModel((java.io.Serializable) arguments[0]);
}
if (_methodName12.equals(name) &&
Arrays.deepEquals(_methodParameterTypes12, parameterTypes)) {
return AcaoLocalServiceUtil.getAcaos(((Integer) arguments[0]).intValue(),
((Integer) arguments[1]).intValue());
}
if (_methodName13.equals(name) &&
Arrays.deepEquals(_methodParameterTypes13, parameterTypes)) {
return AcaoLocalServiceUtil.getAcaosCount();
}
if (_methodName14.equals(name) &&
Arrays.deepEquals(_methodParameterTypes14, parameterTypes)) {
return AcaoLocalServiceUtil.updateAcao((br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao) arguments[0]);
}
if (_methodName15.equals(name) &&
Arrays.deepEquals(_methodParameterTypes15, parameterTypes)) {
return AcaoLocalServiceUtil.updateAcao((br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao) arguments[0],
((Boolean) arguments[1]).booleanValue());
}
if (_methodName44.equals(name) &&
Arrays.deepEquals(_methodParameterTypes44, parameterTypes)) {
return AcaoLocalServiceUtil.getBeanIdentifier();
}
if (_methodName45.equals(name) &&
Arrays.deepEquals(_methodParameterTypes45, parameterTypes)) {
AcaoLocalServiceUtil.setBeanIdentifier((java.lang.String) arguments[0]);
}
if (_methodName50.equals(name) &&
Arrays.deepEquals(_methodParameterTypes50, parameterTypes)) {
return AcaoLocalServiceUtil.addAcao((br.gov.camara.edemocracia.portlets.guiadiscussao.model.Acao) arguments[0]);
}
if (_methodName51.equals(name) &&
Arrays.deepEquals(_methodParameterTypes51, parameterTypes)) {
AcaoLocalServiceUtil.excluirAcao(((Long) arguments[0]).longValue());
}
if (_methodName52.equals(name) &&
Arrays.deepEquals(_methodParameterTypes52, parameterTypes)) {
return AcaoLocalServiceUtil.getAcoesByFaseId(((Long) arguments[0]).longValue());
}
if (_methodName53.equals(name) &&
Arrays.deepEquals(_methodParameterTypes53, parameterTypes)) {
AcaoLocalServiceUtil.atualizarOrdenacaoDasAcoes((java.lang.Long) arguments[0],
(java.util.Map<java.lang.Long, java.lang.Integer>) arguments[1]);
}
throw new UnsupportedOperationException();
}
}
| lgpl-2.1 |
BlesseNtumble/Traincraft-5 | src/main/java/train/client/render/models/ModelLocoBR80_DB.java | 17590 | package train.client.render.models;
import cpw.mods.fml.client.FMLClientHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBase;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import train.client.core.helpers.HolidayHelper;
import train.client.render.models.blocks.ModelRing;
import train.client.render.CustomModelRenderer;
import train.common.library.Info;
public class ModelLocoBR80_DB extends ModelBase {
public float dig1 = 0.0F;
private long lastframe;
private float dig;
private ModelRing ring;
public CustomModelRenderer body;
public CustomModelRenderer box;
public CustomModelRenderer box0;
public CustomModelRenderer box1;
public CustomModelRenderer box10;
public CustomModelRenderer box11;
public CustomModelRenderer box12;
public CustomModelRenderer box13;
public CustomModelRenderer box14;
public CustomModelRenderer box15;
public CustomModelRenderer box16;
public CustomModelRenderer box17;
public CustomModelRenderer box18;
public CustomModelRenderer box19;
public CustomModelRenderer box2;
public CustomModelRenderer box20;
public CustomModelRenderer box21;
public CustomModelRenderer lightFront;
public CustomModelRenderer box23;
public CustomModelRenderer box24;
public CustomModelRenderer box25;
public CustomModelRenderer box26;
public CustomModelRenderer box27;
public CustomModelRenderer box28;
public CustomModelRenderer box29;
public CustomModelRenderer box3;
public CustomModelRenderer box30;
public CustomModelRenderer box31;
public CustomModelRenderer box32;
public CustomModelRenderer box33;
public CustomModelRenderer box34;
public CustomModelRenderer box35;
public CustomModelRenderer box36;
public CustomModelRenderer box37;
public CustomModelRenderer box38;
public CustomModelRenderer box39;
public CustomModelRenderer box4;
public CustomModelRenderer box40;
public CustomModelRenderer box41;
public CustomModelRenderer box42;
public CustomModelRenderer box43;
public CustomModelRenderer box44;
public CustomModelRenderer box45;
public CustomModelRenderer wheels1;
public CustomModelRenderer wheels2;
public CustomModelRenderer wheels3;
public CustomModelRenderer box49;
public CustomModelRenderer box5;
public CustomModelRenderer box50;
public CustomModelRenderer box51;
public CustomModelRenderer box52;
public CustomModelRenderer box53;
public CustomModelRenderer box54;
public CustomModelRenderer box55;
public CustomModelRenderer box56;
public CustomModelRenderer box57;
public CustomModelRenderer box58;
public CustomModelRenderer lightBack;
public CustomModelRenderer box6;
public CustomModelRenderer box60;
public CustomModelRenderer box61;
public CustomModelRenderer box62;
public CustomModelRenderer box63;
public CustomModelRenderer box64;
public CustomModelRenderer box65;
public CustomModelRenderer box66;
public CustomModelRenderer box67;
public CustomModelRenderer box68;
public CustomModelRenderer coalbox;
public CustomModelRenderer box7;
public CustomModelRenderer box70;
public CustomModelRenderer box8;
public CustomModelRenderer box9;
public ModelLocoBR80_DB() {
ring = new ModelRing();
body = new CustomModelRenderer(0, 206, 128, 256);
body.addBox(0F, 0F, 0F, 23, 2, 22);
body.setPosition(2F, 10F, -11F);
box = new CustomModelRenderer(22, 133, 128, 256);
box.addBox(0F, 0F, 0F, 1, 3, 20);
box.setPosition(2F, 28F, -10F);
box0 = new CustomModelRenderer(75, 180, 128, 256);
box0.addBox(0F, 0F, 0F, 2, 2, 2);
box0.setPosition(-25F, 7F, -7F);
box1 = new CustomModelRenderer(1, 100, 128, 256);
box1.addBox(0F, 0F, 0F, 1, 12, 20);
box1.setPosition(18F, 12F, -10F);
box10 = new CustomModelRenderer(82, 84, 128, 256);
box10.addBox(0F, 0F, 0F, 19, 5, 1);
box10.setPosition(20F, 32F, -7F);
box10.rotateAngleX = -4.1887902047863905F;
box10.rotateAngleY = -3.141592653589793F;
box11 = new CustomModelRenderer(44, 129, 128, 256);
box11.addBox(0F, 0F, 0F, 1, 4, 14);
box11.setPosition(2F, 24F, -7F);
box12 = new CustomModelRenderer(24, 103, 128, 256);
box12.addBox(0F, 0F, 0F, 9, 11, 1);
box12.setPosition(2F, 12F, 10F);
box13 = new CustomModelRenderer(37, 235, 128, 256);
box13.addBox(0F, 0F, 0F, 7, 7, 5);
box13.setPosition(-14F, 3F, -5F);
box13.rotateAngleY = 3.141592653589793F;
box13.rotateAngleZ = 6.283185307179586F;
box14 = new CustomModelRenderer(22, 133, 128, 256);
box14.addBox(0F, 0F, 0F, 1, 3, 20);
box14.setPosition(19F, 28F, 10F);
box14.rotateAngleY = -3.141592653589793F;
box15 = new CustomModelRenderer(44, 129, 128, 256);
box15.addBox(0F, 0F, 0F, 1, 4, 14);
box15.setPosition(19F, 24F, 7F);
box15.rotateAngleY = -3.141592653589793F;
box16 = new CustomModelRenderer(116, 249, 128, 256);
box16.addBox(0F, 0F, 0F, 1, 3, 3);
box16.setPosition(-26F, 7F, 5F);
box17 = new CustomModelRenderer(75, 180, 128, 256);
box17.addBox(0F, 0F, 0F, 2, 2, 2);
box17.setPosition(26F, 7F, 5F);
box18 = new CustomModelRenderer(75, 180, 128, 256);
box18.addBox(0F, 0F, 0F, 2, 2, 2);
box18.setPosition(26F, 7F, -7F);
box19 = new CustomModelRenderer(116, 249, 128, 256);
box19.addBox(0F, 0F, 0F, 1, 3, 3);
box19.setPosition(28F, 7F, 5F);
box2 = new CustomModelRenderer(25, 69, 128, 256);
box2.addBox(0F, 0F, 0F, 19, 1, 14);
box2.setPosition(1F, 31F, -7F);
box20 = new CustomModelRenderer(116, 249, 128, 256);
box20.addBox(0F, 0F, 0F, 1, 3, 3);
box20.setPosition(28F, 7F, -8F);
box21 = new CustomModelRenderer(0, 103, 128, 256);
box21.addBox(0F, 0F, 0F, 9, 11, 1);
box21.setPosition(2F, 12F, -11F);
lightFront = new CustomModelRenderer(23, 143, 128, 256);
lightFront.addBox(0F, 0F, 0F, 2, 4, 4);
lightFront.setPosition(-22F, 25F, -2F);
box23 = new CustomModelRenderer(53, 93, 128, 256);
box23.addBox(0F, 0F, 0F, 3, 7, 1);
box23.setPosition(2F, 23F, -11F);
box23.rotateAngleX = -6.1086523819801535F;
box24 = new CustomModelRenderer(81, 93, 128, 256);
box24.addBox(0F, 0F, 0F, 1, 7, 1);
box24.setPosition(10F, 23F, -11F);
box24.rotateAngleX = -6.1086523819801535F;
box25 = new CustomModelRenderer(52, 103, 128, 256);
box25.addBox(0F, 0F, 0F, 2, 11, 1);
box25.setPosition(17F, 12F, -11F);
box26 = new CustomModelRenderer(1, 68, 128, 256);
box26.addBox(0F, 0F, 0F, 1, 12, 20);
box26.setPosition(2F, 12F, -10F);
box27 = new CustomModelRenderer(62, 93, 128, 256);
box27.addBox(0F, 0F, 0F, 2, 7, 1);
box27.setPosition(17F, 23F, -11F);
box27.rotateAngleX = -6.1086523819801535F;
box28 = new CustomModelRenderer(44, 93, 128, 256);
box28.addBox(0F, 0F, 0F, 3, 7, 1);
box28.setPosition(5F, 23F, 11F);
box28.rotateAngleX = -6.1086523819801535F;
box28.rotateAngleY = -3.141592653589793F;
box29 = new CustomModelRenderer(45, 103, 128, 256);
box29.addBox(0F, 0F, 0F, 2, 11, 1);
box29.setPosition(17F, 12F, 10F);
box3 = new CustomModelRenderer(0, 248, 128, 256);
box3.addBox(0F, 0F, 0F, 47, 6, 1);
box3.setPosition(25F, 4F, -3F);
box3.rotateAngleY = -3.141592653589793F;
box30 = new CustomModelRenderer(76, 93, 128, 256);
box30.addBox(0F, 0F, 0F, 1, 7, 1);
box30.setPosition(11F, 23F, 11F);
box30.rotateAngleX = -6.1086523819801535F;
box30.rotateAngleY = -3.141592653589793F;
box31 = new CustomModelRenderer(69, 93, 128, 256);
box31.addBox(0F, 0F, 0F, 2, 7, 1);
box31.setPosition(19F, 23F, 11F);
box31.rotateAngleX = -6.1086523819801535F;
box31.rotateAngleY = -3.141592653589793F;
box32 = new CustomModelRenderer(37, 235, 128, 256);
box32.addBox(0F, 0F, 0F, 7, 7, 5);
box32.setPosition(-14F, 3F, 10F);
box32.rotateAngleY = -3.141592653589793F;
box33 = new CustomModelRenderer(72, 142, 128, 256);
box33.addBox(0F, 0F, 0F, 22, 12, 6);
box33.setPosition(-20F, 15F, -3F);
box34 = new CustomModelRenderer(60, 124, 128, 256);
box34.addBox(0F, 0F, 0F, 22, 6, 12);
box34.setPosition(-20F, 18F, -6F);
box35 = new CustomModelRenderer(76, 160, 128, 256);
box35.addBox(0F, 0F, 0F, 22, 4, 4);
box35.setPosition(-20F, 24F, -6F);
box35.rotateAngleX = -5.497787143782138F;
box36 = new CustomModelRenderer(76, 160, 128, 256);
box36.addBox(0F, 0F, 0F, 22, 4, 4);
box36.setPosition(2F, 24F, 6F);
box36.rotateAngleX = -5.497787143782138F;
box36.rotateAngleY = -3.141592653589793F;
box37 = new CustomModelRenderer(76, 160, 128, 256);
box37.addBox(0F, 0F, 0F, 22, 4, 4);
box37.setPosition(2F, 18F, 6F);
box37.rotateAngleX = -5.497787143782138F;
box37.rotateAngleY = -3.141592653589793F;
box38 = new CustomModelRenderer(76, 160, 128, 256);
box38.addBox(0F, 0F, 0F, 22, 4, 4);
box38.setPosition(-20F, 18F, -6F);
box38.rotateAngleX = -5.497787143782138F;
box39 = new CustomModelRenderer(109, 198, 128, 256);
box39.addBox(0F, 0F, 0F, 4, 7, 4);
box39.setPosition(-19F, 27F, -2F);
box4 = new CustomModelRenderer(82, 84, 128, 256);
box4.addBox(0F, 0F, 0F, 19, 5, 1);
box4.setPosition(1F, 32F, 7F);
box4.rotateAngleX = -4.1887902047863905F;
box40 = new CustomModelRenderer(44, 101, 128, 256);
box40.addBox(0F, 0F, 0F, 20, 1, 22);
box40.setPosition(-18F, 13F, -11F);
box41 = new CustomModelRenderer(2, 4, 128, 256);
box41.addBox(0F, 0F, 0F, 15, 9, 22);
box41.setPosition(-13F, 14F, -11F);
box42 = new CustomModelRenderer(70, 188, 128, 256);
box42.addBox(0F, 0F, 0F, 7, 11, 22);
box42.setPosition(19F, 12F, -11F);
box43 = new CustomModelRenderer(89, 170, 128, 256);
box43.addBox(-1F, 0F, 0F, 7, 7, 10);
box43.setPosition(20F, 23F, -5F);
box43.rotateAngleZ = -0.17453292519943295F;
box44 = new CustomModelRenderer(35, 157, 128, 256);
box44.addBox(0F, 0F, 0F, 4, 1, 18);
box44.setPosition(-22F, 10F, -9F);
box45 = new CustomModelRenderer(53, 179, 128, 256);
box45.addBox(0F, 0F, 0F, 5, 10, 8);
box45.setPosition(-19F, 10F, -4F);
wheels1 = new CustomModelRenderer(0, 230, 128, 256);
wheels1.addBox(-4F, -4F, 0F, 8, 8, 10);
wheels1.setPosition(-8F, 4F, 5F);
wheels1.rotateAngleY = -3.141592653589793F;
wheels2 = new CustomModelRenderer(0, 230, 128, 256);
wheels2.addBox(-4F, -4F, 0F, 8, 8, 10);
wheels2.setPosition(12F, 4F, 5F);
wheels2.rotateAngleY = -3.141592653589793F;
wheels3 = new CustomModelRenderer(0, 230, 128, 256);
wheels3.addBox(-4F, -4F, 0F, 8, 8, 10);
wheels3.setPosition(2F, 4F, 5F);
wheels3.rotateAngleY = -3.141592653589793F;
box49 = new CustomModelRenderer(107, 113, 128, 256);
box49.addBox(0F, 0F, 0F, 2, 3, 4);
box49.setPosition(-25F, 6F, -2F);
box5 = new CustomModelRenderer(75, 180, 128, 256);
box5.addBox(0F, 0F, 0F, 2, 2, 2);
box5.setPosition(-25F, 7F, 5F);
box50 = new CustomModelRenderer(107, 113, 128, 256);
box50.addBox(0F, 0F, 0F, 4, 3, 4);
box50.setPosition(26F, 6F, -2F);
box51 = new CustomModelRenderer(22, 164, 128, 256);
box51.addBox(0F, 0F, 0F, 9, 4, 6);
box51.setPosition(-12F, 26F, -3F);
box52 = new CustomModelRenderer(27, 232, 128, 256);
box52.addBox(0F, 0F, 0F, 20, 1, 1);
box52.setPosition(14F, 2F, 7F);
box52.rotateAngleY = -3.141592653589793F;
box53 = new CustomModelRenderer(27, 232, 128, 256);
box53.addBox(0F, 0F, 0F, 21, 1, 1);
box53.setPosition(13F, 2F, 8F);
box53.rotateAngleY = 3.141592653589793F;
box53.rotateAngleZ = 6.14355896702004F;
box54 = new CustomModelRenderer(27, 230, 128, 256);
box54.addBox(0F, 0F, 0F, 16, 1, 1);
box54.setPosition(-8F, 5F, 8F);
box54.rotateAngleY = -3.141592653589793F;
box55 = new CustomModelRenderer(27, 232, 128, 256);
box55.addBox(0F, 0F, 0F, 20, 1, 1);
box55.setPosition(14F, 2F, -6F);
box55.rotateAngleY = -3.141592653589793F;
box56 = new CustomModelRenderer(27, 232, 128, 256);
box56.addBox(0F, 0F, 0F, 21, 1, 1);
box56.setPosition(13F, 2F, -7F);
box56.rotateAngleY = 3.141592653589793F;
box56.rotateAngleZ = 6.14355896702004F;
box57 = new CustomModelRenderer(27, 230, 128, 256);
box57.addBox(0F, 0F, 0F, 16, 1, 1);
box57.setPosition(-8F, 5F, -7F);
box57.rotateAngleY = -3.141592653589793F;
box58 = new CustomModelRenderer(1, 210, 128, 256);
box58.addBox(0F, 0F, 0F, 2, 8, 8);
box58.setPosition(-21F, 17F, -4F);
lightBack = new CustomModelRenderer(23, 143, 128, 256);
lightBack.addBox(0F, 0F, 0F, 2, 4, 4);
lightBack.setPosition(28F, 22F, 2F);
lightBack.rotateAngleY = -3.141592653589793F;
box6 = new CustomModelRenderer(0, 248, 128, 256);
box6.addBox(0F, 0F, 0F, 47, 6, 1);
box6.setPosition(25F, 4F, 4F);
box6.rotateAngleY = -3.141592653589793F;
box60 = new CustomModelRenderer(86, 221, 128, 256);
box60.addBox(0F, 0F, 0F, 9, 16, 12);
box60.setPosition(6F, 10F, 6F);
box60.rotateAngleY = -3.141592653589793F;
box61 = new CustomModelRenderer(64, 238, 128, 256);
box61.addBox(0F, 0F, 0F, 6, 8, 1);
box61.setPosition(17F, 2F, -9F);
box61.rotateAngleY = -3.141592653589793F;
box62 = new CustomModelRenderer(64, 238, 128, 256);
box62.addBox(0F, 0F, 0F, 6, 8, 1);
box62.setPosition(17F, 2F, 10F);
box62.rotateAngleY = -3.141592653589793F;
box63 = new CustomModelRenderer(112, 101, 128, 256);
box63.addBox(0F, 0F, 1F, 1, 3, 3);
box63.setPosition(-20F, 11F, 5F);
box63.rotateAngleZ = -0.5061454830783556F;
box64 = new CustomModelRenderer(112, 101, 128, 256);
box64.addBox(0F, 0F, -14F, 1, 3, 3);
box64.setPosition(-20F, 11F, 5F);
box64.rotateAngleZ = -0.5061454830783556F;
box65 = new CustomModelRenderer(75, 48, 128, 256);
box65.addBox(0F, 0F, 0F, 7, 4, 16);
box65.setPosition(25F, 6F, 8F);
box65.rotateAngleY = -3.141592653589793F;
box66 = new CustomModelRenderer(2, 51, 128, 256);
box66.addBox(0F, 0F, 0F, 2, 2, 12);
box66.setPosition(-7F, 3F, 6F);
box66.rotateAngleY = -3.141592653589793F;
box67 = new CustomModelRenderer(2, 51, 128, 256);
box67.addBox(0F, 0F, 0F, 2, 2, 12);
box67.setPosition(3F, 3F, 6F);
box67.rotateAngleY = -3.141592653589793F;
box68 = new CustomModelRenderer(2, 51, 128, 256);
box68.addBox(0F, 0F, 0F, 2, 2, 12);
box68.setPosition(13F, 3F, 6F);
box68.rotateAngleY = -3.141592653589793F;
coalbox = new CustomModelRenderer(28, 54, 128, 256);
coalbox.addBox(1F, 5F, 0F, 9, 2, 12);
coalbox.setPosition(18F, 23F, -6F);
box7 = new CustomModelRenderer(0, 140, 128, 256);
box7.addBox(0F, 1F, 0F, 1, 5, 18);
box7.setPosition(-23F, 5F, -9F);
box70 = new CustomModelRenderer(60, 35, 128, 256);
box70.addBox(1F, 5F, 0F, 3, 7, 10);
box70.setPosition(18F, 17F, -5F);
box8 = new CustomModelRenderer(0, 140, 128, 256);
box8.addBox(0F, 0F, 0F, 1, 5, 18);
box8.setPosition(26F, 6F, 9F);
box8.rotateAngleY = -3.141592653589793F;
box9 = new CustomModelRenderer(116, 249, 128, 256);
box9.addBox(0F, 0F, 0F, 1, 3, 3);
box9.setPosition(-26F, 7F, -8F);
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
long now = System.nanoTime();
int elapsed = (int) ((now - lastframe) / (1000 * 1000));
dig -= (float) elapsed / 500.0f;
lastframe = now;
if(HolidayHelper.isHoliday()) {
FMLClientHandler.instance().getClient().renderEngine.bindTexture(new ResourceLocation(Info.resourceLocation, "textures/trains/locoBR80_DB_winter.png"));
}
body.render(f5);
box.render(f5);
box0.render(f5);
box1.render(f5);
box10.render(f5);
box11.render(f5);
box12.render(f5);
box13.render(f5);
box14.render(f5);
box15.render(f5);
box16.render(f5);
box17.render(f5);
box18.render(f5);
box19.render(f5);
box2.render(f5);
box20.render(f5);
box21.render(f5);
box23.render(f5);
box24.render(f5);
box25.render(f5);
box26.render(f5);
box27.render(f5);
box28.render(f5);
box29.render(f5);
box3.render(f5);
box30.render(f5);
box31.render(f5);
box32.render(f5);
box33.render(f5);
box34.render(f5);
box35.render(f5);
box36.render(f5);
box37.render(f5);
box38.render(f5);
box39.render(f5);
box4.render(f5);
box40.render(f5);
box41.render(f5);
box42.render(f5);
box43.render(f5);
box44.render(f5);
box45.render(f5);
wheels1.render(f5);
wheels2.render(f5);
wheels3.render(f5);
box49.render(f5);
box5.render(f5);
box50.render(f5);
box51.render(f5);
box52.render(f5);
box53.render(f5);
box54.render(f5);
box55.render(f5);
box56.render(f5);
box57.render(f5);
box58.render(f5);
Minecraft.getMinecraft().entityRenderer.disableLightmap(1D);
lightBack.render(f5);
lightFront.render(f5);
Minecraft.getMinecraft().entityRenderer.enableLightmap(1D);
box6.render(f5);
box60.render(f5);
box61.render(f5);
box62.render(f5);
box63.render(f5);
box64.render(f5);
box65.render(f5);
box66.render(f5);
box67.render(f5);
box68.render(f5);
coalbox.render(f5);
box7.render(f5);
box70.render(f5);
box8.render(f5);
box9.render(f5);
double moveX = entity.lastTickPosX-entity.posX;
double moveZ = entity.lastTickPosZ-entity.posZ;
if(moveX != 0 || moveZ != 0) {
if((entity.lastTickPosX-entity.posX) != 0) {
wheels1.rotateAngleZ = (float) (-dig*moveX);
wheels2.rotateAngleZ = (float) (-dig*moveX);
wheels3.rotateAngleZ = (float) (-dig*moveX);
}
else {
wheels1.rotateAngleZ = (float) (-dig*moveZ);
wheels2.rotateAngleZ = (float) (-dig*moveZ);
wheels3.rotateAngleZ = (float) (-dig*moveZ);
}
}
if(HolidayHelper.isHoliday()) {
GL11.glPushMatrix();
GL11.glTranslatef(-1.4f, 1.2f, 0);
GL11.glRotatef(180, 0, 1, 0);
GL11.glScalef(0.7f, 0.7f, 0.7f);
ring.render(5);
GL11.glPopMatrix();
}
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5) {}
}
| lgpl-2.1 |
raffy1982/spine-project | Spine_serverApp/src/spine/payload/codec/bt/StepCounterSpineFunctionReq.java | 2622 | /*****************************************************************
SPINE - Signal Processing In-Node Environment is a framework that
allows dynamic configuration of feature extraction capabilities
of WSN nodes via an OtA protocol
Copyright (C) 2007 Telecom Italia S.p.A.
GNU Lesser General Public License
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,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU 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.
*****************************************************************/
/**
*
* Objects of this class are used for expressing at high level function requests
* (both activation and deactivation) of type 'StepCounter'.
* An application that needs to do a StepCounter request, must create a new StepCounterSpineFunctionReq
* object for alarm activation, or deactivation.
*
* This class also implements the encode method of the abstract class SpineFunctionReq that is used internally
* to convert the high level request into an actual SPINE Ota message.
*
* Note that this class is used only internally at the framework.
*
* @author Raffaele Gravina
* @author Alessia Salmeri
*
* @version 1.3
*/
package spine.payload.codec.bt;
import spine.SPINEFunctionConstants;
import spine.datamodel.Node;
import spine.datamodel.functions.*;
import spine.exceptions.*;
public class StepCounterSpineFunctionReq extends SpineCodec {
private final static int PARAM_LENGTH = 0;
public SpineObject decode(Node node, byte[] payload) throws MethodNotSupportedException {
throw new MethodNotSupportedException("decode");
};
public byte[] encode(SpineObject payload) {
spine.datamodel.functions.StepCounterSpineFunctionReq workPayLoad = (spine.datamodel.functions.StepCounterSpineFunctionReq)payload;
byte[] data = new byte[3 + PARAM_LENGTH];
data[0] = SPINEFunctionConstants.STEP_COUNTER;
byte activationBinaryFlag = (workPayLoad.getActivationFlag())? (byte)1 : 0;
data[1] = activationBinaryFlag;
data[2] = PARAM_LENGTH;
return data;
}
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/modules/gui/pdf/PdfExportPlugin.java | 6999 | /*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.modules.gui.pdf;
import java.util.Locale;
import javax.swing.Icon;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.modules.gui.common.StatusType;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.AbstractExportActionPlugin;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.ReportProgressDialog;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.SwingGuiContext;
import org.pentaho.reporting.libraries.base.util.ObjectUtilities;
import org.pentaho.reporting.libraries.base.util.ResourceBundleSupport;
import org.pentaho.reporting.libraries.designtime.swing.LibSwingUtil;
/**
* Encapsulates the PDF export into a separate export plugin.
*
* @author Thomas Morgner
*/
public class PdfExportPlugin extends AbstractExportActionPlugin {
private static final Log logger = LogFactory.getLog( PdfExportPlugin.class );
/**
* Localized resources.
*/
private final ResourceBundleSupport resources;
/**
* The base resource class.
*/
public static final String BASE_RESOURCE_CLASS =
"org.pentaho.reporting.engine.classic.core.modules.gui.pdf.messages.messages"; //$NON-NLS-1$
public static final String PROGRESS_DIALOG_ENABLE_KEY =
"org.pentaho.reporting.engine.classic.core.modules.gui.pdf.ProgressDialogEnabled"; //$NON-NLS-1$
protected String getConfigurationPrefix() {
return "org.pentaho.reporting.engine.classic.core.modules.gui.pdf.export."; //$NON-NLS-1$
}
/**
* DefaultConstructor.
*/
public PdfExportPlugin() {
resources =
new ResourceBundleSupport( Locale.getDefault(), PdfExportPlugin.BASE_RESOURCE_CLASS, ObjectUtilities
.getClassLoader( PdfExportPlugin.class ) );
}
public boolean initialize( final SwingGuiContext context ) {
if ( super.initialize( context ) == false ) {
return false;
}
if ( ClassicEngineBoot.getInstance().isModuleAvailable( PdfExportGUIModule.class.getName() ) == false ) {
return false;
}
return true;
}
/**
* Creates the progress dialog that monitors the export process.
*
* @return the progress monitor dialog.
*/
protected ReportProgressDialog createProgressDialog() {
final ReportProgressDialog progressDialog = super.createProgressDialog();
progressDialog.setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
progressDialog.setMessage( resources.getString( "pdf-export.progressdialog.message" ) ); //$NON-NLS-1$
progressDialog.pack();
LibSwingUtil.positionFrameRandomly( progressDialog );
return progressDialog;
}
/**
* Shows this dialog and (if the dialog is confirmed) saves the complete report into an PDF file.
*
* @param report
* the report being processed.
* @return true or false.
*/
public boolean performExport( final MasterReport report ) {
final boolean result =
performShowExportDialog( report, "org.pentaho.reporting.engine.classic.core.modules.gui.pdf.Dialog" ); //$NON-NLS-1$
if ( result == false ) {
// user canceled the dialog ...
return false;
}
final ReportProgressDialog progressDialog;
if ( isProgressDialogEnabled( report,
"org.pentaho.reporting.engine.classic.core.modules.gui.pdf.ProgressDialogEnabled" ) ) {
progressDialog = createProgressDialog();
if ( report.getTitle() == null ) {
progressDialog.setTitle( getResources().getString( "ProgressDialog.EMPTY_TITLE" ) );
} else {
progressDialog.setTitle( getResources().formatMessage( "ProgressDialog.TITLE", report.getTitle() ) );
}
} else {
progressDialog = null;
}
try {
final PdfExportTask task = new PdfExportTask( report, progressDialog, getContext() );
final Thread worker = new Thread( task );
worker.start();
return true;
} catch ( Exception e ) {
PdfExportPlugin.logger.error( "Failure while preparing the PDF export", e ); //$NON-NLS-1$
getContext().getStatusListener().setStatus( StatusType.ERROR,
resources.getString( "PdfExportPlugin.USER_FAILED" ), e ); //$NON-NLS-1$
return false;
}
}
/**
* Returns the display name.
*
* @return The display name.
*/
public String getDisplayName() {
return resources.getString( "action.save-as.name" ); //$NON-NLS-1$
}
/**
* Returns the short description for the action.
*
* @return The short description.
*/
public String getShortDescription() {
return resources.getString( "action.save-as.description" ); //$NON-NLS-1$
}
/**
* Returns the small icon for the action.
*
* @return The icon.
*/
public Icon getSmallIcon() {
final Locale locale = getContext().getLocale();
return getIconTheme().getSmallIcon( locale, "action.export-to-pdf.small-icon" ); //$NON-NLS-1$
}
/**
* Returns the large icon for the action.
*
* @return The icon.
*/
public Icon getLargeIcon() {
final Locale locale = getContext().getLocale();
return getIconTheme().getLargeIcon( locale, "action.export-to-pdf.icon" ); //$NON-NLS-1$
}
/**
* Returns the accelerator key for the action.
*
* @return The accelerator key.
*/
public KeyStroke getAcceleratorKey() {
return resources.getOptionalKeyStroke( "action.save-as.accelerator" ); //$NON-NLS-1$
}
/**
* Returns the mnemonic key code.
*
* @return The key code.
*/
public Integer getMnemonicKey() {
return resources.getOptionalMnemonic( "action.save-as.mnemonic" ); //$NON-NLS-1$
}
/**
* Returns the resourcebundle to be used to translate strings into localized content.
*
* @return the resourcebundle for the localization.
*/
protected ResourceBundleSupport getResources() {
return resources;
}
}
| lgpl-2.1 |
timthelion/FreeCAD_sf_master | src/Mod/Fem/Gui/Resources/translations/Fem_hr.ts | 36027 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="hr" sourcelanguage="en">
<context>
<name>CmdFemAddPart</name>
<message>
<location filename="../../Command.cpp" line="+183"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>Add a part to the Analysis</source>
<translation type="unfinished">Add a part to the Analysis</translation>
</message>
</context>
<context>
<name>CmdFemConstraintBearing</name>
<message>
<location line="+65"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM bearing constraint</source>
<translation type="unfinished">Create FEM bearing constraint</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a bearing</source>
<translation type="unfinished">Create FEM constraint for a bearing</translation>
</message>
</context>
<context>
<name>CmdFemConstraintFixed</name>
<message>
<location line="+36"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM fixed constraint</source>
<translation type="unfinished">Create FEM fixed constraint</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a fixed geometric entity</source>
<translation type="unfinished">Create FEM constraint for a fixed geometric entity</translation>
</message>
</context>
<context>
<name>CmdFemConstraintForce</name>
<message>
<location line="+36"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM force constraint</source>
<translation type="unfinished">Create FEM force constraint</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a force acting on a geometric entity</source>
<translation type="unfinished">Create FEM constraint for a force acting on a geometric entity</translation>
</message>
</context>
<context>
<name>CmdFemConstraintGear</name>
<message>
<location line="+37"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM gear constraint</source>
<translation type="unfinished">Create FEM gear constraint</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a gear</source>
<translation type="unfinished">Create FEM constraint for a gear</translation>
</message>
</context>
<context>
<name>CmdFemConstraintPulley</name>
<message>
<location line="+36"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM pulley constraint</source>
<translation type="unfinished">Create FEM pulley constraint</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a pulley</source>
<translation type="unfinished">Create FEM constraint for a pulley</translation>
</message>
</context>
<context>
<name>CmdFemCreateAnalysis</name>
<message>
<location line="-286"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>Create a FEM analysis</source>
<translation type="unfinished">Create a FEM analysis</translation>
</message>
</context>
<context>
<name>CmdFemCreateFromShape</name>
<message>
<location line="-31"/>
<source>Fem</source>
<translation>Fem</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM mesh</source>
<translation>Napravi FEM mrežu</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM mesh from shape</source>
<translation>Napravite FEM mrežu od oblika</translation>
</message>
</context>
<context>
<name>CmdFemCreateNodesSet</name>
<message>
<location line="+500"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>Define/create a nodes set...</source>
<translation type="unfinished">Define/create a nodes set...</translation>
</message>
</context>
<context>
<name>CmdFemDefineNodesSet</name>
<message>
<location line="-59"/>
<source>Fem</source>
<translation type="unfinished">Fem</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<location line="+2"/>
<source>Create node set by Poly</source>
<translation type="unfinished">Create node set by Poly</translation>
</message>
</context>
<context>
<name>FemGui::HypothesisWidget</name>
<message>
<location filename="../../Hypothesis.ui" line="+14"/>
<source>Hypothesis</source>
<translation>Hipoteza</translation>
</message>
<message>
<location line="+8"/>
<source>Quadrangle</source>
<translation>Četverokut</translation>
</message>
<message>
<location line="+10"/>
<source>Maximum length</source>
<translation>Maksimalna duljina</translation>
</message>
<message>
<location line="+20"/>
<source>Local length</source>
<translation>Lokalna duljina</translation>
</message>
<message>
<location line="+20"/>
<source>Maximum element area</source>
<translation>Maksimalna površina elementa</translation>
</message>
</context>
<context>
<name>FemGui::TaskAnalysisInfo</name>
<message>
<location filename="../../TaskAnalysisInfo.cpp" line="+45"/>
<source>Nodes set</source>
<translation type="unfinished">Nodes set</translation>
</message>
</context>
<context>
<name>FemGui::TaskCreateNodeSet</name>
<message>
<location filename="../../TaskCreateNodeSet.cpp" line="+63"/>
<source>Nodes set</source>
<translation type="unfinished">Nodes set</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraint</name>
<message>
<location filename="../../TaskFemConstraint.cpp" line="+184"/>
<location line="+11"/>
<source>Input error</source>
<translation type="unfinished">Pogreška na ulazu</translation>
</message>
<message>
<location line="-11"/>
<source>You must specify at least one reference</source>
<translation type="unfinished">You must specify at least one reference</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraintBearing</name>
<message>
<location filename="../../TaskFemConstraintBearing.cpp" line="+349"/>
<source>Input error</source>
<translation type="unfinished">Pogreška na ulazu</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraintForce</name>
<message>
<location filename="../../TaskFemConstraintForce.cpp" line="+356"/>
<source>Input error</source>
<translation type="unfinished">Pogreška na ulazu</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraintGear</name>
<message>
<location filename="../../TaskFemConstraintGear.cpp" line="+308"/>
<source>Input error</source>
<translation type="unfinished">Pogreška na ulazu</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraintPulley</name>
<message>
<location filename="../../TaskFemConstraintPulley.cpp" line="+203"/>
<source>Input error</source>
<translation type="unfinished">Pogreška na ulazu</translation>
</message>
</context>
<context>
<name>FemGui::TaskDriver</name>
<message>
<location filename="../../TaskDriver.cpp" line="+51"/>
<source>Nodes set</source>
<translation type="unfinished">Nodes set</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraint</name>
<message>
<location filename="../../TaskFemConstraint.cpp" line="-120"/>
<source>FEM constraint parameters</source>
<translation type="unfinished">FEM constraint parameters</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintBearing</name>
<message>
<location filename="../../TaskFemConstraintBearing.cpp" line="-274"/>
<source>Delete</source>
<translation type="unfinished">Izbriši</translation>
</message>
<message>
<location line="+98"/>
<location line="+4"/>
<location line="+7"/>
<location line="+16"/>
<location line="+6"/>
<location line="+4"/>
<source>Selection error</source>
<translation type="unfinished">Selection error</translation>
</message>
<message>
<location line="-37"/>
<source>Please use only a single reference for bearing constraint</source>
<translation type="unfinished">Please use only a single reference for bearing constraint</translation>
</message>
<message>
<location line="+4"/>
<source>Only faces can be picked</source>
<translation type="unfinished">Only faces can be picked</translation>
</message>
<message>
<location line="+7"/>
<source>Only cylindrical faces can be picked</source>
<translation type="unfinished">Only cylindrical faces can be picked</translation>
</message>
<message>
<location line="+16"/>
<source>Only planar faces can be picked</source>
<translation type="unfinished">Only planar faces can be picked</translation>
</message>
<message>
<location line="+6"/>
<source>Only linear edges can be picked</source>
<translation type="unfinished">Only linear edges can be picked</translation>
</message>
<message>
<location line="+4"/>
<source>Only faces and edges can be picked</source>
<translation type="unfinished">Only faces and edges can be picked</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintFixed</name>
<message>
<location filename="../../TaskFemConstraintFixed.cpp" line="+74"/>
<source>Delete</source>
<translation type="unfinished">Izbriši</translation>
</message>
<message>
<location line="+61"/>
<location line="+5"/>
<source>Selection error</source>
<translation type="unfinished">Selection error</translation>
</message>
<message>
<location line="-5"/>
<source>Mixed shape types are not possible. Use a second constraint instead</source>
<translation type="unfinished">Mixed shape types are not possible. Use a second constraint instead</translation>
</message>
<message>
<location line="+5"/>
<source>Only faces, edges and vertices can be picked</source>
<translation type="unfinished">Only faces, edges and vertices can be picked</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintForce</name>
<message>
<location filename="../../TaskFemConstraintForce.cpp" line="-282"/>
<source>Delete</source>
<translation type="unfinished">Izbriši</translation>
</message>
<message>
<source>Force [N]</source>
<translation type="obsolete">Force [N]</translation>
</message>
<message>
<source>Force [N/mm]</source>
<translation type="obsolete">Force [N/mm]</translation>
</message>
<message>
<source>Force [N/mm²]</source>
<translation type="obsolete">Force [N/mm²]</translation>
</message>
<message>
<location line="+67"/>
<source>Point load [N]</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Line load [N/mm]</source>
<translation type="unfinished"></translation>
</message>
<message utf8="true">
<location line="+2"/>
<source>Area load [N/mm²]</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+30"/>
<location line="+5"/>
<location line="+27"/>
<location line="+6"/>
<location line="+4"/>
<source>Selection error</source>
<translation type="unfinished">Selection error</translation>
</message>
<message>
<location line="-42"/>
<source>Mixed shape types are not possible. Use a second constraint instead</source>
<translation type="unfinished">Mixed shape types are not possible. Use a second constraint instead</translation>
</message>
<message>
<location line="+5"/>
<source>Only faces, edges and vertices can be picked</source>
<translation type="unfinished">Only faces, edges and vertices can be picked</translation>
</message>
<message>
<location line="+27"/>
<source>Only planar faces can be picked</source>
<translation type="unfinished">Only planar faces can be picked</translation>
</message>
<message>
<location line="+6"/>
<source>Only linear edges can be picked</source>
<translation type="unfinished">Only linear edges can be picked</translation>
</message>
<message>
<location line="+4"/>
<source>Only faces and edges can be picked</source>
<translation type="unfinished">Only faces and edges can be picked</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintGear</name>
<message>
<location filename="../../TaskFemConstraintGear.cpp" line="-155"/>
<location line="+6"/>
<location line="+4"/>
<source>Selection error</source>
<translation type="unfinished">Selection error</translation>
</message>
<message>
<location line="-10"/>
<source>Only planar faces can be picked</source>
<translation type="unfinished">Only planar faces can be picked</translation>
</message>
<message>
<location line="+6"/>
<source>Only linear edges can be picked</source>
<translation type="unfinished">Only linear edges can be picked</translation>
</message>
<message>
<location line="+4"/>
<source>Only faces and edges can be picked</source>
<translation type="unfinished">Only faces and edges can be picked</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintPulley</name>
<message>
<location filename="../../TaskFemConstraintPulley.cpp" line="-110"/>
<source>Pulley diameter</source>
<translation type="unfinished">Pulley diameter</translation>
</message>
<message>
<location line="+1"/>
<source>Torque [Nm]</source>
<translation type="unfinished">Torque [Nm]</translation>
</message>
</context>
<context>
<name>FemGui::TaskObjectName</name>
<message>
<location filename="../../TaskObjectName.cpp" line="+48"/>
<source>TaskObjectName</source>
<translation type="unfinished">TaskObjectName</translation>
</message>
</context>
<context>
<name>FemGui::TaskTetParameter</name>
<message>
<location filename="../../TaskTetParameter.cpp" line="+52"/>
<source>Tet Parameter</source>
<translation type="unfinished">Tet Parameter</translation>
</message>
</context>
<context>
<name>MechanicalMaterial</name>
<message>
<location filename="../../../MechanicalAnalysis.ui" line="+14"/>
<source>Mechanical analysis</source>
<translation type="unfinished">Mechanical analysis</translation>
</message>
<message>
<location line="+21"/>
<source>...</source>
<translation type="unfinished">...</translation>
</message>
<message>
<location line="+9"/>
<source>Run Calculix</source>
<translation type="unfinished">Run Calculix</translation>
</message>
<message>
<location line="+19"/>
<source>Time:</source>
<translation type="unfinished">Time:</translation>
</message>
<message>
<location filename="../../../MechanicalMaterial.ui" line="+14"/>
<source>Mechanical material</source>
<translation type="unfinished">Mechanical material</translation>
</message>
<message>
<location line="+7"/>
<source>choose...</source>
<translation type="unfinished">choose...</translation>
</message>
<message>
<location line="+10"/>
<source>MatWeb database...</source>
<translation type="unfinished">MatWeb database...</translation>
</message>
<message>
<location line="+11"/>
<source>Young's Modulus:</source>
<translation type="unfinished">Young's Modulus:</translation>
</message>
<message>
<location line="+22"/>
<source>Pa</source>
<translation type="unfinished">Pa</translation>
</message>
<message>
<location line="+19"/>
<source>Poisson Ratio:</source>
<translation type="unfinished">Poisson Ratio:</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../../Command.cpp" line="-468"/>
<source>No active Analysis</source>
<translation type="unfinished">No active Analysis</translation>
</message>
<message>
<location line="+1"/>
<source>You need to create or activate a Analysis</source>
<translation type="unfinished">You need to create or activate a Analysis</translation>
</message>
<message>
<location line="+58"/>
<location line="+8"/>
<location line="+56"/>
<location line="+8"/>
<source>Wrong selection</source>
<translation type="unfinished">Pogrešan odabir</translation>
</message>
<message>
<location line="-71"/>
<location line="+64"/>
<source>Your FreeCAD is build without NETGEN support. Meshing will not work....</source>
<translation type="unfinished">Your FreeCAD is build without NETGEN support. Meshing will not work....</translation>
</message>
<message>
<location line="-56"/>
<location line="+64"/>
<source>Select an edge, face or body. Only one body is allowed.</source>
<translation type="unfinished">Odaberite rub, plohu ili tijelo. Samo jedno tijelo je dozvoljeno.</translation>
</message>
<message>
<location line="-59"/>
<location line="+64"/>
<source>Wrong object type</source>
<translation type="unfinished">Pogrešan tip objekta</translation>
</message>
<message>
<location line="-63"/>
<location line="+64"/>
<source>Fillet works only on parts</source>
<translation type="unfinished">Rubove možete zaobliti samo na tijelima</translation>
</message>
<message>
<location filename="../../TaskFemConstraint.cpp" line="+16"/>
<source>Ok</source>
<translation type="unfinished">Ok</translation>
</message>
<message>
<location line="+1"/>
<source>Cancel</source>
<translation type="unfinished">Otkazati</translation>
</message>
<message>
<location filename="../../ViewProviderFemConstraint.cpp" line="+144"/>
<source>Edit constraint</source>
<translation type="unfinished">Edit constraint</translation>
</message>
<message>
<location line="+280"/>
<location line="+2"/>
<source>Combo View</source>
<translation type="unfinished">Kombinirani pregled</translation>
</message>
<message>
<location line="+2"/>
<source>combiTab</source>
<translation type="unfinished">combiTab</translation>
</message>
<message>
<location line="+2"/>
<source>qt_tabwidget_stackedwidget</source>
<translation type="unfinished">qt_tabwidget_stackedwidget</translation>
</message>
<message>
<location line="+6"/>
<source>ShaftWizard</source>
<translation type="unfinished">ShaftWizard</translation>
</message>
<message>
<location line="+3"/>
<source>ShaftWizardLayout</source>
<translation type="unfinished">ShaftWizardLayout</translation>
</message>
<message>
<location filename="../../ViewProviderFemConstraintBearing.cpp" line="+74"/>
<location filename="../../ViewProviderFemConstraintFixed.cpp" line="+74"/>
<location filename="../../ViewProviderFemConstraintForce.cpp" line="+72"/>
<location filename="../../ViewProviderFemConstraintGear.cpp" line="+73"/>
<location filename="../../ViewProviderFemConstraintPulley.cpp" line="+72"/>
<source>A dialog is already open in the task panel</source>
<translation type="unfinished">Dijalog je već otvoren u ploči zadataka</translation>
</message>
<message>
<location line="+1"/>
<location filename="../../ViewProviderFemConstraintFixed.cpp" line="+1"/>
<location filename="../../ViewProviderFemConstraintForce.cpp" line="+1"/>
<location filename="../../ViewProviderFemConstraintGear.cpp" line="+1"/>
<location filename="../../ViewProviderFemConstraintPulley.cpp" line="+1"/>
<source>Do you want to close this dialog?</source>
<translation type="unfinished">Želite li zatvoriti ovaj dijalog?</translation>
</message>
<message>
<location filename="../../ViewProviderFemMeshShapeNetgen.cpp" line="+57"/>
<source>Meshing</source>
<translation type="unfinished">Meshing</translation>
</message>
</context>
<context>
<name>ShowDisplacement</name>
<message>
<location filename="../../../ShowDisplacement.ui" line="+14"/>
<source>Show result</source>
<translation type="unfinished">Show result</translation>
</message>
<message>
<location line="+8"/>
<source>Colors</source>
<translation type="unfinished">Boje</translation>
</message>
<message>
<location line="+73"/>
<source>Displacement</source>
<translation type="unfinished">Premještanje</translation>
</message>
<message>
<location line="-39"/>
<source>Max:</source>
<translation type="unfinished">Max:</translation>
</message>
<message>
<location line="+17"/>
<source>Min:</source>
<translation type="unfinished">Min:</translation>
</message>
<message>
<location line="-44"/>
<source>None</source>
<translation type="unfinished">Prazno</translation>
</message>
<message>
<location line="+10"/>
<source>Avg:</source>
<translation type="unfinished">Avg:</translation>
</message>
<message>
<location line="+10"/>
<location line="+17"/>
<location line="+17"/>
<source>mm</source>
<translation type="unfinished">mm</translation>
</message>
<message>
<location line="+18"/>
<source>Show</source>
<translation type="unfinished">Show</translation>
</message>
<message>
<location line="+12"/>
<source>Factor:</source>
<translation type="unfinished">Factor:</translation>
</message>
<message>
<location line="+27"/>
<source>Slider max:</source>
<translation type="unfinished">Slider max:</translation>
</message>
</context>
<context>
<name>TaskAnalysisInfo</name>
<message>
<location filename="../../TaskAnalysisInfo.ui" line="+20"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
<message>
<location line="+12"/>
<source>Meshes:</source>
<translation type="unfinished">Meshes:</translation>
</message>
<message>
<location line="+16"/>
<source>Constraints</source>
<translation type="unfinished">Ograničenja</translation>
</message>
</context>
<context>
<name>TaskCreateNodeSet</name>
<message>
<location filename="../../TaskCreateNodeSet.ui" line="+20"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
<message>
<location line="+7"/>
<source>Volume</source>
<translation type="unfinished">Volume</translation>
</message>
<message>
<location line="+5"/>
<source>Surface</source>
<translation type="unfinished">Surface</translation>
</message>
<message>
<location line="+17"/>
<source>Nodes: 0</source>
<translation type="unfinished">Nodes: 0</translation>
</message>
<message>
<location line="+11"/>
<source>Poly</source>
<translation type="unfinished">Poly</translation>
</message>
<message>
<location line="+10"/>
<source>Box</source>
<translation type="unfinished">Kutija</translation>
</message>
<message>
<location line="+10"/>
<source>Pick</source>
<translation type="unfinished">Pick</translation>
</message>
<message>
<location line="+7"/>
<source>Add</source>
<translation type="unfinished">Dodaj</translation>
</message>
<message>
<location line="+9"/>
<source>Angle-search</source>
<translation type="unfinished">Angle-search</translation>
</message>
<message>
<location line="+6"/>
<source>Collect adjancent nodes</source>
<translation type="unfinished">Collect adjancent nodes</translation>
</message>
<message>
<location line="+9"/>
<source>Stop angle:</source>
<translation type="unfinished">Stop angle:</translation>
</message>
</context>
<context>
<name>TaskDriver</name>
<message>
<location filename="../../TaskDriver.ui" line="+20"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
</context>
<context>
<name>TaskFemConstraint</name>
<message>
<location filename="../../TaskFemConstraint.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
<message>
<location line="+9"/>
<source>Add reference</source>
<translation type="unfinished">Add reference</translation>
</message>
<message>
<location line="+12"/>
<source>Load [N]</source>
<translation type="unfinished">Load [N]</translation>
</message>
<message>
<location line="+24"/>
<source>Diameter</source>
<translation type="unfinished">Diameter</translation>
</message>
<message>
<location line="+27"/>
<source>Other diameter</source>
<translation type="unfinished">Other diameter</translation>
</message>
<message>
<location line="+27"/>
<source>Center distance</source>
<translation type="unfinished">Center distance</translation>
</message>
<message>
<location line="+24"/>
<source>Direction</source>
<translation type="unfinished">Smjer</translation>
</message>
<message>
<location line="+12"/>
<source>Reverse direction</source>
<translation type="unfinished">Obrnutim smjerom</translation>
</message>
<message>
<location line="+9"/>
<source>Location</source>
<translation type="unfinished">Lokacija</translation>
</message>
<message>
<location line="+14"/>
<source>Distance</source>
<translation type="unfinished">Udaljenost</translation>
</message>
</context>
<context>
<name>TaskFemConstraintBearing</name>
<message>
<location filename="../../TaskFemConstraintBearing.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
<message>
<location line="+6"/>
<source>Add reference</source>
<translation type="unfinished">Add reference</translation>
</message>
<message>
<location line="+15"/>
<source>Gear diameter</source>
<translation type="unfinished">Gear diameter</translation>
</message>
<message>
<location line="+27"/>
<source>Other pulley dia</source>
<translation type="unfinished">Other pulley dia</translation>
</message>
<message>
<location line="+24"/>
<source>Center distance</source>
<translation type="unfinished">Center distance</translation>
</message>
<message>
<location line="+24"/>
<source>Force</source>
<translation type="unfinished">Force</translation>
</message>
<message>
<location line="+24"/>
<source>Belt tension force</source>
<translation type="unfinished">Belt tension force</translation>
</message>
<message>
<location line="+22"/>
<source>Driven pulley</source>
<translation type="unfinished">Driven pulley</translation>
</message>
<message>
<location line="+9"/>
<source>Force location [deg]</source>
<translation type="unfinished">Force location [deg]</translation>
</message>
<message>
<location line="+27"/>
<source>Force Direction</source>
<translation type="unfinished">Force Direction</translation>
</message>
<message>
<location line="+12"/>
<source>Reversed direction</source>
<translation type="unfinished">Reversed direction</translation>
</message>
<message>
<location line="+7"/>
<source>Axial free</source>
<translation type="unfinished">Axial free</translation>
</message>
<message>
<location line="+9"/>
<source>Location</source>
<translation type="unfinished">Lokacija</translation>
</message>
<message>
<location line="+14"/>
<source>Distance</source>
<translation type="unfinished">Udaljenost</translation>
</message>
</context>
<context>
<name>TaskFemConstraintFixed</name>
<message>
<location filename="../../TaskFemConstraintFixed.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
<message>
<location line="+6"/>
<source>Add reference</source>
<translation type="unfinished">Add reference</translation>
</message>
</context>
<context>
<name>TaskFemConstraintForce</name>
<message>
<location filename="../../TaskFemConstraintForce.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
<message>
<location line="+6"/>
<source>Add reference</source>
<translation type="unfinished">Add reference</translation>
</message>
<message>
<location line="+12"/>
<source>Load [N]</source>
<translation type="unfinished">Load [N]</translation>
</message>
<message>
<location line="+24"/>
<source>Direction</source>
<translation type="unfinished">Smjer</translation>
</message>
<message>
<location line="+12"/>
<source>Reverse direction</source>
<translation type="unfinished">Obrnutim smjerom</translation>
</message>
</context>
<context>
<name>TaskObjectName</name>
<message>
<location filename="../../TaskObjectName.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
</context>
<context>
<name>TaskTetParameter</name>
<message>
<location filename="../../TaskTetParameter.ui" line="+20"/>
<source>Form</source>
<translation type="unfinished">Obrazac</translation>
</message>
<message>
<location line="+8"/>
<source>Max. Size:</source>
<translation type="unfinished">Max. Size:</translation>
</message>
<message>
<location line="+16"/>
<source>Second order</source>
<translation type="unfinished">Second order</translation>
</message>
<message>
<location line="+9"/>
<source>Fineness:</source>
<translation type="unfinished">Fineness:</translation>
</message>
<message>
<location line="+11"/>
<source>VeryCoarse</source>
<translation type="unfinished">VeryCoarse</translation>
</message>
<message>
<location line="+5"/>
<source>Coarse</source>
<translation type="unfinished">Coarse</translation>
</message>
<message>
<location line="+5"/>
<source>Moderate</source>
<translation type="unfinished">Moderate</translation>
</message>
<message>
<location line="+5"/>
<source>Fine</source>
<translation type="unfinished">Fine</translation>
</message>
<message>
<location line="+5"/>
<source>VeryFine</source>
<translation type="unfinished">VeryFine</translation>
</message>
<message>
<location line="+5"/>
<source>UserDefined</source>
<translation type="unfinished">UserDefined</translation>
</message>
<message>
<location line="+8"/>
<source>Growth Rate:</source>
<translation type="unfinished">Growth Rate:</translation>
</message>
<message>
<location line="+14"/>
<source>Nbr. Segs per Edge:</source>
<translation type="unfinished">Nbr. Segs per Edge:</translation>
</message>
<message>
<location line="+17"/>
<source>Nbr. Segs per Radius:</source>
<translation type="unfinished">Nbr. Segs per Radius:</translation>
</message>
<message>
<location line="+16"/>
<source>Optimize</source>
<translation type="unfinished">Optimize</translation>
</message>
<message>
<location line="+22"/>
<source>Node count: </source>
<translation type="unfinished">Node count: </translation>
</message>
<message>
<location line="+14"/>
<source>Triangle count:</source>
<translation type="unfinished">Triangle count:</translation>
</message>
<message>
<location line="+14"/>
<source>Tetraeder count:</source>
<translation type="unfinished">Tetraeder count:</translation>
</message>
</context>
<context>
<name>Workbench</name>
<message>
<location filename="../../Workbench.cpp" line="+38"/>
<source>FEM</source>
<translation>FEM</translation>
</message>
<message>
<location line="+1"/>
<source>&FEM</source>
<translation>&FEM</translation>
</message>
</context>
</TS>
| lgpl-2.1 |
TheQwertiest/foo_title | foo_title/fooManagedWrapper/mainMenuCommands.cpp | 4558 | /*
Copyright 2005 - 2006 Roman Plasil
http://foo-title.sourceforge.net
This file is part of foo_title.
foo_title 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.
foo_title 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 foo_title; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "stdafx.h"
#include "mainMenuCommands.h"
#include "ManagedWrapper.h"
namespace fooManagedWrapper {
CMainMenuCommandsImpl::CMainMenuCommandsImpl(List<CCommand ^> ^_cmds) {
commonInit();
cmds = _cmds;
};
CMainMenuCommandsImpl::CMainMenuCommandsImpl() {
commonInit();
}
void CMainMenuCommandsImpl::commonInit() {
cmds = gcnew List<CCommand ^>();
CManagedWrapper::GetInstance()->AddService(this);
wrapper = new CMainMenuCommandsFactoryWrapper();
wrapper->mainMenuCommands.get_static_instance().SetImplementation(this);
}
CMainMenuCommandsImpl::!CMainMenuCommandsImpl() {
this->~CMainMenuCommandsImpl();
}
CMainMenuCommandsImpl::~CMainMenuCommandsImpl() {
delete wrapper;
}
unsigned int CMainMenuCommandsImpl::CommandsCount::get() {
return cmds->Count;
}
Guid CMainMenuCommandsImpl::GetGuid(unsigned int index) {
return cmds[index]->GetGuid();
}
String ^CMainMenuCommandsImpl::GetName(unsigned int index) {
return cmds[index]->GetName();
}
bool CMainMenuCommandsImpl::GetDescription(unsigned int index, String ^ %desc) {
return cmds[index]->GetDescription(desc);
}
void CMainMenuCommandsImpl::Execute(unsigned int index) {
return cmds[index]->Execute();
}
bool CMainMenuCommandsImpl::GetDisplay(unsigned int index, String ^ %text, unsigned int %flags) {
return cmds[index]->GetDisplay(text, flags);
}
void CCustomMainMenuCommands::SetImplementation(gcroot<CMainMenuCommandsImpl ^> impl) {
managedMainMenuCommands = impl;
}
t_uint32 CCustomMainMenuCommands::get_command_count() {
return managedMainMenuCommands->CommandsCount;
}
GUID CCustomMainMenuCommands::get_command(t_uint32 p_index) {
return CManagedWrapper::ToGUID(managedMainMenuCommands->GetGuid(p_index));
}
void CCustomMainMenuCommands::get_name(t_uint32 p_index, pfc::string_base & p_out) {
p_out = CManagedWrapper::StringToPfcString(managedMainMenuCommands->GetName(p_index));
}
bool CCustomMainMenuCommands::get_description(t_uint32 p_index, pfc::string_base &p_out) {
String ^str;
bool res = managedMainMenuCommands->GetDescription(p_index, str);
p_out = CManagedWrapper::StringToPfcString(str);
return res;
}
GUID CCustomMainMenuCommands::get_parent() {
return CManagedWrapper::ToGUID(managedMainMenuCommands->Parent);
}
void CCustomMainMenuCommands::execute(t_uint32 p_index, service_ptr_t<service_base> p_callback) {
managedMainMenuCommands->Execute(p_index);
}
unsigned int CCustomMainMenuCommands::get_sort_priority() {
return managedMainMenuCommands->SortPriority;
}
bool CCustomMainMenuCommands::get_display(t_uint32 p_index,pfc::string_base & p_text,t_uint32 & p_flags) {
String ^str;
bool res = managedMainMenuCommands->GetDisplay(p_index, str, p_flags);
p_text = CManagedWrapper::StringToPfcString(str);
return res;
}
CMainMenuCommands::CMainMenuCommands(const service_ptr_t<mainmenu_commands> &_ptr) {
this->ptr = new service_ptr_t<mainmenu_commands>(_ptr);
}
CMainMenuCommands::~CMainMenuCommands() {
FT_NULL_DELETE(ptr);
}
String ^CMainMenuCommands::GetName(unsigned int index) {
pfc::string8 pfcName;
(*ptr)->get_name(index, pfcName);
return CManagedWrapper::PfcStringToString(pfcName);
}
Guid CMainMenuCommands::Parent::get() {
return safe_cast<Guid>(CManagedWrapper::FromGUID((*ptr)->get_parent()));
}
Guid ^CMainMenuCommands::GetCommand(unsigned int index) {
return CManagedWrapper::FromGUID((*ptr)->get_command(index));
}
void CMainMenuCommands::Execute(unsigned int index) {
(*ptr)->execute(index, NULL);
}
}; | lgpl-2.1 |
alphabetsoup/gpstk | tests/gpsNavMsg/xPackedNavBitsgpsNavMsg.cpp | 12548 | #pragma ident "$Id: $"
/*********************************************************************
* $Id:$
*
* Test program from July 2011. Written to test the PackedNavBits
* module as it was being developed.
*
*********************************************************************/
#include <stdio.h>
#include <math.h>
#include "PackedNavBits.hpp"
#include "CivilTime.hpp"
#include "CommonTime.hpp"
#include "GPSWeekSecond.hpp"
#include "GNSSconstants.hpp"
#include "xPackedNavBitsgpsNavMsg.hpp"
CPPUNIT_TEST_SUITE_REGISTRATION (xPackedNavBitsgpsNavMsg);
using namespace std;
using namespace gpstk;
void xPackedNavBitsgpsNavMsg::setUp(void)
{
}
void xPackedNavBitsgpsNavMsg::firstTest(void)
{
// Set time to Day 153, 2011 (6/2/2011) at noon
CivilTime g( 2011, 6, 2, 12, 14, 44.0, TimeSystem::GPS );
CommonTime TransmitTime = g.convertToCommonTime();
SatID satSys(1, SatID::systemGPS);
ObsID obsID( ObsID::otNavMsg, ObsID::cbL2, ObsID::tcC2LM );
// Test Unsigned Integers
unsigned long u_i1 = 32767;
int u_n1 = 16;
int u_s1 = 1;
unsigned long u_i2 = 1;
int u_n2 = 8;
int u_s2 = 1;
unsigned long u_i3 = 255;
int u_n3 = 8;
int u_s3 = 1;
unsigned long u_i4 = 604500;
int u_n4 = 11;
int u_s4 = 300;
// Test Signed Integers
long s_i1 = 15;
int s_n1 = 5;
int s_s1 = 1;
long s_i2 = -16;
int s_n2 = 5;
int s_s2 = 1;
long s_i3 = -1;
int s_n3 = 5;
int s_s3 = 1;
long s_i4 = 0;
int s_n4 = 6;
int s_s4 = 1;
long s_i5 = 4194304;
int s_n5 = 24;
int s_s5 = 1;
// Test Unsigned Doubles
double d_i1 = 0.490005493;
int d_n1 = 16;
int d_s1 = -16;
double d_i2 = -0.5;
int d_n2 = 16;
int d_s2 = -16;
double d_i3 = 0;
int d_n3 = 16;
int d_s3 = -16;
// Test Signed Doubles
double d_i4 = 32000.0;
int d_n4 = 16;
int d_s4 = 0;
// Test Semi-Circles
double sd_i1 = PI-2*pow(2,-31);
int sd_n1 = 32;
int sd_s1 = -31;
double sd_i2 = -PI;
int sd_n2 = 32;
int sd_s2 = -31;
//Test Data copied from RINEX file for PRN3, week 1638, day 153 2011
double rToe = 388800.0;
int n_rToe = 16;
int s_rToe = 4;
unsigned long riodc = 22;
int n_riodc = 8;
int s_riodc = 1;
unsigned long riode = 22;
int n_riode = 8;
int s_riode = 1;
unsigned long raodo = 10;
int n_raodo = 5;
int s_raodo = 1;
unsigned long rfitInt = 0;
int n_rfitInt = 1;
int s_rfitInt = 1;
double rToc = 388800.0;
int n_rToc = 16;
int s_rToc = 4;
double rCuc = 9.57399606705E-07;
int n_rCuc = 16;
int s_rCuc = -29;
double rCus = 8.35768878460E-06;
int n_rCus = 16;
int s_rCus = -29;
double rCrc = 2.03562500000E+02;
int n_rCrc = 16;
int s_rCrc = -5;
double rCrs = 1.87812500000E+01;
int n_rCrs = 16;
int s_rCrs = -5;
double rCic = -2.30967998505E-07;
int n_rCic = 16;
int s_rCic = -29;
double rCis = 5.02914190292E-08;
int n_rCis = 16;
int s_rCis = -29;
double rM0 = 1.05539162795E+00;
int n_rM0 = 32;
int s_rM0 = -31;
double rdn = 5.39093883996E-09;
int n_rdn = 16;
int s_rdn = -43;
double recc = 1.42575260252E-02;
int n_recc = 32;
int s_recc = -33;
double rAhalf = 5.15365527534E+03;
int n_rAhalf = 32;
int s_rAhalf = -19;
double rOMEGA0 = -2.16947563164E+00;
int n_rOMEGA0 = 32;
int s_rOMEGA0 = -31;
double ri0 = 9.28692497530E-01;
int n_ri0 = 32;
int s_ri0 = -31;
double rw = 1.09154604931E+00;
int n_rw = 32;
int s_rw = -31;
double rOMEGAdot = -8.56285667735E-09;
int n_rOMEGAdot = 24;
int s_rOMEGAdot = -43;
double ridot = 5.52880172536E-10;
int n_ridot = 14;
int s_ridot = -43;
double raf0 = 7.23189674318E-04;
int n_raf0 = 22;
int s_raf0 = -31;
double raf1 = 5.11590769747E-12;
int n_raf1 = 16;
int s_raf1 = -43;
double raf2 = 0.0;
int n_raf2 = 8;
int s_raf2 = -55;
double rTgd = -4.65661287308E-09;
int n_rTgd = 8;
int s_rTgd = -31;
ofstream outf("Logs/PackedNavBits_Output", ios::out);
outf.precision(11);
// First Test Case. Create PNB object.
PackedNavBits pnb;
/* Pack */
pnb.setSatID(satSys);
pnb.setObsID(obsID);
pnb.setTime(TransmitTime);
/* pnb.addUnsignedLong(u_i1, u_n1, u_s1);
pnb.addUnsignedLong(u_i2, u_n2, u_s2);
pnb.addUnsignedLong(u_i3, u_n3, u_s3);
pnb.addUnsignedLong(u_i4, u_n4, u_s4);
pnb.addLong(s_i1, s_n1, s_s1);
pnb.addLong(s_i2, s_n2, s_s2);
pnb.addLong(s_i3, s_n3, s_s3);
pnb.addLong(s_i4, s_n4, s_s4);
pnb.addLong(s_i5, s_n5, s_s5);
pnb.addSignedDouble(d_i1, d_n1, d_s1);
pnb.addSignedDouble(d_i2, d_n2, d_s2);
pnb.addSignedDouble(d_i3, d_n3, d_s3);
pnb.addUnsignedDouble(d_i4, d_n4, d_s4);
pnb.addDoubleSemiCircles(sd_i1, sd_n1, sd_s1);
pnb.addDoubleSemiCircles(sd_i2, sd_n2, sd_s2); */
/* Unpack */
/* outf << endl;
outf << "Unpacked Unsigned Integers:" << endl;
int startbit = 0;
outf << "Number 32767: " << pnb.asUnsignedLong(startbit, u_n1, u_s1) << endl;
startbit += u_n1;
outf << "Number 1: " << pnb.asUnsignedLong(startbit, u_n2, u_s2) << endl;
startbit += u_n2;
outf << "Number 255: " << pnb.asUnsignedLong(startbit, u_n3, u_s3) << endl;
startbit += u_n3;
outf << "Number 604500: " << pnb.asUnsignedLong(startbit, u_n4, u_s4) << endl;
startbit += u_n4;
outf << endl;
outf << "Unpacked Signed Integers: " << endl;
outf << "Number 15: " << pnb.asLong(startbit, s_n1, s_s1) << endl;
startbit += s_n1;
outf << "Number -16: " << pnb.asLong(startbit, s_n2, s_s2) << endl;
startbit += s_n2;
outf << "Number -1: " << pnb.asLong(startbit, s_n3, s_s3) << endl;
startbit += s_n3;
outf << "Number 0: " << pnb.asLong(startbit, s_n4, s_s4) << endl;
startbit += s_n4;
outf << "Number 4194304: " << pnb.asLong(startbit, s_n5, s_s5) << endl;
startbit += s_n5;
outf << endl;
outf << "Unpacked Signed Doubles: " << endl;
outf << "Number 0.490005493: " << pnb.asSignedDouble(startbit, d_n1, d_s1) << endl;
startbit += d_n1;
outf << "Number -0.5: " << pnb.asSignedDouble(startbit, d_n2, d_s2) << endl;
startbit += d_n2;
outf << "Number 0: " << pnb.asSignedDouble(startbit, d_n3, d_s3) << endl;
startbit += d_n3;
outf << endl;
outf << "Unpacked Unsigned Doubles: " << endl;
outf << "Number 32000.0: " << pnb.asUnsignedDouble(startbit, d_n4, d_s4) << endl;
startbit += d_n4;
outf << endl;
outf << "Unpacked Double Semi-Circles: " << endl;
outf << "Number PI: " << pnb.asDoubleSemiCircles(startbit, sd_n1, sd_s1) << endl;
startbit += sd_n1;
outf << "Number -PI: " << pnb.asDoubleSemiCircles(startbit, sd_n2, sd_s2) << endl; */
// Pack legacy nav message data
pnb.addSignedDouble(rTgd, n_rTgd, s_rTgd);
pnb.addUnsignedLong(riodc, n_riodc, s_riodc);
pnb.addUnsignedDouble(rToc, n_rToc, s_rToc);
pnb.addSignedDouble(raf2, n_raf2, s_raf2);
pnb.addSignedDouble(raf1, n_raf1, s_raf1);
pnb.addSignedDouble(raf0, n_raf0, s_raf0);
pnb.addUnsignedLong(riode, n_riode, s_riode);
pnb.addSignedDouble(rCrs, n_rCrs, s_rCrs);
pnb.addDoubleSemiCircles(rdn, n_rdn, s_rdn);
pnb.addDoubleSemiCircles(rM0, n_rM0, s_rM0);
pnb.addSignedDouble(rCuc, n_rCuc, s_rCuc);
pnb.addUnsignedDouble(recc, n_recc, s_recc);
pnb.addSignedDouble(rCus, n_rCus, s_rCus);
pnb.addUnsignedDouble(rAhalf, n_rAhalf, s_rAhalf);
pnb.addUnsignedDouble(rToe, n_rToe, s_rToe);
pnb.addUnsignedLong(rfitInt, n_rfitInt, s_rfitInt);
pnb.addUnsignedLong(raodo, n_raodo, s_raodo);
pnb.addSignedDouble(rCic, n_rCic, s_rCic);
pnb.addDoubleSemiCircles(rOMEGA0, n_rOMEGA0, s_rOMEGA0);
pnb.addSignedDouble(rCis, n_rCis, s_rCis);
pnb.addDoubleSemiCircles(ri0, n_ri0, s_ri0);
pnb.addSignedDouble(rCrc, n_rCrc, s_rCrc);
pnb.addDoubleSemiCircles(rw, n_rw, s_rw);
pnb.addDoubleSemiCircles(rOMEGAdot, n_rOMEGAdot, s_rOMEGAdot);
pnb.addUnsignedLong(riode, n_riode, s_riode);
pnb.addDoubleSemiCircles(ridot, n_ridot, s_ridot);
// Unpack the legacy nav message data and get back the results in engineering terms
// Test Data copied from RINEX file for PRN3, week 1638, day 153 2011
int startbit = 0;
outf << "Tgd: " << pnb.asSignedDouble(startbit, n_rTgd, s_rTgd) << endl;
startbit += n_rTgd;
outf << "IODC: " << pnb.asUnsignedLong(startbit, n_riodc, s_riodc) << endl;
startbit += n_riodc;
outf << "Toc: " << pnb.asUnsignedDouble(startbit, n_rToc, s_rToc) << endl;
startbit += n_rToc;
outf << "af2: " << pnb.asSignedDouble(startbit, n_raf2, s_raf2) << endl;
startbit += n_raf2;
outf << "af1: " << pnb.asSignedDouble(startbit, n_raf1, s_raf1) << endl;
startbit += n_raf1;
outf << "af0: " << pnb.asSignedDouble(startbit, n_raf0, s_raf0) << endl;
startbit += n_raf0;
outf << "IODE: " << pnb.asUnsignedLong(startbit, n_riode, s_riode) << endl;
startbit += n_riode;
outf << "Crs: " << pnb.asSignedDouble(startbit, n_rCrs, s_rCrs) << endl;
startbit += n_rCrs;
outf << "dn: " << pnb.asDoubleSemiCircles(startbit, n_rdn, s_rdn) << endl;
startbit += n_rdn;
outf << "M0: " << pnb.asDoubleSemiCircles(startbit, n_rM0, s_rM0) << endl;
startbit += n_rM0;
outf << "Cuc: " << pnb.asSignedDouble(startbit, n_rCuc, s_rCuc) << endl;
startbit += n_rCuc;
outf << "ecc: " << pnb.asUnsignedDouble(startbit, n_recc, s_recc) << endl;
startbit += n_recc;
outf << "Cus: " << pnb.asSignedDouble(startbit, n_rCus, s_rCus) << endl;
startbit += n_rCus;
outf << "Ahalf: " << pnb.asUnsignedDouble(startbit, n_rAhalf, s_rAhalf) << endl;
startbit += n_rAhalf;
outf << "Toe: " << pnb.asUnsignedDouble(startbit, n_rToe, s_rToe) << endl;
startbit += n_rToe;
outf << "fitInt: " << pnb.asUnsignedLong(startbit, n_rfitInt, s_rfitInt) << endl;
startbit += n_rfitInt;
outf << "AODO: " << pnb.asUnsignedLong(startbit, n_raodo, s_raodo) << endl;
startbit += n_raodo;
outf << "Cic: " << pnb.asSignedDouble(startbit, n_rCic, s_rCic) << endl;
startbit += n_rCic;
outf << "OMEGA0: " << pnb.asDoubleSemiCircles(startbit, n_rOMEGA0, s_rOMEGA0) << endl;
startbit += n_rOMEGA0;
outf << "Cis: " << pnb.asSignedDouble(startbit, n_rCis, s_rCis) << endl;
startbit += n_rCis;
outf << "i0: " << pnb.asDoubleSemiCircles(startbit, n_ri0, s_ri0) << endl;
startbit += n_ri0;
outf << "Crc: " << pnb.asSignedDouble(startbit, n_rCrc, s_rCrc) << endl;
startbit += n_rCrc;
outf << "w: " << pnb.asDoubleSemiCircles(startbit, n_rw, s_rw) << endl;
startbit += n_rw;
outf << "OMEGAdot: " << pnb.asDoubleSemiCircles(startbit, n_rOMEGAdot, s_rOMEGAdot) << endl;
startbit += n_rOMEGAdot;
outf << "IODE: " << pnb.asUnsignedLong(startbit, n_riode, s_riode) << endl;
startbit += n_riode;
outf << "idot: " << pnb.asDoubleSemiCircles(startbit, n_ridot, s_ridot) << endl;
outf << endl;
outf << "Time of Transmission: " << pnb.getTransmitTime() << endl;
outf << "Time of Transmission pnb: " << GPSWeekSecond(pnb.getTransmitTime()).printf("%F, %g") << endl;
/* Resize the vector holding the packed nav message data. */
pnb.trimsize();
outf << endl;
outf << "PNB object dump:" << endl;
outf << pnb << endl;
CPPUNIT_ASSERT(fileEqualTest((char*)"Logs/PackedNavBits_Truth",(char*)"Logs/PackedNavBits_Output"));
}
bool xPackedNavBitsgpsNavMsg :: fileEqualTest (char* handle1, char* handle2)
{
bool isEqual = false;
ifstream File1;
ifstream File2;
std::string File1Line;
std::string File2Line;
File1.open(handle1);
File2.open(handle2);
while (!File1.eof())
{
if (File2.eof())
return isEqual;
getline (File1, File1Line);
getline (File2, File2Line);
if (File1Line != File2Line)
return isEqual;
}
if (!File2.eof())
return isEqual;
else
return isEqual = true;
}
| lgpl-2.1 |
hal/core | gui/src/main/java/org/jboss/as/console/client/shared/jvm/Jvm.java | 2188 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.console.client.shared.jvm;
import org.jboss.as.console.client.widgets.forms.Binding;
import java.util.List;
/**
* @author Heiko Braun
* @date 4/20/11
*/
public interface Jvm {
@Binding(detypedName = "none", skip = true)
String getName();
void setName(String name);
@Binding(detypedName = "debug-enabled")
boolean isDebugEnabled();
void setDebugEnabled(boolean b);
@Binding(detypedName = "debug-options")
String getDebugOptions();
void setDebugOptions(String options);
@Binding(detypedName = "heap-size")
String getHeapSize();
void setHeapSize(String heap);
@Binding(detypedName = "max-heap-size")
String getMaxHeapSize();
void setMaxHeapSize(String maxHeap);
@Binding(detypedName = "permgen-size")
String getPermgen();
void setPermgen(String permgen);
@Binding(detypedName = "max-permgen-size")
String getMaxPermgen();
void setMaxPermgen(String maxPermgen);
@Binding(skip = true)
boolean isInherited();
void setInherited(boolean inherited);
@Binding(detypedName = "jvm-options", listType="java.lang.String")
List<String> getOptions();
void setOptions(List<String> options);
}
| lgpl-2.1 |
roboidstudio/embedded | org.roboid.audio/src/org/xiph/speex/LbrLspQuant.java | 6677 | /******************************************************************************
* *
* Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. *
* *
* COPYRIGHT: *
* This software is the property of Wimba S.A. *
* This software is redistributed under the Xiph.org variant of *
* the BSD license. *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* - Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* - Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* - Neither the name of Wimba, the Xiph.org Foundation nor the names of *
* its contributors may be used to endorse or promote products derived *
* from this software without specific prior written permission. *
* *
* WARRANTIES: *
* This software is made available by the authors in the hope *
* that it will be useful, but without any warranty. *
* Wimba S.A. is not liable for any consequence related to the *
* use of the provided software. *
* *
* Class: LbrLU.java *
* *
* Author: James LAWRENCE *
* Modified by: Marc GIMPEL *
* Based on code by: Jean-Marc VALIN *
* *
* Date: March 2003 *
* *
******************************************************************************/
/* $Id: LbrLspQuant.java,v 1.1 2009/12/11 18:36:01 robomation Exp $ */
/* Copyright (C) 2002 Jean-Marc Valin
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.xiph.speex;
/**
* LSP Quantisation and Unquantisation (Lbr)
*
* @author Jim Lawrence, helloNetwork.com
* @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com)
* @version $Revision: 1.1 $
*/
public class LbrLspQuant
extends LspQuant
{
/**
* Line Spectral Pair Quantification (Lbr).
* @param lsp - Line Spectral Pairs table.
* @param qlsp - Quantified Line Spectral Pairs table.
* @param order
* @param bits - Speex bits buffer.
*/
public final void quant(final float[] lsp,
final float[] qlsp,
final int order,
final Bits bits)
{
int i;
float tmp1, tmp2;
int id;
float[] quant_weight = new float[MAX_LSP_SIZE];
for (i=0;i<order;i++)
qlsp[i]=lsp[i];
quant_weight[0] = 1/(qlsp[1]-qlsp[0]);
quant_weight[order-1] = 1/(qlsp[order-1]-qlsp[order-2]);
for (i=1;i<order-1;i++) {
tmp1 = 1/((.15f+qlsp[i]-qlsp[i-1])*(.15f+qlsp[i]-qlsp[i-1]));
tmp2 = 1/((.15f+qlsp[i+1]-qlsp[i])*(.15f+qlsp[i+1]-qlsp[i]));
quant_weight[i] = tmp1 > tmp2 ? tmp1 : tmp2;
}
for (i=0;i<order;i++)
qlsp[i]-=(.25*i+.25);
for (i=0;i<order;i++)
qlsp[i]*=256;
id = lsp_quant(qlsp, 0, cdbk_nb, NB_CDBK_SIZE, order);
bits.pack(id, 6);
for (i=0;i<order;i++)
qlsp[i]*=2;
id = lsp_weight_quant(qlsp, 0, quant_weight, 0, cdbk_nb_low1, NB_CDBK_SIZE_LOW1, 5);
bits.pack(id, 6);
id = lsp_weight_quant(qlsp, 5, quant_weight, 5, cdbk_nb_high1, NB_CDBK_SIZE_HIGH1, 5);
bits.pack(id, 6);
for (i=0;i<order;i++)
qlsp[i]*=0.0019531;
for (i=0;i<order;i++)
qlsp[i]=lsp[i]-qlsp[i];
}
/**
* Line Spectral Pair Unquantification (Lbr).
* @param lsp - Line Spectral Pairs table.
* @param order
* @param bits - Speex bits buffer.
*/
public final void unquant(final float[] lsp,
final int order,
final Bits bits)
{
for (int i=0;i<order;i++){
lsp[i]=.25f*i+.25f;
}
unpackPlus(lsp, cdbk_nb, bits, 0.0039062f, 10, 0);
unpackPlus(lsp, cdbk_nb_low1, bits, 0.0019531f, 5, 0);
unpackPlus(lsp, cdbk_nb_high1, bits, 0.0019531f, 5, 5);
}
}
| lgpl-2.1 |
ioef/tlslite-ng | tlslite/utils/python_aes.py | 2163 | # Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
"""Pure-Python AES implementation."""
from .cryptomath import *
import time
from .aes import *
from .rijndael import rijndael
def new(key, mode, IV):
return Python_AES(key, mode, IV)
class Python_AES(AES):
def __init__(self, key, mode, IV):
AES.__init__(self, key, mode, IV, "python")
self.rijndael = rijndael(key, 16)
self.IV = IV
def encrypt(self, plaintext):
AES.encrypt(self, plaintext)
plaintextBytes = plaintext[:]
chainBytes = self.IV[:]
encrypt = self.rijndael.encrypt
starttime = time.clock()
#CBC Mode: For each block...
for x in xrange(len(plaintextBytes)//16):
#XOR with the chaining block
blockBytes = plaintextBytes[x*16 : (x*16)+16]
for y in xrange(16):
blockBytes[y] ^= chainBytes[y]
#Encrypt it
encryptedBytes = encrypt(blockBytes)
#Overwrite the input with the output
for y in xrange(16):
plaintextBytes[(x*16)+y] = encryptedBytes[y]
#Set the next chaining block
chainBytes = encryptedBytes
self.IV = chainBytes[:]
return plaintextBytes
def decrypt(self, ciphertext):
AES.decrypt(self, ciphertext)
ciphertextBytes = ciphertext[:]
chainBytes = self.IV[:]
decrypt = self.rijndael.decrypt
#CBC Mode: For each block...
for x in xrange(len(ciphertextBytes)//16):
#Decrypt it
blockBytes = ciphertextBytes[x*16 : (x*16)+16]
decryptedBytes = decrypt(blockBytes)
#XOR with the chaining block and overwrite the input with output
for y in xrange(16):
decryptedBytes[y] ^= chainBytes[y]
ciphertextBytes[(x*16)+y] = decryptedBytes[y]
#Set the next chaining block
chainBytes = blockBytes
self.IV = chainBytes[:]
return ciphertextBytes
| lgpl-2.1 |
alexmcbride/insimdotnet | InSimDotNet/InitializeEventArgs.cs | 768 | using System;
namespace InSimDotNet {
/// <summary>
/// Provides data for the <see cref="InSim"/> initialized event.
/// </summary>
public class InitializeEventArgs : EventArgs {
/// <summary>
/// Gets the settings used to initialize the connection with LFS.
/// </summary>
public ReadOnlyInSimSettings Settings { get; private set; }
/// <summary>
/// Creates a new instance of the <see cref="InitializeEventArgs"/> object.
/// </summary>
/// <param name="settings">The InSim settings used to initialize the connection with LFS.</param>
public InitializeEventArgs(ReadOnlyInSimSettings settings) {
this.Settings = settings;
}
}
}
| lgpl-2.1 |
kobolabs/qt-everywhere-opensource-src-4.6.2 | doc/src/snippets/i18n-non-qt-class/main.cpp | 2250 | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore>
#include "myclass.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QTranslator translator;
translator.load(":/translations/i18n-non-qt-class_" + QLocale::system().name());
app.installTranslator(&translator);
MyClass instance;
return 0;
}
| lgpl-2.1 |
regnirpsj/dcs08961 | src/lib/platform/window/manager.cpp | 6317 | // -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2015 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : platform/window/manager.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// include i/f header
#include "platform/window/manager.hpp"
// includes, system
#include <algorithm> // std::find<>
#include <ostream> // std::ostream
// includes, project
#include <support/io_utils.hpp>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
namespace platform {
namespace window {
class manager::window_compare {
public:
explicit window_compare(id_type a, base const* b)
: id_ (a),
inst_(b)
{
TRACE_NEVER("platform::window::manager::window_compare::window_compare");
}
bool operator()(window_id_list_type::value_type const& a) const
{
TRACE_NEVER("platform::window::manager::window_compare::operator()");
bool result(false);
if ((-1 != id_) && inst_) {
result = (a.first == id_) && (a.second == inst_);
} else if (-1 != id_) {
result = (a.first == id_);
} else if (nullptr != inst_) {
result = (a.second == inst_);
}
return result;
}
private:
id_type const id_;
base const* inst_;
};
size_t
manager::window_type_hasher::operator()(manager::window_type const& a) const
{
TRACE_NEVER("platform::window::manager::window_type_hasher::operator()");
return static_cast<size_t>(a);
}
} // namespace window {
} // namespace platform {
namespace platform {
namespace window {
// variables, exported
/* static */ manager::window_type_map_type manager::window_type_map_;
// functions, exported
/* static */ unsigned
manager::count()
{
TRACE("platform::window::manager::count");
unsigned result(0);
for (auto m : window_type_map_) {
result += unsigned(m.second.size());
}
return result;
}
/* static */ unsigned
manager::count(window_type a)
{
TRACE("platform::window::manager::count(window_type)");
return unsigned(window_type_map_[a].size());
}
/* static */ void
manager::print_on(std::ostream& os)
{
TRACE_NEVER("platform::window::manager::print_on");
os << '[';
for (auto m : window_type_map_) {
using support::ostream::operator<<;
os << m.first << ':' << m.second;
}
os << ']';
}
/* static */ bool
manager::add(window_type a, id_type b, base* c)
{
TRACE("platform::window::manager::add");
return window_type_map_[a].insert(std::make_pair(b, c)).second;
}
/* static */ bool
manager::sub(window_type a, base* b)
{
TRACE("platform::window::manager::sub(base*)");
bool result(false);
auto found (std::find_if(window_type_map_[a].begin(),
window_type_map_[a].end(),
window_compare(-1, b)));
if (window_type_map_[a].end() != found) {
window_type_map_[a].erase(found);
result = true;
}
return result;
}
/* static */ bool
manager::sub(window_type a, id_type b)
{
TRACE("platform::window::manager::sub(id_type)");
bool result(false);
auto found (std::find_if(window_type_map_[a].begin(),
window_type_map_[a].end(),
window_compare(b, nullptr)));
if (window_type_map_[a].end() != found) {
window_type_map_[a].erase(found);
result = true;
}
return result;
}
/* static */ base*
manager::get(window_type a, id_type b)
{
TRACE("platform::window::manager::get");
base* result(nullptr);
auto found(std::find_if(window_type_map_[a].begin(),
window_type_map_[a].end(),
window_compare(b, nullptr)));
if (window_type_map_[a].end() != found) {
result = found->second;
}
return result;
}
/* static */ std::vector<manager::id_type>
manager::all(window_type a)
{
TRACE("platform::window::manager::all:" + std::to_string(window_type_map_[a].size()));
std::vector<id_type> result;
for (auto w : window_type_map_[a]) {
result.push_back(w.first);
}
return result;
}
std::ostream&
operator<<(std::ostream& os, manager::window_type const& a)
{
TRACE_NEVER("platform::window::operator<<(manager::window_type)");
std::ostream::sentry const cerberus(os);
if (cerberus) {
switch (a) {
case manager::window_type::glut: os << "GLUT"; break;
case manager::window_type::glx: os << "GLX"; break;
case manager::window_type::win32: os << "Win32"; break;
case manager::window_type::winrt: os << "WinRT"; break;
}
}
return os;
}
} // namespace window {
} // namespace platform {
| lgpl-2.1 |
jbarriosc/ACSUFRO | LGPL/CommonSoftware/acspycommon/src/Acspy/Util/NameTree.py | 6439 | # @(#) $Id: NameTree.py,v 1.1.1.1 2012/03/07 17:40:45 acaproni Exp $
__revision__ = "$Id: NameTree.py,v 1.1.1.1 2012/03/07 17:40:45 acaproni Exp $"
'''
TODO:
- missing lots of inline doc here
- ???
'''
from Acspy.Util.ACSCorba import nameService
from Acspy.Util import NodeList
import CosNaming
import string
import sys
from traceback import print_exc
#
# extensions added to the different object types in the name service
#
extensions = {
'ROProperty':'rop',
'RWProperty':'rwp',
'Device':'dev',
'Service':'srv'
}
#
# getnode - used by many local routines to resolve and narrow
# the node and return a context.
#
def getnode (node, wd):
ctx = None
try:
obj = wd.resolve(node)
try:
ctx = obj._narrow(CosNaming.NamingContext)
except:
ctx = None
except:
pass
return ctx
#
# keep a directory tree without any cycles
#
class nameTree:
def __init__(self, corba_object, nameServerName=''):
# get reference to name service
ns_obj = nameService()
if (ns_obj is None):
print "name service bad resolve"
return
self.top = ns_obj._narrow(CosNaming.NamingContext)
self.path = [('',self.top)] # keep track of where we are
self.pathcopy = []
#
# ls ()
#
def ls (self): # pragma: NO COVER
(n, cwd) = self.path[-1]
nl = NodeList.nodeList(cwd)
nl.ls()
#
# listdir ()
#
def listdir (self): # pragma: NO COVER
(n, cwd) = self.path[-1]
nl = NodeList.nodeList(cwd)
return nl.listdir()
#
# mkdir (path)
#
def mkdir (self, path):
#
# path can be relative or absolute. This is determined
# by the leading /
#
# break path into parts by the /
#
nodes = string.splitfields(path,'/')
wd = None
if (nodes[0] == ''):
wd = self.top
del nodes[0]
else:
(n, wd) = self.path[-1]
for name in nodes:
# try to resolve the name, if it fails, jump out and
# start creating contexts
node = [CosNaming.NameComponent (name,"")]
nextwd = getnode (node , wd)
if (nextwd is None):
try:
nextwd = wd.bind_new_context (node) #
except:
print "Error binding new context for ", name, "!!!", sys.exc_info()[0]
return
wd = nextwd
#
# cd (path)
#
def cd (self, path, ignore_error=0):
nodes = string.splitfields(path,'/')
# check for "../../xxx" addresses
if (nodes[0] == '..'):
while (nodes != [] and self.path != [] and nodes[0] == '..'):
(x,y) = self.path[len(self.path)-1]
if(x == '/'): break
del nodes[0]
del self.path[len(self.path)-1]
# reached the directory top, fix self.path
if ((nodes != [] and nodes[0] == '')
or len(self.path) == 0): # absolute, search from the top
self.path = [('', self.top)]
(n, wd) = self.path[len(self.path)-1]
changed = 1
changes = []
for name in nodes:
if (name == ''): continue
wd = getnode ([CosNaming.NameComponent (name,"")], wd)
if (wd is not None):
changes.append ((name, wd))
continue
if (ignore_error == 0):
changed = 0
return 0
if (changed == 1):
self.path = self.path + changes
return 1
#
# getObject (name, type) - return CORBA::Object()
#
def getObject (self, name, type):
"this does not handle absolute or relative path, just cwd"
(n, cwd) = self.path[-1]
leaf = [CosNaming.NameComponent (name, type)]
try: return cwd.resolve (leaf)
except CosNaming.NamingContext.NotFound:
raise
except:
print 'name service error resolving ', self.path, name, type
print sys.exc_info()
#
# putObject (name, object) - put CORBA::Object() at this
# name. If name does not exist, make it. If no object, then
# make a placeholder
#
def putObject (self, name, type, object): # pragma: NO COVER
"this does not handle absolute or relative path, just cwd"
# first just try a rebind() if that fails, then see if
# path and name. If it is a path, then check the path
# and make it if needed. Then try a bind.
(n, cwd) = self.path[-1]
leaf = [CosNaming.NameComponent (name, type)]
return cwd.rebind (leaf, object)
#
# putObject (name, object) - put CORBA::Object() at this
# name. If name does not exist, make it. If no object, then
# make a placeholder
#
def delObject (self, name, type): # pragma: NO COVER
"this does not handle absolute or relative path, just cwd"
# Unbind something.
(n, cwd) = self.path[-1]
leaf = [CosNaming.NameComponent (name, type)]
cwd.unbind (leaf)
return
#
# pwd()
#
def pwd (self):
wd = ''
for (x, y) in self.path:
if x == '': continue
wd = wd + '/' + x
return wd
#
# rm()
#
def rm (self, name, args="noforce"): # pragma: NO COVER
# pushd this directory, cd to other directory less last name,
# get the objet for last name, and if it is a context, check
# force flag. if it is to go, follow the directory tree and
# toss all the links
if (args == "noforce"): return
return
#
# cp()
#
def cp (self, name): # pragma: NO COVER
return
#
# pushd()
#
def pushd (self, l=""): # pragma: NO COVER
if (l == "?"):
i = 0
for path in self.pathcopy:
s = ''
for (n, ctx) in path:
s = s + '/' + n
print "%02d: %s" %(i, s)
i = i + 1
else:
self.pathcopy.append(self.path)
return
#
# popd()
#
def popd (self, index=-1): # pragma: NO COVER
try:
self.path = self.pathcopy.pop(index)
except:
print "top of list, no pop"
return
if (__name__ == "__main__"): # pragma: NO COVER
print '==> Testing nameTree class'
testlevel = 0
nt = nameTree(None)
print '==> Naming service variable name is: nt'
print '==> Listing entries in Naming Service:'
nt.ls ()
# It seems this does not work
print '==> PWD: ', nt.pwd ()
if (testlevel > 0):
nt.pushd ()
nt.cd ("/")
nt.pushd ()
nt.cd ("/cat")
nt.pushd()
nt.pushd ("?")
print '==> cd into MOUNT1.0'
# Nothing happens here
nt.cd("MOUNT1.0")
nt.ls ()
# nt.cd("Antenna Systems/Services/Cryogenics")
# obj = nt.getObject("Status","rwp")
# from acs.baci import ESO
# status = obj._narrow(ESO.ROlong)
# print 'status at status'
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/emops/cascade/C1.java | 977 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.emops.cascade;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class C1 {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
private int id;
@ManyToOne( fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST} )
@JoinColumn( name = "b1Id" )
private B1 b1;
public B1 getB1() {
return b1;
}
public void setB1(B1 b1) {
this.b1 = b1;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| lgpl-2.1 |
richardmg/qtcreator | src/plugins/bineditor/bineditorplugin.cpp | 17708 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "bineditorplugin.h"
#include "bineditor.h"
#include "bineditorconstants.h"
#include <coreplugin/icore.h>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QRegExp>
#include <QVariant>
#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QRegExpValidator>
#include <QToolBar>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/id.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/idocument.h>
#include <coreplugin/mimedatabase.h>
#include <extensionsystem/pluginmanager.h>
#include <find/ifindsupport.h>
#include <utils/reloadpromptutils.h>
#include <utils/qtcassert.h>
using namespace BINEditor;
using namespace BINEditor::Internal;
class BinEditorFind : public Find::IFindSupport
{
Q_OBJECT
public:
BinEditorFind(BinEditorWidget *widget)
{
m_widget = widget;
m_incrementalStartPos = m_contPos = -1;
m_incrementalWrappedState = false;
}
bool supportsReplace() const { return false; }
QString currentFindString() const { return QString(); }
QString completedFindString() const { return QString(); }
Find::FindFlags supportedFindFlags() const
{
return Find::FindBackward | Find::FindCaseSensitively;
}
void resetIncrementalSearch()
{
m_incrementalStartPos = m_contPos = -1;
m_incrementalWrappedState = false;
}
virtual void highlightAll(const QString &txt, Find::FindFlags findFlags)
{
m_widget->highlightSearchResults(txt.toLatin1(), Find::textDocumentFlagsForFindFlags(findFlags));
}
void clearResults()
{
m_widget->highlightSearchResults(QByteArray());
}
int find(const QByteArray &pattern, int pos, Find::FindFlags findFlags, bool *wrapped)
{
if (wrapped)
*wrapped = false;
if (pattern.isEmpty()) {
m_widget->setCursorPosition(pos);
return pos;
}
int res = m_widget->find(pattern, pos, Find::textDocumentFlagsForFindFlags(findFlags));
if (res < 0) {
pos = (findFlags & Find::FindBackward) ? -1 : 0;
res = m_widget->find(pattern, pos, Find::textDocumentFlagsForFindFlags(findFlags));
if (res < 0)
return res;
if (wrapped)
*wrapped = true;
}
return res;
}
Result findIncremental(const QString &txt, Find::FindFlags findFlags) {
QByteArray pattern = txt.toLatin1();
if (pattern != m_lastPattern)
resetIncrementalSearch(); // Because we don't search for nibbles.
m_lastPattern = pattern;
if (m_incrementalStartPos < 0)
m_incrementalStartPos = m_widget->selectionStart();
if (m_contPos == -1)
m_contPos = m_incrementalStartPos;
bool wrapped;
int found = find(pattern, m_contPos, findFlags, &wrapped);
if (wrapped != m_incrementalWrappedState && (found >= 0)) {
m_incrementalWrappedState = wrapped;
showWrapIndicator(m_widget);
}
Result result;
if (found >= 0) {
result = Found;
m_widget->highlightSearchResults(pattern, Find::textDocumentFlagsForFindFlags(findFlags));
m_contPos = -1;
} else {
if (found == -2) {
result = NotYetFound;
m_contPos +=
findFlags & Find::FindBackward
? -BinEditorWidget::SearchStride : BinEditorWidget::SearchStride;
} else {
result = NotFound;
m_contPos = -1;
m_widget->highlightSearchResults(QByteArray(), 0);
}
}
return result;
}
Result findStep(const QString &txt, Find::FindFlags findFlags) {
QByteArray pattern = txt.toLatin1();
bool wasReset = (m_incrementalStartPos < 0);
if (m_contPos == -1) {
m_contPos = m_widget->cursorPosition();
if (findFlags & Find::FindBackward)
m_contPos = m_widget->selectionStart()-1;
}
bool wrapped;
int found = find(pattern, m_contPos, findFlags, &wrapped);
if (wrapped)
showWrapIndicator(m_widget);
Result result;
if (found >= 0) {
result = Found;
m_incrementalStartPos = found;
m_contPos = -1;
if (wasReset)
m_widget->highlightSearchResults(pattern, Find::textDocumentFlagsForFindFlags(findFlags));
} else if (found == -2) {
result = NotYetFound;
m_contPos += findFlags & Find::FindBackward
? -BinEditorWidget::SearchStride : BinEditorWidget::SearchStride;
} else {
result = NotFound;
m_contPos = -1;
}
return result;
}
private:
BinEditorWidget *m_widget;
int m_incrementalStartPos;
int m_contPos; // Only valid if last result was NotYetFound.
bool m_incrementalWrappedState;
QByteArray m_lastPattern;
};
class BinEditorDocument : public Core::IDocument
{
Q_OBJECT
public:
BinEditorDocument(BinEditorWidget *parent) :
Core::IDocument(parent)
{
m_widget = parent;
connect(m_widget, SIGNAL(dataRequested(quint64)),
this, SLOT(provideData(quint64)));
connect(m_widget, SIGNAL(newRangeRequested(quint64)),
this, SLOT(provideNewRange(quint64)));
}
~BinEditorDocument() {}
QString mimeType() const {
return QLatin1String(Constants::C_BINEDITOR_MIMETYPE);
}
bool setContents(const QByteArray &contents)
{
if (!contents.isEmpty())
return false;
m_widget->clear();
return true;
}
bool save(QString *errorString, const QString &fn, bool autoSave)
{
QTC_ASSERT(!autoSave, return true); // bineditor does not support autosave - it would be a bit expensive
const QString fileNameToUse
= fn.isEmpty() ? filePath() : fn;
if (m_widget->save(errorString, filePath(), fileNameToUse)) {
setFilePath(fileNameToUse);
return true;
} else {
return false;
}
}
bool open(QString *errorString, const QString &fileName, quint64 offset = 0) {
QFile file(fileName);
quint64 size = static_cast<quint64>(file.size());
if (size == 0 && !fileName.isEmpty()) {
QString msg = tr("The Binary Editor cannot open empty files.");
if (errorString)
*errorString = msg;
else
QMessageBox::critical(Core::ICore::mainWindow(), tr("File Error"), msg);
return false;
}
if (offset >= size)
return false;
if (file.open(QIODevice::ReadOnly)) {
file.close();
setFilePath(fileName);
m_widget->setSizes(offset, file.size());
return true;
}
QString errStr = tr("Cannot open %1: %2").arg(
QDir::toNativeSeparators(fileName), file.errorString());
if (errorString)
*errorString = errStr;
else
QMessageBox::critical(Core::ICore::mainWindow(), tr("File Error"), errStr);
return false;
}
private slots:
void provideData(quint64 block)
{
const QString fn = filePath();
if (fn.isEmpty())
return;
QFile file(fn);
if (file.open(QIODevice::ReadOnly)) {
int blockSize = m_widget->dataBlockSize();
file.seek(block * blockSize);
QByteArray data = file.read(blockSize);
file.close();
const int dataSize = data.size();
if (dataSize != blockSize)
data += QByteArray(blockSize - dataSize, 0);
m_widget->addData(block, data);
} else {
QMessageBox::critical(Core::ICore::mainWindow(), tr("File Error"),
tr("Cannot open %1: %2").arg(
QDir::toNativeSeparators(fn), file.errorString()));
}
}
void provideNewRange(quint64 offset)
{
open(0, filePath(), offset);
}
public:
QString defaultPath() const { return QString(); }
QString suggestedFileName() const { return QString(); }
bool isModified() const { return isTemporary()/*e.g. memory view*/ ? false
: m_widget->isModified(); }
bool isFileReadOnly() const {
const QString fn = filePath();
if (fn.isEmpty())
return false;
const QFileInfo fi(fn);
return !fi.isWritable();
}
bool isSaveAsAllowed() const { return true; }
bool reload(QString *errorString, ReloadFlag flag, ChangeType type) {
if (flag == FlagIgnore)
return true;
if (type == TypePermissions) {
emit changed();
} else {
emit aboutToReload();
const bool success = open(errorString, filePath());
emit reloadFinished(success);
return success;
}
return true;
}
private:
BinEditorWidget *m_widget;
};
class BinEditor : public Core::IEditor
{
Q_OBJECT
public:
BinEditor(BinEditorWidget *widget)
{
setWidget(widget);
m_widget = widget;
m_file = new BinEditorDocument(m_widget);
m_context.add(Core::Constants::K_DEFAULT_BINARY_EDITOR_ID);
m_context.add(Constants::C_BINEDITOR);
m_addressEdit = new QLineEdit;
QRegExpValidator * const addressValidator
= new QRegExpValidator(QRegExp(QLatin1String("[0-9a-fA-F]{1,16}")),
m_addressEdit);
m_addressEdit->setValidator(addressValidator);
QHBoxLayout *l = new QHBoxLayout;
QWidget *w = new QWidget;
l->setMargin(0);
l->setContentsMargins(0, 0, 5, 0);
l->addStretch(1);
l->addWidget(m_addressEdit);
w->setLayout(l);
m_toolBar = new QToolBar;
m_toolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
m_toolBar->addWidget(w);
widget->setEditor(this);
connect(m_widget, SIGNAL(cursorPositionChanged(int)), SLOT(updateCursorPosition(int)));
connect(m_addressEdit, SIGNAL(editingFinished()), SLOT(jumpToAddress()));
connect(m_widget, SIGNAL(modificationChanged(bool)), m_file, SIGNAL(changed()));
updateCursorPosition(m_widget->cursorPosition());
}
~BinEditor() {
delete m_widget;
}
bool open(QString *errorString, const QString &fileName, const QString &realFileName) {
QTC_ASSERT(fileName == realFileName, return false); // The bineditor can do no autosaving
return m_file->open(errorString, fileName);
}
Core::IDocument *document() { return m_file; }
Core::Id id() const { return Core::Id(Core::Constants::K_DEFAULT_BINARY_EDITOR_ID); }
QWidget *toolBar() { return m_toolBar; }
private slots:
void updateCursorPosition(int position) {
m_addressEdit->setText(QString::number(m_widget->baseAddress() + position, 16));
}
void jumpToAddress() {
m_widget->jumpToAddress(m_addressEdit->text().toULongLong(0, 16));
updateCursorPosition(m_widget->cursorPosition());
}
private:
BinEditorWidget *m_widget;
BinEditorDocument *m_file;
QToolBar *m_toolBar;
QLineEdit *m_addressEdit;
};
///////////////////////////////// BinEditorFactory //////////////////////////////////
BinEditorFactory::BinEditorFactory(BinEditorPlugin *owner) :
m_owner(owner)
{
setId(Core::Constants::K_DEFAULT_BINARY_EDITOR_ID);
setDisplayName(qApp->translate("OpenWith::Editors", Constants::C_BINEDITOR_DISPLAY_NAME));
addMimeType(Constants::C_BINEDITOR_MIMETYPE);
}
Core::IEditor *BinEditorFactory::createEditor(QWidget *parent)
{
BinEditorWidget *widget = new BinEditorWidget(parent);
BinEditor *editor = new BinEditor(widget);
m_owner->initializeEditor(widget);
return editor;
}
/*!
\class BINEditor::BinEditorWidgetFactory
\brief The BinEditorWidgetFactory class offers a service registered with
PluginManager to create bin editor widgets for plugins
without direct linkage.
\sa ExtensionSystem::PluginManager::getObjectByClassName, ExtensionSystem::invoke
*/
BinEditorWidgetFactory::BinEditorWidgetFactory(QObject *parent) :
QObject(parent)
{
}
QWidget *BinEditorWidgetFactory::createWidget(QWidget *parent)
{
return new BinEditorWidget(parent);
}
///////////////////////////////// BinEditorPlugin //////////////////////////////////
BinEditorPlugin::BinEditorPlugin()
{
m_undoAction = m_redoAction = m_copyAction = m_selectAllAction = 0;
}
BinEditorPlugin::~BinEditorPlugin()
{
}
QAction *BinEditorPlugin::registerNewAction(Core::Id id, const QString &title)
{
QAction *result = new QAction(title, this);
Core::ActionManager::registerAction(result, id, m_context);
return result;
}
QAction *BinEditorPlugin::registerNewAction(Core::Id id,
QObject *receiver,
const char *slot,
const QString &title)
{
QAction *rc = registerNewAction(id, title);
if (!rc)
return 0;
connect(rc, SIGNAL(triggered()), receiver, slot);
return rc;
}
void BinEditorPlugin::initializeEditor(BinEditorWidget *widget)
{
m_context.add(Constants::C_BINEDITOR);
if (!m_undoAction) {
m_undoAction = registerNewAction(Core::Constants::UNDO, this, SLOT(undoAction()), tr("&Undo"));
m_redoAction = registerNewAction(Core::Constants::REDO, this, SLOT(redoAction()), tr("&Redo"));
m_copyAction = registerNewAction(Core::Constants::COPY, this, SLOT(copyAction()));
m_selectAllAction = registerNewAction(Core::Constants::SELECTALL, this, SLOT(selectAllAction()));
}
QObject::connect(widget, SIGNAL(undoAvailable(bool)), this, SLOT(updateActions()));
QObject::connect(widget, SIGNAL(redoAvailable(bool)), this, SLOT(updateActions()));
Aggregation::Aggregate *aggregate = new Aggregation::Aggregate;
BinEditorFind *binEditorFind = new BinEditorFind(widget);
aggregate->add(binEditorFind);
aggregate->add(widget);
}
bool BinEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(updateCurrentEditor(Core::IEditor*)));
addAutoReleasedObject(new BinEditorFactory(this));
addAutoReleasedObject(new BinEditorWidgetFactory);
return true;
}
void BinEditorPlugin::extensionsInitialized()
{
}
void BinEditorPlugin::updateCurrentEditor(Core::IEditor *editor)
{
BinEditorWidget *binEditor = 0;
if (editor)
binEditor = qobject_cast<BinEditorWidget *>(editor->widget());
if (m_currentEditor == binEditor)
return;
m_currentEditor = binEditor;
updateActions();
}
void BinEditorPlugin::updateActions()
{
bool hasEditor = (m_currentEditor != 0);
if (m_selectAllAction)
m_selectAllAction->setEnabled(hasEditor);
if (m_undoAction)
m_undoAction->setEnabled(m_currentEditor && m_currentEditor->isUndoAvailable());
if (m_redoAction)
m_redoAction->setEnabled(m_currentEditor && m_currentEditor->isRedoAvailable());
}
void BinEditorPlugin::undoAction()
{
if (m_currentEditor)
m_currentEditor->undo();
}
void BinEditorPlugin::redoAction()
{
if (m_currentEditor)
m_currentEditor->redo();
}
void BinEditorPlugin::copyAction()
{
if (m_currentEditor)
m_currentEditor->copy();
}
void BinEditorPlugin::selectAllAction()
{
if (m_currentEditor)
m_currentEditor->selectAll();
}
Q_EXPORT_PLUGIN(BinEditorPlugin)
#include "bineditorplugin.moc"
| lgpl-2.1 |
DNPA/OcfaLib | fs/inc/BasicFileDump.hpp | 2138 | //The Open Computer Forensics Library
//Copyright (C) KLPD 2003..2006 <ocfa@dnpa.nl>
//
//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
#ifndef BASICFILEDUMP
#define BASICFILEDUMP
#include "BasicFsEntity.hpp"
namespace ocfa {
namespace fs {
/**
* JBS Documentation: What does this class do?
*/
//RJM:CODEREVIEW Alternate naming: DirTreeFileDumpImplementation: public GenericDirTreeNode
//This class is the basic implementation for classes that represent a non file entity
//as a filedump.
class BasicFileDump:public BasicFsEntity {
FILE *mFile; //The open file handle
std::string mPath; // the path of the filedump
bool mHasContent;
public:
BasicFileDump(std::string path);
bool hasContent();
void openStream();
off_t getSize();
size_t streamRead(char *buf, size_t count);
void closeStream();
std::string getSoftLinkablePath(ocfa::misc::DigestPair **);
std::string getHardLinkablePath(std::string basepath,ocfa::misc::DigestPair **);
protected:
BasicFileDump(const BasicFileDump& bfd):TreeGraphNode(bfd),BasicFsEntity(bfd),mFile(0),mPath(""),mHasContent(false) {
throw misc::OcfaException("No copying allowed",this);
}
const BasicFileDump& operator=(const BasicFileDump&) {
throw misc::OcfaException("No assigment allowed",this);
return *this;
}
};
}
}
#endif
| lgpl-2.1 |
LudovicRousseau/pyscard | smartcard/sw/ISO7816_8ErrorChecker.py | 5267 | """ISO7816-8 error checker.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
This file is part of pyscard.
pyscard 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.
pyscard 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 pyscard; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from smartcard.sw.ErrorChecker import ErrorChecker
import smartcard.sw.SWExceptions
iso7816_8SW = {
0x63: (smartcard.sw.SWExceptions.WarningProcessingException,
{0x00: "Authentication failed",
0xC0: "PIN verification failed. 0 retries before blocking PIN",
0xC1: "PIN verification failed. 1 retries before blocking PIN",
0xC2: "PIN verification failed. 2 retries before blocking PIN",
0xC3: "PIN verification failed. 3 retries before blocking PIN",
0xC4: "PIN verification failed. 4 retries before blocking PIN",
0xC5: "PIN verification failed. 5 retries before blocking PIN",
0xC6: "PIN verification failed. 6 retries before blocking PIN",
0xC7: "PIN verification failed. 7 retries before blocking PIN",
0xC8: "PIN verification failed. 8 retries before blocking PIN",
0xC9: "PIN verification failed. 9 retries before blocking PIN",
0xCA: "PIN verification failed. 10 retries before blocking PIN",
0xCB: "PIN verification failed. 11 retries before blocking PIN",
0xCC: "PIN verification failed. 12 retries before blocking PIN",
0xCD: "PIN verification failed. 13 retries before blocking PIN",
0xCE: "PIN verification failed. 14 retries before blocking PIN",
0xCF: "PIN verification failed. 15 retries before blocking PIN"}),
0x65: (smartcard.sw.SWExceptions.ExecutionErrorException,
{0x81: "Memory failure (unsuccessful changing)"}),
0x66: (smartcard.sw.SWExceptions.SecurityRelatedException,
{0x00: "The environment cannot be set or modified",
0x87: "Expected SM data objects missing",
0x88: "SM data objects incorrect"}),
0x67: (smartcard.sw.SWExceptions.CheckingErrorException,
{0x00: "Wrong length (emtpy Lc field)"}),
0x68: (smartcard.sw.SWExceptions.CheckingErrorException,
{0x83: "Final command expected",
0x84: "Command chaining not supported"}),
0x69: (smartcard.sw.SWExceptions.CheckingErrorException,
{0x82: "Security status not satisfied",
0x83: "Authentification method blocked",
0x84: "Referenced data invalidated",
0x85: "Conditions of use not satisfied"}),
0x6A: (smartcard.sw.SWExceptions.CheckingErrorException,
{0x81: "Function not supported",
0x82: "File not found",
0x86: "Incorrect parameters P1-P2",
0x88: "Referenced data not found"}),
}
class ISO7816_8ErrorChecker(ErrorChecker):
"""ISO7816-8 error checker.
This error checker raises the following exceptions:
- sw1 sw2
- 63 00,c0-cf WarningProcessingException
- 65 81 ExecutionErrorException
- 66 00,87,88 SecurityRelatedException
- 67 00 CheckingErrorException
- 68 82,84 CheckingErrorException
- 69 82,83,84,85 CheckingErrorException
- 6A 81,82,86,88 CheckingErrorException
This checker does not raise exceptions on undefined sw1 values, e.g.:
- sw1 sw2
- 62 any
- 6f any
and on undefined sw2 values, e.g.:
- sw1 sw2
- 66 81 82
- 67 any except 00
Use another checker in the error checking chain, e.g., the
ISO7816_4SW1ErrorChecker or ISO7816_4ErrorChecker, to raise
exceptions on these undefined values.
"""
def __call__(self, data, sw1, sw2):
"""Called to test data, sw1 and sw2 for error.
@param data: apdu response data
@param sw1, sw2: apdu data status words
Derived classes must raise a L{smartcard.sw.SWException} upon error."""
if sw1 in iso7816_8SW:
exception, sw2dir = iso7816_8SW[sw1]
if type(sw2dir) == type({}):
try:
message = sw2dir[sw2]
raise exception(data, sw1, sw2, message)
except KeyError:
pass
if __name__ == '__main__':
"""Small sample illustrating the use of ISO7816_8ErrorChecker."""
ecs = ISO7816_8ErrorChecker()
ecs([], 0x90, 0x00)
ecs([], 0x6a, 0x83)
try:
ecs([], 0x66, 0x87)
except smartcard.sw.SWExceptions.SecurityRelatedException as e:
print(str(e) + " {:x} {:x}".format(e.sw1, e.sw2))
| lgpl-2.1 |
joao-lima/starpu-1.2.0rc2 | doc/doxygen/html/search/variables_10.js | 5982 | var searchData=
[
['scc_5ffuncs',['scc_funcs',['../group__API__Codelet__And__Tasks.html#a61ae676f51abb49231aecc69ca28413a',1,'starpu_codelet']]],
['scc_5fsink_5fto_5fsink',['scc_sink_to_sink',['../group__API__Data__Interfaces.html#aa1025d14aed49b801917a6fa2e60c390',1,'starpu_data_copy_methods']]],
['scc_5fsink_5fto_5fsrc',['scc_sink_to_src',['../group__API__Data__Interfaces.html#a8b9f37c7fe837334f66ce327a87b89f1',1,'starpu_data_copy_methods']]],
['scc_5fsrc_5fto_5fsink',['scc_src_to_sink',['../group__API__Data__Interfaces.html#a84146443d094c81cdc7cac52b28f5114',1,'starpu_data_copy_methods']]],
['sched_5fctx',['sched_ctx',['../group__API__Codelet__And__Tasks.html#a0764b7bdd11bfc686aa7ca4cddccd27a',1,'starpu_task::sched_ctx()'],['../group__API__SC__Hypervisor.html#ab56be8402f4a8e45938a7f688dc0e304',1,'sc_hypervisor_wrapper::sched_ctx()']]],
['sched_5fctx_5fid',['sched_ctx_id',['../group__API__Modularized__Scheduler.html#a79f98f04b4efe58b32fe1ab4f244fe46',1,'starpu_sched_tree::sched_ctx_id()'],['../group__API__SC__Hypervisor.html#a8c2e8240be080f6aa6f0ad02c9918a95',1,'sc_hypervisor_policy_task_pool::sched_ctx_id()']]],
['sched_5fpolicy',['sched_policy',['../group__API__Initialization__and__Termination.html#adf3d42945dba3e6c41a7c9258b192acd',1,'starpu_conf']]],
['sched_5fpolicy_5fname',['sched_policy_name',['../group__API__Initialization__and__Termination.html#adfc5911b1042a9d0edd8ef1ed16f03d6',1,'starpu_conf']]],
['scheduled',['scheduled',['../group__API__Codelet__And__Tasks.html#ad9c17b28982f4cf7074f2e39a45a9acc',1,'starpu_task']]],
['sequential_5fconsistency',['sequential_consistency',['../group__API__Codelet__And__Tasks.html#ae58d5501929b01629dc8b9e3da0cf9ea',1,'starpu_task']]],
['single_5fcombined_5fworker',['single_combined_worker',['../group__API__Initialization__and__Termination.html#a1fc825906ff041878bc3a05ce9681e9c',1,'starpu_conf']]],
['size',['size',['../group__API__Performance__Model.html#a247765c3a84e99b1a0906e26f63151d3',1,'starpu_perfmodel_history_entry']]],
['size_5fbase',['size_base',['../group__API__Performance__Model.html#aa82fae955253d333733d34fe4a44e298',1,'starpu_perfmodel_per_arch::size_base()'],['../group__API__Performance__Model.html#a3cc9f010dd62bf59c1e43e361ea8302f',1,'starpu_perfmodel::size_base()']]],
['size_5fctxs',['size_ctxs',['../group__API__SC__Hypervisor.html#a81431b76980a77c424c38772968102e5',1,'sc_hypervisor_policy']]],
['sleeping_5ftime',['sleeping_time',['../group__API__Profiling.html#acc882d8569e28d51fd5e820962fed773',1,'starpu_profiling_worker_info']]],
['slice_5fbase',['slice_base',['../group__API__Data__Interfaces.html#a90c8cddece28b8576636e6ae4953a30f',1,'starpu_vector_interface']]],
['specific_5fnodes',['specific_nodes',['../group__API__Codelet__And__Tasks.html#a018dfc2c8999ad7646d37ac6c60a5c9e',1,'starpu_codelet']]],
['stall_5fcycles',['stall_cycles',['../group__API__Profiling.html#a78e32404bdff71292562d2dc5892061c',1,'starpu_profiling_task_info::stall_cycles()'],['../group__API__Profiling.html#a24037f0f53113b23f32c7af7a39f982d',1,'starpu_profiling_worker_info::stall_cycles()']]],
['starpu_5fdisk_5fleveldb_5fops',['starpu_disk_leveldb_ops',['../group__API__Out__Of__Core.html#ga4a1bd09de991de1491afa05f5e528e94',1,'starpu_disk.h']]],
['starpu_5fdisk_5fstdio_5fops',['starpu_disk_stdio_ops',['../group__API__Out__Of__Core.html#ga5bb135a02ac97b9efa9ab0280a604868',1,'starpu_disk.h']]],
['starpu_5fdisk_5funistd_5fo_5fdirect_5fops',['starpu_disk_unistd_o_direct_ops',['../group__API__Out__Of__Core.html#ga902a7c5a3920a874f6e4db36c86c1e4b',1,'starpu_disk.h']]],
['starpu_5fdisk_5funistd_5fops',['starpu_disk_unistd_ops',['../group__API__Out__Of__Core.html#ga647a9db1632791e9410643658ad50ffd',1,'starpu_disk.h']]],
['starpu_5fprivate',['starpu_private',['../group__API__Codelet__And__Tasks.html#af4af32520531879aaddcb6ac4e9d1c54',1,'starpu_task']]],
['start_5ftime',['start_time',['../group__API__Profiling.html#ab8de457be74df606d29c3efa1169998a',1,'starpu_profiling_task_info::start_time()'],['../group__API__Profiling.html#aed6a8be9b919f03e093912bfc44c5559',1,'starpu_profiling_worker_info::start_time()'],['../group__API__Profiling.html#a8032d6b4c3391555b255718d7da4279c',1,'starpu_profiling_bus_info::start_time()'],['../group__API__SC__Hypervisor.html#adc95fd3044241fb7a37334c55c90e597',1,'sc_hypervisor_wrapper::start_time()']]],
['status',['status',['../group__API__Codelet__And__Tasks.html#a71d0b3bfe39f4c5f0ecccd7bc39aacd1',1,'starpu_task']]],
['submit_5ftime',['submit_time',['../group__API__Profiling.html#a3a1a7c8e4ce2552a0f96a8dd4f9ad37f',1,'starpu_profiling_task_info']]],
['submitted_5fflops',['submitted_flops',['../group__API__SC__Hypervisor.html#a874e7f62575f017b1956e7ec4035514a',1,'sc_hypervisor_wrapper']]],
['sum',['sum',['../group__API__Performance__Model.html#ab1a7822099d984503f1c67d45ab6f4b8',1,'starpu_perfmodel_history_entry']]],
['sum2',['sum2',['../group__API__Performance__Model.html#a0d9823a671de1b10de6c2bb4ced92163',1,'starpu_perfmodel_history_entry']]],
['sumlnx',['sumlnx',['../group__API__Performance__Model.html#acce4202682709ec0e1f0f22ecc55d1d0',1,'starpu_perfmodel_regression_model']]],
['sumlnx2',['sumlnx2',['../group__API__Performance__Model.html#a4f23ac95d204cc38c51c3e0e5552ef62',1,'starpu_perfmodel_regression_model']]],
['sumlnxlny',['sumlnxlny',['../group__API__Performance__Model.html#a8ddcc5e8aeaf6dd2459e883fab483409',1,'starpu_perfmodel_regression_model']]],
['sumlny',['sumlny',['../group__API__Performance__Model.html#a77f3000cf6f0dff4ac86b6664cc386ea',1,'starpu_perfmodel_regression_model']]],
['symbol',['symbol',['../group__API__FxT__Support.html#a51da03a4801f1824a16cddcbcc515054',1,'starpu_fxt_codelet_event::symbol()'],['../group__API__Performance__Model.html#aa1c188b698608555c94952f9c09e3825',1,'starpu_perfmodel::symbol()']]],
['synchronous',['synchronous',['../group__API__Codelet__And__Tasks.html#a18439d7a6d4ad65b75c75ec02d60075e',1,'starpu_task']]]
];
| lgpl-2.1 |
EmreAtes/spack | var/spack/repos/builtin/packages/busco/package.py | 2523 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# 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) version 2.1, February 1999.
#
# 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 terms and
# conditions of 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Busco(PythonPackage):
"""Assesses genome assembly and annotation completeness with Benchmarking
Universal Single-Copy Orthologs"""
homepage = "http://busco.ezlab.org/"
url = "https://gitlab.com/ezlab/busco"
version('3.0.1', git='https://gitlab.com/ezlab/busco.git', commit='078252e00399550d7b0e8941cd4d986c8e868a83')
version('2.0.1', git='https://gitlab.com/ezlab/busco.git', commit='89aa1ab2527f03a87a214ca90a504ad236582a11')
depends_on('python', type=('build', 'run'))
depends_on('blast-plus')
depends_on('hmmer')
depends_on('augustus')
def build(self, spec, prefix):
if self.spec.satisfies('@2.0.1'):
pass
def install(self, spec, prefix):
if self.spec.satisfies('@3.0.1'):
with working_dir('scripts'):
mkdirp(prefix.bin)
install('generate_plot.py', prefix.bin)
install('run_BUSCO.py', prefix.bin)
install_tree('config', prefix.config)
args = self.install_args(spec, prefix)
self.setup_py('install', *args)
if self.spec.satisfies('@2.0.1'):
mkdirp(prefix.bin)
install('BUSCO.py', prefix.bin)
install('BUSCO_plot.py', prefix.bin)
| lgpl-2.1 |
pbondoer/xwiki-platform | xwiki-platform-core/xwiki-platform-rest/xwiki-platform-rest-server/src/main/java/org/xwiki/rest/internal/resources/pages/PageTranslationResourceImpl.java | 3018 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.rest.internal.resources.pages;
import javax.inject.Named;
import javax.ws.rs.core.Response;
import org.xwiki.component.annotation.Component;
import org.xwiki.rest.XWikiRestException;
import org.xwiki.rest.model.jaxb.Page;
import org.xwiki.rest.resources.pages.PageTranslationResource;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Document;
/**
* @version $Id$
*/
@Component
@Named("org.xwiki.rest.internal.resources.pages.PageTranslationResourceImpl")
public class PageTranslationResourceImpl extends ModifiablePageResource implements PageTranslationResource
{
@Override
public Page getPageTranslation(String wikiName, String spaceName, String pageName, String language,
Boolean withPrettyNames) throws XWikiRestException
{
try {
DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, language, null, true, false);
Document doc = documentInfo.getDocument();
return this.factory.toRestPage(this.uriInfo.getBaseUri(), this.uriInfo.getAbsolutePath(), doc, false,
withPrettyNames, false, false, false);
} catch (XWikiException e) {
throw new XWikiRestException(e);
}
}
@Override
public Response putPageTranslation(String wikiName, String spaceName, String pageName, String language, Page page)
throws XWikiRestException
{
try {
DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, language, null, false, true);
return putPage(documentInfo, page);
} catch (XWikiException e) {
throw new XWikiRestException(e);
}
}
@Override
public void deletePageTranslation(String wikiName, String spaceName, String pageName, String language)
throws XWikiRestException
{
try {
DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, language, null, true, false);
deletePage(documentInfo);
} catch (XWikiException e) {
throw new XWikiRestException(e);
}
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java | 9228 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.resource.transaction.backend.jdbc.internal;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Status;
import org.hibernate.TransactionException;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.transaction.spi.IsolationDelegate;
import org.hibernate.engine.transaction.spi.TransactionObserver;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.resource.jdbc.spi.JdbcSessionOwner;
import org.hibernate.resource.transaction.SynchronizationRegistry;
import org.hibernate.resource.transaction.TransactionCoordinator;
import org.hibernate.resource.transaction.TransactionCoordinatorBuilder;
import org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransaction;
import org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransactionAccess;
import org.hibernate.resource.transaction.internal.SynchronizationRegistryStandardImpl;
import org.hibernate.resource.transaction.spi.TransactionCoordinatorOwner;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import static org.hibernate.internal.CoreLogging.messageLogger;
/**
* An implementation of TransactionCoordinator based on managing a transaction through the JDBC Connection
* via {@link org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransaction}
*
* @author Steve Ebersole
*
* @see org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransaction
*/
public class JdbcResourceLocalTransactionCoordinatorImpl implements TransactionCoordinator {
private static final CoreMessageLogger log = messageLogger( JdbcResourceLocalTransactionCoordinatorImpl.class );
private final TransactionCoordinatorBuilder transactionCoordinatorBuilder;
private final JdbcResourceTransactionAccess jdbcResourceTransactionAccess;
private final TransactionCoordinatorOwner transactionCoordinatorOwner;
private final SynchronizationRegistryStandardImpl synchronizationRegistry = new SynchronizationRegistryStandardImpl();
private TransactionDriverControlImpl physicalTransactionDelegate;
private int timeOut = -1;
private final transient List<TransactionObserver> observers;
/**
* Construct a ResourceLocalTransactionCoordinatorImpl instance. package-protected to ensure access goes through
* builder.
*
* @param owner The transactionCoordinatorOwner
*/
JdbcResourceLocalTransactionCoordinatorImpl(
TransactionCoordinatorBuilder transactionCoordinatorBuilder,
TransactionCoordinatorOwner owner,
JdbcResourceTransactionAccess jdbcResourceTransactionAccess) {
this.observers = new ArrayList<TransactionObserver>();
this.transactionCoordinatorBuilder = transactionCoordinatorBuilder;
this.jdbcResourceTransactionAccess = jdbcResourceTransactionAccess;
this.transactionCoordinatorOwner = owner;
}
@Override
public TransactionDriver getTransactionDriverControl() {
// Again, this PhysicalTransactionDelegate will act as the bridge from the local transaction back into the
// coordinator. We lazily build it as we invalidate each delegate after each transaction (a delegate is
// valid for just one transaction)
if ( physicalTransactionDelegate == null ) {
physicalTransactionDelegate = new TransactionDriverControlImpl( jdbcResourceTransactionAccess.getResourceLocalTransaction() );
}
return physicalTransactionDelegate;
}
@Override
public void explicitJoin() {
// nothing to do here, but log a warning
log.callingJoinTransactionOnNonJtaEntityManager();
}
@Override
public boolean isJoined() {
return physicalTransactionDelegate != null && physicalTransactionDelegate.getStatus() == TransactionStatus.ACTIVE;
}
@Override
public void pulse() {
// nothing to do here
}
@Override
public SynchronizationRegistry getLocalSynchronizations() {
return synchronizationRegistry;
}
@Override
public boolean isActive() {
return transactionCoordinatorOwner.isActive();
}
@Override
public IsolationDelegate createIsolationDelegate() {
final JdbcSessionOwner jdbcSessionOwner = transactionCoordinatorOwner.getJdbcSessionOwner();
return new JdbcIsolationDelegate(
jdbcSessionOwner.getJdbcConnectionAccess(),
jdbcSessionOwner.getJdbcSessionContext().getServiceRegistry().getService( JdbcServices.class ).getSqlExceptionHelper()
);
}
@Override
public TransactionCoordinatorBuilder getTransactionCoordinatorBuilder() {
return this.transactionCoordinatorBuilder;
}
@Override
public void setTimeOut(int seconds) {
this.timeOut = seconds;
}
@Override
public int getTimeOut() {
return this.timeOut;
}
// PhysicalTransactionDelegate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private void afterBeginCallback() {
if(this.timeOut > 0) {
transactionCoordinatorOwner.setTransactionTimeOut( this.timeOut );
}
transactionCoordinatorOwner.afterTransactionBegin();
for ( TransactionObserver observer : observers ) {
observer.afterBegin();
}
log.trace( "ResourceLocalTransactionCoordinatorImpl#afterBeginCallback" );
}
private void beforeCompletionCallback() {
log.trace( "ResourceLocalTransactionCoordinatorImpl#beforeCompletionCallback" );
try {
transactionCoordinatorOwner.beforeTransactionCompletion();
synchronizationRegistry.notifySynchronizationsBeforeTransactionCompletion();
for ( TransactionObserver observer : observers ) {
observer.beforeCompletion();
}
}
catch (RuntimeException e) {
if ( physicalTransactionDelegate != null ) {
// should never happen that the physicalTransactionDelegate is null, but to be safe
physicalTransactionDelegate.markRollbackOnly();
}
throw e;
}
}
private void afterCompletionCallback(boolean successful) {
log.tracef( "ResourceLocalTransactionCoordinatorImpl#afterCompletionCallback(%s)", successful );
final int statusToSend = successful ? Status.STATUS_COMMITTED : Status.STATUS_UNKNOWN;
synchronizationRegistry.notifySynchronizationsAfterTransactionCompletion( statusToSend );
transactionCoordinatorOwner.afterTransactionCompletion( successful, false );
for ( TransactionObserver observer : observers ) {
observer.afterCompletion( successful, false );
}
invalidateDelegate();
}
private void invalidateDelegate() {
if ( physicalTransactionDelegate == null ) {
throw new IllegalStateException( "Physical-transaction delegate not known on attempt to invalidate" );
}
physicalTransactionDelegate.invalidate();
physicalTransactionDelegate = null;
}
public void addObserver(TransactionObserver observer) {
observers.add( observer );
}
@Override
public void removeObserver(TransactionObserver observer) {
observers.remove( observer );
}
/**
* The delegate bridging between the local (application facing) transaction and the "physical" notion of a
* transaction via the JDBC Connection.
*/
public class TransactionDriverControlImpl implements TransactionDriver {
private final JdbcResourceTransaction jdbcResourceTransaction;
private boolean invalid;
private boolean rollbackOnly = false;
public TransactionDriverControlImpl(JdbcResourceTransaction jdbcResourceTransaction) {
super();
this.jdbcResourceTransaction = jdbcResourceTransaction;
}
protected void invalidate() {
invalid = true;
}
@Override
public void begin() {
errorIfInvalid();
jdbcResourceTransaction.begin();
JdbcResourceLocalTransactionCoordinatorImpl.this.afterBeginCallback();
}
protected void errorIfInvalid() {
if ( invalid ) {
throw new IllegalStateException( "Physical-transaction delegate is no longer valid" );
}
}
@Override
public void commit() {
try {
if ( rollbackOnly ) {
throw new TransactionException( "Transaction was marked for rollback only; cannot commit" );
}
JdbcResourceLocalTransactionCoordinatorImpl.this.beforeCompletionCallback();
jdbcResourceTransaction.commit();
JdbcResourceLocalTransactionCoordinatorImpl.this.afterCompletionCallback( true );
}
catch (RuntimeException e) {
try {
rollback();
}
catch (RuntimeException e2) {
log.debug( "Encountered failure rolling back failed commit", e2 );;
}
throw e;
}
}
@Override
public void rollback() {
if ( rollbackOnly || getStatus() == TransactionStatus.ACTIVE ) {
rollbackOnly = false;
jdbcResourceTransaction.rollback();
JdbcResourceLocalTransactionCoordinatorImpl.this.afterCompletionCallback( false );
}
// no-op otherwise.
}
@Override
public TransactionStatus getStatus() {
return rollbackOnly ? TransactionStatus.MARKED_ROLLBACK : jdbcResourceTransaction.getStatus();
}
@Override
public void markRollbackOnly() {
if ( log.isDebugEnabled() ) {
log.debug(
"JDBC transaction marked for rollback-only (exception provided for stack trace)",
new Exception( "exception just for purpose of providing stack trace" )
);
}
rollbackOnly = true;
}
}
}
| lgpl-2.1 |
mate-desktop/python-corba | src/MATECORBA.py | 1018 | # -*- Mode: Python; py-indent-offset: 4 -*-
# pymatecorba - a Python language mapping for the MateCORBA2 CORBA ORB
# Copyright (C) 1998-2003 James Henstridge
#
# CORBA.py: dummy module to make "import CORBA" initialise PyMateCORBA
#
# 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
# this will replace the CORBA.py module.
import MateCORBA
| lgpl-2.1 |
wood-galaxy/FreeCAD | src/Mod/Fem/z88DispReader.py | 7032 | # ***************************************************************************
# * *
# * Copyright (c) 2016 - Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
import FreeCAD
import os
from math import pow, sqrt
__title__ = "FreeCAD Z88 Disp Reader"
__author__ = "Bernd Hahnebach "
__url__ = "http://www.freecadweb.org"
Debug = False
if open.__module__ == '__builtin__':
pyopen = open # because we'll redefine open below
def open(filename):
"called when freecad opens a file"
docname = os.path.splitext(os.path.basename(filename))[0]
insert(filename, docname)
def insert(filename, docname):
"called when freecad wants to import a file"
try:
doc = FreeCAD.getDocument(docname)
except NameError:
doc = FreeCAD.newDocument(docname)
FreeCAD.ActiveDocument = doc
import_z88_disp(filename)
def import_z88_disp(filename, analysis=None, result_name_prefix=None):
'''insert a FreeCAD FEM Result object in the ActiveDocument
'''
m = read_z88_disp(filename)
if(len(m['Nodes']) > 0):
if analysis is None:
analysis_name = os.path.splitext(os.path.basename(filename))[0]
import FemAnalysis
analysis_object = FemAnalysis.makeFemAnalysis('Analysis')
analysis_object.Label = analysis_name
else:
analysis_object = analysis # see if statement few lines later, if not analysis -> no FemMesh object is created !
for result_set in m['Results']:
results_name = result_name_prefix + 'results'
results = FreeCAD.ActiveDocument.addObject('Fem::FemResultObject', results_name)
for m in analysis_object.Member:
if m.isDerivedFrom("Fem::FemMeshObject"):
results.Mesh = m
break
disp = result_set['disp']
no_of_values = len(disp)
displacement = []
for k, v in disp.iteritems():
displacement.append(v)
x_max, y_max, z_max = map(max, zip(*displacement))
scale = 1.0
if len(disp) > 0:
results.DisplacementVectors = map((lambda x: x * scale), disp.values())
results.NodeNumbers = disp.keys()
x_min, y_min, z_min = map(min, zip(*displacement))
sum_list = map(sum, zip(*displacement))
x_avg, y_avg, z_avg = [i / no_of_values for i in sum_list]
s_max = max(results.StressValues)
s_min = min(results.StressValues)
s_avg = sum(results.StressValues) / no_of_values
p1_min = min(results.PrincipalMax)
p1_avg = sum(results.PrincipalMax) / no_of_values
p1_max = max(results.PrincipalMax)
p2_min = min(results.PrincipalMed)
p2_avg = sum(results.PrincipalMed) / no_of_values
p2_max = max(results.PrincipalMed)
p3_min = min(results.PrincipalMin)
p3_avg = sum(results.PrincipalMin) / no_of_values
p3_max = max(results.PrincipalMin)
ms_min = min(results.MaxShear)
ms_avg = sum(results.MaxShear) / no_of_values
ms_max = max(results.MaxShear)
disp_abs = []
for d in displacement:
disp_abs.append(sqrt(pow(d[0], 2) + pow(d[1], 2) + pow(d[2], 2)))
results.DisplacementLengths = disp_abs
a_max = max(disp_abs)
a_min = min(disp_abs)
a_avg = sum(disp_abs) / no_of_values
results.Stats = [x_min, x_avg, x_max,
y_min, y_avg, y_max,
z_min, z_avg, z_max,
a_min, a_avg, a_max,
s_min, s_avg, s_max,
p1_min, p1_avg, p1_max,
p2_min, p2_avg, p2_max,
p3_min, p3_avg, p3_max,
ms_min, ms_avg, ms_max]
analysis_object.Member = analysis_object.Member + [results]
if(FreeCAD.GuiUp):
import FemGui
FemGui.setActiveAnalysis(analysis_object)
def read_z88_disp(z88_disp_input):
'''
read a z88 disp file and extract the nodes and elements
z88 Displacment output file is z88o2.txt
works with Z88OS14
pure usage:
import FemToolsZ88
fea = FemToolsZ88.FemToolsZ88()
import z88dispReader
disp_file = '/pathtofile/z88o2.txt'
z88DispReader.import_z88_disp(disp_file , fea.analysis)
The FreeCAD file needs to have an Analysis and an appropiate FEM Mesh
'''
nodes = {}
mode_disp = {}
mode_results = {}
results = []
z88_disp_file = pyopen(z88_disp_input, "r")
for no, line in enumerate(z88_disp_file):
lno = no + 1
linelist = line.split()
if lno >= 6:
# disp line
# print(linelist)
node_no = int(linelist[0])
mode_disp_x = float(linelist[1])
mode_disp_y = float(linelist[2])
if len(linelist) > 3:
mode_disp_z = float(linelist[3])
else:
mode_disp_z = 0.0
mode_disp[node_no] = FreeCAD.Vector(mode_disp_x, mode_disp_y, mode_disp_z)
nodes[node_no] = node_no
mode_results['disp'] = mode_disp
results.append(mode_results)
if Debug:
for r in results[0]['disp']:
print(r, ' --> ', results[0]['disp'][r])
z88_disp_file.close()
return {'Nodes': nodes, 'Results': results}
| lgpl-2.1 |
cxx-hep/root-cern | interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelDAGToDAG.cpp | 69690 | //===-- NVPTXISelDAGToDAG.cpp - A dag to dag inst selector for NVPTX ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the NVPTX target.
//
//===----------------------------------------------------------------------===//
#include "NVPTXISelDAGToDAG.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetIntrinsicInfo.h"
#undef DEBUG_TYPE
#define DEBUG_TYPE "nvptx-isel"
using namespace llvm;
static cl::opt<int>
FMAContractLevel("nvptx-fma-level", cl::ZeroOrMore,
cl::desc("NVPTX Specific: FMA contraction (0: don't do it"
" 1: do it 2: do it aggressively"),
cl::init(2));
static cl::opt<int> UsePrecDivF32(
"nvptx-prec-divf32", cl::ZeroOrMore,
cl::desc("NVPTX Specifies: 0 use div.approx, 1 use div.full, 2 use"
" IEEE Compliant F32 div.rnd if avaiable."),
cl::init(2));
static cl::opt<bool>
UsePrecSqrtF32("nvptx-prec-sqrtf32",
cl::desc("NVPTX Specific: 0 use sqrt.approx, 1 use sqrt.rn."),
cl::init(true));
static cl::opt<bool>
FtzEnabled("nvptx-f32ftz", cl::ZeroOrMore,
cl::desc("NVPTX Specific: Flush f32 subnormals to sign-preserving zero."),
cl::init(false));
/// createNVPTXISelDag - This pass converts a legalized DAG into a
/// NVPTX-specific DAG, ready for instruction scheduling.
FunctionPass *llvm::createNVPTXISelDag(NVPTXTargetMachine &TM,
llvm::CodeGenOpt::Level OptLevel) {
return new NVPTXDAGToDAGISel(TM, OptLevel);
}
NVPTXDAGToDAGISel::NVPTXDAGToDAGISel(NVPTXTargetMachine &tm,
CodeGenOpt::Level OptLevel)
: SelectionDAGISel(tm, OptLevel),
Subtarget(tm.getSubtarget<NVPTXSubtarget>()) {
doFMAF32 = (OptLevel > 0) && Subtarget.hasFMAF32() && (FMAContractLevel >= 1);
doFMAF64 = (OptLevel > 0) && Subtarget.hasFMAF64() && (FMAContractLevel >= 1);
doFMAF32AGG =
(OptLevel > 0) && Subtarget.hasFMAF32() && (FMAContractLevel == 2);
doFMAF64AGG =
(OptLevel > 0) && Subtarget.hasFMAF64() && (FMAContractLevel == 2);
allowFMA = (FMAContractLevel >= 1);
doMulWide = (OptLevel > 0);
}
int NVPTXDAGToDAGISel::getDivF32Level() const {
if (UsePrecDivF32.getNumOccurrences() > 0) {
// If nvptx-prec-div32=N is used on the command-line, always honor it
return UsePrecDivF32;
} else {
// Otherwise, use div.approx if fast math is enabled
if (TM.Options.UnsafeFPMath)
return 0;
else
return 2;
}
}
bool NVPTXDAGToDAGISel::usePrecSqrtF32() const {
if (UsePrecSqrtF32.getNumOccurrences() > 0) {
// If nvptx-prec-sqrtf32 is used on the command-line, always honor it
return UsePrecSqrtF32;
} else {
// Otherwise, use sqrt.approx if fast math is enabled
if (TM.Options.UnsafeFPMath)
return false;
else
return true;
}
}
bool NVPTXDAGToDAGISel::useF32FTZ() const {
if (FtzEnabled.getNumOccurrences() > 0) {
// If nvptx-f32ftz is used on the command-line, always honor it
return FtzEnabled;
} else {
const Function *F = MF->getFunction();
// Otherwise, check for an nvptx-f32ftz attribute on the function
if (F->hasFnAttribute("nvptx-f32ftz"))
return (F->getAttributes().getAttribute(AttributeSet::FunctionIndex,
"nvptx-f32ftz")
.getValueAsString() == "true");
else
return false;
}
}
/// Select - Select instructions not customized! Used for
/// expanded, promoted and normal instructions.
SDNode *NVPTXDAGToDAGISel::Select(SDNode *N) {
if (N->isMachineOpcode()) {
N->setNodeId(-1);
return NULL; // Already selected.
}
SDNode *ResNode = NULL;
switch (N->getOpcode()) {
case ISD::LOAD:
ResNode = SelectLoad(N);
break;
case ISD::STORE:
ResNode = SelectStore(N);
break;
case NVPTXISD::LoadV2:
case NVPTXISD::LoadV4:
ResNode = SelectLoadVector(N);
break;
case NVPTXISD::LDGV2:
case NVPTXISD::LDGV4:
case NVPTXISD::LDUV2:
case NVPTXISD::LDUV4:
ResNode = SelectLDGLDUVector(N);
break;
case NVPTXISD::StoreV2:
case NVPTXISD::StoreV4:
ResNode = SelectStoreVector(N);
break;
case NVPTXISD::LoadParam:
case NVPTXISD::LoadParamV2:
case NVPTXISD::LoadParamV4:
ResNode = SelectLoadParam(N);
break;
case NVPTXISD::StoreRetval:
case NVPTXISD::StoreRetvalV2:
case NVPTXISD::StoreRetvalV4:
ResNode = SelectStoreRetval(N);
break;
case NVPTXISD::StoreParam:
case NVPTXISD::StoreParamV2:
case NVPTXISD::StoreParamV4:
case NVPTXISD::StoreParamS32:
case NVPTXISD::StoreParamU32:
ResNode = SelectStoreParam(N);
break;
default:
break;
}
if (ResNode)
return ResNode;
return SelectCode(N);
}
static unsigned int getCodeAddrSpace(MemSDNode *N,
const NVPTXSubtarget &Subtarget) {
const Value *Src = N->getSrcValue();
if (!Src)
return NVPTX::PTXLdStInstCode::GENERIC;
if (const PointerType *PT = dyn_cast<PointerType>(Src->getType())) {
switch (PT->getAddressSpace()) {
case llvm::ADDRESS_SPACE_LOCAL: return NVPTX::PTXLdStInstCode::LOCAL;
case llvm::ADDRESS_SPACE_GLOBAL: return NVPTX::PTXLdStInstCode::GLOBAL;
case llvm::ADDRESS_SPACE_SHARED: return NVPTX::PTXLdStInstCode::SHARED;
case llvm::ADDRESS_SPACE_GENERIC: return NVPTX::PTXLdStInstCode::GENERIC;
case llvm::ADDRESS_SPACE_PARAM: return NVPTX::PTXLdStInstCode::PARAM;
case llvm::ADDRESS_SPACE_CONST: return NVPTX::PTXLdStInstCode::CONSTANT;
default: break;
}
}
return NVPTX::PTXLdStInstCode::GENERIC;
}
SDNode *NVPTXDAGToDAGISel::SelectLoad(SDNode *N) {
SDLoc dl(N);
LoadSDNode *LD = cast<LoadSDNode>(N);
EVT LoadedVT = LD->getMemoryVT();
SDNode *NVPTXLD = NULL;
// do not support pre/post inc/dec
if (LD->isIndexed())
return NULL;
if (!LoadedVT.isSimple())
return NULL;
// Address Space Setting
unsigned int codeAddrSpace = getCodeAddrSpace(LD, Subtarget);
// Volatile Setting
// - .volatile is only availalble for .global and .shared
bool isVolatile = LD->isVolatile();
if (codeAddrSpace != NVPTX::PTXLdStInstCode::GLOBAL &&
codeAddrSpace != NVPTX::PTXLdStInstCode::SHARED &&
codeAddrSpace != NVPTX::PTXLdStInstCode::GENERIC)
isVolatile = false;
// Vector Setting
MVT SimpleVT = LoadedVT.getSimpleVT();
unsigned vecType = NVPTX::PTXLdStInstCode::Scalar;
if (SimpleVT.isVector()) {
unsigned num = SimpleVT.getVectorNumElements();
if (num == 2)
vecType = NVPTX::PTXLdStInstCode::V2;
else if (num == 4)
vecType = NVPTX::PTXLdStInstCode::V4;
else
return NULL;
}
// Type Setting: fromType + fromTypeWidth
//
// Sign : ISD::SEXTLOAD
// Unsign : ISD::ZEXTLOAD, ISD::NON_EXTLOAD or ISD::EXTLOAD and the
// type is integer
// Float : ISD::NON_EXTLOAD or ISD::EXTLOAD and the type is float
MVT ScalarVT = SimpleVT.getScalarType();
// Read at least 8 bits (predicates are stored as 8-bit values)
unsigned fromTypeWidth = std::max(8U, ScalarVT.getSizeInBits());
unsigned int fromType;
if ((LD->getExtensionType() == ISD::SEXTLOAD))
fromType = NVPTX::PTXLdStInstCode::Signed;
else if (ScalarVT.isFloatingPoint())
fromType = NVPTX::PTXLdStInstCode::Float;
else
fromType = NVPTX::PTXLdStInstCode::Unsigned;
// Create the machine instruction DAG
SDValue Chain = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue Addr;
SDValue Offset, Base;
unsigned Opcode;
MVT::SimpleValueType TargetVT = LD->getSimpleValueType(0).SimpleTy;
if (SelectDirectAddr(N1, Addr)) {
switch (TargetVT) {
case MVT::i8:
Opcode = NVPTX::LD_i8_avar;
break;
case MVT::i16:
Opcode = NVPTX::LD_i16_avar;
break;
case MVT::i32:
Opcode = NVPTX::LD_i32_avar;
break;
case MVT::i64:
Opcode = NVPTX::LD_i64_avar;
break;
case MVT::f32:
Opcode = NVPTX::LD_f32_avar;
break;
case MVT::f64:
Opcode = NVPTX::LD_f64_avar;
break;
default:
return NULL;
}
SDValue Ops[] = { getI32Imm(isVolatile), getI32Imm(codeAddrSpace),
getI32Imm(vecType), getI32Imm(fromType),
getI32Imm(fromTypeWidth), Addr, Chain };
NVPTXLD = CurDAG->getMachineNode(Opcode, dl, TargetVT, MVT::Other, Ops);
} else if (Subtarget.is64Bit()
? SelectADDRsi64(N1.getNode(), N1, Base, Offset)
: SelectADDRsi(N1.getNode(), N1, Base, Offset)) {
switch (TargetVT) {
case MVT::i8:
Opcode = NVPTX::LD_i8_asi;
break;
case MVT::i16:
Opcode = NVPTX::LD_i16_asi;
break;
case MVT::i32:
Opcode = NVPTX::LD_i32_asi;
break;
case MVT::i64:
Opcode = NVPTX::LD_i64_asi;
break;
case MVT::f32:
Opcode = NVPTX::LD_f32_asi;
break;
case MVT::f64:
Opcode = NVPTX::LD_f64_asi;
break;
default:
return NULL;
}
SDValue Ops[] = { getI32Imm(isVolatile), getI32Imm(codeAddrSpace),
getI32Imm(vecType), getI32Imm(fromType),
getI32Imm(fromTypeWidth), Base, Offset, Chain };
NVPTXLD = CurDAG->getMachineNode(Opcode, dl, TargetVT, MVT::Other, Ops);
} else if (Subtarget.is64Bit()
? SelectADDRri64(N1.getNode(), N1, Base, Offset)
: SelectADDRri(N1.getNode(), N1, Base, Offset)) {
if (Subtarget.is64Bit()) {
switch (TargetVT) {
case MVT::i8:
Opcode = NVPTX::LD_i8_ari_64;
break;
case MVT::i16:
Opcode = NVPTX::LD_i16_ari_64;
break;
case MVT::i32:
Opcode = NVPTX::LD_i32_ari_64;
break;
case MVT::i64:
Opcode = NVPTX::LD_i64_ari_64;
break;
case MVT::f32:
Opcode = NVPTX::LD_f32_ari_64;
break;
case MVT::f64:
Opcode = NVPTX::LD_f64_ari_64;
break;
default:
return NULL;
}
} else {
switch (TargetVT) {
case MVT::i8:
Opcode = NVPTX::LD_i8_ari;
break;
case MVT::i16:
Opcode = NVPTX::LD_i16_ari;
break;
case MVT::i32:
Opcode = NVPTX::LD_i32_ari;
break;
case MVT::i64:
Opcode = NVPTX::LD_i64_ari;
break;
case MVT::f32:
Opcode = NVPTX::LD_f32_ari;
break;
case MVT::f64:
Opcode = NVPTX::LD_f64_ari;
break;
default:
return NULL;
}
}
SDValue Ops[] = { getI32Imm(isVolatile), getI32Imm(codeAddrSpace),
getI32Imm(vecType), getI32Imm(fromType),
getI32Imm(fromTypeWidth), Base, Offset, Chain };
NVPTXLD = CurDAG->getMachineNode(Opcode, dl, TargetVT, MVT::Other, Ops);
} else {
if (Subtarget.is64Bit()) {
switch (TargetVT) {
case MVT::i8:
Opcode = NVPTX::LD_i8_areg_64;
break;
case MVT::i16:
Opcode = NVPTX::LD_i16_areg_64;
break;
case MVT::i32:
Opcode = NVPTX::LD_i32_areg_64;
break;
case MVT::i64:
Opcode = NVPTX::LD_i64_areg_64;
break;
case MVT::f32:
Opcode = NVPTX::LD_f32_areg_64;
break;
case MVT::f64:
Opcode = NVPTX::LD_f64_areg_64;
break;
default:
return NULL;
}
} else {
switch (TargetVT) {
case MVT::i8:
Opcode = NVPTX::LD_i8_areg;
break;
case MVT::i16:
Opcode = NVPTX::LD_i16_areg;
break;
case MVT::i32:
Opcode = NVPTX::LD_i32_areg;
break;
case MVT::i64:
Opcode = NVPTX::LD_i64_areg;
break;
case MVT::f32:
Opcode = NVPTX::LD_f32_areg;
break;
case MVT::f64:
Opcode = NVPTX::LD_f64_areg;
break;
default:
return NULL;
}
}
SDValue Ops[] = { getI32Imm(isVolatile), getI32Imm(codeAddrSpace),
getI32Imm(vecType), getI32Imm(fromType),
getI32Imm(fromTypeWidth), N1, Chain };
NVPTXLD = CurDAG->getMachineNode(Opcode, dl, TargetVT, MVT::Other, Ops);
}
if (NVPTXLD != NULL) {
MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
cast<MachineSDNode>(NVPTXLD)->setMemRefs(MemRefs0, MemRefs0 + 1);
}
return NVPTXLD;
}
SDNode *NVPTXDAGToDAGISel::SelectLoadVector(SDNode *N) {
SDValue Chain = N->getOperand(0);
SDValue Op1 = N->getOperand(1);
SDValue Addr, Offset, Base;
unsigned Opcode;
SDLoc DL(N);
SDNode *LD;
MemSDNode *MemSD = cast<MemSDNode>(N);
EVT LoadedVT = MemSD->getMemoryVT();
if (!LoadedVT.isSimple())
return NULL;
// Address Space Setting
unsigned int CodeAddrSpace = getCodeAddrSpace(MemSD, Subtarget);
// Volatile Setting
// - .volatile is only availalble for .global and .shared
bool IsVolatile = MemSD->isVolatile();
if (CodeAddrSpace != NVPTX::PTXLdStInstCode::GLOBAL &&
CodeAddrSpace != NVPTX::PTXLdStInstCode::SHARED &&
CodeAddrSpace != NVPTX::PTXLdStInstCode::GENERIC)
IsVolatile = false;
// Vector Setting
MVT SimpleVT = LoadedVT.getSimpleVT();
// Type Setting: fromType + fromTypeWidth
//
// Sign : ISD::SEXTLOAD
// Unsign : ISD::ZEXTLOAD, ISD::NON_EXTLOAD or ISD::EXTLOAD and the
// type is integer
// Float : ISD::NON_EXTLOAD or ISD::EXTLOAD and the type is float
MVT ScalarVT = SimpleVT.getScalarType();
// Read at least 8 bits (predicates are stored as 8-bit values)
unsigned FromTypeWidth = std::max(8U, ScalarVT.getSizeInBits());
unsigned int FromType;
// The last operand holds the original LoadSDNode::getExtensionType() value
unsigned ExtensionType = cast<ConstantSDNode>(
N->getOperand(N->getNumOperands() - 1))->getZExtValue();
if (ExtensionType == ISD::SEXTLOAD)
FromType = NVPTX::PTXLdStInstCode::Signed;
else if (ScalarVT.isFloatingPoint())
FromType = NVPTX::PTXLdStInstCode::Float;
else
FromType = NVPTX::PTXLdStInstCode::Unsigned;
unsigned VecType;
switch (N->getOpcode()) {
case NVPTXISD::LoadV2:
VecType = NVPTX::PTXLdStInstCode::V2;
break;
case NVPTXISD::LoadV4:
VecType = NVPTX::PTXLdStInstCode::V4;
break;
default:
return NULL;
}
EVT EltVT = N->getValueType(0);
if (SelectDirectAddr(Op1, Addr)) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LoadV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v2_avar;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v2_avar;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v2_avar;
break;
case MVT::i64:
Opcode = NVPTX::LDV_i64_v2_avar;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v2_avar;
break;
case MVT::f64:
Opcode = NVPTX::LDV_f64_v2_avar;
break;
}
break;
case NVPTXISD::LoadV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v4_avar;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v4_avar;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v4_avar;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v4_avar;
break;
}
break;
}
SDValue Ops[] = { getI32Imm(IsVolatile), getI32Imm(CodeAddrSpace),
getI32Imm(VecType), getI32Imm(FromType),
getI32Imm(FromTypeWidth), Addr, Chain };
LD = CurDAG->getMachineNode(Opcode, DL, N->getVTList(), Ops);
} else if (Subtarget.is64Bit()
? SelectADDRsi64(Op1.getNode(), Op1, Base, Offset)
: SelectADDRsi(Op1.getNode(), Op1, Base, Offset)) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LoadV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v2_asi;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v2_asi;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v2_asi;
break;
case MVT::i64:
Opcode = NVPTX::LDV_i64_v2_asi;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v2_asi;
break;
case MVT::f64:
Opcode = NVPTX::LDV_f64_v2_asi;
break;
}
break;
case NVPTXISD::LoadV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v4_asi;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v4_asi;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v4_asi;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v4_asi;
break;
}
break;
}
SDValue Ops[] = { getI32Imm(IsVolatile), getI32Imm(CodeAddrSpace),
getI32Imm(VecType), getI32Imm(FromType),
getI32Imm(FromTypeWidth), Base, Offset, Chain };
LD = CurDAG->getMachineNode(Opcode, DL, N->getVTList(), Ops);
} else if (Subtarget.is64Bit()
? SelectADDRri64(Op1.getNode(), Op1, Base, Offset)
: SelectADDRri(Op1.getNode(), Op1, Base, Offset)) {
if (Subtarget.is64Bit()) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LoadV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v2_ari_64;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v2_ari_64;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v2_ari_64;
break;
case MVT::i64:
Opcode = NVPTX::LDV_i64_v2_ari_64;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v2_ari_64;
break;
case MVT::f64:
Opcode = NVPTX::LDV_f64_v2_ari_64;
break;
}
break;
case NVPTXISD::LoadV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v4_ari_64;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v4_ari_64;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v4_ari_64;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v4_ari_64;
break;
}
break;
}
} else {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LoadV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v2_ari;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v2_ari;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v2_ari;
break;
case MVT::i64:
Opcode = NVPTX::LDV_i64_v2_ari;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v2_ari;
break;
case MVT::f64:
Opcode = NVPTX::LDV_f64_v2_ari;
break;
}
break;
case NVPTXISD::LoadV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v4_ari;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v4_ari;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v4_ari;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v4_ari;
break;
}
break;
}
}
SDValue Ops[] = { getI32Imm(IsVolatile), getI32Imm(CodeAddrSpace),
getI32Imm(VecType), getI32Imm(FromType),
getI32Imm(FromTypeWidth), Base, Offset, Chain };
LD = CurDAG->getMachineNode(Opcode, DL, N->getVTList(), Ops);
} else {
if (Subtarget.is64Bit()) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LoadV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v2_areg_64;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v2_areg_64;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v2_areg_64;
break;
case MVT::i64:
Opcode = NVPTX::LDV_i64_v2_areg_64;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v2_areg_64;
break;
case MVT::f64:
Opcode = NVPTX::LDV_f64_v2_areg_64;
break;
}
break;
case NVPTXISD::LoadV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v4_areg_64;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v4_areg_64;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v4_areg_64;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v4_areg_64;
break;
}
break;
}
} else {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LoadV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v2_areg;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v2_areg;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v2_areg;
break;
case MVT::i64:
Opcode = NVPTX::LDV_i64_v2_areg;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v2_areg;
break;
case MVT::f64:
Opcode = NVPTX::LDV_f64_v2_areg;
break;
}
break;
case NVPTXISD::LoadV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::LDV_i8_v4_areg;
break;
case MVT::i16:
Opcode = NVPTX::LDV_i16_v4_areg;
break;
case MVT::i32:
Opcode = NVPTX::LDV_i32_v4_areg;
break;
case MVT::f32:
Opcode = NVPTX::LDV_f32_v4_areg;
break;
}
break;
}
}
SDValue Ops[] = { getI32Imm(IsVolatile), getI32Imm(CodeAddrSpace),
getI32Imm(VecType), getI32Imm(FromType),
getI32Imm(FromTypeWidth), Op1, Chain };
LD = CurDAG->getMachineNode(Opcode, DL, N->getVTList(), Ops);
}
MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
cast<MachineSDNode>(LD)->setMemRefs(MemRefs0, MemRefs0 + 1);
return LD;
}
SDNode *NVPTXDAGToDAGISel::SelectLDGLDUVector(SDNode *N) {
SDValue Chain = N->getOperand(0);
SDValue Op1 = N->getOperand(1);
unsigned Opcode;
SDLoc DL(N);
SDNode *LD;
MemSDNode *Mem = cast<MemSDNode>(N);
SDValue Base, Offset, Addr;
EVT EltVT = Mem->getMemoryVT().getVectorElementType();
if (SelectDirectAddr(Op1, Addr)) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LDGV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v2i8_ELE_avar;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v2i16_ELE_avar;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v2i32_ELE_avar;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDG_G_v2i64_ELE_avar;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v2f32_ELE_avar;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDG_G_v2f64_ELE_avar;
break;
}
break;
case NVPTXISD::LDUV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v2i8_ELE_avar;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v2i16_ELE_avar;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v2i32_ELE_avar;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDU_G_v2i64_ELE_avar;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v2f32_ELE_avar;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDU_G_v2f64_ELE_avar;
break;
}
break;
case NVPTXISD::LDGV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v4i8_ELE_avar;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v4i16_ELE_avar;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v4i32_ELE_avar;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v4f32_ELE_avar;
break;
}
break;
case NVPTXISD::LDUV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v4i8_ELE_avar;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v4i16_ELE_avar;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v4i32_ELE_avar;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v4f32_ELE_avar;
break;
}
break;
}
SDValue Ops[] = { Addr, Chain };
LD = CurDAG->getMachineNode(Opcode, DL, N->getVTList(),
ArrayRef<SDValue>(Ops, 2));
} else if (Subtarget.is64Bit()
? SelectADDRri64(Op1.getNode(), Op1, Base, Offset)
: SelectADDRri(Op1.getNode(), Op1, Base, Offset)) {
if (Subtarget.is64Bit()) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LDGV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v2i8_ELE_ari64;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v2i16_ELE_ari64;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v2i32_ELE_ari64;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDG_G_v2i64_ELE_ari64;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v2f32_ELE_ari64;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDG_G_v2f64_ELE_ari64;
break;
}
break;
case NVPTXISD::LDUV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v2i8_ELE_ari64;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v2i16_ELE_ari64;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v2i32_ELE_ari64;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDU_G_v2i64_ELE_ari64;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v2f32_ELE_ari64;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDU_G_v2f64_ELE_ari64;
break;
}
break;
case NVPTXISD::LDGV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v4i8_ELE_ari64;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v4i16_ELE_ari64;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v4i32_ELE_ari64;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v4f32_ELE_ari64;
break;
}
break;
case NVPTXISD::LDUV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v4i8_ELE_ari64;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v4i16_ELE_ari64;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v4i32_ELE_ari64;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v4f32_ELE_ari64;
break;
}
break;
}
} else {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LDGV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v2i8_ELE_ari32;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v2i16_ELE_ari32;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v2i32_ELE_ari32;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDG_G_v2i64_ELE_ari32;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v2f32_ELE_ari32;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDG_G_v2f64_ELE_ari32;
break;
}
break;
case NVPTXISD::LDUV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v2i8_ELE_ari32;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v2i16_ELE_ari32;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v2i32_ELE_ari32;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDU_G_v2i64_ELE_ari32;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v2f32_ELE_ari32;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDU_G_v2f64_ELE_ari32;
break;
}
break;
case NVPTXISD::LDGV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v4i8_ELE_ari32;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v4i16_ELE_ari32;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v4i32_ELE_ari32;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v4f32_ELE_ari32;
break;
}
break;
case NVPTXISD::LDUV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v4i8_ELE_ari32;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v4i16_ELE_ari32;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v4i32_ELE_ari32;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v4f32_ELE_ari32;
break;
}
break;
}
}
SDValue Ops[] = { Base, Offset, Chain };
LD = CurDAG->getMachineNode(Opcode, DL, N->getVTList(),
ArrayRef<SDValue>(Ops, 3));
} else {
if (Subtarget.is64Bit()) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LDGV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v2i8_ELE_areg64;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v2i16_ELE_areg64;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v2i32_ELE_areg64;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDG_G_v2i64_ELE_areg64;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v2f32_ELE_areg64;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDG_G_v2f64_ELE_areg64;
break;
}
break;
case NVPTXISD::LDUV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v2i8_ELE_areg64;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v2i16_ELE_areg64;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v2i32_ELE_areg64;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDU_G_v2i64_ELE_areg64;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v2f32_ELE_areg64;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDU_G_v2f64_ELE_areg64;
break;
}
break;
case NVPTXISD::LDGV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v4i8_ELE_areg64;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v4i16_ELE_areg64;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v4i32_ELE_areg64;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v4f32_ELE_areg64;
break;
}
break;
case NVPTXISD::LDUV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v4i8_ELE_areg64;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v4i16_ELE_areg64;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v4i32_ELE_areg64;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v4f32_ELE_areg64;
break;
}
break;
}
} else {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::LDGV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v2i8_ELE_areg32;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v2i16_ELE_areg32;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v2i32_ELE_areg32;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDG_G_v2i64_ELE_areg32;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v2f32_ELE_areg32;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDG_G_v2f64_ELE_areg32;
break;
}
break;
case NVPTXISD::LDUV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v2i8_ELE_areg32;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v2i16_ELE_areg32;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v2i32_ELE_areg32;
break;
case MVT::i64:
Opcode = NVPTX::INT_PTX_LDU_G_v2i64_ELE_areg32;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v2f32_ELE_areg32;
break;
case MVT::f64:
Opcode = NVPTX::INT_PTX_LDU_G_v2f64_ELE_areg32;
break;
}
break;
case NVPTXISD::LDGV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDG_G_v4i8_ELE_areg32;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDG_G_v4i16_ELE_areg32;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDG_G_v4i32_ELE_areg32;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDG_G_v4f32_ELE_areg32;
break;
}
break;
case NVPTXISD::LDUV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::INT_PTX_LDU_G_v4i8_ELE_areg32;
break;
case MVT::i16:
Opcode = NVPTX::INT_PTX_LDU_G_v4i16_ELE_areg32;
break;
case MVT::i32:
Opcode = NVPTX::INT_PTX_LDU_G_v4i32_ELE_areg32;
break;
case MVT::f32:
Opcode = NVPTX::INT_PTX_LDU_G_v4f32_ELE_areg32;
break;
}
break;
}
}
SDValue Ops[] = { Op1, Chain };
LD = CurDAG->getMachineNode(Opcode, DL, N->getVTList(),
ArrayRef<SDValue>(Ops, 2));
}
MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
cast<MachineSDNode>(LD)->setMemRefs(MemRefs0, MemRefs0 + 1);
return LD;
}
SDNode *NVPTXDAGToDAGISel::SelectStore(SDNode *N) {
SDLoc dl(N);
StoreSDNode *ST = cast<StoreSDNode>(N);
EVT StoreVT = ST->getMemoryVT();
SDNode *NVPTXST = NULL;
// do not support pre/post inc/dec
if (ST->isIndexed())
return NULL;
if (!StoreVT.isSimple())
return NULL;
// Address Space Setting
unsigned int codeAddrSpace = getCodeAddrSpace(ST, Subtarget);
// Volatile Setting
// - .volatile is only availalble for .global and .shared
bool isVolatile = ST->isVolatile();
if (codeAddrSpace != NVPTX::PTXLdStInstCode::GLOBAL &&
codeAddrSpace != NVPTX::PTXLdStInstCode::SHARED &&
codeAddrSpace != NVPTX::PTXLdStInstCode::GENERIC)
isVolatile = false;
// Vector Setting
MVT SimpleVT = StoreVT.getSimpleVT();
unsigned vecType = NVPTX::PTXLdStInstCode::Scalar;
if (SimpleVT.isVector()) {
unsigned num = SimpleVT.getVectorNumElements();
if (num == 2)
vecType = NVPTX::PTXLdStInstCode::V2;
else if (num == 4)
vecType = NVPTX::PTXLdStInstCode::V4;
else
return NULL;
}
// Type Setting: toType + toTypeWidth
// - for integer type, always use 'u'
//
MVT ScalarVT = SimpleVT.getScalarType();
unsigned toTypeWidth = ScalarVT.getSizeInBits();
unsigned int toType;
if (ScalarVT.isFloatingPoint())
toType = NVPTX::PTXLdStInstCode::Float;
else
toType = NVPTX::PTXLdStInstCode::Unsigned;
// Create the machine instruction DAG
SDValue Chain = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
SDValue Addr;
SDValue Offset, Base;
unsigned Opcode;
MVT::SimpleValueType SourceVT = N1.getNode()->getSimpleValueType(0).SimpleTy;
if (SelectDirectAddr(N2, Addr)) {
switch (SourceVT) {
case MVT::i8:
Opcode = NVPTX::ST_i8_avar;
break;
case MVT::i16:
Opcode = NVPTX::ST_i16_avar;
break;
case MVT::i32:
Opcode = NVPTX::ST_i32_avar;
break;
case MVT::i64:
Opcode = NVPTX::ST_i64_avar;
break;
case MVT::f32:
Opcode = NVPTX::ST_f32_avar;
break;
case MVT::f64:
Opcode = NVPTX::ST_f64_avar;
break;
default:
return NULL;
}
SDValue Ops[] = { N1, getI32Imm(isVolatile), getI32Imm(codeAddrSpace),
getI32Imm(vecType), getI32Imm(toType),
getI32Imm(toTypeWidth), Addr, Chain };
NVPTXST = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
} else if (Subtarget.is64Bit()
? SelectADDRsi64(N2.getNode(), N2, Base, Offset)
: SelectADDRsi(N2.getNode(), N2, Base, Offset)) {
switch (SourceVT) {
case MVT::i8:
Opcode = NVPTX::ST_i8_asi;
break;
case MVT::i16:
Opcode = NVPTX::ST_i16_asi;
break;
case MVT::i32:
Opcode = NVPTX::ST_i32_asi;
break;
case MVT::i64:
Opcode = NVPTX::ST_i64_asi;
break;
case MVT::f32:
Opcode = NVPTX::ST_f32_asi;
break;
case MVT::f64:
Opcode = NVPTX::ST_f64_asi;
break;
default:
return NULL;
}
SDValue Ops[] = { N1, getI32Imm(isVolatile), getI32Imm(codeAddrSpace),
getI32Imm(vecType), getI32Imm(toType),
getI32Imm(toTypeWidth), Base, Offset, Chain };
NVPTXST = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
} else if (Subtarget.is64Bit()
? SelectADDRri64(N2.getNode(), N2, Base, Offset)
: SelectADDRri(N2.getNode(), N2, Base, Offset)) {
if (Subtarget.is64Bit()) {
switch (SourceVT) {
case MVT::i8:
Opcode = NVPTX::ST_i8_ari_64;
break;
case MVT::i16:
Opcode = NVPTX::ST_i16_ari_64;
break;
case MVT::i32:
Opcode = NVPTX::ST_i32_ari_64;
break;
case MVT::i64:
Opcode = NVPTX::ST_i64_ari_64;
break;
case MVT::f32:
Opcode = NVPTX::ST_f32_ari_64;
break;
case MVT::f64:
Opcode = NVPTX::ST_f64_ari_64;
break;
default:
return NULL;
}
} else {
switch (SourceVT) {
case MVT::i8:
Opcode = NVPTX::ST_i8_ari;
break;
case MVT::i16:
Opcode = NVPTX::ST_i16_ari;
break;
case MVT::i32:
Opcode = NVPTX::ST_i32_ari;
break;
case MVT::i64:
Opcode = NVPTX::ST_i64_ari;
break;
case MVT::f32:
Opcode = NVPTX::ST_f32_ari;
break;
case MVT::f64:
Opcode = NVPTX::ST_f64_ari;
break;
default:
return NULL;
}
}
SDValue Ops[] = { N1, getI32Imm(isVolatile), getI32Imm(codeAddrSpace),
getI32Imm(vecType), getI32Imm(toType),
getI32Imm(toTypeWidth), Base, Offset, Chain };
NVPTXST = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
} else {
if (Subtarget.is64Bit()) {
switch (SourceVT) {
case MVT::i8:
Opcode = NVPTX::ST_i8_areg_64;
break;
case MVT::i16:
Opcode = NVPTX::ST_i16_areg_64;
break;
case MVT::i32:
Opcode = NVPTX::ST_i32_areg_64;
break;
case MVT::i64:
Opcode = NVPTX::ST_i64_areg_64;
break;
case MVT::f32:
Opcode = NVPTX::ST_f32_areg_64;
break;
case MVT::f64:
Opcode = NVPTX::ST_f64_areg_64;
break;
default:
return NULL;
}
} else {
switch (SourceVT) {
case MVT::i8:
Opcode = NVPTX::ST_i8_areg;
break;
case MVT::i16:
Opcode = NVPTX::ST_i16_areg;
break;
case MVT::i32:
Opcode = NVPTX::ST_i32_areg;
break;
case MVT::i64:
Opcode = NVPTX::ST_i64_areg;
break;
case MVT::f32:
Opcode = NVPTX::ST_f32_areg;
break;
case MVT::f64:
Opcode = NVPTX::ST_f64_areg;
break;
default:
return NULL;
}
}
SDValue Ops[] = { N1, getI32Imm(isVolatile), getI32Imm(codeAddrSpace),
getI32Imm(vecType), getI32Imm(toType),
getI32Imm(toTypeWidth), N2, Chain };
NVPTXST = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
}
if (NVPTXST != NULL) {
MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
cast<MachineSDNode>(NVPTXST)->setMemRefs(MemRefs0, MemRefs0 + 1);
}
return NVPTXST;
}
SDNode *NVPTXDAGToDAGISel::SelectStoreVector(SDNode *N) {
SDValue Chain = N->getOperand(0);
SDValue Op1 = N->getOperand(1);
SDValue Addr, Offset, Base;
unsigned Opcode;
SDLoc DL(N);
SDNode *ST;
EVT EltVT = Op1.getValueType();
MemSDNode *MemSD = cast<MemSDNode>(N);
EVT StoreVT = MemSD->getMemoryVT();
// Address Space Setting
unsigned CodeAddrSpace = getCodeAddrSpace(MemSD, Subtarget);
if (CodeAddrSpace == NVPTX::PTXLdStInstCode::CONSTANT) {
report_fatal_error("Cannot store to pointer that points to constant "
"memory space");
}
// Volatile Setting
// - .volatile is only availalble for .global and .shared
bool IsVolatile = MemSD->isVolatile();
if (CodeAddrSpace != NVPTX::PTXLdStInstCode::GLOBAL &&
CodeAddrSpace != NVPTX::PTXLdStInstCode::SHARED &&
CodeAddrSpace != NVPTX::PTXLdStInstCode::GENERIC)
IsVolatile = false;
// Type Setting: toType + toTypeWidth
// - for integer type, always use 'u'
assert(StoreVT.isSimple() && "Store value is not simple");
MVT ScalarVT = StoreVT.getSimpleVT().getScalarType();
unsigned ToTypeWidth = ScalarVT.getSizeInBits();
unsigned ToType;
if (ScalarVT.isFloatingPoint())
ToType = NVPTX::PTXLdStInstCode::Float;
else
ToType = NVPTX::PTXLdStInstCode::Unsigned;
SmallVector<SDValue, 12> StOps;
SDValue N2;
unsigned VecType;
switch (N->getOpcode()) {
case NVPTXISD::StoreV2:
VecType = NVPTX::PTXLdStInstCode::V2;
StOps.push_back(N->getOperand(1));
StOps.push_back(N->getOperand(2));
N2 = N->getOperand(3);
break;
case NVPTXISD::StoreV4:
VecType = NVPTX::PTXLdStInstCode::V4;
StOps.push_back(N->getOperand(1));
StOps.push_back(N->getOperand(2));
StOps.push_back(N->getOperand(3));
StOps.push_back(N->getOperand(4));
N2 = N->getOperand(5);
break;
default:
return NULL;
}
StOps.push_back(getI32Imm(IsVolatile));
StOps.push_back(getI32Imm(CodeAddrSpace));
StOps.push_back(getI32Imm(VecType));
StOps.push_back(getI32Imm(ToType));
StOps.push_back(getI32Imm(ToTypeWidth));
if (SelectDirectAddr(N2, Addr)) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::StoreV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v2_avar;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v2_avar;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v2_avar;
break;
case MVT::i64:
Opcode = NVPTX::STV_i64_v2_avar;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v2_avar;
break;
case MVT::f64:
Opcode = NVPTX::STV_f64_v2_avar;
break;
}
break;
case NVPTXISD::StoreV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v4_avar;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v4_avar;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v4_avar;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v4_avar;
break;
}
break;
}
StOps.push_back(Addr);
} else if (Subtarget.is64Bit()
? SelectADDRsi64(N2.getNode(), N2, Base, Offset)
: SelectADDRsi(N2.getNode(), N2, Base, Offset)) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::StoreV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v2_asi;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v2_asi;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v2_asi;
break;
case MVT::i64:
Opcode = NVPTX::STV_i64_v2_asi;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v2_asi;
break;
case MVT::f64:
Opcode = NVPTX::STV_f64_v2_asi;
break;
}
break;
case NVPTXISD::StoreV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v4_asi;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v4_asi;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v4_asi;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v4_asi;
break;
}
break;
}
StOps.push_back(Base);
StOps.push_back(Offset);
} else if (Subtarget.is64Bit()
? SelectADDRri64(N2.getNode(), N2, Base, Offset)
: SelectADDRri(N2.getNode(), N2, Base, Offset)) {
if (Subtarget.is64Bit()) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::StoreV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v2_ari_64;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v2_ari_64;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v2_ari_64;
break;
case MVT::i64:
Opcode = NVPTX::STV_i64_v2_ari_64;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v2_ari_64;
break;
case MVT::f64:
Opcode = NVPTX::STV_f64_v2_ari_64;
break;
}
break;
case NVPTXISD::StoreV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v4_ari_64;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v4_ari_64;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v4_ari_64;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v4_ari_64;
break;
}
break;
}
} else {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::StoreV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v2_ari;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v2_ari;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v2_ari;
break;
case MVT::i64:
Opcode = NVPTX::STV_i64_v2_ari;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v2_ari;
break;
case MVT::f64:
Opcode = NVPTX::STV_f64_v2_ari;
break;
}
break;
case NVPTXISD::StoreV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v4_ari;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v4_ari;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v4_ari;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v4_ari;
break;
}
break;
}
}
StOps.push_back(Base);
StOps.push_back(Offset);
} else {
if (Subtarget.is64Bit()) {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::StoreV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v2_areg_64;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v2_areg_64;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v2_areg_64;
break;
case MVT::i64:
Opcode = NVPTX::STV_i64_v2_areg_64;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v2_areg_64;
break;
case MVT::f64:
Opcode = NVPTX::STV_f64_v2_areg_64;
break;
}
break;
case NVPTXISD::StoreV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v4_areg_64;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v4_areg_64;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v4_areg_64;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v4_areg_64;
break;
}
break;
}
} else {
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::StoreV2:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v2_areg;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v2_areg;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v2_areg;
break;
case MVT::i64:
Opcode = NVPTX::STV_i64_v2_areg;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v2_areg;
break;
case MVT::f64:
Opcode = NVPTX::STV_f64_v2_areg;
break;
}
break;
case NVPTXISD::StoreV4:
switch (EltVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i8:
Opcode = NVPTX::STV_i8_v4_areg;
break;
case MVT::i16:
Opcode = NVPTX::STV_i16_v4_areg;
break;
case MVT::i32:
Opcode = NVPTX::STV_i32_v4_areg;
break;
case MVT::f32:
Opcode = NVPTX::STV_f32_v4_areg;
break;
}
break;
}
}
StOps.push_back(N2);
}
StOps.push_back(Chain);
ST = CurDAG->getMachineNode(Opcode, DL, MVT::Other, StOps);
MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
cast<MachineSDNode>(ST)->setMemRefs(MemRefs0, MemRefs0 + 1);
return ST;
}
SDNode *NVPTXDAGToDAGISel::SelectLoadParam(SDNode *Node) {
SDValue Chain = Node->getOperand(0);
SDValue Offset = Node->getOperand(2);
SDValue Flag = Node->getOperand(3);
SDLoc DL(Node);
MemSDNode *Mem = cast<MemSDNode>(Node);
unsigned VecSize;
switch (Node->getOpcode()) {
default:
return NULL;
case NVPTXISD::LoadParam:
VecSize = 1;
break;
case NVPTXISD::LoadParamV2:
VecSize = 2;
break;
case NVPTXISD::LoadParamV4:
VecSize = 4;
break;
}
EVT EltVT = Node->getValueType(0);
EVT MemVT = Mem->getMemoryVT();
unsigned Opc = 0;
switch (VecSize) {
default:
return NULL;
case 1:
switch (MemVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opc = NVPTX::LoadParamMemI8;
break;
case MVT::i8:
Opc = NVPTX::LoadParamMemI8;
break;
case MVT::i16:
Opc = NVPTX::LoadParamMemI16;
break;
case MVT::i32:
Opc = NVPTX::LoadParamMemI32;
break;
case MVT::i64:
Opc = NVPTX::LoadParamMemI64;
break;
case MVT::f32:
Opc = NVPTX::LoadParamMemF32;
break;
case MVT::f64:
Opc = NVPTX::LoadParamMemF64;
break;
}
break;
case 2:
switch (MemVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opc = NVPTX::LoadParamMemV2I8;
break;
case MVT::i8:
Opc = NVPTX::LoadParamMemV2I8;
break;
case MVT::i16:
Opc = NVPTX::LoadParamMemV2I16;
break;
case MVT::i32:
Opc = NVPTX::LoadParamMemV2I32;
break;
case MVT::i64:
Opc = NVPTX::LoadParamMemV2I64;
break;
case MVT::f32:
Opc = NVPTX::LoadParamMemV2F32;
break;
case MVT::f64:
Opc = NVPTX::LoadParamMemV2F64;
break;
}
break;
case 4:
switch (MemVT.getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opc = NVPTX::LoadParamMemV4I8;
break;
case MVT::i8:
Opc = NVPTX::LoadParamMemV4I8;
break;
case MVT::i16:
Opc = NVPTX::LoadParamMemV4I16;
break;
case MVT::i32:
Opc = NVPTX::LoadParamMemV4I32;
break;
case MVT::f32:
Opc = NVPTX::LoadParamMemV4F32;
break;
}
break;
}
SDVTList VTs;
if (VecSize == 1) {
VTs = CurDAG->getVTList(EltVT, MVT::Other, MVT::Glue);
} else if (VecSize == 2) {
VTs = CurDAG->getVTList(EltVT, EltVT, MVT::Other, MVT::Glue);
} else {
EVT EVTs[] = { EltVT, EltVT, EltVT, EltVT, MVT::Other, MVT::Glue };
VTs = CurDAG->getVTList(&EVTs[0], 5);
}
unsigned OffsetVal = cast<ConstantSDNode>(Offset)->getZExtValue();
SmallVector<SDValue, 2> Ops;
Ops.push_back(CurDAG->getTargetConstant(OffsetVal, MVT::i32));
Ops.push_back(Chain);
Ops.push_back(Flag);
SDNode *Ret =
CurDAG->getMachineNode(Opc, DL, VTs, Ops);
return Ret;
}
SDNode *NVPTXDAGToDAGISel::SelectStoreRetval(SDNode *N) {
SDLoc DL(N);
SDValue Chain = N->getOperand(0);
SDValue Offset = N->getOperand(1);
unsigned OffsetVal = cast<ConstantSDNode>(Offset)->getZExtValue();
MemSDNode *Mem = cast<MemSDNode>(N);
// How many elements do we have?
unsigned NumElts = 1;
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::StoreRetval:
NumElts = 1;
break;
case NVPTXISD::StoreRetvalV2:
NumElts = 2;
break;
case NVPTXISD::StoreRetvalV4:
NumElts = 4;
break;
}
// Build vector of operands
SmallVector<SDValue, 6> Ops;
for (unsigned i = 0; i < NumElts; ++i)
Ops.push_back(N->getOperand(i + 2));
Ops.push_back(CurDAG->getTargetConstant(OffsetVal, MVT::i32));
Ops.push_back(Chain);
// Determine target opcode
// If we have an i1, use an 8-bit store. The lowering code in
// NVPTXISelLowering will have already emitted an upcast.
unsigned Opcode = 0;
switch (NumElts) {
default:
return NULL;
case 1:
switch (Mem->getMemoryVT().getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opcode = NVPTX::StoreRetvalI8;
break;
case MVT::i8:
Opcode = NVPTX::StoreRetvalI8;
break;
case MVT::i16:
Opcode = NVPTX::StoreRetvalI16;
break;
case MVT::i32:
Opcode = NVPTX::StoreRetvalI32;
break;
case MVT::i64:
Opcode = NVPTX::StoreRetvalI64;
break;
case MVT::f32:
Opcode = NVPTX::StoreRetvalF32;
break;
case MVT::f64:
Opcode = NVPTX::StoreRetvalF64;
break;
}
break;
case 2:
switch (Mem->getMemoryVT().getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opcode = NVPTX::StoreRetvalV2I8;
break;
case MVT::i8:
Opcode = NVPTX::StoreRetvalV2I8;
break;
case MVT::i16:
Opcode = NVPTX::StoreRetvalV2I16;
break;
case MVT::i32:
Opcode = NVPTX::StoreRetvalV2I32;
break;
case MVT::i64:
Opcode = NVPTX::StoreRetvalV2I64;
break;
case MVT::f32:
Opcode = NVPTX::StoreRetvalV2F32;
break;
case MVT::f64:
Opcode = NVPTX::StoreRetvalV2F64;
break;
}
break;
case 4:
switch (Mem->getMemoryVT().getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opcode = NVPTX::StoreRetvalV4I8;
break;
case MVT::i8:
Opcode = NVPTX::StoreRetvalV4I8;
break;
case MVT::i16:
Opcode = NVPTX::StoreRetvalV4I16;
break;
case MVT::i32:
Opcode = NVPTX::StoreRetvalV4I32;
break;
case MVT::f32:
Opcode = NVPTX::StoreRetvalV4F32;
break;
}
break;
}
SDNode *Ret =
CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops);
MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
cast<MachineSDNode>(Ret)->setMemRefs(MemRefs0, MemRefs0 + 1);
return Ret;
}
SDNode *NVPTXDAGToDAGISel::SelectStoreParam(SDNode *N) {
SDLoc DL(N);
SDValue Chain = N->getOperand(0);
SDValue Param = N->getOperand(1);
unsigned ParamVal = cast<ConstantSDNode>(Param)->getZExtValue();
SDValue Offset = N->getOperand(2);
unsigned OffsetVal = cast<ConstantSDNode>(Offset)->getZExtValue();
MemSDNode *Mem = cast<MemSDNode>(N);
SDValue Flag = N->getOperand(N->getNumOperands() - 1);
// How many elements do we have?
unsigned NumElts = 1;
switch (N->getOpcode()) {
default:
return NULL;
case NVPTXISD::StoreParamU32:
case NVPTXISD::StoreParamS32:
case NVPTXISD::StoreParam:
NumElts = 1;
break;
case NVPTXISD::StoreParamV2:
NumElts = 2;
break;
case NVPTXISD::StoreParamV4:
NumElts = 4;
break;
}
// Build vector of operands
SmallVector<SDValue, 8> Ops;
for (unsigned i = 0; i < NumElts; ++i)
Ops.push_back(N->getOperand(i + 3));
Ops.push_back(CurDAG->getTargetConstant(ParamVal, MVT::i32));
Ops.push_back(CurDAG->getTargetConstant(OffsetVal, MVT::i32));
Ops.push_back(Chain);
Ops.push_back(Flag);
// Determine target opcode
// If we have an i1, use an 8-bit store. The lowering code in
// NVPTXISelLowering will have already emitted an upcast.
unsigned Opcode = 0;
switch (N->getOpcode()) {
default:
switch (NumElts) {
default:
return NULL;
case 1:
switch (Mem->getMemoryVT().getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opcode = NVPTX::StoreParamI8;
break;
case MVT::i8:
Opcode = NVPTX::StoreParamI8;
break;
case MVT::i16:
Opcode = NVPTX::StoreParamI16;
break;
case MVT::i32:
Opcode = NVPTX::StoreParamI32;
break;
case MVT::i64:
Opcode = NVPTX::StoreParamI64;
break;
case MVT::f32:
Opcode = NVPTX::StoreParamF32;
break;
case MVT::f64:
Opcode = NVPTX::StoreParamF64;
break;
}
break;
case 2:
switch (Mem->getMemoryVT().getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opcode = NVPTX::StoreParamV2I8;
break;
case MVT::i8:
Opcode = NVPTX::StoreParamV2I8;
break;
case MVT::i16:
Opcode = NVPTX::StoreParamV2I16;
break;
case MVT::i32:
Opcode = NVPTX::StoreParamV2I32;
break;
case MVT::i64:
Opcode = NVPTX::StoreParamV2I64;
break;
case MVT::f32:
Opcode = NVPTX::StoreParamV2F32;
break;
case MVT::f64:
Opcode = NVPTX::StoreParamV2F64;
break;
}
break;
case 4:
switch (Mem->getMemoryVT().getSimpleVT().SimpleTy) {
default:
return NULL;
case MVT::i1:
Opcode = NVPTX::StoreParamV4I8;
break;
case MVT::i8:
Opcode = NVPTX::StoreParamV4I8;
break;
case MVT::i16:
Opcode = NVPTX::StoreParamV4I16;
break;
case MVT::i32:
Opcode = NVPTX::StoreParamV4I32;
break;
case MVT::f32:
Opcode = NVPTX::StoreParamV4F32;
break;
}
break;
}
break;
// Special case: if we have a sign-extend/zero-extend node, insert the
// conversion instruction first, and use that as the value operand to
// the selected StoreParam node.
case NVPTXISD::StoreParamU32: {
Opcode = NVPTX::StoreParamI32;
SDValue CvtNone = CurDAG->getTargetConstant(NVPTX::PTXCvtMode::NONE,
MVT::i32);
SDNode *Cvt = CurDAG->getMachineNode(NVPTX::CVT_u32_u16, DL,
MVT::i32, Ops[0], CvtNone);
Ops[0] = SDValue(Cvt, 0);
break;
}
case NVPTXISD::StoreParamS32: {
Opcode = NVPTX::StoreParamI32;
SDValue CvtNone = CurDAG->getTargetConstant(NVPTX::PTXCvtMode::NONE,
MVT::i32);
SDNode *Cvt = CurDAG->getMachineNode(NVPTX::CVT_s32_s16, DL,
MVT::i32, Ops[0], CvtNone);
Ops[0] = SDValue(Cvt, 0);
break;
}
}
SDVTList RetVTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
SDNode *Ret =
CurDAG->getMachineNode(Opcode, DL, RetVTs, Ops);
MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
cast<MachineSDNode>(Ret)->setMemRefs(MemRefs0, MemRefs0 + 1);
return Ret;
}
// SelectDirectAddr - Match a direct address for DAG.
// A direct address could be a globaladdress or externalsymbol.
bool NVPTXDAGToDAGISel::SelectDirectAddr(SDValue N, SDValue &Address) {
// Return true if TGA or ES.
if (N.getOpcode() == ISD::TargetGlobalAddress ||
N.getOpcode() == ISD::TargetExternalSymbol) {
Address = N;
return true;
}
if (N.getOpcode() == NVPTXISD::Wrapper) {
Address = N.getOperand(0);
return true;
}
if (N.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
unsigned IID = cast<ConstantSDNode>(N.getOperand(0))->getZExtValue();
if (IID == Intrinsic::nvvm_ptr_gen_to_param)
if (N.getOperand(1).getOpcode() == NVPTXISD::MoveParam)
return (SelectDirectAddr(N.getOperand(1).getOperand(0), Address));
}
return false;
}
// symbol+offset
bool NVPTXDAGToDAGISel::SelectADDRsi_imp(
SDNode *OpNode, SDValue Addr, SDValue &Base, SDValue &Offset, MVT mvt) {
if (Addr.getOpcode() == ISD::ADD) {
if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
SDValue base = Addr.getOperand(0);
if (SelectDirectAddr(base, Base)) {
Offset = CurDAG->getTargetConstant(CN->getZExtValue(), mvt);
return true;
}
}
}
return false;
}
// symbol+offset
bool NVPTXDAGToDAGISel::SelectADDRsi(SDNode *OpNode, SDValue Addr,
SDValue &Base, SDValue &Offset) {
return SelectADDRsi_imp(OpNode, Addr, Base, Offset, MVT::i32);
}
// symbol+offset
bool NVPTXDAGToDAGISel::SelectADDRsi64(SDNode *OpNode, SDValue Addr,
SDValue &Base, SDValue &Offset) {
return SelectADDRsi_imp(OpNode, Addr, Base, Offset, MVT::i64);
}
// register+offset
bool NVPTXDAGToDAGISel::SelectADDRri_imp(
SDNode *OpNode, SDValue Addr, SDValue &Base, SDValue &Offset, MVT mvt) {
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), mvt);
Offset = CurDAG->getTargetConstant(0, mvt);
return true;
}
if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
Addr.getOpcode() == ISD::TargetGlobalAddress)
return false; // direct calls.
if (Addr.getOpcode() == ISD::ADD) {
if (SelectDirectAddr(Addr.getOperand(0), Addr)) {
return false;
}
if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
if (FrameIndexSDNode *FIN =
dyn_cast<FrameIndexSDNode>(Addr.getOperand(0)))
// Constant offset from frame ref.
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), mvt);
else
Base = Addr.getOperand(0);
Offset = CurDAG->getTargetConstant(CN->getZExtValue(), mvt);
return true;
}
}
return false;
}
// register+offset
bool NVPTXDAGToDAGISel::SelectADDRri(SDNode *OpNode, SDValue Addr,
SDValue &Base, SDValue &Offset) {
return SelectADDRri_imp(OpNode, Addr, Base, Offset, MVT::i32);
}
// register+offset
bool NVPTXDAGToDAGISel::SelectADDRri64(SDNode *OpNode, SDValue Addr,
SDValue &Base, SDValue &Offset) {
return SelectADDRri_imp(OpNode, Addr, Base, Offset, MVT::i64);
}
bool NVPTXDAGToDAGISel::ChkMemSDNodeAddressSpace(SDNode *N,
unsigned int spN) const {
const Value *Src = NULL;
// Even though MemIntrinsicSDNode is a subclas of MemSDNode,
// the classof() for MemSDNode does not include MemIntrinsicSDNode
// (See SelectionDAGNodes.h). So we need to check for both.
if (MemSDNode *mN = dyn_cast<MemSDNode>(N)) {
Src = mN->getSrcValue();
} else if (MemSDNode *mN = dyn_cast<MemIntrinsicSDNode>(N)) {
Src = mN->getSrcValue();
}
if (!Src)
return false;
if (const PointerType *PT = dyn_cast<PointerType>(Src->getType()))
return (PT->getAddressSpace() == spN);
return false;
}
/// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
/// inline asm expressions.
bool NVPTXDAGToDAGISel::SelectInlineAsmMemoryOperand(
const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps) {
SDValue Op0, Op1;
switch (ConstraintCode) {
default:
return true;
case 'm': // memory
if (SelectDirectAddr(Op, Op0)) {
OutOps.push_back(Op0);
OutOps.push_back(CurDAG->getTargetConstant(0, MVT::i32));
return false;
}
if (SelectADDRri(Op.getNode(), Op, Op0, Op1)) {
OutOps.push_back(Op0);
OutOps.push_back(Op1);
return false;
}
break;
}
return true;
}
// Return true if N is a undef or a constant.
// If N was undef, return a (i8imm 0) in Retval
// If N was imm, convert it to i8imm and return in Retval
// Note: The convert to i8imm is required, otherwise the
// pattern matcher inserts a bunch of IMOVi8rr to convert
// the imm to i8imm, and this causes instruction selection
// to fail.
bool NVPTXDAGToDAGISel::UndefOrImm(SDValue Op, SDValue N, SDValue &Retval) {
if (!(N.getOpcode() == ISD::UNDEF) && !(N.getOpcode() == ISD::Constant))
return false;
if (N.getOpcode() == ISD::UNDEF)
Retval = CurDAG->getTargetConstant(0, MVT::i8);
else {
ConstantSDNode *cn = cast<ConstantSDNode>(N.getNode());
unsigned retval = cn->getZExtValue();
Retval = CurDAG->getTargetConstant(retval, MVT::i8);
}
return true;
}
| lgpl-2.1 |
mono/linux-packaging-monodevelop | src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor.Extension/BraceMatcherTextEditorExtension.cs | 6124 | //
// BraceMatcherTextEditorExtension.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Gtk;
using Mono.Addins;
using MonoDevelop.Components.Commands;
using MonoDevelop.Core;
using MonoDevelop.Ide.Extensions;
namespace MonoDevelop.Ide.Editor.Extension
{
sealed class BraceMatcherTextEditorExtension : TextEditorExtension
{
CancellationTokenSource src = new CancellationTokenSource();
static List<AbstractBraceMatcher> braceMatcher = new List<AbstractBraceMatcher> ();
BraceMatchingResult? currentResult;
bool isSubscribed;
static BraceMatcherTextEditorExtension()
{
AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Ide/BraceMatcher", delegate(object sender, ExtensionNodeEventArgs args) {
var node = (MimeTypeExtensionNode)args.ExtensionNode;
switch (args.Change) {
case ExtensionChange.Add:
var matcher = (AbstractBraceMatcher)node.CreateInstance ();
matcher.MimeType = node.MimeType;
braceMatcher.Add (matcher);
break;
case ExtensionChange.Remove:
var toRemove = braceMatcher.FirstOrDefault (m => m.MimeType == node.MimeType);
if (toRemove != null)
braceMatcher.Remove (toRemove);
break;
}
});
braceMatcher.Add (new DefaultBraceMatcher());
}
AbstractBraceMatcher GetBraceMatcher ()
{
return braceMatcher.First (m => m.CanHandle (Editor));
}
protected override void Initialize ()
{
if ((Editor.TextEditorType & TextEditorType.Invisible) != 0)
return;
DefaultSourceEditorOptions.Instance.highlightMatchingBracket.Changed += HighlightMatchingBracket_Changed;
HighlightMatchingBracket_Changed (this, EventArgs.Empty);
}
void HighlightMatchingBracket_Changed (object sender, EventArgs e)
{
if (DefaultSourceEditorOptions.Instance.HighlightMatchingBracket) {
if (isSubscribed)
return;
Editor.CaretPositionChanged += Editor_CaretPositionChanged;
DocumentContext.DocumentParsed += HandleDocumentParsed;
isSubscribed = true;
Editor_CaretPositionChanged (null, null);
} else {
if (!isSubscribed)
return;
Editor.CaretPositionChanged -= Editor_CaretPositionChanged;
DocumentContext.DocumentParsed -= HandleDocumentParsed;
Editor.UpdateBraceMatchingResult (null);
isSubscribed = false;
}
}
public override void Dispose ()
{
src.Cancel ();
DefaultSourceEditorOptions.Instance.highlightMatchingBracket.Changed -= HighlightMatchingBracket_Changed;
if (isSubscribed) {
Editor.CaretPositionChanged -= Editor_CaretPositionChanged;
DocumentContext.DocumentParsed -= HandleDocumentParsed;
isSubscribed = false;
}
base.Dispose ();
}
void HandleDocumentParsed (object sender, EventArgs e)
{
Editor_CaretPositionChanged (sender, e);
}
[CommandHandler (MonoDevelop.Ide.Commands.TextEditorCommands.GotoMatchingBrace)]
internal void OnGotoMatchingBrace ()
{
if (currentResult != null && currentResult.HasValue) {
Editor.CaretOffset = currentResult.Value.IsCaretInLeft ? currentResult.Value.RightSegment.Offset : currentResult.Value.LeftSegment.Offset;
}
}
void Editor_CaretPositionChanged (object sender, EventArgs e)
{
Editor.UpdateBraceMatchingResult (null);
currentResult = null;
src.Cancel ();
src = new CancellationTokenSource ();
var token = src.Token;
var matcher = GetBraceMatcher ();
if (matcher == null)
return;
var caretOffset = Editor.CaretOffset;
var ctx = DocumentContext;
var snapshot = Editor.CreateDocumentSnapshot ();
Task.Run (async delegate() {
BraceMatchingResult? result = null;
try {
if (caretOffset > 0)
result = await matcher.GetMatchingBracesAsync (snapshot, ctx, caretOffset - 1, token).ConfigureAwait (false);
if (result == null)
result = await matcher.GetMatchingBracesAsync (snapshot, ctx, caretOffset, token).ConfigureAwait (false);
if (result == null)
return;
if (result.HasValue) {
if (result.Value.LeftSegment.Offset < 0 ||
result.Value.LeftSegment.EndOffset > snapshot.Length) {
LoggingService.LogError ("bracket matcher left segment invalid:" + result.Value.LeftSegment);
return;
}
if (result.Value.RightSegment.Offset < 0 ||
result.Value.RightSegment.EndOffset > snapshot.Length) {
LoggingService.LogError ("bracket matcher right segment invalid:" + result.Value.RightSegment);
return;
}
}
} catch (OperationCanceledException) {
return;
} catch (AggregateException ae) {
ae.Flatten ().Handle (ex => ex is OperationCanceledException);
return;
}
if (token.IsCancellationRequested)
return;
Application.Invoke ((o, args) => {
if (token.IsCancellationRequested)
return;
Editor.UpdateBraceMatchingResult (result);
currentResult = result;
});
});
}
}
} | lgpl-2.1 |
kalj/dealii | tests/base/pattern_tools_06.cc | 1776 | // ---------------------------------------------------------------------
//
// Copyright (C) 2005 - 2015 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include "../tests.h"
#include <deal.II/base/patterns.h>
#include <deal.II/base/point.h>
#include <deal.II/base/numbers.h>
#include <boost/core/demangle.hpp>
#include <memory>
using namespace dealii;
using namespace Patterns::Tools;
// Try conversion on complex map types
template<class T>
void test(T t)
{
auto p = Convert<T>::to_pattern();
deallog << "Pattern : " << p->description() << std::endl;
auto s = Convert<T>::to_string(t);
deallog << "To String: " << s << std::endl;
deallog << "To value : " << Convert<T>::to_string(Convert<T>::to_value(s)) << std::endl;
}
int main()
{
initlog();
std::map<int, double> t0;
std::unordered_map<int, double> t1;
std::multimap<int, double> t2;
std::unordered_multimap<int, double> t3;
auto p = std::make_pair(5,1.0);
auto p2 = std::make_pair(5,2.0);
auto p3 = std::make_pair(1,3.0);
t0.insert(p);
t1.insert(p);
t2.insert(p);
t3.insert(p);
t0.insert(p3);
t1.insert(p3);
t2.insert(p3);
t3.insert(p3);
t2.insert(p2);
t3.insert(p2);
test(t0);
test(t1);
test(t2);
test(t3);
return 0;
}
| lgpl-2.1 |
JolantaWojcik/biojavaOwn | biojava3-phylo/src/main/java/org/biojava3/phylo/CheckTreeAccuracy.java | 4197 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.biojava3.phylo;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.forester.phylogeny.Phylogeny;
import org.forester.phylogeny.PhylogenyNode;
import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
import org.forester.evoinference.matrix.distance.DistanceMatrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Scooter
*/
public class CheckTreeAccuracy {
private static final Logger logger = LoggerFactory.getLogger(CheckTreeAccuracy.class);
public static DistanceMatrix copyMatrix(DistanceMatrix matrix) {
DistanceMatrix distanceMatrix = new BasicSymmetricalDistanceMatrix(matrix.getSize());
for (int i = 0; i < matrix.getSize(); i++) {
distanceMatrix.setIdentifier(i, matrix.getIdentifier(i));
}
for (int col = 0; col < matrix.getSize(); col++) {
for (int row = 0; row < matrix.getSize(); row++) {
distanceMatrix.setValue(col, row, matrix.getValue(col, row));
}
}
return distanceMatrix;
}
public void process(Phylogeny tree, DistanceMatrix matrix) {
int numSequences = matrix.getSize();
List<PhylogenyNode> externalNodes = tree.getExternalNodes();
HashMap<String, PhylogenyNode> externalNodesHashMap = new HashMap<String, PhylogenyNode>();
Set<PhylogenyNode> path = new HashSet<PhylogenyNode>();
for (PhylogenyNode node : externalNodes) {
externalNodesHashMap.put(node.getName(), node);
}
int count = 0;
double averageMatrixDistance = 0.0;
double averageTreeDistance = 0.0;
double averageTreeErrorDistance = 0.0;
for (int row = 0; row < numSequences - 1; row++) {
String nodeName1 = matrix.getIdentifier(row);
PhylogenyNode node1 = externalNodesHashMap.get(nodeName1);
markPathToRoot(node1, path);
for (int col = row + 1; col < numSequences; col++) {
count++;
String nodeName2 = matrix.getIdentifier(col);
PhylogenyNode node2 = externalNodesHashMap.get(nodeName2);
double distance = matrix.getValue(col, row);
averageMatrixDistance = averageMatrixDistance + distance;
PhylogenyNode commonParent = findCommonParent(node2, path);
if (commonParent != null) {
double treeDistance = getNodeDistance(commonParent, node1) + getNodeDistance(commonParent, node2);
averageTreeDistance = averageTreeDistance + treeDistance;
averageTreeErrorDistance = averageTreeErrorDistance + Math.abs(distance - treeDistance);
logger.info("{} {} Distance: {}Tree: {} difference: {}", nodeName1, nodeName2, distance, treeDistance, Math.abs(distance - treeDistance));
} else {
logger.warn("Unable to find common parent with {} {}", node1, node2);
}
}
path.clear();
}
logger.info("Average matrix distance: {}", averageMatrixDistance / count);
logger.info("Average tree distance: {}", averageTreeDistance / count);
logger.info("Average error: {}", averageTreeErrorDistance / count);
}
public double getNodeDistance(PhylogenyNode parentNode, PhylogenyNode childNode) {
double distance = 0.0;
while (childNode != parentNode) {
distance = distance + childNode.getDistanceToParent();
childNode = childNode.getParent();
}
return distance;
}
public PhylogenyNode findCommonParent(PhylogenyNode node, Set<PhylogenyNode> path) {
while (!path.contains(node)) {
node = node.getParent();
}
return node;
}
public void markPathToRoot(PhylogenyNode node, Set<PhylogenyNode> path) {
path.add(node);
while (!node.isRoot()) {
node = node.getParent();
path.add(node);
}
}
}
| lgpl-2.1 |
champtar/fmj-sourceforge-mirror | src.test/net/sf/fmj/test/compat/sun/RTPSyncBufferMuxTest.java | 1508 | package net.sf.fmj.test.compat.sun;
import javax.media.*;
import javax.media.format.*;
import junit.framework.*;
/**
*
* @author Ken Larson
*
*/
public class RTPSyncBufferMuxTest extends TestCase
{
public void test1()
{
com.sun.media.multiplexer.RTPSyncBufferMux m = new com.sun.media.multiplexer.RTPSyncBufferMux();
assertEquals(m.getName(), "RTP Sync Buffer Multiplexer");
Format[] f = m.getSupportedInputFormats();
assertEquals(f.length, 2);
assertEquals(f.length, 2);
assertEquals(f[0], new AudioFormat(null, -1.0, -1, -1, -1, -1, -1,
-1.0, Format.byteArray));
assertEquals(f[1], new VideoFormat(null, null, -1, Format.byteArray,
-1.0f));
{
Format f1 = new AudioFormat(AudioFormat.ULAW_RTP, -1.0, -1, -1, -1,
-1, -1, -1.0, Format.byteArray);
for (int i = 0; i < 100; ++i)
{
// JMF doesn't mind if we set the input format before the mux or
// tracks are initialized.
// not sure if it remembers the formats in this case though.
Format f2 = m.setInputFormat(f1, i);
assertTrue(f2 == f1);
}
}
{
Format f1 = new AudioFormat(AudioFormat.ULAW, -1.0, -1, -1, -1, -1,
-1, -1.0, Format.byteArray);
Format f2 = m.setInputFormat(f1, 0);
assertTrue(f2 == null);
}
}
}
| lgpl-2.1 |
tmcguire/qt-mobility | src/contacts/qcontactmanager.cpp | 48763 | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcontactmanager.h"
#include "qcontact_p.h"
#include "qcontactfilter.h"
#include "qcontactdetaildefinition.h"
#include "qcontactmanager_p.h"
#include "qcontactfetchhint.h"
#include <QSharedData>
#include <QPair>
#include <QSet>
QTM_BEGIN_NAMESPACE
/*!
\class QContactManager
\brief The QContactManager class provides an interface which allows clients with access to contact information stored in a particular backend.
\inmodule QtContacts
\since 1.0
\ingroup contacts-main
This class provides an abstraction of a datastore or aggregation of datastores which contains contact information.
It provides methods to retrieve and manipulate contact information, contact relationship information, and
supported schema definitions. It also provides metadata and error information reporting.
The functions provided by QContactManager are purely synchronous; to access the same functionality in an
asynchronous manner, clients should use the use-case-specific classes derived from QContactAbstractRequest.
Some functionality provided by QContactManager directly is not accessible using the asynchronous API; see
the \l{Contacts Synchronous API}{synchronous} and \l{Contacts Asynchronous API}{asynchronous} API
information from the \l{Contacts}{contacts module} API documentation.
*/
/*!
\fn QContactManager::dataChanged()
This signal is emitted by the manager if its internal state changes, and it is unable to determine the changes
which occurred, or if the manager considers the changes to be radical enough to require clients to reload all data.
If this signal is emitted, no other signals will be emitted for the associated changes.
\since 1.0
*/
/*!
\fn QContactManager::contactsAdded(const QList<QContactLocalId>& contactIds)
This signal is emitted at some point once the contacts identified by \a contactIds have been added to a datastore managed by this manager.
This signal must not be emitted if the dataChanged() signal was previously emitted for these changes.
\since 1.0
*/
/*!
\fn QContactManager::contactsChanged(const QList<QContactLocalId>& contactIds)
This signal is emitted at some point once the contacts identified by \a contactIds have been modified in a datastore managed by this manager.
This signal must not be emitted if the dataChanged() signal was previously emitted for these changes.
\since 1.0
*/
/*!
\fn QContactManager::contactsRemoved(const QList<QContactLocalId>& contactIds)
This signal is emitted at some point once the contacts identified by \a contactIds have been removed from a datastore managed by this manager.
This signal must not be emitted if the dataChanged() signal was previously emitted for these changes.
\since 1.0
*/
/*!
\fn QContactManager::relationshipsAdded(const QList<QContactLocalId>& affectedContactIds)
This signal is emitted at some point after relationships have been added to the manager which involve the contacts identified by \a affectedContactIds.
This signal must not be emitted if the dataChanged() signal was previously emitted for these changes.
\since 1.0
*/
/*!
\fn QContactManager::relationshipsRemoved(const QList<QContactLocalId>& affectedContactIds)
This signal is emitted at some point after relationships have eben removed from the manager which involve the contacts identified by \a affectedContactIds.
This signal must not be emitted if the dataChanged() signal was previously emitted for these changes.
\since 1.0
*/
/*!
\fn QContactManager::selfContactIdChanged(const QContactLocalId& oldId, const QContactLocalId& newId)
This signal is emitted at some point after the id of the self-contact is changed from \a oldId to \a newId in the manager.
If the \a newId is the invalid, zero id, then the self contact was deleted or no self contact exists.
This signal must not be emitted if the dataChanged() signal was previously emitted for this change.
\since 1.0
*/
#define makestr(x) (#x)
#define makename(x) makestr(x)
/*!
Returns a list of available manager ids that can be used when constructing
a QContactManager. If an empty id is specified to the constructor, the
first value in this list will be used instead.
\since 1.0
*/
QStringList QContactManager::availableManagers()
{
QStringList ret;
ret << QLatin1String("memory") << QLatin1String("invalid");
#ifdef QT_SIMULATOR
ret << QLatin1String("simulator");
#endif
QContactManagerData::loadFactories();
ret.append(QContactManagerData::m_engines.keys());
// now swizzle the default engine to pole position
#if defined(Q_CONTACTS_DEFAULT_ENGINE)
if (ret.removeAll(QLatin1String(makename(Q_CONTACTS_DEFAULT_ENGINE)))) {
ret.prepend(QLatin1String(makename(Q_CONTACTS_DEFAULT_ENGINE)));
}
#endif
return ret;
}
/*!
Splits the given \a uri into the manager, store, and parameters that it describes, and places the information into the memory addressed by \a pManagerId and \a pParams respectively. Returns true if \a uri could be split successfully, otherwise returns false
\since 1.0
*/
bool QContactManager::parseUri(const QString& uri, QString* pManagerId, QMap<QString, QString>* pParams)
{
// Format: qtcontacts:<managerid>:<key>=<value>&<key>=<value>
// 1) parameters are currently a qstringlist.. should they be a map?
// 2) is the uri going to be escaped? my guess would be "probably not"
// 3) hence, do we assume that the prefix, managerid and storeid cannot contain `:'
// 4) similarly, that neither keys nor values can contain `=' or `&'
QStringList colonSplit = uri.split(QLatin1Char(':'));
QString prefix = colonSplit.value(0);
if (prefix != QLatin1String("qtcontacts"))
return false;
QString managerName = colonSplit.value(1);
if (managerName.trimmed().isEmpty())
return false;
QString firstParts = prefix + QLatin1Char(':') + managerName + QLatin1Char(':');
QString paramString = uri.mid(firstParts.length());
QMap<QString, QString> outParams;
// Now we have to decode each parameter
if (!paramString.isEmpty()) {
QStringList params = paramString.split(QRegExp(QLatin1String("&(?!(amp;|equ;))")), QString::KeepEmptyParts);
// If we have an empty string for paramstring, we get one entry in params,
// so skip that case.
for(int i = 0; i < params.count(); i++) {
/* This should be something like "foo&bar&equ;=grob&" */
QStringList paramChunk = params.value(i).split(QLatin1String("="), QString::KeepEmptyParts);
if (paramChunk.count() != 2)
return false;
QString arg = paramChunk.value(0);
QString param = paramChunk.value(1);
arg.replace(QLatin1String("&equ;"), QLatin1String("="));
arg.replace(QLatin1String("&"), QLatin1String("&"));
param.replace(QLatin1String("&equ;"), QLatin1String("="));
param.replace(QLatin1String("&"), QLatin1String("&"));
if (arg.isEmpty())
return false;
outParams.insert(arg, param);
}
}
if (pParams)
*pParams = outParams;
if (pManagerId)
*pManagerId = managerName;
return true;
}
/*!
Returns a URI that completely describes a manager implementation, datastore, and the parameters
with which to instantiate the manager, from the given \a managerName, \a params and an optional
\a implementationVersion. This function is generally useful only if you intend to construct a
manager with the \l fromUri() function, or wish to set the manager URI field in a QContactId
manually (for synchronization or other purposes). Most clients will not need to use this function.
\since 1.0
*/
QString QContactManager::buildUri(const QString& managerName, const QMap<QString, QString>& params, int implementationVersion)
{
QString ret(QLatin1String("qtcontacts:%1:%2"));
// we have to escape each param
QStringList escapedParams;
QStringList keys = params.keys();
for (int i=0; i < keys.size(); i++) {
QString key = keys.at(i);
QString arg = params.value(key);
arg = arg.replace(QLatin1Char('&'), QLatin1String("&"));
arg = arg.replace(QLatin1Char('='), QLatin1String("&equ;"));
key = key.replace(QLatin1Char('&'), QLatin1String("&"));
key = key.replace(QLatin1Char('='), QLatin1String("&equ;"));
key = key + QLatin1Char('=') + arg;
escapedParams.append(key);
}
if (implementationVersion != -1) {
QString versionString = QString(QLatin1String(QTCONTACTS_IMPLEMENTATION_VERSION_NAME));
versionString += QString::fromAscii("=");
versionString += QString::number(implementationVersion);
escapedParams.append(versionString);
}
return ret.arg(managerName, escapedParams.join(QLatin1String("&")));
}
/*!
Constructs a QContactManager whose implementation version, manager name and specific parameters
are specified in the given \a managerUri, and whose parent object is \a parent.
\since 1.0
*/
QContactManager* QContactManager::fromUri(const QString& managerUri, QObject* parent)
{
if (managerUri.isEmpty()) {
return new QContactManager(QString(), QMap<QString, QString>(), parent);
} else {
QString id;
QMap<QString, QString> parameters;
if (parseUri(managerUri, &id, ¶meters)) {
return new QContactManager(id, parameters, parent);
} else {
// invalid
return new QContactManager(QLatin1String("invalid"), QMap<QString, QString>(), parent);
}
}
}
/*!
Constructs a QContactManager whose parent QObject is \a parent.
The default implementation for the platform will be created.
\since 1.0
*/
QContactManager::QContactManager(QObject* parent)
: QObject(parent),
d(new QContactManagerData)
{
createEngine(QString(), QMap<QString, QString>());
}
/*!
Constructs a QContactManager whose implementation is identified by \a managerName with the given \a parameters.
The \a parent QObject will be used as the parent of this QContactManager.
If an empty \a managerName is specified, the default implementation for the platform will
be used.
\since 1.0
*/
QContactManager::QContactManager(const QString& managerName, const QMap<QString, QString>& parameters, QObject* parent)
: QObject(parent),
d(new QContactManagerData)
{
createEngine(managerName, parameters);
}
void QContactManager::createEngine(const QString& managerName, const QMap<QString, QString>& parameters)
{
d->createEngine(managerName, parameters);
QContactManagerData::m_aliveEngines.insert(this);
}
/*!
Constructs a QContactManager whose backend has the name \a managerName and version \a implementationVersion, where the manager
is constructed with the provided \a parameters.
The \a parent QObject will be used as the parent of this QContactManager.
If an empty \a managerName is specified, the default implementation for the platform will be instantiated.
If the specified implementation version is not available, the manager with the name \a managerName with the default implementation version is instantiated.
\since 1.0
*/
QContactManager::QContactManager(const QString& managerName, int implementationVersion, const QMap<QString, QString>& parameters, QObject* parent)
: QObject(parent),
d(new QContactManagerData)
{
QMap<QString, QString> params = parameters;
params[QString(QLatin1String(QTCONTACTS_IMPLEMENTATION_VERSION_NAME))] = QString::number(implementationVersion);
createEngine(managerName, params);
}
/*! Frees the memory used by the QContactManager */
QContactManager::~QContactManager()
{
QContactManagerData::m_aliveEngines.remove(this);
delete d;
}
/*!
\variable QContactManager::ParameterSignalSources
The string constant for the parameter key which holds the value for signal sources.
If a manager supports suppressing change signals depending on the value given for
this construction parameter, clients can request that signals be suppressed if the
changes which might cause a signal to be emitted do not match particular criteria.
If the parameter (or value given for the parameter) is not supported by the manager,
the manager may still be constructed, however the parameter will not be reported
to the client if the client calls managerParameters() subsequent to manager construction.
The default (assumed) value for this parameter, if this parameter is not given,
is that the client wants to be notified of all changes to the data, regardless of
the source of the change.
*/
Q_DEFINE_LATIN1_CONSTANT(QContactManager::ParameterSignalSources, "SignalSources");
/*!
\variable QContactManager::ParameterSignalDefinitions
The string constant for the parameter key which holds the names of detail definitions.
If a manager supports suppressing change signals depending on the value given for
this construction parameter, clients can request that signals be suppressed if the
changes which might otherwise cause a signal to be emitted, involve details whose
definition name is not contained in the given list.
That is, if a detail in a contact is changed, but that detail's definition name is
not listed in the value for this parameter, the manager will not emit a change signal
for that change.
If this parameter is not specified at construction time, changes to any detail of a contact
will cause a change signal to be emitted.
The value of this parameter should be a comma (,) separated list of definition names. Any
commas which might be part of a definition name must be escaped with a single backslash
(\) character prior to concatenation. Any backslash character which might be part of a
definition name must also be escaped with a backslash.
If the parameter (or value given for the parameter) is not supported by the manager,
the manager may still be constructed, however the parameter will not be reported
to the client if the client calls managerParameters() subsequent to manager construction.
*/
Q_DEFINE_LATIN1_CONSTANT(QContactManager::ParameterSignalDefinitions, "SignalDefinitions");
/*!
\variable QContactManager::ParameterValueOnlyOtherManagers
This value tells the manager to only emit signals for changes which
are made in other manager instances. That is, the client wishes to receive
change signals when another client (or background service) changes
the data as it is stored in the backend, but does not wish to be
notified of changes (or side effects) which it has caused itself.
*/
Q_DEFINE_LATIN1_CONSTANT(QContactManager::ParameterValueOnlyOtherManagers, "OnlyOtherManagers");
/*!
\variable QContactManager::ParameterValueOnlyOtherProcesses
This value tells the manager to only emit signals for changes which
are made in other processes. That is, the client wishes to receive
change signals when a client (or background service) in another process changes
the data as it is stored in the backend, but does not wish to be
notified of changes (or side effects) which were caused in the current client's
process, even if those changes were made in a different manager instance to this
one.
*/
Q_DEFINE_LATIN1_CONSTANT(QContactManager::ParameterValueOnlyOtherProcesses, "OnlyOtherProcesses");
/*!
\enum QContactManager::Error
This enum specifies an error that occurred during the most recent operation:
\value NoError The most recent operation was successful
\value DoesNotExistError The most recent operation failed because the requested contact or detail definition does not exist
\value AlreadyExistsError The most recent operation failed because the specified contact or detail definition already exists
\value InvalidDetailError The most recent operation failed because the specified contact contains details which do not conform to their definition
\value InvalidRelationshipError The most recent operation failed because the specified relationship is circular or references an invalid local contact
\value InvalidContactTypeError The most recent operation failed because the contact type specified was not valid for the operation
\value LockedError The most recent operation failed because the datastore specified is currently locked
\value DetailAccessError The most recent operation failed because a detail was modified or removed and its access method does not allow that
\value PermissionsError The most recent operation failed because the caller does not have permission to perform the operation
\value OutOfMemoryError The most recent operation failed due to running out of memory
\value VersionMismatchError The most recent operation failed because the backend of the manager is not of the required version
\value LimitReachedError The most recent operation failed because the limit for that type of object has been reached
\value NotSupportedError The most recent operation failed because the requested operation is not supported in the specified store
\value BadArgumentError The most recent operation failed because one or more of the parameters to the operation were invalid
\value TimeoutError The most recent operation failed because it took longer than expected. It may be possible to try again.
\value UnspecifiedError The most recent operation failed for an undocumented reason
*/
/*!
Return the error code of the most recent operation.
For batch operations, if the error code is not equal to
\c QContactManager::NoError, detailed per-input errors
may be retrieved by calling \l errorMap().
\sa errorMap()
\since 1.0
*/
QContactManager::Error QContactManager::error() const
{
return d->m_lastError;
}
/*!
Returns per-input error codes for the most recent operation.
This function only returns meaningful information if the most
recent operation was a batch operation.
Each key in the map is the index of the element in the input list
for which the error (whose error code is stored in the value for
that key in the map) occurred during the batch operation.
\sa error(), contacts(), saveContacts(), removeContacts(), saveRelationships(), removeRelationships()
\since 1.0
*/
QMap<int, QContactManager::Error> QContactManager::errorMap() const
{
return d->m_lastErrorMap;
}
/*!
Return the list of contact ids, sorted according to the given list of \a sortOrders
\since 1.0
*/
QList<QContactLocalId> QContactManager::contactIds(const QList<QContactSortOrder>& sortOrders) const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->contactIds(QContactFilter(), sortOrders, &h.error);
}
/*!
Returns a list of contact ids that match the given \a filter, sorted according to the given list of \a sortOrders.
Depending on the backend, this filtering operation may involve retrieving all the contacts.
\since 1.0
*/
QList<QContactLocalId> QContactManager::contactIds(const QContactFilter& filter, const QList<QContactSortOrder>& sortOrders) const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->contactIds(filter, sortOrders, &h.error);
}
/*!
Returns the list of contacts stored in the manager sorted according to the given list of \a sortOrders.
The \a fetchHint parameter describes the optimization hints that a manager may take.
If the \a fetchHint is the default constructed hint, all existing details, relationships and
action preferences in the matching contact will be returned. If a client makes changes to an
contact which has been retrieved with a fetch hint, they should save it back using a partial save,
masked by the same set of detail names in order to avoid information loss.
\sa QContactFetchHint
\since 1.0
*/
QList<QContact> QContactManager::contacts(const QList<QContactSortOrder>& sortOrders, const QContactFetchHint& fetchHint) const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->contacts(QContactFilter(), sortOrders, fetchHint, &h.error);
}
/*!
Returns a list of contacts that match the given \a filter, sorted according to the given list of \a sortOrders.
Depending on the manager implementation, this filtering operation might be slow and involve retrieving all the
contacts and testing them against the supplied filter - see the \l isFilterSupported() function.
The \a fetchHint parameter describes the optimization hints that a manager may take.
If the \a fetchHint is the default constructed hint, all existing details, relationships and
action preferences in the matching contact will be returned. If a client makes changes to an
contact which has been retrieved with a fetch hint, they should save it back using a partial save,
masked by the same set of detail names in order to avoid information loss.
\sa QContactFetchHint
\since 1.0
*/
QList<QContact> QContactManager::contacts(const QContactFilter& filter, const QList<QContactSortOrder>& sortOrders, const QContactFetchHint& fetchHint) const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->contacts(filter, sortOrders, fetchHint, &h.error);
}
/*!
Returns the contact in the database identified by \a contactId.
If the contact does not exist, an empty, default constructed QContact will be returned,
and the error returned by \l error() will be \c QContactManager::DoesNotExistError.
The \a fetchHint parameter describes the optimization hints that a manager may take.
If the \a fetchHint is the default constructed hint, all existing details, relationships and
action preferences in the matching contact will be returned. If a client makes changes to an
contact which has been retrieved with a fetch hint, they should save it back using a partial save,
masked by the same set of detail names in order to avoid information loss.
\since 1.0
\sa QContactFetchHint
*/
QContact QContactManager::contact(const QContactLocalId& contactId, const QContactFetchHint& fetchHint) const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->contact(contactId, fetchHint, &h.error);
}
/*!
Returns a list of contacts given a list of local ids (\a localIds).
Returns the list of contacts with the ids given by \a localIds. There is a one-to-one
correspondence between the returned contacts and the supplied \a localIds.
If there is an invalid id in \a localIds, then an empty QContact will take its place in the
returned list. The deprecated \a errorMap parameter can be supplied to store per-input errors in.
In all cases, calling \l errorMap() will return the per-input errors for the latest batch function.
The \a fetchHint parameter describes the optimization hints that a manager may take.
If the \a fetchHint is the default constructed hint, all existing details, relationships and
action preferences in the matching contact will be returned. If a client makes changes to an
contact which has been retrieved with a fetch hint, they should save it back using a partial save,
masked by the same set of detail names in order to avoid information loss.
\sa QContactFetchHint
*/
QList<QContact> QContactManager::contacts(const QList<QContactLocalId>& localIds, const QContactFetchHint &fetchHint, QMap<int, QContactManager::Error> *errorMap) const
{
QContactManagerSyncOpErrorHolder h(this, errorMap);
return d->m_engine->contacts(localIds, fetchHint, &h.errorMap, &h.error);
}
/*!
Adds the given \a contact to the database if \a contact has a
default-constructed id, or an id with the manager URI set to the URI of
this manager and a local id of zero.
Alternatively, the function will update the existing contact in the database if \a contact
has a manager URI set to the URI of this manager and a non-zero local id and currently
exists in the database.
If the id of \a contact does not match any of these two descriptions, the operation will
fail and calling error() will return \c QContactManager::DoesNotExistError.
If the \a contact contains one or more details whose definitions have
not yet been saved with the manager, the operation will fail and calling
error() will return \c QContactManager::UnsupportedError.
If the \a contact has had its relationships reordered, the manager
will check to make sure that every relationship that the contact is currently
involved in is included in the reordered list, and that no relationships which
either do not involve the contact, or have not been saved in the manager are
included in the list. If these conditions are not met, the function will
return \c false and calling error() will return
\c QContactManager::InvalidRelationshipError.
Returns false on failure, or true on
success. On successful save of a contact with a local id of zero, its
id will be set to a new, valid id with the manager URI set to the URI of
this manager, and the local id set to a new, valid local id.
The manager will automatically synthesize the display label of the contact when it is saved.
The manager is not required to fetch updated details of the contact on save,
and as such, clients should fetch a contact if they want the most up-to-date information
by calling \l QContactManager::contact().
\since 1.0
\sa managerUri()
*/
bool QContactManager::saveContact(QContact* contact)
{
QContactManagerSyncOpErrorHolder h(this);
if (contact) {
return d->m_engine->saveContact(contact, &h.error);
} else {
h.error = QContactManager::BadArgumentError;
return false;
}
}
/*!
Remove the contact identified by \a contactId from the database,
and also removes any relationships in which the contact was involved.
Returns true if the contact was removed successfully, otherwise
returns false.
\since 1.0
*/
bool QContactManager::removeContact(const QContactLocalId& contactId)
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->removeContact(contactId, &h.error);
}
/*!
Adds the list of contacts given by \a contacts list to the database.
Returns true if the contacts were saved successfully, otherwise false.
The deprecated \a errorMap parameter can be supplied to store per-input errors in.
In all cases, calling \l errorMap() will return the per-input errors for the latest batch function.
The \l QContactManager::error() function will only return \c QContactManager::NoError
if all contacts were saved successfully.
For each newly saved contact that was successful, the id of the contact
in the \a contacts list will be updated with the new value.
\since 1.0
\sa QContactManager::saveContact()
*/
bool QContactManager::saveContacts(QList<QContact>* contacts, QMap<int, QContactManager::Error>* errorMap)
{
QContactManagerSyncOpErrorHolder h(this, errorMap);
if (contacts) {
return d->m_engine->saveContacts(contacts, &h.errorMap, &h.error);
} else {
h.error = QContactManager::BadArgumentError;
return false;
}
}
/*!
Adds the list of contacts given by \a contacts list to the database.
Returns true if the contacts were saved successfully, otherwise false.
This function accepts a \a definitionMask, which specifies which details of
the contacts should be added or updated. Details with definition names not included in
the definitionMask will not be updated or added.
The deprecated \a errorMap parameter can be supplied to store per-input errors in.
In all cases, calling \l errorMap() will return the per-input errors for the latest batch function.
The \l QContactManager::error() function will only return \c QContactManager::NoError
if all contacts were saved successfully.
For each newly saved contact that was successful, the id of the contact
in the \a contacts list will be updated with the new value.
\sa QContactManager::saveContact()
*/
bool QContactManager::saveContacts(QList<QContact>* contacts, const QStringList& definitionMask, QMap<int, QContactManager::Error>* errorMap)
{
QContactManagerSyncOpErrorHolder h(this, errorMap);
if (contacts) {
return d->m_engine->saveContacts(contacts, definitionMask, &h.errorMap, &h.error);
} else {
h.error = QContactManager::BadArgumentError;
return false;
}
}
/*!
Remove every contact whose id is contained in the list of contacts ids
\a contactIds. Returns true if all contacts were removed successfully,
otherwise false.
Any contact that was removed successfully will have the relationships
in which it was involved removed also.
The deprecated \a errorMap parameter can be supplied to store per-input errors in.
In all cases, calling \l errorMap() will return the per-input errors for the latest batch function.
The \l QContactManager::error() function will
only return \c QContactManager::NoError if all contacts were removed
successfully.
If the given list of contact ids \a contactIds is empty, the function will return false
and calling error() will return \c QContactManager::BadArgumentError. If the list is non-empty
and contains ids which do not identify a valid contact in the manager, the function will
remove any contacts which are identified by ids in the \a contactIds list, insert
\c QContactManager::DoesNotExist entries into the \a errorMap for the indices of invalid ids
in the \a contactIds list, return false, and set the overall operation error to
\c QContactManager::DoesNotExistError.
\since 1.0
\sa QContactManager::removeContact()
*/
bool QContactManager::removeContacts(const QList<QContactLocalId>& contactIds, QMap<int, QContactManager::Error>* errorMap)
{
QContactManagerSyncOpErrorHolder h(this, errorMap);
if (!contactIds.isEmpty()) {
return d->m_engine->removeContacts(contactIds, &h.errorMap, &h.error);
} else {
h.error = QContactManager::BadArgumentError;
return false;
}
}
/*!
Returns a pruned or modified version of the \a original contact which is valid and can be saved in the manager.
The returned contact might have entire details removed or arbitrarily changed. The cache of relationships
in the contact are ignored entirely when considering compatibility with the backend, as they are
saved and validated separately.
\since 1.0
*/
QContact QContactManager::compatibleContact(const QContact& original)
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->compatibleContact(original, &h.error);
}
/*!
Returns a display label for a \a contact which is synthesized from its details in a manager specific
manner.
If you want to update the display label stored in the contact, use the synthesizeContactDisplayLabel()
function instead.
Note: Depending on the used engine it is possible that the data
that is used to synthesize the display label is not up-to-date
after a partial save of the contact, i.e after the contact was
saved with \l saveContacts() with a \a definitionMask parameter.
It is recommended to fetch the contact from the engine again and
use that new contact as a parameter to this function.
Right now this is needed for the tracker engine on the Harmattan platform.
\since 1.0
\sa synthesizeContactDisplayLabel(), saveContacts()
*/
QString QContactManager::synthesizedContactDisplayLabel(const QContact& contact) const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->synthesizedDisplayLabel(contact, &h.error);
}
/*!
* Updates the display label of the supplied \a contact, according to the formatting rules
* of this manager.
*
* Different managers can format the display label of a contact in different ways -
* some managers may only consider first or last name, or might put them in different
* orders. Others might consider an organization, a nickname, or a freeform label.
*
* This function will update the QContactDisplayLabel of this contact, and the string
* returned by QContact::displayLabel().
*
* If \a contact is null, nothing will happen.
*
* See the following example for more information:
* \snippet doc/src/snippets/qtcontactsdocsample/qtcontactsdocsample.cpp Updating the display label of a contact
*
* Note: Depending on the used engine it is possible that the data
* that is used to synthesize the display label is not up-to-date
* after a partial save of the contact, i.e after the contact was
* saved with \l saveContacts() with a \a definitionMask parameter.
* It is recommended to fetch the contact from the engine again and
* use that new contact as a parameter to this function.
* Right now this is needed for the tracker engine on the Harmattan platform.
*
* \since 1.0
* \sa synthesizedContactDisplayLabel(), QContact::displayLabel(), saveContacts()
*/
void QContactManager::synthesizeContactDisplayLabel(QContact *contact) const
{
QContactManagerSyncOpErrorHolder h(this);
if (contact) {
QContactManagerEngine::setContactDisplayLabel(contact, d->m_engine->synthesizedDisplayLabel(*contact, &h.error));
} else {
h.error = QContactManager::BadArgumentError;
}
}
/*!
Sets the id of the "self" contact to the given \a contactId.
Returns true if the "self" contact id was set successfully.
If the given \a contactId does not identify a contact
stored in this manager, the error will be set to
\c QContactManager::DoesNotExistError and the function will
return false; if the backend does not support the
concept of a "self" contact then the error will be set to
\c QContactManager::NotSupportedError and the function will
return false.
\since 1.0
*/
bool QContactManager::setSelfContactId(const QContactLocalId& contactId)
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->setSelfContactId(contactId, &h.error);
}
/*!
Returns the id of the "self" contact which has previously been set.
If no "self" contact has been set, or if the self contact was removed
from the manager after being set, or if the backend does not support
the concept of a "self" contact, an invalid id will be returned
and the error will be set to \c QContactManager::DoesNotExistError.
\since 1.0
*/
QContactLocalId QContactManager::selfContactId() const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->selfContactId(&h.error);
}
/*!
Returns a list of relationships in which the contact identified by the given \a participantId participates in the given \a role.
If \a participantId is the default-constructed id, \a role is ignored and all relationships are returned.
\since 1.0
*/
QList<QContactRelationship> QContactManager::relationships(const QContactId& participantId, QContactRelationship::Role role) const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->relationships(QString(), participantId, role, &h.error);
}
/*!
Returns a list of relationships of the given \a relationshipType in which the contact identified by the given \a participantId participates in the given \a role.
If \a participantId is the default-constructed id, \a role is ignored and all relationships of the given \a relationshipType are returned.
If \a relationshipType is empty, relationships of any type are returned.
\since 1.0
*/
QList<QContactRelationship> QContactManager::relationships(const QString& relationshipType, const QContactId& participantId, QContactRelationship::Role role) const
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->relationships(relationshipType, participantId, role, &h.error);
}
/*!
Saves the given \a relationship in the database. If the relationship already exists in the database, this function will
return \c false and the error will be set to \c QContactManager::AlreadyExistsError.
If the relationship is saved successfully, this function will return \c true and error will be set
to \c QContactManager::NoError. Note that relationships cannot be updated directly using this function; in order
to update a relationship, you must remove the old relationship, make the required modifications, and then save it.
The given relationship is invalid if it is circular (the first contact is the second contact), or
if it references a non-existent local contact (either the first or second contact). If the given \a relationship is invalid,
the function will return \c false and the error will be set to \c QContactManager::InvalidRelationshipError.
If the given \a relationship could not be saved in the database (due to backend limitations)
the function will return \c false and error will be set to \c QContactManager::NotSupportedError.
\since 1.0
*/
bool QContactManager::saveRelationship(QContactRelationship* relationship)
{
QContactManagerSyncOpErrorHolder h(this);
if (relationship) {
return d->m_engine->saveRelationship(relationship, &h.error);
} else {
h.error = QContactManager::BadArgumentError;
return false;
}
}
/*!
Saves the given \a relationships in the database and returns true if the operation was successful.
The deprecated \a errorMap parameter can be supplied to store per-input errors in.
In all cases, calling \l errorMap() will return the per-input errors for the latest batch function.
\since 1.0
*/
bool QContactManager::saveRelationships(QList<QContactRelationship>* relationships, QMap<int, QContactManager::Error>* errorMap)
{
QContactManagerSyncOpErrorHolder h(this, errorMap);
if (relationships) {
return d->m_engine->saveRelationships(relationships, &h.errorMap, &h.error);
} else {
h.error = QContactManager::BadArgumentError;
return false;
}
}
/*!
Removes the given \a relationship from the manager. If the relationship exists in the manager, the relationship
will be removed, the error will be set to \c QContactManager::NoError and this function will return true. If no such
relationship exists in the manager, the error will be set to \c QContactManager::DoesNotExistError and this function
will return false.
\since 1.0
*/
bool QContactManager::removeRelationship(const QContactRelationship& relationship)
{
QContactManagerSyncOpErrorHolder h(this);
return d->m_engine->removeRelationship(relationship, &h.error);
}
/*!
Removes the given \a relationships from the database and returns true if the operation was successful.
The deprecated \a errorMap parameter can be supplied to store per-input errors in.
In all cases, calling \l errorMap() will return the per-input errors for the latest batch function.
\since 1.0
*/
bool QContactManager::removeRelationships(const QList<QContactRelationship>& relationships, QMap<int, QContactManager::Error>* errorMap)
{
QContactManagerSyncOpErrorHolder h(this, errorMap);
return d->m_engine->removeRelationships(relationships, &h.errorMap, &h.error);
}
/*!
Returns a map of identifier to detail definition for the registered detail definitions which are valid for contacts whose type is the given \a contactType
which are valid for the contacts in this store
\since 1.0
*/
QMap<QString, QContactDetailDefinition> QContactManager::detailDefinitions(const QString& contactType) const
{
QContactManagerSyncOpErrorHolder h(this);
if (!supportedContactTypes().contains(contactType)) {
h.error = QContactManager::InvalidContactTypeError;
return QMap<QString, QContactDetailDefinition>();
}
return d->m_engine->detailDefinitions(contactType, &h.error);
}
/*! Returns the definition identified by the given \a definitionName that is valid for the contacts whose type is the given \a contactType in this store, or a default-constructed QContactDetailDefinition if no such definition exists
\since 1.0
*/
QContactDetailDefinition QContactManager::detailDefinition(const QString& definitionName, const QString& contactType) const
{
QContactManagerSyncOpErrorHolder h(this);
if (!supportedContactTypes().contains(contactType)) {
h.error = QContactManager::InvalidContactTypeError;
return QContactDetailDefinition();
}
return d->m_engine->detailDefinition(definitionName, contactType, &h.error);
}
/*! Persists the given definition \a def in the database, which is valid for contacts whose type is the given \a contactType. Returns true if the definition was saved successfully, otherwise returns false
\since 1.0
*/
bool QContactManager::saveDetailDefinition(const QContactDetailDefinition& def, const QString& contactType)
{
QContactManagerSyncOpErrorHolder h(this);
if (!supportedContactTypes().contains(contactType)) {
h.error = QContactManager::InvalidContactTypeError;
return false;
}
return d->m_engine->saveDetailDefinition(def, contactType, &h.error);
}
/*! Removes the detail definition identified by \a definitionName from the database, which is valid for contacts whose type is the given \a contactType. Returns true if the definition was removed successfully, otherwise returns false \since 1.0
*/
bool QContactManager::removeDetailDefinition(const QString& definitionName, const QString& contactType)
{
QContactManagerSyncOpErrorHolder h(this);
if (!supportedContactTypes().contains(contactType)) {
h.error = QContactManager::InvalidContactTypeError;
return false;
}
return d->m_engine->removeDetailDefinition(definitionName, contactType, &h.error);
}
/*!
\enum QContactManager::ManagerFeature
This enum describes the possible features that a particular manager may support
\value Groups The manager supports saving contacts of the \c QContactType::TypeGroup type
\value ActionPreferences The manager supports saving preferred details per action per contact
\value DetailOrdering When a contact is retrieved, the manager will return the details in the same order in which they were saved
\value Relationships The manager supports at least some types of relationships between contacts
\value ArbitraryRelationshipTypes The manager supports relationships of arbitrary types between contacts
\value MutableDefinitions The manager supports saving, updating or removing detail definitions. Some built-in definitions may still be immutable
\value SelfContact The manager supports the concept of saving a contact which represents the current user
\value ChangeLogs The manager supports reporting of timestamps of changes, and filtering and sorting by those timestamps
\value Anonymous The manager is isolated from other managers
*/
/*!
Returns true if the given feature \a feature is supported by the manager, for the specified type of contact \a contactType
\since 1.0
*/
bool QContactManager::hasFeature(QContactManager::ManagerFeature feature, const QString& contactType) const
{
return d->m_engine->hasFeature(feature, contactType);
}
/*!
Returns the list of data types supported by the manager
\since 1.0
*/
QList<QVariant::Type> QContactManager::supportedDataTypes() const
{
return d->m_engine->supportedDataTypes();
}
/*!
Returns true if the given \a filter is supported natively by the
manager, and false if the filter behaviour would be emulated.
Note: In some cases, the behaviour of an unsupported filter
cannot be emulated. For example, a filter that requests contacts
that have changed since a given time depends on having that information
available. In these cases, the filter will fail.
\since 1.0
*/
bool QContactManager::isFilterSupported(const QContactFilter& filter) const
{
return d->m_engine->isFilterSupported(filter);
}
/*!
Returns true if the manager supports the relationship type specified in \a relationshipType for
contacts whose type is the given \a contactType.
Note that some managers may support the relationship type for a contact in a limited manner
(for example, only as the first contact in the relationship, or only as the second contact
in the relationship). In this case, it will still return true. It will only return false
if the relationship is entirely unsupported for the given type of contact.
\since 1.0
*/
bool QContactManager::isRelationshipTypeSupported(const QString& relationshipType, const QString& contactType) const
{
return d->m_engine->isRelationshipTypeSupported(relationshipType, contactType);
}
/*!
Returns the list of contact types which are supported by this manager.
This is a convenience function, equivalent to retrieving the allowable values
for the \c QContactType::FieldType field of the QContactType definition
which is valid in this manager.
\since 1.0
*/
QStringList QContactManager::supportedContactTypes() const
{
return d->m_engine->supportedContactTypes();
}
/*!
Returns the engine backend implementation version number
*/
int QContactManager::managerVersion() const
{
return d->m_engine->managerVersion();
}
/*! Returns the manager name for this QContactManager */
QString QContactManager::managerName() const
{
return d->m_engine->managerName();
}
/*! Return the parameters relevant to the creation of this QContactManager */
QMap<QString, QString> QContactManager::managerParameters() const
{
QMap<QString, QString> params = d->m_engine->managerParameters();
params.remove(QString::fromAscii(QTCONTACTS_VERSION_NAME));
params.remove(QString::fromAscii(QTCONTACTS_IMPLEMENTATION_VERSION_NAME));
return params;
}
/*!
Return the uri describing this QContactManager, consisting of the manager name and any parameters.
\since 1.0
*/
QString QContactManager::managerUri() const
{
return d->m_engine->managerUri();
}
/*!
\internal
When someone connects to this manager, connect the corresponding signal from the engine, if we
haven't before. If we have, just increment a count.
This allows lazy evaluation on the engine side (e.g. setting up dbus watchers) and prevents
unnecessary work.
*/
void QContactManager::connectNotify(const char *signal)
{
/* For most signals we just connect from the engine to ourselves, since we just proxy, but we should connect only once */
QByteArray ba(signal);
if (!d->m_connectedSignals.contains(ba)) {
// As a special case, we know that the V2 wrapper just proxies all the signals
// so we skip the second proxy. If a wrapper ever emits signals itself then we
// can't do this.
connect(d->m_signalSource, signal, this, signal);
}
d->m_connectedSignals[ba]++;
}
/*!
\internal
When someone disconnects, disconnect from the engine too if there are no more users of that signal.
*/
void QContactManager::disconnectNotify(const char *signal)
{
QByteArray ba(signal);
if (d->m_connectedSignals[ba] <= 1) {
disconnect(d->m_signalSource, signal, this, signal);
d->m_connectedSignals.remove(ba);
} else {
d->m_connectedSignals[ba]--;
}
}
#include "moc_qcontactmanager.cpp"
QTM_END_NAMESPACE
| lgpl-2.1 |
jadahl/jgroups-android | tests/other/org/jgroups/tests/StringTest.java | 2044 | package org.jgroups.tests;
/**
* @author Bela Ban
* @version $Id: StringTest.java,v 1.1.20.1 2008/01/22 10:01:30 belaban Exp $
*/
public class StringTest {
final int NUM=1000000;
long start, stop;
public static void main(String[] args) {
new StringTest().start();
}
private void start() {
rawStringsWithObjects();
rawStringsWithLiterals();
StringBuilder();
}
private void rawStringsWithObjects() {
String result=null;
String a="a", b="b", c="c", d="d";
long time=System.currentTimeMillis();
start=System.currentTimeMillis();
for(int i=0; i < NUM; i++) {
result=a + b + c + d + "ecdsfh" + time;
}
stop=System.currentTimeMillis();
System.out.println("total time for rawStringsWithObjects(): " + (stop-start));
System.out.println("result=" + result);
}
private void rawStringsWithLiterals() {
String result=null;
long time=System.currentTimeMillis();
start=System.currentTimeMillis();
for(int i=0; i < NUM; i++) {
result="a" + "b" + "c" + "d" + "ecdsfh" + time; // needs runtime resolution
// result="a" + "b" + "c" + "d" + "ecdsfh" + 322463; // is concatenated at *compile time*
}
stop=System.currentTimeMillis();
System.out.println("total time for rawStringsWithLiterals(): " + (stop-start));
System.out.println("result=" + result);
}
private void StringBuilder() {
String result=null;
StringBuilder sb;
long time=System.currentTimeMillis();
start=System.currentTimeMillis();
for(int i=0; i < NUM; i++) {
sb=new StringBuilder("a");
sb.append("b").append("c").append("d").append("ecdsfh").append(time);
result=sb.toString();
}
stop=System.currentTimeMillis();
System.out.println("total time for StringBuilder(): " + (stop-start));
System.out.println("result=" + result);
}
}
| lgpl-2.1 |
tikiorg/tiki | lib/accounting/accountinglib.php | 52539 | <?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
// this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
$logslib = TikiLib::lib('logs');
/**
* Basic functions used by the accounting feature
*
* <p>This file contains all functions used by more than one file from the ccsg_accounting feature.
* This feature is a simple accounting/bookkeeping function.</p>
*
* @package accounting
* @author Joern Ott <white@ott-service.de>
* @version 1.2
* @date 2010-11-16
* @copyright LGPL
*/
class AccountingLib extends LogsLib
{
/**
*
* Storing the book data if already requested once, this may save us a few queries
* @var array $_book array with the books structure
*/
private $_book = '';
/**
* Lists all books available to a user
* @param string $order sorting order
* @return array list of books (complete table structure)
*/
function listBooks($order = 'bookId ASC')
{
$query = "SELECT * FROM tiki_acct_book ORDER BY $order";
return $this->fetchAll($query, []);
}
/**
*
* Creates a new book and gives full permissions to the creator
* @param string $bookName descriptive name of the book
* @param string $bookStartDate first permitted date for the book
* @param string $bookEndDate last permitted date for the book
* @param string $bookCurrency up to 3 letter cuurency code
* @param int $bookCurrencyPos where should the currency symbol appear -1=before, 1=after
* @param int $bookDecimals number of decimal points
* @param string $bookDecPoint separator for the decimal point
* @param string $bookThousand separator for the thousands
* @param string $exportSeparator separator between fields when exporting CSV
* @param string $exportEOL end of line definition, either CR, LF or CRLF
* @param string $exportQuote Quote character to enclose strings in CSV
* @param string $bookClosed 'y' if the book is closed (no more changes), 'n' otherwise
* @param string $bookAutoTax
* @return int/string bookId on success, error message otherwise
*/
function createBook($bookName, $bookClosed = 'n', $bookStartDate, $bookEndDate, $bookCurrency, $bookCurrencyPos = -1, $bookDecimals, $bookDecPoint, $bookThousand, $exportSeparator, $exportEOL, $exportQuote, $bookAutoTax = 'y'
)
{
global $user;
$userlib = TikiLib::lib('user');
if (strlen($bookName) == 0) {
return "The book must have a name";
}
if (strtotime($bookStartDate) === false) {
return "Invalid start date";
}
if (strtotime($bookEndDate) === false) {
return "Invalid end date";
}
$query = "INSERT INTO `tiki_acct_book`" .
" (`bookName`, `bookClosed`, `bookStartDate`, `bookEndDate`," .
" `bookCurrency`, `bookCurrencyPos`, `bookDecimals`, `bookDecPoint`, `bookThousand`," .
" `exportSeparator`, `exportEOL`, `exportQuote`, `bookAutoTax`)" .
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$res = $this->query(
$query,
[
$bookName,
$bookClosed,
$bookStartDate,
$bookEndDate,
$bookCurrency,
$bookCurrencyPos,
$bookDecimals,
$bookDecPoint,
$bookThousand,
$exportSeparator,
$exportEOL,
$exportQuote,
$bookAutoTax
]
);
$bookId = $this->lastInsertId();
$this->createTax($bookId, tra('No automated tax'), 0, 'n');
$groupId = $bookId;
do {
//make sure we don't have that group already
$groupname = "accounting_book_$groupId";
$groupexists = $userlib->group_exists($groupname);
if ($groupexists) {
$groupId++;
}
} while ($groupexists);
if ($groupId != $bookId) {
$query = "UPDATE `tiki_acct_book` SET `bookId`=? WHERE `bookId`=?";
$res = $this->query($query, [$groupId, $bookId]);
$bookId = $groupId;
}
$userlib->add_group($groupname);
$userlib->assign_user_to_group($user, $groupname);
$userlib->assign_object_permission($groupname, $bookId, 'accounting book', 'tiki_p_acct_view');
$userlib->assign_object_permission($groupname, $bookId, 'accounting book', 'tiki_p_acct_book');
$userlib->assign_object_permission($groupname, $bookId, 'accounting book', 'tiki_p_acct_manage_accounts');
$userlib->assign_object_permission($groupname, $bookId, 'accounting book', 'tiki_p_acct_book_stack');
$userlib->assign_object_permission($groupname, $bookId, 'accounting book', 'tiki_p_acct_book_import');
$userlib->assign_object_permission($groupname, $bookId, 'accounting book', 'tiki_p_acct_manage_template');
return $bookId;
}
/**
*
* Returns the details for a book with a given bookId
* @param int $bookId Id of the book to retrieve the data for
* @return array Array with book details
*/
function getBook($bookId)
{
if (! is_array($this->_book) or $this->_book['bookId'] != $bookId) {
$query = "SELECT * FROM `tiki_acct_book` WHERE `bookId`=?";
$res = $this->query($query, [$bookId]);
$this->_book = $res->fetchRow();
}
return $this->_book;
}
/**
*
* This function sets a books status to closed, so transactions can no longer be used
* @param int $bookId id of the book to close
* @return bool true on success
*/
function closeBook($bookId)
{
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
return false;
}
$query = "UPDATE `tiki_acct_book` SET `bookClosed`='y' WHERE `bookId`=?";
$res = $this->query($query, [$bookId]);
if ($res === false) {
return false;
}
return true;
}
/**
* Returns the complete journal for a given account, if none is provided, the whole journal will be fetched
*
* @param int $bookId id of the current book
* @param int $accountId account for which we should display the journal, defaults to '%' (all accounts)
* @param string $order sorting order
* @param int $limit max number of records to fetch, defaults to 0 = all
* @return array|bool journal with all posts, false on errors
*/
function getJournal($bookId, $accountId = '%', $order = '`journalId` ASC', $limit = 0)
{
$journal = [];
if ($limit != 0) {
if ($limit < 0) {
$order = str_replace("ASC", "DESC", $order);
}
$order .= " LIMIT " . abs($limit);
}
if ($accountId == '%') {
$query = "SELECT `journalId`, `journalDate`, `journalDescription`, `journalCancelled`" .
" FROM `tiki_acct_journal`" .
" WHERE `journalBookId`=?" .
" ORDER BY $order";
$res = $this->query($query, [$bookId]);
} else {
$query = "SELECT `journalId`, `journalDate`, `journalDescription`, `journalCancelled`" .
" FROM `tiki_acct_journal` INNER JOIN `tiki_acct_item`" .
" ON (`tiki_acct_journal`.`journalBookId`=`tiki_acct_item`.`itemBookId` AND" .
" `tiki_acct_journal`.`journalId`=`tiki_acct_item`.`itemJournalId`)" .
" WHERE `journalBookId`=? AND `itemAccountId` LIKE ?" .
" GROUP BY `journalId`, `journalDate`, `journalDescription`, `journalCancelled`" .
" ORDER BY $order";
$res = $this->query($query, [$bookId, $accountId]);
}
if ($res === false) {
return false;
}
while ($row = $res->fetchRow()) {
$query = "SELECT * FROM `tiki_acct_item` WHERE `itemBookId`=? AND `itemJournalId`=? AND `itemType`=? ORDER BY `itemAccountId` ASC";
$row['debit'] = $this->fetchAll($query, [$bookId, $row['journalId'], -1]);
$row['debitcount'] = count($row['debit']);
$row['credit'] = $this->fetchAll($query, [$bookId, $row['journalId'], 1]);
$row['creditcount'] = count($row['credit']);
$row['maxcount'] = max($row['creditcount'], $row['debitcount']);
$journal[] = $row;
}
return $journal;
}
/**
* Returns the totals for a given book and account
*
* @param int $bookId id of the current book
* @param int $accountId account for which we should fetch the totals, defaults to '%' (all accounts)
* @return array array with three elements debit, credit and the total (credit-debit)
*/
function getJournalTotals($bookId, $accountId = '%')
{
$journal = [];
$query = "SELECT `itemAccountId`, SUM(`itemAmount`*IF(`itemType`<0,1,0)) AS debit," .
" sum(`itemAmount`*IF(`itemType`>0,1,0)) AS credit" .
" FROM `tiki_acct_journal` INNER JOIN `tiki_acct_item`" .
" ON (`tiki_acct_journal`.`journalBookId`=`tiki_acct_item`.`itemBookId`" .
" AND `tiki_acct_journal`.`journalId`=`tiki_acct_item`.`itemJournalId`)" .
" WHERE `journalBookId`=? AND `itemAccountId` LIKE ?" .
" GROUP BY `itemAccountId`";
$res = $this->query($query, [$bookId, $accountId]);
$totals = $res->fetchRow();
$totals['total'] = $totals['credit'] - $totals['debit'];
return $totals;
}
/**
* Returns a list of accounts as defined in table tiki_acct_account
*
* @param int $bookId id of the book to retrieve the accounts for
* @param string $order order of items, defaults to accountId
* @param boolean $all true = fetch all accounts, false = fetch only unlocked accounts
* @return array list of accounts
*/
function getAccounts($bookId, $order = "`accountId` ASC", $all = false)
{
$query = 'SELECT * FROM `tiki_acct_account` WHERE `accountBookId`=? ' .
($all ? '' : 'AND `accountLocked`=0 ') .
" ORDER BY $order";
return $this->fetchAll($query, [$bookId]);
} //getAccounts
/**
* Returns an extended list of accounts with totals
*
* @param int $bookId id of the book to fetch the account list for
* @param bool $all true = fetch all accounts or false = only unlocked accounts, defaults to false
* @return array list of accounts
*/
function getExtendedAccounts($bookId, $all = false)
{
$allcond = $all ? '' : ' AND accountLocked=0';
$query = "SELECT accountBookId, accountId, accountName, accountNotes, accountBudget, accountLocked, " .
" SUM(itemAmount*IF(itemType<0,1,0)) AS debit, SUM(itemAmount*IF(itemType>0,1,0)) AS credit" .
" FROM tiki_acct_account" .
" LEFT JOIN tiki_acct_journal ON tiki_acct_account.accountBookId=tiki_acct_journal.journalBookId" .
" LEFT JOIN tiki_acct_item ON tiki_acct_journal.journalId=tiki_acct_item.itemJournalId" .
" AND tiki_acct_account.accountId=tiki_acct_item.itemAccountId" .
" WHERE tiki_acct_account.accountBookId=? $allcond" .
" GROUP BY accountId, accountName, accountNotes, accountBudget, accountLocked, accountBookId";
return $this->fetchAll($query, [$bookId]);
}//getExtendedAccounts
/**
* Returns an array with all data from the account
*
* @param int $bookId id of the current book
* @param int $accountId account id to retrieve
* @param boolean $checkChangeable perform check, if the account is changeable
* @return array account data or false on error
*/
function getAccount($bookId, $accountId, $checkChangeable = true)
{
$query = "SELECT * FROM `tiki_acct_account` WHERE `accountbookId`=? AND `accountId`=?";
$res = $this->query($query, [$bookId, $accountId]);
$account = $res->fetchRow();
if ($checkChangeable) {
$account['changeable'] = $this->accountChangeable($bookId, $accountId);
}
return $account;
} //getAccount
/**
* Checks if this accountId can be changed or the account can be deleted.
* This can only be done, if the account has not been used -> no posts exist for the account
*
* @param int $bookId id of the current book
* @param int $accountId account id to check
* @return boolean true, if the account can be changed/deleted
*/
function accountChangeable($bookId, $accountId)
{
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
return false;
}
$query = "SELECT Count(`itemAccountId`) AS posts" .
" FROM `tiki_acct_journal`" .
" INNER JOIN `tiki_acct_item` ON `tiki_acct_journal`.`journalId`=`tiki_acct_item`.`itemJournalId`" .
" WHERE `journalBookId`=? and `itemAccountId`=?";
$res = $this->query($query, [$bookId, $accountId]);
$posts = $res->fetchRow();
return ($posts['posts'] == 0);
} //accountChangeable
/**
* Creates an account with the given information
*
* @param int $bookId id of the current book
* @param int $accountId id of the account to create
* @param string $accountName name of the account to create
* @param string $accountNotes notes for this account
* @param float $accountBudget planned budget for the account
* @param boolean $accountLocked can this account be used, 0=unlocked, 1=locked
* @param int $accountTax taxId for tax automation
* @return array|bool list of errors or true on success
*/
function createAccount(
$bookId,
$accountId,
$accountName,
$accountNotes,
$accountBudget,
$accountLocked,
$accountTax = 0
) {
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
$errors = [tra("This book has been closed. You can't create new accounts.")];
return $errors;
}
$errors = $this->validateId('accountId', $accountId, 'tiki_acct_account', false, 'accountBookId', $bookId);
if ($accountName == '') {
$errors[] = tra('Account name must not be empty.');
}
$cleanbudget = $this->cleanupAmount($bookId, $accountBudget);
if ($cleanbudget === '') {
$errors[] = tra('Budget is not a valid amount: ') . $accountBudget;
}
if ($accountLocked != 0 and $accountLocked != 1) {
$errors[] = tra('Locked must be either 0 or 1.');
}
if ($accountTax != 0) {
$errors = array_merge($errors, $this->validateId('taxId', $accountTax, 'tiki_acct_tax', true, 'taxBookId', $bookId));
}
if (! empty($errors)) {
return $errors;
}
$query = 'INSERT INTO tiki_acct_account' .
' SET accountBookId=?, accountId=?, accountName=?,' .
' accountNotes=?, accountBudget=?, accountLocked=?, accountTax=?';
$res = $this->query(
$query,
[
$bookId,
$accountId,
$accountName,
$accountNotes,
$cleanbudget,
$accountLocked,
$accountTax
]
);
if ($res === false) {
$errors[] = tra('Error creating account') & " $accountId: " . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
return $errors;
}
return true;
} //createAccount
/**
* Unlocks or locks an account which means it can not be used accidentally for booking
*
* @param int $bookId current book
* @param int $accountId account to lock
* @return bool true on success
*/
function changeAccountLock($bookId, $accountId)
{
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
return false;
}
$query = "UPDATE `tiki_acct_account` SET `accountLocked` = NOT `accountLocked`
WHERE `accountBookId`=? AND `accountId`=?";
$res = $this->query($query, [$bookId, $accountId]);
if ($res === false) {
return false;
}
return true;
} //changeAccountLock
/**
* Updates an account with the given information
*
* @param int $bookId id of the current book
* @param int $accountId original id of the account
* @param int $newAccountId new id of the account (only if the account is changeable)
* @param string $accountName name of the account
* @param string $accountNotes notes for the account
* @param float $accountBudget planned yearly budget for the account
* @param boolean $accountLocked can this account be used 0=unlocked, 1=locked
* @param int $accountTax id of the auto tax type, defaults to 0
* @return array|bool list of errors, true on success
*/
function updateAccount(
$bookId,
$accountId,
$newAccountId,
$accountName,
$accountNotes,
$accountBudget,
$accountLocked,
$accountTax = 0
) {
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
$errors = [tra("This book has been closed. You can't modify the account.")];
return $errors;
}
$errors = $this->validateId('accountId', $newAccountId, 'tiki_acct_account', true, 'accountBookId', $bookId);
if ($accountId != $newAccountId) {
if (! $this->accountChangeable($bookId, $accountId)) {
$errors[] = tra('AccountId %0 is already in use and must not be changed. Please disable it if it is no longer needed.', $args = [$accountId]);
}
}
if ($accountName === '') {
$errors[] = tra('Account name must not be empty.');
}
$cleanbudget = $this->cleanupAmount($bookId, $accountBudget);
if ($cleanbudget === '') {
$errors[] = tra('Budget is not a valid amount: ') . $cleanbudget;
}
if ($accountLocked != 0 and $accountLocked != 1) {
$errors[] = tra('Locked must be either 0 or 1.');
}
if ($accountTax != 0) {
$errors = array_merge($errors, $this->validateId('taxId', $accountTax, 'tiki_acct_tax', true, 'taxBookId', $bookId));
}
if (count($errors) != 0) {
return $errors;
}
$query = "UPDATE tiki_acct_account SET accountId=?, accountName=?,
accountNotes=?, accountBudget=?, accountLocked=?, accountTax=?
WHERE accountBookId=? AND accountId=?";
$res = $this->query(
$query,
[
$newAccountId,
$accountName,
$accountNotes,
$cleanbudget,
$accountLocked,
$accountTax,
$bookId,
$accountId
]
);
if ($res === false) {
$errors[] = tra('Error updating account') & " $accountId: " . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
return $errors;
}
return true;
} //updateAccount
/**
* Delete an account (if deleteable)
*
* @param int $bookId id of the current book
* @param int $accountId account id to delete
* @param bool $checkChangeable check, if the account is unused and can be deleted
* @return array|bool array with errors or true, if deletion was successful
*/
function deleteAccount($bookId, $accountId, $checkChangeable = true)
{
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
return [tra("This book has been closed. You can't delete the account.")];
}
if (! $this->accountChangeable($bookId, $accountId)) {
return [tra('Account is already in use and must not be deleted. Please disable it, if it is no longer needed.')];
}
$query = "DELETE FROM `tiki_acct_account` WHERE `accountBookId`=? AND `accountId`=?";
$res = $this->query($query, [$bookId, $accountId]);
return true;
} //deleteAccount
/**
*
* Do a manual rollback, if the creation of a complete booking fails.
* This is a workaround for missing transaction support
* @param int $bookId id of the current book
* @param int $journalId id of the entry to roll back
* @return string Text messages stating the success/failure of the rollback
*/
function manualRollback($bookId, $journalId)
{
$errors = [];
$query = "DELETE FROM `tiki_acct_item` WHERE `itemBookId`=? AND `itemJournalId`=?";
$res = $this->query($query, [$bookId, $journalId]);
$rollback = ($res !== false);
$query = "DELETE FROM `tiki_acct_journal` WHERE `journalBookId`=? AND `journalId`=?";
$res = $this->query($query, [$bookId, $journalId]);
$rollback = $rollback and ($res !== false);
if (! $rollback) {
return tra('Rollback failed, inconsistent database: Cleanup needed for journalId %0 in book %1', [$journalId, $bookId]);
} else {
return tra('successfully rolled back #') . " $journalId";
}
} //manualRollback
/**
* Checks if the book date is within the books limits
*
* @param array $book book array
* @param DateTime $Date
* @retun array|bool
*/
function checkBookDates($book, $Date)
{
$StartDate = new DateTime($book['bookStartDate']);
if ($Date < $StartDate) {
return [tra("The date of the transaction is before the start date of this book.")];
}
$EndDate = new DateTime($book['bookEndDate']);
if ($Date > $EndDate) {
return [tra("The date of the transaction is after the end date of this book.")];
}
return true;
}
/**
* books a simple transaction
*
* @param int $bookId id of the current book
* @param string $journalDate date of the transaction
* @param string $journalDescription description of this transaction
* @param int $debitAccount account to debit
* @param int $creditAccount account to credit
* @param double $amount amount to transfer between the accounts
* @param string $debitText text for the debit post, defaults to an empty string
* @param string $creditText text for the credit post, defaults to an empty string
* @return int|array list of errors or journalId on success
*/
function simpleBook(
$bookId,
$journalDate,
$journalDescription,
$debitAccount,
$creditAccount,
$amount,
$debitText = '',
$creditText = ''
) {
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
return [tra("This book has been closed. Bookings can no longer be made in it.")];
} try {
$date = new DateTime($journalDate);
} catch (Exception $e) {
return [tra("Invalid booking date.")];
}
$errors = $this->checkBookDates($book, $date);
if (is_array($errors)) {
return $errors;
}
$errors = [];
$query = "INSERT INTO `tiki_acct_journal` (`journalBookId`, `journalDate`, `journalDescription`,
`journalCancelled`, `journalTs`)
VALUES (?,?,?,0,NOW())";
$res = $this->query($query, [$bookId, $date->toString('Y-M-d'), $journalDescription]);
if ($res === false) {
$errors[] = tra('Booking error creating journal entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$this->rollback();
return $errors;
}
$journalId = $this->lastInsertId();
$query = "INSERT INTO `tiki_acct_item` (`itemBookId`, `itemJournalId`, `itemAccountId`, `itemType`,
`itemAmount`, `itemText`, `itemTs`)
VALUES (?, ?, ?, ?, ?, ?, NOW())";
$res = $this->query($query, [$bookId, $journalId, $debitAccount, -1, $amount, $debitText]);
if ($res === false) {
$errors[] = tra('Booking error creating debit entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->manualRollback($bookId, $journalId);
return $errors;
}
$res = $this->query($query, [$bookId, $journalId, $creditAccount, 1, $amount, $creditText]);
if ($res === false) {
$errors[] = tra('Booking error creating credit entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->manualRollback($bookId, $journalId);
return $errors;
}
// everything ok
return $journalId;
}// simplebook
/**
* books a complex transaction with multiple accounts on one side
*
* @param int $bookId id of the current book
* @param DateTime $journalDate date of the transaction
* @param string $journalDescription description of this transaction
* @param mixed $debitAccount account(s) to debit
* @param mixed $creditAccount account(s) to credit
* @param mixed $debitAmount amount(s) on debit side
* @param mixed $creditAmount amount(s) on credit side
* @param mixed $debitText text(s) for the debit post, defaults to an empty string
* @param mixed $creditText text(s) for the credit post, defaults to an empty string
*
* @return int|array journalID or list of errors
*/
function book(
$bookId,
$journalDate,
$journalDescription,
$debitAccount,
$creditAccount,
$debitAmount,
$creditAmount,
$debitText = [],
$creditText = []
) {
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
$errors[] = tra("This book has been closed. Bookings can no longer be made in it.");
}
if (! ($journalDate instanceof DateTime)) {
return [tra("Invalid booking date.")];
}
$errors = $this->checkBookDates($book, $journalDate);
if (is_array($errors)) {
return $errors;
}
$errors = [];
if (! is_array($debitAccount)) {
$debitAccount = [$debitAccount];
}
if (! is_array($creditAccount)) {
$creditAccount = [$creditAccount];
}
if (! is_array($debitAmount)) {
$debitAmount = [$debitAmount];
}
if (! is_array($creditAmount)) {
$creditAmount = [$creditAmount];
}
if (! is_array($debitText)) {
$debitText = [$debitText];
}
if (! is_array($creditText)) {
$creditText = [$creditText];
}
if (count($debitAccount) != count($debitAmount) or count($debitAccount) != count($debitText)) {
$errors[] = tra('The number of debit entries differs: ') . count($debitAccount) . '/' . count($debitAmount) . '/' . count($debitText);
}
if (count($creditAccount) != count($creditAmount) or count($creditAccount) != count($creditText)) {
$errors[] = tra('The number of credit entries differs: ') . count($creditAccount) . '/' . count($creditAmount) . '/' . count($creditText);
}
if (count($debitAccount) > 1 and count($creditAccount) > 1) {
$errors[] = tra('Splitting is only allowed on one side.');
}
$checkamount = 0;
for ($i = 0, $icount_debitAmount = count($debitAmount); $i < $icount_debitAmount; $i++) {
$a = $this->cleanupAmount($bookId, $debitAmount[$i]);
if (! is_numeric($a) or $a <= 0) {
$errors[] = tra('Invalid debit amount ') . $debitAmount[$i];
} else {
$checkamount -= $a;
}
if (! is_numeric($debitAccount[$i])) {
$errors[] = tra('Invalid debit account number ') . $debitAccount[$i];
}
}
for ($i = 0, $icount_creditAmount = count($creditAmount); $i < $icount_creditAmount; $i++) {
$a = $this->cleanupAmount($bookId, $creditAmount[$i]);
if (! is_numeric($a) or $a <= 0) {
$errors[] = tra('Invalid credit amount ') . $creditAmount[$i];
} else {
$checkamount += $a;
}
if (! is_numeric($creditAccount[$i])) {
$errors[] = tra('Invalid credit account number ') . $creditAccount[$i];
}
}
if ($checkamount != 0) {
$errors[] = tra('Difference between debit and credit amounts ') . $checkamount;
}
if (count($errors) > 0) {
return $errors;
}
$query = "INSERT INTO `tiki_acct_journal` (`journalBookId`, `journalDate`, `journalDescription`,
`journalCancelled`, `journalTs`)
VALUES (?,?,?,0,NOW())";
$res = $this->query($query, [$bookId, date_format($journalDate, 'Y-m-d'), $journalDescription]);
if ($res === false) {
$errors[] = tra('Booking error creating journal entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
return $errors;
}
$journalId = $this->lastInsertId();
$query = "INSERT INTO `tiki_acct_item` (`itemBookId`, `itemJournalId`, `itemAccountId`, `itemType`,
`itemAmount`, `itemText`, `itemTs`)
VALUES (?, ?, ?, ?, ?, ?, NOW())";
for ($i = 0, $icount_debitAccount = count($debitAccount); $i < $icount_debitAccount; $i++) {
$a = $this->cleanupAmount($bookId, $debitAmount[$i]);
$res = $this->query($query, [$bookId, $journalId, $debitAccount[$i], -1, $a, $debitText[$i]]);
if ($res === false) {
$errors[] = tra('Booking error creating debit entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->manualRollback($bookId, $journalId);
return $errors;
}
}
for ($i = 0, $icount_creditAccount = count($creditAccount); $i < $icount_creditAccount; $i++) {
$a = $this->cleanupAmount($bookId, $creditAmount[$i]);
$res = $this->query($query, [$bookId, $journalId, $creditAccount[$i], 1, $a, $creditText[$i]]);
if ($res === false) {
$errors[] = tra('Booking error creating credit entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->manualRollback($bookId, $journalId);
return $errors;
}
}
return $journalId;
}// book
/**
*
* Retrieves one entry from the journal
*
* @param int $bookId id of the current book
* @param int $journalId id of the post in the journal
* @return array|bool array with post, false on error
*/
function getTransaction($bookId, $journalId)
{
$query = 'SELECT `journalId`, `journalDate`, `journalDescription`, `journalCancelled`' .
' FROM `tiki_acct_journal`' .
' WHERE `journalBookId`=? AND `journalId`=?'
;
$res = $this->query($query, [$bookId, $journalId]);
if ($res === false) {
return false;
}
$entry = $res->fetchRow();
$query = "SELECT * FROM `tiki_acct_item` WHERE `itemBookId`=? AND `itemJournalId`=? AND `itemType`=? ORDER BY `itemAccountId` ASC";
$entry['debit'] = $this->fetchAll($query, [$bookId, $entry['journalId'], -1]);
$entry['debitcount'] = count($entry['debit']);
$entry['credit'] = $this->fetchAll($query, [$bookId, $entry['journalId'], 1]);
$entry['creditcount'] = count($entry['credit']);
$entry['maxcount'] = max($entry['creditcount'], $entry['debitcount']);
return $entry;
} //getTransaction
/**
* Declares a statement in the journal as cancelled.
* @param int $bookId id of the current book
* @param int $journalId journalId of the statement to cancel
*/
function cancelTransaction($bookId, $journalId)
{
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
$errors[] = tra("This book has been closed. Transactions can no longer be cancelled in it.");
}
$query = "UPDATE `tiki_acct_journal` SET `journalCancelled`=1 WHERE `journalBookId`=? and `journalId`=?";
$res = $this->query($query, [$bookId, $journalId]);
return true;
} // cancelTransaction
/**
* Returns the complete stack
*
* @param int $bookId id of the current book
* @return array|bool stack with all posts, false on errors
*/
function getStack($bookId)
{
$stack = [];
$query = "SELECT * FROM `tiki_acct_stack` WHERE `stackBookId`=?";
$res = $this->query($query, [$bookId]);
if ($res === false) {
return false;
}
while ($row = $res->fetchRow()) {
$query = "SELECT * FROM `tiki_acct_stackitem` WHERE `stackBookId`=? AND `stackItemStackId`=? AND `stackItemType`=? ORDER BY `stackItemAccountId` ASC";
$row['debit'] = $this->fetchAll($query, [$bookId, $row['stackId'], -1]);
$row['debitcount'] = count($row['debit']);
$row['credit'] = $this->fetchAll($query, [$bookId, $row['stackId'], 1]);
$row['creditcount'] = count($row['credit']);
$row['maxcount'] = max($row['creditcount'], $row['debitcount']);
$stack[] = $row;
}
return $stack;
}
/**
*
* Do a manual rollback, if the creation of a complete booking fails.
* This is a workaround for missing transaction support
* @param int $bookId id of the current book
* @param int $stackId id of the entry to roll back
* @return string Text messages stating the success/failure of the rollback
*/
function stackManualRollback($bookId, $stackId)
{
$errors = [];
$query = "DELETE FROM `tiki_acct_stackitem` WHERE `stackitemBookId`=? AND `stackitemJournalId`=?";
$res = $this->query($query, [$bookId, $stackId]);
$rollback = ($res !== false);
$query = "DELETE FROM `tiki_acct_stack` WHERE `stackBookId`=? AND `stackId`=?";
$res = $this->query($query, [$bookId, $stackId]);
$rollback = $rollback and ($res !== false);
if (! $rollback) {
return tra('Rollback failed, inconsistent database: Cleanup needed for stackId %0 in book %1', [$stackId, $bookId]);
} else {
return tra('successfully rolled back #') . " $stackId";
}
} //stackManualRollback
/**
* books a complex transaction with multiple accounts on one side into the stack
*
* @param int $bookId id of the current book
* @param DateTime $stackDate date of the transaction
* @param string $stackDescription description of this transaction
* @param mixed $debitAccount account(s) to debit
* @param mixed $creditAccount account(s) to credit
* @param mixed $debitAmount amount(s) on debit side
* @param mixed $creditAmount amount(s) on credit side
* @param mixed $debitText text(s) for the debit post, defaults to an empty string
* @param mixed $creditText text(s) for the credit post, defaults to an empty string
*
* @return int|array stackID or list of errors
*/
function stackBook(
$bookId,
$stackDate,
$stackDescription,
$debitAccount,
$creditAccount,
$debitAmount,
$creditAmount,
$debitText = [],
$creditText = []
) {
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
$errors[] = tra("This book has been closed. Bookings can no longer be made in it.");
}
$date = $stackDate;
$errors = $this->checkBookDates($book, $date);
if (is_array($errors)) {
return $errors;
}
$errors = [];
if (! is_array($debitAccount)) {
$debitAccount = [$debitAccount];
}
if (! is_array($creditAccount)) {
$creditAccount = [$creditAccount];
}
if (! is_array($debitAmount)) {
$debitAmount = [$debitAmount];
}
if (! is_array($creditAmount)) {
$creditAmount = [$creditAmount];
}
if (! is_array($debitText)) {
$debitText = [$debitText];
}
if (! is_array($creditText)) {
$creditText = [$creditText];
}
if (count($debitAccount) != count($debitAmount) or count($debitAccount) != count($debitText)) {
$errors[] = tra('The number of debit entries differs: ') . count($debitAccount) . '/' . count($debitAmount) . '/' . count($debitText);
}
if (count($creditAccount) != count($creditAmount) or count($creditAccount) != count($creditText)) {
$errors[] = tra('The number of credit entries differs: ') . count($creditAccount) . '/' . count($creditAmount) . '/' . count($creditText);
}
if (count($debitAccount) > 1 and count($creditAccount) > 1) {
$errors[] = tra('Splitting is only allowed on one side.');
}
$checkamount = 0;
for ($i = 0, $icount_debitAmount = count($debitAmount); $i < $icount_debitAmount; $i++) {
$a = $this->cleanupAmount($bookId, $debitAmount[$i]);
if (! is_numeric($a) or $a <= 0) {
$errors[] = tra('Invalid debit amount ') . $debitAmount[$i];
} else {
$checkamount -= $a;
}
if (! is_numeric($debitAccount[$i])) {
$errors[] = tra('Invalid debit account number ') . $debitAccount[$i];
}
}
for ($i = 0, $icount_creditAmount = count($creditAmount); $i < $icount_creditAmount; $i++) {
$a = $this->cleanupAmount($bookId, $creditAmount[$i]);
if (! is_numeric($a) or $a <= 0) {
$errors[] = tra('Invalid credit amount ') . $creditAmount[$i];
} else {
$checkamount += $a;
}
if (! is_numeric($creditAccount[$i])) {
$errors[] = tra('Invalid credit account number ') . $creditAccount[$i];
}
}
if ($checkamount != 0) {
$errors[] = tra('Difference between debit and credit amounts ') . $checkamount;
}
if (count($errors) > 0) {
return $errors;
}
$query = "INSERT INTO `tiki_acct_stack` (`stackBookId`, `stackDate`, `stackDescription`) VALUES (?,?,?)";
$res = $this->query($query, [$bookId, date('Y-m-d', $date->getTimestamp()), $stackDescription]);
if ($res === false) {
$errors[] = tra('Booking error creating stack entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
return $errors;
}
$stackId = $this->lastInsertId();
$query = "INSERT INTO `tiki_acct_stackitem` (`stackBookId`, `stackItemStackId`, `stackItemAccountId`, `stackItemType`,
`stackItemAmount`, `stackItemText`)
VALUES (?, ?, ?, ?, ?, ?)";
for ($i = 0, $icount_debitAccount = count($debitAccount); $i < $icount_debitAccount; $i++) {
$a = $this->cleanupAmount($bookId, $debitAmount[$i]);
$res = $this->query($query, [$bookId, $stackId, $debitAccount[$i], -1, $a, $debitText[$i]]);
if ($res === false) {
$errors[] = tra('Booking error creating stack debit entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->stackManualRollback($bookId, $stackId);
return $errors;
}
}
for ($i = 0, $icount_creditAccount = count($creditAccount); $i < $icount_creditAccount; $i++) {
$a = $this->cleanupAmount($bookId, $creditAmount[$i]);
$res = $this->query($query, [$bookId, $stackId, $creditAccount[$i], 1, $a, $creditText[$i]]);
if ($res === false) {
$errors[] = tra('Booking error creating stack credit entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->manualRollback($bookId, $stackId);
return $errors;
}
}
// everything ok
return $stackId;
}// stackBook
function stackUpdate(
$bookId,
$stackId,
$stackDate,
$stackDescription,
$debitAccount,
$creditAccount,
$debitAmount,
$creditAmount,
$debitText = [],
$creditText = []
) {
$book = $this->getBook($bookId);
if ($book['bookClosed'] == 'y') {
$errors[] = tra("This book has been closed. Bookings can no longer be made in it.");
}
$date = $stackDate;
$errors = $this->checkBookDates($book, $date);
if (is_array($errors)) {
return $errors;
}
$errors = [];
if (! is_array($debitAccount)) {
$debitAccount = [$debitAccount];
}
if (! is_array($creditAccount)) {
$creditAccount = [$creditAccount];
}
if (! is_array($debitAmount)) {
$debitAmount = [$debitAmount];
}
if (! is_array($creditAmount)) {
$creditAmount = [$creditAmount];
}
if (! is_array($debitText)) {
$debitText = [$debitText];
}
if (! is_array($creditText)) {
$creditText = [$creditText];
}
if (count($debitAccount) != count($debitAmount) or count($debitAccount) != count($debitText)) {
$errors[] = tra('The number of debit entries differs: ') . count($debitAccount) . '/' . count($debitAmount) . '/' . count($debitText);
}
if (count($creditAccount) != count($creditAmount) or count($creditAccount) != count($creditText)) {
$errors[] = tra('The number of credit entries differs: ') . count($creditAccount) . '/' . count($creditAmount) . '/' . count($creditText);
}
if (count($debitAccount) > 1 and count($creditAccount) > 1) {
$errors[] = tra('Splitting is only allowed on one side.');
}
$checkamount = 0;
for ($i = 0, $icount_debitAmount = count($debitAmount); $i < $icount_debitAmount; $i++) {
$a = $this->cleanupAmount($bookId, $debitAmount[$i]);
if (! is_numeric($a) or $a <= 0) {
$errors[] = tra('Invalid debit amount ') . $debitAmount[$i];
} else {
$checkamount -= $a;
}
if (! is_numeric($debitAccount[$i])) {
$errors[] = tra('Invalid debit account number ') . $debitAccount[$i];
}
}
for ($i = 0, $icount_creditAmount = count($creditAmount); $i < $icount_creditAmount; $i++) {
$a = $this->cleanupAmount($bookId, $creditAmount[$i]);
if (! is_numeric($a) or $a <= 0) {
$errors[] = tra('Invalid credit amount ') . $creditAmount[$i];
} else {
$checkamount += $a;
}
if (! is_numeric($creditAccount[$i])) {
$errors[] = tra('Invalid credit account number ') . $creditAccount[$i];
}
}
if ($checkamount != 0) {
$errors[] = tra('Difference between debit and credit amounts ') . $checkamount;
}
if (count($errors) > 0) {
return $errors;
}
$query = "UPDATE `tiki_acct_stack` SET `stackDate`=?, `stackDescription`=? WHERE `stackBookId`=? AND `stackId`=?";
$res = $this->query($query, [date('Y-m-d', $date->getTimestamp()), $stackDescription, $bookId, $stackId]);
if ($res === false) {
$errors[] = tra('Booking error creating stack entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
return $errors;
}
$query = "DELETE FROM `tiki_acct_stackitem` WHERE `stackBookId`=? AND `stackItemStackId`=?";
$res = $this->query($query, [$bookId, $stackId]);
if ($res === false) {
$errors[] = tra('Booking error creating stack entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->stackManualRollback($bookId, $stackId);
return $errors;
}
$query = "INSERT INTO `tiki_acct_stackitem` (`stackBookId`, `stackItemStackId`, `stackItemAccountId`, `stackItemType`,
`stackItemAmount`, `stackItemText`)
VALUES (?, ?, ?, ?, ?, ?)";
for ($i = 0, $icount_debitAccount = count($debitAccount); $i < $icount_debitAccount; $i++) {
$a = $this->cleanupAmount($bookId, $debitAmount[$i]);
$res = $this->query($query, [$bookId, $stackId, $debitAccount[$i], -1, $a, $debitText[$i]]);
if ($res === false) {
$errors[] = tra('Booking error creating stack debit entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->stackManualRollback($bookId, $stackId);
return $errors;
}
}
for ($i = 0, $icount_creditAccount = count($creditAccount); $i < $icount_creditAccount; $i++) {
$a = $this->cleanupAmount($bookId, $creditAmount[$i]);
$res = $this->query($query, [$bookId, $stackId, $creditAccount[$i], 1, $a, $creditText[$i]]);
if ($res === false) {
$errors[] = tra('Booking error creating stack credit entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->manualRollback($bookId, $stackId);
return $errors;
}
}
// everything ok
return $stackId;
}
/**
* deletes an entry from the stack
* @param int $bookId id of the current book
* @param int $stackId id of the entry to delete
* @return bool|array true on success, array of error messages otherwise
*/
function stackDelete($bookId, $stackId)
{
$errors = [];
$query = "DELETE FROM `tiki_acct_stackitem` WHERE `stackBookId`=? AND `stackItemStackId`=?";
$res = $this->query($query, [$bookId, $stackId]);
if ($res === false) {
$errors[] = tra('Error deleting entry from stack') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
}
$query = "DELETE FROM `tiki_acct_stack` WHERE `stackBookId`=? AND `stackId`=?";
$res = $this->query($query, [$bookId, $stackId]);
if ($res === false) {
$errors[] = tra('Error deleting entry from stack') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
}
if (count($errors) != 0) {
return $errors;
}
return true;
}
/**
*
* Confirm a transaction and transfer it to the journal
* @param int $bookId id of the current book
* @param int $stackId id of the entry in the stack
*/
function stackConfirm($bookId, $stackId)
{
$query = "INSERT into `tiki_acct_journal` (`journalBookId`, `journalDate`, `journalDescription`,
`journalCancelled`, `journalTs`)
SELECT ?, `stackDate`, `stackDescription` , 0, NOW() FROM `tiki_acct_stack` WHERE `stackBookId`=? AND `stackId`=?";
$res = $this->query($query, [$bookId, $bookId, $stackId]);
if ($res === false) {
$errors[] = tra('Booking error confirming stack entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
return $errors;
}
$journalId = $this->lastInsertId();
$query = "INSERT INTO `tiki_acct_item` (`itemBookId`, `itemJournalId`, `itemAccountId`, `itemType`,
`itemAmount`, `itemText`, `itemTs`)
SELECT ?, ?, `stackItemAccountId`, `stackItemType`, `stackItemAmount`, `stackItemText`, NOW()
FROM `tiki_acct_stackitem` WHERE `stackBookId`=? AND `stackItemStackId`=?";
$res = $this->query($query, [$bookId, $journalId, $bookId, $stackId]);
if ($res === false) {
$errors[] = tra('Booking error confirming stack entry') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
$errors[] = $this->manualRollback($bookId, $journalId);
return $errors;
}
$this->stackDelete($bookId, $stackId);
$query = "UPDATE `tiki_acct_statement` SET `statementJournalId`=? WHERE `statementBookId`=? AND `statementStackId`=?";
$res = $this->query($query, [$journalId, $bookId, $stackId]);
return true;
}
/**
*
* Retrieves one entry from the stack
*
* @param int $bookId id of the current book
* @param int $journalId id of the post in the journal
* @return array|bool array with post, false on error
*/
function getStackTransaction($bookId, $stackId)
{
$query = "SELECT * FROM `tiki_acct_stack` WHERE `stackBookId`=? AND `stackId`=?";
$res = $this->query($query, [$bookId, $stackId]);
if ($res === false) {
return false;
}
$entry = $res->fetchRow();
$query = "SELECT * FROM `tiki_acct_stackitem` WHERE `stackBookId`=? AND `stackItemStackId`=? AND `stackItemType`=? ORDER BY `stackItemAccountId` ASC";
$entry['debit'] = $this->fetchAll($query, [$bookId, $entry['stackId'], -1]);
$entry['debitcount'] = count($entry['debit']);
$entry['credit'] = $this->fetchAll($query, [$bookId, $entry['stackId'], 1]);
$entry['creditcount'] = count($entry['credit']);
$entry['maxcount'] = max($entry['creditcount'], $entry['debitcount']);
return $entry;
} //getTransaction
/**
* Returns a list of bankaccounts which are related to internal accounts
* @param int $bookId id if the current book
*
* @return array list of accounts
*/
function getBankAccounts($bookId)
{
$query = "SELECT * FROM `tiki_acct_bankaccount` INNER JOIN `tiki_acct_account`
ON `tiki_acct_bankaccount`.`bankBookId` = `tiki_acct_account`.`accountBookId` AND
`tiki_acct_bankaccount`.`bankAccountId`=`tiki_acct_account`.`accountId`
WHERE `tiki_acct_bankaccount`.`bankBookId`=?";
return $this->fetchAll($query, [$bookId]);
}//getBankAccounts
/**
* Returns a list of bank statements which have been uploaded but not yet been processed
*
* @param int $bookId id of the current book
* @param int $accountId id of the account to fetch the statements for
* @return array|bool list of statements or false if an error occurred
*/
function getOpenStatements($bookId, $accountId)
{
$query = "SELECT * FROM `tiki_acct_statement`
WHERE `statementJournalId`=0 AND `statementStackId`=0
AND `statementBookId`=? AND `statementAccountId`=?";
return $this->fetchAll($query, [$bookId, $accountId]);
}//getOpenStatements
/**
* Returns the statement with the given Id from the list of statements
*
* @param int $statetmentId id of the statement to retrieve
* @return array|bool statement data or false on error
*/
function getStatement($statementId)
{
$query = "SELECT * FROM `tiki_acct_statement` WHERE `statementId`=?";
$res = $this->query($query, [$statementId]);
if ($res === false) {
return $res;
}
return $res->fetchRow();
}//getStatement
/**
* Returns the import specification for a given accountId
* @param int $bookId id of the current book
* @param int $accountId id of the account we want the specs for
* @return array|bool list of statements or false
*/
function getBankAccount($bookId, $accountId)
{
$query = "SELECT * FROM `tiki_acct_bankaccount` WHERE bankBookId=? and bankAccountId=?";
$res = $this->query($query, [$bookId, $accountId]);
if ($res === false) {
return $res;
}
return $res->fetchRow();
}//getBankAccount
/**
* Splits a header line into a matching array according to the specifications
*
* @param string $header line containing headers
* @param array $defs file definitions
* @return array list of statements
*/
function analyzeHeader($header, $defs)
{
$cols = explode($defs['bankDelimeter'], $header);
$columns = [];
for ($i = 0, $isizeof_cols = count($cols); $i < $isizeof_cols; $i++) {
switch ($cols[$i]) {
case $defs['fieldNameAccount']:
$columns['accountId'] = $i;
break;
case $defs['fieldNameBookingDate']:
$columns['bookingDate'] = $i;
break;
case $defs['fieldNameValueDate']:
$columns['valueDate'] = $i;
break;
case $defs['fieldNameBookingText']:
$columns['bookingText'] = $i;
break;
case $defs['fieldNameReason']:
$columns['reason'] = $i;
break;
case $defs['fieldNameCounterpartName']:
$columns['counterpartName'] = $i;
break;
case $defs['fieldNameCounterpartAccount']:
$columns['counterpartAccount'] = $i;
break;
case $defs['fieldNameCounterpartBankcode']:
$columns['counterpartBankcode'] = $i;
break;
case $defs['fieldNameAmount']:
$columns['amount'] = $i;
break;
case $defs['fieldNameAmountSign']:
$columns['amountSign'] = $i;
break;
}
}
return $columns;
}//analyzeHeader
/**
* updates journalId in the given statement
*
* @param int $statementId id of the statement to update
* @param int $journalId id of the entry in the journal which was caused by this statement
* @return array|boolean list of errors, empty if no errors were found
*/
function updateStatement($statementId, $journalId)
{
$errors = [];
$query = "UPDATE `tiki_acct_statement` SET `statementJournalId`=? WHERE `statementId`=?";
$res = $this->query($query, [$journalId, $statementId]);
if ($res === false) {
$errors[] = tra('Error while updating statement:') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
return $errors;
}
return true;
}//updateStatement
/**
* updates journalId in the given statement
*
* @param int $statementId id of the statement to update
* @param int $journalId id of the entry in the journal which was caused by this statement
* @return array|bool list of errors, empty if no errors were found
*/
function updateStatementStack($statementId, $stackId)
{
$errors = [];
$query = "UPDATE `tiki_acct_statement` SET `statementStackId`=? WHERE `statementId`=?";
$res = $this->query($query, [$stackId, $statementId]);
if ($res === false) {
$errors[] = tra('Error while updating statement:') . $this->ErrorNo() . ": " . $this->ErrorMsg() . "<br /><pre>$query</pre>";
return $errors;
}
return true;
}//updateStatementStack
/**
*
* Creates a tax setting for automated tax deduction/splitting
* @param int $bookId
* @param string $taxText
* @param double $taxAmount
* @param string $taxIsFix
* @return int id of the newly created tax
*/
function createTax($bookId, $taxText, $taxAmount, $taxIsFix = 'n')
{
$query = "INSERT INTO `tiki_acct_tax` (`taxBookId`, `taxText`, `taxAmount`, `taxIsFix`) VALUES (?, ?, ?, ?)";
$res = $this->query($query, [$bookId, $taxText, $taxAmount, $taxIsFix]);
return $this->lastInsertId();
}
/**
* removes all unnecessary thousand markers and replaces local decimal characters with "." to enable handling as numbers.
*
* @param int $bookId id of the current book
* @param string $amount date of the transaction
* @return string/float Returns a float or an empty string if the source is not numeric
*/
function cleanupAmount($bookId, $amount)
{
$book = $this->getBook($bookId);
$a = str_replace($book['bookDecPoint'], '.', str_replace($book['bookThousand'], '', $amount));
if (! is_numeric($a)) {
return '';
}
return floatval($a);
}//cleanupAmount
/**
* Checks the existence/non-existence of a numerical id in the given table
*
* @param string $idname name of the id field in the table
* @param int $id the id to check
* @param string $table the table to search
* @param boolean $exists true if a record must exist, false if it must not
*
* @return array Returns aa array of errors (empty if none occurred)
*/
function validateId($idname, $id, $table, $exists = true, $bookIdName = '', $bookId = 0)
{
$errors = [];
if (! is_numeric($id)) {
$errors[] = htmlspecialchars($idname) . ' (' . htmlspecialchars($id) . ')'
. tra('is not a number.');
} elseif ($id <= 0) {
$errors[] = htmlspecialchars($idname) . ' ' . tra('must be greater than 0.');
} else {
//static whitelist based on usage of the validateId function in accountinglib.php
$tablesWhitelist = [
'tiki_acct_tax' => [
'idname' => 'taxId',
'bookIdName' => 'taxBookId'
],
'tiki_acct_account' => [
'idname' => 'accountId',
'bookIdName' => 'accountBookId'
]
];
if (! array_key_exists($table, $tablesWhitelist)) {
$errors[] = tra('Invalid transaction - please contact administrator.');
} elseif ($idname !== $tablesWhitelist[$table]['idname']) {
$errors[] = tra('Invalid transaction - please contact administrator.');
} else {
$query = "SELECT $idname FROM $table WHERE $idname = ?";
$bindvars = [$id];
if ($bookIdName === $tablesWhitelist[$table]['bookIdName']) {
$query .= " AND $bookIdName = ?";
array_push($bindvars, $bookId);
}
$res = $this->query($query, $bindvars);
if ($res === false) {
$errors[] = tra('Error checking') . htmlspecialchars($idname) . ': ' . $this->ErrorNo() . ': '
. $this->ErrorMsg() . '<br /><pre>' . htmlspecialchars($query) . '</pre>';
} else {
if ($exists) {
if ($res->numRows() == 0) {
$errors[] = htmlspecialchars($idname) . ' ' . tra('does not exist.');
}
} else {
if ($res->numRows() > 0) {
$errors[] = htmlspecialchars($idname) . ' ' . tra('already exists');
}
} //existence
} // query
}
} // numeric
return $errors;
} // validateId
}
| lgpl-2.1 |
pjuren/pyokit | setup.py | 1563 | """
Date of Creation: 2013.
Description: Settings for setup tools to install this package
Copyright (C) 2010-2015
Philip J. Uren,
Authors: Philip J. Uren
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/>.
"""
from setuptools import setup, find_packages
setup(name='pyokit',
version='0.2.0',
packages=find_packages('src'), # include all packages under src
entry_points={'console_scripts':
['pyokit=pyokit.scripts.pyokitMain:main']},
package_dir={'': 'src'}, # ell distutils packages are under src
install_requires=['mock>=1.0.0', 'enum34'],
description='A library of python functions and classes to assist in '
'processing high-throughput biological data',
author='Philip J. Uren',
author_email='philip.uren@gmail.com',
url='https://github.com/pjuren/pyokit',
download_url='https://github.com/pjuren/pyokit/tarball/pyokit_0.2.0',
license='LGPL2',
keywords=[],
classifiers=[])
| lgpl-2.1 |
knevcher/limb | config/package.php | 2783 | <?php
/*
* Limb PHP Framework
*
* @link http://limb-project.com
* @copyright Copyright © 2004-2009 BIT(http://bit-creative.com)
* @license LGPL http://www.gnu.org/copyleft/lesser.html
*/
/**
* @package config
* @version $Id$
*/
require_once 'PEAR/PackageFileManager2.php';
require_once 'PEAR/PackageFileManager/Svn.php';
list($name, $baseVersion, $state) = explode('-', trim(file_get_contents(dirname(__FILE__) . '/VERSION')));
$changelog = htmlspecialchars(file_get_contents(dirname(__FILE__) . '/CHANGELOG'));
$summary = htmlspecialchars(file_get_contents(dirname(__FILE__) . '/SUMMARY'));
$description = htmlspecialchars(file_get_contents(dirname(__FILE__) . '/DESCRIPTION'));
$maintainers = explode("\n", trim(file_get_contents(dirname(__FILE__) . '/MAINTAINERS')));
$version = $baseVersion . (isset($argv[3]) ? $argv[3] : '');
$dir = dirname(__FILE__);
$apiVersion = $baseVersion;
$apiStability = $state;
$package = new PEAR_PackageFileManager2();
$result = $package->setOptions(array(
'license' => 'LGPL',
'filelistgenerator' => 'file',
'ignore' => array('package.php',
'package.xml',
'*.tgz',
'var',
'setup.override.php',
'common.ini.override'),
//'simpleoutput' => true,
'baseinstalldir' => 'limb/' . $name,
'packagedirectory' => './',
'packagefile' => 'package.xml',
'dir_roles' => array('docs' => 'doc',
'examples' => 'doc',
'tests' => 'test'),
'roles' => array('*' => 'php'),
));
if(PEAR::isError($result))
{
echo $result->getMessage();
exit(1);
}
$package->setPackage($name);
$package->setSummary($summary);
$package->setDescription($description);
$package->setChannel('pear.limb-project.com');
$package->setAPIVersion($apiVersion);
$package->setReleaseVersion($version);
$package->setReleaseStability($state);
$package->setAPIStability($apiStability);
$package->setNotes($changelog);
$package->setPackageType('php');
$package->setLicense('LGPL', 'http://www.gnu.org/copyleft/lesser.txt');
foreach($maintainers as $line)
{
list($role, $nick, $name, $email, $active) = explode(',', $line);
$package->addMaintainer($role, $nick, $name, $email, $active);
}
$package->setPhpDep('5.1.4');
$package->setPearinstallerDep('1.4.99');
$package->addPackageDepWithChannel('required', 'core', 'pear.limb-project.com', '0.2.0');
$package->addPackageDepWithChannel('required', 'fs', 'pear.limb-project.com', '0.1.0');
$package->generateContents();
$result = $package->writePackageFile();
if(PEAR::isError($result))
{
echo $result->getMessage();
exit(1);
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | designer/report-designer/src/test/java/org/pentaho/reporting/designer/core/util/undo/UndoManagerTest.java | 4547 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.designer.core.util.undo;
import junit.framework.TestCase;
import org.pentaho.reporting.designer.core.ReportDesignerBoot;
import org.pentaho.reporting.designer.core.auth.GlobalAuthenticationStore;
import org.pentaho.reporting.designer.core.editor.ReportRenderContext;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.util.InstanceID;
/**
* Todo: Document Me
*
* @author Thomas Morgner
* @noinspection HardCodedStringLiteral
*/
public class UndoManagerTest extends TestCase {
public UndoManagerTest() {
}
public UndoManagerTest( final String s ) {
super( s );
}
@Override
protected void setUp() throws Exception {
ReportDesignerBoot.getInstance().start();
}
public void testUndo() {
final UndoManager manager = new UndoManager();
assertFalse( manager.isRedoPossible() );
assertFalse( manager.isUndoPossible() );
final MasterReport report = new MasterReport();
final ReportRenderContext rrc = new ReportRenderContext( report, report, null, new GlobalAuthenticationStore() );
// must return silently
manager.undo( rrc );
// must return silently
manager.redo( rrc );
}
public void testRecords() {
final UndoManager manager = new UndoManager();
final MasterReport report = new MasterReport();
final ReportRenderContext rrc = new ReportRenderContext( report, report, null, new GlobalAuthenticationStore() );
final InstanceID id = report.getObjectID();
manager.addChange( "name1", new AttributeEditUndoEntry( id, "test-ns", "test", null, "new" ) );
manager.addChange( "name2", new AttributeEditUndoEntry( id, "test-ns", "test2", null, "groovy" ) );
manager.addChange( "name3", new AttributeEditUndoEntry( id, "test-ns", "test", "new", "other" ) );
report.setAttribute( "test-ns", "test", "other" );
report.setAttribute( "test-ns", "test2", "groovy" );
assertFalse( manager.isRedoPossible() );
assertTrue( manager.isUndoPossible() );
assertEquals( "Attr test = other", "other", report.getAttribute( "test-ns", "test" ) );
assertEquals( "Attr test2 = groovy", "groovy", report.getAttribute( "test-ns", "test2" ) );
manager.undo( rrc );
assertTrue( manager.isRedoPossible() );
assertTrue( manager.isUndoPossible() );
assertEquals( "Attr test = new", "new", report.getAttribute( "test-ns", "test" ) );
assertEquals( "Attr test2 = groovy", "groovy", report.getAttribute( "test-ns", "test2" ) );
manager.redo( rrc );
assertFalse( manager.isRedoPossible() );
assertTrue( manager.isUndoPossible() );
assertEquals( "Attr test = other", "other", report.getAttribute( "test-ns", "test" ) );
assertEquals( "Attr test2 = groovy", "groovy", report.getAttribute( "test-ns", "test2" ) );
manager.undo( rrc );
assertTrue( manager.isRedoPossible() );
assertTrue( manager.isUndoPossible() );
assertEquals( "Attr test = new", "new", report.getAttribute( "test-ns", "test" ) );
assertEquals( "Attr test2 = groovy", "groovy", report.getAttribute( "test-ns", "test2" ) );
manager.undo( rrc );
assertTrue( manager.isRedoPossible() );
assertTrue( manager.isUndoPossible() );
assertEquals( "Attr test = new", "new", report.getAttribute( "test-ns", "test" ) );
assertEquals( "Attr test2 = <null>", null, report.getAttribute( "test-ns", "test2" ) );
manager.undo( rrc );
assertTrue( manager.isRedoPossible() );
assertFalse( manager.isUndoPossible() );
assertEquals( "Attr test = <null>", null, report.getAttribute( "test-ns", "test" ) );
assertEquals( "Attr test2 = <null>", null, report.getAttribute( "test-ns", "test2" ) );
}
}
| lgpl-2.1 |
qtoolkit/qtk | tests/list-layouter.test.js | 611 |
describe('ListLayouter', function() {
this.timeout(3000);
var listView = qtk.ListView.create();
listView.resizeTo(2000, 600);
listView.itemH = 75;
listView.itemSpacing = 5;
it('test basic', (done) => {
var item = qtk.ListItem.create();
listView.addChild(item);
var item1 = qtk.ListItem.create();
listView.padding = 0;
listView.addChild(item1);
var result = item.x === 0 && item.y === 0 && item.h === listView.itemH
&& item1.y === listView.itemSpacing + item.h && item1.h === listView.itemH
done(result ? null : new Error("item x/y/w/h wrong"));
});
});
| lgpl-2.1 |
ltcmelo/uaiso | Semantic/CompletionTest.cpp | 4229 | /******************************************************************************
* Copyright (c) 2014-2016 Leandro T. C. Melo (ltcmelo@gmail.com)
*
* 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
*****************************************************************************/
/*--------------------------*/
/*--- The UaiSo! Project ---*/
/*--------------------------*/
#include "Semantic/CompletionTest.h"
#include "Semantic/Binder.h"
#include "Semantic/CompletionProposer.h"
#include "Semantic/Manager.h"
#include "Semantic/Program.h"
#include "Semantic/TypeChecker.h"
#include "Semantic/Snapshot.h"
#include "Semantic/Symbol.h"
#include "Ast/Ast.h"
#include "Ast/AstDumper.h"
#include "Parsing/Factory.h"
#include "Parsing/Lexeme.h"
#include "Parsing/LexemeMap.h"
#include "Parsing/TokenMap.h"
#include "Parsing/Unit.h"
#include <sstream>
#include <algorithm>
using namespace uaiso;
std::vector<std::string> readSearchPaths();
std::unique_ptr<Unit>
CompletionProposer::CompletionProposerTest::runCore(
std::unique_ptr<Factory> factory,
const std::string& code,
const std::string& fullFileName,
const std::vector<const char*>& expected)
{
std::vector<std::string> searchPaths = readSearchPaths();
TokenMap tokens;
LexemeMap lexs;
Snapshot snapshot;
Manager manager;
manager.config(factory.get(), &tokens, &lexs, snapshot);
Manager::BehaviourFlags flags = 0;
if (disableBuiltins_)
flags |= Manager::BehaviourFlag::IgnoreBuiltins;
if (disableAutoModules_)
flags |= Manager::BehaviourFlag::IgnoreAutomaticModules;
manager.setBehaviour(flags);
for (const auto& path : searchPaths)
manager.addSearchPath(path);
std::unique_ptr<Unit> unit = manager.process(code, fullFileName, lineCol_);
UAISO_EXPECT_TRUE(unit->ast());
ProgramAst* progAst = Program_Cast(unit->ast());
if (dumpAst_) {
std::ostringstream oss;
oss << "AST dump\n";
AstDumper().dumpProgram(progAst, oss);
std::cout << oss.str();
}
Program* prog = snapshot.find(fullFileName);
UAISO_EXPECT_TRUE(prog);
UAISO_EXPECT_FALSE(prog->env().isEmpty());
TypeChecker checker(factory.get());
checker.setLexemes(&lexs);
checker.setTokens(&tokens);
checker.check(progAst);
CompletionProposer completer(factory.get());
auto syms = std::get<0>(completer.propose(progAst, &lexs));
if (dumpCompletions_) {
std::ostringstream oss;
oss << "Produced completions\n";
std::for_each(syms.begin(), syms.end(), [&oss] (auto sym) {
if (isDecl(sym))
oss << ConstDeclSymbol_Cast(sym)->name()->str() << " ";
else if (sym->kind() == Symbol::Kind::Namespace)
oss << ConstNamespace_Cast(sym)->name()->str() << " ";
else
oss << "<anonymous symbol>";
});
oss << std::endl;
std::cout << oss.str().c_str();
}
UAISO_EXPECT_INT_EQ(expected.size(), syms.size());
for (const auto& s : expected) {
UAISO_EXPECT_TRUE(std::find_if(syms.begin(), syms.end(),
[s](auto sym) {
if (isDecl(sym))
return ConstDeclSymbol_Cast(sym)->name()->str() == s;
if (sym->kind() == Symbol::Kind::Namespace)
return ConstNamespace_Cast(sym)->name()->str() == s;
return false;
}) != syms.end());
}
return std::move(unit);
}
MAKE_CLASS_TEST(CompletionProposer)
| lgpl-2.1 |
fjalvingh/domui | to.etc.domui.demo/src/main/java/to/etc/domuidemo/pages/searchpanel/SearchPanelManual2.java | 1612 | package to.etc.domuidemo.pages.searchpanel;
import to.etc.domui.component.layout.ContentPanel;
import to.etc.domui.component.searchpanel.SearchPanel;
import to.etc.domui.component.searchpanel.lookupcontrols.DatePeriod;
import to.etc.domui.component.searchpanel.lookupcontrols.NumberLookupValue;
import to.etc.domui.derbydata.db.Customer;
import to.etc.domui.derbydata.db.Invoice;
import to.etc.util.DateUtil;
import to.etc.webapp.query.QOperation;
import java.math.BigDecimal;
/**
* Manual configuration with defaults.
*
* @author <a href="mailto:jal@etc.to">Frits Jalvingh</a>
* Created on 21-1-18.
*/
public class SearchPanelManual2 extends AbstractSearchPage<Invoice> {
public SearchPanelManual2() {
super(Invoice.class);
}
@Override public void createContent() throws Exception {
ContentPanel cp = new ContentPanel();
add(cp);
SearchPanel<Invoice> lf = new SearchPanel<>(Invoice.class);
cp.add(lf);
lf.setClicked(a -> search(lf.getCriteria()));
//-- Find customer by ID
Customer defaultCustomer = getSharedContext().get(Customer.class, Long.valueOf(10));
lf.add().property("customer").defaultValue(defaultCustomer).control(); // Default customer
//-- Default the search total to >= 5.0
NumberLookupValue nlv = new NumberLookupValue(QOperation.GE, BigDecimal.valueOf(5.0));
lf.add().property("total").defaultValue(nlv).control(); // Allow searching for a total
//-- Default the date to before 2010.
DatePeriod period = new DatePeriod(null, DateUtil.dateFor(2010, 0, 1));
lf.add().property("invoiceDate").defaultValue(period).control(); // And the date.
}
}
| lgpl-2.1 |
sugarlabs/sugar-toolkit | src/sugar/graphics/alert.py | 15963 | """
Alerts appear at the top of the body of your activity.
At a high level, Alert and its different variations (TimeoutAlert,
ConfirmationAlert, etc.) have a title, an alert message and then several
buttons that the user can click. The Alert class will pass "response" events
to your activity when any of these buttons are clicked, along with a
response_id to help you identify what button was clicked.
Examples
--------
create a simple alert message.
.. code-block:: python
from sugar.graphics.alert import Alert
...
# Create a new simple alert
alert = Alert()
# Populate the title and text body of the alert.
alert.props.title=_('Title of Alert Goes Here')
alert.props.msg = _('Text message of alert goes here')
# Call the add_alert() method (inherited via the sugar.graphics.Window
# superclass of Activity) to add this alert to the activity window.
self.add_alert(alert)
alert.show()
STABLE.
"""
# Copyright (C) 2007, One Laptop Per Child
# Copyright (C) 2010, Anish Mangal <anishmangal2002@gmail.com>
#
# 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 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.
import gettext
import gtk
import gobject
import pango
import math
from sugar.graphics import style
from sugar.graphics.icon import Icon
_ = lambda msg: gettext.dgettext('sugar-toolkit', msg)
class Alert(gtk.EventBox):
"""
UI interface for Alerts
Alerts are used inside the activity window instead of being a
separate popup window. They do not hide canvas content. You can
use add_alert(widget) and remove_alert(widget) inside your activity
to add and remove the alert. The position of the alert is below the
toolbox or top in fullscreen mode.
Properties:
'title': the title of the alert,
'message': the message of the alert,
'icon': the icon that appears at the far left
See __gproperties__
"""
__gtype_name__ = 'SugarAlert'
__gsignals__ = {
'response': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([object])),
}
__gproperties__ = {
'title': (str, None, None, None, gobject.PARAM_READWRITE),
'msg': (str, None, None, None, gobject.PARAM_READWRITE),
'icon': (object, None, None, gobject.PARAM_WRITABLE),
}
def __init__(self, **kwargs):
self._title = None
self._msg = None
self._icon = None
self._buttons = {}
self._hbox = gtk.HBox()
self._hbox.set_border_width(style.DEFAULT_SPACING)
self._hbox.set_spacing(style.DEFAULT_SPACING)
self._msg_box = gtk.VBox()
self._title_label = gtk.Label()
self._title_label.set_alignment(0, 0.5)
self._msg_box.pack_start(self._title_label, False)
self._msg_label = gtk.Label()
self._msg_label.set_alignment(0, 0.5)
self._msg_box.pack_start(self._msg_label, False)
self._hbox.pack_start(self._msg_box, False)
self._buttons_box = gtk.HButtonBox()
self._buttons_box.set_layout(gtk.BUTTONBOX_END)
self._buttons_box.set_spacing(style.DEFAULT_SPACING)
self._hbox.pack_end(self._buttons_box)
gobject.GObject.__init__(self, **kwargs)
self.set_visible_window(True)
self.add(self._hbox)
self._title_label.show()
self._msg_label.show()
self._buttons_box.show()
self._msg_box.show()
self._hbox.show()
self.show()
def do_set_property(self, pspec, value):
"""
Set alert property
Parameters
----------
pspec :
value :
Returns
-------
None
"""
if pspec.name == 'title':
if self._title != value:
self._title = value
self._title_label.set_markup('<b>' + self._title + '</b>')
elif pspec.name == 'msg':
if self._msg != value:
self._msg = value
self._msg_label.set_markup(self._msg)
self._msg_label.set_line_wrap(True)
elif pspec.name == 'icon':
if self._icon != value:
self._icon = value
self._hbox.pack_start(self._icon, False)
self._hbox.reorder_child(self._icon, 0)
def do_get_property(self, pspec):
"""
Get alert property
Parameters
----------
pspec :
property for which the value will be returned
Returns
-------
value of the property specified
"""
if pspec.name == 'title':
return self._title
elif pspec.name == 'msg':
return self._msg
def add_entry(self):
"""
Add an entry, after the title and before the buttons.
Returns:
gtk.Entry: the entry added to the alert
"""
entry = gtk.Entry()
self._hbox.pack_start(entry, True, True, 0)
entry.show()
self._hbox.reorder_child(entry, 2)
return entry
def add_button(self, response_id, label, icon=None, position=-1):
"""
Add a button to the alert
Parameters
----------
response_id :
will be emitted with the response signal a response ID should one
of the pre-defined GTK Response Type Constants or a positive number
label :
that will occure right to the buttom
icon :
this can be a SugarIcon or a gtk.Image
postion :
the position of the button in the box (optional)
Returns
-------
button :gtk.Button
"""
button = gtk.Button()
self._buttons[response_id] = button
if icon is not None:
button.set_image(icon)
button.set_label(label)
self._buttons_box.pack_start(button)
button.show()
button.connect('clicked', self.__button_clicked_cb, response_id)
if position != -1:
self._buttons_box.reorder_child(button, position)
return button
def remove_button(self, response_id):
"""
Remove a button from the alert by the given response id
Parameters
----------
response_id :
Returns
-------
None
"""
self._buttons_box.remove(self._buttons[response_id])
def _response(self, response_id):
"""Emitting response when we have a result
A result can be that a user has clicked a button or
a timeout has occured, the id identifies the button
that has been clicked and -1 for a timeout
"""
self.emit('response', response_id)
def __button_clicked_cb(self, button, response_id):
self._response(response_id)
class ConfirmationAlert(Alert):
"""
This is a ready-made two button (Cancel,Ok) alert.
A confirmation alert is a nice shortcut from a standard Alert because it
comes with 'OK' and 'Cancel' buttons already built-in. When clicked, the
'OK' button will emit a response with a response_id of gtk.RESPONSE_OK,
while the 'Cancel' button will emit gtk.RESPONSE_CANCEL.
Examples
--------
.. code-block:: python
from sugar.graphics.alert import ConfirmationAlert
...
#### Method: _alert_confirmation, create a Confirmation alert (with ok
and cancel buttons standard)
# and add it to the UI.
def _alert_confirmation(self):
alert = ConfirmationAlert()
alert.props.title=_('Title of Alert Goes Here')
alert.props.msg = _('Text message of alert goes here')
alert.connect('response', self._alert_response_cb)
self.add_alert(alert)
#### Method: _alert_response_cb, called when an alert object throws a
response event.
def _alert_response_cb(self, alert, response_id):
#remove the alert from the screen, since either a response button
#was clicked or there was a timeout
self.remove_alert(alert)
#Do any work that is specific to the type of button clicked.
if response_id is gtk.RESPONSE_OK:
print 'Ok Button was clicked. Do any work upon ok here ...'
elif response_id is gtk.RESPONSE_CANCEL:
print 'Cancel Button was clicked.'
"""
def __init__(self, **kwargs):
Alert.__init__(self, **kwargs)
icon = Icon(icon_name='dialog-cancel')
self.add_button(gtk.RESPONSE_CANCEL, _('Cancel'), icon)
icon.show()
icon = Icon(icon_name='dialog-ok')
self.add_button(gtk.RESPONSE_OK, _('Ok'), icon)
icon.show()
class ErrorAlert(Alert):
"""
This is a ready-made one button (Ok) alert.
An error alert is a nice shortcut from a standard Alert because it
comes with the 'OK' button already built-in. When clicked, the
'OK' button will emit a response with a response_id of gtk.RESPONSE_OK.
Examples
--------
.. code-block:: python
from sugar.graphics.alert import ErrorAlert
...
#### Method: _alert_error, create a Error alert (with ok
button standard)
# and add it to the UI.
def _alert_error(self):
alert = ErrorAlert()
alert.props.title=_('Title of Alert Goes Here')
alert.props.msg = _('Text message of alert goes here')
alert.connect('response', self._alert_response_cb)
self.add_alert(alert)
#### Method: _alert_response_cb, called when an alert object throws a
response event.
def _alert_response_cb(self, alert, response_id):
#remove the alert from the screen, since either a response button
#was clicked or there was a timeout
self.remove_alert(alert)
#Do any work that is specific to the response_id.
if response_id is gtk.RESPONSE_OK:
print 'Ok Button was clicked. Do any work upon ok here ...'
"""
def __init__(self, **kwargs):
Alert.__init__(self, **kwargs)
icon = Icon(icon_name='dialog-ok')
self.add_button(gtk.RESPONSE_OK, _('Ok'), icon)
icon.show()
class _TimeoutIcon(gtk.Alignment):
__gtype_name__ = 'SugarTimeoutIcon'
def __init__(self):
gtk.Alignment.__init__(self, 0, 0, 1, 1)
self.set_app_paintable(True)
self._text = gtk.Label()
self._text.set_alignment(0.5, 0.5)
attrlist = pango.AttrList()
attrlist.insert(pango.AttrWeight(pango.WEIGHT_BOLD))
self._text.set_attributes(attrlist)
self.add(self._text)
self._text.show()
self.connect("expose_event", self.__expose_cb)
def __expose_cb(self, widget, event):
context = widget.window.cairo_create()
self._draw(context)
return False
def do_size_request(self, requisition):
requisition.height, requisition.width = \
gtk.icon_size_lookup(gtk.ICON_SIZE_BUTTON)
self._text.size_request()
def _draw(self, context):
rect = self.get_allocation()
x = rect.x + rect.width * 0.5
y = rect.y + rect.height * 0.5
radius = rect.width / 2
context.arc(x, y, radius, 0, 2 * math.pi)
widget_style = self.get_style()
context.set_source_color(widget_style.bg[self.get_state()])
context.fill_preserve()
def set_text(self, text):
self._text.set_text(str(text))
class TimeoutAlert(Alert):
"""
This is a ready-made two button (Cancel,Continue) alert
It times out with a positive response after the given amount of seconds.
Examples
--------
.. code-block:: python
from sugar.graphics.alert import TimeoutAlert
...
#### Method: _alert_timeout, create a Timeout alert (with ok and cancel
buttons standard)
# and add it to the UI.
def _alert_timeout(self):
#Notice that for a TimeoutAlert, you pass the number of seconds in
#which to timeout. By default, this is 5.
alert = TimeoutAlert(10)
alert.props.title=_('Title of Alert Goes Here')
alert.props.msg = _('Text message of timeout alert goes here')
alert.connect('response', self._alert_response_cb)
self.add_alert(alert)
#### Method: _alert_response_cb, called when an alert object throws a
response event.
def _alert_response_cb(self, alert, response_id):
#remove the alert from the screen, since either a response button
#was clicked or there was a timeout
self.remove_alert(alert)
#Do any work that is specific to the type of button clicked.
if response_id is gtk.RESPONSE_OK:
print 'Ok Button was clicked. Do any work upon ok here ...'
elif response_id is gtk.RESPONSE_CANCEL:
print 'Cancel Button was clicked.'
elif response_id == -1:
print 'Timout occurred'
"""
def __init__(self, timeout=5, **kwargs):
Alert.__init__(self, **kwargs)
self._timeout = timeout
icon = Icon(icon_name='dialog-cancel')
self.add_button(gtk.RESPONSE_CANCEL, _('Cancel'), icon)
icon.show()
self._timeout_text = _TimeoutIcon()
self._timeout_text.set_text(self._timeout)
self.add_button(gtk.RESPONSE_OK, _('Continue'), self._timeout_text)
self._timeout_text.show()
gobject.timeout_add_seconds(1, self.__timeout)
def __timeout(self):
self._timeout -= 1
self._timeout_text.set_text(self._timeout)
if self._timeout == 0:
self._response(gtk.RESPONSE_OK)
return False
return True
class NotifyAlert(Alert):
"""
Timeout alert with only an "OK" button - just for notifications
Examples
--------
.. code-block:: python
from sugar.graphics.alert import NotifyAlert
...
#### Method: _alert_notify, create a Notify alert (with only an 'OK'
button)
# and add it to the UI.
def _alert_notify(self):
#Notice that for a NotifyAlert, you pass the number of seconds in
#which to notify. By default, this is 5.
alert = NotifyAlert(10)
alert.props.title=_('Title of Alert Goes Here')
alert.props.msg = _('Text message of notify alert goes here')
alert.connect('response', self._alert_response_cb)
self.add_alert(alert)
"""
def __init__(self, timeout=5, **kwargs):
Alert.__init__(self, **kwargs)
self._timeout = timeout
self._timeout_text = _TimeoutIcon()
self._timeout_text.set_text(self._timeout)
self.add_button(gtk.RESPONSE_OK, _('Ok'), self._timeout_text)
self._timeout_text.show()
gobject.timeout_add(1000, self.__timeout)
def __timeout(self):
self._timeout -= 1
self._timeout_text.set_text(self._timeout)
if self._timeout == 0:
self._response(gtk.RESPONSE_OK)
return False
return True
| lgpl-2.1 |
pennymax/meego-qa-reports | config/initializers/session_store.rb | 581 | # Be sure to restart your server when you modify this file.
Meegoqa::Application.config.session_store :cookie_store, :key => '_meegoqa_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# Meegoqa::Application.config.session_store :active_record_store
Rails.application.config.middleware.insert_before(
ActionDispatch::Session::CookieStore,
FlashSessionCookieMiddleware,
Rails.application.config.session_options[:key]
) | lgpl-2.1 |
calexslash/MyMod | src/main/java/com/Cameron/Slash/items/ItemTinDagger.java | 502 | package com.Cameron.Slash.items;
import com.Cameron.Slash.Reference;
import net.minecraft.creativetab.CreativeTabs;
/**
* Created by slashcam000 on 5/24/2017.
*/
public class ItemTinDagger extends ItemDagger{
public ItemTinDagger(ToolMaterial material) {
super(material);
setUnlocalizedName(Reference.TutorialItems.TINDAGGER.getUnlocalizedName());
setRegistryName(Reference.TutorialItems.TINDAGGER.getRegistryName());
setCreativeTab(CreativeTabs.TOOLS);
}
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/filter/types/ElementTypeUtils.java | 11968 | /*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.filter.types;
import org.pentaho.reporting.engine.classic.core.AttributeNames;
import org.pentaho.reporting.engine.classic.core.ReportElement;
import org.pentaho.reporting.engine.classic.core.ResourceBundleFactory;
import org.pentaho.reporting.engine.classic.core.function.ExpressionRuntime;
import org.pentaho.reporting.libraries.base.util.IOUtils;
import org.pentaho.reporting.libraries.base.util.StringUtils;
import org.pentaho.reporting.libraries.formula.EvaluationException;
import org.pentaho.reporting.libraries.formula.typing.ArrayCallback;
import org.pentaho.reporting.libraries.xmlns.common.ParserUtil;
import java.math.BigDecimal;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class ElementTypeUtils {
private static final Number[] EMPTY_NUMBERS = new Number[0];
private ElementTypeUtils() {
}
public static Object queryFieldName( final ReportElement element ) {
if ( element == null ) {
throw new NullPointerException( "Element must never be null." );
}
final Object attribute = element.getAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.FIELD );
if ( attribute != null ) {
return attribute;
}
return null;
}
public static Object queryStaticValue( final ReportElement element ) {
if ( element == null ) {
throw new NullPointerException( "Element must never be null." );
}
final Object attribute = element.getAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE );
if ( attribute != null ) {
return attribute;
}
return null;
}
public static Object queryFieldOrValue( final ExpressionRuntime runtime, final ReportElement element ) {
if ( runtime == null ) {
throw new NullPointerException( "Runtime must never be null." );
}
if ( element == null ) {
throw new NullPointerException( "Element must never be null." );
}
// This has been possibly computed by the system using a formula or other attribute-expression.
final Object value = element.getAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE );
if ( value != null ) {
return value;
}
final Object field = element.getAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.FIELD );
if ( field != null ) {
return runtime.getDataRow().get( String.valueOf( field ) );
}
return null;
}
public static String queryResourceId( final ExpressionRuntime runtime, final ReportElement element ) {
if ( runtime == null ) {
throw new NullPointerException( "Runtime must never be null." );
}
if ( element == null ) {
throw new NullPointerException( "Element must never be null." );
}
final Object resourceId =
element.getAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.RESOURCE_IDENTIFIER );
if ( resourceId != null ) {
return String.valueOf( resourceId );
}
return runtime.getConfiguration().getConfigProperty( ResourceBundleFactory.DEFAULT_RESOURCE_BUNDLE_CONFIG_KEY );
}
public static String toString( final Object object ) {
if ( object == null ) {
return null;
}
if ( object instanceof String ) {
return (String) object;
}
if ( object instanceof Clob ) {
final Clob clob = (Clob) object;
try {
return IOUtils.getInstance().readClob( clob );
} catch ( Exception e ) {
return null;
}
}
if ( object.getClass().isArray() ) {
if ( object instanceof char[] ) {
return new String( (char[]) object );
}
if ( object instanceof Object[] ) {
final StringBuilder b = new StringBuilder();
final Object[] array = (Object[]) object;
for ( int i = 0; i < array.length; i++ ) {
if ( i != 0 ) {
b.append( ", " );
}
b.append( toString( array[i] ) );
}
return b.toString();
}
if ( object instanceof byte[] ) {
final StringBuilder b = new StringBuilder();
final byte[] array = (byte[]) object;
for ( int i = 0; i < array.length; i++ ) {
if ( i != 0 ) {
b.append( ", " );
}
b.append( array[i] );
}
return b.toString();
}
if ( object instanceof short[] ) {
final StringBuilder b = new StringBuilder();
final short[] array = (short[]) object;
for ( int i = 0; i < array.length; i++ ) {
if ( i != 0 ) {
b.append( ", " );
}
b.append( array[i] );
}
return b.toString();
}
if ( object instanceof boolean[] ) {
final StringBuilder b = new StringBuilder();
final boolean[] array = (boolean[]) object;
for ( int i = 0; i < array.length; i++ ) {
if ( i != 0 ) {
b.append( ", " );
}
b.append( array[i] );
}
return b.toString();
}
if ( object instanceof int[] ) {
final StringBuilder b = new StringBuilder();
final int[] array = (int[]) object;
for ( int i = 0; i < array.length; i++ ) {
if ( i != 0 ) {
b.append( ", " );
}
b.append( array[i] );
}
return b.toString();
}
if ( object instanceof long[] ) {
final StringBuilder b = new StringBuilder();
final long[] array = (long[]) object;
for ( int i = 0; i < array.length; i++ ) {
if ( i != 0 ) {
b.append( ", " );
}
b.append( array[i] );
}
return b.toString();
}
if ( object instanceof float[] ) {
final StringBuilder b = new StringBuilder();
final float[] array = (float[]) object;
for ( int i = 0; i < array.length; i++ ) {
if ( i != 0 ) {
b.append( ", " );
}
b.append( array[i] );
}
return b.toString();
}
if ( object instanceof double[] ) {
final StringBuilder b = new StringBuilder();
final double[] array = (double[]) object;
for ( int i = 0; i < array.length; i++ ) {
if ( i != 0 ) {
b.append( ", " );
}
b.append( array[i] );
}
return b.toString();
}
}
return String.valueOf( object );
}
public static Number getNumberAttribute( final ReportElement e, final String namespace, final String name,
final Number defaultValue ) {
final Object val = e.getAttribute( namespace, name );
if ( val == null ) {
return defaultValue;
}
if ( val instanceof Number ) {
return (Number) val;
}
return defaultValue;
}
public static int getIntAttribute( final ReportElement e, final String namespace, final String name,
final int defaultValue ) {
final Object val = e.getAttribute( namespace, name );
if ( val == null ) {
return defaultValue;
}
if ( val instanceof Number ) {
final Number nval = (Number) val;
return nval.intValue();
}
return ParserUtil.parseInt( String.valueOf( val ), defaultValue );
}
public static String getStringAttribute( final ReportElement e, final String namespace, final String name,
final String defaultValue ) {
final Object val = e.getAttribute( namespace, name );
if ( val == null ) {
return defaultValue;
}
return String.valueOf( val );
}
public static boolean getBooleanAttribute( final ReportElement e, final String namespace, final String name,
final boolean defaultValue ) {
final Object val = e.getAttribute( namespace, name );
if ( val == null ) {
return defaultValue;
}
if ( val instanceof Boolean ) {
final Boolean nval = (Boolean) val;
return nval.booleanValue();
}
return ParserUtil.parseBoolean( String.valueOf( val ), defaultValue );
}
public static Number[] getData( final Object o ) {
final ArrayList<Number> numbers = new ArrayList<Number>();
try {
if ( o instanceof ArrayCallback ) {
final ArrayCallback acb = (ArrayCallback) o;
final int rowCount = acb.getRowCount();
final int colCount = acb.getColumnCount();
for ( int row = 0; row < rowCount; row++ ) {
for ( int column = 0; column < colCount; column++ ) {
numbers.add( (Number) acb.getValue( row, column ) );
}
}
return numbers.toArray( new Number[numbers.size()] );
}
if ( o instanceof List ) {
final List<?> l = (List<?>) o;
for ( int i = 0; i < l.size(); i++ ) {
final Object value = l.get( i );
if ( value instanceof Number ) {
numbers.add( (Number) value );
} else if ( value instanceof String ) {
numbers.add( new BigDecimal( (String) value ) );
}
}
return numbers.toArray( new Number[numbers.size()] );
}
if ( o instanceof Object[] ) {
final Object[] l = (Object[]) o;
arrayToList( numbers, l );
return numbers.toArray( new Number[numbers.size()] );
}
if ( o instanceof String ) {
return toBigDecimalList( (String) o, "," );
}
if ( o instanceof Number ) {
numbers.add( (Number) o );
return numbers.toArray( new Number[numbers.size()] );
}
} catch ( final NumberFormatException nfe ) {
// fall through...
} catch ( EvaluationException e ) {
// ignore ..
}
return null;
}
private static void arrayToList( final ArrayList<Number> numbers, final Object[] l ) {
for ( int i = 0; i < l.length; i++ ) {
final Object value = l[i];
if ( value instanceof Number ) {
numbers.add( (Number) value );
} else if ( value instanceof String ) {
numbers.add( new BigDecimal( (String) value ) );
} else if ( value instanceof Object[] ) {
final Object[] innerArray = (Object[]) value;
arrayToList( numbers, innerArray );
}
}
}
/**
* Converts the given string into a array of <code>BigDecimal</code> numbers using the given separator as splitting
* argument.<br/>
* Take care that <code>BigDecimal</code> string constructor do not support inputs like "10f", "5d" ...
*
* @param s
* the string to be converted.
* @param sep
* the separator, usually a comma.
* @return the array of numbers produced from the string.
*/
private static Number[] toBigDecimalList( final String s, final String sep ) {
if ( StringUtils.isEmpty( s ) ) {
return EMPTY_NUMBERS;
}
final StringTokenizer stringTokenizer = new StringTokenizer( s, sep );
final Number[] ret = new Number[stringTokenizer.countTokens()];
int i = 0;
while ( stringTokenizer.hasMoreTokens() ) {
final String val = stringTokenizer.nextToken().trim();
ret[i] = new BigDecimal( val );
i += 1;
}
return ret;
}
}
| lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsh/itemh241.java | 159 | package fr.toss.FF7itemsh;
public class itemh241 extends FF7itemshbase {
public itemh241(int id) {
super(id);
setUnlocalizedName("itemh241");
}
}
| lgpl-2.1 |
fifengine/fifengine | engine/python/fife/extensions/pychan/widgets/radiobutton.py | 4543 | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE 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
# ####################################################################
from __future__ import absolute_import
from fife import fifechan
from fife.extensions.pychan.attrs import Attr, BoolAttr
from .basictextwidget import BasicTextWidget
from .common import text2gui
class RadioButton(BasicTextWidget):
"""
A basic radiobutton (an exclusive checkbox).
New Attributes
==============
- marked: Boolean: Whether the checkbox is checked or not.
- group: String: All RadioButtons with the same group name
can only be checked exclusively.
Data
====
The marked status can be read and set via L{distributeData} and L{collectData}
"""
ATTRIBUTES = BasicTextWidget.ATTRIBUTES + [ BoolAttr('marked'),
Attr('group')
]
DEFAULT_GROUP = "_no_group_"
def __init__(self,
parent = None,
name = None,
size = None,
min_size = None,
max_size = None,
fixed_size = None,
margins = None,
padding = None,
helptext = None,
position = None,
style = None,
hexpand = None,
vexpand = None,
font = None,
base_color = None,
background_color = None,
foreground_color = None,
selection_color = None,
border_color = None,
outline_color = None,
border_size = None,
outline_size = None,
position_technique = None,
is_focusable = None,
comment = None,
text = None,
group = None):
self.real_widget = fifechan.RadioButton()
self.group = self.DEFAULT_GROUP
super(RadioButton,self).__init__(parent=parent,
name=name,
size=size,
min_size=min_size,
max_size=max_size,
fixed_size=fixed_size,
margins=margins,
padding=padding,
helptext=helptext,
position=position,
style=style,
hexpand=hexpand,
vexpand=vexpand,
font=font,
base_color=base_color,
background_color=background_color,
foreground_color=foreground_color,
selection_color=selection_color,
border_color=border_color,
outline_color=outline_color,
border_size=border_size,
outline_size=outline_size,
position_technique=position_technique,
is_focusable=is_focusable,
comment=comment,
text=text)
if group is not None: self.group = group
# Prepare Data collection framework
self.accepts_data = True
self._realGetData = self._isMarked
self._realSetData = self._setMarked
# Initial data stuff inherited.
def clone(self, prefix):
rbuttonClone = RadioButton(None,
self._createNameWithPrefix(prefix),
self.size,
self.min_size,
self.max_size,
self.fixed_size,
self.margins,
self.padding,
self.helptext,
self.position,
self.style,
self.hexpand,
self.vexpand,
self.font,
self.base_color,
self.background_color,
self.foreground_color,
self.selection_color,
self.border_color,
self.outline_color,
self.border_size,
self.outline_size,
self.position_technique,
self.is_focusable,
self.comment,
self.text,
self.group)
return rbuttonClone
def _isMarked(self): return self.real_widget.isSelected()
def _setMarked(self,mark): self.real_widget.setSelected(mark)
marked = property(_isMarked,_setMarked)
def _setGroup(self,group): self.real_widget.setGroup(group)
def _getGroup(self): return self.real_widget.getGroup()
group = property(_getGroup,_setGroup)
| lgpl-2.1 |
Mag-nus/Mag-Plugins | Mag-Tools/Macros/InventoryPacker.cs | 11663 | using System;
using System.IO;
using System.Collections.ObjectModel;
using Mag.Shared;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
namespace MagTools.Macros
{
class InventoryPacker : IDisposable, IInventoryPacker
{
public InventoryPacker()
{
try
{
CoreManager.Current.ChatBoxMessage += new EventHandler<ChatTextInterceptEventArgs>(Current_ChatBoxMessage);
}
catch (Exception ex) { Debug.LogException(ex); }
}
private bool disposed;
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!disposed)
{
if (disposing)
{
if (started)
Stop();
CoreManager.Current.ChatBoxMessage -= new EventHandler<ChatTextInterceptEventArgs>(Current_ChatBoxMessage);
}
// Indicate that the instance has been disposed.
disposed = true;
}
}
void Current_ChatBoxMessage(object sender, ChatTextInterceptEventArgs e)
{
try
{
if (e.Text.StartsWith("You say, ") || e.Text.Contains("says, \""))
return;
if (e.Text.ToLower().Contains(CoreManager.Current.CharacterFilter.Name.ToLower() + " autopack"))
{
e.Eat = true;
Start();
}
}
catch (Exception ex) { Debug.LogException(ex); }
}
bool started;
// We store our lootProfile as an object instead of a VTClassic.LootCore.
// We do this so that if this object is instantiated before vtank's plugins are loaded, we don't throw a VTClassic.dll error.
// By delaying the object initialization to use, we can make sure we're using the VTClassic.dll that Virindi Tank loads.
private object lootProfile;
bool idsRequested;
readonly Collection<int> blackLitedItems = new Collection<int>();
public void Start()
{
if (started)
return;
// Init our LootCore object at the very last minute (looks for VTClassic.dll if its not already loaded)
if (lootProfile == null)
lootProfile = new VTClassic.LootCore();
FileInfo fileInfo = new FileInfo(PluginCore.PluginPersonalFolder + @"\" + CoreManager.Current.CharacterFilter.Name + ".AutoPack.utl");
if (!fileInfo.Exists)
{
// Try to find a Default.AutoPack.utl
fileInfo = new FileInfo(PluginCore.PluginPersonalFolder + @"\" + "Default.AutoPack.utl");
if (!fileInfo.Exists)
return;
}
MyClasses.VCS_Connector.SendChatTextCategorized("CommandLine", "<{" + PluginCore.PluginName + "}>: " + "Auto Pack - Started.", 5, Settings.SettingsManager.Misc.OutputTargetWindow.Value);
// Load our loot profile
((VTClassic.LootCore)lootProfile).LoadProfile(fileInfo.FullName, false);
idsRequested = false;
blackLitedItems.Clear();
CoreManager.Current.RenderFrame += new EventHandler<EventArgs>(Current_RenderFrame);
started = true;
}
public void Stop()
{
if (!started)
return;
CoreManager.Current.RenderFrame -= new EventHandler<EventArgs>(Current_RenderFrame);
((VTClassic.LootCore)lootProfile).UnloadProfile();
started = false;
MyClasses.VCS_Connector.SendChatTextCategorized("CommandLine", "<{" + PluginCore.PluginName + "}>: " + "Auto Pack - Completed.", 5, Settings.SettingsManager.Misc.OutputTargetWindow.Value);
}
DateTime lastThought = DateTime.MinValue;
void Current_RenderFrame(object sender, EventArgs e)
{
try
{
if (DateTime.UtcNow - lastThought < TimeSpan.FromMilliseconds(100))
return;
lastThought = DateTime.UtcNow;
Think();
}
catch (Exception ex) { Debug.LogException(ex); }
}
int currentWorkingId;
DateTime currentWorkingIdFirstAttempt;
void Think()
{
if (!idsRequested)
{
foreach (WorldObject item in CoreManager.Current.WorldFilter.GetInventory())
{
// If the item is equipped or wielded, don't process it.
if (item.Values(LongValueKey.EquippedSlots, 0) > 0 || item.Values(LongValueKey.Slot, -1) == -1)
continue;
// Convert the item into a VT GameItemInfo object
uTank2.LootPlugins.GameItemInfo itemInfo = uTank2.PluginCore.PC.FWorldTracker_GetWithID(item.Id);
if (itemInfo == null)
{
// This happens all the time for aetheria that has been converted
continue;
}
if (((VTClassic.LootCore)lootProfile).DoesPotentialItemNeedID(itemInfo))
CoreManager.Current.Actions.RequestId(item.Id);
}
idsRequested = true;
}
if (CoreManager.Current.Actions.BusyState != 0)
return;
if (DoAutoStack())
return;
if (DoAutoPack())
return;
// If we've gotten to this point no items were moved.
Stop();
}
bool DoAutoStack()
{
foreach (WorldObject item in CoreManager.Current.WorldFilter.GetInventory())
{
if (blackLitedItems.Contains(item.Id))
continue;
// If the item is equipped or wielded, don't process it.
if (item.Values(LongValueKey.EquippedSlots, 0) > 0 || item.Values(LongValueKey.Slot, -1) == -1)
continue;
// If the item isn't stackable, don't process it.
if (item.Values(LongValueKey.StackMax, 0) <= 1)
continue;
// If the item is already max stack, don't process it
if (item.Values(LongValueKey.StackCount, 0) == item.Values(LongValueKey.StackMax))
continue;
foreach (WorldObject secondItem in CoreManager.Current.WorldFilter.GetByContainer(item.Container))
{
if (item.Id == secondItem.Id || item.Name != secondItem.Name)
continue;
// If the item is already max stack, don't process it
if (secondItem.Values(LongValueKey.StackCount, 0) == secondItem.Values(LongValueKey.StackMax))
continue;
if (currentWorkingId != item.Id)
{
currentWorkingId = item.Id;
currentWorkingIdFirstAttempt = DateTime.UtcNow;
}
else
{
if (DateTime.UtcNow - currentWorkingIdFirstAttempt > TimeSpan.FromSeconds(10))
{
Debug.WriteToChat("Blacklisting item: " + item.Id + ", " + item.Name);
blackLitedItems.Add(item.Id);
return true;
}
}
CoreManager.Current.Actions.MoveItem(item.Id, secondItem.Id);
return true;
}
}
return false;
}
private struct ItemToProcess
{
public ItemToProcess(int id, int[] targetPackIds)
{
Id = id;
TargetPackIds = targetPackIds;
}
public readonly int Id;
public readonly int[] TargetPackIds;
}
bool DoAutoPack()
{
bool waitingForIds = false;
// Get all of our side pack information and put them in the correct order
int[] packs = new int[CoreManager.Current.WorldFilter[CoreManager.Current.CharacterFilter.Id].Values(LongValueKey.PackSlots) + 1];
// Main pack
packs[0] = CoreManager.Current.CharacterFilter.Id;
// Load the side pack information
foreach (WorldObject obj in CoreManager.Current.WorldFilter.GetByContainer(CoreManager.Current.CharacterFilter.Id))
{
if (obj.ObjectClass != ObjectClass.Container)
continue;
packs[obj.Values(LongValueKey.Slot) + 1] = obj.Id;
}
// Process our inventory
Collection<ItemToProcess> itemsToProcess = new Collection<ItemToProcess>();
foreach (WorldObject item in CoreManager.Current.WorldFilter.GetInventory())
{
if (blackLitedItems.Contains(item.Id))
continue;
// If the item is equipped or wielded, don't process it.
if (item.Values(LongValueKey.EquippedSlots, 0) > 0 || item.Values(LongValueKey.Slot, -1) == -1)
continue;
// If the item is a container or a foci, don't process it.
if (item.ObjectClass == ObjectClass.Container || item.ObjectClass == ObjectClass.Foci)
continue;
// Convert the item into a VT GameItemInfo object
uTank2.LootPlugins.GameItemInfo itemInfo = uTank2.PluginCore.PC.FWorldTracker_GetWithID(item.Id);
if (itemInfo == null)
{
// This happens all the time for aetheria that has been converted
continue;
}
if (((VTClassic.LootCore)lootProfile).DoesPotentialItemNeedID(itemInfo))
{
waitingForIds = true;
continue;
}
uTank2.LootPlugins.LootAction result = ((VTClassic.LootCore)lootProfile).GetLootDecision(itemInfo);
if (!result.IsKeepUpTo)
continue;
// Separate the Data1 int result into a byte[]. Meaning, turn 123456 into { 1, 2, 3, 4, 5, 6 }
char[] packNumbersAsChar = result.Data1.ToString().ToCharArray();
byte[] packNumbers = new byte[packNumbersAsChar.Length];
for (int i = 0 ; i < packNumbersAsChar.Length ; i++)
packNumbers[i] = byte.Parse(packNumbersAsChar[i].ToString());
// If this item is already in its primary pack, we don't need to queue it up.
if (item.Container == packs[packNumbers[0]])
continue;
int[] targetPackIds = new int[packNumbers.Length];
for (int i = 0 ; i < packNumbers.Length ; i++)
targetPackIds[i] = packs[packNumbers[i]];
ItemToProcess itemToProcess = new ItemToProcess(item.Id, targetPackIds);
itemsToProcess.Add(itemToProcess);
}
// Lets go through our list and see if any items are in their primary target pack
for (int i = itemsToProcess.Count - 1 ; i >= 0 ; i--)
{
ItemToProcess itemToProcess = itemsToProcess[i];
WorldObject item = CoreManager.Current.WorldFilter[itemToProcess.Id];
if (item == null)
{
itemsToProcess.RemoveAt(i);
continue;
}
if (item.Container == itemToProcess.TargetPackIds[0])
itemsToProcess.RemoveAt(i);
}
Collection<int> itemsToSkip = new Collection<int>();
// Lets see if we can find an item that can be moved to its target pack
for (int packIndex = 0 ; packIndex < 10 ; packIndex++)
{
for (int i = itemsToProcess.Count - 1 ; i >= 0 ; i--)
{
ItemToProcess itemToProcess = itemsToProcess[i];
WorldObject item = CoreManager.Current.WorldFilter[itemToProcess.Id];
if (itemToProcess.TargetPackIds.Length <= packIndex)
continue;
if (itemsToSkip.Contains(item.Id))
continue;
// Check to see if this item is already in the target pack
if (item.Container == itemToProcess.TargetPackIds[packIndex])
{
itemsToSkip.Add(item.Id);
continue;
}
// Check to see that the target is even a pack.
WorldObject target = CoreManager.Current.WorldFilter[itemToProcess.TargetPackIds[packIndex]];
if (target == null || (target.ObjectClass != ObjectClass.Container && target.ObjectClass != ObjectClass.Player))
continue;
if (Util.GetFreePackSlots(itemToProcess.TargetPackIds[packIndex]) > 0)
{
if (currentWorkingId != item.Id)
{
currentWorkingId = item.Id;
currentWorkingIdFirstAttempt = DateTime.UtcNow;
}
else
{
if (DateTime.UtcNow - currentWorkingIdFirstAttempt > TimeSpan.FromSeconds(10))
{
Debug.WriteToChat("Blacklisting item: " + item.Id + ", " + item.Name);
blackLitedItems.Add(item.Id);
return true;
}
}
CoreManager.Current.Actions.MoveItem(item.Id, itemToProcess.TargetPackIds[packIndex], 0, true);
return true;
}
}
}
if (waitingForIds)
return true;
return false;
}
}
}
| lgpl-2.1 |
cogtool/cogtool | java/edu/cmu/cs/hcii/cogtool/controller/DesignEditorCmd.java | 35042 | /*******************************************************************************
* CogTool Copyright Notice and Distribution Terms
* CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* CogTool 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.
*
* CogTool 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 CogTool; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* CogTool makes use of several third-party components, with the
* following notices:
*
* Eclipse SWT version 3.448
* Eclipse GEF Draw2D version 3.2.1
*
* Unless otherwise indicated, all Content made available by the Eclipse
* Foundation is provided to you under the terms and conditions of the Eclipse
* Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this
* Content and is also available at http://www.eclipse.org/legal/epl-v10.html.
*
* CLISP version 2.38
*
* Copyright (c) Sam Steingold, Bruno Haible 2001-2006
* This software is distributed under the terms of the FSF Gnu Public License.
* See COPYRIGHT file in clisp installation folder for more information.
*
* ACT-R 6.0
*
* Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere &
* John R Anderson.
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* Apache Jakarta Commons-Lang 2.1
*
* This product contains software developed by the Apache Software Foundation
* (http://www.apache.org/)
*
* jopt-simple version 1.0
*
* Copyright (c) 2004-2013 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Mozilla XULRunner 1.9.0.5
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/.
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The J2SE(TM) Java Runtime Environment version 5.0
*
* Copyright 2009 Sun Microsystems, Inc., 4150
* Network Circle, Santa Clara, California 95054, U.S.A. All
* rights reserved. U.S.
* See the LICENSE file in the jre folder for more information.
******************************************************************************/
package edu.cmu.cs.hcii.cogtool.controller;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import edu.cmu.cs.hcii.cogtool.CogToolClipboard;
import edu.cmu.cs.hcii.cogtool.CogToolLID;
import edu.cmu.cs.hcii.cogtool.FrameTemplateSupport;
import edu.cmu.cs.hcii.cogtool.controller.DemoStateManager.IDesignUndoableEdit;
import edu.cmu.cs.hcii.cogtool.model.AParentWidget;
import edu.cmu.cs.hcii.cogtool.model.AShape;
import edu.cmu.cs.hcii.cogtool.model.Design;
import edu.cmu.cs.hcii.cogtool.model.DeviceType;
import edu.cmu.cs.hcii.cogtool.model.DoublePoint;
import edu.cmu.cs.hcii.cogtool.model.DoubleSize;
import edu.cmu.cs.hcii.cogtool.model.Frame;
import edu.cmu.cs.hcii.cogtool.model.FrameElement;
import edu.cmu.cs.hcii.cogtool.model.FrameElementGroup;
import edu.cmu.cs.hcii.cogtool.model.ChildWidget;
import edu.cmu.cs.hcii.cogtool.model.GridButtonGroup;
import edu.cmu.cs.hcii.cogtool.model.MenuItem;
import edu.cmu.cs.hcii.cogtool.model.Transition;
import edu.cmu.cs.hcii.cogtool.model.TransitionSource;
import edu.cmu.cs.hcii.cogtool.model.IWidget;
import edu.cmu.cs.hcii.cogtool.model.SimpleWidgetGroup;
import edu.cmu.cs.hcii.cogtool.model.Project;
import edu.cmu.cs.hcii.cogtool.model.WidgetAttributes;
import edu.cmu.cs.hcii.cogtool.ui.DesignEditorLID;
import edu.cmu.cs.hcii.cogtool.ui.FrameEditorLID;
import edu.cmu.cs.hcii.cogtool.util.AUndoableEdit;
import edu.cmu.cs.hcii.cogtool.util.CompoundUndoableEdit;
import edu.cmu.cs.hcii.cogtool.util.IUndoableEdit;
import edu.cmu.cs.hcii.cogtool.util.IUndoableEditSequence;
import edu.cmu.cs.hcii.cogtool.util.L10N;
import edu.cmu.cs.hcii.cogtool.util.NamedObjectUtil;
import edu.cmu.cs.hcii.cogtool.util.RcvrClipboardException;
import edu.cmu.cs.hcii.cogtool.util.RcvrOutOfMemoryException;
import edu.cmu.cs.hcii.cogtool.util.UndoManager;
public class DesignEditorCmd
{
public static final String PASTE = L10N.get("UNDO.Paste", "Paste");
private static final String NEW_WIDGET =
L10N.get("UNDO.DE.NewWidget", "New Widget");
public static final String NEW_FRAME =
L10N.get("UNDO.DE.NewFrame", "New Frame");
public static final String USE_TEMPLATE =
L10N.get("UNDO.DE.UseTemplate", "Populate New Frame");
private static final String CHANGE_TARGET_FRAME =
L10N.get("UNDO.DE.ChangeTarget", "Change Target Frame");
public static final String NEW_TRANSITION =
L10N.get("UNDO.DE.NewTransition", "New Transition");
private DesignEditorCmd() { } // prevent instantiation
public static final boolean SAVE_TO_CLIPBOARD =
CogToolClipboard.SAVE_TO_CLIPBOARD;
public static final boolean SAVE_TO_TEMPLATE =
CogToolClipboard.SAVE_STRING_ONLY;
public static void copyElements(Design design,
FrameElement[] selectedElts,
Iterator<FrameElement> eltsToCopy,
boolean saveToClipboard)
{
try {
// Set up a clipboard saver. Indicate that no transitions
// should be copied.
CogToolClipboard.ClipboardClassSaver s =
CogToolClipboard.startClipboardSave(CogToolClipboard.CopyWidgets,
selectedElts,
saveToClipboard);
// Iterate through the widgets and save the selected items.
while (eltsToCopy.hasNext()) {
FrameElement elt = eltsToCopy.next();
// TODO: Fix this when we can limit where menu/pull-down items
// get pasted.
if (! (elt instanceof ChildWidget)) {
s.saveObject(elt);
}
}
s.finish();
if (! saveToClipboard) {
FrameTemplateSupport.setFrameTemplate(design,
s.getSavedString());
}
}
catch (IOException e) {
throw new RcvrClipboardException(e);
}
catch (OutOfMemoryError error) {
throw new RcvrOutOfMemoryException("Copying Widgets", error);
}
}
private static void makeWidgetNameUnique(IWidget widget, Frame frame)
{
widget.setName(NamedObjectUtil.makeNameUnique(widget.getName(),
frame.getWidgets()));
}
private static void makeEltGroupNameUnique(FrameElementGroup eltGroup,
Frame frame)
{
eltGroup.setName(NamedObjectUtil.makeNameUnique(eltGroup.getName(),
frame.getEltGroups()));
}
private static void addChildWidgets(SimpleWidgetGroup widgetGroup, Frame f)
{
if (widgetGroup != null) {
Iterator<IWidget> children = widgetGroup.iterator();
while (children.hasNext()) {
IWidget child = children.next();
makeWidgetNameUnique(child, f);
f.addWidget(child);
if (child instanceof MenuItem) {
MenuItem item = (MenuItem) child;
if (item.isSubmenu()) {
addChildWidgets(item.getChildren(), f);
}
}
}
}
}
private static DoublePoint getFirstChildPosition(AParentWidget parent)
{
AShape parentShape = parent.getShape();
DoublePoint pos = parentShape.getOrigin();
DoubleSize extent = parentShape.getSize();
switch (parent.getChildrenLocation()) {
case AParentWidget.CHILDREN_BELOW: {
pos.y += extent.height;
break;
}
case AParentWidget.CHILDREN_RIGHT: {
pos.x += extent.width;
break;
}
case AParentWidget.CHILDREN_CENTER: {
pos.x += extent.width / 2.0;
pos.y += extent.height / 2.0;
break;
}
}
return pos;
}
public static void repositionChildren(AParentWidget parent)
{
if (parent.hasChildren()) {
DoublePoint startPos = getFirstChildPosition(parent);
repositionChildren(parent.getChildren(), startPos.x, startPos.y);
}
}
/**
* TODO: If we ever allow children above or left of a parent,
* we need to pass in childrenLocation here in addition to the group.
*/
public static void repositionChildren(SimpleWidgetGroup group,
double x,
double y)
{
int orientation = group.getOrientation();
if (orientation == SimpleWidgetGroup.FREEFORM) {
return;
}
Iterator<IWidget> groupIter = group.iterator();
while (groupIter.hasNext()) {
IWidget widget = groupIter.next();
widget.setWidgetOrigin(x, y);
if (orientation == SimpleWidgetGroup.HORIZONTAL) {
x += widget.getEltBounds().width;
}
else if (orientation == SimpleWidgetGroup.VERTICAL) {
y += widget.getEltBounds().height;
}
if (widget instanceof AParentWidget) {
repositionChildren((AParentWidget) widget);
}
}
}
public static void repositionChildren(SimpleWidgetGroup group)
{
if (group.size() > 0) {
DoublePoint startPos = group.get(0).getShape().getOrigin();
repositionChildren(group, startPos.x, startPos.y);
}
}
private abstract static class AddWidgetUndoableEdit
extends DemoStateManager.InvalidatingEdit
{
protected DemoStateManager demoStateMgr;
protected Frame frame;
protected IWidget widget;
public AddWidgetUndoableEdit(Frame f, IWidget w, DemoStateManager mgr)
{
super(FrameEditorLID.NewWidget, mgr);
frame = f;
widget = w;
demoStateMgr = mgr;
}
@Override
public String getPresentationName()
{
return NEW_WIDGET;
}
protected abstract void redoHelper();
protected abstract void undoHelper();
@Override
public void redo()
{
super.redo();
redoHelper();
frame.addWidget(widget);
demoStateMgr.noteWidgetEdit(widget, this);
}
@Override
public void undo()
{
super.undo();
undoHelper();
frame.removeWidget(widget);
demoStateMgr.noteWidgetEdit(widget, this);
}
}
public static IDesignUndoableEdit addWidgetUndoableEdit(Frame frame,
IWidget widget,
DemoStateManager mgr)
{
if (widget instanceof ChildWidget) {
ChildWidget childWidget = (ChildWidget) widget;
final AParentWidget itemParent = childWidget.getParent();
final int atIndex = itemParent.indexOf(childWidget);
return new AddWidgetUndoableEdit(frame, widget, mgr) {
@Override
protected void redoHelper()
{
itemParent.addItem(atIndex, (ChildWidget) widget);
}
@Override
protected void undoHelper()
{
itemParent.removeItem((ChildWidget) widget);
}
};
}
final SimpleWidgetGroup parentGroup = widget.getParentGroup();
final int atIndex =
(parentGroup != null) ? parentGroup.indexOf(widget) : -1;
return new AddWidgetUndoableEdit(frame, widget, mgr)
{
@Override
protected void redoHelper()
{
if (parentGroup != null) {
parentGroup.add(atIndex, widget);
// TODO:mlh reposition items/headers following!
}
}
@Override
protected void undoHelper()
{
if (parentGroup != null) {
parentGroup.remove(widget);
// TODO:mlh reposition items/headers following!
}
}
};
}
private static void addChildWidgets(Frame frame,
SimpleWidgetGroup widgetGroup,
DemoStateManager mgr,
IUndoableEditSequence editSeq)
{
if (widgetGroup != null) {
Iterator<IWidget> children = widgetGroup.iterator();
while (children.hasNext()) {
IWidget child = children.next();
makeWidgetNameUnique(child, frame);
frame.addWidget(child);
if (editSeq != null) {
editSeq.addEdit(addWidgetUndoableEdit(frame,
child,
mgr));
}
if (child instanceof MenuItem) {
MenuItem item = (MenuItem) child;
if (item.isSubmenu()) {
addChildWidgets(frame,
item.getChildren(),
mgr,
editSeq);
}
}
}
}
}
private static void checkForRemoteLabel(FrameElement elt,
Set<IWidget> addedRemoteLabels)
{
FrameElement owner = elt.getRemoteLabelOwner();
if (owner != null) {
IWidget remoteLabel =
(IWidget) owner.getAttribute(WidgetAttributes.REMOTE_LABEL_ATTR);
if (remoteLabel != null) {
addedRemoteLabels.add(remoteLabel);
}
}
}
private static int pasteWidget(IWidget widget,
Design design,
int currentDeviceTypes,
Frame frame,
DemoStateManager mgr,
IUndoableEditSequence editSequence,
Set<FrameElementGroup> groups,
Set<IWidget> addedRemoteLabels)
{
if (frame.getWidgets().contains(widget)) {
return 0;
}
int requiresOneOf = widget.getWidgetType().requiresOneOf();
if (! DeviceType.intersects(requiresOneOf, currentDeviceTypes)) {
// Missing either Mouse or Touchscreen
if (DeviceType.Touchscreen.isMember(requiresOneOf)) {
DesignCmd.addDevice(design,
DeviceType.Touchscreen);
}
else if (DeviceType.Mouse.isMember(requiresOneOf)) {
DesignCmd.addDevice(design,
DeviceType.Mouse);
}
}
makeWidgetNameUnique(widget, frame);
frame.addWidget(widget);
IDesignUndoableEdit edit = addWidgetUndoableEdit(frame, widget, mgr);
mgr.noteWidgetEdit(widget, edit);
editSequence.addEdit(edit);
if (widget instanceof AParentWidget) {
AParentWidget parent = (AParentWidget) widget;
addChildWidgets(frame, parent.getChildren(), mgr, editSequence);
}
groups.addAll(widget.getEltGroups());
checkForRemoteLabel(widget, addedRemoteLabels);
return 1;
}
private static int pasteWidgetGroup(SimpleWidgetGroup group,
Design design,
int currentDeviceTypes,
Frame frame,
DemoStateManager mgr,
IUndoableEditSequence editSequence,
Set<FrameElementGroup> groups,
Set<IWidget> addedRemoteLabels)
{
int numPasted = 0;
Iterator<IWidget> groupWidgets = group.iterator();
while (groupWidgets.hasNext()) {
numPasted += pasteWidget(groupWidgets.next(),
design,
currentDeviceTypes,
frame,
mgr,
editSequence,
groups,
addedRemoteLabels);
}
groups.addAll(group.getEltGroups());
checkForRemoteLabel(group, addedRemoteLabels);
return numPasted;
}
private static int pasteFrameElementGroup(FrameElementGroup eltGroup,
Design design,
int currentDeviceTypes,
Frame frame,
DemoStateManager mgr,
IUndoableEditSequence editSeq,
Set<FrameElementGroup> groups,
Set<IWidget> addedRemoteLabels)
{
int numPasted = 0;
makeEltGroupNameUnique(eltGroup, frame);
groups.add(eltGroup);
groups.addAll(eltGroup.getEltGroups());
checkForRemoteLabel(eltGroup, addedRemoteLabels);
Iterator<FrameElement> elementsToAdd = eltGroup.iterator();
while (elementsToAdd.hasNext()) {
FrameElement eltToAdd = elementsToAdd.next();
if (eltToAdd instanceof IWidget) {
numPasted += pasteWidget((IWidget) eltToAdd,
design,
currentDeviceTypes,
frame,
mgr,
editSeq,
groups,
addedRemoteLabels);
}
else if (eltToAdd instanceof SimpleWidgetGroup) {
numPasted += pasteWidgetGroup((SimpleWidgetGroup) eltToAdd,
design,
currentDeviceTypes,
frame,
mgr,
editSeq,
groups,
addedRemoteLabels);
}
else if (eltToAdd instanceof FrameElementGroup) {
numPasted +=
pasteFrameElementGroup((FrameElementGroup) eltToAdd,
design,
currentDeviceTypes,
frame,
mgr,
editSeq,
groups,
addedRemoteLabels);
}
}
return numPasted;
} // pasteFrameElementGroup
public static int pasteElements(Design design,
final Frame frame,
Collection<Object> objects,
DemoStateManager mgr,
IUndoableEditSequence editSequence)
{
// If given objects contain widgets, insert into the given frame
if ((objects != null) && (objects.size() > 0)) {
Iterator<Object> objIt = objects.iterator();
Set<SimpleWidgetGroup> addedGroups = new HashSet<SimpleWidgetGroup>();
final Set<IWidget> addedRemoteLabels = new HashSet<IWidget>();
final Set<FrameElementGroup> addedEltGroups =
new HashSet<FrameElementGroup>();
int numPasted = 0;
// May need to add a device
int currentDeviceTypes =
DeviceType.buildDeviceSet(design.getDeviceTypes());
// Loop through all objects and, if widgets,
// create them.
while (objIt.hasNext()) {
Object o = objIt.next();
if (o instanceof IWidget) {
IWidget widget = (IWidget) o;
numPasted += pasteWidget(widget,
design,
currentDeviceTypes,
frame,
mgr,
editSequence,
addedEltGroups,
addedRemoteLabels);
SimpleWidgetGroup group = widget.getParentGroup();
if (group != null) {
addedGroups.add(group);
}
}
else if (o instanceof FrameElementGroup) {
numPasted += pasteFrameElementGroup((FrameElementGroup) o,
design,
currentDeviceTypes,
frame,
mgr,
editSequence,
addedEltGroups,
addedRemoteLabels);
}
}
Iterator<SimpleWidgetGroup> groupsIter = addedGroups.iterator();
while (groupsIter.hasNext()) {
SimpleWidgetGroup group = groupsIter.next();
repositionChildren(group);
if (group instanceof GridButtonGroup) {
((GridButtonGroup) group).recalculateOffsets();
}
addedEltGroups.addAll(group.getEltGroups());
}
Iterator<FrameElementGroup> eltGroups = addedEltGroups.iterator();
while (eltGroups.hasNext()) {
frame.addEltGroup(eltGroups.next());
}
Iterator<IWidget> remoteLabels = addedRemoteLabels.iterator();
while (remoteLabels.hasNext()) {
IWidget remoteLabel = remoteLabels.next();
if (! frame.containsWidget(remoteLabel)) {
String uniqueName =
NamedObjectUtil.makeNameUnique(remoteLabel.getName(),
frame.getWidgets());
remoteLabel.setName(uniqueName);
frame.addWidget(remoteLabel);
}
}
IUndoableEdit edit =
new AUndoableEdit(CogToolLID.Paste)
{
@Override
public String getPresentationName()
{
return PASTE;
}
@Override
public void redo()
{
super.redo();
Iterator<FrameElementGroup> eltGroups =
addedEltGroups.iterator();
while (eltGroups.hasNext()) {
frame.addEltGroup(eltGroups.next());
}
Iterator<IWidget> remoteLabels =
addedRemoteLabels.iterator();
while (remoteLabels.hasNext()) {
IWidget remoteLabel = remoteLabels.next();
if (! frame.containsWidget(remoteLabel)) {
frame.addWidget(remoteLabel);
}
}
}
@Override
public void undo()
{
super.undo();
Iterator<FrameElementGroup> eltGroups =
addedEltGroups.iterator();
while (eltGroups.hasNext()) {
frame.removeEltGroup(eltGroups.next());
}
Iterator<IWidget> remoteLabels =
addedRemoteLabels.iterator();
while (remoteLabels.hasNext()) {
IWidget remoteLabel = remoteLabels.next();
if (frame.containsWidget(remoteLabel)) {
frame.removeWidget(remoteLabel);
}
}
}
};
editSequence.addEdit(edit);
return numPasted;
}
return 0;
} // pasteElements
public static void addFrame(final Project project,
final Design design,
final DemoStateManager demoStateMgr,
final Frame frame,
IUndoableEditSequence editSequence)
{
design.addFrame(frame);
Collection<Object> objects =
FrameTemplateSupport.getFrameTemplate(design);
if ((objects != null) && (objects.size() > 0)) {
CompoundUndoableEdit tplEdit =
new CompoundUndoableEdit(USE_TEMPLATE, null);
pasteElements(design, frame, objects, demoStateMgr, tplEdit);
UndoManager undoMgr =
UndoManager.getUndoManager(frame, project);
tplEdit.end();
undoMgr.addEdit(tplEdit);
}
IUndoableEdit edit =
new DemoStateManager.InvalidatingEdit(DesignEditorLID.NewFrame,
demoStateMgr)
{
private boolean recoverMgr = false;
@Override
public String getPresentationName()
{
return NEW_FRAME;
}
@Override
public void redo()
{
super.redo();
recoverMgr = false;
design.addFrame(frame);
demoStateMgr.noteFrameEdit(frame, this);
}
@Override
public void undo()
{
super.undo();
recoverMgr = true;
design.removeFrame(frame);
demoStateMgr.noteFrameEdit(frame, this);
}
@Override
public void die()
{
super.die();
if (recoverMgr) {
UndoManagerRecovery.recoverManagers(project, frame);
}
}
};
editSequence.addEdit(edit);
}
public static void addIncidentTransitions(Transition[] transitions)
{
// Maps Transition to the IWidget that is its source.
for (Transition transition : transitions) {
TransitionSource sourceWidget = transition.getSource();
sourceWidget.addTransition(transition);
}
}
public static void deleteFrame(final Project project,
final Design design,
final DemoStateManager demoStateMgr,
final Frame frame,
CogToolLID lid,
IUndoableEditSequence editSequence)
{
final Transition[] incidentTransitions =
frame.removeIncidentTransitions();
design.removeFrame(frame);
DemoStateManager.IDesignUndoableEdit edit =
new DemoStateManager.InvalidatingEdit(lid, demoStateMgr)
{
private boolean recoverMgr = true;
@Override
public void redo()
{
super.redo();
recoverMgr = true;
frame.removeIncidentTransitions();
design.removeFrame(frame);
demoStateMgr.noteFrameEdit(frame, this);
}
@Override
public void undo()
{
super.undo();
recoverMgr = false;
design.addFrame(frame);
addIncidentTransitions(incidentTransitions);
demoStateMgr.noteFrameEdit(frame, this);
}
@Override
public void die()
{
super.die();
if (recoverMgr) {
UndoManagerRecovery.recoverManagers(project, frame);
}
}
};
demoStateMgr.noteFrameEdit(frame, edit);
editSequence.addEdit(edit);
}
public static IUndoableEdit addTransition(final DemoStateManager demoStateMgr,
final Transition transition)
{
transition.getSource().addTransition(transition);
IDesignUndoableEdit edit =
new DemoStateManager.InvalidatingEdit(DesignEditorLID.NewTransition,
demoStateMgr)
{
@Override
public String getPresentationName()
{
return NEW_TRANSITION;
}
@Override
public void redo()
{
super.redo();
transition.getSource().addTransition(transition);
demoStateMgr.noteTransitionEdit(transition, this);
}
@Override
public void undo()
{
super.undo();
transition.getSource().removeTransition(transition);
demoStateMgr.noteTransitionEdit(transition, this);
}
};
demoStateMgr.noteTransitionEdit(transition, edit);
return edit;
}
public static void changeTransitionTarget(final DemoStateManager demoStateMgr,
final Transition transition,
final Frame newDestination,
IUndoableEditSequence editSeq)
{
final Frame oldDestination = transition.getDestination();
if (newDestination != oldDestination) {
transition.setDestination(newDestination);
DemoStateManager.IDesignUndoableEdit edit =
new DemoStateManager.InvalidatingEdit(DesignEditorLID.ChangeTarget,
demoStateMgr)
{
@Override
public String getPresentationName()
{
return CHANGE_TARGET_FRAME;
}
@Override
public void redo()
{
super.redo();
transition.setDestination(newDestination);
demoStateMgr.noteTransitionEdit(transition, this);
}
@Override
public void undo()
{
super.undo();
transition.setDestination(oldDestination);
demoStateMgr.noteTransitionEdit(transition, this);
}
};
demoStateMgr.noteTransitionEdit(transition, edit);
editSeq.addEdit(edit);
}
} // changeTransitionTarget
}
| lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsi/itemi191.java | 159 | package fr.toss.FF7itemsi;
public class itemi191 extends FF7itemsibase {
public itemi191(int id) {
super(id);
setUnlocalizedName("itemi191");
}
}
| lgpl-2.1 |
qt-users-jp/qimsys | src/plugins/converters/japanese/katakana/half/converter.cpp | 8312 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* qimsys *
* Copyright (C) 2009-2015 by Tasuku Suzuki <stasuku@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Lesser 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "converter.h"
#include <plugins/inputmethods/japanese/standard/global.h>
#include <qimsysdebug.h>
#include <qimsysinputmethodmanager.h>
#include <qimsyspreeditmanager.h>
#include <qimsysdynamictranslator.h>
#include <QFile>
#include <QTextStream>
#include <QTextCodec>
namespace Japanese {
namespace Katakana {
namespace Half {
class Converter::Private : private QObject
{
Q_OBJECT
public:
Private(Converter *parent);
~Private();
private slots:
void init();
void activeChanged(bool isActive);
void stateChanged(uint state);
void itemChanged(const QimsysPreeditItem &item);
private:
void readMap(const QString &fileName);
private:
Converter *q;
QimsysInputMethodManager *inputMethodManager;
QimsysPreeditManager *preeditManager;
QStringList previous;
QMap<QString, QString> convertMap;
};
}
}
}
using namespace Japanese::Katakana::Half;
Converter::Private::Private(Converter *parent)
: QObject(parent)
, q(parent)
, inputMethodManager(0)
, preeditManager(0)
{
qimsysDebugIn() << parent;
init();
qimsysDebugOut();
}
Converter::Private::~Private()
{
qimsysDebugIn();
qimsysDebugOut();
}
void Converter::Private::init()
{
qimsysDebugIn();
q->setIdentifier(QLatin1String("Halfwidth Katakana"));
q->setPriority(0x21);
q->setLocale("ja_JP");
q->setLanguage("Japanese(Standard)");
#ifndef QIMSYS_NO_GUI
q->setIcon(QIcon(":/japanese/katakana/half/resources/katakana-half.png"));
#endif
trConnect(this, QT_TR_NOOP("Katakana(Half)"), q, "name");
trConnect(this, QT_TR_NOOP("Tasuku Suzuki"), q, "author");
trConnect(this, QT_TR_NOOP(""), q, "translator");
trConnect(this, QT_TR_NOOP("Japanese converter for Katakana"), q, "description");
q->setGroups(QStringList() << QLatin1String("X11 Classic"));
q->setCategoryType(MoreThanOne);
trConnect(this, QT_TR_NOOP("Input/Converter"), q, "categoryName");
connect(q, SIGNAL(activeChanged(bool)), this, SLOT(activeChanged(bool)));
activeChanged(q->isActive());
qimsysDebugOut();
}
void Converter::Private::readMap(const QString &fileName)
{
qimsysDebugIn() << fileName;
QFile file(fileName);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
convertMap.clear();
QTextStream stream(&file);
stream.setCodec(QTextCodec::codecForName("UTF-8"));
while (!stream.atEnd()) {
QString line = stream.readLine();
if (line.contains('\t')) {
QStringList fields = line.split('\t');
if (fields.isEmpty() || fields.first().isEmpty() || fields.first().startsWith("#")) continue;
qimsysDebug() << fields.at(0) << fields.at(1);
convertMap[fields.at(0)] = fields.at(1);
}
}
file.close();
} else {
qimsysWarning() << file.error() << file.errorString() << fileName;
}
qimsysDebugOut();
}
void Converter::Private::activeChanged(bool isActive)
{
qimsysDebugIn() << isActive;
if (isActive) {
if (!inputMethodManager) {
inputMethodManager = new QimsysInputMethodManager(this);
inputMethodManager->init();
connect(inputMethodManager, SIGNAL(stateChanged(uint)), this, SLOT(stateChanged(uint)));
}
if (convertMap.isEmpty()) {
readMap(QLatin1String(":/japanese/katakana/half/resources/katakana-half.txt"));
}
stateChanged(inputMethodManager->state());
} else {
convertMap.clear();
stateChanged(Reset);
if (inputMethodManager) {
disconnect(inputMethodManager, SIGNAL(stateChanged(uint)), this, SLOT(stateChanged(uint)));
inputMethodManager->deleteLater();
inputMethodManager = 0;
}
}
qimsysDebugOut();
}
void Converter::Private::stateChanged(uint state)
{
qimsysDebugIn() << state;
switch (state) {
case Input:
if (!preeditManager) {
preeditManager = new QimsysPreeditManager(this);
preeditManager->init();
connect(preeditManager, SIGNAL(itemChanged(QimsysPreeditItem)), this, SLOT(itemChanged(QimsysPreeditItem)));
}
itemChanged(preeditManager->item());
break;
case ConvertTo: {
if (!preeditManager) {
preeditManager = new QimsysPreeditManager(this);
preeditManager->init();
connect(preeditManager, SIGNAL(itemChanged(QimsysPreeditItem)), this, SLOT(itemChanged(QimsysPreeditItem)));
}
QimsysPreeditItem item = preeditManager->item();
item.to.clear();
foreach (const QString &from, item.from) {
QString to;
foreach (const QChar &ch, from) {
if (convertMap.contains(ch)) {
to.append(convertMap[ch]);
} else {
to.append(ch);
}
}
item.to.append(to);
}
preeditManager->setItem(item);
fallthrough;
}
default:
if (preeditManager) {
disconnect(preeditManager, SIGNAL(itemChanged(QimsysPreeditItem)), this, SLOT(itemChanged(QimsysPreeditItem)));
preeditManager->deleteLater();
preeditManager = 0;
}
break;
}
qimsysDebugOut();
}
void Converter::Private::itemChanged(const QimsysPreeditItem &item)
{
if (item.selection != 0) return;
if (item.from == previous) return;
qimsysDebugIn() << item;
QStringList to = item.to;
int cursor = item.cursor;
int l = 0;
int i = 0;
for (i = 0; i < to.length(); i++) {
l += to.at(i).length();
if (l > cursor - 1) {
break;
}
}
qimsysDebug() << i;
int modified = item.modified;
int k = i;
for (int j = 0; j < modified; j++) {
QString str = item.from.at(k);
int index = str.length() - j - 1 - k + i;
str = str.mid(index, 1);
qimsysDebug() << str << index;
if (convertMap.contains(str)) {
to.replace(k, to[k].replace(index, 1, convertMap[str]));
cursor += convertMap[str].length() - str.length();
}
if (index == 0) k--;
}
QimsysPreeditItem newItem = item;
newItem.to = to;
newItem.cursor = cursor;
preeditManager->blockSignals(true);
preeditManager->setItem(newItem);
preeditManager->blockSignals(false);
previous = item.from;
qimsysDebugOut();
}
Converter::Converter(QObject *parent)
: QimsysConverter(parent)
{
qimsysDebugIn() << parent;
d = new Private(this);
qimsysDebugOut();
}
Converter::~Converter()
{
qimsysDebugIn();
delete d;
qimsysDebugOut();
}
#include "converter.moc"
| lgpl-2.1 |
RPCS3/discord-bot | CompatBot/Utils/FixedLengthBuffer.cs | 4087 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CompatBot.Utils
{
internal class FixedLengthBuffer<TKey, TValue>: IList<TValue>
where TKey: notnull
{
internal readonly object SyncObj = new();
public FixedLengthBuffer(Func<TValue, TKey> keyGenerator)
{
makeKey = keyGenerator;
}
public FixedLengthBuffer<TKey, TValue> CloneShallow()
{
var result = new FixedLengthBuffer<TKey, TValue>(makeKey);
foreach (var key in keyList)
result.keyList.Add(key);
foreach (var (key, value) in lookup)
result.lookup[key] = value;
return result;
}
public IEnumerator<TValue> GetEnumerator() => keyList.Select(k => lookup[k]).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void Add(TValue item)
{
var key = makeKey(item);
if (!lookup.ContainsKey(key))
keyList.Add(key);
lookup[key] = item;
}
public void AddOrReplace(TValue item) => Add(item);
public void Clear()
{
keyList.Clear();
lookup.Clear();
}
public void TrimOldItems(int count)
{
var keys = keyList.Take(count).ToList();
keyList.RemoveRange(0, keys.Count);
foreach (var k in keys)
lookup.Remove(k);
}
public void TrimExcess()
{
if (Count <= FixedLengthBuffer<TKey, TValue>.MaxLength)
return;
TrimOldItems(Count - FixedLengthBuffer<TKey, TValue>.MaxLength);
}
public List<TValue> GetOldItems(int count)
=> keyList.Take(Math.Min(Count, count)).Select(k => lookup[k]).ToList();
public List<TValue> GetExcess()
{
if (Count <= FixedLengthBuffer<TKey, TValue>.MaxLength)
return new List<TValue>(0);
return GetOldItems(Count - FixedLengthBuffer<TKey, TValue>.MaxLength);
}
public TValue? Evict(TKey key)
{
if (!lookup.TryGetValue(key, out var result))
return result;
lookup.Remove(key);
keyList.Remove(key);
return result;
}
public bool Remove(TValue item)
{
var key = makeKey(item);
if (!Contains(key))
return false;
Evict(key);
return true;
}
public void CopyTo(TValue[] array, int arrayIndex)
{
var available = array.Length-arrayIndex;
if (available < Count)
throw new ArgumentException($"Insufficient lenght of the destination array: available={available}, required={Count}");
for (var i = 0; i < Count; i++)
array[arrayIndex + i] = lookup[keyList[i]];
}
public bool Contains(TKey key) => lookup.ContainsKey(key);
public bool Contains(TValue item) => Contains(makeKey(item));
public int IndexOf(TValue item) => throw new NotSupportedException();
public void Insert(int index, TValue item) => throw new NotSupportedException();
public void RemoveAt(int index) => throw new NotSupportedException();
public TValue this[int index]
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public int Count => lookup.Count;
public bool IsReadOnly => false;
public bool NeedTrimming => Count > FixedLengthBuffer<TKey, TValue>.MaxLength + 20;
public TValue this[TKey index] => lookup[index];
private static int MaxLength => Config.ChannelMessageHistorySize;
private readonly Func<TValue, TKey> makeKey;
private readonly List<TKey> keyList = new();
private readonly Dictionary<TKey, TValue> lookup = new();
}
} | lgpl-2.1 |
xwiki/xwiki-platform | xwiki-platform-core/xwiki-platform-mail/xwiki-platform-mail-send/xwiki-platform-mail-send-default/src/main/java/org/xwiki/mail/internal/configuration/MainWikiSendMailConfigClassDocumentConfigurationSource.java | 2271 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.mail.internal.configuration;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.WikiReference;
import javax.inject.Named;
import javax.inject.Singleton;
/**
* Provides configuration from the {@code Mail.MailConfig} document in the main wiki.
* If the {@code Mail.SendMailConfigClass} xobject exists in the {@code Mail.MailConfig} document then always use
* configuration values from it and if it doesn't then use the passed default values (if a default value is passed).
*
* @version $Id$
* @since 11.8RC1
*/
@Component
@Named("mailsendmainwiki")
@Singleton
public class MainWikiSendMailConfigClassDocumentConfigurationSource
extends AbstractSendMailConfigClassDocumentConfigurationSource
{
@Override
protected String getCacheId()
{
// Note: we use a single cache id because this module is installed on the root namespace and thus there's
// only a single MainWikiSendMailConfigClassDocumentConfigurationSource component in the farm (and thus a single
// cache).
return "configuration.document.mail.send.mainwiki";
}
@Override
protected DocumentReference getDocumentReference()
{
return new DocumentReference(MAILCONFIG_REFERENCE, new WikiReference(this.wikiManager.getMainWikiId()));
}
}
| lgpl-2.1 |
andreasprlic/biojava | biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java | 18270 | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on 01-21-2010
*
* @author Richard Holland
* @author Scooter Willis
* @author Paolo Pavan
*
*/
package org.biojava.nbio.core.sequence.template;
import org.biojava.nbio.core.exceptions.CompoundNotFoundException;
import org.biojava.nbio.core.sequence.AccessionID;
import org.biojava.nbio.core.sequence.DataSource;
import org.biojava.nbio.core.sequence.Strand;
import org.biojava.nbio.core.sequence.TaxonomyID;
import org.biojava.nbio.core.sequence.features.*;
import org.biojava.nbio.core.sequence.loader.UniprotProxySequenceReader;
import org.biojava.nbio.core.sequence.location.SequenceLocation;
import org.biojava.nbio.core.sequence.location.SimpleLocation;
import org.biojava.nbio.core.sequence.location.template.Location;
import org.biojava.nbio.core.sequence.storage.ArrayListSequenceReader;
import org.biojava.nbio.core.util.Equals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
*
* The base class for DNA, RNA and Protein sequences.
* @param <C>
*/
public abstract class AbstractSequence<C extends Compound> implements Sequence<C> {
private final static Logger logger = LoggerFactory.getLogger(AbstractSequence.class);
private TaxonomyID taxonomy;
private AccessionID accession;
private SequenceReader<C> sequenceStorage = null;
private CompoundSet<C> compoundSet;
private AnnotationType annotationType = AnnotationType.UNKNOWN;
private String description;
private String originalHeader;
private Collection<Object> userCollection;
private Integer bioBegin = null;
private Integer bioEnd = null;
private AbstractSequence<?> parentSequence = null;
private String source = null;
private ArrayList<String> notesList = new ArrayList<String>();
private Double sequenceScore = null;
private FeaturesKeyWordInterface featuresKeyWord = null;
private DatabaseReferenceInterface databaseReferences = null;
private FeatureRetriever featureRetriever = null;
private ArrayList<FeatureInterface<AbstractSequence<C>, C>> features =
new ArrayList<FeatureInterface<AbstractSequence<C>, C>>();
private LinkedHashMap<String, ArrayList<FeatureInterface<AbstractSequence<C>, C>>> groupedFeatures =
new LinkedHashMap<String, ArrayList<FeatureInterface<AbstractSequence<C>, C>>>();
public AbstractSequence() {
}
/**
* Create a Sequence from a simple string where the values should be found in compoundSet
* @param seqString
* @param compoundSet
* @throws CompoundNotFoundException
*/
public AbstractSequence(String seqString, CompoundSet<C> compoundSet) throws CompoundNotFoundException {
setCompoundSet(compoundSet);
sequenceStorage = new ArrayListSequenceReader<C>();
sequenceStorage.setCompoundSet(this.getCompoundSet());
sequenceStorage.setContents(seqString);
}
/**
* A ProxySequenceReader allows abstraction of both the storage of the sequence data and the location
* of the sequence data. A variety of use cases are possible. A ProxySequenceReader that knows the offset and of the sequence in
* a large fasta file. A ProxySequenceReader that can pull Sequence data from UniProt, NCBI or a custom database.
* If the ProxySequenceReader implements various interfaces then the sequence will set those interfaces so that calls to
* various methods will be valid.
*
* @param proxyLoader
* @param compoundSet
*/
public AbstractSequence(SequenceReader<C> proxyLoader, CompoundSet<C> compoundSet) {
setCompoundSet(compoundSet);
setProxySequenceReader(proxyLoader);
}
/**
* Very important method that allows external mappings of sequence data and features. This method
* will gain additional interface inspection that allows external data sources with knowledge
* of features for a sequence to be supported.
*
* @param proxyLoader
*/
public void setProxySequenceReader(SequenceReader<C> proxyLoader) {
this.sequenceStorage = proxyLoader;
if (proxyLoader instanceof FeaturesKeyWordInterface) {
this.setFeaturesKeyWord((FeaturesKeyWordInterface) sequenceStorage);
}
if (proxyLoader instanceof DatabaseReferenceInterface) {
this.setDatabaseReferences((DatabaseReferenceInterface) sequenceStorage);
}
if (proxyLoader instanceof FeatureRetriever) {
this.setFeatureRetriever((FeatureRetriever) sequenceStorage);
HashMap<String, ArrayList<AbstractFeature>> ff = getFeatureRetriever().getFeatures();
for (String k: ff.keySet()){
for (AbstractFeature f: ff.get(k)){
this.addFeature(f);
}
}
// success of next statement guaranteed because source is a compulsory field
//DBReferenceInfo dbQualifier = (DBReferenceInfo)ff.get("source").get(0).getQualifiers().get("db_xref");
ArrayList<DBReferenceInfo> dbQualifiers = (ArrayList)ff.get("source").get(0).getQualifiers().get("db_xref");
DBReferenceInfo dbQualifier = dbQualifiers.get(0);
if (dbQualifier != null) this.setTaxonomy(new TaxonomyID(dbQualifier.getDatabase()+":"+dbQualifier.getId(), DataSource.UNKNOWN));
}
if(getAccession() == null && proxyLoader instanceof UniprotProxySequenceReader){ // we have lots of unsupported operations for this call so quick fix to allow this tow rork
this.setAccession(proxyLoader.getAccession());
}
}
public SequenceReader<C> getProxySequenceReader() {
return sequenceStorage;
}
/**
* @return the bioBegin
*/
public Integer getBioBegin() {
if (bioBegin == null) {
return 1;
} else {
return bioBegin;
}
}
/**
* @param bioBegin the bioBegin to set
*/
public void setBioBegin(Integer bioBegin) {
this.bioBegin = bioBegin;
}
/**
* @return the bioEnd
*/
public Integer getBioEnd() {
if (bioEnd == null) {
return this.getLength();
} else {
return bioEnd;
}
}
/**
* @param bioEnd the bioEnd to set
*/
public void setBioEnd(Integer bioEnd) {
this.bioEnd = bioEnd;
}
/**
* Provided for convince if the developer needs to associate data with a sequence
*
* @return
*/
public Collection<Object> getUserCollection() {
return userCollection;
}
/**
*
* @param userCollection
*/
public void setUserCollection(Collection<Object> userCollection) {
this.userCollection = userCollection;
}
/**
* @return the annotation
*/
public AnnotationType getAnnotationType() {
return annotationType;
}
/**
* @param annotationType the annotation to set
*/
public void setAnnotationType(AnnotationType annotationType) {
this.annotationType = annotationType;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the originalHeader
*/
public String getOriginalHeader() {
return originalHeader;
}
/**
* @param originalHeader the originalHeader to set
*/
public void setOriginalHeader(String originalHeader) {
this.originalHeader = originalHeader;
}
/**
* @return the parentSequence
*/
public AbstractSequence<?> getParentSequence() {
return parentSequence;
}
/**
* @param parentSequence the parentSequence to set
*/
public void setParentSequence(AbstractSequence<?> parentSequence) {
this.parentSequence = parentSequence;
}
/**
* Added support for the source of this sequence for GFF3 export
* If a sub sequence doesn't have source then check for parent source
* @return the source
*/
public String getSource() {
if (source != null) {
return source;
}
if (parentSequence != null) {
return parentSequence.getSource();
}
return null;
}
/**
* Added support for the source of this sequence for GFF3 export
* @param source the source to set
*/
public void setSource(String source) {
this.source = source;
}
/**
* Add notes about this sequence that will get exported for GFF3
* @param note
*/
public void addNote(String note) {
notesList.add(note);
}
public void removeNote(String note) {
notesList.remove(note);
}
/**
* @return the notesList
*/
public ArrayList<String> getNotesList() {
return notesList;
}
/**
* @param notesList the notesList to set
*/
public void setNotesList(ArrayList<String> notesList) {
this.notesList = notesList;
}
/**
* Provide place holder for a metric that indicate a score associated with the sequence
* @return the sequenceScore
*/
public Double getSequenceScore() {
return sequenceScore;
}
/**
* @param sequenceScore the sequenceScore to set
*/
public void setSequenceScore(Double sequenceScore) {
this.sequenceScore = sequenceScore;
}
/**
* Return features at a sequence position by type
* @param featureType
* @param bioSequencePosition
* @return
*/
public List<FeatureInterface<AbstractSequence<C>, C>> getFeatures(String featureType, int bioSequencePosition) {
ArrayList<FeatureInterface<AbstractSequence<C>, C>> featureHits =
new ArrayList<FeatureInterface<AbstractSequence<C>, C>>();
List<FeatureInterface<AbstractSequence<C>, C>> features = getFeaturesByType(featureType);
if (features != null) {
for (FeatureInterface<AbstractSequence<C>, C> feature : features) {
if (bioSequencePosition >= feature.getLocations().getStart().getPosition() && bioSequencePosition <= feature.getLocations().getEnd().getPosition()) {
featureHits.add(feature);
}
}
}
return featureHits;
}
/**
* Return features at a sequence position
* @param bioSequencePosition
* @return
*/
public List<FeatureInterface<AbstractSequence<C>, C>> getFeatures(int bioSequencePosition) {
ArrayList<FeatureInterface<AbstractSequence<C>, C>> featureHits =
new ArrayList<FeatureInterface<AbstractSequence<C>, C>>();
if (features != null) {
for (FeatureInterface<AbstractSequence<C>, C> feature : features) {
if (bioSequencePosition >= feature.getLocations().getStart().getPosition() && bioSequencePosition <= feature.getLocations().getEnd().getPosition()) {
featureHits.add(feature);
}
}
}
return featureHits;
}
/**
*
* @return
*/
public List<FeatureInterface<AbstractSequence<C>, C>> getFeatures() {
return features;
}
/**
* Method to help set the proper details for a feature as it relates to a sequence
* where the feature needs to have a location on the sequence
* @param bioStart
* @param bioEnd
* @param feature
*/
public void addFeature(int bioStart, int bioEnd, FeatureInterface<AbstractSequence<C>, C> feature) {
SequenceLocation<AbstractSequence<C>, C> sequenceLocation =
new SequenceLocation<AbstractSequence<C>, C>(bioStart, bioEnd, this);
feature.setLocation(sequenceLocation);
addFeature(feature);
}
/**
* Add a feature to this sequence. The feature will be added to the collection where the order is start position and if more than
* one feature at the same start position then longest is added first. This helps on doing feature layout for displaying features
* in SequenceFeaturePanel
* @param feature
*/
public void addFeature(FeatureInterface<AbstractSequence<C>, C> feature) {
features.add(feature);
ArrayList<FeatureInterface<AbstractSequence<C>, C>> featureList = groupedFeatures.get(feature.getType());
if (featureList == null) {
featureList = new ArrayList<FeatureInterface<AbstractSequence<C>, C>>();
groupedFeatures.put(feature.getType(), featureList);
}
featureList.add(feature);
Collections.sort(features, AbstractFeature.LOCATION_LENGTH);
Collections.sort(featureList, AbstractFeature.LOCATION_LENGTH);
}
/**
* Remove a feature from the sequence
* @param feature
*/
public void removeFeature(FeatureInterface<AbstractSequence<C>, C> feature) {
features.remove(feature);
ArrayList<FeatureInterface<AbstractSequence<C>, C>> featureList = groupedFeatures.get(feature.getType());
if (featureList != null) {
featureList.remove(feature);
if (featureList.isEmpty()) {
groupedFeatures.remove(feature.getType());
}
}
}
/**
*
* @param type
* @return
*/
public List<FeatureInterface<AbstractSequence<C>, C>> getFeaturesByType(String type) {
List<FeatureInterface<AbstractSequence<C>, C>> features = groupedFeatures.get(type);
if (features == null) {
features = new ArrayList<FeatureInterface<AbstractSequence<C>, C>>();
}
return features;
}
/**
* @return the featuresKeyWord
*/
public FeaturesKeyWordInterface getFeaturesKeyWord() {
return featuresKeyWord;
}
/**
* @param featuresKeyWord the featuresKeyWord to set
*/
public void setFeaturesKeyWord(FeaturesKeyWordInterface featuresKeyWord) {
this.featuresKeyWord = featuresKeyWord;
}
/**
* @return the databaseReferences
*/
public DatabaseReferenceInterface getDatabaseReferences() {
return databaseReferences;
}
/**
* @param databaseReferences the databaseReferences to set
*/
public void setDatabaseReferences(DatabaseReferenceInterface databaseReferences) {
this.databaseReferences = databaseReferences;
}
public FeatureRetriever getFeatureRetriever() {
return featureRetriever;
}
public void setFeatureRetriever(FeatureRetriever featureRetriever) {
this.featureRetriever = featureRetriever;
}
public enum AnnotationType {
CURATED, PREDICTED, UNKNOWN;
}
/**
* @return the accession
*/
@Override
public AccessionID getAccession() {
return accession;
}
/**
* @param accession the accession to set
*/
public void setAccession(AccessionID accession) {
this.accession = accession;
}
/**
* @return the species
*/
public TaxonomyID getTaxonomy() {
return taxonomy;
}
/**
* @param taxonomy the species to set
*/
public void setTaxonomy(TaxonomyID taxonomy) {
this.taxonomy = taxonomy;
}
@Override
public CompoundSet<C> getCompoundSet() {
if (compoundSet != null) {
return compoundSet;
}
// This is invalid since the parentSequence isn't guaranteed to have the same compound set as this sequence,
// e.g., the case where the parent sequence for a protein is a CDS.
/*
if (parentSequence != null) {
return parentSequence.getCompoundSet();
}
*/
return null;
}
public void setCompoundSet(CompoundSet<C> compoundSet) {
this.compoundSet = compoundSet;
}
@Override
public boolean equals(Object o){
if(! Equals.classEqual(this, o)) {
return false;
}
Sequence<C> other = (Sequence<C>)o;
if ( other.getCompoundSet() != getCompoundSet())
return false;
List<C> rawCompounds = getAsList();
List<C> otherCompounds = other.getAsList();
if ( rawCompounds.size() != otherCompounds.size())
return false;
for (int i = 0 ; i < rawCompounds.size() ; i++){
Compound myCompound = rawCompounds.get(i);
Compound otherCompound = otherCompounds.get(i);
if ( ! myCompound.equalsIgnoreCase(otherCompound))
return false;
}
return true;
}
@Override
public int hashCode(){
String s = getSequenceAsString();
return s.hashCode();
}
@Override
public String toString() {
return getSequenceAsString();
}
private SequenceReader<C> getSequenceStorage() {
if (sequenceStorage != null) {
return sequenceStorage;
}
if (parentSequence != null) {
//return parentSequence.getSequenceStorage();
if ( this.compoundSet.equals(parentSequence.getCompoundSet())){
sequenceStorage = new ArrayListSequenceReader<C>();
sequenceStorage.setCompoundSet(this.getCompoundSet());
try {
sequenceStorage.setContents(parentSequence.getSequenceAsString());
} catch (CompoundNotFoundException e) {
// TODO is there a better way to handle this exception?
logger.error("Problem setting contents from parent sequence, some unrecognised compound: {}",e.getMessage());
}
return sequenceStorage;
}
}
return null;
}
/**
*
* @param bioStart
* @param bioEnd
* @param strand
* @return
*/
public String getSequenceAsString(Integer bioStart, Integer bioEnd, Strand strand) {
Location loc = new SimpleLocation(bioStart, bioEnd, strand);
return loc.getSubSequence(this).getSequenceAsString();
}
/**
* Default case is to assume strand is positive because only CDSSequence can be either positive or negative Strand.
* @return
*/
@Override
public String getSequenceAsString() {
return SequenceMixin.toString(this);
}
/**
*
* @return
*/
@Override
public List<C> getAsList() {
return sequenceStorage.getAsList();
}
/**
*
* @param position The 1-indexed position of the amino acid
* @return
*/
@Override
public C getCompoundAt(int position) {
return getSequenceStorage().getCompoundAt(position);
}
/**
*
* @param compound
* @return The first index of compound in this sequence (1-based)
*/
@Override
public int getIndexOf(C compound) {
return getSequenceStorage().getIndexOf(compound);
}
/**
*
* @param compound
* @return The last index of compound in this sequence (1-based)
*/
@Override
public int getLastIndexOf(C compound) {
return getSequenceStorage().getLastIndexOf(compound);
}
/**
*
* @return
*/
@Override
public int getLength() {
return getSequenceStorage().getLength();
}
/**
*
* @param bioStart
* @param bioEnd
* @return
*/
@Override
public SequenceView<C> getSubSequence(final Integer bioStart, final Integer bioEnd) {
return new SequenceProxyView<C>(this, bioStart, bioEnd);
}
/**
*
* @return
*/
@Override
public Iterator<C> iterator() {
return getSequenceStorage().iterator();
}
/**
*
* @param compounds
* @return
*/
@Override
public int countCompounds(C... compounds) {
return SequenceMixin.countCompounds(this, compounds);
}
/**
*
* @return
*/
@Override
public SequenceView<C> getInverse() {
return SequenceMixin.inverse(this);
}
}
| lgpl-2.1 |
XavierSolerFR/diem25tiki | lib/core/Tiki/Profile/InstallHandler/TrackerOption.php | 1597 | <?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: TrackerOption.php 57949 2016-03-17 19:30:36Z jyhem $
class Tiki_Profile_InstallHandler_TrackerOption extends Tiki_Profile_InstallHandler
{
private function getData() // {{{
{
if ( $this->data )
return $this->data;
$data = $this->obj->getData();
$data = Tiki_Profile::convertYesNo($data);
return $this->data = $data;
} // }}}
private function getOptionMap() // {{{
{
return Tiki_Profile_InstallHandler_Tracker::getOptionMap();
} // }}}
private function getOptionConverters() // {{{
{
return Tiki_Profile_InstallHandler_Tracker::getOptionConverters();
} // }}}
function canInstall() // {{{
{
$data = $this->getData();
// Check for mandatory fields
if (! isset($data['tracker'], $data['name'], $data['value'])) {
return false;
}
return true;
} // }}}
function _install() // {{{
{
$input = $this->getData();
$this->replaceReferences($input);
$name = $input['name'];
$value = $input['value'];
$conversions = $this->getOptionConverters();
if (isset($conversions[$name])) {
$value = $conversions[$name]->convert($value);
}
$optionMap = $this->getOptionMap();
if (isset($optionMap[$name])) {
$name = $optionMap[$name];
}
$trklib = TikiLib::lib('trk');
$trklib->replace_tracker_option($input['tracker'], $name, $value);
return true;
} // }}}
}
| lgpl-2.1 |
artemeon/core | module_flow/system/FlowModelTrait.php | 1793 | <?php
/*"******************************************************************************************************
* (c) 2004-2006 by MulchProductions, www.mulchprod.de *
* (c) 2007-2016 by Kajona, www.kajona.de *
* Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt *
********************************************************************************************************/
namespace Kajona\Flow\System;
use Kajona\System\System\Carrier;
use Kajona\System\System\Rights;
use Kajona\System\System\UserGroup;
/**
* @author christoph.kappestein@artemeon.de
* @module flow
*/
trait FlowModelTrait
{
/**
* @return bool
*/
public function rightStatus()
{
return $this->rightEdit();
}
protected function buildPermissionRow($arrGroups) : string
{
return implode(",", $this->convertPermissionToShortIds($this->getPermissionGroupIds($arrGroups)));
}
protected function getPermissionGroupIds($arrGroups) : array
{
if (empty($arrGroups)) {
return [];
}
$arrResult = [];
foreach ($arrGroups as $objObject) {
if ($objObject instanceof UserGroup) {
$arrResult[] = $objObject->getSystemid();
} elseif (is_string($objObject) && validateSystemid($objObject)) {
$arrResult[] = $objObject;
}
}
return $arrResult;
}
protected function convertPermissionToShortIds(array $arrGroups) : array
{
return array_map(function($strSystemId) {
return UserGroup::getShortIdForGroupId($strSystemId);
}, $arrGroups);
}
}
| lgpl-2.1 |
geotools/geotools | modules/extension/grid/src/test/java/org/geotools/grid/oval/OvalTest.java | 4029 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2019, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.grid.oval;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.geotools.grid.PolygonElement;
import org.geotools.grid.TestBase;
import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Polygon;
/** Unit tests for the Oval class. */
public class OvalTest extends TestBase {
private static final double MINX = -10;
private static final double MINY = -5;
private static final double WIDTH = 2.0;
private static final double HEIGHT = 1.0;
@Test
public void createValid() {
PolygonElement oval = new OvalImpl(0, 0, WIDTH, HEIGHT, null);
assertNotNull(oval);
}
@Test(expected = IllegalArgumentException.class)
public void negativeWidth() {
new OvalImpl(0, 0, -1, HEIGHT, null);
}
@Test(expected = IllegalArgumentException.class)
public void zeroWidth() {
new OvalImpl(0, 0, 0, HEIGHT, null);
}
@Test(expected = IllegalArgumentException.class)
public void negativeHeight() {
new OvalImpl(0, 0, WIDTH, -1, null);
}
@Test(expected = IllegalArgumentException.class)
public void zeroHeight() {
new OvalImpl(0, 0, WIDTH, 0, null);
}
@Test
public void getArea() {
PolygonElement oval = new OvalImpl(MINX, MINY, WIDTH, HEIGHT, null);
double expected = WIDTH * HEIGHT;
assertEquals(expected, oval.getArea(), TOL);
}
@Test
public void getBounds() {
PolygonElement oval = new OvalImpl(MINX, MINY, WIDTH, HEIGHT, null);
assertEnvelope(new Envelope(-10, WIDTH - 10, -5, HEIGHT - 5), oval.getBounds());
}
@Test
public void getCenter() {
PolygonElement oval = new OvalImpl(MINX, MINY, WIDTH, HEIGHT, null);
Coordinate expected = new Coordinate(WIDTH / 2 + MINX, HEIGHT / 2 + MINY);
assertCoordinate(expected, oval.getCenter());
}
@Test
public void getVertices() {
PolygonElement oval = new OvalImpl(MINX, MINY, WIDTH, HEIGHT, null);
Coordinate[] expected = {
new Coordinate(MINX, MINY),
new Coordinate(MINX, MINY + HEIGHT),
new Coordinate(MINX + WIDTH, MINY + HEIGHT),
new Coordinate(MINX + WIDTH, MINY),
};
Coordinate[] actual = oval.getVertices();
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertCoordinate(expected[i], actual[i]);
}
}
@Test
public void toGeometry() {
PolygonElement oval = new OvalImpl(MINX, MINY, WIDTH, HEIGHT, null);
Geometry polygon = oval.toGeometry();
assertNotNull(polygon);
assertTrue(polygon instanceof Polygon);
}
@Test
public void toDenseGeometry() {
PolygonElement oval = new OvalImpl(0, 0, WIDTH, HEIGHT, null);
final int density = 10;
final double maxSpacing = Math.min(WIDTH, HEIGHT) / density;
Geometry polygon = oval.toDenseGeometry(maxSpacing);
assertNotNull(polygon);
assertTrue(polygon instanceof Polygon);
assertTrue(polygon.getCoordinates().length - 1 >= 2 * (WIDTH + HEIGHT) * density);
}
}
| lgpl-2.1 |
cuugi/yapat | libuni/inc/box.hh | 1657 | /*
* ============================================================================
* GNU Lesser General Public License
* ============================================================================
*
* yapat - global illumination rendering engine
* copyright (c) 2005-2009 cuugi(a)iki.fi
*
* 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.
*
*/
#ifndef _BOX_HH
#define _BOX_HH
#include <log.hh>
#include <vmvector.hh>
#include "object.hh"
namespace uni
{
/**
* A box.
*
* @author cuugi(a)iki.fi
*/
class box : public object
{
public: // Constructors
/**
* Constructor.
*/
box(const char* aName,
const vm::vector4<I> aCorner1,
const vm::vector4<I> aCorner2);
virtual ~box();
public: // from object
box getBoundingBox(I t = 0.0);
I trace(ray& aRay, bool aShadow = false, I t = 0.0);
void prepare();
private: // Attributes
vm::vector4<I> iCorner[2];
};
} // uni
#endif // _BOX_HH
| lgpl-2.1 |
kalj/dealii | tests/grid/grid_generator_cheese.cc | 1456 | // ---------------------------------------------------------------------
//
// Copyright (C) 2005 - 2015 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// Test output for GridGenerator::cheese()
#include "../tests.h"
#include <deal.II/base/tensor.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
void dim2(std::ostream &os)
{
const unsigned int d=2;
Triangulation<d> tr;
std::vector<unsigned int> holes(d);
holes[0] = 3;
holes[1] = 2;
GridGenerator::cheese(tr, holes);
GridOut gout;
gout.write_vtk(tr, os);
}
void dim3(std::ostream &os)
{
const unsigned int d=3;
Triangulation<d> tr;
std::vector<unsigned int> holes(d);
holes[0] = 3;
holes[1] = 2;
holes[2] = 4;
GridGenerator::cheese(tr, holes);
GridOut gout;
gout.write_vtk(tr, os);
}
int main()
{
initlog(true);
std::ostream &logfile = deallog.get_file_stream();
dim2(logfile);
dim3(logfile);
}
| lgpl-2.1 |
enricoros/k-qt-creator-inspector | src/libs/utils/submiteditorwidget.cpp | 16743 | /**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "submiteditorwidget.h"
#include "submitfieldwidget.h"
#include "ui_submiteditorwidget.h"
#include <QtCore/QDebug>
#include <QtCore/QPointer>
#include <QtCore/QTimer>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
#include <QtGui/QHBoxLayout>
#include <QtGui/QToolButton>
#include <QtGui/QSpacerItem>
enum { debug = 0 };
enum { defaultLineWidth = 72 };
namespace Utils {
// QActionPushButton: A push button tied to an action
// (similar to a QToolButton)
class QActionPushButton : public QPushButton
{
Q_OBJECT
public:
explicit QActionPushButton(QAction *a);
private slots:
void actionChanged();
};
QActionPushButton::QActionPushButton(QAction *a) :
QPushButton(a->icon(), a->text())
{
connect(a, SIGNAL(changed()), this, SLOT(actionChanged()));
connect(this, SIGNAL(clicked()), a, SLOT(trigger()));
setEnabled(a->isEnabled());
}
void QActionPushButton::actionChanged()
{
if (const QAction *a = qobject_cast<QAction*>(sender()))
setEnabled(a->isEnabled());
}
// Helpers to retrieve model data
static inline bool listModelChecked(const QAbstractItemModel *model, int row, int column = 0)
{
const QModelIndex checkableIndex = model->index(row, column, QModelIndex());
return model->data(checkableIndex, Qt::CheckStateRole).toInt() == Qt::Checked;
}
static inline QString listModelText(const QAbstractItemModel *model, int row, int column)
{
const QModelIndex index = model->index(row, column, QModelIndex());
return model->data(index, Qt::DisplayRole).toString();
}
// Find a check item in a model
static bool listModelContainsCheckedItem(const QAbstractItemModel *model)
{
const int count = model->rowCount();
for (int i = 0; i < count; i++)
if (listModelChecked(model, i, 0))
return true;
return false;
}
// Convenience to extract a list of selected indexes
QList<int> selectedRows(const QAbstractItemView *view)
{
const QModelIndexList indexList = view->selectionModel()->selectedRows(0);
if (indexList.empty())
return QList<int>();
QList<int> rc;
const QModelIndexList::const_iterator cend = indexList.constEnd();
for (QModelIndexList::const_iterator it = indexList.constBegin(); it != cend; ++it)
rc.push_back(it->row());
return rc;
}
// ----------- SubmitEditorWidgetPrivate
struct SubmitEditorWidgetPrivate
{
// A pair of position/action to extend context menus
typedef QPair<int, QPointer<QAction> > AdditionalContextMenuAction;
SubmitEditorWidgetPrivate();
Ui::SubmitEditorWidget m_ui;
bool m_filesSelected;
bool m_filesChecked;
int m_fileNameColumn;
int m_activatedRow;
QList<AdditionalContextMenuAction> descriptionEditContextMenuActions;
QVBoxLayout *m_fieldLayout;
QList<SubmitFieldWidget *> m_fieldWidgets;
int m_lineWidth;
};
SubmitEditorWidgetPrivate::SubmitEditorWidgetPrivate() :
m_filesSelected(false),
m_filesChecked(false),
m_fileNameColumn(1),
m_activatedRow(-1),
m_fieldLayout(0),
m_lineWidth(defaultLineWidth)
{
}
SubmitEditorWidget::SubmitEditorWidget(QWidget *parent) :
QWidget(parent),
m_d(new SubmitEditorWidgetPrivate)
{
m_d->m_ui.setupUi(this);
m_d->m_ui.description->setContextMenuPolicy(Qt::CustomContextMenu);
m_d->m_ui.description->setLineWrapMode(QTextEdit::NoWrap);
m_d->m_ui.description->setWordWrapMode(QTextOption::WordWrap);
connect(m_d->m_ui.description, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(editorCustomContextMenuRequested(QPoint)));
// File List
m_d->m_ui.fileView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_d->m_ui.fileView->setRootIsDecorated(false);
connect(m_d->m_ui.fileView, SIGNAL(doubleClicked(QModelIndex)),
this, SLOT(diffActivated(QModelIndex)));
setFocusPolicy(Qt::StrongFocus);
setFocusProxy(m_d->m_ui.description);
}
SubmitEditorWidget::~SubmitEditorWidget()
{
delete m_d;
}
void SubmitEditorWidget::registerActions(QAction *editorUndoAction, QAction *editorRedoAction,
QAction *submitAction, QAction *diffAction)
{
if (editorUndoAction) {
editorUndoAction->setEnabled(m_d->m_ui.description->document()->isUndoAvailable());
connect(m_d->m_ui.description, SIGNAL(undoAvailable(bool)), editorUndoAction, SLOT(setEnabled(bool)));
connect(editorUndoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(undo()));
}
if (editorRedoAction) {
editorRedoAction->setEnabled(m_d->m_ui.description->document()->isRedoAvailable());
connect(m_d->m_ui.description, SIGNAL(redoAvailable(bool)), editorRedoAction, SLOT(setEnabled(bool)));
connect(editorRedoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(redo()));
}
if (submitAction) {
if (debug) {
int count = 0;
if (const QAbstractItemModel *model = m_d->m_ui.fileView->model())
count = model->rowCount();
qDebug() << Q_FUNC_INFO << submitAction << count << "items" << m_d->m_filesChecked;
}
submitAction->setEnabled(m_d->m_filesChecked);
connect(this, SIGNAL(fileCheckStateChanged(bool)), submitAction, SLOT(setEnabled(bool)));
m_d->m_ui.buttonLayout->addWidget(new QActionPushButton(submitAction));
}
if (diffAction) {
if (debug)
qDebug() << diffAction << m_d->m_filesSelected;
diffAction->setEnabled(m_d->m_filesSelected);
connect(this, SIGNAL(fileSelectionChanged(bool)), diffAction, SLOT(setEnabled(bool)));
connect(diffAction, SIGNAL(triggered()), this, SLOT(triggerDiffSelected()));
m_d->m_ui.buttonLayout->addWidget(new QActionPushButton(diffAction));
}
}
void SubmitEditorWidget::unregisterActions(QAction *editorUndoAction, QAction *editorRedoAction,
QAction *submitAction, QAction *diffAction)
{
if (editorUndoAction) {
disconnect(m_d->m_ui.description, SIGNAL(undoAvailableChanged(bool)), editorUndoAction, SLOT(setEnabled(bool)));
disconnect(editorUndoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(undo()));
}
if (editorRedoAction) {
disconnect(m_d->m_ui.description, SIGNAL(redoAvailableChanged(bool)), editorRedoAction, SLOT(setEnabled(bool)));
disconnect(editorRedoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(redo()));
}
if (submitAction)
disconnect(this, SIGNAL(fileCheckStateChanged(bool)), submitAction, SLOT(setEnabled(bool)));
if (diffAction) {
disconnect(this, SIGNAL(fileSelectionChanged(bool)), diffAction, SLOT(setEnabled(bool)));
disconnect(diffAction, SIGNAL(triggered()), this, SLOT(triggerDiffSelected()));
}
}
// Make sure we have one terminating NL. Do not trim front as leading space might be
// required for some formattings.
static inline QString trimMessageText(QString t)
{
if (t.isEmpty())
return t;
// Trim back of string.
const int last = t.size() - 1;
int lastWordCharacter = last;
for ( ; lastWordCharacter >= 0 && t.at(lastWordCharacter).isSpace() ; lastWordCharacter--) ;
if (lastWordCharacter != last)
t.truncate(lastWordCharacter + 1);
t += QLatin1Char('\n');
return t;
}
// Extract the wrapped text from a text edit, which performs
// the wrapping only optically.
static QString wrappedText(const QTextEdit *e)
{
const QChar newLine = QLatin1Char('\n');
QString rc;
QTextCursor cursor(e->document());
cursor.movePosition(QTextCursor::Start);
while (!cursor.atEnd()) {
cursor.select(QTextCursor::LineUnderCursor);
rc += cursor.selectedText();
rc += newLine;
cursor.movePosition(QTextCursor::EndOfLine); // Mac needs it
cursor.movePosition(QTextCursor::Right);
}
return rc;
}
QString SubmitEditorWidget::descriptionText() const
{
QString rc = trimMessageText(lineWrap() ? wrappedText(m_d->m_ui.description) : m_d->m_ui.description->toPlainText());
// append field entries
foreach(const SubmitFieldWidget *fw, m_d->m_fieldWidgets)
rc += fw->fieldValues();
return rc;
}
void SubmitEditorWidget::setDescriptionText(const QString &text)
{
m_d->m_ui.description->setPlainText(text);
}
bool SubmitEditorWidget::lineWrap() const
{
return m_d->m_ui.description->lineWrapMode() != QTextEdit::NoWrap;
}
void SubmitEditorWidget::setLineWrap(bool v)
{
if (debug)
qDebug() << Q_FUNC_INFO << v;
if (v) {
m_d->m_ui.description->setLineWrapColumnOrWidth(m_d->m_lineWidth);
m_d->m_ui.description->setLineWrapMode(QTextEdit::FixedColumnWidth);
} else {
m_d->m_ui.description->setLineWrapMode(QTextEdit::NoWrap);
}
}
int SubmitEditorWidget::lineWrapWidth() const
{
return m_d->m_lineWidth;
}
void SubmitEditorWidget::setLineWrapWidth(int v)
{
if (debug)
qDebug() << Q_FUNC_INFO << v << lineWrap();
if (m_d->m_lineWidth == v)
return;
m_d->m_lineWidth = v;
if (lineWrap())
m_d->m_ui.description->setLineWrapColumnOrWidth(v);
}
int SubmitEditorWidget::fileNameColumn() const
{
return m_d->m_fileNameColumn;
}
void SubmitEditorWidget::setFileNameColumn(int c)
{
m_d->m_fileNameColumn = c;
}
QAbstractItemView::SelectionMode SubmitEditorWidget::fileListSelectionMode() const
{
return m_d->m_ui.fileView->selectionMode();
}
void SubmitEditorWidget::setFileListSelectionMode(QAbstractItemView::SelectionMode sm)
{
m_d->m_ui.fileView->setSelectionMode(sm);
}
void SubmitEditorWidget::setFileModel(QAbstractItemModel *model)
{
m_d->m_ui.fileView->clearSelection(); // trigger the change signals
m_d->m_ui.fileView->setModel(model);
if (model->rowCount()) {
const int columnCount = model->columnCount();
for (int c = 0; c < columnCount; c++)
m_d->m_ui.fileView->resizeColumnToContents(c);
}
connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(updateSubmitAction()));
connect(model, SIGNAL(modelReset()),
this, SLOT(updateSubmitAction()));
connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(updateSubmitAction()));
connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
this, SLOT(updateSubmitAction()));
connect(m_d->m_ui.fileView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(updateDiffAction()));
updateActions();
}
QAbstractItemModel *SubmitEditorWidget::fileModel() const
{
return m_d->m_ui.fileView->model();
}
QStringList SubmitEditorWidget::selectedFiles() const
{
const QList<int> selection = selectedRows(m_d->m_ui.fileView);
if (selection.empty())
return QStringList();
QStringList rc;
const QAbstractItemModel *model = m_d->m_ui.fileView->model();
const int count = selection.size();
for (int i = 0; i < count; i++)
rc.push_back(listModelText(model, selection.at(i), fileNameColumn()));
return rc;
}
QStringList SubmitEditorWidget::checkedFiles() const
{
QStringList rc;
const QAbstractItemModel *model = m_d->m_ui.fileView->model();
if (!model)
return rc;
const int count = model->rowCount();
for (int i = 0; i < count; i++)
if (listModelChecked(model, i, 0))
rc.push_back(listModelText(model, i, fileNameColumn()));
return rc;
}
QTextEdit *SubmitEditorWidget::descriptionEdit() const
{
return m_d->m_ui.description;
}
void SubmitEditorWidget::triggerDiffSelected()
{
const QStringList sel = selectedFiles();
if (!sel.empty())
emit diffSelected(sel);
}
void SubmitEditorWidget::diffActivatedDelayed()
{
const QStringList files = QStringList(listModelText(m_d->m_ui.fileView->model(), m_d->m_activatedRow, fileNameColumn()));
emit diffSelected(files);
}
void SubmitEditorWidget::diffActivated(const QModelIndex &index)
{
// We need to delay the signal, otherwise, the diff editor will not
// be in the foreground.
m_d->m_activatedRow = index.row();
QTimer::singleShot(0, this, SLOT(diffActivatedDelayed()));
}
void SubmitEditorWidget::updateActions()
{
updateSubmitAction();
updateDiffAction();
}
// Enable submit depending on having checked files
void SubmitEditorWidget::updateSubmitAction()
{
const bool newFilesCheckedState = hasCheckedFiles();
if (m_d->m_filesChecked != newFilesCheckedState) {
m_d->m_filesChecked = newFilesCheckedState;
emit fileCheckStateChanged(m_d->m_filesChecked);
}
}
// Enable diff depending on selected files
void SubmitEditorWidget::updateDiffAction()
{
const bool filesSelected = hasSelection();
if (m_d->m_filesSelected != filesSelected) {
m_d->m_filesSelected = filesSelected;
emit fileSelectionChanged(m_d->m_filesSelected);
}
}
bool SubmitEditorWidget::hasSelection() const
{
// Not present until model is set
if (const QItemSelectionModel *sm = m_d->m_ui.fileView->selectionModel())
return sm->hasSelection();
return false;
}
bool SubmitEditorWidget::hasCheckedFiles() const
{
if (const QAbstractItemModel *model = m_d->m_ui.fileView->model())
return listModelContainsCheckedItem(model);
return false;
}
void SubmitEditorWidget::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
m_d->m_ui.retranslateUi(this);
break;
default:
break;
}
}
void SubmitEditorWidget::insertTopWidget(QWidget *w)
{
m_d->m_ui.vboxLayout->insertWidget(0, w);
}
void SubmitEditorWidget::addSubmitFieldWidget(SubmitFieldWidget *f)
{
if (!m_d->m_fieldLayout) {
// VBox with horizontal, expanding spacer
m_d->m_fieldLayout = new QVBoxLayout;
QHBoxLayout *outerLayout = new QHBoxLayout;
outerLayout->addLayout(m_d->m_fieldLayout);
outerLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
QBoxLayout *descrLayout = qobject_cast<QBoxLayout*>(m_d->m_ui.descriptionBox->layout());
Q_ASSERT(descrLayout);
descrLayout->addLayout(outerLayout);
}
m_d->m_fieldLayout->addWidget(f);
m_d->m_fieldWidgets.push_back(f);
}
QList<SubmitFieldWidget *> SubmitEditorWidget::submitFieldWidgets() const
{
return m_d->m_fieldWidgets;
}
void SubmitEditorWidget::addDescriptionEditContextMenuAction(QAction *a)
{
m_d->descriptionEditContextMenuActions.push_back(SubmitEditorWidgetPrivate::AdditionalContextMenuAction(-1, a));
}
void SubmitEditorWidget::insertDescriptionEditContextMenuAction(int pos, QAction *a)
{
m_d->descriptionEditContextMenuActions.push_back(SubmitEditorWidgetPrivate::AdditionalContextMenuAction(pos, a));
}
void SubmitEditorWidget::editorCustomContextMenuRequested(const QPoint &pos)
{
QMenu *menu = m_d->m_ui.description->createStandardContextMenu();
// Extend
foreach (const SubmitEditorWidgetPrivate::AdditionalContextMenuAction &a, m_d->descriptionEditContextMenuActions) {
if (a.second) {
if (a.first >= 0) {
menu->insertAction(menu->actions().at(a.first), a.second);
} else {
menu->addAction(a.second);
}
}
}
menu->exec(m_d->m_ui.description->mapToGlobal(pos));
delete menu;
}
} // namespace Utils
#include "submiteditorwidget.moc"
| lgpl-2.1 |
execuc/LCInterlocking | ExportPanel.py | 4667 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ***************************************************************************
# * *
# * Copyright (c) 2016 execuc *
# * *
# * This file is part of LCInterlocking module. *
# * LCInterlocking module 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 module 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 *
# * *
# ***************************************************************************
from FreeCAD import Gui
import FreeCAD
import FreeCADGui
import os
import math
import Draft
from lasercut.helper import biggest_area_faces
__dir__ = os.path.dirname(__file__)
iconPath = os.path.join(__dir__, 'icons')
def get_freecad_object():
if len(FreeCADGui.Selection.getSelectionEx()) < 1:
raise ValueError("No selection")
obj_list = []
for selection in FreeCADGui.Selection.getSelectionEx():
obj_list.append(selection.Object)
return obj_list
def transform_shape(part_feature, new_part_feature, freecad_document):
new_part_feature.Shape = part_feature.Shape.removeSplitter()
freecad_document.recompute()
normal_face_prop = biggest_area_faces(part_feature.Shape)
normal_ref = normal_face_prop[0]
rotation_to_apply = FreeCAD.Rotation(normal_ref, FreeCAD.Vector(0, 0, 1))
current_rotation = new_part_feature.Placement.Rotation
new_rotation = rotation_to_apply.multiply(current_rotation)
new_part_feature.Placement.Rotation = new_rotation
freecad_document.recompute()
return True
class ExportCommand:
def __init__(self):
return
def GetResources(self):
return {'Pixmap': os.path.join(iconPath, 'export.xpm'), # the name of a svg file available in the resources
'MenuText': "Export",
'ToolTip': "Export"}
def IsActive(self):
return len(FreeCADGui.Selection.getSelection()) > 0
def Activated(self):
parts_list = get_freecad_object()
new_doc = FreeCAD.newDocument("export_shape")
self.export_list(parts_list, new_doc)
FreeCADGui.getDocument(new_doc.Name).ActiveView.fitAll()
return
def export_list(self, parts_list, freecad_document):
x_pos = 0.
y_pos = 0.
margin = 10.
max_line_y = 0
z_fix = 30
new_parts_list = []
per_line = int(math.sqrt(len(parts_list)))
for i in range(len(parts_list)):
part = parts_list[i]
new_part = freecad_document.addObject("Part::Feature", "test")
transform_shape(part, new_part, freecad_document)
bound_box = new_part.Shape.BoundBox
shift_vector = FreeCAD.Vector(-bound_box.XMin + x_pos, -bound_box.YMin + y_pos, z_fix - bound_box.ZMin)
x_pos += bound_box.XLength + margin
new_part.Placement.Base = new_part.Placement.Base.add(shift_vector)
bound_box = new_part.Shape.BoundBox
freecad_document.recompute()
if (bound_box.YLength + y_pos) > max_line_y:
max_line_y = bound_box.YLength + y_pos
if (i+1) % per_line == 0:
y_pos = max_line_y + margin
x_pos = 0
new_parts_list.append(new_part)
for tmppart in new_parts_list:
Draft.makeShape2DView(tmppart)
freecad_document.recompute()
return new_parts_list
Gui.addCommand('export_command', ExportCommand())
| lgpl-2.1 |
yinyunqiao/qtcreator | src/plugins/qmldesigner/designercore/instances/instancecontainer.cpp | 2750 | /**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "instancecontainer.h"
namespace QmlDesigner {
InstanceContainer::InstanceContainer()
: m_instanceId(-1), m_majorNumber(-1), m_minorNumber(-1)
{
}
InstanceContainer::InstanceContainer(qint32 instanceId, const QString &type, int majorNumber, int minorNumber, const QString &componentPath)
: m_instanceId(instanceId), m_type(type), m_majorNumber(majorNumber), m_minorNumber(minorNumber), m_componentPath(componentPath)
{
}
qint32 InstanceContainer::instanceId() const
{
return m_instanceId;
}
QString InstanceContainer::type() const
{
return m_type;
}
int InstanceContainer::majorNumber() const
{
return m_majorNumber;
}
int InstanceContainer::minorNumber() const
{
return m_minorNumber;
}
QString InstanceContainer::componentPath() const
{
return m_componentPath;
}
QDataStream &operator<<(QDataStream &out, const InstanceContainer &container)
{
out << container.instanceId();
out << container.type();
out << container.majorNumber();
out << container.minorNumber();
out << container.componentPath();
return out;
}
QDataStream &operator>>(QDataStream &in, InstanceContainer &container)
{
in >> container.m_instanceId;
in >> container.m_type;
in >> container.m_majorNumber;
in >> container.m_minorNumber;
in >> container.m_componentPath;
return in;
}
} // namespace QmlDesigner
| lgpl-2.1 |
picxenk/p5.js | src/image/p5.Image.js | 13464 | /**
* @module Image
* @submodule Image
* @requires core
* @requires constants
* @requires filters
*/
/**
* This module defines the p5.Image class and P5 methods for
* drawing images to the main display canvas.
*/
'use strict';
var p5 = require('../core/core');
var Filters = require('./filters');
/*
* Class methods
*/
/**
* Creates a new p5.Image. A p5.Image is a canvas backed representation of an
* image. p5 can display .gif, .jpg and .png images. Images may be displayed
* in 2D and 3D space. Before an image is used, it must be loaded with the
* loadImage() function. The p5.Image class contains fields for the width and
* height of the image, as well as an array called pixels[] that contains the
* values for every pixel in the image. The methods described below allow
* easy access to the image's pixels and alpha channel and simplify the
* process of compositing.
*
* Before using the pixels[] array, be sure to use the loadPixels() method on
* the image to make sure that the pixel data is properly loaded.
*
* @class p5.Image
* @constructor
* @param {Number} width
* @param {Number} height
* @param {Object} pInst An instance of a p5 sketch.
*/
p5.Image = function(width, height){
/**
* Image width.
* @property width
*/
this.width = width;
/**
* Image height.
* @property height
*/
this.height = height;
this.canvas = document.createElement('canvas');
this.canvas.width = this.width;
this.canvas.height = this.height;
this.drawingContext = this.canvas.getContext('2d');
this._pixelDensity = 1;
//used for webgl texturing only
this.isTexture = false;
/**
* Array containing the values for all the pixels in the display window.
* These values are numbers. This array is the size (include an appropriate
* factor for pixelDensity) of the display window x4,
* representing the R, G, B, A values in order for each pixel, moving from
* left to right across each row, then down each column. Retina and other
* high denisty displays may have more pixels[] (by a factor of
* pixelDensity^2).
* For example, if the image is 100x100 pixels, there will be 40,000. With
* pixelDensity = 2, there will be 160,000. The first four values
* (indices 0-3) in the array will be the R, G, B, A values of the pixel at
* (0, 0). The second four values (indices 4-7) will contain the R, G, B, A
* values of the pixel at (1, 0). More generally, to set values for a pixel
* at (x, y):
* <code><pre>var d = pixelDensity;
* for (var i = 0; i < d; i++) {
* for (var j = 0; j < d; j++) {
* // loop over
* idx = 4*((y * d + j) * width * d + (x * d + i));
* pixels[idx] = r;
* pixels[idx+1] = g;
* pixels[idx+2] = b;
* pixels[idx+3] = a;
* }
* }
* </pre></code>
* <br><br>
* Before accessing this array, the data must loaded with the loadPixels()
* function. After the array data has been modified, the updatePixels()
* function must be run to update the changes.
* @property pixels[]
* @example
* <div>
* <code>
* img = createImage(66, 66);
* img.loadPixels();
* for (i = 0; i < img.width; i++) {
* for (j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102));
* }
* }
* img.updatePixels();
* image(img, 17, 17);
* </code>
* </div>
* <div>
* <code>
* var pink = color(255, 102, 204);
* img = createImage(66, 66);
* img.loadPixels();
* for (var i = 0; i < 4*(width*height/2); i+=4) {
* img.pixels[i] = red(pink);
* img.pixels[i+1] = green(pink);
* img.pixels[i+2] = blue(pink);
* img.pixels[i+3] = alpha(pink);
* }
* img.updatePixels();
* image(img, 17, 17);
* </code>
* </div>
*/
this.pixels = [];
};
/**
* Helper fxn for sharing pixel methods
*
*/
p5.Image.prototype._setProperty = function (prop, value) {
this[prop] = value;
};
/**
* Loads the pixels data for this image into the [pixels] attribute.
*
* @method loadPixels
*/
p5.Image.prototype.loadPixels = function(){
p5.Renderer2D.prototype.loadPixels.call(this);
};
/**
* Updates the backing canvas for this image with the contents of
* the [pixels] array.
*
* @method updatePixels
* @param {Integer|undefined} x x-offset of the target update area for the
* underlying canvas
* @param {Integer|undefined} y y-offset of the target update area for the
* underlying canvas
* @param {Integer|undefined} w height of the target update area for the
* underlying canvas
* @param {Integer|undefined} h height of the target update area for the
* underlying canvas
*/
p5.Image.prototype.updatePixels = function(x, y, w, h){
p5.Renderer2D.prototype.updatePixels.call(this, x, y, w, h);
};
/**
* Get a region of pixels from an image.
*
* If no params are passed, those whole image is returned,
* if x and y are the only params passed a single pixel is extracted
* if all params are passed a rectangle region is extracted and a p5.Image
* is returned.
*
* Returns undefined if the region is outside the bounds of the image
*
* @method get
* @param {Number} [x] x-coordinate of the pixel
* @param {Number} [y] y-coordinate of the pixel
* @param {Number} [w] width
* @param {Number} [h] height
* @return {Array/Color | p5.Image} color of pixel at x,y in array format
* [R, G, B, A] or p5.Image
*/
p5.Image.prototype.get = function(x, y, w, h){
return p5.Renderer2D.prototype.get.call(this, x, y, w, h);
};
/**
* Set the color of a single pixel or write an image into
* this p5.Image.
*
* Note that for a large number of pixels this will
* be slower than directly manipulating the pixels array
* and then calling updatePixels().
*
* @method set
* @param {Number} x x-coordinate of the pixel
* @param {Number} y y-coordinate of the pixel
* @param {Number|Array|Object} a grayscale value | pixel array |
* a p5.Color | image to copy
* @example
* <div>
* <code>
* img = createImage(66, 66);
* img.loadPixels();
* for (i = 0; i < img.width; i++) {
* for (j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102, i % img.width * 2));
* }
* }
* img.updatePixels();
* image(img, 17, 17);
* image(img, 34, 34);
* </code>
* </div>
*/
p5.Image.prototype.set = function(x, y, imgOrCol){
p5.Renderer2D.prototype.set.call(this, x, y, imgOrCol);
};
/**
* Resize the image to a new width and height. To make the image scale
* proportionally, use 0 as the value for the wide or high parameter.
* For instance, to make the width of an image 150 pixels, and change
* the height using the same proportion, use resize(150, 0).
*
* @method resize
* @param {Number} width the resized image width
* @param {Number} height the resized image height
* @example
* <div><code>
* var img;
*
* function setup() {
* img = loadImage("assets/rockies.jpg");
* }
* function draw() {
* image(img, 0, 0);
* }
*
* function mousePressed() {
* img.resize(50, 100);
* }
* </code></div>
*/
p5.Image.prototype.resize = function(width, height){
// Copy contents to a temporary canvas, resize the original
// and then copy back.
//
// There is a faster approach that involves just one copy and swapping the
// this.canvas reference. We could switch to that approach if (as i think
// is the case) there an expectation that the user would not hold a
// reference to the backing canvas of a p5.Image. But since we do not
// enforce that at the moment, I am leaving in the slower, but safer
// implementation.
width = width || this.canvas.width;
height = height || this.canvas.height;
var tempCanvas = document.createElement('canvas');
tempCanvas.width = width;
tempCanvas.height = height;
tempCanvas.getContext('2d').drawImage(this.canvas,
0, 0, this.canvas.width, this.canvas.height,
0, 0, tempCanvas.width, tempCanvas.height
);
// Resize the original canvas, which will clear its contents
this.canvas.width = this.width = width;
this.canvas.height = this.height = height;
//Copy the image back
this.drawingContext.drawImage(tempCanvas,
0, 0, width, height,
0, 0, width, height
);
if(this.pixels.length > 0){
this.loadPixels();
}
};
/**
* Copies a region of pixels from one image to another. If no
* srcImage is specified this is used as the source. If the source
* and destination regions aren't the same size, it will
* automatically resize source pixels to fit the specified
* target region.
*
* @method copy
* @param {p5.Image|undefined} srcImage source image
* @param {Integer} sx X coordinate of the source's upper left corner
* @param {Integer} sy Y coordinate of the source's upper left corner
* @param {Integer} sw source image width
* @param {Integer} sh source image height
* @param {Integer} dx X coordinate of the destination's upper left corner
* @param {Integer} dy Y coordinate of the destination's upper left corner
* @param {Integer} dw destination image width
* @param {Integer} dh destination image height
*/
p5.Image.prototype.copy = function () {
p5.prototype.copy.apply(this, arguments);
};
/**
* Masks part of an image from displaying by loading another
* image and using it's alpha channel as an alpha channel for
* this image.
*
* @method mask
* @param {p5.Image|undefined} srcImage source image
*
* TODO: - Accept an array of alpha values.
* - Use other channels of an image. p5 uses the
* blue channel (which feels kind of arbitrary). Note: at the
* moment this method does not match native processings original
* functionality exactly.
*
* http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
*
*/
p5.Image.prototype.mask = function(p5Image) {
if(p5Image === undefined){
p5Image = this;
}
var currBlend = this.drawingContext.globalCompositeOperation;
var scaleFactor = 1;
if (p5Image instanceof p5.Renderer) {
scaleFactor = p5Image._pInst._pixelDensity;
}
var copyArgs = [
p5Image,
0,
0,
scaleFactor*p5Image.width,
scaleFactor*p5Image.height,
0,
0,
this.width,
this.height
];
this.drawingContext.globalCompositeOperation = 'destination-in';
this.copy.apply(this, copyArgs);
this.drawingContext.globalCompositeOperation = currBlend;
};
/**
* Applies an image filter to a p5.Image
*
* @method filter
* @param {String} operation one of threshold, gray, invert, posterize and
* opaque see Filters.js for docs on each available
* filter
* @param {Number|undefined} value
*/
p5.Image.prototype.filter = function(operation, value) {
Filters.apply(this.canvas, Filters[operation.toLowerCase()], value);
};
/**
* Copies a region of pixels from one image to another, using a specified
* blend mode to do the operation.
*
* @method blend
* @param {p5.Image|undefined} srcImage source image
* @param {Integer} sx X coordinate of the source's upper left corner
* @param {Integer} sy Y coordinate of the source's upper left corner
* @param {Integer} sw source image width
* @param {Integer} sh source image height
* @param {Integer} dx X coordinate of the destination's upper left corner
* @param {Integer} dy Y coordinate of the destination's upper left corner
* @param {Integer} dw destination image width
* @param {Integer} dh destination image height
* @param {Integer} blendMode the blend mode
*
* Available blend modes are: normal | multiply | screen | overlay |
* darken | lighten | color-dodge | color-burn | hard-light |
* soft-light | difference | exclusion | hue | saturation |
* color | luminosity
*
*
* http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
*
*/
p5.Image.prototype.blend = function() {
p5.prototype.blend.apply(this, arguments);
};
/**
* Saves the image to a file and force the browser to download it.
* Accepts two strings for filename and file extension
* Supports png (default) and jpg.
*
* @method save
* @param {String} filename give your file a name
* @param {String} extension 'png' or 'jpg'
*/
p5.Image.prototype.save = function(filename, extension) {
var mimeType;
if (!extension) {
extension = 'png';
mimeType = 'image/png';
}
else {
// en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
switch(extension.toLowerCase()){
case 'png':
mimeType = 'image/png';
break;
case 'jpeg':
mimeType = 'image/jpeg';
break;
case 'jpg':
mimeType = 'image/jpeg';
break;
default:
mimeType = 'image/png';
break;
}
}
var downloadMime = 'image/octet-stream';
var imageData = this.canvas.toDataURL(mimeType);
imageData = imageData.replace(mimeType, downloadMime);
//Make the browser download the file
p5.prototype.downloadFile(imageData, filename, extension);
};
/**
* creates a gl texture
* used in WEBGL mode only
* @param {[type]} tex [description]
* @return {[type]} [description]
*/
p5.Image.prototype.createTexture = function(tex){
//this.texture = tex;
return this;
};
module.exports = p5.Image;
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | designer/report-designer/src/main/java/org/pentaho/reporting/designer/core/actions/report/preview/PreviewExcelAction.java | 6038 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.designer.core.actions.report.preview;
import org.pentaho.reporting.designer.core.actions.AbstractReportContextAction;
import org.pentaho.reporting.designer.core.actions.ActionMessages;
import org.pentaho.reporting.designer.core.util.ExternalToolLauncher;
import org.pentaho.reporting.designer.core.util.IconLoader;
import org.pentaho.reporting.designer.core.util.exceptions.UncaughtExceptionsModel;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.layout.output.ReportProcessor;
import org.pentaho.reporting.engine.classic.core.modules.gui.base.PreviewParametersDialog;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.ExceptionDialog;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.ReportProgressDialog;
import org.pentaho.reporting.engine.classic.core.modules.output.fast.validator.ReportStructureValidator;
import org.pentaho.reporting.engine.classic.core.modules.output.fast.xls.FastExcelExportProcessor;
import org.pentaho.reporting.engine.classic.core.modules.output.table.base.FlowReportProcessor;
import org.pentaho.reporting.engine.classic.core.modules.output.table.xls.FlowExcelOutputProcessor;
import org.pentaho.reporting.libraries.designtime.swing.LibSwingUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
/**
* Todo: Document Me
*
* @author Thomas Morgner
*/
public final class PreviewExcelAction extends AbstractReportContextAction {
public PreviewExcelAction() {
putValue( Action.NAME, ActionMessages.getString( "PreviewExcelAction.Text" ) );
putValue( Action.SHORT_DESCRIPTION, ActionMessages.getString( "PreviewExcelAction.Description" ) );
putValue( Action.MNEMONIC_KEY, ActionMessages.getOptionalMnemonic( "PreviewExcelAction.Mnemonic" ) );
putValue( Action.ACCELERATOR_KEY, ActionMessages.getOptionalKeyStroke( "PreviewExcelAction.Accelerator" ) );
putValue( Action.SMALL_ICON, IconLoader.getInstance().getPreviewXLSIcon() );
}
/**
* Invoked when an action occurs.
*/
public void actionPerformed( final ActionEvent e ) {
if ( getActiveContext() == null ) {
return;
}
final MasterReport reportElement = getActiveContext().getContextRoot();
final Component parent = getReportDesignerContext().getView().getParent();
final Window window = LibSwingUtil.getWindowAncestor( parent );
if ( PreviewParametersDialog.process( window, reportElement ) ) {
final ReportProgressDialog dialog;
if ( window instanceof JDialog ) {
dialog = new ReportProgressDialog( (JDialog) window );
} else if ( window instanceof JFrame ) {
dialog = new ReportProgressDialog( (JFrame) window );
} else {
dialog = new ReportProgressDialog();
}
final Thread t = new Thread( new ExportTask( reportElement, dialog ) );
t.setDaemon( true );
t.start();
}
}
private static class ExportTask implements Runnable {
private MasterReport report;
private ReportProgressDialog progressDialog;
private ExportTask( final MasterReport report,
final ReportProgressDialog progressDialog ) {
this.report = report;
this.progressDialog = progressDialog;
}
public void run() {
try {
final File tempFile = File.createTempFile( "report-designer-preview", ".xls" );//$NON-NLS-1$
tempFile.deleteOnExit();
final FileOutputStream fout = new FileOutputStream( tempFile );
try {
final BufferedOutputStream bout = new BufferedOutputStream( fout );
ReportStructureValidator validator = new ReportStructureValidator();
ReportProcessor reportProcessor;
if ( validator.isValidForFastProcessing( report ) == false ) {
final FlowExcelOutputProcessor target =
new FlowExcelOutputProcessor( report.getConfiguration(), bout, report.getResourceManager() );
target.setUseXlsxFormat( false );
reportProcessor = new FlowReportProcessor( report, target );
} else {
reportProcessor = new FastExcelExportProcessor( report, bout, false );
}
reportProcessor.addReportProgressListener( progressDialog );
progressDialog.setVisibleInEDT( true );
reportProcessor.processReport();
reportProcessor.close();
bout.flush();
reportProcessor.removeReportProgressListener( progressDialog );
} finally {
fout.close();
}
progressDialog.setVisibleInEDT( false );
ExternalToolLauncher.openXLS( tempFile );
} catch ( Exception e1 ) {
UncaughtExceptionsModel.getInstance().addException( e1 );
progressDialog.dispose();
final String errorMessage = ActionMessages.getString( "PreviewReport.Error.Text" );
final String errorTitle = ActionMessages.getString( "PreviewReport.Error.Title" );
ExceptionDialog.showExceptionDialog( progressDialog.getParent(), errorTitle, errorMessage, e1 );
}
}
}
}
| lgpl-2.1 |
Amichai/PhysicsPad | mathnetnumerics_b382b1690235/src/Numerics/LinearAlgebra/Complex/Solvers/Preconditioners/Diagonal.cs | 5354 | // <copyright file="Diagonal.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2010 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers.Preconditioners
{
using System;
using System.Numerics;
using Properties;
/// <summary>
/// A diagonal preconditioner. The preconditioner uses the inverse
/// of the matrix diagonal as preconditioning values.
/// </summary>
public sealed class Diagonal : IPreConditioner
{
/// <summary>
/// The inverse of the matrix diagonal.
/// </summary>
private Complex[] _inverseDiagonals;
/// <summary>
/// Returns the decomposed matrix diagonal.
/// </summary>
/// <returns>The matrix diagonal.</returns>
internal DiagonalMatrix DiagonalEntries()
{
var result = new DiagonalMatrix(_inverseDiagonals.Length);
for (var i = 0; i < _inverseDiagonals.Length; i++)
{
result[i, i] = 1 / _inverseDiagonals[i];
}
return result;
}
/// <summary>
/// Initializes the preconditioner and loads the internal data structures.
/// </summary>
/// <param name="matrix">
/// The <see cref="Matrix"/> upon which this preconditioner is based.</param>
/// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <see langword="null" />. </exception>
/// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception>
public void Initialize(Matrix matrix)
{
if (matrix == null)
{
throw new ArgumentNullException("matrix");
}
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
}
_inverseDiagonals = new Complex[matrix.RowCount];
for (var i = 0; i < matrix.RowCount; i++)
{
_inverseDiagonals[i] = 1 / matrix[i, i];
}
}
/// <summary>
/// Approximates the solution to the matrix equation <b>Ax = b</b>.
/// </summary>
/// <param name="rhs">The right hand side vector.</param>
/// <returns>The left hand side vector.</returns>
public Vector Approximate(Vector rhs)
{
if (rhs == null)
{
throw new ArgumentNullException("rhs");
}
if (_inverseDiagonals == null)
{
throw new ArgumentException(Resources.ArgumentMatrixDoesNotExist);
}
if (rhs.Count != _inverseDiagonals.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength, "rhs");
}
Vector result = new DenseVector(rhs.Count);
Approximate(rhs, result);
return result;
}
/// <summary>
/// Approximates the solution to the matrix equation <b>Ax = b</b>.
/// </summary>
/// <param name="rhs">The right hand side vector.</param>
/// <param name="lhs">The left hand side vector. Also known as the result vector.</param>
public void Approximate(Vector rhs, Vector lhs)
{
if (rhs == null)
{
throw new ArgumentNullException("rhs");
}
if (lhs == null)
{
throw new ArgumentNullException("lhs");
}
if (_inverseDiagonals == null)
{
throw new ArgumentException(Resources.ArgumentMatrixDoesNotExist);
}
if ((lhs.Count != rhs.Count) || (lhs.Count != _inverseDiagonals.Length))
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength, "rhs");
}
for (var i = 0; i < _inverseDiagonals.Length; i++)
{
lhs[i] = rhs[i] * _inverseDiagonals[i];
}
}
}
}
| lgpl-2.1 |