repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
CnZoom/XcSoarPull | src/Engine/Contest/Solvers/XContestFree.cpp | 1422 | /* Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2015 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "XContestFree.hpp"
XContestFree::XContestFree(const Trace &_trace,
const bool _is_dhv)
:ContestDijkstra(_trace, true, 4, 1000),
is_dhv(_is_dhv) {}
ContestResult
XContestFree::CalculateResult() const
{
ContestResult result = ContestDijkstra::CalculateResult();
// DHV-XC: 1.5 points per km
// XContest: 1.0 points per km
const fixed score_factor = is_dhv ? fixed(0.0015) : fixed(0.0010);
result.score = ApplyHandicap(result.distance * score_factor);
return result;
}
| gpl-2.0 |
thomasdbcklr/duivendagboek | vendor/drupal/console-core/src/Application.php | 14921 | <?php
namespace Drupal\Console\Core;
use Drupal\Console\Core\Utils\TranslatorManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Application as BaseApplication;
use Drupal\Console\Core\EventSubscriber\DefaultValueEventListener;
use Drupal\Console\Core\EventSubscriber\ShowGenerateChainListener;
use Drupal\Console\Core\EventSubscriber\ShowTipsListener;
use Drupal\Console\Core\EventSubscriber\ShowWelcomeMessageListener;
use Drupal\Console\Core\EventSubscriber\ValidateExecutionListener;
use Drupal\Console\Core\EventSubscriber\ShowGeneratedFilesListener;
use Drupal\Console\Core\EventSubscriber\ShowGenerateInlineListener;
use Drupal\Console\Core\EventSubscriber\CallCommandListener;
use Drupal\Console\Core\Utils\ConfigurationManager;
use Drupal\Console\Core\Style\DrupalStyle;
use Drupal\Console\Core\Utils\ChainDiscovery;
use Drupal\Console\Core\Command\Chain\ChainCustomCommand;
/**
* Class Application
*
* @package Drupal\Console
*/
class Application extends BaseApplication
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var string
*/
protected $commandName;
/**
* ConsoleApplication constructor.
*
* @param ContainerInterface $container
* @param string $name
* @param string $version
*/
public function __construct(
ContainerInterface$container,
$name,
$version
) {
$this->container = $container;
parent::__construct($name, $version);
$this->addOptions();
}
/**
* @return TranslatorManagerInterface
*/
public function getTranslator()
{
if ($this->container) {
return $this->container->get('console.translator_manager');
}
return null;
}
/**
* @param $key string
*
* @return string
*/
public function trans($key)
{
if ($this->getTranslator()) {
return $this->getTranslator()->trans($key);
}
return null;
}
/**
* {@inheritdoc}
*/
public function doRun(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$messages = [];
$commandName = $this->getCommandName($input)?:'list';
$this->commandName = $commandName;
$this->registerEvents();
$this->registerExtendCommands();
/**
* @var ConfigurationManager $configurationManager
*/
$configurationManager = $this->container
->get('console.configuration_manager');
$config = $configurationManager->getConfiguration()
->get('application.extras.config')?:'true';
if ($config === 'true') {
$this->registerCommandsFromAutoWireConfiguration();
}
$chains = $configurationManager->getConfiguration()
->get('application.extras.chains')?:'true';
if ($chains === 'true') {
$this->registerChainCommands();
}
if ($commandName && !$this->has($commandName)) {
$isValidCommand = false;
$config = $configurationManager->getConfiguration();
$mappings = $config
->get('application.commands.mappings');
if (array_key_exists($commandName, $mappings)) {
$commandNameMap = $mappings[$commandName];
$messages['warning'][] = sprintf(
$this->trans('application.errors.renamed-command'),
$commandName,
$commandNameMap
);
$this->add(
$this->find($commandNameMap)->setAliases([$commandName])
);
$isValidCommand = true;
}
$drushCommand = $configurationManager->readDrushEquivalents($commandName);
if ($drushCommand) {
$this->add(
$this->find($drushCommand)->setAliases([$commandName])
);
$isValidCommand = true;
$messages['warning'][] = sprintf(
$this->trans('application.errors.drush-command'),
$commandName,
$drushCommand
);
}
if (!$isValidCommand) {
$io->error(
sprintf(
$this->trans('application.errors.invalid-command'),
$this->commandName
)
);
return 1;
}
}
$code = parent::doRun(
$input,
$output
);
if ($this->commandName != 'init' && $configurationManager->getMissingConfigurationFiles(
)
) {
$io->warning(
$this->trans('application.site.errors.missing-config-file')
);
$io->listing($configurationManager->getMissingConfigurationFiles());
$io->commentBlock(
$this->trans(
'application.site.errors.missing-config-file-command'
)
);
}
if ($this->getCommandName(
$input
) == 'list' && $this->container->hasParameter('console.warning')
) {
$io->warning(
$this->trans($this->container->getParameter('console.warning'))
);
}
foreach ($messages as $type => $message) {
$io->$type($message);
}
return $code;
}
/**
* registerEvents
*/
private function registerEvents()
{
$dispatcher = new EventDispatcher();
/* @todo Register listeners as services */
$dispatcher->addSubscriber(
new ValidateExecutionListener(
$this->container->get('console.translator_manager'),
$this->container->get('console.configuration_manager')
)
);
$dispatcher->addSubscriber(
new ShowWelcomeMessageListener(
$this->container->get('console.translator_manager')
)
);
$dispatcher->addSubscriber(
new DefaultValueEventListener(
$this->container->get('console.configuration_manager')
)
);
$dispatcher->addSubscriber(
new ShowTipsListener(
$this->container->get('console.translator_manager')
)
);
$dispatcher->addSubscriber(
new CallCommandListener(
$this->container->get('console.chain_queue')
)
);
$dispatcher->addSubscriber(
new ShowGeneratedFilesListener(
$this->container->get('console.file_queue'),
$this->container->get('console.show_file')
)
);
$dispatcher->addSubscriber(
new ShowGenerateInlineListener(
$this->container->get('console.translator_manager')
)
);
$dispatcher->addSubscriber(
new ShowGenerateChainListener(
$this->container->get('console.translator_manager')
)
);
$this->setDispatcher($dispatcher);
}
/**
* addOptions
*/
private function addOptions()
{
$this->getDefinition()->addOption(
new InputOption(
'--env',
'-e',
InputOption::VALUE_OPTIONAL,
$this->trans('application.options.env'), 'prod'
)
);
$this->getDefinition()->addOption(
new InputOption(
'--root',
null,
InputOption::VALUE_OPTIONAL,
$this->trans('application.options.root')
)
);
$this->getDefinition()->addOption(
new InputOption(
'--debug',
null,
InputOption::VALUE_NONE,
$this->trans('application.options.debug')
)
);
$this->getDefinition()->addOption(
new InputOption(
'--learning',
null,
InputOption::VALUE_NONE,
$this->trans('application.options.learning')
)
);
$this->getDefinition()->addOption(
new InputOption(
'--generate-chain',
'-c',
InputOption::VALUE_NONE,
$this->trans('application.options.generate-chain')
)
);
$this->getDefinition()->addOption(
new InputOption(
'--generate-inline',
'-i',
InputOption::VALUE_NONE,
$this->trans('application.options.generate-inline')
)
);
$this->getDefinition()->addOption(
new InputOption(
'--generate-doc',
'-d',
InputOption::VALUE_NONE,
$this->trans('application.options.generate-doc')
)
);
$this->getDefinition()->addOption(
new InputOption(
'--target',
'-t',
InputOption::VALUE_OPTIONAL,
$this->trans('application.options.target')
)
);
$this->getDefinition()->addOption(
new InputOption(
'--uri',
'-l',
InputOption::VALUE_REQUIRED,
$this->trans('application.options.uri')
)
);
$this->getDefinition()->addOption(
new InputOption(
'--yes',
'-y',
InputOption::VALUE_NONE,
$this->trans('application.options.yes')
)
);
}
/**
* registerExtendCommands
*/
private function registerExtendCommands()
{
$this->container->get('console.configuration_manager')
->loadExtendConfiguration();
}
/**
* registerCommandsFromAutoWireConfiguration
*/
private function registerCommandsFromAutoWireConfiguration()
{
$configuration = $this->container->get('console.configuration_manager')
->getConfiguration();
$autoWireForcedCommands = $configuration
->get('application.autowire.commands.forced');
if (!is_array($autoWireForcedCommands)) {
return;
}
foreach ($autoWireForcedCommands as $autoWireForcedCommand) {
try {
if (!$autoWireForcedCommand['class']) {
continue;
}
$reflectionClass = new \ReflectionClass(
$autoWireForcedCommand['class']
);
$arguments = [];
if (array_key_exists('arguments', $autoWireForcedCommand)) {
foreach ($autoWireForcedCommand['arguments'] as $argument) {
$argument = substr($argument, 1);
$arguments[] = $this->container->get($argument);
}
}
$command = $reflectionClass->newInstanceArgs($arguments);
if (method_exists($command, 'setTranslator')) {
$command->setTranslator(
$this->container->get('console.translator_manager')
);
}
if (method_exists($command, 'setContainer')) {
$command->setContainer(
$this->container->get('service_container')
);
}
$this->add($command);
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
continue;
}
}
$autoWireNameCommand = $configuration->get(
sprintf(
'application.autowire.commands.name.%s',
$this->commandName
)
);
if ($autoWireNameCommand) {
try {
$arguments = [];
if (array_key_exists('arguments', $autoWireNameCommand)) {
foreach ($autoWireNameCommand['arguments'] as $argument) {
$argument = substr($argument, 1);
$arguments[] = $this->container->get($argument);
}
}
$reflectionClass = new \ReflectionClass(
$autoWireNameCommand['class']
);
$command = $reflectionClass->newInstanceArgs($arguments);
if (method_exists($command, 'setTranslator')) {
$command->setTranslator(
$this->container->get('console.translator_manager')
);
}
if (method_exists($command, 'setContainer')) {
$command->setContainer(
$this->container->get('service_container')
);
}
$this->add($command);
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
}
}
/**
* registerChainCommands
*/
public function registerChainCommands()
{
/**
* @var ChainDiscovery $chainDiscovery
*/
$chainDiscovery = $this->container->get('console.chain_discovery');
$chainCommands = $chainDiscovery->getChainCommands();
foreach ($chainCommands as $name => $chainCommand) {
try {
$file = $chainCommand['file'];
$description = $chainCommand['description'];
$placeHolders = $chainCommand['placeholders'];
$command = new ChainCustomCommand(
$name,
$description,
$placeHolders,
$file
);
$this->add($command);
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
}
}
/**
* Finds a command by name or alias.
*
* @param string $name A command name or a command alias
*
* @return mixed A Command instance
*
* Override parent find method to avoid name collisions with automatically
* generated command abbreviations.
* Command name validation was previously done at doRun method.
*/
public function find($name)
{
return $this->get($name);
}
}
| gpl-2.0 |
indigo423/nagvis | share/server/core/ext/php-gettext-1.0.9/gettext.php | 11599 | <?php
/*
Copyright (c) 2003, 2009 Danilo Segan <danilo@kvota.net>.
Copyright (c) 2005 Nico Kaiser <nico@siriux.net>
This file is part of PHP-gettext.
PHP-gettext is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
PHP-gettext 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 PHP-gettext; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* Provides a simple gettext replacement that works independently from
* the system's gettext abilities.
* It can read MO files and use them for translating strings.
* The files are passed to gettext_reader as a Stream (see streams.php)
*
* This version has the ability to cache all strings and translations to
* speed up the string lookup.
* While the cache is enabled by default, it can be switched off with the
* second parameter in the constructor (e.g. whenusing very large MO files
* that you don't want to keep in memory)
*/
class gettext_reader {
//public:
var $error = 0; // public variable that holds error code (0 if no error)
//private:
var $BYTEORDER = 0; // 0: low endian, 1: big endian
var $STREAM = NULL;
var $short_circuit = false;
var $enable_cache = false;
var $originals = NULL; // offset of original table
var $translations = NULL; // offset of translation table
var $pluralheader = NULL; // cache header field for plural forms
var $total = 0; // total string count
var $table_originals = NULL; // table for original strings (offsets)
var $table_translations = NULL; // table for translated strings (offsets)
var $cache_translations = NULL; // original -> translation mapping
/* Methods */
/**
* Reads a 32bit Integer from the Stream
*
* @access private
* @return Integer from the Stream
*/
function readint() {
if ($this->BYTEORDER == 0) {
// low endian
$input=unpack('V', $this->STREAM->read(4));
return array_shift($input);
} else {
// big endian
$input=unpack('N', $this->STREAM->read(4));
return array_shift($input);
}
}
function read($bytes) {
return $this->STREAM->read($bytes);
}
/**
* Reads an array of Integers from the Stream
*
* @param int count How many elements should be read
* @return Array of Integers
*/
function readintarray($count) {
if ($this->BYTEORDER == 0) {
// low endian
return unpack('V'.$count, $this->STREAM->read(4 * $count));
} else {
// big endian
return unpack('N'.$count, $this->STREAM->read(4 * $count));
}
}
/**
* Constructor
*
* @param object Reader the StreamReader object
* @param boolean enable_cache Enable or disable caching of strings (default on)
*/
function gettext_reader($Reader, $enable_cache = true) {
// If there isn't a StreamReader, turn on short circuit mode.
if (! $Reader || isset($Reader->error) ) {
$this->short_circuit = true;
return;
}
// Caching can be turned off
$this->enable_cache = $enable_cache;
$MAGIC1 = "\x95\x04\x12\xde";
$MAGIC2 = "\xde\x12\x04\x95";
$this->STREAM = $Reader;
$magic = $this->read(4);
if ($magic == $MAGIC1) {
$this->BYTEORDER = 1;
} elseif ($magic == $MAGIC2) {
$this->BYTEORDER = 0;
} else {
$this->error = 1; // not MO file
return false;
}
// FIXME: Do we care about revision? We should.
$revision = $this->readint();
$this->total = $this->readint();
$this->originals = $this->readint();
$this->translations = $this->readint();
}
/**
* Loads the translation tables from the MO file into the cache
* If caching is enabled, also loads all strings into a cache
* to speed up translation lookups
*
* @access private
*/
function load_tables() {
if (is_array($this->cache_translations) &&
is_array($this->table_originals) &&
is_array($this->table_translations))
return;
/* get original and translations tables */
$this->STREAM->seekto($this->originals);
$this->table_originals = $this->readintarray($this->total * 2);
$this->STREAM->seekto($this->translations);
$this->table_translations = $this->readintarray($this->total * 2);
if ($this->enable_cache) {
$this->cache_translations = array ();
/* read all strings in the cache */
for ($i = 0; $i < $this->total; $i++) {
$this->STREAM->seekto($this->table_originals[$i * 2 + 2]);
$original = $this->STREAM->read($this->table_originals[$i * 2 + 1]);
$this->STREAM->seekto($this->table_translations[$i * 2 + 2]);
$translation = $this->STREAM->read($this->table_translations[$i * 2 + 1]);
$this->cache_translations[$original] = $translation;
}
}
}
/**
* Returns a string from the "originals" table
*
* @access private
* @param int num Offset number of original string
* @return string Requested string if found, otherwise ''
*/
function get_original_string($num) {
$length = $this->table_originals[$num * 2 + 1];
$offset = $this->table_originals[$num * 2 + 2];
if (! $length)
return '';
$this->STREAM->seekto($offset);
$data = $this->STREAM->read($length);
return (string)$data;
}
/**
* Returns a string from the "translations" table
*
* @access private
* @param int num Offset number of original string
* @return string Requested string if found, otherwise ''
*/
function get_translation_string($num) {
$length = $this->table_translations[$num * 2 + 1];
$offset = $this->table_translations[$num * 2 + 2];
if (! $length)
return '';
$this->STREAM->seekto($offset);
$data = $this->STREAM->read($length);
return (string)$data;
}
/**
* Binary search for string
*
* @access private
* @param string string
* @param int start (internally used in recursive function)
* @param int end (internally used in recursive function)
* @return int string number (offset in originals table)
*/
function find_string($string, $start = -1, $end = -1) {
if (($start == -1) or ($end == -1)) {
// find_string is called with only one parameter, set start end end
$start = 0;
$end = $this->total;
}
if (abs($start - $end) <= 1) {
// We're done, now we either found the string, or it doesn't exist
$txt = $this->get_original_string($start);
if ($string == $txt)
return $start;
else
return -1;
} else if ($start > $end) {
// start > end -> turn around and start over
return $this->find_string($string, $end, $start);
} else {
// Divide table in two parts
$half = (int)(($start + $end) / 2);
$cmp = strcmp($string, $this->get_original_string($half));
if ($cmp == 0)
// string is exactly in the middle => return it
return $half;
else if ($cmp < 0)
// The string is in the upper half
return $this->find_string($string, $start, $half);
else
// The string is in the lower half
return $this->find_string($string, $half, $end);
}
}
/**
* Translates a string
*
* @access public
* @param string string to be translated
* @return string translated string (or original, if not found)
*/
function translate($string) {
if ($this->short_circuit)
return $string;
$this->load_tables();
if ($this->enable_cache) {
// Caching enabled, get translated string from cache
if (array_key_exists($string, $this->cache_translations))
return $this->cache_translations[$string];
else
return $string;
} else {
// Caching not enabled, try to find string
$num = $this->find_string($string);
if ($num == -1)
return $string;
else
return $this->get_translation_string($num);
}
}
/**
* Sanitize plural form expression for use in PHP eval call.
*
* @access private
* @return string sanitized plural form expression
*/
function sanitize_plural_expression($expr) {
// Get rid of disallowed characters.
$expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr);
// Add parenthesis for tertiary '?' operator.
$expr .= ';';
$res = '';
$p = 0;
for ($i = 0; $i < strlen($expr); $i++) {
$ch = $expr[$i];
switch ($ch) {
case '?':
$res .= ' ? (';
$p++;
break;
case ':':
$res .= ') : (';
break;
case ';':
$res .= str_repeat( ')', $p) . ';';
$p = 0;
break;
default:
$res .= $ch;
}
}
return $res;
}
/**
* Get possible plural forms from MO header
*
* @access private
* @return string plural form header
*/
function get_plural_forms() {
// lets assume message number 0 is header
// this is true, right?
$this->load_tables();
// cache header field for plural forms
if (! is_string($this->pluralheader)) {
if ($this->enable_cache) {
$header = $this->cache_translations[""];
} else {
$header = $this->get_translation_string(0);
}
if (eregi("plural-forms: ([^\n]*)\n", $header, $regs))
$expr = $regs[1];
else
$expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
$this->pluralheader = $this->sanitize_plural_expression($expr);
}
return $this->pluralheader;
}
/**
* Detects which plural form to take
*
* @access private
* @param n count
* @return int array index of the right plural form
*/
function select_string($n) {
$string = $this->get_plural_forms();
$string = str_replace('nplurals',"\$total",$string);
$string = str_replace("n",$n,$string);
$string = str_replace('plural',"\$plural",$string);
$total = 0;
$plural = 0;
eval("$string");
if ($plural >= $total) $plural = $total - 1;
return $plural;
}
/**
* Plural version of gettext
*
* @access public
* @param string single
* @param string plural
* @param string number
* @return translated plural form
*/
function ngettext($single, $plural, $number) {
if ($this->short_circuit) {
if ($number != 1)
return $plural;
else
return $single;
}
// find out the appropriate form
$select = $this->select_string($number);
// this should contains all strings separated by NULLs
$key = $single.chr(0).$plural;
if ($this->enable_cache) {
if (! array_key_exists($key, $this->cache_translations)) {
return ($number != 1) ? $plural : $single;
} else {
$result = $this->cache_translations[$key];
$list = explode(chr(0), $result);
return $list[$select];
}
} else {
$num = $this->find_string($key);
if ($num == -1) {
return ($number != 1) ? $plural : $single;
} else {
$result = $this->get_translation_string($num);
$list = explode(chr(0), $result);
return $list[$select];
}
}
}
}
?>
| gpl-2.0 |
ryoon/eCos | packages/language/cxx/ustl/current/tests/bvt24.cpp | 2886 | // This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
#include "stdtest.h"
static void HeapSize (size_t nElements, size_t& layerWidth, size_t& nLayers)
{
layerWidth = 0;
nLayers = 0;
for (size_t fts = 0; nElements > fts; fts += layerWidth) {
layerWidth *= 2;
if (!layerWidth)
++ layerWidth;
++ nLayers;
}
}
static void PrintSpace (size_t n)
{
for (uoff_t s = 0; s < n; ++ s)
cout << ' ';
}
static void PrintHeap (const vector<int>& v)
{
size_t maxWidth, nLayers;
HeapSize (v.size(), maxWidth, nLayers);
vector<int>::const_iterator src (v.begin());
cout << ios::width(3);
maxWidth *= 3;
for (uoff_t i = 0; i < nLayers; ++ i) {
const size_t w = 1 << i;
const size_t spacing = max (0, int(maxWidth / w) - 3);
PrintSpace (spacing / 2);
for (uoff_t j = 0; j < w && src != v.end(); ++ j) {
cout << *src++;
if (j < w - 1 && src != v.end() - 1)
PrintSpace (spacing);
}
cout << endl;
}
}
void TestHeapOperations (void)
{
static const int c_Values [31] = { // 31 values make a full 4-layer tree
93, 92, 90, 86, 83, 86, 77, 40, 72, 36, 68, 82, 62, 67, 63, 15,
26, 26, 49, 21, 11, 62, 67, 27, 29, 30, 35, 23, 59, 35, 29
};
vector<int> v;
v.reserve (VectorSize(c_Values));
for (uoff_t i = 0; i < VectorSize(c_Values); ++ i) {
v.push_back (c_Values[i]);
push_heap (v.begin(), v.end());
cout << "------------------------------------------------\n";
if (!is_heap (v.begin(), v.end()))
cout << "Is NOT a heap\n";
PrintHeap (v);
}
cout << "------------------------------------------------\n";
cout << "make_heap on the full range:\n";
v.resize (VectorSize (c_Values));
copy (VectorRange(c_Values), v.begin());
make_heap (v.begin(), v.end());
PrintHeap (v);
if (!is_heap (v.begin(), v.end()))
cout << "Is NOT a heap\n";
cout << "------------------------------------------------\n";
cout << "pop_heap:\n";
pop_heap (v.begin(), v.end());
v.pop_back();
PrintHeap (v);
if (!is_heap (v.begin(), v.end()))
cout << "Is NOT a heap\n";
cout << "------------------------------------------------\n";
cout << "sort_heap:\n";
v.resize (VectorSize (c_Values));
copy (VectorRange(c_Values), v.begin());
make_heap (v.begin(), v.end());
sort_heap (v.begin(), v.end());
foreach (vector<int>::const_iterator, i, v)
cout << *i;
cout << endl;
cout << "------------------------------------------------\n";
cout << "priority_queue push and pop:\n";
priority_queue<int> q;
for (uoff_t i = 0; i < VectorSize(c_Values); ++ i)
q.push (c_Values[i]);
while (!q.empty()) {
cout << q.top();
q.pop();
}
cout << endl;
}
StdBvtMain (TestHeapOperations)
| gpl-2.0 |
shitizadmirer/unimap.ns-3noc | bindings/python/apidefs/gcc-ILP32/ns3_module_csma.py | 23506 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
def register_types(module):
root_module = module.get_root()
## csma-channel.h: ns3::WireState [enumeration]
module.add_enum('WireState', ['IDLE', 'TRANSMITTING', 'PROPAGATING'])
## backoff.h: ns3::Backoff [class]
module.add_class('Backoff')
## csma-channel.h: ns3::CsmaDeviceRec [class]
module.add_class('CsmaDeviceRec')
## csma-channel.h: ns3::CsmaChannel [class]
module.add_class('CsmaChannel', parent=root_module['ns3::Channel'])
## csma-net-device.h: ns3::CsmaNetDevice [class]
module.add_class('CsmaNetDevice', parent=root_module['ns3::NetDevice'])
## csma-net-device.h: ns3::CsmaNetDevice::EncapsulationMode [enumeration]
module.add_enum('EncapsulationMode', ['ILLEGAL', 'DIX', 'LLC'], outer_class=root_module['ns3::CsmaNetDevice'])
## Register a nested module for the namespace Config
nested_module = module.add_cpp_namespace('Config')
register_types_ns3_Config(nested_module)
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace addressUtils
nested_module = module.add_cpp_namespace('addressUtils')
register_types_ns3_addressUtils(nested_module)
## Register a nested module for the namespace aodv
nested_module = module.add_cpp_namespace('aodv')
register_types_ns3_aodv(nested_module)
## Register a nested module for the namespace dot11s
nested_module = module.add_cpp_namespace('dot11s')
register_types_ns3_dot11s(nested_module)
## Register a nested module for the namespace flame
nested_module = module.add_cpp_namespace('flame')
register_types_ns3_flame(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(nested_module)
## Register a nested module for the namespace olsr
nested_module = module.add_cpp_namespace('olsr')
register_types_ns3_olsr(nested_module)
def register_types_ns3_Config(module):
root_module = module.get_root()
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_addressUtils(module):
root_module = module.get_root()
def register_types_ns3_aodv(module):
root_module = module.get_root()
def register_types_ns3_dot11s(module):
root_module = module.get_root()
def register_types_ns3_flame(module):
root_module = module.get_root()
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_types_ns3_olsr(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3Backoff_methods(root_module, root_module['ns3::Backoff'])
register_Ns3CsmaDeviceRec_methods(root_module, root_module['ns3::CsmaDeviceRec'])
register_Ns3CsmaChannel_methods(root_module, root_module['ns3::CsmaChannel'])
register_Ns3CsmaNetDevice_methods(root_module, root_module['ns3::CsmaNetDevice'])
return
def register_Ns3Backoff_methods(root_module, cls):
## backoff.h: ns3::Backoff::Backoff(ns3::Backoff const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Backoff const &', 'arg0')])
## backoff.h: ns3::Backoff::Backoff() [constructor]
cls.add_constructor([])
## backoff.h: ns3::Backoff::Backoff(ns3::Time slotTime, uint32_t minSlots, uint32_t maxSlots, uint32_t ceiling, uint32_t maxRetries) [constructor]
cls.add_constructor([param('ns3::Time', 'slotTime'), param('uint32_t', 'minSlots'), param('uint32_t', 'maxSlots'), param('uint32_t', 'ceiling'), param('uint32_t', 'maxRetries')])
## backoff.h: ns3::Time ns3::Backoff::GetBackoffTime() [member function]
cls.add_method('GetBackoffTime',
'ns3::Time',
[])
## backoff.h: void ns3::Backoff::IncrNumRetries() [member function]
cls.add_method('IncrNumRetries',
'void',
[])
## backoff.h: bool ns3::Backoff::MaxRetriesReached() [member function]
cls.add_method('MaxRetriesReached',
'bool',
[])
## backoff.h: void ns3::Backoff::ResetBackoffTime() [member function]
cls.add_method('ResetBackoffTime',
'void',
[])
## backoff.h: ns3::Backoff::m_ceiling [variable]
cls.add_instance_attribute('m_ceiling', 'uint32_t', is_const=False)
## backoff.h: ns3::Backoff::m_maxRetries [variable]
cls.add_instance_attribute('m_maxRetries', 'uint32_t', is_const=False)
## backoff.h: ns3::Backoff::m_maxSlots [variable]
cls.add_instance_attribute('m_maxSlots', 'uint32_t', is_const=False)
## backoff.h: ns3::Backoff::m_minSlots [variable]
cls.add_instance_attribute('m_minSlots', 'uint32_t', is_const=False)
## backoff.h: ns3::Backoff::m_slotTime [variable]
cls.add_instance_attribute('m_slotTime', 'ns3::Time', is_const=False)
return
def register_Ns3CsmaDeviceRec_methods(root_module, cls):
## csma-channel.h: ns3::CsmaDeviceRec::CsmaDeviceRec(ns3::CsmaDeviceRec const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CsmaDeviceRec const &', 'arg0')])
## csma-channel.h: ns3::CsmaDeviceRec::CsmaDeviceRec() [constructor]
cls.add_constructor([])
## csma-channel.h: ns3::CsmaDeviceRec::CsmaDeviceRec(ns3::Ptr<ns3::CsmaNetDevice> device) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')])
## csma-channel.h: bool ns3::CsmaDeviceRec::IsActive() [member function]
cls.add_method('IsActive',
'bool',
[])
## csma-channel.h: ns3::CsmaDeviceRec::active [variable]
cls.add_instance_attribute('active', 'bool', is_const=False)
## csma-channel.h: ns3::CsmaDeviceRec::devicePtr [variable]
cls.add_instance_attribute('devicePtr', 'ns3::Ptr< ns3::CsmaNetDevice >', is_const=False)
return
def register_Ns3CsmaChannel_methods(root_module, cls):
## csma-channel.h: ns3::CsmaChannel::CsmaChannel(ns3::CsmaChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CsmaChannel const &', 'arg0')])
## csma-channel.h: ns3::CsmaChannel::CsmaChannel() [constructor]
cls.add_constructor([])
## csma-channel.h: int32_t ns3::CsmaChannel::Attach(ns3::Ptr<ns3::CsmaNetDevice> device) [member function]
cls.add_method('Attach',
'int32_t',
[param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')])
## csma-channel.h: bool ns3::CsmaChannel::Detach(ns3::Ptr<ns3::CsmaNetDevice> device) [member function]
cls.add_method('Detach',
'bool',
[param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')])
## csma-channel.h: bool ns3::CsmaChannel::Detach(uint32_t deviceId) [member function]
cls.add_method('Detach',
'bool',
[param('uint32_t', 'deviceId')])
## csma-channel.h: ns3::Ptr<ns3::CsmaNetDevice> ns3::CsmaChannel::GetCsmaDevice(uint32_t i) const [member function]
cls.add_method('GetCsmaDevice',
'ns3::Ptr< ns3::CsmaNetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## csma-channel.h: ns3::DataRate ns3::CsmaChannel::GetDataRate() [member function]
cls.add_method('GetDataRate',
'ns3::DataRate',
[])
## csma-channel.h: ns3::Time ns3::CsmaChannel::GetDelay() [member function]
cls.add_method('GetDelay',
'ns3::Time',
[])
## csma-channel.h: ns3::Ptr<ns3::NetDevice> ns3::CsmaChannel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## csma-channel.h: int32_t ns3::CsmaChannel::GetDeviceNum(ns3::Ptr<ns3::CsmaNetDevice> device) [member function]
cls.add_method('GetDeviceNum',
'int32_t',
[param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')])
## csma-channel.h: uint32_t ns3::CsmaChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## csma-channel.h: uint32_t ns3::CsmaChannel::GetNumActDevices() [member function]
cls.add_method('GetNumActDevices',
'uint32_t',
[])
## csma-channel.h: ns3::WireState ns3::CsmaChannel::GetState() [member function]
cls.add_method('GetState',
'ns3::WireState',
[])
## csma-channel.h: static ns3::TypeId ns3::CsmaChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## csma-channel.h: bool ns3::CsmaChannel::IsActive(uint32_t deviceId) [member function]
cls.add_method('IsActive',
'bool',
[param('uint32_t', 'deviceId')])
## csma-channel.h: bool ns3::CsmaChannel::IsBusy() [member function]
cls.add_method('IsBusy',
'bool',
[])
## csma-channel.h: void ns3::CsmaChannel::PropagationCompleteEvent() [member function]
cls.add_method('PropagationCompleteEvent',
'void',
[])
## csma-channel.h: bool ns3::CsmaChannel::Reattach(uint32_t deviceId) [member function]
cls.add_method('Reattach',
'bool',
[param('uint32_t', 'deviceId')])
## csma-channel.h: bool ns3::CsmaChannel::Reattach(ns3::Ptr<ns3::CsmaNetDevice> device) [member function]
cls.add_method('Reattach',
'bool',
[param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')])
## csma-channel.h: bool ns3::CsmaChannel::TransmitEnd() [member function]
cls.add_method('TransmitEnd',
'bool',
[])
## csma-channel.h: bool ns3::CsmaChannel::TransmitStart(ns3::Ptr<ns3::Packet> p, uint32_t srcId) [member function]
cls.add_method('TransmitStart',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'srcId')])
return
def register_Ns3CsmaNetDevice_methods(root_module, cls):
## csma-net-device.h: static ns3::TypeId ns3::CsmaNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## csma-net-device.h: ns3::CsmaNetDevice::CsmaNetDevice() [constructor]
cls.add_constructor([])
## csma-net-device.h: void ns3::CsmaNetDevice::SetInterframeGap(ns3::Time t) [member function]
cls.add_method('SetInterframeGap',
'void',
[param('ns3::Time', 't')])
## csma-net-device.h: void ns3::CsmaNetDevice::SetBackoffParams(ns3::Time slotTime, uint32_t minSlots, uint32_t maxSlots, uint32_t maxRetries, uint32_t ceiling) [member function]
cls.add_method('SetBackoffParams',
'void',
[param('ns3::Time', 'slotTime'), param('uint32_t', 'minSlots'), param('uint32_t', 'maxSlots'), param('uint32_t', 'maxRetries'), param('uint32_t', 'ceiling')])
## csma-net-device.h: bool ns3::CsmaNetDevice::Attach(ns3::Ptr<ns3::CsmaChannel> ch) [member function]
cls.add_method('Attach',
'bool',
[param('ns3::Ptr< ns3::CsmaChannel >', 'ch')])
## csma-net-device.h: void ns3::CsmaNetDevice::SetQueue(ns3::Ptr<ns3::Queue> queue) [member function]
cls.add_method('SetQueue',
'void',
[param('ns3::Ptr< ns3::Queue >', 'queue')])
## csma-net-device.h: ns3::Ptr<ns3::Queue> ns3::CsmaNetDevice::GetQueue() const [member function]
cls.add_method('GetQueue',
'ns3::Ptr< ns3::Queue >',
[],
is_const=True)
## csma-net-device.h: void ns3::CsmaNetDevice::SetReceiveErrorModel(ns3::Ptr<ns3::ErrorModel> em) [member function]
cls.add_method('SetReceiveErrorModel',
'void',
[param('ns3::Ptr< ns3::ErrorModel >', 'em')])
## csma-net-device.h: void ns3::CsmaNetDevice::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ptr<ns3::CsmaNetDevice> sender) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ptr< ns3::CsmaNetDevice >', 'sender')])
## csma-net-device.h: bool ns3::CsmaNetDevice::IsSendEnabled() [member function]
cls.add_method('IsSendEnabled',
'bool',
[])
## csma-net-device.h: void ns3::CsmaNetDevice::SetSendEnable(bool enable) [member function]
cls.add_method('SetSendEnable',
'void',
[param('bool', 'enable')])
## csma-net-device.h: bool ns3::CsmaNetDevice::IsReceiveEnabled() [member function]
cls.add_method('IsReceiveEnabled',
'bool',
[])
## csma-net-device.h: void ns3::CsmaNetDevice::SetReceiveEnable(bool enable) [member function]
cls.add_method('SetReceiveEnable',
'void',
[param('bool', 'enable')])
## csma-net-device.h: void ns3::CsmaNetDevice::SetEncapsulationMode(ns3::CsmaNetDevice::EncapsulationMode mode) [member function]
cls.add_method('SetEncapsulationMode',
'void',
[param('ns3::CsmaNetDevice::EncapsulationMode', 'mode')])
## csma-net-device.h: ns3::CsmaNetDevice::EncapsulationMode ns3::CsmaNetDevice::GetEncapsulationMode() [member function]
cls.add_method('GetEncapsulationMode',
'ns3::CsmaNetDevice::EncapsulationMode',
[])
## csma-net-device.h: void ns3::CsmaNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## csma-net-device.h: uint32_t ns3::CsmaNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: ns3::Ptr<ns3::Channel> ns3::CsmaNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## csma-net-device.h: uint16_t ns3::CsmaNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: void ns3::CsmaNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## csma-net-device.h: ns3::Address ns3::CsmaNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: void ns3::CsmaNetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: ns3::Address ns3::CsmaNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: ns3::Address ns3::CsmaNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## csma-net-device.h: ns3::Ptr<ns3::Node> ns3::CsmaNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: void ns3::CsmaNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: void ns3::CsmaNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## csma-net-device.h: ns3::Address ns3::CsmaNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## csma-net-device.h: void ns3::CsmaNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## csma-net-device.h: bool ns3::CsmaNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## csma-net-device.h: void ns3::CsmaNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## csma-net-device.h: void ns3::CsmaNetDevice::AddHeader(ns3::Ptr<ns3::Packet> p, ns3::Mac48Address source, ns3::Mac48Address dest, uint16_t protocolNumber) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Mac48Address', 'source'), param('ns3::Mac48Address', 'dest'), param('uint16_t', 'protocolNumber')],
visibility='protected')
return
def register_functions(root_module):
module = root_module
register_functions_ns3_Config(module.get_submodule('Config'), root_module)
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module)
register_functions_ns3_aodv(module.get_submodule('aodv'), root_module)
register_functions_ns3_dot11s(module.get_submodule('dot11s'), root_module)
register_functions_ns3_flame(module.get_submodule('flame'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), root_module)
register_functions_ns3_olsr(module.get_submodule('olsr'), root_module)
return
def register_functions_ns3_Config(module, root_module):
return
def register_functions_ns3_FatalImpl(module, root_module):
return
def register_functions_ns3_addressUtils(module, root_module):
return
def register_functions_ns3_aodv(module, root_module):
return
def register_functions_ns3_dot11s(module, root_module):
return
def register_functions_ns3_flame(module, root_module):
return
def register_functions_ns3_internal(module, root_module):
return
def register_functions_ns3_olsr(module, root_module):
return
| gpl-2.0 |
bsantana/bsantana | wp-content/plugins/jetpack/class.jetpack-network.php | 21477 | <?php
/**
* Used to manage Jetpack installation on Multisite Network installs
*
* SINGLETON: To use call Jetpack_Network::init()
*
* DO NOT USE ANY STATIC METHODS IN THIS CLASS!!!!!!
*
* @since 2.9
*/
class Jetpack_Network {
/**
* Holds a static copy of Jetpack_Network for the singleton
*
* @since 2.9
* @var Jetpack_Network
*/
private static $instance = null;
/**
* Name of the network wide settings
*
* @since 2.9
* @var string
*/
private $settings_name = 'jetpack-network-settings';
/**
* Defaults for settings found on the Jetpack > Settings page
*
* @since 2.9
* @var array
*/
private $setting_defaults = array(
'auto-connect' => 0,
'sub-site-connection-override' => 1,
//'manage_auto_activated_modules' => 0,
);
/**
* Constructor
*
* @since 2.9
*/
private function __construct() {
require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); // For the is_plugin... check
require_once( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' ); // For managing the global whitelist
/*
* Sanity check to ensure the install is Multisite and we
* are in Network Admin
*/
if ( is_multisite() && is_network_admin() ) {
add_action( 'network_admin_menu', array( $this, 'add_network_admin_menu' ) );
add_action( 'network_admin_edit_jetpack-network-settings', array( $this, 'save_network_settings_page' ), 10, 0 );
add_filter( 'admin_body_class', array( $this, 'body_class' ) );
if ( isset( $_GET['page'] ) && 'jetpack' == $_GET['page'] ) {
add_action( 'admin_init', array( $this, 'jetpack_sites_list' ) );
}
}
/*
* Things that should only run on multisite
*/
if ( is_multisite() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
add_action( 'wp_before_admin_bar_render', array( $this, 'add_to_menubar' ) );
/*
* If admin wants to automagically register new sites set the hook here
*
* This is a hacky way because xmlrpc is not available on wpmu_new_blog
*/
if ( $this->get_option( 'auto-connect' ) == 1 ) {
add_action( 'wpmu_new_blog', array( $this, 'do_automatically_add_new_site' ) );
}
}
// Remove the toggles for 2.9, re-evaluate how they're done and added for a 3.0 release. They don't feel quite right yet.
// add_filter( 'jetpack_get_default_modules', array( $this, 'set_auto_activated_modules' ) );
}
/**
* Sets which modules get activated by default on subsite connection.
* Modules can be set in Network Admin > Jetpack > Settings
*
* @since 2.9
*
* @param array $modules
*
* @return array
**/
public function set_auto_activated_modules( $modules ) {
return $modules;
/* Remove the toggles for 2.9, re-evaluate how they're done and added for a 3.0 release. They don't feel quite right yet.
if( 1 == $this->get_option( 'manage_auto_activated_modules' ) ) {
return (array) $this->get_option( 'modules' );
} else {
return $modules;
}
*/
}
/**
* Registers new sites upon creation
*
* @since 2.9
* @uses wpmu_new_blog
*
* @param int $blog_id
**/
public function do_automatically_add_new_site( $blog_id ) {
$this->do_subsiteregister( $blog_id );
}
/**
* Adds .network-admin class to the body tag
* Helps distinguish network admin JP styles from regular site JP styles
*
* @since 2.9
*/
public function body_class( $classes ) {
return trim( $classes ) . ' network-admin ';
}
/**
* Provides access to an instance of Jetpack_Network
*
* This is how the Jetpack_Network object should *always* be accessed
*
* @since 2.9
* @return Jetpack_Network
*/
public static function init() {
if ( ! self::$instance || ! is_a( self::$instance, 'Jetpack_Network' ) ) {
self::$instance = new Jetpack_Network;
}
return self::$instance;
}
/**
* Registers the Multisite admin bar menu item shortcut.
* This shortcut helps users quickly and easily navigate to the Jetpack Network Admin
* menu from anywhere in their network.
*
* @since 2.9
*/
public function register_menubar() {
add_action( 'wp_before_admin_bar_render', array( $this, 'add_to_menubar' ) );
}
/**
* Runs when Jetpack is deactivated from the network admin plugins menu.
* Each individual site will need to have Jetpack::disconnect called on it.
* Site that had Jetpack individually enabled will not be disconnected as
* on Multisite individually activated plugins are still activated when
* a plugin is deactivated network wide.
*
* @since 2.9
**/
public function deactivate() {
// Only fire if in network admin
if ( ! is_network_admin() ) {
return;
}
$sites = get_sites();
foreach ( $sites as $s ) {
switch_to_blog( $s->blog_id );
$active_plugins = get_option( 'active_plugins' );
/*
* If this plugin was activated in the subsite individually
* we do not want to call disconnect. Plugins activated
* individually (before network activation) stay activated
* when the network deactivation occurs
*/
if ( ! in_array( 'jetpack/jetpack.php', $active_plugins ) ) {
Jetpack::disconnect();
}
}
restore_current_blog();
}
/**
* Adds a link to the Jetpack Network Admin page in the network admin menu bar.
*
* @since 2.9
**/
public function add_to_menubar() {
global $wp_admin_bar;
// Don't show for logged out users or single site mode.
if ( ! is_user_logged_in() || ! is_multisite() ) {
return;
}
$wp_admin_bar->add_node( array(
'parent' => 'network-admin',
'id' => 'network-admin-jetpack',
'title' => __( 'Jetpack', 'jetpack' ),
'href' => $this->get_url( 'network_admin_page' ),
) );
}
/**
* Returns various URL strings. Factory like
*
* $args can be a string or an array.
* If $args is an array there must be an element called name for the switch statement
*
* Currently supports:
* - subsiteregister: Pass array( 'name' => 'subsiteregister', 'site_id' => SITE_ID )
* - network_admin_page: Provides link to /wp-admin/network/JETPACK
* - subsitedisconnect: Pass array( 'name' => 'subsitedisconnect', 'site_id' => SITE_ID )
*
* @since 2.9
*
* @param Mixed $args
*
* @return String
**/
public function get_url( $args ) {
$url = null; // Default url value
if ( is_string( $args ) ) {
$name = $args;
} else {
$name = $args['name'];
}
switch ( $name ) {
case 'subsiteregister':
if ( ! isset( $args['site_id'] ) ) {
break; // If there is not a site id present we cannot go further
}
$url = network_admin_url(
'admin.php?page=jetpack&action=subsiteregister&site_id='
. $args['site_id']
);
break;
case 'network_admin_page':
$url = network_admin_url( 'admin.php?page=jetpack' );
break;
case 'subsitedisconnect':
if ( ! isset( $args['site_id'] ) ) {
break; // If there is not a site id present we cannot go further
}
$url = network_admin_url(
'admin.php?page=jetpack&action=subsitedisconnect&site_id='
. $args['site_id']
);
break;
}
return $url;
}
/**
* Adds the Jetpack menu item to the Network Admin area
*
* @since 2.9
*/
public function add_network_admin_menu() {
add_menu_page( __( 'Jetpack', 'jetpack' ), __( 'Jetpack', 'jetpack' ), 'jetpack_network_admin_page', 'jetpack', array( $this, 'network_admin_page' ), 'div', 3 );
add_submenu_page( 'jetpack', __( 'Jetpack Sites', 'jetpack' ), __( 'Sites', 'jetpack' ), 'jetpack_network_sites_page', 'jetpack', array( $this, 'network_admin_page' ) );
add_submenu_page( 'jetpack', __( 'Settings', 'jetpack' ), __( 'Settings', 'jetpack' ), 'jetpack_network_settings_page', 'jetpack-settings', array( $this, 'render_network_admin_settings_page' ) );
/**
* As jetpack_register_genericons is by default fired off a hook,
* the hook may have already fired by this point.
* So, let's just trigger it manually.
*/
require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
jetpack_register_genericons();
if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
}
add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
}
/**
* Adds JP menu icon
*
* @since 2.9
**/
function admin_menu_css() {
wp_enqueue_style( 'jetpack-icons' );
}
/**
* Provides functionality for the Jetpack > Sites page.
* Does not do the display!
*
* @since 2.9
*/
public function jetpack_sites_list() {
Jetpack::init();
if ( isset( $_GET['action'] ) ) {
switch ( $_GET['action'] ) {
case 'subsiteregister':
/*
* @todo check_admin_referer( 'jetpack-subsite-register' );
*/
Jetpack::log( 'subsiteregister' );
// If !$_GET['site_id'] stop registration and error
if ( ! isset( $_GET['site_id'] ) || empty( $_GET['site_id'] ) ) {
// Log error to state cookie for display later
/**
* @todo Make state messages show on Jetpack NA pages
**/
Jetpack::state( 'missing_site_id', esc_html__( 'Site ID must be provided to register a sub-site.', 'jetpack' ) );
break;
}
// Send data to register endpoint and retrieve shadow blog details
$result = $this->do_subsiteregister();
$url = $this->get_url( 'network_admin_page' );
if ( is_wp_error( $result ) ) {
$url = add_query_arg( 'action', 'connection_failed', $url );
} else {
$url = add_query_arg( 'action', 'connected', $url );
}
wp_safe_redirect( $url );
break;
case 'subsitedisconnect':
Jetpack::log( 'subsitedisconnect' );
if ( ! isset( $_GET['site_id'] ) || empty( $_GET['site_id'] ) ) {
Jetpack::state( 'missing_site_id', esc_html__( 'Site ID must be provided to disconnect a sub-site.', 'jetpack' ) );
break;
}
$this->do_subsitedisconnect();
break;
case 'connected':
case 'connection_failed':
add_action( 'jetpack_notices', array( $this, 'show_jetpack_notice' ) );
break;
}
}
}
public function show_jetpack_notice() {
if ( isset( $_GET['action'] ) && 'connected' == $_GET['action'] ) {
$notice = __( 'Site successfully connected.', 'jetpack' );
} else if ( isset( $_GET['action'] ) && 'connection_failed' == $_GET['action'] ) {
$notice = __( 'Site connection <strong>failed</strong>', 'jetpack' );
}
Jetpack::init()->load_view( 'admin/network-admin-alert.php', array( 'notice' => $notice ) );
}
/**
* Disconnect functionality for an individual site
*
* @since 2.9
* @see Jetpack_Network::jetpack_sites_list()
*/
public function do_subsitedisconnect( $site_id = null ) {
if ( ! current_user_can( 'jetpack_disconnect' ) ) {
return;
}
$site_id = ( is_null( $site_id ) ) ? $_GET['site_id'] : $site_id;
switch_to_blog( $site_id );
Jetpack::disconnect();
restore_current_blog();
}
/**
* Registers a subsite with the Jetpack servers
*
* @since 2.9
* @todo Break apart into easier to manage chunks that can be unit tested
* @see Jetpack_Network::jetpack_sites_list();
*/
public function do_subsiteregister( $site_id = null ) {
if ( ! current_user_can( 'jetpack_disconnect' ) ) {
return;
}
if ( Jetpack::is_development_mode() ) {
return;
}
$jp = Jetpack::init();
// Figure out what site we are working on
$site_id = ( is_null( $site_id ) ) ? $_GET['site_id'] : $site_id;
// Remote query timeout limit
$timeout = $jp->get_remote_query_timeout_limit();
// The blog id on WordPress.com of the primary network site
$network_wpcom_blog_id = Jetpack_Options::get_option( 'id' );
/*
* Here we need to switch to the subsite
* For the registration process we really only hijack how it
* works for an individual site and pass in some extra data here
*/
switch_to_blog( $site_id );
// Save the secrets in the subsite so when the wpcom server does a pingback it
// will be able to validate the connection
$secrets = $jp->generate_secrets( 'register' );
@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
return new Jetpack_Error( 'missing_secrets' );
}
// Gra info for gmt offset
$gmt_offset = get_option( 'gmt_offset' );
if ( ! $gmt_offset ) {
$gmt_offset = 0;
}
/*
* Get the stats_option option from the db.
* It looks like the server strips this out so maybe it is not necessary?
* Does it match the Jetpack site with the old stats plugin id?
*
* @todo Find out if sending the stats_id is necessary
*/
$stat_options = get_option( 'stats_options' );
$stat_id = $stat_options = isset( $stats_options['blog_id'] ) ? $stats_options['blog_id'] : null;
$user_id = get_current_user_id();
/**
* Both `state` and `user_id` need to be sent in the request, even though they are the same value.
* Connecting via the network admin combines `register()` and `authorize()` methods into one step,
* because we assume the main site is already authorized. `state` is used to verify the `register()`
* request, while `user_id()` is used to create the token in the `authorize()` request.
*/
$args = array(
'method' => 'POST',
'body' => array(
'network_url' => $this->get_url( 'network_admin_page' ),
'network_wpcom_blog_id' => $network_wpcom_blog_id,
'siteurl' => site_url(),
'home' => home_url(),
'gmt_offset' => $gmt_offset,
'timezone_string' => (string) get_option( 'timezone_string' ),
'site_name' => (string) get_option( 'blogname' ),
'secret_1' => $secret_1,
'secret_2' => $secret_2,
'site_lang' => get_locale(),
'timeout' => $timeout,
'stats_id' => $stat_id, // Is this still required?
'user_id' => $user_id,
'state' => $user_id
),
'headers' => array(
'Accept' => 'application/json',
),
'timeout' => $timeout,
);
// Attempt to retrieve shadow blog details
$response = Jetpack_Client::_wp_remote_request(
Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'subsiteregister' ) ), $args, true
);
/*
* $response should either be invalid or contain:
* - jetpack_id => id
* - jetpack_secret => blog_token
* - jetpack_public
*
* Store the wpcom site details
*/
$valid_response = $jp->validate_remote_register_response( $response );
if ( is_wp_error( $valid_response ) || ! $valid_response ) {
restore_current_blog();
return $valid_response;
}
// Grab the response values to work with
$code = wp_remote_retrieve_response_code( $response );
$entity = wp_remote_retrieve_body( $response );
if ( $entity ) {
$json = json_decode( $entity );
} else {
$json = false;
}
if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) ) {
restore_current_blog();
return new Jetpack_Error( 'jetpack_secret', '', $code );
}
if ( isset( $json->jetpack_public ) ) {
$jetpack_public = (int) $json->jetpack_public;
} else {
$jetpack_public = false;
}
Jetpack_Options::update_options( array(
'id' => (int) $json->jetpack_id,
'blog_token' => (string) $json->jetpack_secret,
'public' => $jetpack_public,
) );
/*
* Update the subsiteregister method on wpcom so that it also sends back the
* token in this same request
*/
$is_master_user = ! Jetpack::is_active();
Jetpack::update_user_token(
get_current_user_id(),
sprintf( '%s.%d', $json->token->secret, get_current_user_id() ),
$is_master_user
);
Jetpack::activate_default_modules();
restore_current_blog();
}
/**
* Handles the displaying of all sites on the network that are
* dis/connected to Jetpack
*
* @since 2.9
* @see Jetpack_Network::jetpack_sites_list()
*/
function network_admin_page() {
global $current_site;
$this->network_admin_page_header();
$jp = Jetpack::init();
// We should be, but ensure we are on the main blog
switch_to_blog( $current_site->blog_id );
$main_active = $jp->is_active();
restore_current_blog();
// If we are in dev mode, just show the notice and bail
if ( Jetpack::is_development_mode() ) {
Jetpack::show_development_mode_notice();
return;
}
/*
* Ensure the main blog is connected as all other subsite blog
* connections will feed off this one
*/
if ( ! $main_active ) {
$url = $this->get_url( array(
'name' => 'subsiteregister',
'site_id' => 1,
) );
$data = array( 'url' => $jp->build_connect_url() );
Jetpack::init()->load_view( 'admin/must-connect-main-blog.php', $data );
return;
}
require_once( 'class.jetpack-network-sites-list-table.php' );
$myListTable = new Jetpack_Network_Sites_List_Table();
echo '<div class="wrap"><h2>' . __( 'Sites', 'jetpack' ) . '</h2>';
echo '<form method="post">';
$myListTable->prepare_items();
$myListTable->display();
echo '</form></div>';
$this->network_admin_page_footer();
}
/**
* Stylized JP header formatting
*
* @since 2.9
*/
function network_admin_page_header() {
global $current_user;
$is_connected = Jetpack::is_active();
$data = array(
'is_connected' => $is_connected
);
Jetpack::init()->load_view( 'admin/network-admin-header.php', $data );
}
/**
* Stylized JP footer formatting
*
* @since 2.9
*/
function network_admin_page_footer() {
Jetpack::init()->load_view( 'admin/network-admin-footer.php' );
}
/**
* Fires when the Jetpack > Settings page is saved.
*
* @since 2.9
*/
public function save_network_settings_page() {
if ( ! wp_verify_nonce( $_POST['_wpnonce'], 'jetpack-network-settings' ) ) {
// no nonce, push back to settings page
wp_safe_redirect(
add_query_arg(
array( 'page' => 'jetpack-settings' ),
network_admin_url( 'admin.php' )
)
);
exit();
}
// try to save the Protect whitelist before anything else, since that action can result in errors
$whitelist = str_replace( ' ', '', $_POST['global-whitelist'] );
$whitelist = explode( PHP_EOL, $whitelist );
$result = jetpack_protect_save_whitelist( $whitelist, $global = true );
if ( is_wp_error( $result ) ) {
wp_safe_redirect(
add_query_arg(
array( 'page' => 'jetpack-settings', 'error' => 'jetpack_protect_whitelist' ),
network_admin_url( 'admin.php' )
)
);
exit();
}
/*
* Fields
*
* auto-connect - Checkbox for global Jetpack connection
* sub-site-connection-override - Allow sub-site admins to (dis)reconnect with their own Jetpack account
*/
$auto_connect = 0;
if ( isset( $_POST['auto-connect'] ) ) {
$auto_connect = 1;
}
$sub_site_connection_override = 0;
if ( isset( $_POST['sub-site-connection-override'] ) ) {
$sub_site_connection_override = 1;
}
/* Remove the toggles for 2.9, re-evaluate how they're done and added for a 3.0 release. They don't feel quite right yet.
$manage_auto_activated_modules = 0;
if ( isset( $_POST['manage_auto_activated_modules'] ) ) {
$manage_auto_activated_modules = 1;
}
$modules = array();
if ( isset( $_POST['modules'] ) ) {
$modules = $_POST['modules'];
}
*/
$data = array(
'auto-connect' => $auto_connect,
'sub-site-connection-override' => $sub_site_connection_override,
//'manage_auto_activated_modules' => $manage_auto_activated_modules,
//'modules' => $modules,
);
update_site_option( $this->settings_name, $data );
wp_safe_redirect(
add_query_arg(
array( 'page' => 'jetpack-settings', 'updated' => 'true' ),
network_admin_url( 'admin.php' )
)
);
exit();
}
public function render_network_admin_settings_page() {
$this->network_admin_page_header();
$options = wp_parse_args( get_site_option( $this->settings_name ), $this->setting_defaults );
$modules = array();
$module_slugs = Jetpack::get_available_modules();
foreach ( $module_slugs as $slug ) {
$module = Jetpack::get_module( $slug );
$module['module'] = $slug;
$modules[] = $module;
}
usort( $modules, array( 'Jetpack', 'sort_modules' ) );
if ( ! isset( $options['modules'] ) ) {
$options['modules'] = $modules;
}
$data = array(
'modules' => $modules,
'options' => $options,
'jetpack_protect_whitelist' => jetpack_protect_format_whitelist(),
);
Jetpack::init()->load_view( 'admin/network-settings.php', $data );
$this->network_admin_page_footer();
}
/**
* Updates a site wide option
*
* @since 2.9
*
* @param string $key
* @param mixed $value
*
* @return boolean
**/
public function update_option( $key, $value ) {
$options = get_site_option( $this->settings_name, $this->setting_defaults );
$options[ $key ] = $value;
return update_site_option( $this->settings_name, $options );
}
/**
* Retrieves a site wide option
*
* @since 2.9
*
* @param string $name - Name of the option in the database
**/
public function get_option( $name ) {
$options = get_site_option( $this->settings_name, $this->setting_defaults );
$options = wp_parse_args( $options, $this->setting_defaults );
if ( ! isset( $options[ $name ] ) ) {
$options[ $name ] = null;
}
return $options[ $name ];
}
}
// end class
| gpl-2.0 |
romaniabex/exchange | jsdev/bitex/ui/remittance_box.js | 2415 | goog.provide('bitex.ui.RemittanceBox');
goog.require('bitex.ui.RemittancesBox.templates');
goog.require('goog.dom');
goog.require('goog.object');
goog.require('goog.ui.Component');
goog.require('goog.ui.registry');
goog.require('goog.debug.Logger');
goog.require('goog.events.Event');
goog.require('goog.i18n.NumberFormat');
goog.require('goog.dom.classes');
/**
* @param {goog.dom.DomHelper=} opt_domHelper
* @constructor
* @extends {goog.ui.Component}
*/
bitex.ui.RemittanceBox = function(opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
};
goog.inherits(bitex.ui.RemittanceBox, goog.ui.Component);
/**
* @type {string}
*/
bitex.ui.RemittanceBox.CSS_CLASS = goog.getCssName('remittance-box');
/** @inheritDoc */
bitex.ui.RemittanceBox.prototype.getCssClass = function() {
return bitex.ui.RemittanceBox.CSS_CLASS;
};
/** @inheritDoc */
bitex.ui.RemittanceBox.prototype.createDom = function() {
var dom = this.getDomHelper();
var el = goog.soy.renderAsElement(bitex.ui.RemittancesBox.templates.RemittancesBox, {
id : this.makeId( 'remittance_box' ),
remittance_data_table : this.getModel()
});
this.setElementInternal(el);
};
/** @inheritDoc */
bitex.ui.RemittanceBox.prototype.decorateInternal = function(element) {
goog.base(this, 'decorateInternal', element);
var dom = this.getDomHelper();
return element;
};
bitex.ui.RemittanceBox.prototype.clearCurrencies = function() {
};
bitex.ui.RemittanceBox.prototype.setCurrencyFormatterFunction = function(fmt){
this.fmt_ = fmt;
};
bitex.ui.RemittanceBox.prototype.setCurrentCurrency = function(currency) {
var remittance_box_elements = goog.dom.getElementsByClass('remittance-box-table', this.getElement());
goog.array.forEach(remittance_box_elements, function(el){
goog.style.showElement(el, false);
}, this);
goog.style.showElement(goog.dom.getElement(this.makeId( 'remittance_box_' + currency ) ), true);
};
/**
* A logger to help debugging
* @type {goog.debug.Logger}
* @private
*/
bitex.ui.RemittanceBox.prototype.logger_ =
goog.debug.Logger.getLogger('bitex.ui.RemittanceBox');
/** @inheritDoc */
bitex.ui.RemittanceBox.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
var handler = this.getHandler();
};
/** @inheritDoc */
bitex.ui.RemittanceBox.prototype.exitDocument = function(){
goog.base(this, 'exitDocument');
};
| gpl-3.0 |
greasydeal/darkstar | scripts/globals/abilities/sublimation.lua | 2210 | -----------------------------------
-- Ability: Sublimation
-- Gradually creates a storage of MP while reducing your HP. The effect ends once an MP limit is reached, or your HP has gone too low. The stored MP is then transferred to your MP pool by using the ability a second time.
-- Obtained: Scholar Level 35
-- Recast Time: 30 seconds after the ability is reactivated
-- Duration (Charging): Until MP stored is 25% of Max HP or until HP = 50%
-- Duration (Charged): 2 hours
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local sublimationComplete = player:getStatusEffect(EFFECT_SUBLIMATION_COMPLETE);
local sublimationCharging = player:getStatusEffect(EFFECT_SUBLIMATION_ACTIVATED);
local mp = 0;
if sublimationComplete ~= nil then
mp = sublimationComplete:getPower();
local maxmp = player:getMaxMP();
local currmp = player:getMP();
if( mp + currmp > maxmp ) then
mp = maxmp - currmp;
end
player:addMP(mp);
player:delStatusEffectSilent(EFFECT_SUBLIMATION_COMPLETE);
ability:setMsg(451);
elseif sublimationCharging ~= nil then
mp = sublimationCharging:getPower();
local maxmp = player:getMaxMP();
local currmp = player:getMP();
if( mp + currmp > maxmp ) then
mp = maxmp - currmp;
end
player:addMP(mp);
player:delStatusEffectSilent(EFFECT_SUBLIMATION_ACTIVATED);
ability:setMsg(451);
else
local refresh = player:getStatusEffect(EFFECT_REFRESH);
if refresh == nil or refresh:getSubPower() < 3 then
player:delStatusEffect(EFFECT_REFRESH);
player:addStatusEffect(EFFECT_SUBLIMATION_ACTIVATED,0,3,7200);
else
ability:setMsg(323);
end
end
return mp;
end; | gpl-3.0 |
geoporalis/MarlinOrg | Marlin/temperature.cpp | 57810 | /**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
/**
* temperature.cpp - temperature control
*/
#include "Marlin.h"
#include "ultralcd.h"
#include "temperature.h"
#include "thermistortables.h"
#include "language.h"
#if ENABLED(BABYSTEPPING)
#include "stepper.h"
#endif
#if ENABLED(USE_WATCHDOG)
#include "watchdog.h"
#endif
#ifdef K1 // Defined in Configuration.h in the PID settings
#define K2 (1.0-K1)
#endif
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
static void* heater_ttbl_map[2] = {(void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE };
static uint8_t heater_ttbllen_map[2] = { HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN };
#else
static void* heater_ttbl_map[HOTENDS] = ARRAY_BY_HOTENDS((void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE, (void*)HEATER_2_TEMPTABLE, (void*)HEATER_3_TEMPTABLE);
static uint8_t heater_ttbllen_map[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN, HEATER_2_TEMPTABLE_LEN, HEATER_3_TEMPTABLE_LEN);
#endif
Temperature thermalManager;
// public:
float Temperature::current_temperature[HOTENDS] = { 0.0 },
Temperature::current_temperature_bed = 0.0;
int Temperature::current_temperature_raw[HOTENDS] = { 0 },
Temperature::target_temperature[HOTENDS] = { 0 },
Temperature::current_temperature_bed_raw = 0,
Temperature::target_temperature_bed = 0;
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
float Temperature::redundant_temperature = 0.0;
#endif
unsigned char Temperature::soft_pwm_bed;
#if ENABLED(FAN_SOFT_PWM)
unsigned char Temperature::fanSpeedSoftPwm[FAN_COUNT];
#endif
#if ENABLED(PIDTEMP)
#if ENABLED(PID_PARAMS_PER_HOTEND) && HOTENDS > 1
float Temperature::Kp[HOTENDS] = ARRAY_BY_HOTENDS1(DEFAULT_Kp),
Temperature::Ki[HOTENDS] = ARRAY_BY_HOTENDS1((DEFAULT_Ki) * (PID_dT)),
Temperature::Kd[HOTENDS] = ARRAY_BY_HOTENDS1((DEFAULT_Kd) / (PID_dT));
#if ENABLED(PID_EXTRUSION_SCALING)
float Temperature::Kc[HOTENDS] = ARRAY_BY_HOTENDS1(DEFAULT_Kc);
#endif
#else
float Temperature::Kp = DEFAULT_Kp,
Temperature::Ki = (DEFAULT_Ki) * (PID_dT),
Temperature::Kd = (DEFAULT_Kd) / (PID_dT);
#if ENABLED(PID_EXTRUSION_SCALING)
float Temperature::Kc = DEFAULT_Kc;
#endif
#endif
#endif
#if ENABLED(PIDTEMPBED)
float Temperature::bedKp = DEFAULT_bedKp,
Temperature::bedKi = ((DEFAULT_bedKi) * PID_dT),
Temperature::bedKd = ((DEFAULT_bedKd) / PID_dT);
#endif
#if ENABLED(BABYSTEPPING)
volatile int Temperature::babystepsTodo[3] = { 0 };
#endif
#if ENABLED(THERMAL_PROTECTION_HOTENDS) && WATCH_TEMP_PERIOD > 0
int Temperature::watch_target_temp[HOTENDS] = { 0 };
millis_t Temperature::watch_heater_next_ms[HOTENDS] = { 0 };
#endif
#if ENABLED(THERMAL_PROTECTION_BED) && WATCH_BED_TEMP_PERIOD > 0
int Temperature::watch_target_bed_temp = 0;
millis_t Temperature::watch_bed_next_ms = 0;
#endif
#if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
bool Temperature::allow_cold_extrude = false;
float Temperature::extrude_min_temp = EXTRUDE_MINTEMP;
#endif
// private:
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
int Temperature::redundant_temperature_raw = 0;
float Temperature::redundant_temperature = 0.0;
#endif
volatile bool Temperature::temp_meas_ready = false;
#if ENABLED(PIDTEMP)
float Temperature::temp_iState[HOTENDS] = { 0 },
Temperature::temp_dState[HOTENDS] = { 0 },
Temperature::pTerm[HOTENDS],
Temperature::iTerm[HOTENDS],
Temperature::dTerm[HOTENDS];
#if ENABLED(PID_EXTRUSION_SCALING)
float Temperature::cTerm[HOTENDS];
long Temperature::last_e_position;
long Temperature::lpq[LPQ_MAX_LEN];
int Temperature::lpq_ptr = 0;
#endif
float Temperature::pid_error[HOTENDS],
Temperature::temp_iState_min[HOTENDS],
Temperature::temp_iState_max[HOTENDS];
bool Temperature::pid_reset[HOTENDS];
#endif
#if ENABLED(PIDTEMPBED)
float Temperature::temp_iState_bed = { 0 },
Temperature::temp_dState_bed = { 0 },
Temperature::pTerm_bed,
Temperature::iTerm_bed,
Temperature::dTerm_bed,
Temperature::pid_error_bed,
Temperature::temp_iState_min_bed,
Temperature::temp_iState_max_bed;
#else
millis_t Temperature::next_bed_check_ms;
#endif
unsigned long Temperature::raw_temp_value[4] = { 0 };
unsigned long Temperature::raw_temp_bed_value = 0;
// Init min and max temp with extreme values to prevent false errors during startup
int Temperature::minttemp_raw[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_RAW_LO_TEMP , HEATER_1_RAW_LO_TEMP , HEATER_2_RAW_LO_TEMP, HEATER_3_RAW_LO_TEMP),
Temperature::maxttemp_raw[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_RAW_HI_TEMP , HEATER_1_RAW_HI_TEMP , HEATER_2_RAW_HI_TEMP, HEATER_3_RAW_HI_TEMP),
Temperature::minttemp[HOTENDS] = { 0 },
Temperature::maxttemp[HOTENDS] = ARRAY_BY_HOTENDS1(16383);
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
int Temperature::consecutive_low_temperature_error[HOTENDS] = { 0 };
#endif
#ifdef MILLISECONDS_PREHEAT_TIME
unsigned long Temperature::preheat_end_time[HOTENDS] = { 0 };
#endif
#ifdef BED_MINTEMP
int Temperature::bed_minttemp_raw = HEATER_BED_RAW_LO_TEMP;
#endif
#ifdef BED_MAXTEMP
int Temperature::bed_maxttemp_raw = HEATER_BED_RAW_HI_TEMP;
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
int Temperature::meas_shift_index; // Index of a delayed sample in buffer
#endif
#if HAS_AUTO_FAN
millis_t Temperature::next_auto_fan_check_ms;
#endif
unsigned char Temperature::soft_pwm[HOTENDS];
#if ENABLED(FAN_SOFT_PWM)
unsigned char Temperature::soft_pwm_fan[FAN_COUNT];
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
int Temperature::current_raw_filwidth = 0; //Holds measured filament diameter - one extruder only
#endif
#if HAS_PID_HEATING
void Temperature::PID_autotune(float temp, int hotend, int ncycles, bool set_result/*=false*/) {
float input = 0.0;
int cycles = 0;
bool heating = true;
millis_t temp_ms = millis(), t1 = temp_ms, t2 = temp_ms;
long t_high = 0, t_low = 0;
long bias, d;
float Ku, Tu;
float workKp = 0, workKi = 0, workKd = 0;
float max = 0, min = 10000;
#if HAS_AUTO_FAN
next_auto_fan_check_ms = temp_ms + 2500UL;
#endif
if (hotend >=
#if ENABLED(PIDTEMP)
HOTENDS
#else
0
#endif
|| hotend <
#if ENABLED(PIDTEMPBED)
-1
#else
0
#endif
) {
SERIAL_ECHOLN(MSG_PID_BAD_EXTRUDER_NUM);
return;
}
SERIAL_ECHOLN(MSG_PID_AUTOTUNE_START);
disable_all_heaters(); // switch off all heaters.
#if HAS_PID_FOR_BOTH
if (hotend < 0)
soft_pwm_bed = bias = d = (MAX_BED_POWER) / 2;
else
soft_pwm[hotend] = bias = d = (PID_MAX) / 2;
#elif ENABLED(PIDTEMP)
soft_pwm[hotend] = bias = d = (PID_MAX) / 2;
#else
soft_pwm_bed = bias = d = (MAX_BED_POWER) / 2;
#endif
wait_for_heatup = true;
// PID Tuning loop
while (wait_for_heatup) {
millis_t ms = millis();
if (temp_meas_ready) { // temp sample ready
updateTemperaturesFromRawValues();
input =
#if HAS_PID_FOR_BOTH
hotend < 0 ? current_temperature_bed : current_temperature[hotend]
#elif ENABLED(PIDTEMP)
current_temperature[hotend]
#else
current_temperature_bed
#endif
;
max = max(max, input);
min = min(min, input);
#if HAS_AUTO_FAN
if (ELAPSED(ms, next_auto_fan_check_ms)) {
checkExtruderAutoFans();
next_auto_fan_check_ms = ms + 2500UL;
}
#endif
if (heating && input > temp) {
if (ELAPSED(ms, t2 + 5000UL)) {
heating = false;
#if HAS_PID_FOR_BOTH
if (hotend < 0)
soft_pwm_bed = (bias - d) >> 1;
else
soft_pwm[hotend] = (bias - d) >> 1;
#elif ENABLED(PIDTEMP)
soft_pwm[hotend] = (bias - d) >> 1;
#elif ENABLED(PIDTEMPBED)
soft_pwm_bed = (bias - d) >> 1;
#endif
t1 = ms;
t_high = t1 - t2;
max = temp;
}
}
if (!heating && input < temp) {
if (ELAPSED(ms, t1 + 5000UL)) {
heating = true;
t2 = ms;
t_low = t2 - t1;
if (cycles > 0) {
long max_pow =
#if HAS_PID_FOR_BOTH
hotend < 0 ? MAX_BED_POWER : PID_MAX
#elif ENABLED(PIDTEMP)
PID_MAX
#else
MAX_BED_POWER
#endif
;
bias += (d * (t_high - t_low)) / (t_low + t_high);
bias = constrain(bias, 20, max_pow - 20);
d = (bias > max_pow / 2) ? max_pow - 1 - bias : bias;
SERIAL_PROTOCOLPAIR(MSG_BIAS, bias);
SERIAL_PROTOCOLPAIR(MSG_D, d);
SERIAL_PROTOCOLPAIR(MSG_T_MIN, min);
SERIAL_PROTOCOLPAIR(MSG_T_MAX, max);
if (cycles > 2) {
Ku = (4.0 * d) / (3.14159265 * (max - min) * 0.5);
Tu = ((float)(t_low + t_high) * 0.001);
SERIAL_PROTOCOLPAIR(MSG_KU, Ku);
SERIAL_PROTOCOLPAIR(MSG_TU, Tu);
workKp = 0.6 * Ku;
workKi = 2 * workKp / Tu;
workKd = workKp * Tu * 0.125;
SERIAL_PROTOCOLLNPGM(MSG_CLASSIC_PID);
SERIAL_PROTOCOLPAIR(MSG_KP, workKp);
SERIAL_PROTOCOLPAIR(MSG_KI, workKi);
SERIAL_PROTOCOLPAIR(MSG_KD, workKd);
/**
workKp = 0.33*Ku;
workKi = workKp/Tu;
workKd = workKp*Tu/3;
SERIAL_PROTOCOLLNPGM(" Some overshoot");
SERIAL_PROTOCOLPAIR(" Kp: ", workKp);
SERIAL_PROTOCOLPAIR(" Ki: ", workKi);
SERIAL_PROTOCOLPAIR(" Kd: ", workKd);
workKp = 0.2*Ku;
workKi = 2*workKp/Tu;
workKd = workKp*Tu/3;
SERIAL_PROTOCOLLNPGM(" No overshoot");
SERIAL_PROTOCOLPAIR(" Kp: ", workKp);
SERIAL_PROTOCOLPAIR(" Ki: ", workKi);
SERIAL_PROTOCOLPAIR(" Kd: ", workKd);
*/
}
}
#if HAS_PID_FOR_BOTH
if (hotend < 0)
soft_pwm_bed = (bias + d) >> 1;
else
soft_pwm[hotend] = (bias + d) >> 1;
#elif ENABLED(PIDTEMP)
soft_pwm[hotend] = (bias + d) >> 1;
#else
soft_pwm_bed = (bias + d) >> 1;
#endif
cycles++;
min = temp;
}
}
}
#define MAX_OVERSHOOT_PID_AUTOTUNE 20
if (input > temp + MAX_OVERSHOOT_PID_AUTOTUNE) {
SERIAL_PROTOCOLLNPGM(MSG_PID_TEMP_TOO_HIGH);
return;
}
// Every 2 seconds...
if (ELAPSED(ms, temp_ms + 2000UL)) {
#if HAS_TEMP_HOTEND || HAS_TEMP_BED
print_heaterstates();
SERIAL_EOL;
#endif
temp_ms = ms;
} // every 2 seconds
// Over 2 minutes?
if (((ms - t1) + (ms - t2)) > (10L * 60L * 1000L * 2L)) {
SERIAL_PROTOCOLLNPGM(MSG_PID_TIMEOUT);
return;
}
if (cycles > ncycles) {
SERIAL_PROTOCOLLNPGM(MSG_PID_AUTOTUNE_FINISHED);
#if HAS_PID_FOR_BOTH
const char* estring = hotend < 0 ? "bed" : "";
SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Kp ", workKp);
SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Ki ", workKi);
SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Kd ", workKd);
#elif ENABLED(PIDTEMP)
SERIAL_PROTOCOLPAIR("#define DEFAULT_Kp ", workKp);
SERIAL_PROTOCOLPAIR("#define DEFAULT_Ki ", workKi);
SERIAL_PROTOCOLPAIR("#define DEFAULT_Kd ", workKd);
#else
SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKp ", workKp);
SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKi ", workKi);
SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKd ", workKd);
#endif
#define _SET_BED_PID() \
bedKp = workKp; \
bedKi = scalePID_i(workKi); \
bedKd = scalePID_d(workKd); \
updatePID()
#define _SET_EXTRUDER_PID() \
PID_PARAM(Kp, hotend) = workKp; \
PID_PARAM(Ki, hotend) = scalePID_i(workKi); \
PID_PARAM(Kd, hotend) = scalePID_d(workKd); \
updatePID()
// Use the result? (As with "M303 U1")
if (set_result) {
#if HAS_PID_FOR_BOTH
if (hotend < 0) {
_SET_BED_PID();
}
else {
_SET_EXTRUDER_PID();
}
#elif ENABLED(PIDTEMP)
_SET_EXTRUDER_PID();
#else
_SET_BED_PID();
#endif
}
return;
}
lcd_update();
}
if (!wait_for_heatup) disable_all_heaters();
}
#endif // HAS_PID_HEATING
/**
* Class and Instance Methods
*/
Temperature::Temperature() { }
void Temperature::updatePID() {
#if ENABLED(PIDTEMP)
#if ENABLED(PID_EXTRUSION_SCALING)
last_e_position = 0;
#endif
HOTEND_LOOP() {
temp_iState_max[e] = (PID_INTEGRAL_DRIVE_MAX) / PID_PARAM(Ki, e);
}
#endif
#if ENABLED(PIDTEMPBED)
temp_iState_max_bed = (PID_BED_INTEGRAL_DRIVE_MAX) / bedKi;
#endif
}
int Temperature::getHeaterPower(int heater) {
return heater < 0 ? soft_pwm_bed : soft_pwm[heater];
}
#if HAS_AUTO_FAN
void Temperature::checkExtruderAutoFans() {
const int8_t fanPin[] = { EXTRUDER_0_AUTO_FAN_PIN, EXTRUDER_1_AUTO_FAN_PIN, EXTRUDER_2_AUTO_FAN_PIN, EXTRUDER_3_AUTO_FAN_PIN };
const int fanBit[] = { 0,
EXTRUDER_1_AUTO_FAN_PIN == EXTRUDER_0_AUTO_FAN_PIN ? 0 : 1,
EXTRUDER_2_AUTO_FAN_PIN == EXTRUDER_0_AUTO_FAN_PIN ? 0 :
EXTRUDER_2_AUTO_FAN_PIN == EXTRUDER_1_AUTO_FAN_PIN ? 1 : 2,
EXTRUDER_3_AUTO_FAN_PIN == EXTRUDER_0_AUTO_FAN_PIN ? 0 :
EXTRUDER_3_AUTO_FAN_PIN == EXTRUDER_1_AUTO_FAN_PIN ? 1 :
EXTRUDER_3_AUTO_FAN_PIN == EXTRUDER_2_AUTO_FAN_PIN ? 2 : 3
};
uint8_t fanState = 0;
HOTEND_LOOP() {
if (current_temperature[e] > EXTRUDER_AUTO_FAN_TEMPERATURE)
SBI(fanState, fanBit[e]);
}
uint8_t fanDone = 0;
for (int8_t f = 0; f <= 3; f++) {
int8_t pin = fanPin[f];
if (pin >= 0 && !TEST(fanDone, fanBit[f])) {
unsigned char newFanSpeed = TEST(fanState, fanBit[f]) ? EXTRUDER_AUTO_FAN_SPEED : 0;
// this idiom allows both digital and PWM fan outputs (see M42 handling).
digitalWrite(pin, newFanSpeed);
analogWrite(pin, newFanSpeed);
SBI(fanDone, fanBit[f]);
}
}
}
#endif // HAS_AUTO_FAN
//
// Temperature Error Handlers
//
void Temperature::_temp_error(int e, const char* serial_msg, const char* lcd_msg) {
static bool killed = false;
if (IsRunning()) {
SERIAL_ERROR_START;
serialprintPGM(serial_msg);
SERIAL_ERRORPGM(MSG_STOPPED_HEATER);
if (e >= 0) SERIAL_ERRORLN((int)e); else SERIAL_ERRORLNPGM(MSG_HEATER_BED);
}
#if DISABLED(BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE)
if (!killed) {
Running = false;
killed = true;
kill(lcd_msg);
}
else
disable_all_heaters(); // paranoia
#endif
}
void Temperature::max_temp_error(uint8_t e) {
#if HOTENDS == 1
UNUSED(e);
#endif
_temp_error(HOTEND_INDEX, PSTR(MSG_T_MAXTEMP), PSTR(MSG_ERR_MAXTEMP));
}
void Temperature::min_temp_error(uint8_t e) {
#if HOTENDS == 1
UNUSED(e);
#endif
_temp_error(HOTEND_INDEX, PSTR(MSG_T_MINTEMP), PSTR(MSG_ERR_MINTEMP));
}
float Temperature::get_pid_output(int e) {
#if HOTENDS == 1
UNUSED(e);
#define _HOTEND_TEST true
#else
#define _HOTEND_TEST e == active_extruder
#endif
float pid_output;
#if ENABLED(PIDTEMP)
#if DISABLED(PID_OPENLOOP)
pid_error[HOTEND_INDEX] = target_temperature[HOTEND_INDEX] - current_temperature[HOTEND_INDEX];
dTerm[HOTEND_INDEX] = K2 * PID_PARAM(Kd, HOTEND_INDEX) * (current_temperature[HOTEND_INDEX] - temp_dState[HOTEND_INDEX]) + K1 * dTerm[HOTEND_INDEX];
temp_dState[HOTEND_INDEX] = current_temperature[HOTEND_INDEX];
if (pid_error[HOTEND_INDEX] > PID_FUNCTIONAL_RANGE) {
pid_output = BANG_MAX;
pid_reset[HOTEND_INDEX] = true;
}
else if (pid_error[HOTEND_INDEX] < -(PID_FUNCTIONAL_RANGE) || target_temperature[HOTEND_INDEX] == 0) {
pid_output = 0;
pid_reset[HOTEND_INDEX] = true;
}
else {
if (pid_reset[HOTEND_INDEX]) {
temp_iState[HOTEND_INDEX] = 0.0;
pid_reset[HOTEND_INDEX] = false;
}
pTerm[HOTEND_INDEX] = PID_PARAM(Kp, HOTEND_INDEX) * pid_error[HOTEND_INDEX];
temp_iState[HOTEND_INDEX] += pid_error[HOTEND_INDEX];
temp_iState[HOTEND_INDEX] = constrain(temp_iState[HOTEND_INDEX], temp_iState_min[HOTEND_INDEX], temp_iState_max[HOTEND_INDEX]);
iTerm[HOTEND_INDEX] = PID_PARAM(Ki, HOTEND_INDEX) * temp_iState[HOTEND_INDEX];
pid_output = pTerm[HOTEND_INDEX] + iTerm[HOTEND_INDEX] - dTerm[HOTEND_INDEX];
#if ENABLED(PID_EXTRUSION_SCALING)
cTerm[HOTEND_INDEX] = 0;
if (_HOTEND_TEST) {
long e_position = stepper.position(E_AXIS);
if (e_position > last_e_position) {
lpq[lpq_ptr] = e_position - last_e_position;
last_e_position = e_position;
}
else {
lpq[lpq_ptr] = 0;
}
if (++lpq_ptr >= lpq_len) lpq_ptr = 0;
cTerm[HOTEND_INDEX] = (lpq[lpq_ptr] * planner.steps_to_mm[E_AXIS]) * PID_PARAM(Kc, HOTEND_INDEX);
pid_output += cTerm[HOTEND_INDEX];
}
#endif // PID_EXTRUSION_SCALING
if (pid_output > PID_MAX) {
if (pid_error[HOTEND_INDEX] > 0) temp_iState[HOTEND_INDEX] -= pid_error[HOTEND_INDEX]; // conditional un-integration
pid_output = PID_MAX;
}
else if (pid_output < 0) {
if (pid_error[HOTEND_INDEX] < 0) temp_iState[HOTEND_INDEX] -= pid_error[HOTEND_INDEX]; // conditional un-integration
pid_output = 0;
}
}
#else
pid_output = constrain(target_temperature[HOTEND_INDEX], 0, PID_MAX);
#endif //PID_OPENLOOP
#if ENABLED(PID_DEBUG)
SERIAL_ECHO_START;
SERIAL_ECHOPAIR(MSG_PID_DEBUG, HOTEND_INDEX);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_INPUT, current_temperature[HOTEND_INDEX]);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_OUTPUT, pid_output);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_PTERM, pTerm[HOTEND_INDEX]);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_ITERM, iTerm[HOTEND_INDEX]);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_DTERM, dTerm[HOTEND_INDEX]);
#if ENABLED(PID_EXTRUSION_SCALING)
SERIAL_ECHOPAIR(MSG_PID_DEBUG_CTERM, cTerm[HOTEND_INDEX]);
#endif
SERIAL_EOL;
#endif //PID_DEBUG
#else /* PID off */
pid_output = (current_temperature[HOTEND_INDEX] < target_temperature[HOTEND_INDEX]) ? PID_MAX : 0;
#endif
return pid_output;
}
#if ENABLED(PIDTEMPBED)
float Temperature::get_pid_output_bed() {
float pid_output;
#if DISABLED(PID_OPENLOOP)
pid_error_bed = target_temperature_bed - current_temperature_bed;
pTerm_bed = bedKp * pid_error_bed;
temp_iState_bed += pid_error_bed;
temp_iState_bed = constrain(temp_iState_bed, temp_iState_min_bed, temp_iState_max_bed);
iTerm_bed = bedKi * temp_iState_bed;
dTerm_bed = K2 * bedKd * (current_temperature_bed - temp_dState_bed) + K1 * dTerm_bed;
temp_dState_bed = current_temperature_bed;
pid_output = pTerm_bed + iTerm_bed - dTerm_bed;
if (pid_output > MAX_BED_POWER) {
if (pid_error_bed > 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
pid_output = MAX_BED_POWER;
}
else if (pid_output < 0) {
if (pid_error_bed < 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
pid_output = 0;
}
#else
pid_output = constrain(target_temperature_bed, 0, MAX_BED_POWER);
#endif // PID_OPENLOOP
#if ENABLED(PID_BED_DEBUG)
SERIAL_ECHO_START;
SERIAL_ECHOPGM(" PID_BED_DEBUG ");
SERIAL_ECHOPGM(": Input ");
SERIAL_ECHO(current_temperature_bed);
SERIAL_ECHOPGM(" Output ");
SERIAL_ECHO(pid_output);
SERIAL_ECHOPGM(" pTerm ");
SERIAL_ECHO(pTerm_bed);
SERIAL_ECHOPGM(" iTerm ");
SERIAL_ECHO(iTerm_bed);
SERIAL_ECHOPGM(" dTerm ");
SERIAL_ECHOLN(dTerm_bed);
#endif //PID_BED_DEBUG
return pid_output;
}
#endif //PIDTEMPBED
/**
* Manage heating activities for extruder hot-ends and a heated bed
* - Acquire updated temperature readings
* - Also resets the watchdog timer
* - Invoke thermal runaway protection
* - Manage extruder auto-fan
* - Apply filament width to the extrusion rate (may move)
* - Update the heated bed PID output value
*/
void Temperature::manage_heater() {
if (!temp_meas_ready) return;
updateTemperaturesFromRawValues(); // also resets the watchdog
#if ENABLED(HEATER_0_USES_MAX6675)
float ct = current_temperature[0];
if (ct > min(HEATER_0_MAXTEMP, 1023)) max_temp_error(0);
if (ct < max(HEATER_0_MINTEMP, 0.01)) min_temp_error(0);
#endif
#if (ENABLED(THERMAL_PROTECTION_HOTENDS) && WATCH_TEMP_PERIOD > 0) || (ENABLED(THERMAL_PROTECTION_BED) && WATCH_BED_TEMP_PERIOD > 0) || DISABLED(PIDTEMPBED) || HAS_AUTO_FAN
millis_t ms = millis();
#endif
// Loop through all hotends
HOTEND_LOOP() {
#if ENABLED(THERMAL_PROTECTION_HOTENDS)
thermal_runaway_protection(&thermal_runaway_state_machine[e], &thermal_runaway_timer[e], current_temperature[e], target_temperature[e], e, THERMAL_PROTECTION_PERIOD, THERMAL_PROTECTION_HYSTERESIS);
#endif
float pid_output = get_pid_output(e);
// Check if temperature is within the correct range
soft_pwm[e] = (current_temperature[e] > minttemp[e] || is_preheating(e)) && current_temperature[e] < maxttemp[e] ? (int)pid_output >> 1 : 0;
// Check if the temperature is failing to increase
#if ENABLED(THERMAL_PROTECTION_HOTENDS) && WATCH_TEMP_PERIOD > 0
// Is it time to check this extruder's heater?
if (watch_heater_next_ms[e] && ELAPSED(ms, watch_heater_next_ms[e])) {
// Has it failed to increase enough?
if (degHotend(e) < watch_target_temp[e]) {
// Stop!
_temp_error(e, PSTR(MSG_T_HEATING_FAILED), PSTR(MSG_HEATING_FAILED_LCD));
}
else {
// Start again if the target is still far off
start_watching_heater(e);
}
}
#endif // THERMAL_PROTECTION_HOTENDS
// Check if the temperature is failing to increase
#if ENABLED(THERMAL_PROTECTION_BED) && WATCH_BED_TEMP_PERIOD > 0
// Is it time to check the bed?
if (watch_bed_next_ms && ELAPSED(ms, watch_bed_next_ms)) {
// Has it failed to increase enough?
if (degBed() < watch_target_bed_temp) {
// Stop!
_temp_error(-1, PSTR(MSG_T_HEATING_FAILED), PSTR(MSG_HEATING_FAILED_LCD));
}
else {
// Start again if the target is still far off
start_watching_bed();
}
}
#endif // THERMAL_PROTECTION_HOTENDS
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
if (fabs(current_temperature[0] - redundant_temperature) > MAX_REDUNDANT_TEMP_SENSOR_DIFF) {
_temp_error(0, PSTR(MSG_REDUNDANCY), PSTR(MSG_ERR_REDUNDANT_TEMP));
}
#endif
} // Hotends Loop
#if HAS_AUTO_FAN
if (ELAPSED(ms, next_auto_fan_check_ms)) { // only need to check fan state very infrequently
checkExtruderAutoFans();
next_auto_fan_check_ms = ms + 2500UL;
}
#endif
// Control the extruder rate based on the width sensor
#if ENABLED(FILAMENT_WIDTH_SENSOR)
if (filament_sensor) {
meas_shift_index = filwidth_delay_index1 - meas_delay_cm;
if (meas_shift_index < 0) meas_shift_index += MAX_MEASUREMENT_DELAY + 1; //loop around buffer if needed
// Get the delayed info and add 100 to reconstitute to a percent of
// the nominal filament diameter then square it to get an area
meas_shift_index = constrain(meas_shift_index, 0, MAX_MEASUREMENT_DELAY);
float vm = pow((measurement_delay[meas_shift_index] + 100.0) * 0.01, 2);
NOLESS(vm, 0.01);
volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = vm;
}
#endif //FILAMENT_WIDTH_SENSOR
#if DISABLED(PIDTEMPBED)
if (PENDING(ms, next_bed_check_ms)) return;
next_bed_check_ms = ms + BED_CHECK_INTERVAL;
#endif
#if TEMP_SENSOR_BED != 0
#if HAS_THERMALLY_PROTECTED_BED
thermal_runaway_protection(&thermal_runaway_bed_state_machine, &thermal_runaway_bed_timer, current_temperature_bed, target_temperature_bed, -1, THERMAL_PROTECTION_BED_PERIOD, THERMAL_PROTECTION_BED_HYSTERESIS);
#endif
#if ENABLED(PIDTEMPBED)
float pid_output = get_pid_output_bed();
soft_pwm_bed = current_temperature_bed > BED_MINTEMP && current_temperature_bed < BED_MAXTEMP ? (int)pid_output >> 1 : 0;
#elif ENABLED(BED_LIMIT_SWITCHING)
// Check if temperature is within the correct band
if (current_temperature_bed > BED_MINTEMP && current_temperature_bed < BED_MAXTEMP) {
if (current_temperature_bed >= target_temperature_bed + BED_HYSTERESIS)
soft_pwm_bed = 0;
else if (current_temperature_bed <= target_temperature_bed - (BED_HYSTERESIS))
soft_pwm_bed = MAX_BED_POWER >> 1;
}
else {
soft_pwm_bed = 0;
WRITE_HEATER_BED(LOW);
}
#else // !PIDTEMPBED && !BED_LIMIT_SWITCHING
// Check if temperature is within the correct range
if (current_temperature_bed > BED_MINTEMP && current_temperature_bed < BED_MAXTEMP) {
soft_pwm_bed = current_temperature_bed < target_temperature_bed ? MAX_BED_POWER >> 1 : 0;
}
else {
soft_pwm_bed = 0;
WRITE_HEATER_BED(LOW);
}
#endif
#endif //TEMP_SENSOR_BED != 0
}
#define PGM_RD_W(x) (short)pgm_read_word(&x)
// Derived from RepRap FiveD extruder::getTemperature()
// For hot end temperature measurement.
float Temperature::analog2temp(int raw, uint8_t e) {
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
if (e > HOTENDS)
#else
if (e >= HOTENDS)
#endif
{
SERIAL_ERROR_START;
SERIAL_ERROR((int)e);
SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER_NUM);
kill(PSTR(MSG_KILLED));
return 0.0;
}
#if ENABLED(HEATER_0_USES_MAX6675)
if (e == 0) return 0.25 * raw;
#endif
if (heater_ttbl_map[e] != NULL) {
float celsius = 0;
uint8_t i;
short(*tt)[][2] = (short(*)[][2])(heater_ttbl_map[e]);
for (i = 1; i < heater_ttbllen_map[e]; i++) {
if (PGM_RD_W((*tt)[i][0]) > raw) {
celsius = PGM_RD_W((*tt)[i - 1][1]) +
(raw - PGM_RD_W((*tt)[i - 1][0])) *
(float)(PGM_RD_W((*tt)[i][1]) - PGM_RD_W((*tt)[i - 1][1])) /
(float)(PGM_RD_W((*tt)[i][0]) - PGM_RD_W((*tt)[i - 1][0]));
break;
}
}
// Overflow: Set to last value in the table
if (i == heater_ttbllen_map[e]) celsius = PGM_RD_W((*tt)[i - 1][1]);
return celsius;
}
return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN)) + TEMP_SENSOR_AD595_OFFSET;
}
// Derived from RepRap FiveD extruder::getTemperature()
// For bed temperature measurement.
float Temperature::analog2tempBed(int raw) {
#if ENABLED(BED_USES_THERMISTOR)
float celsius = 0;
byte i;
for (i = 1; i < BEDTEMPTABLE_LEN; i++) {
if (PGM_RD_W(BEDTEMPTABLE[i][0]) > raw) {
celsius = PGM_RD_W(BEDTEMPTABLE[i - 1][1]) +
(raw - PGM_RD_W(BEDTEMPTABLE[i - 1][0])) *
(float)(PGM_RD_W(BEDTEMPTABLE[i][1]) - PGM_RD_W(BEDTEMPTABLE[i - 1][1])) /
(float)(PGM_RD_W(BEDTEMPTABLE[i][0]) - PGM_RD_W(BEDTEMPTABLE[i - 1][0]));
break;
}
}
// Overflow: Set to last value in the table
if (i == BEDTEMPTABLE_LEN) celsius = PGM_RD_W(BEDTEMPTABLE[i - 1][1]);
return celsius;
#elif defined(BED_USES_AD595)
return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN)) + TEMP_SENSOR_AD595_OFFSET;
#else
UNUSED(raw);
return 0;
#endif
}
/**
* Get the raw values into the actual temperatures.
* The raw values are created in interrupt context,
* and this function is called from normal context
* as it would block the stepper routine.
*/
void Temperature::updateTemperaturesFromRawValues() {
#if ENABLED(HEATER_0_USES_MAX6675)
current_temperature_raw[0] = read_max6675();
#endif
HOTEND_LOOP() {
current_temperature[e] = Temperature::analog2temp(current_temperature_raw[e], e);
}
current_temperature_bed = Temperature::analog2tempBed(current_temperature_bed_raw);
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
redundant_temperature = Temperature::analog2temp(redundant_temperature_raw, 1);
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
filament_width_meas = analog2widthFil();
#endif
#if ENABLED(USE_WATCHDOG)
// Reset the watchdog after we know we have a temperature measurement.
watchdog_reset();
#endif
CRITICAL_SECTION_START;
temp_meas_ready = false;
CRITICAL_SECTION_END;
}
#if ENABLED(FILAMENT_WIDTH_SENSOR)
// Convert raw Filament Width to millimeters
float Temperature::analog2widthFil() {
return current_raw_filwidth / 16383.0 * 5.0;
//return current_raw_filwidth;
}
// Convert raw Filament Width to a ratio
int Temperature::widthFil_to_size_ratio() {
float temp = filament_width_meas;
if (temp < MEASURED_LOWER_LIMIT) temp = filament_width_nominal; //assume sensor cut out
else NOMORE(temp, MEASURED_UPPER_LIMIT);
return filament_width_nominal / temp * 100;
}
#endif
/**
* Initialize the temperature manager
* The manager is implemented by periodic calls to manage_heater()
*/
void Temperature::init() {
#if MB(RUMBA) && ((TEMP_SENSOR_0==-1)||(TEMP_SENSOR_1==-1)||(TEMP_SENSOR_2==-1)||(TEMP_SENSOR_BED==-1))
//disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
MCUCR = _BV(JTD);
MCUCR = _BV(JTD);
#endif
// Finish init of mult hotend arrays
HOTEND_LOOP() {
// populate with the first value
maxttemp[e] = maxttemp[0];
#if ENABLED(PIDTEMP)
temp_iState_min[e] = 0.0;
temp_iState_max[e] = (PID_INTEGRAL_DRIVE_MAX) / PID_PARAM(Ki, e);
#if ENABLED(PID_EXTRUSION_SCALING)
last_e_position = 0;
#endif
#endif //PIDTEMP
#if ENABLED(PIDTEMPBED)
temp_iState_min_bed = 0.0;
temp_iState_max_bed = (PID_BED_INTEGRAL_DRIVE_MAX) / bedKi;
#endif //PIDTEMPBED
}
#if ENABLED(PIDTEMP) && ENABLED(PID_EXTRUSION_SCALING)
last_e_position = 0;
#endif
#if HAS_HEATER_0
SET_OUTPUT(HEATER_0_PIN);
#endif
#if HAS_HEATER_1
SET_OUTPUT(HEATER_1_PIN);
#endif
#if HAS_HEATER_2
SET_OUTPUT(HEATER_2_PIN);
#endif
#if HAS_HEATER_3
SET_OUTPUT(HEATER_3_PIN);
#endif
#if HAS_HEATER_BED
SET_OUTPUT(HEATER_BED_PIN);
#endif
#if ENABLED(FAST_PWM_FAN) || ENABLED(FAN_SOFT_PWM)
#if HAS_FAN0
SET_OUTPUT(FAN_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#if ENABLED(FAN_SOFT_PWM)
soft_pwm_fan[0] = fanSpeedSoftPwm[0] / 2;
#endif
#endif
#if HAS_FAN1
SET_OUTPUT(FAN1_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(FAN1_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#if ENABLED(FAN_SOFT_PWM)
soft_pwm_fan[1] = fanSpeedSoftPwm[1] / 2;
#endif
#endif
#if HAS_FAN2
SET_OUTPUT(FAN2_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(FAN2_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#if ENABLED(FAN_SOFT_PWM)
soft_pwm_fan[2] = fanSpeedSoftPwm[2] / 2;
#endif
#endif
#endif // FAST_PWM_FAN || FAN_SOFT_PWM
#if ENABLED(HEATER_0_USES_MAX6675)
#if DISABLED(SDSUPPORT)
OUT_WRITE(SCK_PIN, LOW);
OUT_WRITE(MOSI_PIN, HIGH);
OUT_WRITE(MISO_PIN, HIGH);
#else
OUT_WRITE(SS_PIN, HIGH);
#endif
OUT_WRITE(MAX6675_SS, HIGH);
#endif //HEATER_0_USES_MAX6675
#ifdef DIDR2
#define ANALOG_SELECT(pin) do{ if (pin < 8) SBI(DIDR0, pin); else SBI(DIDR2, pin - 8); }while(0)
#else
#define ANALOG_SELECT(pin) do{ SBI(DIDR0, pin); }while(0)
#endif
// Set analog inputs
ADCSRA = _BV(ADEN) | _BV(ADSC) | _BV(ADIF) | 0x07;
DIDR0 = 0;
#ifdef DIDR2
DIDR2 = 0;
#endif
#if HAS_TEMP_0
ANALOG_SELECT(TEMP_0_PIN);
#endif
#if HAS_TEMP_1
ANALOG_SELECT(TEMP_1_PIN);
#endif
#if HAS_TEMP_2
ANALOG_SELECT(TEMP_2_PIN);
#endif
#if HAS_TEMP_3
ANALOG_SELECT(TEMP_3_PIN);
#endif
#if HAS_TEMP_BED
ANALOG_SELECT(TEMP_BED_PIN);
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
ANALOG_SELECT(FILWIDTH_PIN);
#endif
#if HAS_AUTO_FAN_0
pinMode(EXTRUDER_0_AUTO_FAN_PIN, OUTPUT);
#endif
#if HAS_AUTO_FAN_1 && (EXTRUDER_1_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN)
pinMode(EXTRUDER_1_AUTO_FAN_PIN, OUTPUT);
#endif
#if HAS_AUTO_FAN_2 && (EXTRUDER_2_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN) && (EXTRUDER_2_AUTO_FAN_PIN != EXTRUDER_1_AUTO_FAN_PIN)
pinMode(EXTRUDER_2_AUTO_FAN_PIN, OUTPUT);
#endif
#if HAS_AUTO_FAN_3 && (EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN) && (EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_1_AUTO_FAN_PIN) && (EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_2_AUTO_FAN_PIN)
pinMode(EXTRUDER_3_AUTO_FAN_PIN, OUTPUT);
#endif
// Use timer0 for temperature measurement
// Interleave temperature interrupt with millies interrupt
OCR0B = 128;
SBI(TIMSK0, OCIE0B);
// Wait for temperature measurement to settle
delay(250);
#define TEMP_MIN_ROUTINE(NR) \
minttemp[NR] = HEATER_ ## NR ## _MINTEMP; \
while(analog2temp(minttemp_raw[NR], NR) < HEATER_ ## NR ## _MINTEMP) { \
if (HEATER_ ## NR ## _RAW_LO_TEMP < HEATER_ ## NR ## _RAW_HI_TEMP) \
minttemp_raw[NR] += OVERSAMPLENR; \
else \
minttemp_raw[NR] -= OVERSAMPLENR; \
}
#define TEMP_MAX_ROUTINE(NR) \
maxttemp[NR] = HEATER_ ## NR ## _MAXTEMP; \
while(analog2temp(maxttemp_raw[NR], NR) > HEATER_ ## NR ## _MAXTEMP) { \
if (HEATER_ ## NR ## _RAW_LO_TEMP < HEATER_ ## NR ## _RAW_HI_TEMP) \
maxttemp_raw[NR] -= OVERSAMPLENR; \
else \
maxttemp_raw[NR] += OVERSAMPLENR; \
}
#ifdef HEATER_0_MINTEMP
TEMP_MIN_ROUTINE(0);
#endif
#ifdef HEATER_0_MAXTEMP
TEMP_MAX_ROUTINE(0);
#endif
#if HOTENDS > 1
#ifdef HEATER_1_MINTEMP
TEMP_MIN_ROUTINE(1);
#endif
#ifdef HEATER_1_MAXTEMP
TEMP_MAX_ROUTINE(1);
#endif
#if HOTENDS > 2
#ifdef HEATER_2_MINTEMP
TEMP_MIN_ROUTINE(2);
#endif
#ifdef HEATER_2_MAXTEMP
TEMP_MAX_ROUTINE(2);
#endif
#if HOTENDS > 3
#ifdef HEATER_3_MINTEMP
TEMP_MIN_ROUTINE(3);
#endif
#ifdef HEATER_3_MAXTEMP
TEMP_MAX_ROUTINE(3);
#endif
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#ifdef BED_MINTEMP
while(analog2tempBed(bed_minttemp_raw) < BED_MINTEMP) {
#if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
bed_minttemp_raw += OVERSAMPLENR;
#else
bed_minttemp_raw -= OVERSAMPLENR;
#endif
}
#endif //BED_MINTEMP
#ifdef BED_MAXTEMP
while (analog2tempBed(bed_maxttemp_raw) > BED_MAXTEMP) {
#if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
bed_maxttemp_raw -= OVERSAMPLENR;
#else
bed_maxttemp_raw += OVERSAMPLENR;
#endif
}
#endif //BED_MAXTEMP
}
#if ENABLED(THERMAL_PROTECTION_HOTENDS) && WATCH_TEMP_PERIOD > 0
/**
* Start Heating Sanity Check for hotends that are below
* their target temperature by a configurable margin.
* This is called when the temperature is set. (M104, M109)
*/
void Temperature::start_watching_heater(uint8_t e) {
#if HOTENDS == 1
UNUSED(e);
#endif
if (degHotend(HOTEND_INDEX) < degTargetHotend(HOTEND_INDEX) - (WATCH_TEMP_INCREASE + TEMP_HYSTERESIS + 1)) {
watch_target_temp[HOTEND_INDEX] = degHotend(HOTEND_INDEX) + WATCH_TEMP_INCREASE;
watch_heater_next_ms[HOTEND_INDEX] = millis() + (WATCH_TEMP_PERIOD) * 1000UL;
}
else
watch_heater_next_ms[HOTEND_INDEX] = 0;
}
#endif
#if ENABLED(THERMAL_PROTECTION_BED) && WATCH_BED_TEMP_PERIOD > 0
/**
* Start Heating Sanity Check for hotends that are below
* their target temperature by a configurable margin.
* This is called when the temperature is set. (M140, M190)
*/
void Temperature::start_watching_bed() {
if (degBed() < degTargetBed() - (WATCH_BED_TEMP_INCREASE + TEMP_BED_HYSTERESIS + 1)) {
watch_target_bed_temp = degBed() + WATCH_BED_TEMP_INCREASE;
watch_bed_next_ms = millis() + (WATCH_BED_TEMP_PERIOD) * 1000UL;
}
else
watch_bed_next_ms = 0;
}
#endif
#if ENABLED(THERMAL_PROTECTION_HOTENDS) || HAS_THERMALLY_PROTECTED_BED
#if ENABLED(THERMAL_PROTECTION_HOTENDS)
Temperature::TRState Temperature::thermal_runaway_state_machine[HOTENDS] = { TRInactive };
millis_t Temperature::thermal_runaway_timer[HOTENDS] = { 0 };
#endif
#if HAS_THERMALLY_PROTECTED_BED
Temperature::TRState Temperature::thermal_runaway_bed_state_machine = TRInactive;
millis_t Temperature::thermal_runaway_bed_timer;
#endif
void Temperature::thermal_runaway_protection(Temperature::TRState* state, millis_t* timer, float temperature, float target_temperature, int heater_id, int period_seconds, int hysteresis_degc) {
static float tr_target_temperature[HOTENDS + 1] = { 0.0 };
/**
SERIAL_ECHO_START;
SERIAL_ECHOPGM("Thermal Thermal Runaway Running. Heater ID: ");
if (heater_id < 0) SERIAL_ECHOPGM("bed"); else SERIAL_ECHO(heater_id);
SERIAL_ECHOPAIR(" ; State:", *state);
SERIAL_ECHOPAIR(" ; Timer:", *timer);
SERIAL_ECHOPAIR(" ; Temperature:", temperature);
SERIAL_ECHOPAIR(" ; Target Temp:", target_temperature);
SERIAL_EOL;
*/
int heater_index = heater_id >= 0 ? heater_id : HOTENDS;
// If the target temperature changes, restart
if (tr_target_temperature[heater_index] != target_temperature) {
tr_target_temperature[heater_index] = target_temperature;
*state = target_temperature > 0 ? TRFirstHeating : TRInactive;
}
switch (*state) {
// Inactive state waits for a target temperature to be set
case TRInactive: break;
// When first heating, wait for the temperature to be reached then go to Stable state
case TRFirstHeating:
if (temperature < tr_target_temperature[heater_index]) break;
*state = TRStable;
// While the temperature is stable watch for a bad temperature
case TRStable:
if (temperature < tr_target_temperature[heater_index] - hysteresis_degc && ELAPSED(millis(), *timer))
*state = TRRunaway;
else {
*timer = millis() + period_seconds * 1000UL;
break;
}
case TRRunaway:
_temp_error(heater_id, PSTR(MSG_T_THERMAL_RUNAWAY), PSTR(MSG_THERMAL_RUNAWAY));
}
}
#endif // THERMAL_PROTECTION_HOTENDS || THERMAL_PROTECTION_BED
void Temperature::disable_all_heaters() {
HOTEND_LOOP() setTargetHotend(0, e);
setTargetBed(0);
// If all heaters go down then for sure our print job has stopped
print_job_timer.stop();
#define DISABLE_HEATER(NR) { \
setTargetHotend(0, NR); \
soft_pwm[NR] = 0; \
WRITE_HEATER_ ## NR (LOW); \
}
#if HAS_TEMP_HOTEND
setTargetHotend(0, 0);
soft_pwm[0] = 0;
WRITE_HEATER_0P(LOW); // Should HEATERS_PARALLEL apply here? Then change to DISABLE_HEATER(0)
#endif
#if HOTENDS > 1 && HAS_TEMP_1
DISABLE_HEATER(1);
#endif
#if HOTENDS > 2 && HAS_TEMP_2
DISABLE_HEATER(2);
#endif
#if HOTENDS > 3 && HAS_TEMP_3
DISABLE_HEATER(3);
#endif
#if HAS_TEMP_BED
target_temperature_bed = 0;
soft_pwm_bed = 0;
#if HAS_HEATER_BED
WRITE_HEATER_BED(LOW);
#endif
#endif
}
#if ENABLED(HEATER_0_USES_MAX6675)
#define MAX6675_HEAT_INTERVAL 250u
#if ENABLED(MAX6675_IS_MAX31855)
uint32_t max6675_temp = 2000;
#define MAX6675_ERROR_MASK 7
#define MAX6675_DISCARD_BITS 18
#define MAX6675_SPEED_BITS (_BV(SPR1)) // clock ÷ 64
#else
uint16_t max6675_temp = 2000;
#define MAX6675_ERROR_MASK 4
#define MAX6675_DISCARD_BITS 3
#define MAX6675_SPEED_BITS (_BV(SPR0)) // clock ÷ 16
#endif
int Temperature::read_max6675() {
static millis_t next_max6675_ms = 0;
millis_t ms = millis();
if (PENDING(ms, next_max6675_ms)) return (int)max6675_temp;
next_max6675_ms = ms + MAX6675_HEAT_INTERVAL;
CBI(
#ifdef PRR
PRR
#elif defined(PRR0)
PRR0
#endif
, PRSPI);
SPCR = _BV(MSTR) | _BV(SPE) | MAX6675_SPEED_BITS;
WRITE(MAX6675_SS, 0); // enable TT_MAX6675
// ensure 100ns delay - a bit extra is fine
asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
// Read a big-endian temperature value
max6675_temp = 0;
for (uint8_t i = sizeof(max6675_temp); i--;) {
SPDR = 0;
for (;!TEST(SPSR, SPIF););
max6675_temp |= SPDR;
if (i > 0) max6675_temp <<= 8; // shift left if not the last byte
}
WRITE(MAX6675_SS, 1); // disable TT_MAX6675
if (max6675_temp & MAX6675_ERROR_MASK)
max6675_temp = 4000; // thermocouple open
else
max6675_temp >>= MAX6675_DISCARD_BITS;
return (int)max6675_temp;
}
#endif //HEATER_0_USES_MAX6675
/**
* Get raw temperatures
*/
void Temperature::set_current_temp_raw() {
#if HAS_TEMP_0 && DISABLED(HEATER_0_USES_MAX6675)
current_temperature_raw[0] = raw_temp_value[0];
#endif
#if HAS_TEMP_1
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
redundant_temperature_raw = raw_temp_value[1];
#else
current_temperature_raw[1] = raw_temp_value[1];
#endif
#if HAS_TEMP_2
current_temperature_raw[2] = raw_temp_value[2];
#if HAS_TEMP_3
current_temperature_raw[3] = raw_temp_value[3];
#endif
#endif
#endif
current_temperature_bed_raw = raw_temp_bed_value;
temp_meas_ready = true;
}
/**
* Timer 0 is shared with millies
* - Manage PWM to all the heaters and fan
* - Update the raw temperature values
* - Check new temperature values for MIN/MAX errors
* - Step the babysteps value for each axis towards 0
*/
ISR(TIMER0_COMPB_vect) { Temperature::isr(); }
void Temperature::isr() {
static unsigned char temp_count = 0;
static TempState temp_state = StartupDelay;
static unsigned char pwm_count = _BV(SOFT_PWM_SCALE);
// Static members for each heater
#if ENABLED(SLOW_PWM_HEATERS)
static unsigned char slow_pwm_count = 0;
#define ISR_STATICS(n) \
static unsigned char soft_pwm_ ## n; \
static unsigned char state_heater_ ## n = 0; \
static unsigned char state_timer_heater_ ## n = 0
#else
#define ISR_STATICS(n) static unsigned char soft_pwm_ ## n
#endif
// Statics per heater
ISR_STATICS(0);
#if (HOTENDS > 1) || ENABLED(HEATERS_PARALLEL)
ISR_STATICS(1);
#if HOTENDS > 2
ISR_STATICS(2);
#if HOTENDS > 3
ISR_STATICS(3);
#endif
#endif
#endif
#if HAS_HEATER_BED
ISR_STATICS(BED);
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
static unsigned long raw_filwidth_value = 0;
#endif
#if DISABLED(SLOW_PWM_HEATERS)
/**
* standard PWM modulation
*/
if (pwm_count == 0) {
soft_pwm_0 = soft_pwm[0];
if (soft_pwm_0 > 0) {
WRITE_HEATER_0(1);
}
else WRITE_HEATER_0P(0); // If HEATERS_PARALLEL should apply, change to WRITE_HEATER_0
#if HOTENDS > 1
soft_pwm_1 = soft_pwm[1];
WRITE_HEATER_1(soft_pwm_1 > 0 ? 1 : 0);
#if HOTENDS > 2
soft_pwm_2 = soft_pwm[2];
WRITE_HEATER_2(soft_pwm_2 > 0 ? 1 : 0);
#if HOTENDS > 3
soft_pwm_3 = soft_pwm[3];
WRITE_HEATER_3(soft_pwm_3 > 0 ? 1 : 0);
#endif
#endif
#endif
#if HAS_HEATER_BED
soft_pwm_BED = soft_pwm_bed;
WRITE_HEATER_BED(soft_pwm_BED > 0 ? 1 : 0);
#endif
#if ENABLED(FAN_SOFT_PWM)
#if HAS_FAN0
soft_pwm_fan[0] = fanSpeedSoftPwm[0] / 2;
WRITE_FAN(soft_pwm_fan[0] > 0 ? 1 : 0);
#endif
#if HAS_FAN1
soft_pwm_fan[1] = fanSpeedSoftPwm[1] / 2;
WRITE_FAN1(soft_pwm_fan[1] > 0 ? 1 : 0);
#endif
#if HAS_FAN2
soft_pwm_fan[2] = fanSpeedSoftPwm[2] / 2;
WRITE_FAN2(soft_pwm_fan[2] > 0 ? 1 : 0);
#endif
#endif
}
if (soft_pwm_0 < pwm_count) WRITE_HEATER_0(0);
#if HOTENDS > 1
if (soft_pwm_1 < pwm_count) WRITE_HEATER_1(0);
#if HOTENDS > 2
if (soft_pwm_2 < pwm_count) WRITE_HEATER_2(0);
#if HOTENDS > 3
if (soft_pwm_3 < pwm_count) WRITE_HEATER_3(0);
#endif
#endif
#endif
#if HAS_HEATER_BED
if (soft_pwm_BED < pwm_count) WRITE_HEATER_BED(0);
#endif
#if ENABLED(FAN_SOFT_PWM)
#if HAS_FAN0
if (soft_pwm_fan[0] < pwm_count) WRITE_FAN(0);
#endif
#if HAS_FAN1
if (soft_pwm_fan[1] < pwm_count) WRITE_FAN1(0);
#endif
#if HAS_FAN2
if (soft_pwm_fan[2] < pwm_count) WRITE_FAN2(0);
#endif
#endif
pwm_count += _BV(SOFT_PWM_SCALE);
pwm_count &= 0x7f;
#else // SLOW_PWM_HEATERS
/**
* SLOW PWM HEATERS
*
* for heaters drived by relay
*/
#ifndef MIN_STATE_TIME
#define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
#endif
// Macros for Slow PWM timer logic - HEATERS_PARALLEL applies
#define _SLOW_PWM_ROUTINE(NR, src) \
soft_pwm_ ## NR = src; \
if (soft_pwm_ ## NR > 0) { \
if (state_timer_heater_ ## NR == 0) { \
if (state_heater_ ## NR == 0) state_timer_heater_ ## NR = MIN_STATE_TIME; \
state_heater_ ## NR = 1; \
WRITE_HEATER_ ## NR(1); \
} \
} \
else { \
if (state_timer_heater_ ## NR == 0) { \
if (state_heater_ ## NR == 1) state_timer_heater_ ## NR = MIN_STATE_TIME; \
state_heater_ ## NR = 0; \
WRITE_HEATER_ ## NR(0); \
} \
}
#define SLOW_PWM_ROUTINE(n) _SLOW_PWM_ROUTINE(n, soft_pwm[n])
#define PWM_OFF_ROUTINE(NR) \
if (soft_pwm_ ## NR < slow_pwm_count) { \
if (state_timer_heater_ ## NR == 0) { \
if (state_heater_ ## NR == 1) state_timer_heater_ ## NR = MIN_STATE_TIME; \
state_heater_ ## NR = 0; \
WRITE_HEATER_ ## NR (0); \
} \
}
if (slow_pwm_count == 0) {
SLOW_PWM_ROUTINE(0); // EXTRUDER 0
#if HOTENDS > 1
SLOW_PWM_ROUTINE(1); // EXTRUDER 1
#if HOTENDS > 2
SLOW_PWM_ROUTINE(2); // EXTRUDER 2
#if HOTENDS > 3
SLOW_PWM_ROUTINE(3); // EXTRUDER 3
#endif
#endif
#endif
#if HAS_HEATER_BED
_SLOW_PWM_ROUTINE(BED, soft_pwm_bed); // BED
#endif
} // slow_pwm_count == 0
PWM_OFF_ROUTINE(0); // EXTRUDER 0
#if HOTENDS > 1
PWM_OFF_ROUTINE(1); // EXTRUDER 1
#if HOTENDS > 2
PWM_OFF_ROUTINE(2); // EXTRUDER 2
#if HOTENDS > 3
PWM_OFF_ROUTINE(3); // EXTRUDER 3
#endif
#endif
#endif
#if HAS_HEATER_BED
PWM_OFF_ROUTINE(BED); // BED
#endif
#if ENABLED(FAN_SOFT_PWM)
if (pwm_count == 0) {
#if HAS_FAN0
soft_pwm_fan[0] = fanSpeedSoftPwm[0] / 2;
WRITE_FAN(soft_pwm_fan[0] > 0 ? 1 : 0);
#endif
#if HAS_FAN1
soft_pwm_fan[1] = fanSpeedSoftPwm[1] / 2;
WRITE_FAN1(soft_pwm_fan[1] > 0 ? 1 : 0);
#endif
#if HAS_FAN2
soft_pwm_fan[2] = fanSpeedSoftPwm[2] / 2;
WRITE_FAN2(soft_pwm_fan[2] > 0 ? 1 : 0);
#endif
}
#if HAS_FAN0
if (soft_pwm_fan[0] < pwm_count) WRITE_FAN(0);
#endif
#if HAS_FAN1
if (soft_pwm_fan[1] < pwm_count) WRITE_FAN1(0);
#endif
#if HAS_FAN2
if (soft_pwm_fan[2] < pwm_count) WRITE_FAN2(0);
#endif
#endif //FAN_SOFT_PWM
pwm_count += _BV(SOFT_PWM_SCALE);
pwm_count &= 0x7f;
// increment slow_pwm_count only every 64 pwm_count circa 65.5ms
if ((pwm_count % 64) == 0) {
slow_pwm_count++;
slow_pwm_count &= 0x7f;
// EXTRUDER 0
if (state_timer_heater_0 > 0) state_timer_heater_0--;
#if HOTENDS > 1 // EXTRUDER 1
if (state_timer_heater_1 > 0) state_timer_heater_1--;
#if HOTENDS > 2 // EXTRUDER 2
if (state_timer_heater_2 > 0) state_timer_heater_2--;
#if HOTENDS > 3 // EXTRUDER 3
if (state_timer_heater_3 > 0) state_timer_heater_3--;
#endif
#endif
#endif
#if HAS_HEATER_BED
if (state_timer_heater_BED > 0) state_timer_heater_BED--;
#endif
} // (pwm_count % 64) == 0
#endif // SLOW_PWM_HEATERS
#define SET_ADMUX_ADCSRA(pin) ADMUX = _BV(REFS0) | (pin & 0x07); SBI(ADCSRA, ADSC)
#ifdef MUX5
#define START_ADC(pin) if (pin > 7) ADCSRB = _BV(MUX5); else ADCSRB = 0; SET_ADMUX_ADCSRA(pin)
#else
#define START_ADC(pin) ADCSRB = 0; SET_ADMUX_ADCSRA(pin)
#endif
// Prepare or measure a sensor, each one every 12th frame
switch (temp_state) {
case PrepareTemp_0:
#if HAS_TEMP_0
START_ADC(TEMP_0_PIN);
#endif
lcd_buttons_update();
temp_state = MeasureTemp_0;
break;
case MeasureTemp_0:
#if HAS_TEMP_0
raw_temp_value[0] += ADC;
#endif
temp_state = PrepareTemp_BED;
break;
case PrepareTemp_BED:
#if HAS_TEMP_BED
START_ADC(TEMP_BED_PIN);
#endif
lcd_buttons_update();
temp_state = MeasureTemp_BED;
break;
case MeasureTemp_BED:
#if HAS_TEMP_BED
raw_temp_bed_value += ADC;
#endif
temp_state = PrepareTemp_1;
break;
case PrepareTemp_1:
#if HAS_TEMP_1
START_ADC(TEMP_1_PIN);
#endif
lcd_buttons_update();
temp_state = MeasureTemp_1;
break;
case MeasureTemp_1:
#if HAS_TEMP_1
raw_temp_value[1] += ADC;
#endif
temp_state = PrepareTemp_2;
break;
case PrepareTemp_2:
#if HAS_TEMP_2
START_ADC(TEMP_2_PIN);
#endif
lcd_buttons_update();
temp_state = MeasureTemp_2;
break;
case MeasureTemp_2:
#if HAS_TEMP_2
raw_temp_value[2] += ADC;
#endif
temp_state = PrepareTemp_3;
break;
case PrepareTemp_3:
#if HAS_TEMP_3
START_ADC(TEMP_3_PIN);
#endif
lcd_buttons_update();
temp_state = MeasureTemp_3;
break;
case MeasureTemp_3:
#if HAS_TEMP_3
raw_temp_value[3] += ADC;
#endif
temp_state = Prepare_FILWIDTH;
break;
case Prepare_FILWIDTH:
#if ENABLED(FILAMENT_WIDTH_SENSOR)
START_ADC(FILWIDTH_PIN);
#endif
lcd_buttons_update();
temp_state = Measure_FILWIDTH;
break;
case Measure_FILWIDTH:
#if ENABLED(FILAMENT_WIDTH_SENSOR)
// raw_filwidth_value += ADC; //remove to use an IIR filter approach
if (ADC > 102) { //check that ADC is reading a voltage > 0.5 volts, otherwise don't take in the data.
raw_filwidth_value -= (raw_filwidth_value >> 7); //multiply raw_filwidth_value by 127/128
raw_filwidth_value += ((unsigned long)ADC << 7); //add new ADC reading
}
#endif
temp_state = PrepareTemp_0;
temp_count++;
break;
case StartupDelay:
temp_state = PrepareTemp_0;
break;
// default:
// SERIAL_ERROR_START;
// SERIAL_ERRORLNPGM("Temp measurement error!");
// break;
} // switch(temp_state)
if (temp_count >= OVERSAMPLENR) { // 10 * 16 * 1/(16000000/64/256) = 164ms.
// Update the raw values if they've been read. Else we could be updating them during reading.
if (!temp_meas_ready) set_current_temp_raw();
// Filament Sensor - can be read any time since IIR filtering is used
#if ENABLED(FILAMENT_WIDTH_SENSOR)
current_raw_filwidth = raw_filwidth_value >> 10; // Divide to get to 0-16384 range since we used 1/128 IIR filter approach
#endif
temp_count = 0;
for (int i = 0; i < 4; i++) raw_temp_value[i] = 0;
raw_temp_bed_value = 0;
#if HAS_TEMP_0 && DISABLED(HEATER_0_USES_MAX6675)
#if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
#define GE0 <=
#else
#define GE0 >=
#endif
if (current_temperature_raw[0] GE0 maxttemp_raw[0]) max_temp_error(0);
if (minttemp_raw[0] GE0 current_temperature_raw[0] && !is_preheating(0) && target_temperature[0] > 0.0f) {
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
if (++consecutive_low_temperature_error[0] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)
#endif
min_temp_error(0);
}
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
else
consecutive_low_temperature_error[0] = 0;
#endif
#endif
#if HAS_TEMP_1 && HOTENDS > 1
#if HEATER_1_RAW_LO_TEMP > HEATER_1_RAW_HI_TEMP
#define GE1 <=
#else
#define GE1 >=
#endif
if (current_temperature_raw[1] GE1 maxttemp_raw[1]) max_temp_error(1);
if (minttemp_raw[1] GE1 current_temperature_raw[1] && !is_preheating(1) && target_temperature[1] > 0.0f) {
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
if (++consecutive_low_temperature_error[1] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)
#endif
min_temp_error(1);
}
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
else
consecutive_low_temperature_error[1] = 0;
#endif
#endif // TEMP_SENSOR_1
#if HAS_TEMP_2 && HOTENDS > 2
#if HEATER_2_RAW_LO_TEMP > HEATER_2_RAW_HI_TEMP
#define GE2 <=
#else
#define GE2 >=
#endif
if (current_temperature_raw[2] GE2 maxttemp_raw[2]) max_temp_error(2);
if (minttemp_raw[2] GE2 current_temperature_raw[2] && !is_preheating(2) && target_temperature[2] > 0.0f) {
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
if (++consecutive_low_temperature_error[2] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)
#endif
min_temp_error(2);
}
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
else
consecutive_low_temperature_error[2] = 0;
#endif
#endif // TEMP_SENSOR_2
#if HAS_TEMP_3 && HOTENDS > 3
#if HEATER_3_RAW_LO_TEMP > HEATER_3_RAW_HI_TEMP
#define GE3 <=
#else
#define GE3 >=
#endif
if (current_temperature_raw[3] GE3 maxttemp_raw[3]) max_temp_error(3);
if (minttemp_raw[3] GE3 current_temperature_raw[3] && !is_preheating(3) && target_temperature[3] > 0.0f) {
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
if (++consecutive_low_temperature_error[3] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)
#endif
min_temp_error(3);
}
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
else
consecutive_low_temperature_error[3] = 0;
#endif
#endif // TEMP_SENSOR_3
#if HAS_TEMP_BED
#if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
#define GEBED <=
#else
#define GEBED >=
#endif
if (current_temperature_bed_raw GEBED bed_maxttemp_raw) _temp_error(-1, PSTR(MSG_T_MAXTEMP), PSTR(MSG_ERR_MAXTEMP_BED));
if (bed_minttemp_raw GEBED current_temperature_bed_raw) _temp_error(-1, PSTR(MSG_T_MINTEMP), PSTR(MSG_ERR_MINTEMP_BED));
#endif
} // temp_count >= OVERSAMPLENR
#if ENABLED(BABYSTEPPING)
for (uint8_t axis = X_AXIS; axis <= Z_AXIS; axis++) {
int curTodo = babystepsTodo[axis]; //get rid of volatile for performance
if (curTodo > 0) {
stepper.babystep(axis,/*fwd*/true);
babystepsTodo[axis]--; //fewer to do next time
}
else if (curTodo < 0) {
stepper.babystep(axis,/*fwd*/false);
babystepsTodo[axis]++; //fewer to do next time
}
}
#endif //BABYSTEPPING
}
| gpl-3.0 |
ibm2431/darkstar | src/map/ai/states/weaponskill_state.cpp | 4484 | /*
===========================================================================
Copyright (c) 2010-2015 Darkstar Dev Teams
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/
This file is part of DarkStar-server source code.
===========================================================================
*/
#include "weaponskill_state.h"
#include "../ai_container.h"
#include "../../entities/battleentity.h"
#include "../../packets/action.h"
#include "../../utils/battleutils.h"
#include "../../weapon_skill.h"
#include "../../status_effect_container.h"
CWeaponSkillState::CWeaponSkillState(CBattleEntity* PEntity, uint16 targid, uint16 wsid) :
CState(PEntity, targid),
m_PEntity(PEntity)
{
auto skill = battleutils::GetWeaponSkill(wsid);
if (!skill)
{
throw CStateInitException(std::make_unique<CMessageBasicPacket>(PEntity, PEntity, 0, 0, MSGBASIC_CANNOT_USE_WS));
}
auto target_flags = battleutils::isValidSelfTargetWeaponskill(wsid) ? TARGET_SELF : TARGET_ENEMY;
auto PTarget = m_PEntity->IsValidTarget(m_targid, target_flags, m_errorMsg);
if (!PTarget || m_errorMsg)
{
throw CStateInitException(std::move(m_errorMsg));
}
if (!m_PEntity->PAI->TargetFind->canSee(&PTarget->loc.p))
{
throw CStateInitException(std::make_unique<CMessageBasicPacket>(m_PEntity, PTarget, 0, 0, MSGBASIC_CANNOT_PERFORM_ACTION));
}
m_PSkill = std::make_unique<CWeaponSkill>(*skill);
//m_castTime = std::chrono::milliseconds(m_PSkill->getActivationTime());
action_t action;
action.id = m_PEntity->id;
action.actiontype = ACTION_WEAPONSKILL_START;
actionList_t& actionList = action.getNewActionList();
actionList.ActionTargetID = PTarget->id;
actionTarget_t& actionTarget = actionList.getNewActionTarget();
actionTarget.reaction = REACTION_NONE;
actionTarget.speceffect = SPECEFFECT_NONE;
actionTarget.animation = 0;
actionTarget.param = m_PSkill->getID();
actionTarget.messageID = 43;
m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
}
CWeaponSkill* CWeaponSkillState::GetSkill()
{
return m_PSkill.get();
}
void CWeaponSkillState::SpendCost()
{
auto tp = 0;
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_MEIKYO_SHISUI))
{
tp = m_PEntity->addTP(-1000);
}
else if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_SEKKANOKI))
{
tp = m_PEntity->addTP(-1000);
m_PEntity->StatusEffectContainer->DelStatusEffect(EFFECT_SEKKANOKI);
}
else
{
tp = m_PEntity->health.tp;
if (m_PEntity->getMod(Mod::WS_NO_DEPLETE) <= dsprand::GetRandomNumber(100))
{
m_PEntity->health.tp = 0;
}
}
if (dsprand::GetRandomNumber(100) < m_PEntity->getMod(Mod::CONSERVE_TP))
{
m_PEntity->addTP(dsprand::GetRandomNumber(10, 200));
}
m_spent = tp;
}
bool CWeaponSkillState::Update(time_point tick)
{
if (!IsCompleted())
{
SpendCost();
action_t action;
m_PEntity->OnWeaponSkillFinished(*this, action);
m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
auto PTarget {GetTarget()};
m_PEntity->PAI->EventHandler.triggerListener("WEAPONSKILL_USE", m_PEntity, PTarget, m_PSkill->getID(), m_spent, &action);
PTarget->PAI->EventHandler.triggerListener("WEAPONSKILL_TAKE", PTarget, m_PEntity, m_PSkill->getID(), m_spent, &action);
auto delay = m_PSkill->getAnimationTime();
m_finishTime = tick + delay;
Complete();
}
else if (tick > m_finishTime)
{
m_PEntity->PAI->EventHandler.triggerListener("WEAPONSKILL_STATE_EXIT", m_PEntity, m_PSkill->getID());
return true;
}
return false;
}
void CWeaponSkillState::Cleanup(time_point tick)
{
//#TODO: interrupt an in progress ws
}
| gpl-3.0 |
redFrik/supercollider | external_libraries/boost/boost/thread/detail/thread.hpp | 26312 | #ifndef BOOST_THREAD_THREAD_COMMON_HPP
#define BOOST_THREAD_THREAD_COMMON_HPP
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-2010 Anthony Williams
// (C) Copyright 2011-2012 Vicente J. Botet Escriba
#include <boost/thread/detail/config.hpp>
#include <boost/predef/platform.h>
#include <boost/thread/exceptions.hpp>
#ifndef BOOST_NO_IOSTREAM
#include <ostream>
#endif
#include <boost/thread/detail/move.hpp>
#include <boost/thread/mutex.hpp>
#if defined BOOST_THREAD_USES_DATETIME
#include <boost/thread/xtime.hpp>
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
#include <boost/thread/interruption.hpp>
#endif
#include <boost/thread/detail/thread_heap_alloc.hpp>
#include <boost/thread/detail/make_tuple_indices.hpp>
#include <boost/thread/detail/invoke.hpp>
#include <boost/thread/detail/is_convertible.hpp>
#include <boost/assert.hpp>
#include <list>
#include <algorithm>
#include <boost/core/ref.hpp>
#include <boost/cstdint.hpp>
#include <boost/bind/bind.hpp>
#include <stdlib.h>
#include <memory>
#include <boost/core/enable_if.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/io/ios_state.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/decay.hpp>
#include <boost/functional/hash.hpp>
#include <boost/thread/detail/platform_time.hpp>
#ifdef BOOST_THREAD_USES_CHRONO
#include <boost/chrono/system_clocks.hpp>
#include <boost/chrono/ceil.hpp>
#endif
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
#include <tuple>
#endif
#include <boost/config/abi_prefix.hpp>
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4251)
#endif
namespace boost
{
namespace detail
{
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename F, class ...ArgTypes>
class thread_data:
public detail::thread_data_base
{
public:
BOOST_THREAD_NO_COPYABLE(thread_data)
thread_data(BOOST_THREAD_RV_REF(F) f_, BOOST_THREAD_RV_REF(ArgTypes)... args_):
fp(boost::forward<F>(f_), boost::forward<ArgTypes>(args_)...)
{}
template <std::size_t ...Indices>
void run2(tuple_indices<Indices...>)
{
detail::invoke(std::move(std::get<0>(fp)), std::move(std::get<Indices>(fp))...);
}
void run()
{
typedef typename make_tuple_indices<std::tuple_size<std::tuple<F, ArgTypes...> >::value, 1>::type index_type;
run2(index_type());
}
private:
std::tuple<typename decay<F>::type, typename decay<ArgTypes>::type...> fp;
};
#else // defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename F>
class thread_data:
public detail::thread_data_base
{
public:
BOOST_THREAD_NO_COPYABLE(thread_data)
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
thread_data(BOOST_THREAD_RV_REF(F) f_):
f(boost::forward<F>(f_))
{}
// This overloading must be removed if we want the packaged_task's tests to pass.
// thread_data(F& f_):
// f(f_)
// {}
#else
thread_data(BOOST_THREAD_RV_REF(F) f_):
f(f_)
{}
thread_data(F f_):
f(f_)
{}
#endif
//thread_data() {}
void run()
{
f();
}
private:
F f;
};
template<typename F>
class thread_data<boost::reference_wrapper<F> >:
public detail::thread_data_base
{
private:
F& f;
public:
BOOST_THREAD_NO_COPYABLE(thread_data)
thread_data(boost::reference_wrapper<F> f_):
f(f_)
{}
void run()
{
f();
}
};
template<typename F>
class thread_data<const boost::reference_wrapper<F> >:
public detail::thread_data_base
{
private:
F& f;
public:
BOOST_THREAD_NO_COPYABLE(thread_data)
thread_data(const boost::reference_wrapper<F> f_):
f(f_)
{}
void run()
{
f();
}
};
#endif
}
class BOOST_THREAD_DECL thread
{
public:
typedef thread_attributes attributes;
BOOST_THREAD_MOVABLE_ONLY(thread)
private:
struct dummy;
void release_handle();
detail::thread_data_ptr thread_info;
private:
bool start_thread_noexcept();
bool start_thread_noexcept(const attributes& attr);
void start_thread()
{
if (!start_thread_noexcept())
{
boost::throw_exception(thread_resource_error());
}
}
void start_thread(const attributes& attr)
{
if (!start_thread_noexcept(attr))
{
boost::throw_exception(thread_resource_error());
}
}
explicit thread(detail::thread_data_ptr data);
detail::thread_data_ptr get_thread_info BOOST_PREVENT_MACRO_SUBSTITUTION () const;
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename F, class ...ArgTypes>
static inline detail::thread_data_ptr make_thread_info(BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_RV_REF(ArgTypes)... args)
{
return detail::thread_data_ptr(detail::heap_new<
detail::thread_data<typename boost::remove_reference<F>::type, ArgTypes...>
>(
boost::forward<F>(f), boost::forward<ArgTypes>(args)...
)
);
}
#else
template<typename F>
static inline detail::thread_data_ptr make_thread_info(BOOST_THREAD_RV_REF(F) f)
{
return detail::thread_data_ptr(detail::heap_new<detail::thread_data<typename boost::remove_reference<F>::type> >(
boost::forward<F>(f)));
}
#endif
static inline detail::thread_data_ptr make_thread_info(void (*f)())
{
return detail::thread_data_ptr(detail::heap_new<detail::thread_data<void(*)()> >(
boost::forward<void(*)()>(f)));
}
#else
template<typename F>
static inline detail::thread_data_ptr make_thread_info(F f
, typename disable_if_c<
//boost::thread_detail::is_convertible<F&,BOOST_THREAD_RV_REF(F)>::value ||
is_same<typename decay<F>::type, thread>::value,
dummy* >::type=0
)
{
return detail::thread_data_ptr(detail::heap_new<detail::thread_data<F> >(f));
}
template<typename F>
static inline detail::thread_data_ptr make_thread_info(BOOST_THREAD_RV_REF(F) f)
{
return detail::thread_data_ptr(detail::heap_new<detail::thread_data<F> >(f));
}
#endif
public:
#if 0 // This should not be needed anymore. Use instead BOOST_THREAD_MAKE_RV_REF.
#if BOOST_WORKAROUND(__SUNPRO_CC, < 0x5100)
thread(const volatile thread&);
#endif
#endif
thread() BOOST_NOEXCEPT;
~thread()
{
#if defined BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE
if (joinable()) {
std::terminate();
}
#else
detach();
#endif
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <
class F
>
explicit thread(BOOST_THREAD_RV_REF(F) f
//, typename disable_if<is_same<typename decay<F>::type, thread>, dummy* >::type=0
):
thread_info(make_thread_info(thread_detail::decay_copy(boost::forward<F>(f))))
{
start_thread();
}
template <
class F
>
thread(attributes const& attrs, BOOST_THREAD_RV_REF(F) f):
thread_info(make_thread_info(thread_detail::decay_copy(boost::forward<F>(f))))
{
start_thread(attrs);
}
#else
#ifdef BOOST_NO_SFINAE
template <class F>
explicit thread(F f):
thread_info(make_thread_info(f))
{
start_thread();
}
template <class F>
thread(attributes const& attrs, F f):
thread_info(make_thread_info(f))
{
start_thread(attrs);
}
#else
template <class F>
explicit thread(F f
, typename disable_if_c<
boost::thread_detail::is_rv<F>::value // todo as a thread_detail::is_rv
//boost::thread_detail::is_convertible<F&,BOOST_THREAD_RV_REF(F)>::value
//|| is_same<typename decay<F>::type, thread>::value
, dummy* >::type=0
):
thread_info(make_thread_info(f))
{
start_thread();
}
template <class F>
thread(attributes const& attrs, F f
, typename disable_if<boost::thread_detail::is_rv<F>, dummy* >::type=0
//, typename disable_if<boost::thread_detail::is_convertible<F&,BOOST_THREAD_RV_REF(F) >, dummy* >::type=0
):
thread_info(make_thread_info(f))
{
start_thread(attrs);
}
#endif
template <class F>
explicit thread(BOOST_THREAD_RV_REF(F) f
, typename disable_if<is_same<typename decay<F>::type, thread>, dummy* >::type=0
):
#ifdef BOOST_THREAD_USES_MOVE
thread_info(make_thread_info(boost::move<F>(f))) // todo : Add forward
#else
thread_info(make_thread_info(f)) // todo : Add forward
#endif
{
start_thread();
}
template <class F>
thread(attributes const& attrs, BOOST_THREAD_RV_REF(F) f):
#ifdef BOOST_THREAD_USES_MOVE
thread_info(make_thread_info(boost::move<F>(f))) // todo : Add forward
#else
thread_info(make_thread_info(f)) // todo : Add forward
#endif
{
start_thread(attrs);
}
#endif
thread(BOOST_THREAD_RV_REF(thread) x) BOOST_NOEXCEPT
{
thread_info=BOOST_THREAD_RV(x).thread_info;
BOOST_THREAD_RV(x).thread_info.reset();
}
#if 0 // This should not be needed anymore. Use instead BOOST_THREAD_MAKE_RV_REF.
#if BOOST_WORKAROUND(__SUNPRO_CC, < 0x5100)
thread& operator=(thread x)
{
swap(x);
return *this;
}
#endif
#endif
thread& operator=(BOOST_THREAD_RV_REF(thread) other) BOOST_NOEXCEPT
{
#if defined BOOST_THREAD_PROVIDES_THREAD_MOVE_ASSIGN_CALLS_TERMINATE_IF_JOINABLE
if (joinable()) std::terminate();
#else
detach();
#endif
thread_info=BOOST_THREAD_RV(other).thread_info;
BOOST_THREAD_RV(other).thread_info.reset();
return *this;
}
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template <class F, class Arg, class ...Args>
thread(F&& f, Arg&& arg, Args&&... args) :
thread_info(make_thread_info(
thread_detail::decay_copy(boost::forward<F>(f)),
thread_detail::decay_copy(boost::forward<Arg>(arg)),
thread_detail::decay_copy(boost::forward<Args>(args))...)
)
{
start_thread();
}
template <class F, class Arg, class ...Args>
thread(attributes const& attrs, F&& f, Arg&& arg, Args&&... args) :
thread_info(make_thread_info(
thread_detail::decay_copy(boost::forward<F>(f)),
thread_detail::decay_copy(boost::forward<Arg>(arg)),
thread_detail::decay_copy(boost::forward<Args>(args))...)
)
{
start_thread(attrs);
}
#else
template <class F,class A1>
thread(F f,A1 a1,typename disable_if<boost::thread_detail::is_convertible<F&,thread_attributes >, dummy* >::type=0):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1)))
{
start_thread();
}
template <class F,class A1,class A2>
thread(F f,A1 a1,A2 a2):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2)))
{
start_thread();
}
template <class F,class A1,class A2,class A3>
thread(F f,A1 a1,A2 a2,A3 a3):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5,class A6>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5,A6 a6):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5,a6)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5,class A6,class A7>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5,A6 a6,A7 a7):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5,a6,a7)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5,class A6,class A7,class A8>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5,A6 a6,A7 a7,A8 a8):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5,a6,a7,a8)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5,class A6,class A7,class A8,class A9>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5,A6 a6,A7 a7,A8 a8,A9 a9):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5,a6,a7,a8,a9)))
{
start_thread();
}
#endif
void swap(thread& x) BOOST_NOEXCEPT
{
thread_info.swap(x.thread_info);
}
class id;
id get_id() const BOOST_NOEXCEPT;
bool joinable() const BOOST_NOEXCEPT;
private:
bool join_noexcept();
bool do_try_join_until_noexcept(detail::internal_platform_timepoint const &timeout, bool& res);
bool do_try_join_until(detail::internal_platform_timepoint const &timeout);
public:
void join();
#ifdef BOOST_THREAD_USES_CHRONO
template <class Duration>
bool try_join_until(const chrono::time_point<detail::internal_chrono_clock, Duration>& t)
{
return do_try_join_until(boost::detail::internal_platform_timepoint(t));
}
template <class Clock, class Duration>
bool try_join_until(const chrono::time_point<Clock, Duration>& t)
{
typedef typename common_type<Duration, typename Clock::duration>::type common_duration;
common_duration d(t - Clock::now());
d = (std::min)(d, common_duration(chrono::milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS)));
while ( ! try_join_until(detail::internal_chrono_clock::now() + d) )
{
d = t - Clock::now();
if ( d <= common_duration::zero() ) return false; // timeout occurred
d = (std::min)(d, common_duration(chrono::milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS)));
}
return true;
}
template <class Rep, class Period>
bool try_join_for(const chrono::duration<Rep, Period>& rel_time)
{
return try_join_until(chrono::steady_clock::now() + rel_time);
}
#endif
#if defined BOOST_THREAD_USES_DATETIME
bool timed_join(const system_time& abs_time)
{
const detail::real_platform_timepoint ts(abs_time);
#if defined BOOST_THREAD_INTERNAL_CLOCK_IS_MONO
detail::platform_duration d(ts - detail::real_platform_clock::now());
d = (std::min)(d, detail::platform_milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS));
while ( ! do_try_join_until(detail::internal_platform_clock::now() + d) )
{
d = ts - detail::real_platform_clock::now();
if ( d <= detail::platform_duration::zero() ) return false; // timeout occurred
d = (std::min)(d, detail::platform_milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS));
}
return true;
#else
return do_try_join_until(ts);
#endif
}
template<typename TimeDuration>
bool timed_join(TimeDuration const& rel_time)
{
detail::platform_duration d(rel_time);
#if defined(BOOST_THREAD_HAS_MONO_CLOCK) && !defined(BOOST_THREAD_INTERNAL_CLOCK_IS_MONO)
const detail::mono_platform_timepoint ts(detail::mono_platform_clock::now() + d);
d = (std::min)(d, detail::platform_milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS));
while ( ! do_try_join_until(detail::internal_platform_clock::now() + d) )
{
d = ts - detail::mono_platform_clock::now();
if ( d <= detail::platform_duration::zero() ) return false; // timeout occurred
d = (std::min)(d, detail::platform_milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS));
}
return true;
#else
return do_try_join_until(detail::internal_platform_clock::now() + d);
#endif
}
#endif
void detach();
static unsigned hardware_concurrency() BOOST_NOEXCEPT;
static unsigned physical_concurrency() BOOST_NOEXCEPT;
#define BOOST_THREAD_DEFINES_THREAD_NATIVE_HANDLE
typedef detail::thread_data_base::native_handle_type native_handle_type;
native_handle_type native_handle();
#if defined BOOST_THREAD_PROVIDES_THREAD_EQ
// Use thread::id when comparisions are needed
// backwards compatibility
bool operator==(const thread& other) const;
bool operator!=(const thread& other) const;
#endif
#if defined BOOST_THREAD_USES_DATETIME
static inline void yield() BOOST_NOEXCEPT
{
this_thread::yield();
}
static inline void sleep(const system_time& xt)
{
this_thread::sleep(xt);
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
// extensions
void interrupt();
bool interruption_requested() const BOOST_NOEXCEPT;
#endif
};
inline void swap(thread& lhs,thread& rhs) BOOST_NOEXCEPT
{
return lhs.swap(rhs);
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
inline thread&& move(thread& t) BOOST_NOEXCEPT
{
return static_cast<thread&&>(t);
}
#endif
BOOST_THREAD_DCL_MOVABLE(thread)
namespace this_thread
{
#ifdef BOOST_THREAD_PLATFORM_PTHREAD
thread::id get_id() BOOST_NOEXCEPT;
#else
thread::id BOOST_THREAD_DECL get_id() BOOST_NOEXCEPT;
#endif
#if defined BOOST_THREAD_USES_DATETIME
inline BOOST_SYMBOL_VISIBLE void sleep(::boost::xtime const& abs_time)
{
sleep(system_time(abs_time));
}
#endif
}
class BOOST_SYMBOL_VISIBLE thread::id
{
private:
friend inline
std::size_t
hash_value(const thread::id &v)
{
#if defined BOOST_THREAD_PROVIDES_BASIC_THREAD_ID
return hash_value(v.thread_data);
#else
return hash_value(v.thread_data.get());
#endif
}
#if defined BOOST_THREAD_PROVIDES_BASIC_THREAD_ID
#if defined(BOOST_THREAD_PLATFORM_WIN32)
typedef unsigned int data;
#else
typedef thread::native_handle_type data;
#endif
#else
typedef detail::thread_data_ptr data;
#endif
data thread_data;
id(data thread_data_):
thread_data(thread_data_)
{}
friend class thread;
friend id BOOST_THREAD_DECL this_thread::get_id() BOOST_NOEXCEPT;
public:
id() BOOST_NOEXCEPT:
#if defined BOOST_THREAD_PROVIDES_BASIC_THREAD_ID
thread_data(0)
#else
thread_data()
#endif
{}
bool operator==(const id& y) const BOOST_NOEXCEPT
{
return thread_data==y.thread_data;
}
bool operator!=(const id& y) const BOOST_NOEXCEPT
{
return thread_data!=y.thread_data;
}
bool operator<(const id& y) const BOOST_NOEXCEPT
{
return thread_data<y.thread_data;
}
bool operator>(const id& y) const BOOST_NOEXCEPT
{
return y.thread_data<thread_data;
}
bool operator<=(const id& y) const BOOST_NOEXCEPT
{
return !(y.thread_data<thread_data);
}
bool operator>=(const id& y) const BOOST_NOEXCEPT
{
return !(thread_data<y.thread_data);
}
#ifndef BOOST_NO_IOSTREAM
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
template<class charT, class traits>
friend BOOST_SYMBOL_VISIBLE
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const id& x)
{
if(x.thread_data)
{
io::ios_flags_saver ifs( os );
return os<< std::hex << x.thread_data;
}
else
{
return os<<"{Not-any-thread}";
}
}
#else
template<class charT, class traits>
BOOST_SYMBOL_VISIBLE
std::basic_ostream<charT, traits>&
print(std::basic_ostream<charT, traits>& os) const
{
if(thread_data)
{
io::ios_flags_saver ifs( os );
return os<< std::hex << thread_data;
}
else
{
return os<<"{Not-any-thread}";
}
}
#endif
#endif
};
#ifdef BOOST_THREAD_PLATFORM_PTHREAD
inline thread::id thread::get_id() const BOOST_NOEXCEPT
{
#if defined BOOST_THREAD_PROVIDES_BASIC_THREAD_ID
return const_cast<thread*>(this)->native_handle();
#else
detail::thread_data_ptr const local_thread_info=(get_thread_info)();
return (local_thread_info? id(local_thread_info) : id());
#endif
}
namespace this_thread
{
inline thread::id get_id() BOOST_NOEXCEPT
{
#if defined BOOST_THREAD_PROVIDES_BASIC_THREAD_ID
return pthread_self();
#else
boost::detail::thread_data_base* const thread_info=get_or_make_current_thread_data();
return (thread_info?thread::id(thread_info->shared_from_this()):thread::id());
#endif
}
}
#endif
inline void thread::join() {
if (this_thread::get_id() == get_id())
boost::throw_exception(thread_resource_error(static_cast<int>(system::errc::resource_deadlock_would_occur), "boost thread: trying joining itself"));
BOOST_THREAD_VERIFY_PRECONDITION( join_noexcept(),
thread_resource_error(static_cast<int>(system::errc::invalid_argument), "boost thread: thread not joinable")
);
}
inline bool thread::do_try_join_until(detail::internal_platform_timepoint const &timeout)
{
if (this_thread::get_id() == get_id())
boost::throw_exception(thread_resource_error(static_cast<int>(system::errc::resource_deadlock_would_occur), "boost thread: trying joining itself"));
bool res;
if (do_try_join_until_noexcept(timeout, res))
{
return res;
}
else
{
BOOST_THREAD_THROW_ELSE_RETURN(
(thread_resource_error(static_cast<int>(system::errc::invalid_argument), "boost thread: thread not joinable")),
false
);
}
}
#if !defined(BOOST_NO_IOSTREAM) && defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
template<class charT, class traits>
BOOST_SYMBOL_VISIBLE
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const thread::id& x)
{
return x.print(os);
}
#endif
#if defined BOOST_THREAD_PROVIDES_THREAD_EQ
inline bool thread::operator==(const thread& other) const
{
return get_id()==other.get_id();
}
inline bool thread::operator!=(const thread& other) const
{
return get_id()!=other.get_id();
}
#endif
namespace detail
{
struct thread_exit_function_base
{
virtual ~thread_exit_function_base()
{}
virtual void operator()()=0;
};
template<typename F>
struct thread_exit_function:
thread_exit_function_base
{
F f;
thread_exit_function(F f_):
f(f_)
{}
void operator()()
{
f();
}
};
void BOOST_THREAD_DECL add_thread_exit_function(thread_exit_function_base*);
//#ifndef BOOST_NO_EXCEPTIONS
struct shared_state_base;
#if defined(BOOST_THREAD_PLATFORM_WIN32)
inline void make_ready_at_thread_exit(shared_ptr<shared_state_base> as)
{
detail::thread_data_base* const current_thread_data(detail::get_current_thread_data());
if(current_thread_data)
{
current_thread_data->make_ready_at_thread_exit(as);
}
}
#else
void BOOST_THREAD_DECL make_ready_at_thread_exit(shared_ptr<shared_state_base> as);
#endif
//#endif
}
namespace this_thread
{
template<typename F>
void at_thread_exit(F f)
{
detail::thread_exit_function_base* const thread_exit_func=detail::heap_new<detail::thread_exit_function<F> >(f);
detail::add_thread_exit_function(thread_exit_func);
}
}
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#include <boost/config/abi_suffix.hpp>
#endif
| gpl-3.0 |
inabeel/mixerp | src/Libraries/DAL/Core/IGetTaxMasterIdByTaxMasterCodeRepository.cs | 441 | // ReSharper disable All
using System;
using System.Collections.Generic;
using System.Dynamic;
using PetaPoco;
using MixERP.Net.Entities.Core;
namespace MixERP.Net.Schemas.Core.Data
{
public interface IGetTaxMasterIdByTaxMasterCodeRepository
{
string PgArg0 { get; set; }
/// <summary>
/// Prepares and executes IGetTaxMasterIdByTaxMasterCodeRepository.
/// </summary>
int Execute();
}
} | gpl-3.0 |
PeaceWorksTechnologySolutions/atom | vendor/FluentDOM/examples/filter-fn.php | 795 | <?php
/**
*
* @version $Id: filter-fn.php 429 2010-03-29 08:05:32Z subjective $
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @copyright Copyright (c) 2009 Bastian Feder, Thomas Weinert
*/
header('Content-type: text/plain');
$xml = <<<XML
<html>
<head></head>
<body>
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
<div id="fifth"></div>
<div id="sixth"></div>
</body>
</html>
XML;
require_once('../FluentDOM.php');
echo FluentDOM($xml)
->find('//div')
->attr('border', 1)
->filter(
function($node, $index) {
if ($index == 1 ||
FluentDOM($node)->attr('id') == 'fourth') {
return TRUE;
}
return FALSE;
}
)
->attr('style', 'text-align: center;');
?> | agpl-3.0 |
clemensgeibel/inspectIT | CMR/src/info/novatec/inspectit/cmr/dao/impl/MethodIdentToSensorTypeDaoImpl.java | 1596 | package info.novatec.inspectit.cmr.dao.impl;
import info.novatec.inspectit.cmr.dao.MethodIdentToSensorTypeDao;
import info.novatec.inspectit.cmr.model.MethodIdentToSensorType;
import java.util.List;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
/**
* The default implementation of the {@link MethodIdentToSensorTypeDao} interface by using Entity
* manager.
*
* @author Ivan Senic
*
*/
@Repository
public class MethodIdentToSensorTypeDaoImpl extends AbstractJpaDao<MethodIdentToSensorType> implements MethodIdentToSensorTypeDao {
/**
* Default constructor.
*/
public MethodIdentToSensorTypeDaoImpl() {
super(MethodIdentToSensorType.class);
}
/**
* {@inheritDoc}
*/
public void saveOrUpdate(MethodIdentToSensorType methodIdentToSensorType) {
// we save if id is not set, otherwise merge
if (null == methodIdentToSensorType.getId()) {
super.create(methodIdentToSensorType);
} else {
super.update(methodIdentToSensorType);
}
}
/**
* {@inheritDoc}
*/
public MethodIdentToSensorType find(long methodIdentId, long methodSensorTypeIdentId) {
TypedQuery<MethodIdentToSensorType> query = getEntityManager().createNamedQuery(MethodIdentToSensorType.FIND_FOR_METHOD_ID_AND_METOHD_SENSOR_TYPE_ID, MethodIdentToSensorType.class);
query.setParameter("methodIdentId", methodIdentId);
query.setParameter("methodSensorTypeIdentId", methodSensorTypeIdentId);
List<MethodIdentToSensorType> results = query.getResultList();
if (1 == results.size()) {
return results.get(0);
} else {
return null;
}
}
}
| agpl-3.0 |
boredherobrine13/morefuelsmod-1.10 | build/tmp/recompileMc/sources/net/minecraft/network/play/server/SPacketUpdateScore.java | 2943 | package net.minecraft.network.play.server;
import java.io.IOException;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.scoreboard.Score;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class SPacketUpdateScore implements Packet<INetHandlerPlayClient>
{
private String name = "";
private String objective = "";
private int value;
private SPacketUpdateScore.Action action;
public SPacketUpdateScore()
{
}
public SPacketUpdateScore(Score scoreIn)
{
this.name = scoreIn.getPlayerName();
this.objective = scoreIn.getObjective().getName();
this.value = scoreIn.getScorePoints();
this.action = SPacketUpdateScore.Action.CHANGE;
}
public SPacketUpdateScore(String nameIn)
{
this.name = nameIn;
this.objective = "";
this.value = 0;
this.action = SPacketUpdateScore.Action.REMOVE;
}
public SPacketUpdateScore(String nameIn, ScoreObjective objectiveIn)
{
this.name = nameIn;
this.objective = objectiveIn.getName();
this.value = 0;
this.action = SPacketUpdateScore.Action.REMOVE;
}
/**
* Reads the raw packet data from the data stream.
*/
public void readPacketData(PacketBuffer buf) throws IOException
{
this.name = buf.readStringFromBuffer(40);
this.action = (SPacketUpdateScore.Action)buf.readEnumValue(SPacketUpdateScore.Action.class);
this.objective = buf.readStringFromBuffer(16);
if (this.action != SPacketUpdateScore.Action.REMOVE)
{
this.value = buf.readVarIntFromBuffer();
}
}
/**
* Writes the raw packet data to the data stream.
*/
public void writePacketData(PacketBuffer buf) throws IOException
{
buf.writeString(this.name);
buf.writeEnumValue(this.action);
buf.writeString(this.objective);
if (this.action != SPacketUpdateScore.Action.REMOVE)
{
buf.writeVarIntToBuffer(this.value);
}
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
public void processPacket(INetHandlerPlayClient handler)
{
handler.handleUpdateScore(this);
}
@SideOnly(Side.CLIENT)
public String getPlayerName()
{
return this.name;
}
@SideOnly(Side.CLIENT)
public String getObjectiveName()
{
return this.objective;
}
@SideOnly(Side.CLIENT)
public int getScoreValue()
{
return this.value;
}
@SideOnly(Side.CLIENT)
public SPacketUpdateScore.Action getScoreAction()
{
return this.action;
}
public static enum Action
{
CHANGE,
REMOVE;
}
} | lgpl-2.1 |
soul2zimate/wildfly-core | testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/slavereconnect/deployment/ServiceActivatorDeploymentFour.java | 1555 | /*
* JBoss, Home of Professional Open Source.
* Copyright ${year}, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.as.test.integration.domain.slavereconnect.deployment;
/**
* ServiceActivator that installs itself as a service and sets a set of system
* properties read from a "service-activator-deployment.properties" resource in the deployment.
* If no resource is available, sets a default property.
*
* @author Brian Stansberry (c) 2014 Red Hat Inc.
*/
public class ServiceActivatorDeploymentFour extends ServiceActivatorBaseDeployment {
public ServiceActivatorDeploymentFour() {
super("four");
}
}
| lgpl-2.1 |
PatidarWeb/opencms-core | modules/org.opencms.workplace/resources/system/workplace/galleries/imagegallery/js/integrator_editor.js | 20860 | <%@ page import="org.opencms.util.CmsStringUtil, org.opencms.workplace.galleries.*" %><%
A_CmsAjaxGallery wp = new CmsAjaxImageGallery(pageContext, request, response);
String editedResource = "";
if (CmsStringUtil.isNotEmpty(wp.getParamResource())) {
editedResource = wp.getParamResource();
}
%><%= wp.getJsp().getContent("/system/workplace/resources/editors/fckeditor/editor/dialog/common/fck_dialog_common.js") %>
/* Initialize important FCKeditor variables from editor. */
var dialog = window.parent;
var oEditor = dialog.InnerDialogLoaded();
var FCK = oEditor.FCK;
var FCKConfig = oEditor.FCKConfig;
var FCKBrowserInfo = oEditor.FCKBrowserInfo;
/* Enables or disables the enhanced image dialog options. */
var showEnhancedOptions = FCKConfig.ShowEnhancedOptions;
var useTbForLinkOriginal = FCKConfig.UseTbForLinkOriginal;
/* The selected image (if available). */
var oImage = null;
/* The active link. */
var oLink = null;
/* The span around the image, if present. */
var oSpan = null;
/* Absolute path to the JSP that displays the image in original size. */
var vfsPopupUri = "<%= wp.getJsp().link("/system/workplace/editors/fckeditor/plugins/ocmsimage/popup.html") %>";
/* Size of the preview area. */
previewX = 600;
previewY = 230;
imagesPerPage = 12;
/* Initialize the dialog values. */
initValues = {};
initValues.dialogmode = "<% if (CmsStringUtil.isEmpty(request.getParameter(A_CmsAjaxGallery.PARAM_DIALOGMODE))) { out.print(""); } else { out.print(request.getParameter(A_CmsAjaxGallery.PARAM_DIALOGMODE)); } %>";
initValues.viewonly = false;
initValues.editedresource = "<%= editedResource %>";
/* Initializes the image gallery popup window. */
function initPopup() {
if (showEnhancedOptions == true) {
// show additional fields in enhanced mode
$("#enhAltCheck").show();
$("#enhAltBt").show();
$("#enhCopy").show();
$("#enhOrig").show();
} else {
// common mode, hide enhanced options and enlarge preview area
$("#enhAltCheck").hide();
$("#enhAltBt").hide();
$("#enhCopy").hide();
$("#enhOrig").hide();
previewY = 270;
$("#previewwrapper").height(270);
$("#imgoptions").height(108);
}
// load eventually selected image and information
loadSelection();
$("#galleryresetsearchbutton").hide();
$("#categoryresetsearchbutton").hide();
if (initValues.itempath != null && initValues.itempath != "") {
$.post(vfsPathAjaxJsp, { action: "getactiveitem", itempath: initValues.itempath}, function(data){ loadActiveItem(data, true); });
} else {
$tabs.tabs("select", 1);
$tabs.tabs("disable", 0);
$tabs.tabs("disable", 3);
}
// load galleries and categories
setTimeout("getGalleries();", 50);
setTimeout("getCategories();", 100);
}
/* Do additional stuff when active image is loaded. */
function activeImageAdditionalActions(isInitial) {
if (!isInitial == true) {
resetCopyrightText();
var imgTitle = activeItem.title;
if (activeItem.description != "") {
imgTitle = activeItem.description;
}
GetE("txtAlt").value = imgTitle;
}
// activate the "OK" button of the dialog
window.parent.SetOkButton(true);
}
/* Opens the file browser popup for the link dialog. */
function LnkBrowseServer() {
OpenFileBrowser(FCKConfig.LinkBrowserURL, FCKConfig.LinkBrowserWindowWidth, FCKConfig.LinkBrowserWindowHeight);
}
/* Triggered by the file browser popup to set the selected URL in the input field. */
function SetUrl( url, width, height, alt ) {
GetE("txtLnkUrl").value = url;
}
/* Loads the selected image from the editor, if available. */
function loadSelection() {
// get the selected image
oImage = dialog.Selection.GetSelectedElement();
if (oImage && oImage.tagName != "IMG" && oImage.tagName != "SPAN" && !(oImage.tagName == "INPUT" && oImage.type == "image")) {
oImage = null;
}
// get the active link
oLink = dialog.Selection.GetSelection().MoveToAncestorNode("A");
if (!oImage) {
// no image selected, nothing to do...
GetE('cmbAlign').value = "left";
GetE("txtHSpace").value = "5";
GetE("txtVSpace").value = "5";
GetE("imageBorder").checked = true;
return;
}
var altText = "";
var copyText = "";
var imgBorder = false;
var imgHSp = "";
var imgVSp = "";
var imgAlign = GetAttribute(oImage, "align", "");;
if (dialog.Selection.GetSelection().HasAncestorNode("SPAN") || dialog.Selection.GetSelection().HasAncestorNode("TABLE")) {
if (FCK.Selection.HasAncestorNode("SPAN")) {
oSpan = dialog.Selection.GetSelection().MoveToAncestorNode("SPAN");
} else {
oSpan = dialog.Selection.GetSelection().MoveToAncestorNode("TABLE");
}
try {
var idPart = oSpan.getAttribute("id").substring(1);
if (idPart == oImage.getAttribute("id").substring(1)) {
var altElem = oEditor.FCK.EditorDocument.getElementById("s" + idPart);
if (altElem) {
altText = altElem.firstChild.data;
GetE("insertAlt").checked = true;
}
var cpElem = oEditor.FCK.EditorDocument.getElementById("c" + idPart);
if (cpElem) {
copyText = cpElem.firstChild.data;
GetE("insertCopyright").checked = true;
}
var divElem = oEditor.FCK.EditorDocument.getElementById("a" + idPart);
imgHSp = divElem.style.marginLeft;
if (imgAlign == "left") {
imgHSp = divElem.style.marginRight;
} else if (imgAlign == "right") {
imgHSp = divElem.style.marginLeft;
}
imgVSp = divElem.style.marginBottom;
}
} catch (e) {}
} else {
if (imgAlign == "left") {
imgHSp = oImage.style.marginRight;
imgVSp = oImage.style.marginBottom;
if (imgHSp == "") {
imgHSp = GetAttribute(oImage, "hspace", "");
}
if (imgVSp == "") {
imgVSp = GetAttribute(oImage, "vspace", "");
}
} else if (imgAlign == "right") {
imgHSp = oImage.style.marginLeft;
imgVSp = oImage.style.marginBottom;
if (imgHSp == "") {
imgHSp = GetAttribute(oImage, "hspace", "");
}
if (imgVSp == "") {
imgVSp = GetAttribute(oImage, "vspace", "");
}
} else {
imgHSp = GetAttribute(oImage, "hspace", "");
imgVSp = GetAttribute(oImage, "vspace", "");
}
}
var cssTxt = oImage.style.cssText;
if (showEnhancedOptions) {
if (imgAlign == "left") {
cssTxt = cssTxt.replace(/margin-right:\s*\d+px;/, "");
cssTxt = cssTxt.replace(/margin-bottom:\s*\d+px;/, "");
} else if (imgAlign == "right") {
cssTxt = cssTxt.replace(/margin-left:\s*\d+px;/, "");
cssTxt = cssTxt.replace(/margin-bottom:\s*\d+px;/, "");
}
}
if (altText == "") {
altText = GetAttribute(oImage, "alt", "");
}
var sUrl = oImage.getAttribute("_fcksavedurl");
if (sUrl == null) {
sUrl = GetAttribute(oImage, "src", "");
}
var paramIndex = sUrl.indexOf("?__scale");
if (paramIndex != -1) {
initValues.scale = sUrl.substring(paramIndex + 9);
sUrl = sUrl.substring(0, paramIndex);
}
initValues.itempath = sUrl;
GetE("txtAlt").value = altText;
if (copyText != "") {
GetE("txtCopyright").value = copyText;
}
if (isNaN(imgHSp) && imgHSp.indexOf("px") != -1) {
imgHSp = imgHSp.substring(0, imgHSp.length - 2);
}
if (isNaN(imgVSp) && imgVSp.indexOf("px") != -1) {
imgVSp = imgVSp.substring(0, imgVSp.length - 2);
}
if (imgHSp != "" || imgVSp != "") {
imgBorder = true;
}
if (imgBorder) {
GetE("txtVSpace").value = imgVSp;
GetE("txtHSpace").value = imgHSp;
GetE("imageBorder").checked = true;
}
GetE("cmbAlign").value = imgAlign;
var iWidth, iHeight;
var regexSize = /^\s*(\d+)px\s*$/i ;
if (oImage.style.width) {
var aMatch = oImage.style.width.match(regexSize);
if (aMatch) {
iWidth = aMatch[1];
oImage.style.width = "";
}
}
if (oImage.style.height) {
var aMatch = oImage.style.height.match(regexSize);
if (aMatch) {
iHeight = aMatch[1];
oImage.style.height = "";
}
}
iWidth = iWidth ? iWidth : GetAttribute(oImage, "width", "");
iHeight = iHeight ? iHeight : GetAttribute(oImage, "height", "");
initValues.imgwidth = "" + iWidth;
initValues.imgheight = "" + iHeight;
// get Advanced Attributes
GetE("txtAttId").value = oImage.id;
GetE("cmbAttLangDir").value = oImage.dir;
GetE("txtAttLangCode").value = oImage.lang;
GetE("txtAttTitle").value = oImage.title;
GetE("txtAttClasses").value = oImage.getAttribute("class", 2) || "";
GetE("txtLongDesc").value = oImage.longDesc;
GetE("txtAttStyle").value = cssTxt;
if (oLink) {
var lnkUrl = oLink.getAttribute("_fcksavedurl");
if (lnkUrl == null) {
lnkUrl = oLink.getAttribute("href", 2);
}
if (lnkUrl != sUrl) {
GetE("txtLnkUrl").value = lnkUrl;
GetE("cmbLnkTarget").value = oLink.target;
}
var idAttr = oLink.id;
if (idAttr != null && idAttr.indexOf("limg_") == 0) {
GetE("linkOriginal").checked = true;
}
}
}
/* Resets the image alternative text to the original value. */
function resetAltText() {
var imgTitle = activeItem.title;
if (activeItem.description != "") {
imgTitle = activeItem.description;
}
GetE("txtAlt").value = imgTitle;
}
/* Resets the image copyright text to the original value. */
function resetCopyrightText() {
var copyText = activeItem.copyright;
if (copyText == null || copyText == "") {
copyText = "";
} else {
copyText = "© " + copyText;
}
GetE("txtCopyright").value = copyText;
}
/* Toggles the image spacing values. */
function setImageBorder() {
if (insertImageBorder()) {
var hSp = GetE("txtHSpace").value;
if (hSp == "") {
GetE("txtHSpace").value = "5";
}
var vSp = GetE("txtVSpace").value;
if (vSp == "") {
GetE("txtVSpace").value = "5";
}
} else {
GetE("txtHSpace").value = "";
GetE("txtVSpace").value = "";
}
}
/* Returns if the image border checkbox is checked or not. */
function insertImageBorder() {
return checkChecked("imageBorder");
}
/* Returns if the link to original image checkbox is checked or not. */
function insertLinkToOriginal() {
return checkChecked("linkOriginal");
}
/* Returns if the sub title checkbox is checked or not. */
function insertSubTitle() {
return checkChecked("insertAlt");
}
/* Returns if the copyright checkbox is checked or not. */
function insertCopyright() {
return checkChecked("insertCopyright");
}
/* Helper method to determine if a checkbox is checked or not. */
function checkChecked(elemName) {
var elem = GetE(elemName);
if (elem) {
return elem.checked;
}
return false;
}
/* Returns if enhanced options are used and sub title or copyright should be inserted. */
function isEnhancedPreview() {
return showEnhancedOptions && (insertSubTitle() || insertCopyright());
}
/* The OK button was hit, called by editor button click event. */
function Ok() {
var bHasImage = oImage != null;
var imgCreated = false;
if (!bHasImage) {
oImage = FCK.InsertElement("img");
// set flag that image is newly created
imgCreated = true;
} else {
oEditor.FCKUndo.SaveUndoStep();
}
updateImage(oImage);
// now its getting difficult, be careful when modifying anything below this comment...
if (isEnhancedPreview() && oLink) {
// original link has to be removed if a span is created in enhanced options
FCK.Selection.SelectNode(oLink);
FCK.ExecuteNamedCommand("Unlink");
}
// now we set the image object either to the image or in case of enhanced options to a span element
oImage = createEnhancedImage();
if (showEnhancedOptions && oSpan != null && (oSpan.id.substring(0, 5) == "aimg_" || oSpan.id.substring(0, 5) == "timg_")) {
// span is already present, select it
FCK.Selection.SelectNode(oSpan);
// remove child elements of span
while (oSpan.firstChild != null) {
oSpan.removeChild(oSpan.firstChild);
}
}
if (!imgCreated) {
// delete the selection (either the image or the complete span) if the image was not freshly created
FCK.Selection.Delete();
// now insert the new element
oImage = oEditor.FCK.InsertElementAndGetIt(oImage);
} else {
// this handles the initial creation of an image, might be buggy...
if (!oEditor.FCKBrowserInfo.IsIE) {
// we have to differ here, otherwise the stupid IE creates the image twice!
oImage = oEditor.FCK.InsertElementAndGetIt(oImage);
} else if (isEnhancedPreview()) {
// in IE... insert the new element to make sure the span is inserted
oImage = oEditor.FCK.InsertElementAndGetIt(oImage);
}
}
if (oImage.tagName != "SPAN") {
// the object to insert is a simple image, check the link to set
FCK.Selection.SelectNode(oImage);
oLink = FCK.Selection.MoveToAncestorNode("A");
var sLnkUrl = GetE("txtLnkUrl").value.Trim();
var linkOri = "";
if (insertLinkToOriginal()) {
sLnkUrl = "#";
linkOri = getLinkToOriginal();
} else if (sLnkUrl == "#") {
sLnkUrl = "";
}
if (sLnkUrl.length == 0) {
if (oLink) {
oLink.removeAttribute("class");
FCK.ExecuteNamedCommand("Unlink");
}
} else {
if (oLink) {
// remove an existing link and create it newly, because otherwise the "onclick" attribute does not vanish in Mozilla
oLink.removeAttribute("class");
FCK.ExecuteNamedCommand("Unlink");
oLink = oEditor.FCK.CreateLink(sLnkUrl)[0];
} else {
// creating a new link
if (!bHasImage) {
oEditor.FCKSelection.SelectNode(oImage);
}
oLink = oEditor.FCK.CreateLink(sLnkUrl)[0];
if (!bHasImage) {
oEditor.FCKSelection.SelectNode(oLink);
oEditor.FCKSelection.Collapse(false);
}
}
if (linkOri != "") {
// set the necessary attributes for the link to original image
try {
if (useTbForLinkOriginal == true) {
oLink.setAttribute("href", linkOri);
oLink.setAttribute("title", GetE("txtAlt").value);
oLink.setAttribute("class", "thickbox");
sLnkUrl = linkOri;
} else {
oLink.setAttribute("onclick", linkOri);
}
oLink.setAttribute("id", "limg_" + activeItem.hash);
oImage.setAttribute("border", "0");
} catch (e) {}
}
try {
SetAttribute(oLink, "_fcksavedurl", sLnkUrl);
SetAttribute(oLink, "target", GetE("cmbLnkTarget").value);
} catch (e) {}
}
} // end simple image tag
return true;
}
/* Creates the enhanced image HTML if configured. */
function createEnhancedImage() {
if (isEnhancedPreview()) {
// sub title and/or copyright information has to be inserted
var oNewElement = oEditor.FCK.EditorDocument.createElement("SPAN");
// now set the span attributes
var st = "width: " + GetE("txtWidth").value + "px;";
var al = GetE("cmbAlign").value;
if (al == "left" || al == "right") {
st += " float: " + al + ";";
}
var imgVSp = GetE('txtVSpace').value;
var imgHSp = GetE('txtHSpace').value;
if (imgVSp != "" || imgHSp != "") {
if (imgVSp == "") {
imgVSp = "0";
}
if (imgHSp == "") {
imgHSp = "0";
}
if (showEnhancedOptions && al != "") {
var marginH = "right";
if (al == "right") {
marginH = "left";
}
st += "margin-bottom: " + imgVSp + "px; margin-" + marginH + ": " + imgHSp + "px;";
} else {
st += "margin: " + imgVSp + "px " + imgHSp + "px " + imgVSp + "px " + imgHSp + "px";
}
}
oNewElement.style.cssText = st;
SetAttribute(oNewElement, "id", "aimg_" + activeItem.hash);
// insert the image
if (insertLinkToOriginal()) {
var oLinkOrig = oEditor.FCK.EditorDocument.createElement("A");
if (useTbForLinkOriginal == true) {
oLinkOrig.href = getLinkToOriginal();
oLinkOrig.setAttribute("title", activeItem.title);
oLinkOrig.setAttribute("class", "thickbox");
} else {
oLinkOrig.href = "#";
oLinkOrig.setAttribute("onclick", getLinkToOriginal());
}
oLinkOrig.setAttribute("id", "limg_" + activeItem.hash);
oImage.setAttribute("border", "0");
oLinkOrig.appendChild(oImage);
oNewElement.appendChild(oLinkOrig);
} else {
// simply add image
oNewElement.appendChild(oImage);
}
if (insertCopyright()) {
// insert the 2nd span with the copyright information
var copyText = GetE("txtCopyright").value;
if (copyText == "") {
copyText = "© " + activeItem.copyright;
}
var oSpan2 = oEditor.FCK.EditorDocument.createElement("SPAN");
oSpan2.style.cssText = "display: block; clear: both;";
oSpan2.className = "imgCopyright";
oSpan2.id = "cimg_" + activeItem.hash;
oSpan2.innerHTML = copyText;
oNewElement.appendChild(oSpan2);
}
if (insertSubTitle()) {
// insert the 3rd span with the subtitle
var altText = GetE("txtAlt").value;
if (altText == "") {
altText = activeItem.title;
}
var oSpan3 = oEditor.FCK.EditorDocument.createElement("SPAN");
oSpan3.style.cssText = "display: block; clear: both;";
oSpan3.className = "imgSubtitle";
oSpan3.id = "simg_" + activeItem.hash;
oSpan3.innerHTML = altText;
oNewElement.appendChild(oSpan3);
}
// return the new object
return oNewElement;
} else {
// return the original object
return oImage;
}
}
/* Creates the link to the original image. */
function getLinkToOriginal() {
var linkUri = "";
if (useTbForLinkOriginal == true) {
linkUri += activeItem.linkpath;
} else {
linkUri += "javascript:window.open('";
linkUri += vfsPopupUri;
linkUri += "?uri=";
linkUri += activeItem.linkpath;
linkUri += "', 'original', 'width=";
linkUri += activeItem.width;
linkUri += ",height=";
linkUri += activeItem.height;
linkUri += ",location=no,menubar=no,status=no,toolbar=no');";
}
return linkUri;
}
/* Updates the image element with the values of the input fields. */
function updateImage(e) {
var txtUrl = activeItem.linkpath;
var newWidth = activeItem.width;
var newHeight = activeItem.height;
if (initValues.scale == null || initValues.scale == "") {
initValues.scale = "c:transparent,t:4,r=0,q=70";
} else {
if (initValues.scale.lastIndexOf(",") == initValues.scale.length - 1) {
initValues.scale = initValues.scale.substring(0, initValues.scale.length - 1);
}
}
if (activeItem.isCropped) {
var newScale = "";
if (initValues.scale != null && initValues.scale != "") {
newScale += ",";
}
newScale += "cx:" + activeItem.cropx;
newScale += ",cy:" + activeItem.cropy;
newScale += ",cw:" + activeItem.cropw;
newScale += ",ch:" + activeItem.croph;
initValues.scale += newScale;
} else if (getScaleValue(initValues.scale, "cx") != "") {
initValues.scale = removeScaleValue(initValues.scale, "cx");
initValues.scale = removeScaleValue(initValues.scale, "cy");
initValues.scale = removeScaleValue(initValues.scale, "cw");
initValues.scale = removeScaleValue(initValues.scale, "ch");
}
initValues.scale = removeScaleValue(initValues.scale, "w");
initValues.scale = removeScaleValue(initValues.scale, "h");
var newScale = "";
var sizeChanged = false;
if (initValues.scale != null && initValues.scale != "") {
newScale += ",";
}
if (activeItem.newwidth > 0 && activeItem.width != activeItem.newwidth) {
sizeChanged = true;
newScale += "w:" + activeItem.newwidth;
newWidth = activeItem.newwidth;
}
if (activeItem.newheight > 0 && activeItem.height != activeItem.newheight ) {
if (sizeChanged == true) {
newScale += ",";
}
sizeChanged = true;
newScale += "h:" + activeItem.newheight;
newHeight = activeItem.newheight;
}
initValues.scale += newScale;
if (activeItem.isCropped || sizeChanged) {
txtUrl += "?__scale=" + initValues.scale;
}
e.src = txtUrl;
SetAttribute(e, "_fcksavedurl", txtUrl);
SetAttribute(e, "alt" , GetE("txtAlt").value);
SetAttribute(e, "width" , newWidth);
SetAttribute(e, "height", newHeight);
SetAttribute(e, "border", "");
SetAttribute(e, "align" , GetE("cmbAlign").value);
var styleAttr = "";
SetAttribute(e, "vspace", "");
SetAttribute(e, "hspace", "");
if (!isEnhancedPreview()) {
var imgAlign = GetE("cmbAlign").value;
var vSp = GetE("txtVSpace").value;
var hSp = GetE("txtHSpace").value;
if (vSp == "") {
vSp = "0";
}
if (hSp == "") {
hSp = "0";
}
if (showEnhancedOptions && imgAlign == "left") {
styleAttr = "margin-bottom: " + vSp + "px; margin-right: " + hSp + "px;";
} else if (showEnhancedOptions && imgAlign == "right") {
styleAttr = "margin-bottom: " + vSp + "px; margin-left: " + hSp + "px;";
} else {
SetAttribute(e, "vspace", GetE("txtVSpace").value);
SetAttribute(e, "hspace", GetE("txtHSpace").value);
}
if (insertLinkToOriginal()) {
SetAttribute(e, "border", "0");
}
}
// advanced attributes
var idVal = GetE("txtAttId").value;
if (idVal == "" || idVal.substring(0, 5) == "iimg_") {
idVal = "iimg_" + activeItem.hash;
}
SetAttribute(e, "id", idVal);
SetAttribute(e, "dir", GetE("cmbAttLangDir").value);
SetAttribute(e, "lang", GetE("txtAttLangCode").value);
SetAttribute(e, "title", GetE("txtAttTitle").value);
SetAttribute(e, "class", GetE("txtAttClasses").value);
SetAttribute(e, "longDesc", GetE("txtLongDesc").value);
styleAttr += GetE("txtAttStyle").value;
if (oEditor.FCKBrowserInfo.IsIE) {
e.style.cssText = styleAttr;
} else {
SetAttribute(e, "style", styleAttr);
}
} | lgpl-2.1 |
Hitcents/iOS4Unity | Assets/NUnitLite/NUnitLite-0.7.0/Constraints/TrueConstraint.cs | 1652 | // ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// 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.
// ***********************************************************************
namespace NUnit.Framework.Constraints
{
/// <summary>
/// TrueConstraint tests that the actual value is true
/// </summary>
public class TrueConstraint : BasicConstraint
{
/// <summary>
/// Initializes a new instance of the <see cref="T:TrueConstraint"/> class.
/// </summary>
public TrueConstraint() : base(true, "True") { }
}
} | apache-2.0 |
q474818917/solr-5.2.0 | lucene/analysis/common/src/java/org/apache/lucene/analysis/shingle/ShingleAnalyzerWrapper.java | 5671 | package org.apache.lucene.analysis.shingle;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.AnalyzerWrapper;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
/**
* A ShingleAnalyzerWrapper wraps a {@link ShingleFilter} around another {@link Analyzer}.
* <p>
* A shingle is another name for a token based n-gram.
* </p>
*/
public final class ShingleAnalyzerWrapper extends AnalyzerWrapper {
private final Analyzer delegate;
private final int maxShingleSize;
private final int minShingleSize;
private final String tokenSeparator;
private final boolean outputUnigrams;
private final boolean outputUnigramsIfNoShingles;
private final String fillerToken;
public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer) {
this(defaultAnalyzer, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE);
}
public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer, int maxShingleSize) {
this(defaultAnalyzer, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, maxShingleSize);
}
public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer, int minShingleSize, int maxShingleSize) {
this(defaultAnalyzer, minShingleSize, maxShingleSize, ShingleFilter.DEFAULT_TOKEN_SEPARATOR,
true, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
}
/**
* Creates a new ShingleAnalyzerWrapper
*
* @param delegate Analyzer whose TokenStream is to be filtered
* @param minShingleSize Min shingle (token ngram) size
* @param maxShingleSize Max shingle size
* @param tokenSeparator Used to separate input stream tokens in output shingles
* @param outputUnigrams Whether or not the filter shall pass the original
* tokens to the output stream
* @param outputUnigramsIfNoShingles Overrides the behavior of outputUnigrams==false for those
* times when no shingles are available (because there are fewer than
* minShingleSize tokens in the input stream)?
* Note that if outputUnigrams==true, then unigrams are always output,
* regardless of whether any shingles are available.
* @param fillerToken filler token to use when positionIncrement is more than 1
*/
public ShingleAnalyzerWrapper(
Analyzer delegate,
int minShingleSize,
int maxShingleSize,
String tokenSeparator,
boolean outputUnigrams,
boolean outputUnigramsIfNoShingles,
String fillerToken) {
super(delegate.getReuseStrategy());
this.delegate = delegate;
if (maxShingleSize < 2) {
throw new IllegalArgumentException("Max shingle size must be >= 2");
}
this.maxShingleSize = maxShingleSize;
if (minShingleSize < 2) {
throw new IllegalArgumentException("Min shingle size must be >= 2");
}
if (minShingleSize > maxShingleSize) {
throw new IllegalArgumentException
("Min shingle size must be <= max shingle size");
}
this.minShingleSize = minShingleSize;
this.tokenSeparator = (tokenSeparator == null ? "" : tokenSeparator);
this.outputUnigrams = outputUnigrams;
this.outputUnigramsIfNoShingles = outputUnigramsIfNoShingles;
this.fillerToken = fillerToken;
}
/**
* Wraps {@link StandardAnalyzer}.
*/
public ShingleAnalyzerWrapper() {
this(ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE);
}
/**
* Wraps {@link StandardAnalyzer}.
*/
public ShingleAnalyzerWrapper(int minShingleSize, int maxShingleSize) {
this(new StandardAnalyzer(), minShingleSize, maxShingleSize);
}
/**
* The max shingle (token ngram) size
*
* @return The max shingle (token ngram) size
*/
public int getMaxShingleSize() {
return maxShingleSize;
}
/**
* The min shingle (token ngram) size
*
* @return The min shingle (token ngram) size
*/
public int getMinShingleSize() {
return minShingleSize;
}
public String getTokenSeparator() {
return tokenSeparator;
}
public boolean isOutputUnigrams() {
return outputUnigrams;
}
public boolean isOutputUnigramsIfNoShingles() {
return outputUnigramsIfNoShingles;
}
public String getFillerToken() {
return fillerToken;
}
@Override
public final Analyzer getWrappedAnalyzer(String fieldName) {
return delegate;
}
@Override
protected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {
ShingleFilter filter = new ShingleFilter(components.getTokenStream(), minShingleSize, maxShingleSize);
filter.setMinShingleSize(minShingleSize);
filter.setMaxShingleSize(maxShingleSize);
filter.setTokenSeparator(tokenSeparator);
filter.setOutputUnigrams(outputUnigrams);
filter.setOutputUnigramsIfNoShingles(outputUnigramsIfNoShingles);
filter.setFillerToken(fillerToken);
return new TokenStreamComponents(components.getTokenizer(), filter);
}
}
| apache-2.0 |
NSAmelchev/ignite | modules/platforms/dotnet/Apache.Ignite.Core/IIgnite.cs | 24582 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.DataStructures;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Plugin;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Main entry point for all Ignite APIs.
/// You can obtain an instance of <see cref="IIgnite"/> through <see cref="Ignition.GetIgnite()"/>,
/// or for named grids you can use <see cref="Ignition.GetIgnite(string)"/>. Note that you
/// can have multiple instances of <see cref="IIgnite"/> running in the same process by giving
/// each instance a different name.
/// <para/>
/// All members are thread-safe and may be used concurrently from multiple threads.
/// </summary>
public interface IIgnite : IDisposable
{
/// <summary>
/// Gets the name of the grid this Ignite instance (and correspondingly its local node) belongs to.
/// Note that single process can have multiple Ignite instances all belonging to different grids. Grid
/// name allows to indicate to what grid this particular Ignite instance (i.e. Ignite runtime and its
/// local node) belongs to.
/// <p/>
/// If default Ignite instance is used, then <c>null</c> is returned. Refer to <see cref="Ignition"/> documentation
/// for information on how to start named grids.
/// </summary>
/// <returns>Name of the grid, or <c>null</c> for default grid.</returns>
string Name { get; }
/// <summary>
/// Gets an instance of <see cref="ICluster" /> interface.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ICluster GetCluster();
/// <summary>
/// Gets compute functionality over this grid projection. All operations
/// on the returned ICompute instance will only include nodes from
/// this projection.
/// </summary>
/// <returns>Compute instance over this grid projection.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ICompute GetCompute();
/// <summary>
/// Gets Ignite version.
/// </summary>
/// <returns>Ignite node version.</returns>
IgniteProductVersion GetVersion();
/// <summary>
/// Gets the cache instance for the given name to work with keys and values of specified types.
/// <para/>
/// You can get instances of ICache of the same name, but with different key/value types.
/// These will use the same named cache, but only allow working with entries of specified types.
/// Attempt to retrieve an entry of incompatible type will result in <see cref="InvalidCastException"/>.
/// Use <see cref="GetCache{TK,TV}"/> in order to work with entries of arbitrary types.
/// </summary>
/// <param name="name">Cache name.</param>
/// <returns>Cache instance for given name.</returns>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
ICache<TK, TV> GetCache<TK, TV>(string name);
/// <summary>
/// Gets existing cache with the given name or creates new one using template configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="name">Cache name.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> GetOrCreateCache<TK, TV>(string name);
/// <summary>
/// Gets existing cache with the given name or creates new one using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration);
/// <summary>
/// Gets existing cache with the given name or creates new one using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// /// <param name="nearConfiguration">Near cache configuration for client.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration);
/// <summary>
/// Gets existing cache with the given name or creates new one using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// /// <param name="nearConfiguration">Near cache configuration for client.</param>
/// <param name="platformCacheConfiguration">Platform cache configuration. Can be null.
/// When not null, native .NET cache is created additionally.</param>
/// <returns>Existing or newly created cache.</returns>
[IgniteExperimental]
ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration, PlatformCacheConfiguration platformCacheConfiguration);
/// <summary>
/// Dynamically starts new cache using template configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="name">Cache name.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> CreateCache<TK, TV>(string name);
/// <summary>
/// Dynamically starts new cache using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration);
/// <summary>
/// Dynamically starts new cache using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <param name="nearConfiguration">Near cache configuration for client.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration);
/// <summary>
/// Dynamically starts new cache using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <param name="nearConfiguration">Near cache configuration for client.</param>
/// <param name="platformCacheConfiguration">Platform cache configuration. Can be null.
/// When not null, native .NET cache is created additionally.</param>
/// <returns>Existing or newly created cache.</returns>
[IgniteExperimental]
ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration, PlatformCacheConfiguration platformCacheConfiguration);
/// <summary>
/// Destroys dynamically created (with <see cref="CreateCache{TK,TV}(string)"/> or
/// <see cref="GetOrCreateCache{TK,TV}(string)"/>) cache.
/// </summary>
/// <param name="name">The name of the cache to stop.</param>
void DestroyCache(string name);
/// <summary>
/// Gets a new instance of data streamer associated with given cache name. Data streamer
/// is responsible for loading external data into Ignite. For more information
/// refer to <see cref="IDataStreamer{K,V}"/> documentation.
/// </summary>
/// <param name="cacheName">Cache name (<c>null</c> for default cache).</param>
/// <returns>Data streamer.</returns>
IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName);
/// <summary>
/// Gets an instance of <see cref="IBinary"/> interface.
/// </summary>
/// <returns>Instance of <see cref="IBinary"/> interface</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IBinary GetBinary();
/// <summary>
/// Gets affinity service to provide information about data partitioning and distribution.
/// </summary>
/// <param name="name">Cache name.</param>
/// <returns>Cache data affinity service.</returns>
ICacheAffinity GetAffinity(string name);
/// <summary>
/// Gets Ignite transactions facade.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ITransactions GetTransactions();
/// <summary>
/// Gets messaging facade over all cluster nodes.
/// </summary>
/// <returns>Messaging instance over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IMessaging GetMessaging();
/// <summary>
/// Gets events facade over all cluster nodes.
/// </summary>
/// <returns>Events facade over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IEvents GetEvents();
/// <summary>
/// Gets services facade over all cluster nodes.
/// </summary>
/// <returns>Services facade over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IServices GetServices();
/// <summary>
/// Gets an atomic long with specified name from cache.
/// Creates new atomic long in cache if it does not exist and <c>create</c> is true.
/// </summary>
/// <param name="name">Name of the atomic long.</param>
/// <param name="initialValue">
/// Initial value for the atomic long. Ignored if <c>create</c> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic long should be created if it does not exist.</param>
/// <returns>Atomic long instance with specified name,
/// or null if it does not exist and <c>create</c> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic long could not be fetched or created.</exception>
IAtomicLong GetAtomicLong(string name, long initialValue, bool create);
/// <summary>
/// Gets an atomic sequence with specified name from cache.
/// Creates new atomic sequence in cache if it does not exist and <paramref name="create"/> is true.
/// </summary>
/// <param name="name">Name of the atomic sequence.</param>
/// <param name="initialValue">
/// Initial value for the atomic sequence. Ignored if <paramref name="create"/> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic sequence should be created if it does not exist.</param>
/// <returns>Atomic sequence instance with specified name,
/// or null if it does not exist and <paramref name="create"/> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic sequence could not be fetched or created.</exception>
IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create);
/// <summary>
/// Gets an atomic reference with specified name from cache.
/// Creates new atomic reference in cache if it does not exist and <paramref name="create"/> is true.
/// </summary>
/// <param name="name">Name of the atomic reference.</param>
/// <param name="initialValue">
/// Initial value for the atomic reference. Ignored if <paramref name="create"/> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic reference should be created if it does not exist.</param>
/// <returns>Atomic reference instance with specified name,
/// or null if it does not exist and <paramref name="create"/> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic reference could not be fetched or created.</exception>
IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create);
/// <summary>
/// Gets the configuration of this Ignite instance.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IgniteConfiguration GetConfiguration();
/// <summary>
/// Starts a near cache on local client node if cache with specified was previously started.
/// This method does not work on server nodes.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="configuration">The configuration.</param>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <returns>Near cache instance.</returns>
ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration);
/// <summary>
/// Starts a near cache on local client node if cache with specified was previously started.
/// This method does not work on server nodes.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="configuration">The configuration.</param>
/// <param name="platformConfiguration">Platform cache configuration. Can be null.
/// When not null, native .NET cache is created additionally.</param>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <returns>Near cache instance.</returns>
[IgniteExperimental]
ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration,
PlatformCacheConfiguration platformConfiguration);
/// <summary>
/// Gets existing near cache with the given name or creates a new one.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="configuration">The configuration.</param>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <returns>Near cache instance.</returns>
ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration);
/// <summary>
/// Gets existing near cache with the given name or creates a new one.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="configuration">The configuration.</param>
/// <param name="platformConfiguration">Platform cache configuration. Can be null.
/// When not null, native .NET cache is created additionally.</param>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <returns>Near cache instance.</returns>
[IgniteExperimental]
ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration,
PlatformCacheConfiguration platformConfiguration);
/// <summary>
/// Gets the collection of names of currently available caches, or empty collection if there are no caches.
/// </summary>
/// <returns>Collection of names of currently available caches.</returns>
ICollection<string> GetCacheNames();
/// <summary>
/// Gets the logger.
/// <para />
/// See <see cref="IgniteConfiguration.Logger"/> for customization.
/// </summary>
ILogger Logger { get; }
/// <summary>
/// Occurs when node begins to stop. Node is fully functional at this point.
/// See also: <see cref="LifecycleEventType.BeforeNodeStop"/>.
/// </summary>
event EventHandler Stopping;
/// <summary>
/// Occurs when node has stopped. Node can't be used at this point.
/// See also: <see cref="LifecycleEventType.AfterNodeStop"/>.
/// </summary>
event EventHandler Stopped;
/// <summary>
/// Occurs when client node disconnects from the cluster. This event can only occur when this instance
/// runs in client mode (<see cref="IgniteConfiguration.ClientMode"/>).
/// </summary>
event EventHandler ClientDisconnected;
/// <summary>
/// Occurs when client node reconnects to the cluster. This event can only occur when this instance
/// runs in client mode (<see cref="IgniteConfiguration.ClientMode"/>).
/// </summary>
event EventHandler<ClientReconnectEventArgs> ClientReconnected;
/// <summary>
/// Gets the plugin by name.
/// </summary>
/// <typeparam name="T">Plugin type</typeparam>
/// <param name="name">Plugin name.</param>
/// <exception cref="PluginNotFoundException">When plugin with specified name has not been found.</exception>
/// <returns>Plugin instance.</returns>
T GetPlugin<T>(string name) where T : class;
/// <summary>
/// Clears partitions' lost state and moves caches to a normal mode.
/// </summary>
/// <param name="cacheNames">Names of caches to reset partitions for.</param>
void ResetLostPartitions(IEnumerable<string> cacheNames);
/// <summary>
/// Clears partitions' lost state and moves caches to a normal mode.
/// </summary>
/// <param name="cacheNames">Names of caches to reset partitions for.</param>
void ResetLostPartitions(params string[] cacheNames);
/// <summary>
/// Gets a collection of memory metrics, one for each <see cref="MemoryConfiguration.MemoryPolicies"/>.
/// <para />
/// Memory metrics should be enabled with <see cref="MemoryPolicyConfiguration.MetricsEnabled"/>.
/// <para />
/// Obsolete, use <see cref="GetDataRegionMetrics()"/>.
/// </summary>
[Obsolete("Use GetDataRegionMetrics.")]
ICollection<IMemoryMetrics> GetMemoryMetrics();
/// <summary>
/// Gets the memory metrics for the specified memory policy.
/// <para />
/// To get metrics for the default memory region,
/// use <see cref="MemoryConfiguration.DefaultMemoryPolicyName"/>.
/// <para />
/// Obsolete, use <see cref="GetDataRegionMetrics(string)"/>.
/// </summary>
/// <param name="memoryPolicyName">Name of the memory policy.</param>
[Obsolete("Use GetDataRegionMetrics.")]
IMemoryMetrics GetMemoryMetrics(string memoryPolicyName);
/// <summary>
/// Changes Ignite grid state to active or inactive.
/// </summary>
[Obsolete("Use GetCluster().SetActive instead.")]
void SetActive(bool isActive);
/// <summary>
/// Determines whether this grid is in active state.
/// </summary>
/// <returns>
/// <c>true</c> if the grid is active; otherwise, <c>false</c>.
/// </returns>
[Obsolete("Use GetCluster().IsActive instead.")]
bool IsActive();
/// <summary>
/// Gets the persistent store metrics.
/// <para />
/// To enable metrics set <see cref="PersistentStoreConfiguration.MetricsEnabled"/> property
/// in <see cref="IgniteConfiguration.PersistentStoreConfiguration"/>.
/// </summary>
[Obsolete("Use GetDataStorageMetrics.")]
IPersistentStoreMetrics GetPersistentStoreMetrics();
/// <summary>
/// Gets a collection of memory metrics, one for each
/// <see cref="DataStorageConfiguration.DataRegionConfigurations"/>.
/// <para />
/// Metrics should be enabled with <see cref="DataStorageConfiguration.MetricsEnabled"/>.
/// </summary>
ICollection<IDataRegionMetrics> GetDataRegionMetrics();
/// <summary>
/// Gets the memory metrics for the specified data region.
/// <para />
/// To get metrics for the default memory region,
/// use <see cref="DataStorageConfiguration.DefaultDataRegionName"/>.
/// </summary>
/// <param name="dataRegionName">Name of the data region.</param>
IDataRegionMetrics GetDataRegionMetrics(string dataRegionName);
/// <summary>
/// Gets the persistent store metrics.
/// <para />
/// To enable metrics set <see cref="DataStorageConfiguration.MetricsEnabled"/> property
/// in <see cref="IgniteConfiguration.DataStorageConfiguration"/>.
/// </summary>
IDataStorageMetrics GetDataStorageMetrics();
/// <summary>
/// Adds cache configuration template. Name should contain *.
/// Template settings are applied to a cache created with <see cref="CreateCache{K,V}(string)"/> if specified
/// name matches the template name.
/// </summary>
/// <param name="configuration">Configuration.</param>
void AddCacheConfiguration(CacheConfiguration configuration);
/// <summary>
/// Gets or creates a distributed reentrant lock (monitor) with default configuration.
/// </summary>
/// <param name="name">Lock name.</param>
/// <returns><see cref="IIgniteLock"/></returns>
IIgniteLock GetOrCreateLock(string name);
/// <summary>
/// Gets or creates a distributed reentrant lock (monitor).
/// </summary>
/// <param name="configuration">Lock configuration.</param>
/// <param name="create">Whether the lock should be created if it does not exist.</param>
/// <returns><see cref="IIgniteLock"/></returns>
IIgniteLock GetOrCreateLock(LockConfiguration configuration, bool create);
}
}
| apache-2.0 |
Susankha/developer-studio | bps/org.eclipse.bpel.ui/src/org/eclipse/bpel/ui/details/providers/PortTypeTreeContentProvider.java | 2436 | /*******************************************************************************
* Copyright (c) 2005, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.bpel.ui.details.providers;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.bpel.model.partnerlinktype.Role;
import org.eclipse.bpel.ui.details.tree.PortTypeTreeNode;
import org.eclipse.wst.wsdl.Definition;
import org.eclipse.wst.wsdl.PortType;
/**
* Provides a tree of model objects representing some expansion of the underlying graph
* of model objects whose roots are the PortTypes of a Role.
*/
public class PortTypeTreeContentProvider extends ModelTreeContentProvider {
public PortTypeTreeContentProvider(boolean isCondensed) {
super(isCondensed);
}
@Override
public Object[] primGetElements (Object inputElement) {
List list = new LinkedList();
if (inputElement instanceof Role) {
Role r = (Role) inputElement;
list.add(new PortTypeTreeNode((PortType) r.getPortType(), isCondensed));
} else if (inputElement instanceof Definition) {
Definition defn = (Definition) inputElement;
Iterator it = defn.getPortTypes().values().iterator();
while (it.hasNext()) {
PortType element = (PortType) it.next();
list.add ( new PortTypeTreeNode(element,isCondensed));
}
}
// https://jira.jboss.org/browse/JBIDE-6697
// from eclipse.org/bpel rev 1.5 on 5/5/2010 5:13AM by smoser: fix for bidirectional PLT - > Tammo/JAX Session Feedback
else if (inputElement instanceof List){
List inputList = (List) inputElement;
for (Iterator iterator = inputList.iterator(); iterator.hasNext();) {
Definition def = (Definition) iterator.next();
Iterator it = def.getPortTypes().values().iterator();
while (it.hasNext()) {
PortType element = (PortType) it.next();
list.add ( new PortTypeTreeNode(element,isCondensed));
}
}
}
return list.isEmpty() ? EMPTY_ARRAY : list.toArray();
}
}
| apache-2.0 |
andyao/dagger | compiler/src/main/java/dagger/internal/codegen/ComponentProcessingStep.java | 7765 | /*
* Copyright (C) 2014 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dagger.internal.codegen;
import com.google.auto.common.BasicAnnotationProcessor.ProcessingStep;
import com.google.auto.common.MoreElements;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import dagger.Component;
import dagger.Subcomponent;
import dagger.internal.codegen.ComponentDescriptor.Factory;
import dagger.internal.codegen.ComponentValidator.ComponentValidationReport;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Messager;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
/**
* A {@link ProcessingStep} that is responsible for dealing with the {@link Component} annotation
* as part of the {@link ComponentProcessor}.
*
* @author Gregory Kick
*/
final class ComponentProcessingStep extends AbstractComponentProcessingStep {
private final Messager messager;
private final ComponentValidator componentValidator;
private final ComponentValidator subcomponentValidator;
private final BuilderValidator componentBuilderValidator;
private final BuilderValidator subcomponentBuilderValidator;
private final ComponentDescriptor.Factory componentDescriptorFactory;
ComponentProcessingStep(
Messager messager,
ComponentValidator componentValidator,
ComponentValidator subcomponentValidator,
BuilderValidator componentBuilderValidator,
BuilderValidator subcomponentBuilderValidator,
BindingGraphValidator bindingGraphValidator,
Factory componentDescriptorFactory,
BindingGraph.Factory bindingGraphFactory,
ComponentGenerator componentGenerator) {
super(
messager,
bindingGraphValidator,
bindingGraphFactory,
componentGenerator);
this.messager = messager;
this.componentValidator = componentValidator;
this.subcomponentValidator = subcomponentValidator;
this.componentBuilderValidator = componentBuilderValidator;
this.subcomponentBuilderValidator = subcomponentBuilderValidator;
this.componentDescriptorFactory = componentDescriptorFactory;
}
@Override
public Set<Class<? extends Annotation>> annotations() {
return ImmutableSet.<Class<? extends Annotation>>of(Component.class, Component.Builder.class,
Subcomponent.class, Subcomponent.Builder.class);
}
@Override
protected ImmutableSet<ComponentDescriptor> componentDescriptors(
SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) {
Map<Element, ValidationReport<TypeElement>> builderReportsByComponent =
processComponentBuilders(elementsByAnnotation.get(Component.Builder.class));
Set<Element> subcomponentBuilderElements = elementsByAnnotation.get(Subcomponent.Builder.class);
Map<Element, ValidationReport<TypeElement>> builderReportsBySubcomponent =
processSubcomponentBuilders(subcomponentBuilderElements);
Set<Element> subcomponentElements = elementsByAnnotation.get(Subcomponent.class);
Map<Element, ValidationReport<TypeElement>> reportsBySubcomponent =
processSubcomponents(subcomponentElements, subcomponentBuilderElements);
Set<Element> componentElements = elementsByAnnotation.get(Component.class);
ImmutableSet.Builder<ComponentDescriptor> builder = ImmutableSet.builder();
for (Element element : componentElements) {
TypeElement componentTypeElement = MoreElements.asType(element);
ComponentValidationReport report = componentValidator.validate(
componentTypeElement, subcomponentElements, subcomponentBuilderElements);
report.report().printMessagesTo(messager);
if (isClean(
report, builderReportsByComponent, reportsBySubcomponent, builderReportsBySubcomponent)) {
try {
builder.add(componentDescriptorFactory.forComponent(componentTypeElement));
} catch (TypeNotPresentException e) {
// just skip it and get it later
}
}
}
return builder.build();
}
private Map<Element, ValidationReport<TypeElement>> processComponentBuilders(
Set<? extends Element> componentBuilderElements) {
Map<Element, ValidationReport<TypeElement>> builderReportsByComponent = Maps.newHashMap();
for (Element element : componentBuilderElements) {
ValidationReport<TypeElement> report =
componentBuilderValidator.validate(MoreElements.asType(element));
report.printMessagesTo(messager);
builderReportsByComponent.put(element.getEnclosingElement(), report);
}
return builderReportsByComponent;
}
private Map<Element, ValidationReport<TypeElement>> processSubcomponentBuilders(
Set<? extends Element> subcomponentBuilderElements) {
Map<Element, ValidationReport<TypeElement>> builderReportsBySubcomponent = Maps.newHashMap();
for (Element element : subcomponentBuilderElements) {
ValidationReport<TypeElement> report =
subcomponentBuilderValidator.validate(MoreElements.asType(element));
report.printMessagesTo(messager);
builderReportsBySubcomponent.put(element, report);
}
return builderReportsBySubcomponent;
}
private Map<Element, ValidationReport<TypeElement>> processSubcomponents(
Set<? extends Element> subcomponentElements,
Set<? extends Element> subcomponentBuilderElements) {
Map<Element, ValidationReport<TypeElement>> reportsBySubcomponent = Maps.newHashMap();
for (Element element : subcomponentElements) {
ComponentValidationReport report = subcomponentValidator.validate(
MoreElements.asType(element), subcomponentElements, subcomponentBuilderElements);
report.report().printMessagesTo(messager);
reportsBySubcomponent.put(element, report.report());
}
return reportsBySubcomponent;
}
/**
* Returns true if the component's report is clean, its builder report is clean, and all
* referenced subcomponent reports & subcomponent builder reports are clean.
*/
private boolean isClean(ComponentValidationReport report,
Map<Element, ValidationReport<TypeElement>> builderReportsByComponent,
Map<Element, ValidationReport<TypeElement>> reportsBySubcomponent,
Map<Element, ValidationReport<TypeElement>> builderReportsBySubcomponent) {
Element component = report.report().subject();
ValidationReport<?> componentReport = report.report();
if (!componentReport.isClean()) {
return false;
}
ValidationReport<?> builderReport = builderReportsByComponent.get(component);
if (builderReport != null && !builderReport.isClean()) {
return false;
}
for (Element element : report.referencedSubcomponents()) {
ValidationReport<?> subcomponentBuilderReport = builderReportsBySubcomponent.get(element);
if (subcomponentBuilderReport != null && !subcomponentBuilderReport.isClean()) {
return false;
}
ValidationReport<?> subcomponentReport = reportsBySubcomponent.get(element);
if (subcomponentReport != null && !subcomponentReport.isClean()) {
return false;
}
}
return true;
}
}
| apache-2.0 |
avinogradovgg/ignite | modules/core/src/main/java/org/apache/ignite/cache/CacheExistsException.java | 1559 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.cache;
import org.jetbrains.annotations.*;
import javax.cache.*;
/**
* Exception thrown when cache must be created but it already exists.
*/
public class CacheExistsException extends CacheException {
/** Serialization ID. */
private static final long serialVersionUID = 0L;
/**
* @param msg Error message.
*/
public CacheExistsException(String msg) {
super(msg);
}
/**
* @param cause Error cause.
*/
public CacheExistsException(Throwable cause) {
super(cause);
}
/**
* @param msg Error message.
* @param cause Error cause.
*/
public CacheExistsException(String msg, @Nullable Throwable cause) {
super(msg, cause);
}
}
| apache-2.0 |
lokinell/spock | spock-core/src/main/java/org/spockframework/builder/SpockConfigurationGestalt.java | 2255 | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.spockframework.builder;
import java.util.List;
import groovy.lang.*;
import org.spockframework.runtime.IConfigurationRegistry;
public class SpockConfigurationGestalt implements IGestalt {
private final IConfigurationRegistry configurationRegistry;
private final IBlueprint blueprint;
private final List<ISlotFactory> slotFactories;
public SpockConfigurationGestalt(IConfigurationRegistry configurationRegistry, IBlueprint blueprint,
List<ISlotFactory> slotFactories) {
this.configurationRegistry = configurationRegistry;
this.blueprint = blueprint;
this.slotFactories = slotFactories;
}
public IBlueprint getBlueprint() {
return blueprint;
}
public Object getProperty(String name) {
Object config = configurationRegistry.getConfigurationByName(name);
if (config == null) throw new MissingPropertyException("configuration not found");
return config;
}
public void setProperty(String name, Object value) {
throw new MissingPropertyException("configurations cannot be set directly");
}
public Object invokeMethod(String name, Object[] args) {
if (args.length != 1 || !(args[0] instanceof Closure))
throw new MissingMethodException(name, this.getClass(), args);
Object config = configurationRegistry.getConfigurationByName(name);
if (config == null) throw new MissingMethodException(name, this.getClass(), args);
ClosureBlueprint blueprint = new ClosureBlueprint((Closure)args[0], config);
IGestalt gestalt = new PojoGestalt(config, config.getClass(), blueprint, slotFactories);
new Sculpturer().$form(gestalt);
return null;
}
}
| apache-2.0 |
aldian/tensorflow | tensorflow/python/kernel_tests/sparse_split_op_test.py | 12572 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for SparseReorder."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import errors
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import sparse_ops
from tensorflow.python.platform import test
class SparseSplitOpTest(test.TestCase):
def _SparseTensor_4x6(self):
# [0 | |2 | |4 |5 ]
# [ |11| |13|14| ]
# [20| | |23| |25]
# [30| |32|33| |35]
ind = np.array([[0, 0], [0, 2], [0, 4], [0, 5], [1, 1], [1, 3], [1, 4],
[2, 0], [2, 3], [2, 5], [3, 0], [3, 2], [3, 3],
[3, 5]]).astype(np.int64)
val = np.array(
[0, 2, 4, 5, 11, 13, 14, 20, 23, 25, 30, 32, 33, 35]).astype(np.int64)
shape = np.array([4, 6]).astype(np.int64)
return sparse_tensor.SparseTensor(ind, val, shape)
def _SparseTensor_5x7(self):
# [0 | |2 | |4 |5 | ]
# [ |11| |13|14| |16]
# [20| | |23| |25| ]
# [30| |32|33| |35| ]
# [ |41| | |44| |46]
ind = np.array([[0, 0], [0, 2], [0, 4], [0, 5], [1, 1], [1, 3], [1, 4],
[1, 6], [2, 0], [2, 3], [2, 5], [3, 0], [3, 2], [3, 3],
[3, 5], [4, 1], [4, 4], [4, 6]]).astype(np.int64)
val = np.array(
[0, 2, 4, 5, 11, 13, 14, 16, 20, 23, 25, 30, 32, 33, 35, 41, 44,
46]).astype(np.int64)
shape = np.array([5, 7]).astype(np.int64)
return sparse_tensor.SparseTensor(ind, val, shape)
def _SparseTensorValue_3x4x2(self):
# slice(:,:, 0)
# ['a0'| |'b0'| ]
# [ |'c0'| |'d0']
# [ | |'e0'| ]
# slice(:,:, 1)
# ['a1'| |'b1'| ]
# [ |'c1'| |'d1']
# [ | |'e1'| ]
ind = np.array([[0, 0, 0], [0, 0, 1], [0, 2, 0], [0, 2, 1], [1, 1, 0],
[1, 1, 1], [1, 3, 0], [1, 3, 1], [2, 2, 0],
[2, 2, 1]]).astype(np.int64)
val = np.array(['a0', 'a1', 'b0', 'b1', 'c0', 'c1', 'd0', 'd1', 'e0', 'e1'])
shape = np.array([3, 4, 2]).astype(np.int64)
return sparse_tensor.SparseTensorValue(ind, val, shape)
def _SparseTensor_3x4x2(self):
return sparse_tensor.SparseTensor.from_value(self._SparseTensorValue_3x4x2(
))
def testSplitMatrixRows(self):
for axis in (0, -2):
sp_tensors = self.evaluate(
sparse_ops.sparse_split(
sp_input=self._SparseTensor_4x6(), num_split=2, axis=axis))
self.assertAllEqual(len(sp_tensors), 2)
self.assertAllEqual(
sp_tensors[0].indices,
[[0, 0], [0, 2], [0, 4], [0, 5], [1, 1], [1, 3], [1, 4]])
self.assertAllEqual(sp_tensors[0].values, [0, 2, 4, 5, 11, 13, 14])
self.assertAllEqual(sp_tensors[0].dense_shape, [2, 6])
self.assertAllEqual(
sp_tensors[1].indices,
[[0, 0], [0, 3], [0, 5], [1, 0], [1, 2], [1, 3], [1, 5]])
self.assertAllEqual(sp_tensors[1].values, [20, 23, 25, 30, 32, 33, 35])
self.assertAllEqual(sp_tensors[1].dense_shape, [2, 6])
def testSplitMatrixUnevenCols(self):
for axis in (1, -1):
sp_tensors_3 = self.evaluate(
sparse_ops.sparse_split(
sp_input=self._SparseTensor_5x7(), num_split=3, axis=axis))
self.assertAllEqual(len(sp_tensors_3), 3)
self.assertAllEqual(
sp_tensors_3[0].indices,
[[0, 0], [0, 2], [1, 1], [2, 0], [3, 0], [3, 2], [4, 1]])
self.assertAllEqual(sp_tensors_3[0].values, [0, 2, 11, 20, 30, 32, 41])
self.assertAllEqual(sp_tensors_3[0].dense_shape, [5, 3])
self.assertAllEqual(sp_tensors_3[1].indices,
[[0, 1], [1, 0], [1, 1], [2, 0], [3, 0], [4, 1]])
self.assertAllEqual(sp_tensors_3[1].values, [4, 13, 14, 23, 33, 44])
self.assertAllEqual(sp_tensors_3[1].dense_shape, [5, 2])
self.assertAllEqual(sp_tensors_3[2].indices,
[[0, 0], [1, 1], [2, 0], [3, 0], [4, 1]])
self.assertAllEqual(sp_tensors_3[2].values, [5, 16, 25, 35, 46])
self.assertAllEqual(sp_tensors_3[2].dense_shape, [5, 2])
sp_tensors_4 = sparse_ops.sparse_split(
sp_input=self._SparseTensor_5x7(), num_split=4, axis=axis)
self.assertAllEqual(len(sp_tensors_4), 4)
self.assertAllEqual(sp_tensors_4[0].indices,
[[0, 0], [1, 1], [2, 0], [3, 0], [4, 1]])
self.assertAllEqual(sp_tensors_4[0].values, [0, 11, 20, 30, 41])
self.assertAllEqual(sp_tensors_4[0].dense_shape, [5, 2])
self.assertAllEqual(sp_tensors_4[1].indices,
[[0, 0], [1, 1], [2, 1], [3, 0], [3, 1]])
self.assertAllEqual(sp_tensors_4[1].values, [2, 13, 23, 32, 33])
self.assertAllEqual(sp_tensors_4[1].dense_shape, [5, 2])
self.assertAllEqual(sp_tensors_4[2].indices,
[[0, 0], [0, 1], [1, 0], [2, 1], [3, 1], [4, 0]])
self.assertAllEqual(sp_tensors_4[2].values, [4, 5, 14, 25, 35, 44])
self.assertAllEqual(sp_tensors_4[2].dense_shape, [5, 2])
self.assertAllEqual(sp_tensors_4[3].indices, [[1, 0], [4, 0]])
self.assertAllEqual(sp_tensors_4[3].values, [16, 46])
self.assertAllEqual(sp_tensors_4[3].dense_shape, [5, 1])
def testSplitMatrixUnevenRows(self):
for axis in (0, -2):
sp_tensors_2 = self.evaluate(
sparse_ops.sparse_split(
sp_input=self._SparseTensor_5x7(), num_split=2, axis=axis))
self.assertAllEqual(sp_tensors_2[0].indices,
[[0, 0], [0, 2], [0, 4], [0, 5], [1, 1], [1, 3],
[1, 4], [1, 6], [2, 0], [2, 3], [2, 5]])
self.assertAllEqual(sp_tensors_2[0].values,
[0, 2, 4, 5, 11, 13, 14, 16, 20, 23, 25])
self.assertAllEqual(sp_tensors_2[0].dense_shape, [3, 7])
self.assertAllEqual(
sp_tensors_2[1].indices,
[[0, 0], [0, 2], [0, 3], [0, 5], [1, 1], [1, 4], [1, 6]])
self.assertAllEqual(sp_tensors_2[1].values, [30, 32, 33, 35, 41, 44, 46])
self.assertAllEqual(sp_tensors_2[1].dense_shape, [2, 7])
self.assertAllEqual(len(sp_tensors_2), 2)
sp_tensors_3 = sparse_ops.sparse_split(
sp_input=self._SparseTensor_5x7(), num_split=3, axis=axis)
self.assertAllEqual(len(sp_tensors_3), 3)
self.assertAllEqual(
sp_tensors_3[0].indices,
[[0, 0], [0, 2], [0, 4], [0, 5], [1, 1], [1, 3], [1, 4], [1, 6]])
self.assertAllEqual(sp_tensors_3[0].values, [0, 2, 4, 5, 11, 13, 14, 16])
self.assertAllEqual(sp_tensors_3[0].dense_shape, [2, 7])
self.assertAllEqual(sp_tensors_3[1].values, [20, 23, 25, 30, 32, 33, 35])
self.assertAllEqual(sp_tensors_3[1].dense_shape, [2, 7])
self.assertAllEqual(sp_tensors_3[2].indices, [[0, 1], [0, 4], [0, 6]])
self.assertAllEqual(sp_tensors_3[2].values, [41, 44, 46])
self.assertAllEqual(sp_tensors_3[2].dense_shape, [1, 7])
def testSplitAllRows(self):
for axis in (0, -2):
sp_tensors = self.evaluate(
sparse_ops.sparse_split(
sp_input=self._SparseTensor_4x6(), num_split=4, axis=axis))
self.assertAllEqual(len(sp_tensors), 4)
self.assertAllEqual(sp_tensors[0].indices,
[[0, 0], [0, 2], [0, 4], [0, 5]])
self.assertAllEqual(sp_tensors[0].values, [0, 2, 4, 5])
self.assertAllEqual(sp_tensors[0].dense_shape, [1, 6])
self.assertAllEqual(sp_tensors[1].indices, [[0, 1], [0, 3], [0, 4]])
self.assertAllEqual(sp_tensors[1].values, [11, 13, 14])
self.assertAllEqual(sp_tensors[1].dense_shape, [1, 6])
self.assertAllEqual(sp_tensors[2].indices, [[0, 0], [0, 3], [0, 5]])
self.assertAllEqual(sp_tensors[2].values, [20, 23, 25])
self.assertAllEqual(sp_tensors[2].dense_shape, [1, 6])
self.assertAllEqual(sp_tensors[3].indices,
[[0, 0], [0, 2], [0, 3], [0, 5]])
self.assertAllEqual(sp_tensors[3].values, [30, 32, 33, 35])
self.assertAllEqual(sp_tensors[3].dense_shape, [1, 6])
def testSplitColumns(self):
for axis in (1, -1):
sparse_tensors = self.evaluate(
sparse_ops.sparse_split(
sp_input=self._SparseTensor_4x6(), num_split=3, axis=axis))
self.assertAllEqual(len(sparse_tensors), 3)
self.assertAllEqual(sparse_tensors[0].indices,
[[0, 0], [1, 1], [2, 0], [3, 0]])
self.assertAllEqual(sparse_tensors[0].values, [0, 11, 20, 30])
self.assertAllEqual(sparse_tensors[0].dense_shape, [4, 2])
self.assertAllEqual(sparse_tensors[1].indices,
[[0, 0], [1, 1], [2, 1], [3, 0], [3, 1]])
self.assertAllEqual(sparse_tensors[1].values, [2, 13, 23, 32, 33])
self.assertAllEqual(sparse_tensors[1].dense_shape, [4, 2])
self.assertAllEqual(sparse_tensors[2].indices,
[[0, 0], [0, 1], [1, 0], [2, 1], [3, 1]])
self.assertAllEqual(sparse_tensors[2].values, [4, 5, 14, 25, 35])
self.assertAllEqual(sparse_tensors[2].dense_shape, [4, 2])
def testSplitAllColumns(self):
for axis in (1, -1):
sparse_tensors = self.evaluate(
sparse_ops.sparse_split(
sp_input=self._SparseTensor_4x6(), num_split=6, axis=axis))
self.assertAllEqual(len(sparse_tensors), 6)
self.assertAllEqual(sparse_tensors[0].indices, [[0, 0], [2, 0], [3, 0]])
self.assertAllEqual(sparse_tensors[0].values, [0, 20, 30])
self.assertAllEqual(sparse_tensors[0].dense_shape, [4, 1])
self.assertAllEqual(sparse_tensors[1].indices, [[1, 0]])
self.assertAllEqual(sparse_tensors[1].values, [11])
self.assertAllEqual(sparse_tensors[1].dense_shape, [4, 1])
self.assertAllEqual(sparse_tensors[2].indices, [[0, 0], [3, 0]])
self.assertAllEqual(sparse_tensors[2].values, [2, 32])
self.assertAllEqual(sparse_tensors[2].dense_shape, [4, 1])
self.assertAllEqual(sparse_tensors[3].indices, [[1, 0], [2, 0], [3, 0]])
self.assertAllEqual(sparse_tensors[3].dense_shape, [4, 1])
self.assertAllEqual(sparse_tensors[3].values, [13, 23, 33])
self.assertAllEqual(sparse_tensors[4].indices, [[0, 0], [1, 0]])
self.assertAllEqual(sparse_tensors[4].values, [4, 14])
self.assertAllEqual(sparse_tensors[4].dense_shape, [4, 1])
self.assertAllEqual(sparse_tensors[5].indices, [[0, 0], [2, 0], [3, 0]])
self.assertAllEqual(sparse_tensors[5].values, [5, 25, 35])
self.assertAllEqual(sparse_tensors[5].dense_shape, [4, 1])
def testSliceConcat(self):
for sp_input in (self._SparseTensorValue_3x4x2(),
self._SparseTensor_3x4x2()):
for axis in (1, -2):
sparse_tensors = sparse_ops.sparse_split(
sp_input=sp_input, num_split=2, axis=axis)
concat_tensor = self.evaluate(
sparse_ops.sparse_concat(1, sparse_tensors))
expected_output = self._SparseTensor_3x4x2()
self.assertAllEqual(concat_tensor.indices, expected_output.indices)
def testInvalidAxis(self):
for axis in (-3, 2):
with self.assertRaisesRegexp(errors.InvalidArgumentError,
r'axis should be in range \[-2, 2\)'):
self.evaluate(
sparse_ops.sparse_split(
sp_input=self._SparseTensor_4x6(), num_split=3, axis=axis))
def testArgumentErrors(self):
with self.assertRaisesRegex(ValueError, 'Keyword arguments are required'):
sparse_ops.sparse_split(3, 2, 1)
with self.assertRaisesRegex(ValueError, 'sp_input is required'):
sparse_ops.sparse_split()
with self.assertRaisesRegex(ValueError, 'num_split is required'):
sparse_ops.sparse_split(sp_input=1)
with self.assertRaisesRegex(ValueError, 'axis is required'):
sparse_ops.sparse_split(num_split=2, sp_input=1)
if __name__ == '__main__':
test.main()
| apache-2.0 |
hgschmie/presto | presto-matching/src/test/java/io/prestosql/matching/example/rel/Expression.java | 634 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.matching.example.rel;
public class Expression
{
}
| apache-2.0 |
GPUOpen-Drivers/llvm | unittests/Analysis/SparsePropagation.cpp | 21268 | //===- SparsePropagation.cpp - Unit tests for the generic solver ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/SparsePropagation.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/IRBuilder.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
/// To enable interprocedural analysis, we assign LLVM values to the following
/// groups. The register group represents SSA registers, the return group
/// represents the return values of functions, and the memory group represents
/// in-memory values. An LLVM Value can technically be in more than one group.
/// It's necessary to distinguish these groups so we can, for example, track a
/// global variable separately from the value stored at its location.
enum class IPOGrouping { Register, Return, Memory };
/// Our LatticeKeys are PointerIntPairs composed of LLVM values and groupings.
/// The PointerIntPair header provides a DenseMapInfo specialization, so using
/// these as LatticeKeys is fine.
using TestLatticeKey = PointerIntPair<Value *, 2, IPOGrouping>;
} // namespace
namespace llvm {
/// A specialization of LatticeKeyInfo for TestLatticeKeys. The generic solver
/// must translate between LatticeKeys and LLVM Values when adding Values to
/// its work list and inspecting the state of control-flow related values.
template <> struct LatticeKeyInfo<TestLatticeKey> {
static inline Value *getValueFromLatticeKey(TestLatticeKey Key) {
return Key.getPointer();
}
static inline TestLatticeKey getLatticeKeyFromValue(Value *V) {
return TestLatticeKey(V, IPOGrouping::Register);
}
};
} // namespace llvm
namespace {
/// This class defines a simple test lattice value that could be used for
/// solving problems similar to constant propagation. The value is maintained
/// as a PointerIntPair.
class TestLatticeVal {
public:
/// The states of the lattices value. Only the ConstantVal state is
/// interesting; the rest are special states used by the generic solver. The
/// UntrackedVal state differs from the other three in that the generic
/// solver uses it to avoid doing unnecessary work. In particular, when a
/// value moves to the UntrackedVal state, it's users are not notified.
enum TestLatticeStateTy {
UndefinedVal,
ConstantVal,
OverdefinedVal,
UntrackedVal
};
TestLatticeVal() : LatticeVal(nullptr, UndefinedVal) {}
TestLatticeVal(Constant *C, TestLatticeStateTy State)
: LatticeVal(C, State) {}
/// Return true if this lattice value is in the Constant state. This is used
/// for checking the solver results.
bool isConstant() const { return LatticeVal.getInt() == ConstantVal; }
/// Return true if this lattice value is in the Overdefined state. This is
/// used for checking the solver results.
bool isOverdefined() const { return LatticeVal.getInt() == OverdefinedVal; }
bool operator==(const TestLatticeVal &RHS) const {
return LatticeVal == RHS.LatticeVal;
}
bool operator!=(const TestLatticeVal &RHS) const {
return LatticeVal != RHS.LatticeVal;
}
private:
/// A simple lattice value type for problems similar to constant propagation.
/// It holds the constant value and the lattice state.
PointerIntPair<const Constant *, 2, TestLatticeStateTy> LatticeVal;
};
/// This class defines a simple test lattice function that could be used for
/// solving problems similar to constant propagation. The test lattice differs
/// from a "real" lattice in a few ways. First, it initializes all return
/// values, values stored in global variables, and arguments in the undefined
/// state. This means that there are no limitations on what we can track
/// interprocedurally. For simplicity, all global values in the tests will be
/// given internal linkage, since this is not something this lattice function
/// tracks. Second, it only handles the few instructions necessary for the
/// tests.
class TestLatticeFunc
: public AbstractLatticeFunction<TestLatticeKey, TestLatticeVal> {
public:
/// Construct a new test lattice function with special values for the
/// Undefined, Overdefined, and Untracked states.
TestLatticeFunc()
: AbstractLatticeFunction(
TestLatticeVal(nullptr, TestLatticeVal::UndefinedVal),
TestLatticeVal(nullptr, TestLatticeVal::OverdefinedVal),
TestLatticeVal(nullptr, TestLatticeVal::UntrackedVal)) {}
/// Compute and return a TestLatticeVal for the given TestLatticeKey. For the
/// test analysis, a LatticeKey will begin in the undefined state, unless it
/// represents an LLVM Constant in the register grouping.
TestLatticeVal ComputeLatticeVal(TestLatticeKey Key) override {
if (Key.getInt() == IPOGrouping::Register)
if (auto *C = dyn_cast<Constant>(Key.getPointer()))
return TestLatticeVal(C, TestLatticeVal::ConstantVal);
return getUndefVal();
}
/// Merge the two given lattice values. This merge should be equivalent to
/// what is done for constant propagation. That is, the resulting lattice
/// value is constant only if the two given lattice values are constant and
/// hold the same value.
TestLatticeVal MergeValues(TestLatticeVal X, TestLatticeVal Y) override {
if (X == getUntrackedVal() || Y == getUntrackedVal())
return getUntrackedVal();
if (X == getOverdefinedVal() || Y == getOverdefinedVal())
return getOverdefinedVal();
if (X == getUndefVal() && Y == getUndefVal())
return getUndefVal();
if (X == getUndefVal())
return Y;
if (Y == getUndefVal())
return X;
if (X == Y)
return X;
return getOverdefinedVal();
}
/// Compute the lattice values that change as a result of executing the given
/// instruction. We only handle the few instructions needed for the tests.
void ComputeInstructionState(
Instruction &I, DenseMap<TestLatticeKey, TestLatticeVal> &ChangedValues,
SparseSolver<TestLatticeKey, TestLatticeVal> &SS) override {
switch (I.getOpcode()) {
case Instruction::Call:
return visitCallSite(cast<CallInst>(&I), ChangedValues, SS);
case Instruction::Ret:
return visitReturn(*cast<ReturnInst>(&I), ChangedValues, SS);
case Instruction::Store:
return visitStore(*cast<StoreInst>(&I), ChangedValues, SS);
default:
return visitInst(I, ChangedValues, SS);
}
}
private:
/// Handle call sites. The state of a called function's argument is the merge
/// of the current formal argument state with the call site's corresponding
/// actual argument state. The call site state is the merge of the call site
/// state with the returned value state of the called function.
void visitCallSite(CallSite CS,
DenseMap<TestLatticeKey, TestLatticeVal> &ChangedValues,
SparseSolver<TestLatticeKey, TestLatticeVal> &SS) {
Function *F = CS.getCalledFunction();
Instruction *I = CS.getInstruction();
auto RegI = TestLatticeKey(I, IPOGrouping::Register);
if (!F) {
ChangedValues[RegI] = getOverdefinedVal();
return;
}
SS.MarkBlockExecutable(&F->front());
for (Argument &A : F->args()) {
auto RegFormal = TestLatticeKey(&A, IPOGrouping::Register);
auto RegActual =
TestLatticeKey(CS.getArgument(A.getArgNo()), IPOGrouping::Register);
ChangedValues[RegFormal] =
MergeValues(SS.getValueState(RegFormal), SS.getValueState(RegActual));
}
auto RetF = TestLatticeKey(F, IPOGrouping::Return);
ChangedValues[RegI] =
MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
}
/// Handle return instructions. The function's return state is the merge of
/// the returned value state and the function's current return state.
void visitReturn(ReturnInst &I,
DenseMap<TestLatticeKey, TestLatticeVal> &ChangedValues,
SparseSolver<TestLatticeKey, TestLatticeVal> &SS) {
Function *F = I.getParent()->getParent();
if (F->getReturnType()->isVoidTy())
return;
auto RegR = TestLatticeKey(I.getReturnValue(), IPOGrouping::Register);
auto RetF = TestLatticeKey(F, IPOGrouping::Return);
ChangedValues[RetF] =
MergeValues(SS.getValueState(RegR), SS.getValueState(RetF));
}
/// Handle store instructions. If the pointer operand of the store is a
/// global variable, we attempt to track the value. The global variable state
/// is the merge of the stored value state with the current global variable
/// state.
void visitStore(StoreInst &I,
DenseMap<TestLatticeKey, TestLatticeVal> &ChangedValues,
SparseSolver<TestLatticeKey, TestLatticeVal> &SS) {
auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand());
if (!GV)
return;
auto RegVal = TestLatticeKey(I.getValueOperand(), IPOGrouping::Register);
auto MemPtr = TestLatticeKey(GV, IPOGrouping::Memory);
ChangedValues[MemPtr] =
MergeValues(SS.getValueState(RegVal), SS.getValueState(MemPtr));
}
/// Handle all other instructions. All other instructions are marked
/// overdefined.
void visitInst(Instruction &I,
DenseMap<TestLatticeKey, TestLatticeVal> &ChangedValues,
SparseSolver<TestLatticeKey, TestLatticeVal> &SS) {
auto RegI = TestLatticeKey(&I, IPOGrouping::Register);
ChangedValues[RegI] = getOverdefinedVal();
}
};
/// This class defines the common data used for all of the tests. The tests
/// should add code to the module and then run the solver.
class SparsePropagationTest : public testing::Test {
protected:
LLVMContext Context;
Module M;
IRBuilder<> Builder;
TestLatticeFunc Lattice;
SparseSolver<TestLatticeKey, TestLatticeVal> Solver;
public:
SparsePropagationTest()
: M("", Context), Builder(Context), Solver(&Lattice) {}
};
} // namespace
/// Test that we mark discovered functions executable.
///
/// define internal void @f() {
/// call void @g()
/// ret void
/// }
///
/// define internal void @g() {
/// call void @f()
/// ret void
/// }
///
/// For this test, we initially mark "f" executable, and the solver discovers
/// "g" because of the call in "f". The mutually recursive call in "g" also
/// tests that we don't add a block to the basic block work list if it is
/// already executable. Doing so would put the solver into an infinite loop.
TEST_F(SparsePropagationTest, MarkBlockExecutable) {
Function *F = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "f", &M);
Function *G = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "g", &M);
BasicBlock *FEntry = BasicBlock::Create(Context, "", F);
BasicBlock *GEntry = BasicBlock::Create(Context, "", G);
Builder.SetInsertPoint(FEntry);
Builder.CreateCall(G);
Builder.CreateRetVoid();
Builder.SetInsertPoint(GEntry);
Builder.CreateCall(F);
Builder.CreateRetVoid();
Solver.MarkBlockExecutable(FEntry);
Solver.Solve();
EXPECT_TRUE(Solver.isBlockExecutable(GEntry));
}
/// Test that we propagate information through global variables.
///
/// @gv = internal global i64
///
/// define internal void @f() {
/// store i64 1, i64* @gv
/// ret void
/// }
///
/// define internal void @g() {
/// store i64 1, i64* @gv
/// ret void
/// }
///
/// For this test, we initially mark both "f" and "g" executable, and the
/// solver computes the lattice state of the global variable as constant.
TEST_F(SparsePropagationTest, GlobalVariableConstant) {
Function *F = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "f", &M);
Function *G = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "g", &M);
GlobalVariable *GV =
new GlobalVariable(M, Builder.getInt64Ty(), false,
GlobalValue::InternalLinkage, nullptr, "gv");
BasicBlock *FEntry = BasicBlock::Create(Context, "", F);
BasicBlock *GEntry = BasicBlock::Create(Context, "", G);
Builder.SetInsertPoint(FEntry);
Builder.CreateStore(Builder.getInt64(1), GV);
Builder.CreateRetVoid();
Builder.SetInsertPoint(GEntry);
Builder.CreateStore(Builder.getInt64(1), GV);
Builder.CreateRetVoid();
Solver.MarkBlockExecutable(FEntry);
Solver.MarkBlockExecutable(GEntry);
Solver.Solve();
auto MemGV = TestLatticeKey(GV, IPOGrouping::Memory);
EXPECT_TRUE(Solver.getExistingValueState(MemGV).isConstant());
}
/// Test that we propagate information through global variables.
///
/// @gv = internal global i64
///
/// define internal void @f() {
/// store i64 0, i64* @gv
/// ret void
/// }
///
/// define internal void @g() {
/// store i64 1, i64* @gv
/// ret void
/// }
///
/// For this test, we initially mark both "f" and "g" executable, and the
/// solver computes the lattice state of the global variable as overdefined.
TEST_F(SparsePropagationTest, GlobalVariableOverDefined) {
Function *F = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "f", &M);
Function *G = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "g", &M);
GlobalVariable *GV =
new GlobalVariable(M, Builder.getInt64Ty(), false,
GlobalValue::InternalLinkage, nullptr, "gv");
BasicBlock *FEntry = BasicBlock::Create(Context, "", F);
BasicBlock *GEntry = BasicBlock::Create(Context, "", G);
Builder.SetInsertPoint(FEntry);
Builder.CreateStore(Builder.getInt64(0), GV);
Builder.CreateRetVoid();
Builder.SetInsertPoint(GEntry);
Builder.CreateStore(Builder.getInt64(1), GV);
Builder.CreateRetVoid();
Solver.MarkBlockExecutable(FEntry);
Solver.MarkBlockExecutable(GEntry);
Solver.Solve();
auto MemGV = TestLatticeKey(GV, IPOGrouping::Memory);
EXPECT_TRUE(Solver.getExistingValueState(MemGV).isOverdefined());
}
/// Test that we propagate information through function returns.
///
/// define internal i64 @f(i1* %cond) {
/// if:
/// %0 = load i1, i1* %cond
/// br i1 %0, label %then, label %else
///
/// then:
/// ret i64 1
///
/// else:
/// ret i64 1
/// }
///
/// For this test, we initially mark "f" executable, and the solver computes
/// the return value of the function as constant.
TEST_F(SparsePropagationTest, FunctionDefined) {
Function *F =
Function::Create(FunctionType::get(Builder.getInt64Ty(),
{Type::getInt1PtrTy(Context)}, false),
GlobalValue::InternalLinkage, "f", &M);
BasicBlock *If = BasicBlock::Create(Context, "if", F);
BasicBlock *Then = BasicBlock::Create(Context, "then", F);
BasicBlock *Else = BasicBlock::Create(Context, "else", F);
F->arg_begin()->setName("cond");
Builder.SetInsertPoint(If);
LoadInst *Cond = Builder.CreateLoad(Type::getInt1Ty(Context), F->arg_begin());
Builder.CreateCondBr(Cond, Then, Else);
Builder.SetInsertPoint(Then);
Builder.CreateRet(Builder.getInt64(1));
Builder.SetInsertPoint(Else);
Builder.CreateRet(Builder.getInt64(1));
Solver.MarkBlockExecutable(If);
Solver.Solve();
auto RetF = TestLatticeKey(F, IPOGrouping::Return);
EXPECT_TRUE(Solver.getExistingValueState(RetF).isConstant());
}
/// Test that we propagate information through function returns.
///
/// define internal i64 @f(i1* %cond) {
/// if:
/// %0 = load i1, i1* %cond
/// br i1 %0, label %then, label %else
///
/// then:
/// ret i64 0
///
/// else:
/// ret i64 1
/// }
///
/// For this test, we initially mark "f" executable, and the solver computes
/// the return value of the function as overdefined.
TEST_F(SparsePropagationTest, FunctionOverDefined) {
Function *F =
Function::Create(FunctionType::get(Builder.getInt64Ty(),
{Type::getInt1PtrTy(Context)}, false),
GlobalValue::InternalLinkage, "f", &M);
BasicBlock *If = BasicBlock::Create(Context, "if", F);
BasicBlock *Then = BasicBlock::Create(Context, "then", F);
BasicBlock *Else = BasicBlock::Create(Context, "else", F);
F->arg_begin()->setName("cond");
Builder.SetInsertPoint(If);
LoadInst *Cond = Builder.CreateLoad(Type::getInt1Ty(Context), F->arg_begin());
Builder.CreateCondBr(Cond, Then, Else);
Builder.SetInsertPoint(Then);
Builder.CreateRet(Builder.getInt64(0));
Builder.SetInsertPoint(Else);
Builder.CreateRet(Builder.getInt64(1));
Solver.MarkBlockExecutable(If);
Solver.Solve();
auto RetF = TestLatticeKey(F, IPOGrouping::Return);
EXPECT_TRUE(Solver.getExistingValueState(RetF).isOverdefined());
}
/// Test that we propagate information through arguments.
///
/// define internal void @f() {
/// call void @g(i64 0, i64 1)
/// call void @g(i64 1, i64 1)
/// ret void
/// }
///
/// define internal void @g(i64 %a, i64 %b) {
/// ret void
/// }
///
/// For this test, we initially mark "f" executable, and the solver discovers
/// "g" because of the calls in "f". The solver computes the state of argument
/// "a" as overdefined and the state of "b" as constant.
///
/// In addition, this test demonstrates that ComputeInstructionState can alter
/// the state of multiple lattice values, in addition to the one associated
/// with the instruction definition. Each call instruction in this test updates
/// the state of arguments "a" and "b".
TEST_F(SparsePropagationTest, ComputeInstructionState) {
Function *F = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "f", &M);
Function *G = Function::Create(
FunctionType::get(Builder.getVoidTy(),
{Builder.getInt64Ty(), Builder.getInt64Ty()}, false),
GlobalValue::InternalLinkage, "g", &M);
Argument *A = G->arg_begin();
Argument *B = std::next(G->arg_begin());
A->setName("a");
B->setName("b");
BasicBlock *FEntry = BasicBlock::Create(Context, "", F);
BasicBlock *GEntry = BasicBlock::Create(Context, "", G);
Builder.SetInsertPoint(FEntry);
Builder.CreateCall(G, {Builder.getInt64(0), Builder.getInt64(1)});
Builder.CreateCall(G, {Builder.getInt64(1), Builder.getInt64(1)});
Builder.CreateRetVoid();
Builder.SetInsertPoint(GEntry);
Builder.CreateRetVoid();
Solver.MarkBlockExecutable(FEntry);
Solver.Solve();
auto RegA = TestLatticeKey(A, IPOGrouping::Register);
auto RegB = TestLatticeKey(B, IPOGrouping::Register);
EXPECT_TRUE(Solver.getExistingValueState(RegA).isOverdefined());
EXPECT_TRUE(Solver.getExistingValueState(RegB).isConstant());
}
/// Test that we can handle exceptional terminator instructions.
///
/// declare internal void @p()
///
/// declare internal void @g()
///
/// define internal void @f() personality i8* bitcast (void ()* @p to i8*) {
/// entry:
/// invoke void @g()
/// to label %exit unwind label %catch.pad
///
/// catch.pad:
/// %0 = catchswitch within none [label %catch.body] unwind to caller
///
/// catch.body:
/// %1 = catchpad within %0 []
/// catchret from %1 to label %exit
///
/// exit:
/// ret void
/// }
///
/// For this test, we initially mark the entry block executable. The solver
/// then discovers the rest of the blocks in the function are executable.
TEST_F(SparsePropagationTest, ExceptionalTerminatorInsts) {
Function *P = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "p", &M);
Function *G = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "g", &M);
Function *F = Function::Create(FunctionType::get(Builder.getVoidTy(), false),
GlobalValue::InternalLinkage, "f", &M);
Constant *C =
ConstantExpr::getCast(Instruction::BitCast, P, Builder.getInt8PtrTy());
F->setPersonalityFn(C);
BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
BasicBlock *Pad = BasicBlock::Create(Context, "catch.pad", F);
BasicBlock *Body = BasicBlock::Create(Context, "catch.body", F);
BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
Builder.SetInsertPoint(Entry);
Builder.CreateInvoke(G, Exit, Pad);
Builder.SetInsertPoint(Pad);
CatchSwitchInst *CatchSwitch =
Builder.CreateCatchSwitch(ConstantTokenNone::get(Context), nullptr, 1);
CatchSwitch->addHandler(Body);
Builder.SetInsertPoint(Body);
CatchPadInst *CatchPad = Builder.CreateCatchPad(CatchSwitch, {});
Builder.CreateCatchRet(CatchPad, Exit);
Builder.SetInsertPoint(Exit);
Builder.CreateRetVoid();
Solver.MarkBlockExecutable(Entry);
Solver.Solve();
EXPECT_TRUE(Solver.isBlockExecutable(Pad));
EXPECT_TRUE(Solver.isBlockExecutable(Body));
EXPECT_TRUE(Solver.isBlockExecutable(Exit));
}
| apache-2.0 |
cripure/openpne3 | plugins/opOpenSocialPlugin/lib/vendor/Shindig/features/i18n/data/DateTimeConstants__ms_MY.js | 2343 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
var gadgets = gadgets || {};
gadgets.i18n = gadgets.i18n || {};
gadgets.i18n.DateTimeConstants = {
ERAS:["S.M.","T.M."],
ERANAMES:["S.M.","T.M."],
NARROWMONTHS:["1","2","3","4","5","6","7","8","9","10","11","12"],
MONTHS:["Januari","Februari","Mac","April","Mei","Jun","Julai","Ogos","September","Oktober","November","Disember"],
SHORTMONTHS:["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ogos","Sep","Okt","Nov","Dis"],
WEEKDAYS:["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"],
SHORTWEEKDAYS:["Ahd","Isn","Sel","Rab","Kha","Jum","Sab"],
NARROWWEEKDAYS:["1","2","3","4","5","6","7"],
SHORTQUARTERS:["S1","S2","S3","S4"],
QUARTERS:["suku pertama","suku kedua","suku ketiga","suku keempat"],
AMPMS:["AM","PM"],
DATEFORMATS:["EEEE dd MMM y","dd MMMM y","dd MMM y","dd/MM/yyyy"],
TIMEFORMATS:["h:mm:ss a zzzz","h:mm:ss a z","h:mm:ss a","h:mm"],
FIRSTDAYOFWEEK: 0,
WEEKENDRANGE: [5, 6],
FIRSTWEEKCUTOFFDAY: 3
};
gadgets.i18n.DateTimeConstants.STANDALONENARROWMONTHS = gadgets.i18n.DateTimeConstants.NARROWMONTHS;
gadgets.i18n.DateTimeConstants.STANDALONEMONTHS = gadgets.i18n.DateTimeConstants.MONTHS;
gadgets.i18n.DateTimeConstants.STANDALONESHORTMONTHS = gadgets.i18n.DateTimeConstants.SHORTMONTHS;
gadgets.i18n.DateTimeConstants.STANDALONEWEEKDAYS = gadgets.i18n.DateTimeConstants.WEEKDAYS;
gadgets.i18n.DateTimeConstants.STANDALONESHORTWEEKDAYS = gadgets.i18n.DateTimeConstants.SHORTWEEKDAYS;
gadgets.i18n.DateTimeConstants.STANDALONENARROWWEEKDAYS = gadgets.i18n.DateTimeConstants.NARROWWEEKDAYS;
| apache-2.0 |
BetterTi/ti.debugger | testprojects/KitchenSink2/Resources/ui/handheld/ios/platform/custom_properties.js | 1019 | function custom_props(_args) {
var win = Titanium.UI.createWindow({
title:_args.title
});
var tab = _args.containingTab;
var l = Titanium.UI.createLabel({
top:10,
width:300,
height:'auto',
color:'#777',
font:{fontSize:16},
text:'We are going to place custom properties on a new window then retrieve them in the new window.'
});
win.add(l);
var b = Titanium.UI.createButton({
title:'Launch Window',
height:40,
width:200,
top:100
});
b.addEventListener('click', function()
{
// set properties on the window object, then open. we will print them out in the new window
var W2 = require('ui/handheld/ios/platform/custom_properties_2'),
w2 = new W2();
w2.title = 'Custom Prop Test';
w2.stringProp1 = 'Foo';
w2.stringProp2 = 'Bar';
w2.numProp1 = 1;
w2.numProp2 = 2;
w2.objProp1 = {name:'Jane', age:30};
w2.myFunc = function()
{
return 'myFunc was called';
};
tab.open(w2,{animated:true});
});
win.add(b);
return win;
};
module.exports = custom_props;
| apache-2.0 |
Asimov4/elasticsearch | src/test/java/org/elasticsearch/search/MultiValueModeTests.java | 22690 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search;
import com.carrotsearch.randomizedtesting.generators.RandomStrings;
import org.apache.lucene.index.*;
import org.apache.lucene.util.BitDocIdSet;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.FixedBitSet;
import org.elasticsearch.index.fielddata.FieldData;
import org.elasticsearch.index.fielddata.NumericDoubleValues;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.test.ElasticsearchTestCase;
import java.io.IOException;
import java.util.Arrays;
public class MultiValueModeTests extends ElasticsearchTestCase {
private static FixedBitSet randomRootDocs(int maxDoc) {
FixedBitSet set = new FixedBitSet(maxDoc);
for (int i = 0; i < maxDoc; ++i) {
if (randomBoolean()) {
set.set(i);
}
}
// the last doc must be a root doc
set.set(maxDoc - 1);
return set;
}
private static FixedBitSet randomInnerDocs(FixedBitSet rootDocs) {
FixedBitSet innerDocs = new FixedBitSet(rootDocs.length());
for (int i = 0; i < innerDocs.length(); ++i) {
if (!rootDocs.get(i) && randomBoolean()) {
innerDocs.set(i);
}
}
return innerDocs;
}
public void testSingleValuedLongs() throws Exception {
final int numDocs = scaledRandomIntBetween(1, 100);
final long[] array = new long[numDocs];
final FixedBitSet docsWithValue = randomBoolean() ? null : new FixedBitSet(numDocs);
for (int i = 0; i < array.length; ++i) {
if (randomBoolean()) {
array[i] = randomLong();
if (docsWithValue != null) {
docsWithValue.set(i);
}
} else if (docsWithValue != null && randomBoolean()) {
docsWithValue.set(i);
}
}
final NumericDocValues singleValues = new NumericDocValues() {
@Override
public long get(int docID) {
return array[docID];
}
};
final SortedNumericDocValues multiValues = DocValues.singleton(singleValues, docsWithValue);
verify(multiValues, numDocs);
final FixedBitSet rootDocs = randomRootDocs(numDocs);
final FixedBitSet innerDocs = randomInnerDocs(rootDocs);
verify(multiValues, numDocs, rootDocs, innerDocs);
}
public void testMultiValuedLongs() throws Exception {
final int numDocs = scaledRandomIntBetween(1, 100);
final long[][] array = new long[numDocs][];
for (int i = 0; i < numDocs; ++i) {
final long[] values = new long[randomInt(4)];
for (int j = 0; j < values.length; ++j) {
values[j] = randomLong();
}
Arrays.sort(values);
array[i] = values;
}
final SortedNumericDocValues multiValues = new SortedNumericDocValues() {
int doc;
@Override
public long valueAt(int index) {
return array[doc][index];
}
@Override
public void setDocument(int doc) {
this.doc = doc;
}
@Override
public int count() {
return array[doc].length;
}
};
verify(multiValues, numDocs);
final FixedBitSet rootDocs = randomRootDocs(numDocs);
final FixedBitSet innerDocs = randomInnerDocs(rootDocs);
verify(multiValues, numDocs, rootDocs, innerDocs);
}
private void verify(SortedNumericDocValues values, int maxDoc) {
for (long missingValue : new long[] { 0, randomLong() }) {
for (MultiValueMode mode : MultiValueMode.values()) {
final NumericDocValues selected = mode.select(values, missingValue);
for (int i = 0; i < maxDoc; ++i) {
final long actual = selected.get(i);
long expected;
values.setDocument(i);
int numValues = values.count();
if (numValues == 0) {
expected = missingValue;
} else {
expected = mode.startLong();
for (int j = 0; j < numValues; ++j) {
expected = mode.apply(expected, values.valueAt(j));
}
expected = mode.reduce(expected, numValues);
}
assertEquals(mode.toString() + " docId=" + i, expected, actual);
}
}
}
}
private void verify(SortedNumericDocValues values, int maxDoc, FixedBitSet rootDocs, FixedBitSet innerDocs) throws IOException {
for (long missingValue : new long[] { 0, randomLong() }) {
for (MultiValueMode mode : MultiValueMode.values()) {
final NumericDocValues selected = mode.select(values, missingValue, rootDocs, new BitDocIdSet(innerDocs), maxDoc);
int prevRoot = -1;
for (int root = rootDocs.nextSetBit(0); root != -1; root = root + 1 < maxDoc ? rootDocs.nextSetBit(root + 1) : -1) {
final long actual = selected.get(root);
long expected = mode.startLong();
int numValues = 0;
for (int child = innerDocs.nextSetBit(prevRoot + 1); child != -1 && child < root; child = innerDocs.nextSetBit(child + 1)) {
values.setDocument(child);
for (int j = 0; j < values.count(); ++j) {
expected = mode.apply(expected, values.valueAt(j));
++numValues;
}
}
if (numValues == 0) {
expected = missingValue;
} else {
expected = mode.reduce(expected, numValues);
}
assertEquals(mode.toString() + " docId=" + root, expected, actual);
prevRoot = root;
}
}
}
}
public void testSingleValuedDoubles() throws Exception {
final int numDocs = scaledRandomIntBetween(1, 100);
final double[] array = new double[numDocs];
final FixedBitSet docsWithValue = randomBoolean() ? null : new FixedBitSet(numDocs);
for (int i = 0; i < array.length; ++i) {
if (randomBoolean()) {
array[i] = randomDouble();
if (docsWithValue != null) {
docsWithValue.set(i);
}
} else if (docsWithValue != null && randomBoolean()) {
docsWithValue.set(i);
}
}
final NumericDoubleValues singleValues = new NumericDoubleValues() {
@Override
public double get(int docID) {
return array[docID];
}
};
final SortedNumericDoubleValues multiValues = FieldData.singleton(singleValues, docsWithValue);
verify(multiValues, numDocs);
final FixedBitSet rootDocs = randomRootDocs(numDocs);
final FixedBitSet innerDocs = randomInnerDocs(rootDocs);
verify(multiValues, numDocs, rootDocs, innerDocs);
}
public void testMultiValuedDoubles() throws Exception {
final int numDocs = scaledRandomIntBetween(1, 100);
final double[][] array = new double[numDocs][];
for (int i = 0; i < numDocs; ++i) {
final double[] values = new double[randomInt(4)];
for (int j = 0; j < values.length; ++j) {
values[j] = randomDouble();
}
Arrays.sort(values);
array[i] = values;
}
final SortedNumericDoubleValues multiValues = new SortedNumericDoubleValues() {
int doc;
@Override
public double valueAt(int index) {
return array[doc][index];
}
@Override
public void setDocument(int doc) {
this.doc = doc;
}
@Override
public int count() {
return array[doc].length;
}
};
verify(multiValues, numDocs);
final FixedBitSet rootDocs = randomRootDocs(numDocs);
final FixedBitSet innerDocs = randomInnerDocs(rootDocs);
verify(multiValues, numDocs, rootDocs, innerDocs);
}
private void verify(SortedNumericDoubleValues values, int maxDoc) {
for (long missingValue : new long[] { 0, randomLong() }) {
for (MultiValueMode mode : MultiValueMode.values()) {
final NumericDoubleValues selected = mode.select(values, missingValue);
for (int i = 0; i < maxDoc; ++i) {
final double actual = selected.get(i);
double expected;
values.setDocument(i);
int numValues = values.count();
if (numValues == 0) {
expected = missingValue;
} else {
expected = mode.startLong();
for (int j = 0; j < numValues; ++j) {
expected = mode.apply(expected, values.valueAt(j));
}
expected = mode.reduce(expected, numValues);
}
assertEquals(mode.toString() + " docId=" + i, expected, actual, 0.1);
}
}
}
}
private void verify(SortedNumericDoubleValues values, int maxDoc, FixedBitSet rootDocs, FixedBitSet innerDocs) throws IOException {
for (long missingValue : new long[] { 0, randomLong() }) {
for (MultiValueMode mode : MultiValueMode.values()) {
final NumericDoubleValues selected = mode.select(values, missingValue, rootDocs, new BitDocIdSet(innerDocs), maxDoc);
int prevRoot = -1;
for (int root = rootDocs.nextSetBit(0); root != -1; root = root + 1 < maxDoc ? rootDocs.nextSetBit(root + 1) : -1) {
final double actual = selected.get(root);
double expected = mode.startLong();
int numValues = 0;
for (int child = innerDocs.nextSetBit(prevRoot + 1); child != -1 && child < root; child = innerDocs.nextSetBit(child + 1)) {
values.setDocument(child);
for (int j = 0; j < values.count(); ++j) {
expected = mode.apply(expected, values.valueAt(j));
++numValues;
}
}
if (numValues == 0) {
expected = missingValue;
} else {
expected = mode.reduce(expected, numValues);
}
assertEquals(mode.toString() + " docId=" + root, expected, actual, 0.1);
prevRoot = root;
}
}
}
}
public void testSingleValuedStrings() throws Exception {
final int numDocs = scaledRandomIntBetween(1, 100);
final BytesRef[] array = new BytesRef[numDocs];
final FixedBitSet docsWithValue = randomBoolean() ? null : new FixedBitSet(numDocs);
for (int i = 0; i < array.length; ++i) {
if (randomBoolean()) {
array[i] = new BytesRef(RandomStrings.randomAsciiOfLength(getRandom(), 8));
if (docsWithValue != null) {
docsWithValue.set(i);
}
} else {
array[i] = new BytesRef();
if (docsWithValue != null && randomBoolean()) {
docsWithValue.set(i);
}
}
}
final BinaryDocValues singleValues = new BinaryDocValues() {
@Override
public BytesRef get(int docID) {
return BytesRef.deepCopyOf(array[docID]);
}
};
final SortedBinaryDocValues multiValues = FieldData.singleton(singleValues, docsWithValue);
verify(multiValues, numDocs);
final FixedBitSet rootDocs = randomRootDocs(numDocs);
final FixedBitSet innerDocs = randomInnerDocs(rootDocs);
verify(multiValues, numDocs, rootDocs, innerDocs);
}
public void testMultiValuedStrings() throws Exception {
final int numDocs = scaledRandomIntBetween(1, 100);
final BytesRef[][] array = new BytesRef[numDocs][];
for (int i = 0; i < numDocs; ++i) {
final BytesRef[] values = new BytesRef[randomInt(4)];
for (int j = 0; j < values.length; ++j) {
values[j] = new BytesRef(RandomStrings.randomAsciiOfLength(getRandom(), 8));
}
Arrays.sort(values);
array[i] = values;
}
final SortedBinaryDocValues multiValues = new SortedBinaryDocValues() {
int doc;
@Override
public BytesRef valueAt(int index) {
return BytesRef.deepCopyOf(array[doc][index]);
}
@Override
public void setDocument(int doc) {
this.doc = doc;
}
@Override
public int count() {
return array[doc].length;
}
};
verify(multiValues, numDocs);
final FixedBitSet rootDocs = randomRootDocs(numDocs);
final FixedBitSet innerDocs = randomInnerDocs(rootDocs);
verify(multiValues, numDocs, rootDocs, innerDocs);
}
private void verify(SortedBinaryDocValues values, int maxDoc) {
for (BytesRef missingValue : new BytesRef[] { new BytesRef(), new BytesRef(RandomStrings.randomAsciiOfLength(getRandom(), 8)) }) {
for (MultiValueMode mode : new MultiValueMode[] {MultiValueMode.MIN, MultiValueMode.MAX}) {
final BinaryDocValues selected = mode.select(values, missingValue);
for (int i = 0; i < maxDoc; ++i) {
final BytesRef actual = selected.get(i);
BytesRef expected = null;
values.setDocument(i);
int numValues = values.count();
if (numValues == 0) {
expected = missingValue;
} else {
for (int j = 0; j < numValues; ++j) {
if (expected == null) {
expected = BytesRef.deepCopyOf(values.valueAt(j));
} else {
expected = mode.apply(expected, BytesRef.deepCopyOf(values.valueAt(j)));
}
}
if (expected == null) {
expected = missingValue;
}
}
assertEquals(mode.toString() + " docId=" + i, expected, actual);
}
}
}
}
private void verify(SortedBinaryDocValues values, int maxDoc, FixedBitSet rootDocs, FixedBitSet innerDocs) throws IOException {
for (BytesRef missingValue : new BytesRef[] { new BytesRef(), new BytesRef(RandomStrings.randomAsciiOfLength(getRandom(), 8)) }) {
for (MultiValueMode mode : new MultiValueMode[] {MultiValueMode.MIN, MultiValueMode.MAX}) {
final BinaryDocValues selected = mode.select(values, missingValue, rootDocs, new BitDocIdSet(innerDocs), maxDoc);
int prevRoot = -1;
for (int root = rootDocs.nextSetBit(0); root != -1; root = root + 1 < maxDoc ? rootDocs.nextSetBit(root + 1) : -1) {
final BytesRef actual = selected.get(root);
BytesRef expected = null;
for (int child = innerDocs.nextSetBit(prevRoot + 1); child != -1 && child < root; child = innerDocs.nextSetBit(child + 1)) {
values.setDocument(child);
for (int j = 0; j < values.count(); ++j) {
if (expected == null) {
expected = BytesRef.deepCopyOf(values.valueAt(j));
} else {
expected = mode.apply(expected, values.valueAt(j));
}
expected = mode.apply(expected, BytesRef.deepCopyOf(values.valueAt(j)));
}
}
if (expected == null) {
expected = missingValue;
}
assertEquals(mode.toString() + " docId=" + root, expected, actual);
prevRoot = root;
}
}
}
}
public void testSingleValuedOrds() throws Exception {
final int numDocs = scaledRandomIntBetween(1, 100);
final int[] array = new int[numDocs];
for (int i = 0; i < array.length; ++i) {
if (randomBoolean()) {
array[i] = randomInt(1000);
} else {
array[i] = -1;
}
}
final SortedDocValues singleValues = new SortedDocValues() {
@Override
public int getOrd(int docID) {
return array[docID];
}
@Override
public BytesRef lookupOrd(int ord) {
throw new UnsupportedOperationException();
}
@Override
public int getValueCount() {
return 1 << 20;
}
};
final RandomAccessOrds multiValues = (RandomAccessOrds) DocValues.singleton(singleValues);
verify(multiValues, numDocs);
final FixedBitSet rootDocs = randomRootDocs(numDocs);
final FixedBitSet innerDocs = randomInnerDocs(rootDocs);
verify(multiValues, numDocs, rootDocs, innerDocs);
}
public void testMultiValuedOrds() throws Exception {
final int numDocs = scaledRandomIntBetween(1, 100);
final long[][] array = new long[numDocs][];
for (int i = 0; i < numDocs; ++i) {
final long[] values = new long[randomInt(4)];
for (int j = 0; j < values.length; ++j) {
values[j] = j == 0 ? randomInt(1000) : values[j - 1] + 1 + randomInt(1000);
}
array[i] = values;
}
final RandomAccessOrds multiValues = new RandomAccessOrds() {
int doc;
@Override
public long ordAt(int index) {
return array[doc][index];
}
@Override
public int cardinality() {
return array[doc].length;
}
@Override
public long nextOrd() {
throw new UnsupportedOperationException();
}
@Override
public void setDocument(int docID) {
this.doc = docID;
}
@Override
public BytesRef lookupOrd(long ord) {
throw new UnsupportedOperationException();
}
@Override
public long getValueCount() {
return 1 << 20;
}
};
verify(multiValues, numDocs);
final FixedBitSet rootDocs = randomRootDocs(numDocs);
final FixedBitSet innerDocs = randomInnerDocs(rootDocs);
verify(multiValues, numDocs, rootDocs, innerDocs);
}
private void verify(RandomAccessOrds values, int maxDoc) {
for (MultiValueMode mode : new MultiValueMode[] {MultiValueMode.MIN, MultiValueMode.MAX}) {
final SortedDocValues selected = mode.select(values);
for (int i = 0; i < maxDoc; ++i) {
final long actual = selected.getOrd(i);
int expected = -1;
values.setDocument(i);
for (int j = 0; j < values.cardinality(); ++j) {
if (expected == -1) {
expected = (int) values.ordAt(j);
} else {
expected = mode.applyOrd(expected, (int) values.ordAt(j));
}
}
assertEquals(mode.toString() + " docId=" + i, expected, actual);
}
}
}
private void verify(RandomAccessOrds values, int maxDoc, FixedBitSet rootDocs, FixedBitSet innerDocs) throws IOException {
for (MultiValueMode mode : new MultiValueMode[] {MultiValueMode.MIN, MultiValueMode.MAX}) {
final SortedDocValues selected = mode.select(values, rootDocs, new BitDocIdSet(innerDocs));
int prevRoot = -1;
for (int root = rootDocs.nextSetBit(0); root != -1; root = root + 1 < maxDoc ? rootDocs.nextSetBit(root + 1) : -1) {
final int actual = selected.getOrd(root);
int expected = -1;
for (int child = innerDocs.nextSetBit(prevRoot + 1); child != -1 && child < root; child = innerDocs.nextSetBit(child + 1)) {
values.setDocument(child);
for (int j = 0; j < values.cardinality(); ++j) {
if (expected == -1) {
expected = (int) values.ordAt(j);
} else {
expected = mode.applyOrd(expected, (int) values.ordAt(j));
}
}
}
assertEquals(mode.toString() + " docId=" + root, expected, actual);
prevRoot = root;
}
}
}
}
| apache-2.0 |
crowell/modpagespeed_tmp | net/instaweb/rewriter/resource_namer_test.cc | 10693 | /*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: jmarantz@google.com (Joshua Marantz)
#include "net/instaweb/rewriter/public/resource_namer.h"
#include "pagespeed/kernel/base/gtest.h"
#include "pagespeed/kernel/base/md5_hasher.h"
#include "pagespeed/kernel/base/mock_hasher.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
namespace net_instaweb {
namespace {
class ResourceNamerTest : public testing::Test {
protected:
ResourceNamerTest() { }
void TestCopyAndSize(int signature_length) {
MockHasher mock_hasher(full_name_.hash());
ResourceNamer copy;
copy.CopyFrom(full_name_);
EXPECT_STREQ(copy.Encode(), full_name_.Encode());
EXPECT_EQ(
full_name_.EventualSize(mock_hasher, signature_length),
full_name_.Encode().size());
}
ResourceNamer full_name_;
};
TEST_F(ResourceNamerTest, TestEncode) {
// Stand up a minimal resource manager that only has the
// resources we should need to encode.
full_name_.set_id("id");
full_name_.set_name("name.ext.as.many.as.I.like");
full_name_.set_hash("hash");
full_name_.set_ext("ext");
TestCopyAndSize(0);
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.id.hash.ext",
full_name_.Encode());
EXPECT_STREQ("id.name.ext.as.many.as.I.like",
full_name_.EncodeIdName());
full_name_.set_experiment("q");
TestCopyAndSize(0);
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.q.id.hash.ext",
full_name_.Encode());
full_name_.set_options("a=b");
full_name_.set_experiment("");
TestCopyAndSize(0);
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.a=b.id.hash.ext",
full_name_.Encode());
full_name_.set_name("name.ext");
full_name_.set_options("options.with.dots");
TestCopyAndSize(0);
EXPECT_STREQ("name.ext.pagespeed.options.with.dots.id.hash.ext",
full_name_.Encode());
full_name_.set_options("options/with/slashes");
EXPECT_STREQ("name.ext.pagespeed.options,_with,_slashes.id.hash.ext",
full_name_.Encode());
TestCopyAndSize(0);
}
TEST_F(ResourceNamerTest, TestDecode) {
EXPECT_TRUE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
EXPECT_FALSE(full_name_.has_experiment());
EXPECT_STREQ("id", full_name_.id());
EXPECT_STREQ("name.ext.as.many.as.I.like", full_name_.name());
EXPECT_STREQ("hash", full_name_.hash());
EXPECT_STREQ("ext", full_name_.ext());
TestCopyAndSize(0);
}
TEST_F(ResourceNamerTest, TestDecodeExperiment) {
EXPECT_TRUE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.d.id.hash.ext",
4 /*hash size*/, 0 /*signature_size*/));
TestCopyAndSize(0);
EXPECT_STREQ("d", full_name_.experiment());
EXPECT_TRUE(full_name_.has_experiment());
EXPECT_STREQ("id", full_name_.id());
EXPECT_STREQ("name.ext.as.many.as.I.like", full_name_.name());
EXPECT_STREQ("hash", full_name_.hash());
EXPECT_STREQ("ext", full_name_.ext());
EXPECT_TRUE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.de.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
TestCopyAndSize(0);
EXPECT_STREQ("", full_name_.experiment());
EXPECT_STREQ("de", full_name_.options());
EXPECT_FALSE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed..id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
EXPECT_FALSE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.D.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
EXPECT_FALSE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.`.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
EXPECT_FALSE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.{.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
EXPECT_TRUE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.a.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
TestCopyAndSize(0);
EXPECT_TRUE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.z.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
TestCopyAndSize(0);
EXPECT_TRUE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.z.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
TestCopyAndSize(0);
EXPECT_STREQ("", full_name_.options());
EXPECT_TRUE(full_name_.Decode("name.ext.pagespeed.opts.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
TestCopyAndSize(0);
EXPECT_STREQ("opts", full_name_.options());
// Make sure a decode without options clears them.
EXPECT_TRUE(
full_name_.Decode("name.ext.as.many.as.I.like.pagespeed.z.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
TestCopyAndSize(0);
EXPECT_STREQ("", full_name_.options());
}
TEST_F(ResourceNamerTest, TestDecodeOptions) {
EXPECT_TRUE(full_name_.Decode("name.ext.pagespeed.options.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
TestCopyAndSize(0);
EXPECT_STREQ("id", full_name_.id());
EXPECT_STREQ("options", full_name_.options());
EXPECT_TRUE(
full_name_.Decode("name.ext.pagespeed.options,_with,_slashes.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
TestCopyAndSize(0);
EXPECT_STREQ("options/with/slashes", full_name_.options());
EXPECT_TRUE(
full_name_.Decode("name.ext.pagespeed.options,_with,_slashes.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
EXPECT_STREQ("options/with/slashes", full_name_.options());
TestCopyAndSize(0);
EXPECT_TRUE(full_name_.Decode(
"name.ext.pagespeed.options,qwith,aquery=params.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
EXPECT_STREQ("options?with&query=params", full_name_.options());
TestCopyAndSize(0);
}
TEST_F(ResourceNamerTest, TestDecodeTooMany) {
EXPECT_TRUE(full_name_.Decode("name.extra_dot.pagespeed.id.hash.ext",
4 /*hash size*/, 0 /*signature size*/));
}
TEST_F(ResourceNamerTest, TestDecodeNotEnough) {
EXPECT_FALSE(
full_name_.Decode("id.name.hash", 4 /*hash size*/, 0 /*signature size*/));
}
TEST_F(ResourceNamerTest, TestLegacyDecode) {
// Legacydecode doesn't include signature at all, and will not use the same
// decode function. Putting -1, -1 because that piece of the code should not
// be hit.
EXPECT_TRUE(full_name_.Decode("id.0123456789abcdef0123456789ABCDEF.name.js",
-1 /*hash size*/, -1 /*signature size*/));
EXPECT_STREQ("id", full_name_.id());
EXPECT_STREQ("name", full_name_.name());
EXPECT_STREQ("0123456789abcdef0123456789ABCDEF", full_name_.hash());
EXPECT_STREQ("js", full_name_.ext());
}
TEST_F(ResourceNamerTest, TestEventualSize) {
MockHasher mock_hasher;
GoogleString file = "some_name.pagespeed.idn.0.extension";
EXPECT_TRUE(full_name_.Decode(file, 1 /*hash size*/, 0 /*signature size*/));
EXPECT_EQ(file.size(),
full_name_.EventualSize(mock_hasher, 0 /*signature size*/));
}
TEST_F(ResourceNamerTest, TestEventualSizeExperiment) {
MockHasher mock_hasher;
GoogleString file = "some_name.pagespeed.c.idn.0.extension";
EXPECT_TRUE(full_name_.Decode(file, 1 /*hash size*/, 0 /*signature size*/));
EXPECT_EQ(file.size(),
full_name_.EventualSize(mock_hasher, 0 /*signature size*/));
}
TEST_F(ResourceNamerTest, TestEventualSizeSignature) {
MockHasher mock_hasher;
GoogleString file = "some_name.pagespeed.idn.0sig.extension";
EXPECT_TRUE(full_name_.Decode(file, 1 /*hash size*/, 3 /*signature size*/));
EXPECT_EQ(file.size(),
full_name_.EventualSize(mock_hasher, 3 /*signature size*/));
EXPECT_STREQ("sig", full_name_.signature());
EXPECT_STREQ("extension", full_name_.ext());
EXPECT_STREQ("0", full_name_.hash());
}
TEST_F(ResourceNamerTest, TestAllSignaturePossibilites) {
// Test with the signature on.
full_name_.set_id("id");
full_name_.set_name("name.ext.as.many.as.I.like");
full_name_.set_hash("hash");
full_name_.set_ext("ext");
full_name_.set_signature("sig");
TestCopyAndSize(3);
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.id.hashsig.ext",
full_name_.Encode());
// Test with the signature off.
full_name_.set_signature("");
TestCopyAndSize(0);
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.id.hash.ext",
full_name_.Encode());
// Test with experiment on and signature on.
full_name_.set_signature("sig");
full_name_.set_experiment("q");
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.q.id.hashsig.ext",
full_name_.Encode());
// Test with experiment on and signature off.
full_name_.set_signature("");
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.q.id.hash.ext",
full_name_.Encode());
// Test with experiment and options on and signature on can't be done.
// Test with experiment and options on and signature off can't be done.
// Test with options on and signature on.
full_name_.set_experiment("");
full_name_.set_options("a=b");
full_name_.set_signature("sig");
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.a=b.id.hashsig.ext",
full_name_.Encode());
// Test with options on and signature off.
full_name_.set_signature("");
EXPECT_STREQ("name.ext.as.many.as.I.like.pagespeed.a=b.id.hash.ext",
full_name_.Encode());
}
TEST_F(ResourceNamerTest, TestSizeWithoutHash_HashNotSet) {
MD5Hasher md5_hasher;
full_name_.set_name("file.css");
full_name_.set_id("id");
full_name_.set_ext("ext");
EXPECT_EQ(STATIC_STRLEN("file.css") + STATIC_STRLEN("id") +
STATIC_STRLEN("ext") + ResourceNamer::kOverhead +
md5_hasher.HashSizeInChars(),
full_name_.EventualSize(md5_hasher, 0 /*signature size*/));
}
} // namespace
} // namespace net_instaweb
| apache-2.0 |
devsoulwolf/DatePicker | DatePicker/src/main/java/cn/aigestudio/datepicker/bizs/themes/DPBaseTheme.java | 901 | package cn.aigestudio.datepicker.bizs.themes;
/**
* 主题的默认实现类
*
* The default implement of theme
*
* @author AigeStudio 2015-06-17
*/
public class DPBaseTheme extends DPTheme {
@Override
public int colorBG() {
return 0xFFFFFFFF;
}
@Override
public int colorBGCircle() {
return 0x44000000;
}
@Override
public int colorTitleBG() {
return 0xFFF37B7A;
}
@Override
public int colorTitle() {
return 0xEEFFFFFF;
}
@Override
public int colorToday() {
return 0x88F37B7A;
}
@Override
public int colorG() {
return 0xEE333333;
}
@Override
public int colorF() {
return 0xEEC08AA4;
}
@Override
public int colorWeekend() {
return 0xEEF78082;
}
@Override
public int colorHoliday() {
return 0x80FED6D6;
}
}
| apache-2.0 |
ftomassetti/effectivejava | test-resources/sample-codebases/spring-jdbc/src/main/java/org/springframework/jdbc/object/SqlUpdate.java | 10107 | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.object;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterUtils;
import org.springframework.jdbc.core.namedparam.ParsedSql;
import org.springframework.jdbc.support.KeyHolder;
/**
* Reusable operation object representing a SQL update.
*
* <p>This class provides a number of {@code update} methods,
* analogous to the {@code execute} methods of query objects.
*
* <p>This class is concrete. Although it can be subclassed (for example
* to add a custom update method) it can easily be parameterized by setting
* SQL and declaring parameters.
*
* <p>Like all {@code RdbmsOperation} classes that ship with the Spring
* Framework, {@code SqlQuery} instances are thread-safe after their
* initialization is complete. That is, after they are constructed and configured
* via their setter methods, they can be used safely from multiple threads.
*
* @author Rod Johnson
* @author Thomas Risberg
* @author Juergen Hoeller
* @see SqlQuery
*/
public class SqlUpdate extends SqlOperation {
/**
* Maximum number of rows the update may affect. If more are
* affected, an exception will be thrown. Ignored if 0.
*/
private int maxRowsAffected = 0;
/**
* An exact number of rows that must be affected.
* Ignored if 0.
*/
private int requiredRowsAffected = 0;
/**
* Constructor to allow use as a JavaBean. DataSource and SQL
* must be supplied before compilation and use.
* @see #setDataSource
* @see #setSql
*/
public SqlUpdate() {
}
/**
* Constructs an update object with a given DataSource and SQL.
* @param ds DataSource to use to obtain connections
* @param sql SQL statement to execute
*/
public SqlUpdate(DataSource ds, String sql) {
setDataSource(ds);
setSql(sql);
}
/**
* Construct an update object with a given DataSource, SQL
* and anonymous parameters.
* @param ds DataSource to use to obtain connections
* @param sql SQL statement to execute
* @param types SQL types of the parameters, as defined in the
* {@code java.sql.Types} class
* @see java.sql.Types
*/
public SqlUpdate(DataSource ds, String sql, int[] types) {
setDataSource(ds);
setSql(sql);
setTypes(types);
}
/**
* Construct an update object with a given DataSource, SQL,
* anonymous parameters and specifying the maximum number of rows
* that may be affected.
* @param ds DataSource to use to obtain connections
* @param sql SQL statement to execute
* @param types SQL types of the parameters, as defined in the
* {@code java.sql.Types} class
* @param maxRowsAffected the maximum number of rows that may
* be affected by the update
* @see java.sql.Types
*/
public SqlUpdate(DataSource ds, String sql, int[] types, int maxRowsAffected) {
setDataSource(ds);
setSql(sql);
setTypes(types);
this.maxRowsAffected = maxRowsAffected;
}
/**
* Set the maximum number of rows that may be affected by this update.
* The default value is 0, which does not limit the number of rows affected.
* @param maxRowsAffected the maximum number of rows that can be affected by
* this update without this class's update method considering it an error
*/
public void setMaxRowsAffected(int maxRowsAffected) {
this.maxRowsAffected = maxRowsAffected;
}
/**
* Set the <i>exact</i> number of rows that must be affected by this update.
* The default value is 0, which allows any number of rows to be affected.
* <p>This is an alternative to setting the <i>maximum</i> number of rows
* that may be affected.
* @param requiredRowsAffected the exact number of rows that must be affected
* by this update without this class's update method considering it an error
*/
public void setRequiredRowsAffected(int requiredRowsAffected) {
this.requiredRowsAffected = requiredRowsAffected;
}
/**
* Check the given number of affected rows against the
* specified maximum number or required number.
* @param rowsAffected the number of affected rows
* @throws JdbcUpdateAffectedIncorrectNumberOfRowsException
* if the actually affected rows are out of bounds
* @see #setMaxRowsAffected
* @see #setRequiredRowsAffected
*/
protected void checkRowsAffected(int rowsAffected) throws JdbcUpdateAffectedIncorrectNumberOfRowsException {
if (this.maxRowsAffected > 0 && rowsAffected > this.maxRowsAffected) {
throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(getSql(), this.maxRowsAffected, rowsAffected);
}
if (this.requiredRowsAffected > 0 && rowsAffected != this.requiredRowsAffected) {
throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(getSql(), this.requiredRowsAffected, rowsAffected);
}
}
/**
* Generic method to execute the update given parameters.
* All other update methods invoke this method.
* @param params array of parameters objects
* @return the number of rows affected by the update
*/
public int update(Object... params) throws DataAccessException {
validateParameters(params);
int rowsAffected = getJdbcTemplate().update(newPreparedStatementCreator(params));
checkRowsAffected(rowsAffected);
return rowsAffected;
}
/**
* Method to execute the update given arguments and
* retrieve the generated keys using a KeyHolder.
* @param params array of parameter objects
* @param generatedKeyHolder KeyHolder that will hold the generated keys
* @return the number of rows affected by the update
*/
public int update(Object[] params, KeyHolder generatedKeyHolder) throws DataAccessException {
if (!isReturnGeneratedKeys() && getGeneratedKeysColumnNames() == null) {
throw new InvalidDataAccessApiUsageException(
"The update method taking a KeyHolder should only be used when generated keys have " +
"been configured by calling either 'setReturnGeneratedKeys' or " +
"'setGeneratedKeysColumnNames'.");
}
validateParameters(params);
int rowsAffected = getJdbcTemplate().update(newPreparedStatementCreator(params), generatedKeyHolder);
checkRowsAffected(rowsAffected);
return rowsAffected;
}
/**
* Convenience method to execute an update with no parameters.
*/
public int update() throws DataAccessException {
return update((Object[]) null);
}
/**
* Convenient method to execute an update given one int arg.
*/
public int update(int p1) throws DataAccessException {
return update(new Object[] {p1});
}
/**
* Convenient method to execute an update given two int args.
*/
public int update(int p1, int p2) throws DataAccessException {
return update(new Object[] {p1, p2});
}
/**
* Convenient method to execute an update given one long arg.
*/
public int update(long p1) throws DataAccessException {
return update(new Object[] {p1});
}
/**
* Convenient method to execute an update given two long args.
*/
public int update(long p1, long p2) throws DataAccessException {
return update(new Object[] {p1, p2});
}
/**
* Convenient method to execute an update given one String arg.
*/
public int update(String p) throws DataAccessException {
return update(new Object[] {p});
}
/**
* Convenient method to execute an update given two String args.
*/
public int update(String p1, String p2) throws DataAccessException {
return update(new Object[] {p1, p2});
}
/**
* Generic method to execute the update given named parameters.
* All other update methods invoke this method.
* @param paramMap Map of parameter name to parameter object,
* matching named parameters specified in the SQL statement
* @return the number of rows affected by the update
*/
public int updateByNamedParam(Map<String, ?> paramMap) throws DataAccessException {
validateNamedParameters(paramMap);
ParsedSql parsedSql = getParsedSql();
MapSqlParameterSource paramSource = new MapSqlParameterSource(paramMap);
String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, getDeclaredParameters());
int rowsAffected = getJdbcTemplate().update(newPreparedStatementCreator(sqlToUse, params));
checkRowsAffected(rowsAffected);
return rowsAffected;
}
/**
* Method to execute the update given arguments and
* retrieve the generated keys using a KeyHolder.
* @param paramMap Map of parameter name to parameter object,
* matching named parameters specified in the SQL statement
* @param generatedKeyHolder KeyHolder that will hold the generated keys
* @return the number of rows affected by the update
*/
public int updateByNamedParam(Map<String, ?> paramMap, KeyHolder generatedKeyHolder) throws DataAccessException {
validateNamedParameters(paramMap);
ParsedSql parsedSql = getParsedSql();
MapSqlParameterSource paramSource = new MapSqlParameterSource(paramMap);
String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, getDeclaredParameters());
int rowsAffected = getJdbcTemplate().update(newPreparedStatementCreator(sqlToUse, params), generatedKeyHolder);
checkRowsAffected(rowsAffected);
return rowsAffected;
}
}
| apache-2.0 |
robin13/elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/Aggregations.java | 5008 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search.aggregations;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.ToXContentFragment;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.common.xcontent.XContentParserUtils.parseTypedKeysObject;
/**
* Represents a set of {@link Aggregation}s
*/
public class Aggregations implements Iterable<Aggregation>, ToXContentFragment {
public static final String AGGREGATIONS_FIELD = "aggregations";
protected final List<? extends Aggregation> aggregations;
private Map<String, Aggregation> aggregationsAsMap;
public Aggregations(List<? extends Aggregation> aggregations) {
this.aggregations = aggregations;
if (aggregations.isEmpty()) {
aggregationsAsMap = emptyMap();
}
}
/**
* Iterates over the {@link Aggregation}s.
*/
@Override
public final Iterator<Aggregation> iterator() {
return aggregations.stream().map((p) -> (Aggregation) p).iterator();
}
/**
* The list of {@link Aggregation}s.
*/
public final List<Aggregation> asList() {
return Collections.unmodifiableList(aggregations);
}
/**
* Returns the {@link Aggregation}s keyed by aggregation name.
*/
public final Map<String, Aggregation> asMap() {
return getAsMap();
}
/**
* Returns the {@link Aggregation}s keyed by aggregation name.
*/
public final Map<String, Aggregation> getAsMap() {
if (aggregationsAsMap == null) {
Map<String, Aggregation> newAggregationsAsMap = new HashMap<>(aggregations.size());
for (Aggregation aggregation : aggregations) {
newAggregationsAsMap.put(aggregation.getName(), aggregation);
}
this.aggregationsAsMap = unmodifiableMap(newAggregationsAsMap);
}
return aggregationsAsMap;
}
/**
* Returns the aggregation that is associated with the specified name.
*/
@SuppressWarnings("unchecked")
public final <A extends Aggregation> A get(String name) {
return (A) asMap().get(name);
}
@Override
public final boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return aggregations.equals(((Aggregations) obj).aggregations);
}
@Override
public final int hashCode() {
return Objects.hash(getClass(), aggregations);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (aggregations.isEmpty()) {
return builder;
}
builder.startObject(AGGREGATIONS_FIELD);
toXContentInternal(builder, params);
return builder.endObject();
}
/**
* Directly write all the aggregations without their bounding object. Used by sub-aggregations (non top level aggs)
*/
public XContentBuilder toXContentInternal(XContentBuilder builder, Params params) throws IOException {
for (Aggregation aggregation : aggregations) {
aggregation.toXContent(builder, params);
}
return builder;
}
public static Aggregations fromXContent(XContentParser parser) throws IOException {
final List<Aggregation> aggregations = new ArrayList<>();
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.START_OBJECT) {
SetOnce<Aggregation> typedAgg = new SetOnce<>();
String currentField = parser.currentName();
parseTypedKeysObject(parser, Aggregation.TYPED_KEYS_DELIMITER, Aggregation.class, typedAgg::set);
if (typedAgg.get() != null) {
aggregations.add(typedAgg.get());
} else {
throw new ParsingException(parser.getTokenLocation(),
String.format(Locale.ROOT, "Could not parse aggregation keyed as [%s]", currentField));
}
}
}
return new Aggregations(aggregations);
}
}
| apache-2.0 |
hgschmie/presto | presto-client/src/main/java/io/prestosql/client/NodeVersion.java | 1705 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.client;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.annotation.concurrent.Immutable;
import java.util.Objects;
import static java.util.Objects.requireNonNull;
@Immutable
public class NodeVersion
{
public static final NodeVersion UNKNOWN = new NodeVersion("<unknown>");
private final String version;
@JsonCreator
public NodeVersion(@JsonProperty("version") String version)
{
this.version = requireNonNull(version, "version is null");
}
@JsonProperty
public String getVersion()
{
return version;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NodeVersion that = (NodeVersion) o;
return Objects.equals(version, that.version);
}
@Override
public int hashCode()
{
return Objects.hash(version);
}
@Override
public String toString()
{
return version;
}
}
| apache-2.0 |
ryano144/intellij-community | java/java-tests/testSrc/com/intellij/lang/java/parser/JavaParsingTestCase.java | 5059 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.lang.java.parser;
import com.intellij.lang.ASTNode;
import com.intellij.lang.LanguageASTFactory;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.lang.java.JavaParserDefinition;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.roots.impl.LanguageLevelProjectExtensionImpl;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.SingleRootFileViewProvider;
import com.intellij.psi.impl.source.PsiJavaFileImpl;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.impl.source.tree.JavaASTFactory;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.util.PsiUtil;
import com.intellij.testFramework.IdeaTestCase;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.testFramework.ParsingTestCase;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
public abstract class JavaParsingTestCase extends ParsingTestCase {
private LanguageLevel myLanguageLevel;
@SuppressWarnings({"JUnitTestCaseWithNonTrivialConstructors"})
public JavaParsingTestCase(@NonNls final String dataPath) {
super("psi/"+dataPath, "java", new JavaParserDefinition());
IdeaTestCase.initPlatformPrefix();
}
@Override
protected void setUp() throws Exception {
super.setUp();
myLanguageLevel = LanguageLevel.JDK_1_6;
getProject().registerService(LanguageLevelProjectExtension.class, new LanguageLevelProjectExtensionImpl(getProject()));
addExplicitExtension(LanguageASTFactory.INSTANCE, JavaLanguage.INSTANCE, new JavaASTFactory());
}
@Override
protected PsiFile createFile(String name, String text) {
final PsiFile file = super.createFile(name, text);
file.putUserData(PsiUtil.FILE_LANGUAGE_LEVEL_KEY, myLanguageLevel);
return file;
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
protected interface TestParser {
void parse(PsiBuilder builder);
}
protected void setLanguageLevel(@NotNull LanguageLevel languageLevel) {
myLanguageLevel = languageLevel;
}
protected void doParserTest(final String text, final TestParser parser) {
final String name = getTestName(false);
myFile = createPsiFile(name, text, parser);
myFile.putUserData(PsiUtil.FILE_LANGUAGE_LEVEL_KEY, myLanguageLevel);
try {
checkResult(name, myFile);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private static IFileElementType TEST_FILE_ELEMENT_TYPE = null;
private static TestParser TEST_PARSER;
private PsiFile createPsiFile(final String name, final String text, final TestParser parser) {
if (TEST_FILE_ELEMENT_TYPE == null) {
TEST_FILE_ELEMENT_TYPE = new MyIFileElementType();
}
TEST_PARSER = parser;
final LightVirtualFile virtualFile = new LightVirtualFile(name + '.' + myFileExt, StdFileTypes.JAVA, text, -1);
final FileViewProvider viewProvider = new SingleRootFileViewProvider(PsiManager.getInstance(getProject()), virtualFile, true);
return new PsiJavaFileImpl(viewProvider) {
@NotNull
@Override
protected FileElement createFileElement(@NotNull final CharSequence text) {
return new FileElement(TEST_FILE_ELEMENT_TYPE, text);
}
};
}
private static PsiBuilder createBuilder(final ASTNode chameleon) {
final PsiBuilder builder = JavaParserUtil.createBuilder(chameleon);
builder.setDebugMode(true);
return builder;
}
private static class MyIFileElementType extends IFileElementType {
public MyIFileElementType() {
super("test.java.file", JavaLanguage.INSTANCE);
}
@Override
public ASTNode parseContents(final ASTNode chameleon) {
final PsiBuilder builder = createBuilder(chameleon);
final PsiBuilder.Marker root = builder.mark();
TEST_PARSER.parse(builder);
if (!builder.eof()) {
final PsiBuilder.Marker unparsed = builder.mark();
while (!builder.eof()) builder.advanceLexer();
unparsed.error("Unparsed tokens");
}
root.done(this);
final ASTNode rootNode = builder.getTreeBuilt();
return rootNode.getFirstChildNode();
}
}
}
| apache-2.0 |
vladisav/ignite | modules/core/src/test/java/org/apache/ignite/cache/store/CacheStoreSessionListenerAbstractSelfTest.java | 10964 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.cache.store;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.cache.configuration.Factory;
import javax.cache.integration.CacheWriterException;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.transactions.Transaction;
/**
* Tests for store session listeners.
*/
public abstract class CacheStoreSessionListenerAbstractSelfTest extends GridCommonAbstractTest implements Serializable {
/** */
private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
/** */
protected static final String URL = "jdbc:h2:mem:example;DB_CLOSE_DELAY=-1";
/** */
protected static final AtomicInteger loadCacheCnt = new AtomicInteger();
/** */
protected static final AtomicInteger loadCnt = new AtomicInteger();
/** */
protected static final AtomicInteger writeCnt = new AtomicInteger();
/** */
protected static final AtomicInteger deleteCnt = new AtomicInteger();
/** */
protected static final AtomicInteger reuseCnt = new AtomicInteger();
/** */
protected static final AtomicBoolean write = new AtomicBoolean();
/** */
protected static final AtomicBoolean fail = new AtomicBoolean();
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
TcpDiscoverySpi disco = new TcpDiscoverySpi();
disco.setIpFinder(IP_FINDER);
cfg.setDiscoverySpi(disco);
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
startGridsMultiThreaded(3);
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
conn.createStatement().executeUpdate("DROP TABLE IF EXISTS Table1");
conn.createStatement().executeUpdate("DROP TABLE IF EXISTS Table2");
conn.createStatement().executeUpdate("CREATE TABLE Table1 (id INT AUTO_INCREMENT, key INT, value INT)");
conn.createStatement().executeUpdate("CREATE TABLE Table2 (id INT AUTO_INCREMENT, key INT, value INT)");
}
loadCacheCnt.set(0);
loadCnt.set(0);
writeCnt.set(0);
deleteCnt.set(0);
reuseCnt.set(0);
write.set(false);
fail.set(false);
}
/**
* @throws Exception If failed.
*/
public void testAtomicCache() throws Exception {
CacheConfiguration<Integer, Integer> cfg = cacheConfiguration(DEFAULT_CACHE_NAME, CacheAtomicityMode.ATOMIC);
IgniteCache<Integer, Integer> cache = ignite(0).createCache(cfg);
try {
cache.loadCache(null);
cache.get(1);
cache.put(1, 1);
cache.remove(1);
}
finally {
cache.destroy();
}
assertEquals(3, loadCacheCnt.get());
assertEquals(1, loadCnt.get());
assertEquals(1, writeCnt.get());
assertEquals(1, deleteCnt.get());
assertEquals(0, reuseCnt.get());
}
/**
* @throws Exception If failed.
*/
public void testTransactionalCache() throws Exception {
CacheConfiguration<Integer, Integer> cfg = cacheConfiguration(DEFAULT_CACHE_NAME, CacheAtomicityMode.TRANSACTIONAL);
IgniteCache<Integer, Integer> cache = ignite(0).createCache(cfg);
try {
cache.loadCache(null);
cache.get(1);
cache.put(1, 1);
cache.remove(1);
}
finally {
cache.destroy();
}
assertEquals(3, loadCacheCnt.get());
assertEquals(1, loadCnt.get());
assertEquals(1, writeCnt.get());
assertEquals(1, deleteCnt.get());
assertEquals(0, reuseCnt.get());
}
/**
* @throws Exception If failed.
*/
public void testExplicitTransaction() throws Exception {
CacheConfiguration<Integer, Integer> cfg = cacheConfiguration(DEFAULT_CACHE_NAME, CacheAtomicityMode.TRANSACTIONAL);
IgniteCache<Integer, Integer> cache = ignite(0).createCache(cfg);
try (Transaction tx = ignite(0).transactions().txStart()) {
cache.put(1, 1);
cache.put(2, 2);
cache.remove(3);
cache.remove(4);
tx.commit();
}
finally {
cache.destroy();
}
assertEquals(2, writeCnt.get());
assertEquals(2, deleteCnt.get());
assertEquals(3, reuseCnt.get());
}
/**
* @throws Exception If failed.
*/
public void testCrossCacheTransaction() throws Exception {
CacheConfiguration<Integer, Integer> cfg1 = cacheConfiguration("cache1", CacheAtomicityMode.TRANSACTIONAL);
CacheConfiguration<Integer, Integer> cfg2 = cacheConfiguration("cache2", CacheAtomicityMode.TRANSACTIONAL);
IgniteCache<Integer, Integer> cache1 = ignite(0).createCache(cfg1);
IgniteCache<Integer, Integer> cache2 = ignite(0).createCache(cfg2);
try (Transaction tx = ignite(0).transactions().txStart()) {
cache1.put(1, 1);
cache2.put(2, 2);
cache1.remove(3);
cache2.remove(4);
tx.commit();
}
finally {
cache1.destroy();
cache2.destroy();
}
assertEquals(2, writeCnt.get());
assertEquals(2, deleteCnt.get());
assertEquals(3, reuseCnt.get());
}
/**
* @throws Exception If failed.
*/
public void testCommit() throws Exception {
write.set(true);
CacheConfiguration<Integer, Integer> cfg1 = cacheConfiguration("cache1", CacheAtomicityMode.TRANSACTIONAL);
CacheConfiguration<Integer, Integer> cfg2 = cacheConfiguration("cache2", CacheAtomicityMode.TRANSACTIONAL);
IgniteCache<Integer, Integer> cache1 = ignite(0).createCache(cfg1);
IgniteCache<Integer, Integer> cache2 = ignite(0).createCache(cfg2);
try (Transaction tx = ignite(0).transactions().txStart()) {
cache1.put(1, 1);
cache2.put(2, 2);
tx.commit();
}
finally {
cache1.destroy();
cache2.destroy();
}
try (Connection conn = DriverManager.getConnection(URL)) {
checkTable(conn, 1, false);
checkTable(conn, 2, false);
}
}
/**
* @throws Exception If failed.
*/
public void testRollback() throws Exception {
write.set(true);
fail.set(true);
CacheConfiguration<Integer, Integer> cfg1 = cacheConfiguration("cache1", CacheAtomicityMode.TRANSACTIONAL);
CacheConfiguration<Integer, Integer> cfg2 = cacheConfiguration("cache2", CacheAtomicityMode.TRANSACTIONAL);
IgniteCache<Integer, Integer> cache1 = ignite(0).createCache(cfg1);
IgniteCache<Integer, Integer> cache2 = ignite(0).createCache(cfg2);
try (Transaction tx = ignite(0).transactions().txStart()) {
cache1.put(1, 1);
cache2.put(2, 2);
tx.commit();
assert false : "Exception was not thrown.";
}
catch (IgniteException e) {
CacheWriterException we = X.cause(e, CacheWriterException.class);
assertNotNull(we);
assertEquals("Expected failure.", we.getMessage());
}
finally {
cache1.destroy();
cache2.destroy();
}
try (Connection conn = DriverManager.getConnection(URL)) {
checkTable(conn, 1, true);
checkTable(conn, 2, true);
}
}
/**
* @param conn Connection.
* @param idx Table index.
* @param empty If table expected to be empty.
* @throws Exception In case of error.
*/
private void checkTable(Connection conn, int idx, boolean empty) throws Exception {
ResultSet rs = conn.createStatement().executeQuery("SELECT key, value FROM Table" + idx);
int cnt = 0;
while (rs.next()) {
int key = rs.getInt(1);
int val = rs.getInt(2);
assertEquals(idx, key);
assertEquals(idx, val);
cnt++;
}
assertEquals(empty ? 0 : 1, cnt);
}
/**
* @param name Cache name.
* @param atomicity Atomicity mode.
* @return Cache configuration.
*/
private CacheConfiguration<Integer, Integer> cacheConfiguration(String name, CacheAtomicityMode atomicity) {
CacheConfiguration<Integer, Integer> cfg = new CacheConfiguration<>();
cfg.setName(name);
cfg.setAtomicityMode(atomicity);
cfg.setCacheStoreFactory(storeFactory());
cfg.setCacheStoreSessionListenerFactories(sessionListenerFactory());
cfg.setReadThrough(true);
cfg.setWriteThrough(true);
cfg.setLoadPreviousValue(true);
return cfg;
}
/**
* @return Store factory.
*/
protected abstract Factory<? extends CacheStore<Integer, Integer>> storeFactory();
/**
* @return Session listener factory.
*/
protected abstract Factory<CacheStoreSessionListener> sessionListenerFactory();
} | apache-2.0 |
duke2906/traccar | test/org/traccar/protocol/CradlepointProtocolDecoderTest.java | 466 | package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class CradlepointProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
CradlepointProtocolDecoder decoder = new CradlepointProtocolDecoder(new CradlepointProtocol());
verifyPosition(decoder, text(
"+12084014675,162658,4337.174385,N,11612.338373,W,0.0,,Verizon,,-71,-44,-11,,"));
}
}
| apache-2.0 |
dongjiaqiang/docker | daemon/volumes.go | 6624 | package daemon
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"github.com/Sirupsen/logrus"
derr "github.com/docker/docker/api/errors"
"github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/chrootarchive"
"github.com/docker/docker/pkg/system"
"github.com/docker/docker/volume"
"github.com/docker/docker/volume/drivers"
)
var (
// ErrVolumeReadonly is used to signal an error when trying to copy data into
// a volume mount that is not writable.
ErrVolumeReadonly = errors.New("mounted volume is marked read-only")
// ErrVolumeInUse is a typed error returned when trying to remove a volume that is currently in use by a container
ErrVolumeInUse = errors.New("volume is in use")
// ErrNoSuchVolume is a typed error returned if the requested volume doesn't exist in the volume store
ErrNoSuchVolume = errors.New("no such volume")
)
// mountPoint is the intersection point between a volume and a container. It
// specifies which volume is to be used and where inside a container it should
// be mounted.
type mountPoint struct {
Name string
Destination string
Driver string
RW bool
Volume volume.Volume `json:"-"`
Source string
Mode string `json:"Relabel"` // Originally field was `Relabel`"
}
// Setup sets up a mount point by either mounting the volume if it is
// configured, or creating the source directory if supplied.
func (m *mountPoint) Setup() (string, error) {
if m.Volume != nil {
return m.Volume.Mount()
}
if len(m.Source) > 0 {
if _, err := os.Stat(m.Source); err != nil {
if !os.IsNotExist(err) {
return "", err
}
if err := system.MkdirAll(m.Source, 0755); err != nil {
return "", err
}
}
return m.Source, nil
}
return "", derr.ErrorCodeMountSetup
}
// hasResource checks whether the given absolute path for a container is in
// this mount point. If the relative path starts with `../` then the resource
// is outside of this mount point, but we can't simply check for this prefix
// because it misses `..` which is also outside of the mount, so check both.
func (m *mountPoint) hasResource(absolutePath string) bool {
relPath, err := filepath.Rel(m.Destination, absolutePath)
return err == nil && relPath != ".." && !strings.HasPrefix(relPath, fmt.Sprintf("..%c", filepath.Separator))
}
// Path returns the path of a volume in a mount point.
func (m *mountPoint) Path() string {
if m.Volume != nil {
return m.Volume.Path()
}
return m.Source
}
// copyExistingContents copies from the source to the destination and
// ensures the ownership is appropriately set.
func copyExistingContents(source, destination string) error {
volList, err := ioutil.ReadDir(source)
if err != nil {
return err
}
if len(volList) > 0 {
srcList, err := ioutil.ReadDir(destination)
if err != nil {
return err
}
if len(srcList) == 0 {
// If the source volume is empty copy files from the root into the volume
if err := chrootarchive.CopyWithTar(source, destination); err != nil {
return err
}
}
}
return copyOwnership(source, destination)
}
func newVolumeStore(vols []volume.Volume) *volumeStore {
store := &volumeStore{
vols: make(map[string]*volumeCounter),
}
for _, v := range vols {
store.vols[v.Name()] = &volumeCounter{v, 0}
}
return store
}
// volumeStore is a struct that stores the list of volumes available and keeps track of their usage counts
type volumeStore struct {
vols map[string]*volumeCounter
mu sync.Mutex
}
type volumeCounter struct {
volume.Volume
count int
}
func getVolumeDriver(name string) (volume.Driver, error) {
if name == "" {
name = volume.DefaultDriverName
}
return volumedrivers.Lookup(name)
}
// Create tries to find an existing volume with the given name or create a new one from the passed in driver
func (s *volumeStore) Create(name, driverName string, opts map[string]string) (volume.Volume, error) {
s.mu.Lock()
if vc, exists := s.vols[name]; exists {
v := vc.Volume
s.mu.Unlock()
return v, nil
}
s.mu.Unlock()
logrus.Debugf("Registering new volume reference: driver %s, name %s", driverName, name)
vd, err := getVolumeDriver(driverName)
if err != nil {
return nil, err
}
v, err := vd.Create(name, opts)
if err != nil {
return nil, err
}
s.mu.Lock()
s.vols[v.Name()] = &volumeCounter{v, 0}
s.mu.Unlock()
return v, nil
}
// Get looks if a volume with the given name exists and returns it if so
func (s *volumeStore) Get(name string) (volume.Volume, error) {
s.mu.Lock()
defer s.mu.Unlock()
vc, exists := s.vols[name]
if !exists {
return nil, ErrNoSuchVolume
}
return vc.Volume, nil
}
// Remove removes the requested volume. A volume is not removed if the usage count is > 0
func (s *volumeStore) Remove(v volume.Volume) error {
s.mu.Lock()
defer s.mu.Unlock()
name := v.Name()
logrus.Debugf("Removing volume reference: driver %s, name %s", v.DriverName(), name)
vc, exists := s.vols[name]
if !exists {
return ErrNoSuchVolume
}
if vc.count != 0 {
return ErrVolumeInUse
}
vd, err := getVolumeDriver(vc.DriverName())
if err != nil {
return err
}
if err := vd.Remove(vc.Volume); err != nil {
return err
}
delete(s.vols, name)
return nil
}
// Increment increments the usage count of the passed in volume by 1
func (s *volumeStore) Increment(v volume.Volume) {
s.mu.Lock()
defer s.mu.Unlock()
logrus.Debugf("Incrementing volume reference: driver %s, name %s", v.DriverName(), v.Name())
vc, exists := s.vols[v.Name()]
if !exists {
s.vols[v.Name()] = &volumeCounter{v, 1}
return
}
vc.count++
return
}
// Decrement decrements the usage count of the passed in volume by 1
func (s *volumeStore) Decrement(v volume.Volume) {
s.mu.Lock()
defer s.mu.Unlock()
logrus.Debugf("Decrementing volume reference: driver %s, name %s", v.DriverName(), v.Name())
vc, exists := s.vols[v.Name()]
if !exists {
return
}
vc.count--
return
}
// Count returns the usage count of the passed in volume
func (s *volumeStore) Count(v volume.Volume) int {
s.mu.Lock()
defer s.mu.Unlock()
vc, exists := s.vols[v.Name()]
if !exists {
return 0
}
return vc.count
}
// List returns all the available volumes
func (s *volumeStore) List() []volume.Volume {
s.mu.Lock()
defer s.mu.Unlock()
var ls []volume.Volume
for _, vc := range s.vols {
ls = append(ls, vc.Volume)
}
return ls
}
// volumeToAPIType converts a volume.Volume to the type used by the remote API
func volumeToAPIType(v volume.Volume) *types.Volume {
return &types.Volume{
Name: v.Name(),
Driver: v.DriverName(),
Mountpoint: v.Path(),
}
}
| apache-2.0 |
dvirgiln/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OperationModel.java | 3297 | /*
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.switchyard.component.common.knowledge.config.model;
import org.switchyard.component.common.knowledge.operation.KnowledgeOperationType;
import org.switchyard.config.model.NamedModel;
/**
* An Operation Model.
*
* @author David Ward <<a href="mailto:dward@jboss.org">dward@jboss.org</a>> © 2012 Red Hat Inc.
*/
public interface OperationModel extends NamedModel {
/** The "operation" name. */
public static final String OPERATION = "operation";
/**
* Gets the eventId attribute.
* @return the eventId attribute
*/
public String getEventId();
/**
* Sets the eventId attribute.
* @param eventId the eventId attribute
* @return this OperationModel (useful for chaining)
*/
public OperationModel setEventId(String eventId);
/**
* Gets the type attribute.
* @return the type attribute
*/
public KnowledgeOperationType getType();
/**
* Sets the type attribute.
* @param type the type attribute
* @return this OperationModel (useful for chaining)
*/
public OperationModel setType(KnowledgeOperationType type);
/**
* Gets the child globals mappings model.
* @return the child globals mappings model
*/
public GlobalsModel getGlobals();
/**
* Sets the child globals mappings model.
* @param globals the child globals mappings model
* @return this OperationModel (useful for chaining)
*/
public OperationModel setGlobals(GlobalsModel globals);
/**
* Gets the child inputs mappings model.
* @return the child inputs mappings model
*/
public InputsModel getInputs();
/**
* Sets the child inputs mappings model.
* @param inputs the child inputs mappings model
* @return this OperationModel (useful for chaining)
*/
public OperationModel setInputs(InputsModel inputs);
/**
* Gets the child outputs mappings model.
* @return the child outputs mappings model
*/
public OutputsModel getOutputs();
/**
* Sets the child outputs mappings model.
* @param outputs the child outputs mappings model
* @return this OperationModel (useful for chaining)
*/
public OperationModel setOutputs(OutputsModel outputs);
/**
* Gets the child faults mappings model.
* @return the child faults mappings model
*/
public FaultsModel getFaults();
/**
* Sets the child faults mappings model.
* @param faults the child faults mappings model
* @return this OperationModel (useful for chaining)
*/
public OperationModel setFaults(FaultsModel faults);
}
| apache-2.0 |
chandresh-pancholi/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/QueryEntityTypeDescriptor.java | 7739 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.query;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.cache.CacheException;
import org.apache.ignite.cache.QueryIndex;
import org.apache.ignite.cache.QueryIndexType;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.internal.processors.query.GridQueryIndexDescriptor;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.jetbrains.annotations.NotNull;
/**
* Descriptor of type.
*/
public class QueryEntityTypeDescriptor {
/** Value field names and types with preserved order. */
@GridToStringInclude
private final Map<String, Class<?>> fields = new LinkedHashMap<>();
/** */
@GridToStringExclude
private final Map<String, QueryEntityClassProperty> props = new LinkedHashMap<>();
/** */
@GridToStringInclude
private final Set<String> keyProps = new HashSet<>();
/** */
@GridToStringInclude
private final Map<String, QueryEntityIndexDescriptor> indexes = new HashMap<>();
/** */
private Set<String> notNullFields = new HashSet<>();
/** Precision information. */
private Map<String, Integer> fieldsPrecision = new HashMap<>();
/** Scale information. */
private Map<String, Integer> fieldsScale = new HashMap<>();
/** */
private QueryEntityIndexDescriptor fullTextIdx;
/** */
private final Class<?> keyCls;
/** */
private final Class<?> valCls;
/** */
private boolean valTextIdx;
/**
* Constructor.
*
* @param keyCls QueryEntity key class.
* @param valCls QueryEntity value class.
*/
public QueryEntityTypeDescriptor(@NotNull Class<?> keyCls, @NotNull Class<?> valCls) {
this.keyCls = keyCls;
this.valCls = valCls;
}
/**
* @return Indexes.
*/
public Map<String, GridQueryIndexDescriptor> indexes() {
return Collections.<String, GridQueryIndexDescriptor>unmodifiableMap(indexes);
}
/**
* Adds index.
*
* @param idxName Index name.
* @param type Index type.
* @param inlineSize Inline size.
* @return Index descriptor.
*/
public QueryEntityIndexDescriptor addIndex(String idxName, QueryIndexType type, int inlineSize) {
if (inlineSize < 0 && inlineSize != QueryIndex.DFLT_INLINE_SIZE)
throw new CacheException("Illegal inline size [idxName=" + idxName + ", inlineSize=" + inlineSize + ']');
QueryEntityIndexDescriptor idx = new QueryEntityIndexDescriptor(type, inlineSize);
if (indexes.put(idxName, idx) != null)
throw new CacheException("Index with name '" + idxName + "' already exists.");
return idx;
}
/**
* Adds field to index.
*
* @param idxName Index name.
* @param field Field name.
* @param orderNum Fields order number in index.
* @param descending Sorting order.
*/
public void addFieldToIndex(String idxName, String field, int orderNum,
boolean descending) {
QueryEntityIndexDescriptor desc = indexes.get(idxName);
if (desc == null)
desc = addIndex(idxName, QueryIndexType.SORTED, QueryIndex.DFLT_INLINE_SIZE);
desc.addField(field, orderNum, descending);
}
/**
* Adds field to text index.
*
* @param field Field name.
*/
public void addFieldToTextIndex(String field) {
if (fullTextIdx == null) {
fullTextIdx = new QueryEntityIndexDescriptor(QueryIndexType.FULLTEXT);
indexes.put(null, fullTextIdx);
}
fullTextIdx.addField(field, 0, false);
}
/**
* @return Value class.
*/
public Class<?> valueClass() {
return valCls;
}
/**
* @return Key class.
*/
public Class<?> keyClass() {
return keyCls;
}
/**
* Adds property to the type descriptor.
*
* @param prop Property.
* @param sqlAnn SQL annotation, can be {@code null}.
* @param key Property ownership flag (key or not).
* @param failOnDuplicate Fail on duplicate flag.
*/
public void addProperty(QueryEntityClassProperty prop, QuerySqlField sqlAnn, boolean key, boolean failOnDuplicate) {
String propName = prop.name();
if (sqlAnn != null && !F.isEmpty(sqlAnn.name()))
propName = sqlAnn.name();
if (props.put(propName, prop) != null && failOnDuplicate) {
throw new CacheException("Property with name '" + propName + "' already exists for " +
(key ? "key" : "value") + ": " +
"QueryEntity [key=" + keyCls.getName() + ", value=" + valCls.getName() + ']');
}
fields.put(prop.fullName(), prop.type());
if (key)
keyProps.add(prop.fullName());
}
/**
* Adds a notNull field.
*
* @param field notNull field.
*/
public void addNotNullField(String field) {
notNullFields.add(field);
}
/**
* Adds fieldsPrecision info.
*
* @param field Field.
* @param precision Precision.
*/
public void addPrecision(String field, Integer precision) {
fieldsPrecision.put(field, precision);
}
/**
* Adds fieldsScale info.
*
* @param field Field.
* @param scale Scale.
*/
public void addScale(String field, int scale) {
fieldsScale.put(field, scale);
}
/**
* @return notNull fields.
*/
public Set<String> notNullFields() {
return notNullFields;
}
/**
* @return Precision info for fields.
*/
public Map<String, Integer> fieldsPrecision() {
return fieldsPrecision;
}
/**
* @return Scale info for fields.
*/
public Map<String, Integer> fieldsScale() {
return fieldsScale;
}
/**
* @return Class properties.
*/
public Map<String, QueryEntityClassProperty> properties() {
return props;
}
/**
* @return Properties keys.
*/
public Set<String> keyProperties() {
return keyProps;
}
/**
* @return {@code true} If we need to have a fulltext index on value.
*/
public boolean valueTextIndex() {
return valTextIdx;
}
/**
* Sets if this value should be text indexed.
*
* @param valTextIdx Flag value.
*/
public void valueTextIndex(boolean valTextIdx) {
this.valTextIdx = valTextIdx;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(QueryEntityTypeDescriptor.class, this);
}
}
| apache-2.0 |
Cloudyle/hapi-fhir | hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java | 5059 | package ca.uhn.fhir.rest.client;
import static org.junit.Assert.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.EnumerationUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.BeforeClass;
import org.junit.Test;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu.resource.Patient;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Read;
import ca.uhn.fhir.rest.server.IResourceProvider;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.util.PortUtil;
public class HttpProxyTest {
private static FhirContext ourCtx;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(HttpProxyTest.class);
private static HttpServletRequest ourRequest;
private boolean myFirstRequest;
private String myAuthHeader;
@SuppressWarnings("serial")
@Test
public void testProxiedRequest() throws Exception {
int port = PortUtil.findFreePort();
Server server = new Server(port);
myFirstRequest = true;
myAuthHeader = null;
RestfulServer restServer = new RestfulServer(ourCtx) {
@Override
protected void doGet(HttpServletRequest theRequest, HttpServletResponse theResponse) throws ServletException, IOException {
if (myFirstRequest) {
theResponse.addHeader("Proxy-Authenticate", "Basic realm=\"some_realm\"");
theResponse.setStatus(407);
theResponse.getWriter().close();
myFirstRequest = false;
return;
}
String auth = theRequest.getHeader("Proxy-Authorization");
if (auth != null) {
myAuthHeader = auth;
}
super.doGet(theRequest, theResponse);
}
};
restServer.setResourceProviders(new PatientResourceProvider());
// ServletHandler proxyHandler = new ServletHandler();
ServletHolder servletHolder = new ServletHolder(restServer);
ServletContextHandler ch = new ServletContextHandler();
ch.setContextPath("/rootctx/rcp2");
ch.addServlet(servletHolder, "/fhirctx/fcp2/*");
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
server.setHandler(ch);
server.start();
try {
// final String authUser = "username";
// final String authPassword = "password";
// CredentialsProvider credsProvider = new BasicCredentialsProvider();
// credsProvider.setCredentials(new AuthScope("127.0.0.1", port), new UsernamePasswordCredentials(authUser, authPassword));
//
// HttpHost myProxy = new HttpHost("127.0.0.1", port);
//
// //@formatter:off
// HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// clientBuilder
// .setProxy(myProxy)
// .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
// .setDefaultCredentialsProvider(credsProvider)
// .disableCookieManagement();
// CloseableHttpClient httpClient = clientBuilder.build();
// //@formatter:on
// ourCtx.getRestfulClientFactory().setHttpClient(httpClient);
ourCtx.getRestfulClientFactory().setProxy("127.0.0.1", port);
ourCtx.getRestfulClientFactory().setProxyCredentials("username", "password");
String baseUri = "http://99.99.99.99:" + port + "/rootctx/rcp2/fhirctx/fcp2";
IGenericClient client = ourCtx.newRestfulGenericClient(baseUri);
IdDt id = new IdDt("Patient", "123");
client.read(Patient.class, id);
assertEquals("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", myAuthHeader);
} finally {
server.stop();
}
}
@BeforeClass
public static void beforeClass() throws Exception {
ourCtx = FhirContext.forDstu1();
}
public static class PatientResourceProvider implements IResourceProvider {
@Override
public Class<? extends IResource> getResourceType() {
return Patient.class;
}
@Read
public Patient read(@IdParam IdDt theId, HttpServletRequest theRequest) {
Patient retVal = new Patient();
retVal.setId(theId);
ourRequest = theRequest;
ourLog.info(EnumerationUtils.toList(ourRequest.getHeaderNames()).toString());
ourLog.info("Proxy-Connection: " + EnumerationUtils.toList(ourRequest.getHeaders("Proxy-Connection")));
ourLog.info("Host: " + EnumerationUtils.toList(ourRequest.getHeaders("Host")));
ourLog.info("User-Agent: " + EnumerationUtils.toList(ourRequest.getHeaders("User-Agent")));
return retVal;
}
}
}
| apache-2.0 |
TheWardoctor/Wardoctors-repo | script.module.schism.common/lib/requests/structures.py | 5513 | # -*- coding: utf-8 -*-
"""
requests.structures
~~~~~~~~~~~~~~~~~~~
Data structures that power Requests.
"""
import collections
import time
from .compat import OrderedDict
current_time = getattr(time, 'monotonic', time.time)
class CaseInsensitiveDict(collections.MutableMapping):
"""A case-insensitive ``dict``-like object.
Implements all methods and operations of
``collections.MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``iter(instance)``,
``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
will contain case-sensitive keys. However, querying and contains
testing is case insensitive::
cid = CaseInsensitiveDict()
cid['Accept'] = 'application/json'
cid['aCCEPT'] == 'application/json' # True
list(cid) == ['Accept'] # True
For example, ``headers['content-encoding']`` will return the
value of a ``'Content-Encoding'`` response header, regardless
of how the header name was originally stored.
If the constructor, ``.update``, or equality comparison
operations are given keys that have equal ``.lower()``s, the
behavior is undefined.
"""
def __init__(self, data=None, **kwargs):
self._store = OrderedDict()
if data is None:
data = {}
self.update(data, **kwargs)
def __setitem__(self, key, value):
# Use the lowercased key for lookups, but store the actual
# key alongside the value.
self._store[key.lower()] = (key, value)
def __getitem__(self, key):
return self._store[key.lower()][1]
def __delitem__(self, key):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values())
def __len__(self):
return len(self._store)
def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
)
def __eq__(self, other):
if isinstance(other, collections.Mapping):
other = CaseInsensitiveDict(other)
else:
return NotImplemented
# Compare insensitively
return dict(self.lower_items()) == dict(other.lower_items())
# Copy is required
def copy(self):
return CaseInsensitiveDict(self._store.values())
def __repr__(self):
return str(dict(self.items()))
class LookupDict(dict):
"""Dictionary lookup object."""
def __init__(self, name=None):
self.name = name
super(LookupDict, self).__init__()
def __repr__(self):
return '<lookup \'%s\'>' % (self.name)
def __getitem__(self, key):
# We allow fall-through here, so values default to None
return self.__dict__.get(key, None)
def get(self, key, default=None):
return self.__dict__.get(key, default)
class TimedCacheManaged(object):
"""
Wrap a function call in a timed cache
"""
def __init__(self, fnc):
self.fnc = fnc
self.cache = TimedCache()
def __call__(self, *args, **kwargs):
key = args[0]
found = None
try:
found = self.cache[key]
except KeyError:
found = self.fnc(key, **kwargs)
self.cache[key] = found
return found
class TimedCache(collections.MutableMapping):
"""
Evicts entries after expiration_secs. If none are expired and maxlen is hit,
will evict the oldest cached entry
"""
def __init__(self, maxlen=32, expiration_secs=60):
"""
:param maxlen: most number of entries to hold on to
:param expiration_secs: the number of seconds to hold on
to entries
"""
self.maxlen = maxlen
self.expiration_secs = expiration_secs
self._dict = OrderedDict()
def __repr__(self):
return '<TimedCache maxlen:%d len:%d expiration_secs:%d>' % \
(self.maxlen, len(self._dict), self.expiration_secs)
def __iter__(self):
return map(lambda kv: (kv[0], kv[1][1]), self._dict.items()).__iter__()
def __delitem__(self, item):
return self._dict.__delitem__(item)
def __getitem__(self, key):
"""
Look up an item in the cache. If the item
has already expired, it will be invalidated and not returned
:param key: which entry to look up
:return: the value in the cache, or None
"""
occurred, value = self._dict[key]
now = int(current_time())
if now - occurred > self.expiration_secs:
del self._dict[key]
raise KeyError
else:
return value
def __setitem__(self, key, value):
"""
Locates the value at lookup key, if cache is full, will evict the
oldest entry
:param key: the key to search the cache for
:param value: the value to be added to the cache
"""
now = int(current_time())
while len(self._dict) >= self.maxlen:
self._dict.popitem(last=False)
return self._dict.__setitem__(key, (now, value))
def __len__(self):
""":return: the length of the cache"""
return len(self._dict)
def clear(self):
"""Clears the cache"""
return self._dict.clear()
| apache-2.0 |
etirelli/jbpm | jbpm-test-coverage/src/test/java/org/jbpm/test/functional/correlation/StartProcessWithCorrelationKeyNoPersistenceTest.java | 879 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.test.functional.correlation;
public class StartProcessWithCorrelationKeyNoPersistenceTest extends AbstractStartProcessWithCorrelationKeyTest {
public StartProcessWithCorrelationKeyNoPersistenceTest() {
super(false);
}
} | apache-2.0 |
cernops/rally | tests/unit/plugins/common/runners/test_serial.py | 2233 | # Copyright (C) 2014 Yahoo! Inc. All Rights Reserved.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from rally.plugins.common.runners import serial
from tests.unit import fakes
from tests.unit import test
class SerialScenarioRunnerTestCase(test.TestCase):
@mock.patch("rally.task.runner._run_scenario_once")
def test__run_scenario(self, mock__run_scenario_once):
times = 5
result = {"duration": 10, "idle_duration": 0, "error": [],
"scenario_output": {}, "atomic_actions": {}}
mock__run_scenario_once.return_value = result
expected_results = [result for i in range(times)]
runner = serial.SerialScenarioRunner(mock.MagicMock(),
{"times": times})
runner._run_scenario(fakes.FakeScenario, "do_it",
fakes.FakeContext().context, {})
self.assertEqual(len(runner.result_queue), times)
results = list(runner.result_queue)
self.assertEqual(results, expected_results)
def test__run_scenario_aborted(self):
runner = serial.SerialScenarioRunner(mock.MagicMock(),
{"times": 5})
runner.abort()
runner._run_scenario(fakes.FakeScenario, "do_it",
fakes.FakeContext().context, {})
self.assertEqual(len(runner.result_queue), 0)
def test_abort(self):
runner = serial.SerialScenarioRunner(mock.MagicMock(),
{"times": 5})
self.assertFalse(runner.aborted.is_set())
runner.abort()
self.assertTrue(runner.aborted.is_set())
| apache-2.0 |
rzyns/homebrew-cask | Casks/texturepacker.rb | 296 | class Texturepacker < Cask
url 'http://www.codeandweb.com/download/texturepacker/3.3.1/TexturePacker-3.3.1-uni.dmg'
homepage 'http://www.codeandweb.com/texturepacker'
version '3.3.1'
sha256 '00f922d036bd7ec991bbe5ee5fcad1431c3c4884bc2b371fdff92cecdaa11339'
link 'TexturePacker.app'
end
| bsd-2-clause |
tom--/yii2 | tests/framework/console/FakeHelpController.php | 512 | <?php
namespace yiiunit\framework\console;
use yii\console\controllers\HelpController;
class FakeHelpController extends HelpController
{
private static $_actionIndexLastCallParams;
public function actionIndex($command = null)
{
self::$_actionIndexLastCallParams = func_get_args();
}
public static function getActionIndexLastCallParams()
{
$params = self::$_actionIndexLastCallParams;
self::$_actionIndexLastCallParams = null;
return $params;
}
}
| bsd-3-clause |
travis-repos/rubinius | spec/core/hash/trie/delete_spec.rb | 527 | require File.expand_path('../../../../spec_helper', __FILE__)
with_feature :hash_hamt do
describe "Hash::Trie#delete" do
before :each do
@state = Hash::State.new
@trie = Hash::Trie.new @state, 0
@entry = Hash::Item.new :a, 1, @state
@trie.add @entry, :b, :b.hash, 2
end
it "returns nil if the entry is not found" do
@trie.delete(:c, :c.hash).should be_nil
end
it "returns the entry if it is found" do
@trie.delete(:a, :a.hash).should equal(@entry)
end
end
end
| bsd-3-clause |
slawosz/rubinius | mspec/spec/helpers/ducktype_spec.rb | 1073 | require File.dirname(__FILE__) + '/../spec_helper'
require 'mspec/helpers/ducktype'
describe Object, "#responds_to" do
it "returns true for specified symbols" do
obj = mock("obj")
obj.responds_to(:to_flo)
obj.should respond_to(:to_flo)
obj.should respond_to(:to_s)
end
end
describe Object, "#does_not_respond_to" do
it "returns false for specified symbols" do
obj = mock("obj")
obj.does_not_respond_to(:to_s)
obj.should_not respond_to(:to_s)
end
end
describe Object, "#undefine" do
it "undefines the method" do
# cannot use a mock here because of the way RSpec handles method_missing
obj = Object.new
obj.undefine(:to_s)
lambda { obj.send :to_s }.should raise_error(NoMethodError)
end
end
describe Object, "#fake!" do
before :each do
@obj = mock("obj")
end
it "makes the object respond to the message" do
@obj.fake!(:to_flo)
@obj.should respond_to(:to_flo)
end
it "returns the value when the obj is sent the message" do
@obj.fake!(:to_flo, 1.2)
@obj.to_flo.should == 1.2
end
end
| bsd-3-clause |
qizenguf/MLC-STT | src/mem/ruby/structures/CacheMemory.cc | 20345 | /*
* Copyright (c) 1999-2012 Mark D. Hill and David A. Wood
* Copyright (c) 2013 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "mem/ruby/structures/CacheMemory.hh"
#include "base/intmath.hh"
#include "debug/RubyCache.hh"
#include "debug/RubyCacheTrace.hh"
#include "debug/RubyResourceStalls.hh"
#include "debug/RubyStats.hh"
#include "mem/protocol/AccessPermission.hh"
#include "mem/ruby/system/RubySystem.hh"
#include "mem/ruby/system/WeightedLRUPolicy.hh"
using namespace std;
ostream&
operator<<(ostream& out, const CacheMemory& obj)
{
obj.print(out);
out << flush;
return out;
}
CacheMemory *
RubyCacheParams::create()
{
return new CacheMemory(this);
}
CacheMemory::CacheMemory(const Params *p)
: SimObject(p),
dataArray(p->dataArrayBanks, p->dataAccessLatency,
p->start_index_bit, p->ruby_system),
tagArray(p->tagArrayBanks, p->tagAccessLatency,
p->start_index_bit, p->ruby_system)
{
m_cache_size = p->size;
m_cache_assoc = p->assoc;
m_replacementPolicy_ptr = p->replacement_policy;
m_replacementPolicy_ptr->setCache(this);
m_start_index_bit = p->start_index_bit;
m_is_instruction_only_cache = p->is_icache;
m_resource_stalls = p->resourceStalls;
m_block_size = p->block_size; // may be 0 at this point. Updated in init()
}
void
CacheMemory::init()
{
if (m_block_size == 0) {
m_block_size = RubySystem::getBlockSizeBytes();
}
m_cache_num_sets = (m_cache_size / m_cache_assoc) / m_block_size;
assert(m_cache_num_sets > 1);
m_cache_num_set_bits = floorLog2(m_cache_num_sets);
assert(m_cache_num_set_bits > 0);
m_cache.resize(m_cache_num_sets,
std::vector<AbstractCacheEntry*>(m_cache_assoc, nullptr));
}
CacheMemory::~CacheMemory()
{
if (m_replacementPolicy_ptr)
delete m_replacementPolicy_ptr;
for (int i = 0; i < m_cache_num_sets; i++) {
for (int j = 0; j < m_cache_assoc; j++) {
delete m_cache[i][j];
}
}
}
// convert a Address to its location in the cache
int64_t
CacheMemory::addressToCacheSet(Addr address) const
{
assert(address == makeLineAddress(address));
return bitSelect(address, m_start_index_bit,
m_start_index_bit + m_cache_num_set_bits - 1);
}
// Given a cache index: returns the index of the tag in a set.
// returns -1 if the tag is not found.
int
CacheMemory::findTagInSet(int64_t cacheSet, Addr tag) const
{
assert(tag == makeLineAddress(tag));
// search the set for the tags
auto it = m_tag_index.find(tag);
if (it != m_tag_index.end())
if (m_cache[cacheSet][it->second]->m_Permission !=
AccessPermission_NotPresent)
return it->second;
return -1; // Not found
}
// Given a cache index: returns the index of the tag in a set.
// returns -1 if the tag is not found.
int
CacheMemory::findTagInSetIgnorePermissions(int64_t cacheSet,
Addr tag) const
{
assert(tag == makeLineAddress(tag));
// search the set for the tags
auto it = m_tag_index.find(tag);
if (it != m_tag_index.end())
return it->second;
return -1; // Not found
}
// Given an unique cache block identifier (idx): return the valid address
// stored by the cache block. If the block is invalid/notpresent, the
// function returns the 0 address
Addr
CacheMemory::getAddressAtIdx(int idx) const
{
Addr tmp(0);
int set = idx / m_cache_assoc;
assert(set < m_cache_num_sets);
int way = idx - set * m_cache_assoc;
assert (way < m_cache_assoc);
AbstractCacheEntry* entry = m_cache[set][way];
if (entry == NULL ||
entry->m_Permission == AccessPermission_Invalid ||
entry->m_Permission == AccessPermission_NotPresent) {
return tmp;
}
return entry->m_Address;
}
bool
CacheMemory::tryCacheAccess(Addr address, RubyRequestType type,
DataBlock*& data_ptr)
{
assert(address == makeLineAddress(address));
DPRINTF(RubyCache, "address: %#x\n", address);
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
if (loc != -1) {
// Do we even have a tag match?
AbstractCacheEntry* entry = m_cache[cacheSet][loc];
m_replacementPolicy_ptr->touch(cacheSet, loc, curTick());
data_ptr = &(entry->getDataBlk());
if (entry->m_Permission == AccessPermission_Read_Write) {
return true;
}
if ((entry->m_Permission == AccessPermission_Read_Only) &&
(type == RubyRequestType_LD || type == RubyRequestType_IFETCH)) {
return true;
}
// The line must not be accessible
}
data_ptr = NULL;
return false;
}
bool
CacheMemory::testCacheAccess(Addr address, RubyRequestType type,
DataBlock*& data_ptr)
{
assert(address == makeLineAddress(address));
DPRINTF(RubyCache, "address: %#x\n", address);
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
if (loc != -1) {
// Do we even have a tag match?
AbstractCacheEntry* entry = m_cache[cacheSet][loc];
m_replacementPolicy_ptr->touch(cacheSet, loc, curTick());
data_ptr = &(entry->getDataBlk());
return m_cache[cacheSet][loc]->m_Permission !=
AccessPermission_NotPresent;
}
data_ptr = NULL;
return false;
}
// tests to see if an address is present in the cache
bool
CacheMemory::isTagPresent(Addr address) const
{
assert(address == makeLineAddress(address));
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
if (loc == -1) {
// We didn't find the tag
DPRINTF(RubyCache, "No tag match for address: %#x\n", address);
return false;
}
DPRINTF(RubyCache, "address: %#x found\n", address);
return true;
}
// Returns true if there is:
// a) a tag match on this address or there is
// b) an unused line in the same cache "way"
bool
CacheMemory::cacheAvail(Addr address) const
{
assert(address == makeLineAddress(address));
int64_t cacheSet = addressToCacheSet(address);
for (int i = 0; i < m_cache_assoc; i++) {
AbstractCacheEntry* entry = m_cache[cacheSet][i];
if (entry != NULL) {
if (entry->m_Address == address ||
entry->m_Permission == AccessPermission_NotPresent) {
// Already in the cache or we found an empty entry
return true;
}
} else {
return true;
}
}
return false;
}
AbstractCacheEntry*
CacheMemory::allocate(Addr address, AbstractCacheEntry *entry, bool touch)
{
assert(address == makeLineAddress(address));
assert(!isTagPresent(address));
assert(cacheAvail(address));
DPRINTF(RubyCache, "address: %#x\n", address);
// Find the first open slot
int64_t cacheSet = addressToCacheSet(address);
std::vector<AbstractCacheEntry*> &set = m_cache[cacheSet];
for (int i = 0; i < m_cache_assoc; i++) {
if (!set[i] || set[i]->m_Permission == AccessPermission_NotPresent) {
if (set[i] && (set[i] != entry)) {
warn_once("This protocol contains a cache entry handling bug: "
"Entries in the cache should never be NotPresent! If\n"
"this entry (%#x) is not tracked elsewhere, it will memory "
"leak here. Fix your protocol to eliminate these!",
address);
}
set[i] = entry; // Init entry
set[i]->m_Address = address;
set[i]->m_Permission = AccessPermission_Invalid;
DPRINTF(RubyCache, "Allocate clearing lock for addr: %x\n",
address);
set[i]->m_locked = -1;
m_tag_index[address] = i;
entry->setSetIndex(cacheSet);
entry->setWayIndex(i);
if (touch) {
m_replacementPolicy_ptr->touch(cacheSet, i, curTick());
}
return entry;
}
}
panic("Allocate didn't find an available entry");
}
void
CacheMemory::deallocate(Addr address)
{
assert(address == makeLineAddress(address));
assert(isTagPresent(address));
DPRINTF(RubyCache, "address: %#x\n", address);
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
if (loc != -1) {
delete m_cache[cacheSet][loc];
m_cache[cacheSet][loc] = NULL;
m_tag_index.erase(address);
}
}
// Returns with the physical address of the conflicting cache line
Addr
CacheMemory::cacheProbe(Addr address) const
{
assert(address == makeLineAddress(address));
assert(!cacheAvail(address));
int64_t cacheSet = addressToCacheSet(address);
return m_cache[cacheSet][m_replacementPolicy_ptr->getVictim(cacheSet)]->
m_Address;
}
// looks an address up in the cache
AbstractCacheEntry*
CacheMemory::lookup(Addr address)
{
assert(address == makeLineAddress(address));
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
if (loc == -1) return NULL;
return m_cache[cacheSet][loc];
}
// looks an address up in the cache
const AbstractCacheEntry*
CacheMemory::lookup(Addr address) const
{
assert(address == makeLineAddress(address));
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
if (loc == -1) return NULL;
return m_cache[cacheSet][loc];
}
// Sets the most recently used bit for a cache block
void
CacheMemory::setMRU(Addr address)
{
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
if (loc != -1)
m_replacementPolicy_ptr->touch(cacheSet, loc, curTick());
}
void
CacheMemory::setMRU(const AbstractCacheEntry *e)
{
uint32_t cacheSet = e->getSetIndex();
uint32_t loc = e->getWayIndex();
m_replacementPolicy_ptr->touch(cacheSet, loc, curTick());
}
void
CacheMemory::setMRU(Addr address, int occupancy)
{
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
if (loc != -1) {
if (m_replacementPolicy_ptr->useOccupancy()) {
(static_cast<WeightedLRUPolicy*>(m_replacementPolicy_ptr))->
touch(cacheSet, loc, curTick(), occupancy);
} else {
m_replacementPolicy_ptr->
touch(cacheSet, loc, curTick());
}
}
}
int
CacheMemory::getReplacementWeight(int64_t set, int64_t loc)
{
assert(set < m_cache_num_sets);
assert(loc < m_cache_assoc);
int ret = 0;
if (m_cache[set][loc] != NULL) {
ret = m_cache[set][loc]->getNumValidBlocks();
assert(ret >= 0);
}
return ret;
}
void
CacheMemory::recordCacheContents(int cntrl, CacheRecorder* tr) const
{
uint64_t warmedUpBlocks = 0;
uint64_t totalBlocks M5_VAR_USED = (uint64_t)m_cache_num_sets *
(uint64_t)m_cache_assoc;
for (int i = 0; i < m_cache_num_sets; i++) {
for (int j = 0; j < m_cache_assoc; j++) {
if (m_cache[i][j] != NULL) {
AccessPermission perm = m_cache[i][j]->m_Permission;
RubyRequestType request_type = RubyRequestType_NULL;
if (perm == AccessPermission_Read_Only) {
if (m_is_instruction_only_cache) {
request_type = RubyRequestType_IFETCH;
} else {
request_type = RubyRequestType_LD;
}
} else if (perm == AccessPermission_Read_Write) {
request_type = RubyRequestType_ST;
}
if (request_type != RubyRequestType_NULL) {
tr->addRecord(cntrl, m_cache[i][j]->m_Address,
0, request_type,
m_replacementPolicy_ptr->getLastAccess(i, j),
m_cache[i][j]->getDataBlk());
warmedUpBlocks++;
}
}
}
}
DPRINTF(RubyCacheTrace, "%s: %lli blocks of %lli total blocks"
"recorded %.2f%% \n", name().c_str(), warmedUpBlocks,
totalBlocks, (float(warmedUpBlocks) / float(totalBlocks)) * 100.0);
}
void
CacheMemory::print(ostream& out) const
{
out << "Cache dump: " << name() << endl;
for (int i = 0; i < m_cache_num_sets; i++) {
for (int j = 0; j < m_cache_assoc; j++) {
if (m_cache[i][j] != NULL) {
out << " Index: " << i
<< " way: " << j
<< " entry: " << *m_cache[i][j] << endl;
} else {
out << " Index: " << i
<< " way: " << j
<< " entry: NULL" << endl;
}
}
}
}
void
CacheMemory::printData(ostream& out) const
{
out << "printData() not supported" << endl;
}
void
CacheMemory::setLocked(Addr address, int context)
{
DPRINTF(RubyCache, "Setting Lock for addr: %#x to %d\n", address, context);
assert(address == makeLineAddress(address));
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
assert(loc != -1);
m_cache[cacheSet][loc]->setLocked(context);
}
void
CacheMemory::clearLocked(Addr address)
{
DPRINTF(RubyCache, "Clear Lock for addr: %#x\n", address);
assert(address == makeLineAddress(address));
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
assert(loc != -1);
m_cache[cacheSet][loc]->clearLocked();
}
bool
CacheMemory::isLocked(Addr address, int context)
{
assert(address == makeLineAddress(address));
int64_t cacheSet = addressToCacheSet(address);
int loc = findTagInSet(cacheSet, address);
assert(loc != -1);
DPRINTF(RubyCache, "Testing Lock for addr: %#llx cur %d con %d\n",
address, m_cache[cacheSet][loc]->m_locked, context);
return m_cache[cacheSet][loc]->isLocked(context);
}
void
CacheMemory::regStats()
{
SimObject::regStats();
m_demand_hits
.name(name() + ".demand_hits")
.desc("Number of cache demand hits")
;
m_demand_misses
.name(name() + ".demand_misses")
.desc("Number of cache demand misses")
;
m_demand_accesses
.name(name() + ".demand_accesses")
.desc("Number of cache demand accesses")
;
m_demand_accesses = m_demand_hits + m_demand_misses;
m_sw_prefetches
.name(name() + ".total_sw_prefetches")
.desc("Number of software prefetches")
.flags(Stats::nozero)
;
m_hw_prefetches
.name(name() + ".total_hw_prefetches")
.desc("Number of hardware prefetches")
.flags(Stats::nozero)
;
m_prefetches
.name(name() + ".total_prefetches")
.desc("Number of prefetches")
.flags(Stats::nozero)
;
m_prefetches = m_sw_prefetches + m_hw_prefetches;
m_accessModeType
.init(RubyRequestType_NUM)
.name(name() + ".access_mode")
.flags(Stats::pdf | Stats::total)
;
for (int i = 0; i < RubyAccessMode_NUM; i++) {
m_accessModeType
.subname(i, RubyAccessMode_to_string(RubyAccessMode(i)))
.flags(Stats::nozero)
;
}
numDataArrayReads
.name(name() + ".num_data_array_reads")
.desc("number of data array reads")
.flags(Stats::nozero)
;
numDataArrayWrites
.name(name() + ".num_data_array_writes")
.desc("number of data array writes")
.flags(Stats::nozero)
;
numTagArrayReads
.name(name() + ".num_tag_array_reads")
.desc("number of tag array reads")
.flags(Stats::nozero)
;
numTagArrayWrites
.name(name() + ".num_tag_array_writes")
.desc("number of tag array writes")
.flags(Stats::nozero)
;
numTagArrayStalls
.name(name() + ".num_tag_array_stalls")
.desc("number of stalls caused by tag array")
.flags(Stats::nozero)
;
numDataArrayStalls
.name(name() + ".num_data_array_stalls")
.desc("number of stalls caused by data array")
.flags(Stats::nozero)
;
}
// assumption: SLICC generated files will only call this function
// once **all** resources are granted
void
CacheMemory::recordRequestType(CacheRequestType requestType, Addr addr)
{
DPRINTF(RubyStats, "Recorded statistic: %s\n",
CacheRequestType_to_string(requestType));
switch(requestType) {
case CacheRequestType_DataArrayRead:
if (m_resource_stalls)
dataArray.reserve(addressToCacheSet(addr));
numDataArrayReads++;
return;
case CacheRequestType_DataArrayWrite:
if (m_resource_stalls)
dataArray.reserve(addressToCacheSet(addr));
numDataArrayWrites++;
return;
case CacheRequestType_TagArrayRead:
if (m_resource_stalls)
tagArray.reserve(addressToCacheSet(addr));
numTagArrayReads++;
return;
case CacheRequestType_TagArrayWrite:
if (m_resource_stalls)
tagArray.reserve(addressToCacheSet(addr));
numTagArrayWrites++;
return;
default:
warn("CacheMemory access_type not found: %s",
CacheRequestType_to_string(requestType));
}
}
bool
CacheMemory::checkResourceAvailable(CacheResourceType res, Addr addr)
{
if (!m_resource_stalls) {
return true;
}
if (res == CacheResourceType_TagArray) {
if (tagArray.tryAccess(addressToCacheSet(addr))) return true;
else {
DPRINTF(RubyResourceStalls,
"Tag array stall on addr %#x in set %d\n",
addr, addressToCacheSet(addr));
numTagArrayStalls++;
return false;
}
} else if (res == CacheResourceType_DataArray) {
if (dataArray.tryAccess(addressToCacheSet(addr))) return true;
else {
DPRINTF(RubyResourceStalls,
"Data array stall on addr %#x in set %d\n",
addr, addressToCacheSet(addr));
numDataArrayStalls++;
return false;
}
} else {
assert(false);
return true;
}
}
bool
CacheMemory::isBlockInvalid(int64_t cache_set, int64_t loc)
{
return (m_cache[cache_set][loc]->m_Permission == AccessPermission_Invalid);
}
bool
CacheMemory::isBlockNotBusy(int64_t cache_set, int64_t loc)
{
return (m_cache[cache_set][loc]->m_Permission != AccessPermission_Busy);
}
| bsd-3-clause |
reinout/django | django/contrib/gis/forms/widgets.py | 3405 | import logging
from django.conf import settings
from django.contrib.gis import gdal
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.forms.widgets import Widget
from django.utils import translation
logger = logging.getLogger('django.contrib.gis')
class BaseGeometryWidget(Widget):
"""
The base class for rich geometry widgets.
Render a map using the WKT of the geometry.
"""
geom_type = 'GEOMETRY'
map_srid = 4326
map_width = 600
map_height = 400
display_raw = False
supports_3d = False
template_name = '' # set on subclasses
def __init__(self, attrs=None):
self.attrs = {}
for key in ('geom_type', 'map_srid', 'map_width', 'map_height', 'display_raw'):
self.attrs[key] = getattr(self, key)
if attrs:
self.attrs.update(attrs)
def serialize(self, value):
return value.wkt if value else ''
def deserialize(self, value):
try:
return GEOSGeometry(value)
except (GEOSException, ValueError) as err:
logger.error("Error creating geometry from value '%s' (%s)", value, err)
return None
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
# If a string reaches here (via a validation error on another
# field) then just reconstruct the Geometry.
if value and isinstance(value, str):
value = self.deserialize(value)
if value:
# Check that srid of value and map match
if value.srid and value.srid != self.map_srid:
try:
ogr = value.ogr
ogr.transform(self.map_srid)
value = ogr
except gdal.GDALException as err:
logger.error(
"Error transforming geometry from srid '%s' to srid '%s' (%s)",
value.srid, self.map_srid, err
)
context.update(self.build_attrs(self.attrs, {
'name': name,
'module': 'geodjango_%s' % name.replace('-', '_'), # JS-safe
'serialized': self.serialize(value),
'geom_type': gdal.OGRGeomType(self.attrs['geom_type']),
'STATIC_URL': settings.STATIC_URL,
'LANGUAGE_BIDI': translation.get_language_bidi(),
**(attrs or {}),
}))
return context
class OpenLayersWidget(BaseGeometryWidget):
template_name = 'gis/openlayers.html'
map_srid = 3857
class Media:
css = {
'all': (
'https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.css',
'gis/css/ol3.css',
)
}
js = (
'https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.js',
'gis/js/OLMapWidget.js',
)
def serialize(self, value):
return value.json if value else ''
class OSMWidget(OpenLayersWidget):
"""
An OpenLayers/OpenStreetMap-based widget.
"""
template_name = 'gis/openlayers-osm.html'
default_lon = 5
default_lat = 47
default_zoom = 12
def __init__(self, attrs=None):
super().__init__()
for key in ('default_lon', 'default_lat', 'default_zoom'):
self.attrs[key] = getattr(self, key)
if attrs:
self.attrs.update(attrs)
| bsd-3-clause |
printedheart/vowpal_wabbit | vowpalwabbit/loss_functions.cc | 9419 | /*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include<math.h>
#include<iostream>
#include<stdlib.h>
#include<float.h>
using namespace std;
#include "global_data.h"
#include "vw_exception.h"
class squaredloss : public loss_function {
public:
squaredloss() {
}
float getLoss(shared_data* sd, float prediction, float label) {
if (prediction <= sd->max_label && prediction >= sd->min_label)
{
float example_loss = (prediction - label) * (prediction - label);
return example_loss;
}
else if (prediction < sd->min_label)
if (label == sd->min_label)
return 0.;
else
return (float) ((label - sd->min_label) * (label - sd->min_label)
+ 2. * (label-sd->min_label) * (sd->min_label - prediction));
else if (label == sd->max_label)
return 0.;
else
return float((sd->max_label - label) * (sd->max_label - label)
+ 2. * (sd->max_label - label) * (prediction - sd->max_label));
}
float getUpdate(float prediction, float label, float eta_t, float pred_per_update)
{
if (eta_t < 1e-6) {
/* When exp(-eta_t)~= 1 we replace 1-exp(-eta_t)
* with its first order Taylor expansion around 0
* to avoid catastrophic cancellation.
*/
return 2.f*(label - prediction)*eta_t/pred_per_update;
}
return (label - prediction)*(1.f-exp(-2.f*eta_t))/pred_per_update;
}
float getUnsafeUpdate(float prediction, float label, float eta_t, float pred_per_update) {
return 2.f*(label - prediction)*eta_t/pred_per_update;
}
float getRevertingWeight(shared_data* sd, float prediction, float eta_t) {
float t = 0.5f*(sd->min_label+sd->max_label);
float alternative = (prediction > t) ? sd->min_label : sd->max_label;
return log((alternative-prediction)/(alternative-t))/eta_t;
}
float getSquareGrad(float prediction, float label) {
return 4.f*(prediction - label) * (prediction - label);
}
float first_derivative(shared_data* sd, float prediction, float label)
{
if (prediction < sd->min_label)
prediction = sd->min_label;
else if (prediction > sd->max_label)
prediction = sd->max_label;
return 2.f * (prediction-label);
}
float second_derivative(shared_data* sd, float prediction, float)
{
if (prediction <= sd->max_label && prediction >= sd->min_label)
return 2.;
else
return 0.;
}
};
class classic_squaredloss : public loss_function {
public:
classic_squaredloss() {
}
float getLoss(shared_data*, float prediction, float label) {
float example_loss = (prediction - label) * (prediction - label);
return example_loss;
}
float getUpdate(float prediction, float label,float eta_t, float pred_per_update) {
return 2.f*eta_t*(label - prediction)/pred_per_update;
}
float getUnsafeUpdate(float prediction, float label,float eta_t,float pred_per_update) {
return 2.f*eta_t*(label - prediction)/pred_per_update;
}
float getRevertingWeight(shared_data* sd, float prediction, float eta_t) {
float t = 0.5f*(sd->min_label+sd->max_label);
float alternative = (prediction > t) ? sd->min_label : sd->max_label;
return (t-prediction)/((alternative-prediction)*eta_t);
}
float getSquareGrad(float prediction, float label) {
return 4.f * (prediction - label) * (prediction - label);
}
float first_derivative(shared_data*, float prediction, float label)
{
return 2.f * (prediction-label);
}
float second_derivative(shared_data*, float, float)
{
return 2.;
}
};
class hingeloss : public loss_function {
public:
hingeloss() {
}
float getLoss(shared_data*, float prediction, float label) {
if (label != -1.f && label != 1.f)
cout << "You are using label " << label << " not -1 or 1 as loss function expects!" << endl;
float e = 1 - label*prediction;
return (e > 0) ? e : 0;
}
float getUpdate(float prediction, float label,float eta_t, float pred_per_update) {
if(label*prediction >= 1) return 0;
float err = 1 - label*prediction;
return label * (eta_t < err ? eta_t : err)/pred_per_update;
}
float getUnsafeUpdate(float prediction, float label,float eta_t, float pred_per_update) {
if(label*prediction >= 1) return 0;
return label * eta_t/pred_per_update;
}
float getRevertingWeight(shared_data*, float prediction, float eta_t) {
return fabs(prediction)/eta_t;
}
float getSquareGrad(float prediction, float label) {
float d = first_derivative(nullptr, prediction,label);
return d*d;
}
float first_derivative(shared_data*, float prediction, float label)
{
return (label*prediction >= 1) ? 0 : -label;
}
float second_derivative(shared_data*, float, float)
{
return 0.;
}
};
class logloss : public loss_function {
public:
logloss() {
}
float getLoss(shared_data*, float prediction, float label) {
if (label != -1.f && label != 1.f)
cout << "You are using label " << label << " not -1 or 1 as loss function expects!" << endl;
return log(1 + exp(-label * prediction));
}
float getUpdate(float prediction, float label, float eta_t, float pred_per_update) {
float w,x;
float d = exp(label * prediction);
if(eta_t < 1e-6) {
/* As with squared loss, for small eta_t we replace the update
* with its first order Taylor expansion to avoid numerical problems
*/
return label*eta_t/((1+d)*pred_per_update);
}
x = eta_t + label*prediction + d;
w = wexpmx(x);
return -(label*w+prediction)/pred_per_update;
}
float getUnsafeUpdate(float prediction, float label, float eta_t, float pred_per_update) {
float d = exp(label * prediction);
return label*eta_t/((1+d)*pred_per_update);
}
inline float wexpmx(float x) {
/* This piece of code is approximating W(exp(x))-x.
* W is the Lambert W function: W(z)*exp(W(z))=z.
* The absolute error of this approximation is less than 9e-5.
* Faster/better approximations can be substituted here.
*/
double w = x>=1. ? 0.86*x+0.01 : exp(0.8*x-0.65); //initial guess
double r = x>=1. ? x-log(w)-w : 0.2*x+0.65-w; //residual
double t = 1.+w;
double u = 2.*t*(t+2.*r/3.); //magic
return (float)(w*(1.+r/t*(u-r)/(u-2.*r))-x); //more magic
}
float getRevertingWeight(shared_data*, float prediction, float eta_t) {
float z = -fabs(prediction);
return (1-z-exp(z))/eta_t;
}
float first_derivative(shared_data*, float prediction, float label)
{
float v = - label/(1+exp(label * prediction));
return v;
}
float getSquareGrad(float prediction, float label) {
float d = first_derivative(nullptr, prediction,label);
return d*d;
}
float second_derivative(shared_data*, float prediction, float label)
{
float p = 1 / (1+exp(label*prediction));
return p*(1-p);
}
};
class quantileloss : public loss_function {
public:
quantileloss(float &tau_) : tau(tau_) {
}
float getLoss(shared_data*, float prediction, float label) {
float e = label - prediction;
if(e > 0) {
return tau * e;
} else {
return -(1 - tau) * e;
}
}
float getUpdate(float prediction, float label, float eta_t, float pred_per_update) {
float err = label - prediction;
if(err == 0) return 0;
float normal = eta_t;//base update size
if(err > 0) {
normal = tau*normal;
return (normal < err ? normal : err) / pred_per_update;
} else {
normal = -(1-tau) * normal;
return ( normal > err ? normal : err) / pred_per_update;
}
}
float getUnsafeUpdate(float prediction, float label, float eta_t, float pred_per_update) {
float err = label - prediction;
if(err == 0) return 0;
if(err > 0) return tau*eta_t/pred_per_update;
return -(1-tau)*eta_t/pred_per_update;
}
float getRevertingWeight(shared_data* sd, float prediction, float eta_t) {
float v,t;
t = 0.5f*(sd->min_label+ sd->max_label);
if(prediction > t)
v = -(1-tau);
else
v = tau;
return (t - prediction)/(eta_t*v);
}
float first_derivative(shared_data*, float prediction, float label)
{
float e = label - prediction;
if(e == 0) return 0;
return e > 0 ? -tau : (1-tau);
}
float getSquareGrad(float prediction, float label) {
float fd = first_derivative(nullptr, prediction,label);
return fd*fd;
}
float second_derivative(shared_data*, float, float)
{
return 0.;
}
float tau;
};
loss_function* getLossFunction(vw& all, string funcName, float function_parameter) {
if(funcName.compare("squared") == 0 || funcName.compare("Huber") == 0)
return new squaredloss();
else if(funcName.compare("classic") == 0)
return new classic_squaredloss();
else if(funcName.compare("hinge") == 0)
return new hingeloss();
else if(funcName.compare("logistic") == 0) {
if (all.set_minmax != noop_mm)
{
all.sd->min_label = -50;
all.sd->max_label = 50;
}
return new logloss();
} else if(funcName.compare("quantile") == 0 || funcName.compare("pinball") == 0 || funcName.compare("absolute") == 0) {
return new quantileloss(function_parameter);
} else
THROW("Invalid loss function name: \'" << funcName << "\' Bailing!");
}
| bsd-3-clause |
kf6kjg/halcyon | ThirdParty/libopenmetaverse/CSJ2K/Icc/ICCMonochromeInputProfile.cs | 1728 | /// <summary>**************************************************************************
///
/// $Id: ICCMonochromeInputProfile.java,v 1.1 2002/07/25 14:56:54 grosbois Exp $
///
/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650
/// $Date $
/// ***************************************************************************
/// </summary>
using System;
using ColorSpace = CSJ2K.Color.ColorSpace;
using ColorSpaceException = CSJ2K.Color.ColorSpaceException;
using RandomAccessIO = CSJ2K.j2k.io.RandomAccessIO;
namespace CSJ2K.Icc
{
/// <summary> The monochrome ICCProfile.
///
/// </summary>
/// <version> 1.0
/// </version>
/// <author> Bruce A. Kern
/// </author>
public class ICCMonochromeInputProfile:ICCProfile
{
/// <summary> Return the ICCProfile embedded in the input image</summary>
/// <param name="in">jp2 image with embedded profile
/// </param>
/// <returns> ICCMonochromeInputProfile
/// </returns>
/// <exception cref="ColorSpaceICCProfileInvalidExceptionException">
/// </exception>
/// <exception cref="">
/// </exception>
public static ICCMonochromeInputProfile createInstance(ColorSpace csm)
{
return new ICCMonochromeInputProfile(csm);
}
/// <summary> Construct a ICCMonochromeInputProfile corresponding to the profile file</summary>
/// <param name="f">disk based ICCMonochromeInputProfile
/// </param>
/// <returns> theICCMonochromeInputProfile
/// </returns>
/// <exception cref="ColorSpaceException">
/// </exception>
/// <exception cref="ICCProfileInvalidException">
/// </exception>
protected internal ICCMonochromeInputProfile(ColorSpace csm):base(csm)
{
}
/* end class ICCMonochromeInputProfile */
}
} | bsd-3-clause |
tefasmile/Mi_Blog | node_modules/knex/lib/dialects/oracle/schema/schema.js | 2657 | 'use strict';
// Oracle Schema Builder & Compiler
// -------
module.exports = function(client) {
var inherits = require('inherits');
var Schema = require('../../../schema');
var utils = require('../utils');
// Schema Builder
// -------
function SchemaBuilder_Oracle() {
this.client = client;
Schema.Builder.apply(this, arguments);
}
inherits(SchemaBuilder_Oracle, Schema.Builder);
// Schema Compiler
// -------
function SchemaCompiler_Oracle() {
this.client = client;
this.Formatter = client.Formatter;
Schema.Compiler.apply(this, arguments);
}
inherits(SchemaCompiler_Oracle, Schema.Compiler);
// Rename a table on the schema.
SchemaCompiler_Oracle.prototype.renameTable = function(tableName, to) {
this.pushQuery('rename ' + this.formatter.wrap(tableName) + ' to ' + this.formatter.wrap(to));
};
// Check whether a table exists on the query.
SchemaCompiler_Oracle.prototype.hasTable = function(tableName) {
this.pushQuery({
sql: 'select TABLE_NAME from USER_TABLES where TABLE_NAME = ' +
this.formatter.parameter(tableName),
output: function(resp) {
return resp.length > 0;
}
});
};
// Check whether a column exists on the schema.
SchemaCompiler_Oracle.prototype.hasColumn = function(tableName, column) {
this.pushQuery({
sql: 'select COLUMN_NAME from USER_TAB_COLUMNS where TABLE_NAME = ' + this.formatter.parameter(tableName) +
' and COLUMN_NAME = ' + this.formatter.parameter(column),
output: function(resp) {
return resp.length > 0;
}
});
};
SchemaCompiler_Oracle.prototype.dropSequenceIfExists = function (sequenceName) {
this.pushQuery(utils.wrapSqlWithCatch("drop sequence " + this.formatter.wrap(sequenceName), -2289));
};
SchemaCompiler_Oracle.prototype._dropRelatedSequenceIfExists = function (tableName) {
// removing the sequence that was possibly generated by increments() column
var sequenceName = utils.generateCombinedName('seq', tableName);
this.dropSequenceIfExists(sequenceName);
};
SchemaCompiler_Oracle.prototype.dropTable = function (tableName) {
this.pushQuery('drop table ' + this.formatter.wrap(tableName));
// removing the sequence that was possibly generated by increments() column
this._dropRelatedSequenceIfExists(tableName);
};
SchemaCompiler_Oracle.prototype.dropTableIfExists = function(tableName) {
this.pushQuery(utils.wrapSqlWithCatch("drop table " + this.formatter.wrap(tableName), -942));
// removing the sequence that was possibly generated by increments() column
this._dropRelatedSequenceIfExists(tableName);
};
client.SchemaBuilder = SchemaBuilder_Oracle;
client.SchemaCompiler = SchemaCompiler_Oracle;
}; | mit |
andre77/XChange | xchange-bleutrade/src/main/java/org/knowm/xchange/bleutrade/BleutradeException.java | 2065 | package org.knowm.xchange.bleutrade;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({"success", "message", "result"})
public class BleutradeException extends RuntimeException {
private static final long serialVersionUID = 6065661242182530213L;
@JsonProperty("success")
private String success;
@JsonProperty("message")
private String message;
@JsonProperty("result")
private List<Object> result = new ArrayList<Object>();
@JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/** @return The success */
@JsonProperty("success")
public String getSuccess() {
return success;
}
/** @param success The success */
@JsonProperty("success")
public void setSuccess(String success) {
this.success = success;
}
/** @return The message */
@JsonProperty("message")
public String getMessage() {
return message;
}
/** @param message The message */
@JsonProperty("message")
public void setMessage(String message) {
this.message = message;
}
/** @return The result */
@JsonProperty("result")
public List<Object> getResult() {
return result;
}
/** @param result The result */
@JsonProperty("result")
public void setResult(List<Object> result) {
this.result = result;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| mit |
ayeletshpigelman/azure-sdk-for-net | sdk/storsimple/Microsoft.Azure.Management.StorSimple/src/Generated/Models/StorageDomain.cs | 3711 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.StorSimple1200Series.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The storage domain.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class StorageDomain : BaseModel
{
/// <summary>
/// Initializes a new instance of the StorageDomain class.
/// </summary>
public StorageDomain()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the StorageDomain class.
/// </summary>
/// <param name="storageAccountCredentialIds">The storage account
/// credentials.</param>
/// <param name="encryptionStatus">The encryption status "Enabled |
/// Disabled". Possible values include: 'Enabled', 'Disabled'</param>
/// <param name="id">The identifier.</param>
/// <param name="name">The name.</param>
/// <param name="type">The type.</param>
/// <param name="encryptionKey">The encryption key used to encrypt the
/// data. This is a user secret.</param>
public StorageDomain(IList<string> storageAccountCredentialIds, EncryptionStatus encryptionStatus, string id = default(string), string name = default(string), string type = default(string), AsymmetricEncryptedSecret encryptionKey = default(AsymmetricEncryptedSecret))
: base(id, name, type)
{
StorageAccountCredentialIds = storageAccountCredentialIds;
EncryptionKey = encryptionKey;
EncryptionStatus = encryptionStatus;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the storage account credentials.
/// </summary>
[JsonProperty(PropertyName = "properties.storageAccountCredentialIds")]
public IList<string> StorageAccountCredentialIds { get; set; }
/// <summary>
/// Gets or sets the encryption key used to encrypt the data. This is a
/// user secret.
/// </summary>
[JsonProperty(PropertyName = "properties.encryptionKey")]
public AsymmetricEncryptedSecret EncryptionKey { get; set; }
/// <summary>
/// Gets or sets the encryption status "Enabled | Disabled". Possible
/// values include: 'Enabled', 'Disabled'
/// </summary>
[JsonProperty(PropertyName = "properties.encryptionStatus")]
public EncryptionStatus EncryptionStatus { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (StorageAccountCredentialIds == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "StorageAccountCredentialIds");
}
if (EncryptionKey != null)
{
EncryptionKey.Validate();
}
}
}
}
| mit |
felipedaragon/sailor | src/sailor/blank-app/tests/helper.lua | 167 | -- Test helper module
-- This module contains functions to be shared with among tests
local helper = {}
function helper.example()
-- do something
end
return helper | mit |
venyii/Sylius | src/Sylius/Bundle/ThemeBundle/HierarchyProvider/NoopThemeHierarchyProvider.php | 583 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ThemeBundle\HierarchyProvider;
use Sylius\Bundle\ThemeBundle\Model\ThemeInterface;
final class NoopThemeHierarchyProvider implements ThemeHierarchyProviderInterface
{
/**
* {@inheritdoc}
*/
public function getThemeHierarchy(ThemeInterface $theme): array
{
return [$theme];
}
}
| mit |
umbraco/Umbraco-CMS | src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js | 11794 | (function () {
//JavaScript extension methods on the core JavaScript objects (like String, Date, etc...)
if (!Date.prototype.toIsoDateTimeString) {
/** Converts a Date object to a globally acceptable ISO string, NOTE: This is different from the built in
JavaScript toISOString method which returns date/time like "2013-08-07T02:04:11.487Z" but we want "yyyy-MM-dd HH:mm:ss" */
Date.prototype.toIsoDateTimeString = function (str) {
var month = (this.getMonth() + 1).toString();
if (month.length === 1) {
month = "0" + month;
}
var day = this.getDate().toString();
if (day.length === 1) {
day = "0" + day;
}
var hour = this.getHours().toString();
if (hour.length === 1) {
hour = "0" + hour;
}
var mins = this.getMinutes().toString();
if (mins.length === 1) {
mins = "0" + mins;
}
var secs = this.getSeconds().toString();
if (secs.length === 1) {
secs = "0" + secs;
}
return this.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + mins + ":" + secs;
};
}
if (!Date.prototype.toIsoDateString) {
/** Converts a Date object to a globally acceptable ISO string, NOTE: This is different from the built in
JavaScript toISOString method which returns date/time like "2013-08-07T02:04:11.487Z" but we want "yyyy-MM-dd" */
Date.prototype.toIsoDateString = function (str) {
var month = (this.getMonth() + 1).toString();
if (month.length === 1) {
month = "0" + month;
}
var day = this.getDate().toString();
if (day.length === 1) {
day = "0" + day;
}
return this.getFullYear() + "-" + month + "-" + day;
};
}
//create guid method on the String
if (String.CreateGuid == null) {
/** generates a new Guid */
String.CreateGuid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
}
if (!window.__debug__) {
/** global method to send debug statements to console that is cross browser (or at least checks if its possible)*/
window.__debug__ = function (msg, category, isErr) {
if (((typeof console) != "undefined") && console.log && console.error) {
if (isErr) console.error(category + ": " + msg);
else console.log(category + ": " + msg);
}
};
}
if (!String.prototype.trimStartSpecial) {
/** trimSpecial extension method for string */
// Removes all non printable chars from beginning of a string
String.prototype.trimStartSpecial = function () {
var index = 0;
while (this.charCodeAt(index) <= 46) {
index++;
}
return this.substr(index);
};
}
if (!String.prototype.startsWith) {
/** startsWith extension method for string */
String.prototype.startsWith = function (str) {
return this.substr(0, str.length) === str;
};
}
if (!String.prototype.endsWith) {
/** endsWith extension method for string*/
String.prototype.endsWith = function (str) {
return this.substr(this.length - str.length) === str;
};
}
/** trims the start of the string*/
String.prototype.trimStart = function (str) {
if (this.startsWith(str)) {
return this.substring(str.length);
}
return this;
};
/** trims the end of the string*/
String.prototype.trimEnd = function (str) {
if (this.endsWith(str)) {
return this.substring(0, this.length - str.length);
}
return this;
};
if (!String.prototype.utf8Encode) {
/** UTF8 encoder for string*/
String.prototype.utf8Encode = function () {
var str = this.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < str.length; n++) {
var c = str.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
}
if (!String.prototype.utf8Decode) {
/** UTF8 decoder for string*/
String.prototype.utf8Decode = function () {
var utftext = this;
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
};
}
if (!String.prototype.base64Encode) {
/** Base64 encoder for string*/
String.prototype.base64Encode = function () {
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
var input = this.utf8Encode();
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
return output;
};
}
if (!String.prototype.base64Decode) {
/** Base64 decoder for string*/
String.prototype.base64Decode = function () {
var input = this;
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
return output.utf8Decode();
};
}
if (!Math.randomRange) {
/** randomRange extension for math*/
Math.randomRange = function (from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
};
}
if (!String.prototype.toCamelCase) {
/** toCamelCase extension method for string*/
String.prototype.toCamelCase = function () {
var s = this.toPascalCase();
if ($.trim(s) == "")
return "";
if (s.length > 1) {
var regex = /^([A-Z]*)([A-Z].*)/g;
if (s.match(regex)) {
var match = regex.exec(s);
s = match[1].toLowerCase() + match[2];
s = s.substr(0, 1).toLowerCase() + s.substr(1);
}
} else {
s = s.toLowerCase();
}
return s;
};
}
if (!String.prototype.toPascalCase) {
/** toPascalCase extension method for string*/
String.prototype.toPascalCase = function () {
var s = "";
$.each($.trim(this).split(/[\s\.-]+/g), function (idx, val) {
if ($.trim(val) == "")
return;
if (val.length > 1)
s += val.substr(0, 1).toUpperCase() + val.substr(1);
else
s += val.toUpperCase();
});
return s;
};
}
if (!String.prototype.toUmbracoAlias) {
/** toUmbracoAlias extension method for string*/
String.prototype.toUmbracoAlias = function () {
var s = this.replace(/[^a-zA-Z0-9\s\.-]+/g, ''); // Strip none alphanumeric chars
return s.toCamelCase(); // Convert to camelCase
};
}
if (!String.prototype.toFunction) {
/** Converts a string into a function if it is found */
String.prototype.toFunction = function () {
var arr = this.split(".");
var fn = (window || this);
for (var i = 0, len = arr.length; i < len; i++) {
fn = fn[arr[i]];
}
if (typeof fn !== "function") {
throw new Error("function not found");
}
return fn;
};
}
if (!String.prototype.detectIsJson) {
/** Rudimentary check to see if the string is a json encoded string */
String.prototype.detectIsJson = function () {
if ((this.startsWith("{") && this.endsWith("}")) || (this.startsWith("[") || this.endsWith("]"))) {
return true;
}
return false;
};
}
if (!Object.toBoolean) {
/** Converts a string/integer/bool to true/false */
Object.toBoolean = function (obj) {
if (obj === undefined || obj === null) {
return false;
}
if ((typeof obj) === "boolean") {
return obj;
}
if (obj === "1" || obj === 1 || obj.toString().toLowerCase() === "true") {
return true;
}
return false;
};
}
})();
| mit |
Vegetam/BootstrapPageGenerator | ckeditor/plugins/about/lang/gl.js | 478 | /*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'about', 'gl', {
copy: 'Copyright © $1. Todos os dereitos reservados.',
dlgTitle: 'Sobre o CKEditor',
help: 'Consulte $1 para obter axuda.',
moreInfo: 'Para obter información sobre a licenza, visite o noso sitio web:',
title: 'Sobre o CKEditor',
userGuide: 'Guía do usuario do CKEditor'
} );
| mit |
dsebastien/DefinitelyTyped | types/vxna__mini-html-webpack-template/index.d.ts | 585 | // Type definitions for @vxna/mini-html-webpack-template 2.0
// Project: https://github.com/vxna/mini-html-webpack-template#readme
// Definitions by: Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { PluginContext } from 'mini-html-webpack-plugin';
/**
* Template for `mini-html-webpack-plugin` that extends default features with useful subset of options
*/
declare function template(ctx: PluginContext): string;
/**
* Minimum viable template for mini-html-webpack-plugin
*/
export = template;
| mit |
JuanLuisClaure/vistas | node_modules/@angular/common/esm/src/forms-deprecated/model.js | 15370 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { PromiseObservable } from 'rxjs/observable/PromiseObservable';
import { EventEmitter } from '../facade/async';
import { ListWrapper, StringMapWrapper } from '../facade/collection';
import { isBlank, isPresent, isPromise, normalizeBool } from '../facade/lang';
/**
* Indicates that a Control is valid, i.e. that no errors exist in the input value.
*/
export const VALID = 'VALID';
/**
* Indicates that a Control is invalid, i.e. that an error exists in the input value.
*/
export const INVALID = 'INVALID';
/**
* Indicates that a Control is pending, i.e. that async validation is occurring and
* errors are not yet available for the input value.
*/
export const PENDING = 'PENDING';
export function isControl(control) {
return control instanceof AbstractControl;
}
function _find(control, path) {
if (isBlank(path))
return null;
if (!(path instanceof Array)) {
path = path.split('/');
}
if (path instanceof Array && ListWrapper.isEmpty(path))
return null;
return path.reduce((v, name) => {
if (v instanceof ControlGroup) {
return isPresent(v.controls[name]) ? v.controls[name] : null;
}
else if (v instanceof ControlArray) {
var index = name;
return isPresent(v.at(index)) ? v.at(index) : null;
}
else {
return null;
}
}, control);
}
function toObservable(r) {
return isPromise(r) ? PromiseObservable.create(r) : r;
}
/**
* @experimental
*/
export class AbstractControl {
constructor(validator, asyncValidator) {
this.validator = validator;
this.asyncValidator = asyncValidator;
this._pristine = true;
this._touched = false;
}
get value() { return this._value; }
get status() { return this._status; }
get valid() { return this._status === VALID; }
/**
* Returns the errors of this control.
*/
get errors() { return this._errors; }
get pristine() { return this._pristine; }
get dirty() { return !this.pristine; }
get touched() { return this._touched; }
get untouched() { return !this._touched; }
get valueChanges() { return this._valueChanges; }
get statusChanges() { return this._statusChanges; }
get pending() { return this._status == PENDING; }
markAsTouched() { this._touched = true; }
markAsDirty({ onlySelf } = {}) {
onlySelf = normalizeBool(onlySelf);
this._pristine = false;
if (isPresent(this._parent) && !onlySelf) {
this._parent.markAsDirty({ onlySelf: onlySelf });
}
}
markAsPending({ onlySelf } = {}) {
onlySelf = normalizeBool(onlySelf);
this._status = PENDING;
if (isPresent(this._parent) && !onlySelf) {
this._parent.markAsPending({ onlySelf: onlySelf });
}
}
setParent(parent) { this._parent = parent; }
updateValueAndValidity({ onlySelf, emitEvent } = {}) {
onlySelf = normalizeBool(onlySelf);
emitEvent = isPresent(emitEvent) ? emitEvent : true;
this._updateValue();
this._errors = this._runValidator();
this._status = this._calculateStatus();
if (this._status == VALID || this._status == PENDING) {
this._runAsyncValidator(emitEvent);
}
if (emitEvent) {
this._valueChanges.emit(this._value);
this._statusChanges.emit(this._status);
}
if (isPresent(this._parent) && !onlySelf) {
this._parent.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
}
}
_runValidator() {
return isPresent(this.validator) ? this.validator(this) : null;
}
_runAsyncValidator(emitEvent) {
if (isPresent(this.asyncValidator)) {
this._status = PENDING;
this._cancelExistingSubscription();
var obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription = obs.subscribe({ next: (res) => this.setErrors(res, { emitEvent: emitEvent }) });
}
}
_cancelExistingSubscription() {
if (isPresent(this._asyncValidationSubscription)) {
this._asyncValidationSubscription.unsubscribe();
}
}
/**
* Sets errors on a control.
*
* This is used when validations are run not automatically, but manually by the user.
*
* Calling `setErrors` will also update the validity of the parent control.
*
* ## Usage
*
* ```
* var login = new Control("someLogin");
* login.setErrors({
* "notUnique": true
* });
*
* expect(login.valid).toEqual(false);
* expect(login.errors).toEqual({"notUnique": true});
*
* login.updateValue("someOtherLogin");
*
* expect(login.valid).toEqual(true);
* ```
*/
setErrors(errors, { emitEvent } = {}) {
emitEvent = isPresent(emitEvent) ? emitEvent : true;
this._errors = errors;
this._status = this._calculateStatus();
if (emitEvent) {
this._statusChanges.emit(this._status);
}
if (isPresent(this._parent)) {
this._parent._updateControlsErrors();
}
}
find(path) { return _find(this, path); }
getError(errorCode, path = null) {
var control = isPresent(path) && !ListWrapper.isEmpty(path) ? this.find(path) : this;
if (isPresent(control) && isPresent(control._errors)) {
return StringMapWrapper.get(control._errors, errorCode);
}
else {
return null;
}
}
hasError(errorCode, path = null) {
return isPresent(this.getError(errorCode, path));
}
get root() {
let x = this;
while (isPresent(x._parent)) {
x = x._parent;
}
return x;
}
/** @internal */
_updateControlsErrors() {
this._status = this._calculateStatus();
if (isPresent(this._parent)) {
this._parent._updateControlsErrors();
}
}
/** @internal */
_initObservables() {
this._valueChanges = new EventEmitter();
this._statusChanges = new EventEmitter();
}
_calculateStatus() {
if (isPresent(this._errors))
return INVALID;
if (this._anyControlsHaveStatus(PENDING))
return PENDING;
if (this._anyControlsHaveStatus(INVALID))
return INVALID;
return VALID;
}
}
/**
* Defines a part of a form that cannot be divided into other controls. `Control`s have values and
* validation state, which is determined by an optional validation function.
*
* `Control` is one of the three fundamental building blocks used to define forms in Angular, along
* with {@link ControlGroup} and {@link ControlArray}.
*
* ## Usage
*
* By default, a `Control` is created for every `<input>` or other form component.
* With {@link NgFormControl} or {@link NgFormModel} an existing {@link Control} can be
* bound to a DOM element instead. This `Control` can be configured with a custom
* validation function.
*
* ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
*
* @experimental
*/
export class Control extends AbstractControl {
constructor(value = null, validator = null, asyncValidator = null) {
super(validator, asyncValidator);
this._value = value;
this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
this._initObservables();
}
/**
* Set the value of the control to `value`.
*
* If `onlySelf` is `true`, this change will only affect the validation of this `Control`
* and not its parent component. If `emitEvent` is `true`, this change will cause a
* `valueChanges` event on the `Control` to be emitted. Both of these options default to
* `false`.
*
* If `emitModelToViewChange` is `true`, the view will be notified about the new value
* via an `onChange` event. This is the default behavior if `emitModelToViewChange` is not
* specified.
*/
updateValue(value, { onlySelf, emitEvent, emitModelToViewChange } = {}) {
emitModelToViewChange = isPresent(emitModelToViewChange) ? emitModelToViewChange : true;
this._value = value;
if (isPresent(this._onChange) && emitModelToViewChange)
this._onChange(this._value);
this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
}
/**
* @internal
*/
_updateValue() { }
/**
* @internal
*/
_anyControlsHaveStatus(status) { return false; }
/**
* Register a listener for change events.
*/
registerOnChange(fn) { this._onChange = fn; }
}
/**
* Defines a part of a form, of fixed length, that can contain other controls.
*
* A `ControlGroup` aggregates the values of each {@link Control} in the group.
* The status of a `ControlGroup` depends on the status of its children.
* If one of the controls in a group is invalid, the entire group is invalid.
* Similarly, if a control changes its value, the entire group changes as well.
*
* `ControlGroup` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link Control} and {@link ControlArray}. {@link ControlArray} can also contain other
* controls, but is of variable length.
*
* ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
*
* @experimental
*/
export class ControlGroup extends AbstractControl {
constructor(controls, optionals = null, validator = null, asyncValidator = null) {
super(validator, asyncValidator);
this.controls = controls;
this._optionals = isPresent(optionals) ? optionals : {};
this._initObservables();
this._setParentForControls();
this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
}
/**
* Register a control with the group's list of controls.
*/
registerControl(name, control) {
this.controls[name] = control;
control.setParent(this);
}
/**
* Add a control to this group.
*/
addControl(name, control) {
this.registerControl(name, control);
this.updateValueAndValidity();
}
/**
* Remove a control from this group.
*/
removeControl(name) {
StringMapWrapper.delete(this.controls, name);
this.updateValueAndValidity();
}
/**
* Mark the named control as non-optional.
*/
include(controlName) {
StringMapWrapper.set(this._optionals, controlName, true);
this.updateValueAndValidity();
}
/**
* Mark the named control as optional.
*/
exclude(controlName) {
StringMapWrapper.set(this._optionals, controlName, false);
this.updateValueAndValidity();
}
/**
* Check whether there is a control with the given name in the group.
*/
contains(controlName) {
var c = StringMapWrapper.contains(this.controls, controlName);
return c && this._included(controlName);
}
/** @internal */
_setParentForControls() {
StringMapWrapper.forEach(this.controls, (control, name) => { control.setParent(this); });
}
/** @internal */
_updateValue() { this._value = this._reduceValue(); }
/** @internal */
_anyControlsHaveStatus(status) {
var res = false;
StringMapWrapper.forEach(this.controls, (control, name) => {
res = res || (this.contains(name) && control.status == status);
});
return res;
}
/** @internal */
_reduceValue() {
return this._reduceChildren({}, (acc, control, name) => {
acc[name] = control.value;
return acc;
});
}
/** @internal */
_reduceChildren(initValue, fn) {
var res = initValue;
StringMapWrapper.forEach(this.controls, (control, name) => {
if (this._included(name)) {
res = fn(res, control, name);
}
});
return res;
}
/** @internal */
_included(controlName) {
var isOptional = StringMapWrapper.contains(this._optionals, controlName);
return !isOptional || StringMapWrapper.get(this._optionals, controlName);
}
}
/**
* Defines a part of a form, of variable length, that can contain other controls.
*
* A `ControlArray` aggregates the values of each {@link Control} in the group.
* The status of a `ControlArray` depends on the status of its children.
* If one of the controls in a group is invalid, the entire array is invalid.
* Similarly, if a control changes its value, the entire array changes as well.
*
* `ControlArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link Control} and {@link ControlGroup}. {@link ControlGroup} can also contain
* other controls, but is of fixed length.
*
* ## Adding or removing controls
*
* To change the controls in the array, use the `push`, `insert`, or `removeAt` methods
* in `ControlArray` itself. These methods ensure the controls are properly tracked in the
* form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
* the `ControlArray` directly, as that will result in strange and unexpected behavior such
* as broken change detection.
*
* ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
*
* @experimental
*/
export class ControlArray extends AbstractControl {
constructor(controls, validator = null, asyncValidator = null) {
super(validator, asyncValidator);
this.controls = controls;
this._initObservables();
this._setParentForControls();
this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
}
/**
* Get the {@link AbstractControl} at the given `index` in the array.
*/
at(index) { return this.controls[index]; }
/**
* Insert a new {@link AbstractControl} at the end of the array.
*/
push(control) {
this.controls.push(control);
control.setParent(this);
this.updateValueAndValidity();
}
/**
* Insert a new {@link AbstractControl} at the given `index` in the array.
*/
insert(index, control) {
ListWrapper.insert(this.controls, index, control);
control.setParent(this);
this.updateValueAndValidity();
}
/**
* Remove the control at the given `index` in the array.
*/
removeAt(index) {
ListWrapper.removeAt(this.controls, index);
this.updateValueAndValidity();
}
/**
* Length of the control array.
*/
get length() { return this.controls.length; }
/** @internal */
_updateValue() { this._value = this.controls.map((control) => control.value); }
/** @internal */
_anyControlsHaveStatus(status) {
return this.controls.some(c => c.status == status);
}
/** @internal */
_setParentForControls() {
this.controls.forEach((control) => { control.setParent(this); });
}
}
//# sourceMappingURL=model.js.map | mit |
ValiMail/arc_test_suite | sig_gen/dkim/asn1.py | 4184 | # This software is provided 'as-is', without any express or implied
# warranty. In no event will the author be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
#
# Copyright (c) 2008 Greg Hewgill http://hewgill.com
#
# This has been modified from the original software.
# Copyright (c) 2011 William Grant <me@williamgrant.id.au>
__all__ = [
'asn1_build',
'asn1_parse',
'ASN1FormatError',
'BIT_STRING',
'INTEGER',
'SEQUENCE',
'OBJECT_IDENTIFIER',
'OCTET_STRING',
'NULL',
]
INTEGER = 0x02
BIT_STRING = 0x03
OCTET_STRING = 0x04
NULL = 0x05
OBJECT_IDENTIFIER = 0x06
SEQUENCE = 0x30
class ASN1FormatError(Exception):
pass
def asn1_parse(template, data):
"""Parse a data structure according to an ASN.1 template.
@param template: tuples comprising the ASN.1 template
@param data: byte string data to parse
@return: decoded structure
"""
data = bytearray(data)
r = []
i = 0
try:
for t in template:
tag = data[i]
i += 1
if tag == t[0]:
length = data[i]
i += 1
if length & 0x80:
n = length & 0x7f
length = 0
for j in range(n):
length = (length << 8) | data[i]
i += 1
if tag == INTEGER:
n = 0
for j in range(length):
n = (n << 8) | data[i]
i += 1
r.append(n)
elif tag == BIT_STRING:
r.append(data[i:i+length])
i += length
elif tag == NULL:
assert length == 0
r.append(None)
elif tag == OBJECT_IDENTIFIER:
r.append(data[i:i+length])
i += length
elif tag == SEQUENCE:
r.append(asn1_parse(t[1], data[i:i+length]))
i += length
else:
raise ASN1FormatError(
"Unexpected tag in template: %02x" % tag)
else:
raise ASN1FormatError(
"Unexpected tag (got %02x, expecting %02x)" % (tag, t[0]))
return r
except IndexError:
raise ASN1FormatError("Data truncated at byte %d"%i)
def asn1_length(n):
"""Return a string representing a field length in ASN.1 format.
@param n: integer field length
@return: ASN.1 field length
"""
assert n >= 0
if n < 0x7f:
return bytearray([n])
r = bytearray()
while n > 0:
r.insert(n & 0xff)
n >>= 8
return r
def asn1_encode(type, data):
length = asn1_length(len(data))
length.insert(0, type)
length.extend(data)
return length
def asn1_build(node):
"""Build a DER-encoded ASN.1 data structure.
@param node: (type, data) tuples comprising the ASN.1 structure
@return: DER-encoded ASN.1 byte string
"""
if node[0] == OCTET_STRING:
return asn1_encode(OCTET_STRING, node[1])
if node[0] == NULL:
assert node[1] is None
return asn1_encode(NULL, b'')
elif node[0] == OBJECT_IDENTIFIER:
return asn1_encode(OBJECT_IDENTIFIER, node[1])
elif node[0] == SEQUENCE:
r = bytearray()
for x in node[1]:
r += asn1_build(x)
return asn1_encode(SEQUENCE, r)
else:
raise ASN1FormatError("Unexpected tag in template: %02x" % node[0])
| mit |
lookout/protobuffy | lib/protobuf/field/sint32_field.rb | 276 | require 'protobuf/field/signed_integer_field'
module Protobuf
module Field
class Sint32Field < SignedIntegerField
##
# Class Methods
#
def self.max
INT32_MAX
end
def self.min
INT32_MIN
end
end
end
end
| mit |
partheinstein/bc-java | pkix/src/main/jdk1.3/org/bouncycastle/cms/jcajce/JceKeyTransRecipientId.java | 927 | package org.bouncycastle.cms.jcajce;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cms.KeyTransRecipientId;
import org.bouncycastle.jce.PrincipalUtil;
import org.bouncycastle.jce.X509Principal;
public class JceKeyTransRecipientId
extends KeyTransRecipientId
{
public JceKeyTransRecipientId(X509Certificate certificate)
{
super(X500Name.getInstance(extractIssuer(certificate)), certificate.getSerialNumber(), CMSUtils.getSubjectKeyId(certificate));
}
private static X509Principal extractIssuer(X509Certificate certificate)
{
try
{
return PrincipalUtil.getIssuerX509Principal(certificate);
}
catch (CertificateEncodingException e)
{
throw new IllegalStateException("can't extract issuer");
}
}
}
| mit |
azazdeaz/component-playground | demo/webpack.config.hot.js | 415 | "use strict";
var _ = require("lodash");
var base = require("./webpack.config.dev");
// Update our own module version.
var mod = _.cloneDeep(base.module);
// First loader needs react hot.
mod.loaders[0].loaders = ["react-hot"].concat(mod.loaders[0].loaders);
module.exports = _.merge({}, _.omit(base, "entry", "module"), {
entry: {
app: ["webpack/hot/dev-server", "./demo/app.jsx"]
},
module: mod
});
| mit |
AndeyR/AngularNet | source/ResourceMetadata/ResourceMetadata.Data/Repositories/ResourceActivityRepository.cs | 619 | using ResourceMetadata.Data.Infrastructure;
using ResourceMetadata.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResourceMetadata.Data.Repositories
{
public class ResourceActivityRepository : RepositoryBase<ResourceActivity>, IResourceActivityRepository
{
public ResourceActivityRepository(IDatabaseFactory databaseFactory)
: base(databaseFactory)
{
}
}
public interface IResourceActivityRepository : IRepository<ResourceActivity>
{
}
}
| mit |
BijayaDas/catarse | db/migrate/20160426160341_add_unique_index_to_category_totals.rb | 294 | class AddUniqueIndexToCategoryTotals < ActiveRecord::Migration
disable_ddl_transaction!
def up
execute %Q{
CREATE UNIQUE INDEX CONCURRENTLY category_totals_idx ON "1".category_totals(category_id);
}
end
def down
execute %Q{
DROP INDEX category_totals_idx;
}
end
end
| mit |
c72578/poedit | deps/boost/libs/hana/test/ext/boost/mpl/list/comparable.cpp | 709 | // Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/ext/boost/mpl/list.hpp>
#include <boost/hana/tuple.hpp>
#include <laws/comparable.hpp>
#include <boost/mpl/list.hpp>
namespace hana = boost::hana;
namespace mpl = boost::mpl;
struct t1; struct t2; struct t3; struct t4;
int main() {
auto lists = hana::make_tuple(
mpl::list<>{}
, mpl::list<t1>{}
, mpl::list<t1, t2>{}
, mpl::list<t1, t2, t3>{}
, mpl::list<t1, t2, t3, t4>{}
);
hana::test::TestComparable<hana::ext::boost::mpl::list_tag>{lists};
}
| mit |
parjong/coreclr | src/mscorlib/src/System/Guid.CoreCLR.cs | 521 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace System
{
partial struct Guid
{
public static Guid NewGuid()
{
Guid guid;
Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1));
return guid;
}
}
}
| mit |
aredotna/case | ios/Pods/boost-for-react-native/boost/asio/detail/signal_op.hpp | 1197 | //
// detail/signal_op.hpp
// ~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_SIGNAL_OP_HPP
#define BOOST_ASIO_DETAIL_SIGNAL_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/detail/operation.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
class signal_op
: public operation
{
public:
// The error code to be passed to the completion handler.
boost::system::error_code ec_;
// The signal number to be passed to the completion handler.
int signal_number_;
protected:
signal_op(func_type func)
: operation(func),
signal_number_(0)
{
}
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_DETAIL_SIGNAL_OP_HPP
| mit |
jkroepke/2Moons | chat/js/lang/en.js | 3942 | /*
* @package AJAX_Chat
* @author Sebastian Tschan
* @copyright (c) Sebastian Tschan
* @license Modified MIT License
* @link https://blueimp.net/ajax/
*/
// Ajax Chat language Object:
var ajaxChatLang = {
login: '%s logs into the Chat.',
logout: '%s logs out of the Chat.',
logoutTimeout: '%s has been logged out (Timeout).',
logoutIP: '%s has been logged out (Invalid IP address).',
logoutKicked: '%s has been logged out (Kicked).',
channelEnter: '%s enters the channel.',
channelLeave: '%s leaves the channel.',
privmsg: '(whispers)',
privmsgto: '(whispers to %s)',
invite: '%s invites you to join %s.',
inviteto: 'Your invitation to %s to join channel %s has been sent.',
uninvite: '%s uninvites you from channel %s.',
uninviteto: 'Your uninvitation to %s for channel %s has been sent.',
queryOpen: 'Private channel opened to %s.',
queryClose: 'Private channel to %s closed.',
ignoreAdded: 'Added %s to the ignore list.',
ignoreRemoved: 'Removed %s from the ignore list.',
ignoreList: 'Ignored Users:',
ignoreListEmpty: 'No ignored Users listed.',
who: 'Online Users:',
whoChannel: 'Online Users in channel %s:',
whoEmpty: 'No online users in the given channel.',
list: 'Available channels:',
bans: 'Banned Users:',
bansEmpty: 'No banned Users listed.',
unban: 'Ban of user %s revoked.',
whois: 'User %s - IP address:',
whereis: 'User %s is in channel %s.',
roll: '%s rolls %s and gets %s.',
nick: '%s is now known as %s.',
toggleUserMenu: 'Toggle user menu for %s',
userMenuLogout: 'Logout',
userMenuWho: 'List online users',
userMenuList: 'List available channels',
userMenuAction: 'Describe action',
userMenuRoll: 'Roll dice',
userMenuNick: 'Change username',
userMenuEnterPrivateRoom: 'Enter private room',
userMenuSendPrivateMessage: 'Send private message',
userMenuDescribe: 'Send private action',
userMenuOpenPrivateChannel: 'Open private channel',
userMenuClosePrivateChannel: 'Close private channel',
userMenuInvite: 'Invite',
userMenuUninvite: 'Uninvite',
userMenuIgnore: 'Ignore/Accept',
userMenuIgnoreList: 'List ignored users',
userMenuWhereis: 'Display channel',
userMenuKick: 'Kick/Ban',
userMenuBans: 'List banned users',
userMenuWhois: 'Display IP',
unbanUser: 'Revoke ban of user %s',
joinChannel: 'Join channel %s',
cite: '%s said:',
urlDialog: 'Please enter the address (URL) of the webpage:',
deleteMessage: 'Delete this chat message',
deleteMessageConfirm: 'Really delete the selected chat message?',
errorCookiesRequired: 'Cookies are required for this chat.',
errorUserNameNotFound: 'Error: User %s not found.',
errorMissingText: 'Error: Missing message text.',
errorMissingUserName: 'Error: Missing username.',
errorInvalidUserName: 'Error: Invalid username.',
errorUserNameInUse: 'Error: Username already in use.',
errorMissingChannelName: 'Error: Missing channel name.',
errorInvalidChannelName: 'Error: Invalid channel name: %s',
errorPrivateMessageNotAllowed: 'Error: Private messages are not allowed.',
errorInviteNotAllowed: 'Error: You are not allowed to invite someone to this channel.',
errorUninviteNotAllowed: 'Error: You are not allowed to uninvite someone from this channel.',
errorNoOpenQuery: 'Error: No private channel open.',
errorKickNotAllowed: 'Error: You are not allowed to kick %s.',
errorCommandNotAllowed: 'Error: Command not allowed: %s',
errorUnknownCommand: 'Error: Unknown command: %s',
errorMaxMessageRate: 'Error: You exceeded the maximum number of messages per minute.',
errorConnectionTimeout: 'Error: Connection timeout. Please try again.',
errorConnectionStatus: 'Error: Connection status: %s',
errorSoundIO: 'Error: Failed to load sound file (Flash IO Error).',
errorSocketIO: 'Error: Connection to socket server failed (Flash IO Error).',
errorSocketSecurity: 'Error: Connection to socket server failed (Flash Security Error).',
errorDOMSyntax: 'Error: Invalid DOM Syntax (DOM ID: %s).'
} | mit |
fabianoleittes/rails | actionpack/lib/action_dispatch/request/utils.rb | 2279 | # frozen_string_literal: true
require "active_support/core_ext/hash/indifferent_access"
module ActionDispatch
class Request
class Utils # :nodoc:
mattr_accessor :perform_deep_munge, default: true
def self.each_param_value(params, &block)
case params
when Array
params.each { |element| each_param_value(element, &block) }
when Hash
params.each_value { |value| each_param_value(value, &block) }
when String
block.call params
end
end
def self.normalize_encode_params(params)
if perform_deep_munge
NoNilParamEncoder.normalize_encode_params params
else
ParamEncoder.normalize_encode_params params
end
end
def self.check_param_encoding(params)
case params
when Array
params.each { |element| check_param_encoding(element) }
when Hash
params.each_value { |value| check_param_encoding(value) }
when String
unless params.valid_encoding?
# Raise Rack::Utils::InvalidParameterError for consistency with Rack.
# ActionDispatch::Request#GET will re-raise as a BadRequest error.
raise Rack::Utils::InvalidParameterError, "Invalid encoding for parameter: #{params.scrub}"
end
end
end
class ParamEncoder # :nodoc:
# Convert nested Hash to HashWithIndifferentAccess.
def self.normalize_encode_params(params)
case params
when Array
handle_array params
when Hash
if params.has_key?(:tempfile)
ActionDispatch::Http::UploadedFile.new(params)
else
params.transform_values do |val|
normalize_encode_params(val)
end.with_indifferent_access
end
else
params
end
end
def self.handle_array(params)
params.map! { |el| normalize_encode_params(el) }
end
end
# Remove nils from the params hash.
class NoNilParamEncoder < ParamEncoder # :nodoc:
def self.handle_array(params)
list = super
list.compact!
list
end
end
end
end
end
| mit |
awesomerobot/discourse | app/serializers/invited_user_serializer.rb | 1009 | class InvitedUserSerializer < BasicUserSerializer
attributes :topics_entered,
:posts_read_count,
:last_seen_at,
:time_read,
:days_visited,
:days_since_created
attr_accessor :invited_by
def time_read
object.user_stat.time_read
end
def include_time_read?
scope.can_see_invite_details?(invited_by)
end
def days_visited
object.user_stat.days_visited
end
def include_days_visited?
scope.can_see_invite_details?(invited_by)
end
def topics_entered
object.user_stat.topics_entered
end
def include_topics_entered?
scope.can_see_invite_details?(invited_by)
end
def posts_read_count
object.user_stat.posts_read_count
end
def include_posts_read_count?
scope.can_see_invite_details?(invited_by)
end
def days_since_created
((Time.now - object.created_at) / 60 / 60 / 24).ceil
end
def include_days_since_created
scope.can_see_invite_details?(invited_by)
end
end
| gpl-2.0 |
kosmosby/medicine-prof | administrator/components/com_virtuemart/views/product/view.json.php | 8569 | <?php
/**
*
* Description
*
* @package VirtueMart
* @subpackage
* @author
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2012 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: view.json.php 8561 2014-11-11 13:31:55Z Milbo $
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
// Load the view framework
if(!class_exists('VmViewAdmin'))require(VMPATH_ADMIN.DS.'helpers'.DS.'vmviewadmin.php');
// Load some common models
if(!class_exists('VirtueMartModelCustomfields')) require(VMPATH_ADMIN.DS.'models'.DS.'customfields.php');
/**
* HTML View class for the VirtueMart Component
*
* @package VirtueMart
* @author
*/
class VirtuemartViewProduct extends VmViewAdmin {
var $json = array();
function __construct( ){
$this->type = vRequest::getCmd('type', false);
$this->row = vRequest::getInt('row', false);
$this->db = JFactory::getDBO();
$this->model = VmModel::getModel('Customfields') ;
}
function display($tpl = null) {
$filter = vRequest::getVar('q', vRequest::getVar('term', false) );
$id = vRequest::getInt('id', false);
$virtuemart_product_id = vRequest::getInt('virtuemart_product_id',array());
if(is_array($virtuemart_product_id) && count($virtuemart_product_id) > 0){
$product_id = (int)$virtuemart_product_id[0];
} else {
$product_id = (int)$virtuemart_product_id;
}
//$customfield = $this->model->getcustomfield();
/* Get the task */
if ($this->type=='relatedproducts') {
$query = "SELECT virtuemart_product_id AS id, CONCAT(product_name, '::', product_sku) AS value
FROM #__virtuemart_products_".VmConfig::$vmlang."
JOIN `#__virtuemart_products` AS p using (`virtuemart_product_id`)";
if ($filter) $query .= " WHERE product_name LIKE '%". $this->db->escape( $filter, true ) ."%' or product_sku LIKE '%". $this->db->escape( $filter, true ) ."%' limit 0,10";
self::setRelatedHtml($product_id,$query,'R');
}
else if ($this->type=='relatedcategories')
{
$query = "SELECT virtuemart_category_id AS id, CONCAT(category_name, '::', virtuemart_category_id) AS value
FROM #__virtuemart_categories_".VmConfig::$vmlang;
if ($filter) $query .= " WHERE category_name LIKE '%". $this->db->escape( $filter, true ) ."%' limit 0,10";
self::setRelatedHtml($product_id,$query,'Z');
}
else if ($this->type=='custom')
{
$query = "SELECT CONCAT(virtuemart_custom_id, '|', custom_value, '|', field_type) AS id, CONCAT(custom_title, '::', custom_tip) AS value
FROM #__virtuemart_customs";
if ($filter) $query .= " WHERE custom_title LIKE '%".$filter."%' limit 0,50";
$this->db->setQuery($query);
$this->json['value'] = $this->db->loadObjectList();
$this->json['ok'] = 1 ;
}
else if ($this->type=='fields')
{
if (!class_exists ('VirtueMartModelCustom')) {
require(VMPATH_ADMIN . DS . 'models' . DS . 'custom.php');
}
$fieldTypes = VirtueMartModelCustom::getCustomTypes();
$query = 'SELECT *,`custom_value` as value FROM `#__virtuemart_customs`
WHERE (`virtuemart_custom_id`='.$id.' or `custom_parent_id`='.$id.') ';
$query .= 'order by `ordering` asc';
$this->db->setQuery($query);
$rows = $this->db->loadObjectlist();
$html = array ();
foreach ($rows as $field) {
if ($field->field_type =='deprecatedwasC' ){
$this->json['table'] = 'childs';
$q='SELECT `virtuemart_product_id` FROM `#__virtuemart_products` WHERE `published`=1
AND `product_parent_id`= '.vRequest::getInt('virtuemart_product_id');
//$this->db->setQuery(' SELECT virtuemart_product_id, product_name FROM `#__virtuemart_products` WHERE `product_parent_id` ='.(int)$product_id);
$this->db->setQuery($q);
if ($childIds = $this->db->loadColumn()) {
// Get childs
foreach ($childIds as $childId) {
$field->custom_value = $childId;
$display = $this->model->displayProductCustomfieldBE($field,$childId,$this->row);
if ($field->is_cart_attribute) $cartIcone= 'default';
else $cartIcone= 'default-off';
$html[] = '<div class="removable">
<td>'.$field->custom_title.'</td>
<td>'.$display.$field->custom_tip.'</td>
<td>'.vmText::_($fieldTypes[$field->field_type]).'
'.$this->model->setEditCustomHidden($field, $this->row).'
</td>
<td><span class="vmicon vmicon-16-'.$cartIcone.'"></span></td>
<td></td>
</div>';
$this->row++;
}
}
} elseif ($field->field_type =='E') {
$this->json['table'] = 'customPlugins';
$this->model->bindCustomEmbeddedFieldParams($field,'E');
$display = $this->model->displayProductCustomfieldBE($field,$product_id,$this->row);
if ($field->is_cart_attribute) {
$cartIcone= 'default';
} else {
$cartIcone= 'default-off';
}
$field->virtuemart_product_id=$product_id;
$html[] = '
<tr class="removable">
<td><span class="hasTip" title="'.vmText::_($field->custom_tip).'">'.$field->custom_title.'</td>
<td>'.$display.'
'.$this->model->setEditCustomHidden($field, $this->row).'
<p>'.vmText::_('COM_VIRTUEMART_CUSTOM_ACTIVATE_JAVASCRIPT').'</p></td>
<td><span class="vmicon vmicon-16-'.$cartIcone.'"></span>'.vmText::_('COM_VIRTUEMART_CUSTOM_EXTENSION').'</td>
<td><span class="vmicon vmicon-16-move"></span>
<span class="vmicon vmicon-16-remove"></span><input class="ordering" type="hidden" value="'.$this->row.'" name="field['.$this->row .'][ordering]" />
</td>
</tr>';
$this->row++;
} else {
$this->json['table'] = 'fields';
$display = $this->model->displayProductCustomfieldBE($field,$product_id,$this->row);
if ($field->is_cart_attribute) $cartIcone= 'default';
else $cartIcone= 'default-off';
if(isset($fieldTypes[$field->field_type])){
$type =vmText::_($fieldTypes[$field->field_type]);
} else {
$type = 'deprecated';
}
$html[] = '<tr class="removable">
<td><span class="hasTip" title="'.vmText::_($field->custom_tip).'">'.$field->custom_title.'</td>
<td>'.$display.'</td>
<td><span class="vmicon vmicon-16-'.$cartIcone.'"></span>'.vmText::_($fieldTypes[$field->field_type]).'
'.$type.$this->model->setEditCustomHidden($field, $this->row).'
</td>
<td><span class="vmicon vmicon-16-move"></span><span class="vmicon vmicon-16-remove"></span><input class="ordering" type="hidden" value="'.$this->row.'" name="field['.$this->row .'][ordering]" /></td>
</tr>';
$this->row++;
}
}
$this->json['value'] = $html;
$this->json['ok'] = 1 ;
} else if ($this->type=='userlist')
{
$status = vRequest::getvar('status');
$productShoppers=0;
if ($status) {
$productModel = VmModel::getModel('product');
$productShoppers = $productModel->getProductShoppersByStatus($product_id ,$status);
}
if(!class_exists('ShopFunctions'))require(VMPATH_ADMIN.DS.'helpers'.DS.'shopfunctions.php');
$html = ShopFunctions::renderProductShopperList($productShoppers);
$this->json['value'] = $html;
} else $this->json['ok'] = 0 ;
if ( empty($this->json)) {
$this->json['value'] = null;
$this->json['ok'] = 1 ;
}
echo json_encode($this->json);
}
function setRelatedHtml($product_id,$query,$fieldType) {
$this->db->setQuery($query);
$this->json = $this->db->loadObjectList();
$query = 'SELECT * FROM `#__virtuemart_customs` WHERE field_type ="'.$fieldType.'" ';
$this->db->setQuery($query);
$custom = $this->db->loadObject();
if(!$custom) {
vmdebug('setRelatedHtml could not find $custom for field type '.$fieldType);
return false;
}
$custom->virtuemart_product_id = $product_id;
foreach ($this->json as &$related) {
$custom->customfield_value = $related->id;
$display = $this->model->displayProductCustomfieldBE($custom,$related->id,$this->row);
$html = '<div class="vm_thumb_image">
<span class="vmicon vmicon-16-move"></span>
<div class="vmicon vmicon-16-remove"></div>
<span>'.$display.'</span>
'.$this->model->setEditCustomHidden($custom, $this->row).'
</div>';
$related->label = $html;
}
}
}
// pure php no closing tag
| gpl-2.0 |
md-5/jdk10 | test/langtools/tools/javac/modules/ProvidesTest.java | 23553 | /*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @summary simple tests of module provides
* @bug 8168854 8172807
* @library /tools/lib
* @modules
* jdk.compiler/com.sun.tools.javac.api
* jdk.compiler/com.sun.tools.javac.main
* @build toolbox.ToolBox toolbox.JavacTask ModuleTestBase
* @run main ProvidesTest
*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import toolbox.JavacTask;
import toolbox.Task;
import toolbox.Task.Expect;
public class ProvidesTest extends ModuleTestBase {
public static void main(String... args) throws Exception {
ProvidesTest t = new ProvidesTest();
t.runTests();
}
@Test
public void testSimple(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p1.C1 with p2.C2; }",
"package p1; public class C1 { }",
"package p2; public class C2 extends p1.C1 { }");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
new JavacTask(tb)
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.SUCCESS)
.writeAll();
}
@Test
public void testMulti(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src.resolve("m1x"),
"module m1x { exports p1; }",
"package p1; public class C1 { }");
tb.writeJavaFiles(src.resolve("m2x"),
"module m2x { requires m1x; provides p1.C1 with p2.C2; }",
"package p2; public class C2 extends p1.C1 { }");
Path modules = base.resolve("modules");
Files.createDirectories(modules);
new JavacTask(tb)
.options("--module-source-path", src.toString())
.outdir(modules)
.files(findJavaFiles(src))
.run(Task.Expect.SUCCESS)
.writeAll();
}
@Test
public void testMissingWith(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p.C; }",
"package p; public class C { }");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
String log = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!log.contains("module-info.java:1:24: compiler.err.expected.str: 'with'"))
throw new Exception("expected output not found");
}
@Test
public void testDuplicateImplementations1(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { exports p1; exports p2; provides p1.C1 with p2.C2, p2.C2; }",
"package p1; public class C1 { }",
"package p2; public class C2 extends p1.C1 { }");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:65: compiler.err.duplicate.provides: p1.C1, p2.C2",
"1 error");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testDuplicateImplementations2(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { exports p1; provides p1.C1 with p2.C2; provides p1.C1 with p2.C2; }",
"package p1; public class C1 { }",
"package p2; public class C2 extends p1.C1 { }");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:62: compiler.err.repeated.provides.for.service: p1.C1",
"module-info.java:1:73: compiler.err.duplicate.provides: p1.C1, p2.C2",
"2 errors");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testMissingService(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p.Missing with p.C; }",
"package p; public class C extends p.Missing { }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"C.java:1:36: compiler.err.cant.resolve.location: kindname.class, Missing, , , (compiler.misc.location: kindname.package, p, null)",
"module-info.java:1:22: compiler.err.cant.resolve.location: kindname.class, Missing, , , (compiler.misc.location: kindname.package, p, null)",
"2 errors");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testProvidesFromAnotherModule(Path base) throws Exception {
Path modules = base.resolve("modules");
tb.writeJavaFiles(modules.resolve("M"),
"module M { exports p; }",
"package p; public class Service { }");
tb.writeJavaFiles(modules.resolve("L"),
"module L { requires M; provides p.Service with p.Service; }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics",
"--module-source-path", modules.toString())
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(modules))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:24: compiler.err.service.implementation.not.in.right.module: M",
"1 error");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testServiceIsNotImplemented(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p.A with p.B; }",
"package p; public class A { }",
"package p; public class B { }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:31: compiler.err.service.implementation.must.be.subtype.of.service.interface",
"module-info.java:1:12: compiler.warn.service.provided.but.not.exported.or.used: p.A",
"1 error",
"1 warning");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testMissingImplementation(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p.C with p.Impl; }",
"package p; public class C { }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList("module-info.java:1:31: compiler.err.cant.resolve.location: kindname.class, Impl, , , (compiler.misc.location: kindname.package, p, null)",
"1 error");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testSeveralImplementations(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p.C with p.Impl1, p.Impl2; }",
"package p; public class C { }",
"package p; public class Impl1 extends p.C { }",
"package p; public class Impl2 extends p.C { }");
new JavacTask(tb)
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.SUCCESS)
.writeAll();
}
@Test
public void testRepeatedProvides(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { exports p; provides p.C with p.Impl1; provides p.C with p.Impl2; }",
"package p; public class C { }",
"package p; public class Impl1 extends p.C { }",
"package p; public class Impl2 extends p.C { }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList("module-info.java:1:60: compiler.err.repeated.provides.for.service: p.C",
"1 error");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testOneImplementationsForServices(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p.Service1 with p.Impl; provides p.Service2 with p.Impl; }",
"package p; public interface Service1 { }",
"package p; public abstract class Service2 { }",
"package p; public class Impl extends p.Service2 implements p.Service1 { }");
new JavacTask(tb)
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.SUCCESS)
.writeAll();
}
@Test
public void testAbstractImplementation(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p1.C1 with p2.C2; }",
"package p1; public class C1 { }",
"package p2; public abstract class C2 extends p1.C1 { }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:34: compiler.err.service.implementation.is.abstract: p2.C2");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testInterfaceImplementation(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p1.Service with p2.Impl; }",
"package p1; public interface Service { }",
"package p2; public interface Impl extends p1.Service { }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:39: compiler.err.service.implementation.is.abstract: p2.Impl");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testProtectedImplementation(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p1.C1 with p2.C2; }",
"package p1; public class C1 { }",
"package p2; class C2 extends p1.C1 { }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList("module-info.java:1:34: compiler.err.not.def.public: p2.C2, p2",
"1 error");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testNoNoArgConstructor(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { uses p1.C1; provides p1.C1 with p2.C2; }",
"package p1; public class C1 { }",
"package p2; public class C2 extends p1.C1 { public C2(String str) { } }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:46: compiler.err.service.implementation.doesnt.have.a.no.args.constructor: p2.C2");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testPrivateNoArgConstructor(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { uses p1.C1; provides p1.C1 with p2.C2; }",
"package p1; public class C1 { }",
"package p2; public class C2 extends p1.C1 { private C2() { } }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:46: compiler.err.service.implementation.no.args.constructor.not.public: p2.C2");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testServiceIndirectlyImplemented(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p1.C1 with p2.C3; }",
"package p1; public class C1 { }",
"package p2; public class C2 extends p1.C1 { }",
"package p2; public class C3 extends p2.C2 { }");
new JavacTask(tb)
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.SUCCESS)
.writeAll();
}
@Test
public void testServiceImplementationInnerClass(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p1.C1 with p2.C2.Inner; }",
"package p1; public class C1 { }",
"package p2; public class C2 { public class Inner extends p1.C1 { } }");
List<String> output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList(
"module-info.java:1:37: compiler.err.service.implementation.is.inner: p2.C2.Inner");
if (!output.containsAll(expected)) {
throw new Exception("Expected output not found");
}
}
@Test
public void testServiceDefinitionInnerClass(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { provides p1.C1.InnerDefinition with p2.C2; }",
"package p1; public class C1 { public class InnerDefinition { } }",
"package p2; public class C2 extends p1.C1.InnerDefinition { public C2() { new p1.C1().super(); } }");
new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Expect.SUCCESS)
.writeAll();
}
@Test
public void testFactory(Path base) throws Exception {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m { exports p1; provides p1.C1 with p2.C2; }",
"package p1; public interface C1 { }",
"package p2; public class C2 { public static p1.C1 provider() { return null; } }");
new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
List<String> output;
List<String> expected;
tb.writeJavaFiles(src,
"package p2; public class C2 { public p1.C1 provider() { return null; } }");
output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:1:46: compiler.err.service.implementation.must.be.subtype.of.service.interface",
"1 error");
if (!expected.equals(output)) {
throw new Exception("Expected output not found. Output: " + output);
}
tb.writeJavaFiles(src,
"package p2; public class C2 { static p1.C1 provider() { return null; } }");
output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:1:46: compiler.err.service.implementation.must.be.subtype.of.service.interface",
"1 error");
if (!expected.equals(output)) {
throw new Exception("Expected output not found. Output: " + output);
}
tb.writeJavaFiles(src,
"package p2; public class C2 { public static Object provider() { return null; } }");
output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:1:46: compiler.err.service.implementation.provider.return.must.be.subtype.of.service.interface",
"1 error");
if (!expected.equals(output)) {
throw new Exception("Expected output not found. Output: " + output);
}
tb.writeJavaFiles(src,
"package p2; public class C2 { public static p1.C1 provider = new p1.C1() {}; }");
output = new JavacTask(tb)
.options("-XDrawDiagnostics")
.outdir(Files.createDirectories(base.resolve("classes")))
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:1:46: compiler.err.service.implementation.must.be.subtype.of.service.interface",
"1 error");
if (!expected.equals(output)) {
throw new Exception("Expected output not found. Output: " + output);
}
}
}
| gpl-2.0 |
mulkieran/blivet | blivet/tsort.py | 3455 | # tsort.py
# Topological sorting.
#
# Copyright (C) 2010 Red Hat, Inc.
#
# 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 General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Dave Lehman <dlehman@redhat.com>
#
class CyclicGraphError(Exception):
pass
def tsort(graph):
order = [] # sorted list of items
if not graph or not graph['items']:
return order
# determine which nodes have no incoming edges
roots = [n for n in graph['items'] if graph['incoming'][n] == 0]
if not roots:
raise CyclicGraphError("no root nodes")
visited = [] # list of nodes visited, for cycle detection
while roots:
# remove a root, add it to the order
root = roots.pop()
if root in visited:
raise CyclicGraphError("graph contains cycles")
visited.append(root)
order.append(root)
# remove each edge from the root to another node
for (parent, child) in [e for e in graph['edges'] if e[0] == root]:
graph['incoming'][child] -= 1
graph['edges'].remove((parent, child))
# if destination node is now a root, add it to roots
if graph['incoming'][child] == 0:
roots.append(child)
if len(graph['items']) != len(visited):
raise CyclicGraphError("graph contains cycles")
return order
def create_graph(items, edges):
""" Create a graph based on a list of items and a list of edges.
Arguments:
items - an iterable containing (hashable) items to sort
edges - an iterable containing (parent, child) edge pair tuples
Return Value:
The return value is a dictionary representing the directed graph.
It has three keys:
items is the same as the input argument of the same name
edges is the same as the input argument of the same name
incoming is a dict of incoming edge count hashed by item
"""
graph = {'items': [], # the items to sort
'edges': [], # partial order info: (parent, child) pairs
'incoming': {}} # incoming edge count for each item
graph['items'] = items
graph['edges'] = edges
for item in items:
graph['incoming'][item] = 0
for (_parent, child) in edges:
graph['incoming'][child] += 1
return graph
def main():
items = [5, 2, 3, 4, 1]
edges = [(1, 2), (2, 4), (4, 5), (3, 2)]
print(items)
print(edges)
graph = create_graph(items, edges)
print(tsort(graph))
if __name__ == "__main__":
main()
| gpl-2.0 |
wnsonsa/destin-foot | vendor/tedivm/stash-bundle/Tests/Adapters/DoctrineAdapterTest.php | 3072 | <?php
/*
* This file is part of the StashBundle package.
*
* (c) Josh Hall-Bachner <jhallbachner@gmail.com>
* (c) Robert Hafner <tedivm@tedivm.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tedivm\StashBundle\Tests\Adapters;
use Stash\Driver\Ephemeral;
use Tedivm\StashBundle\Service\CacheService;
use Tedivm\StashBundle\Service\CacheTracker;
use Tedivm\StashBundle\Adapters\DoctrineAdapter;
use Tedivm\StashBundle\Tests\ThirdParty\Doctrine\CacheTest;
/**
* Class DoctrineAdapterTest
* @package Tedivm\StashBundle\Tests\Adapters
* @author Josh Hall-Bachner <jhallbachner@gmail.com>
* @author Robert Hafner <tedivm@tedivm.com>
*/
class DoctrineAdapterTest extends CacheTest
{
protected $__driver;
public function SetUp()
{
if (!interface_exists('\\Doctrine\\Common\\Cache\\Cache')) {
$this->markTestSkipped('Test requires DoctrineCache');
}
}
public function testGetStatsWithoutTracker()
{
if (!isset($this->__driver)) {
$this->__driver = new Ephemeral(array());
}
$service = new CacheService('test', new Ephemeral(array()));
$adaptor = new DoctrineAdapter($service);
$stats = $adaptor->getStats();
$keys = array('memory_usage', 'memory_available', 'uptime', 'hits', 'misses');
foreach ($keys as $key) {
$this->assertArrayHasKey($key, $stats, 'getStats has ' . $key . ' key even without tracker.');
$this->assertEquals('NA', $stats[$key], 'getStats returns NA for key ' . $key . ' without tracker.');
}
}
public function testGetNamespace()
{
$service = $this->_getCacheDriver();
$this->assertEquals('', $service->getNamespace(), 'getNamespace returns empty string when no namespace is set.');
$service->setNamespace('TestNameSpace');
$this->assertEquals('TestNameSpace', $service->getNamespace(), 'getNamespace returns set namespace.');
}
/**
* @return \Doctrine\Common\Cache\CacheProvider
*/
protected function _getCacheDriver()
{
if (!isset($this->__driver)) {
$this->__driver = new Ephemeral(array());
}
$service = new CacheService('test', $this->__driver, new CacheTracker('test'));
$adaptor = new DoctrineAdapter($service);
return $adaptor;
}
/*
* These tests were originally put in the Doctrine provider to enforce
* bad/buggy behavior. The Stash Doctrine provider *does not* serve
* stale data, but works as it would be expected to. As such I've
* removed the test cases that attempt to enforce that.
*
* The only difference between this and the Doctrine behavior is that
* Stash will not serve stale data in cases were Doctrine's cache might.
*/
public function testDeleteAllAndNamespaceVersioningBetweenCaches()
{
}
public function testFlushAllAndNamespaceVersioningBetweenCaches()
{
}
}
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/vm/mlvm/indy/func/jvmti/share/IndyRedefineTest.java | 2456 | /*
* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package vm.mlvm.indy.func.jvmti.share;
import java.io.File;
import java.lang.reflect.Method;
import vm.mlvm.share.MlvmTest;
import vm.share.options.Option;
public class IndyRedefineTest extends MlvmTest {
@Option(name="dummyClassName", description="Redefined class FQDN")
private String dummyClassName = null;
private static final int CYCLES_COUNT = 2;
public boolean run() throws Throwable {
IndyRedefineClass.setRedefinedClassFileName(dummyClassName.replace('.', File.separatorChar));
IndyRedefineClass.setRedefineTriggerMethodName("redefineNow");
Class<?> dummyClass = Class.forName(dummyClassName);
Method mInvokeTarget = dummyClass.getDeclaredMethod("invokeTarget");
Method mIsRedefinedClass = dummyClass.getDeclaredMethod("isRedefinedClass");
for ( int i = 0; i < CYCLES_COUNT; i++ ) {
if ( ! (Boolean) mInvokeTarget.invoke(null) )
markTestFailed("Error: the original target method was called\n");
if ( ! (Boolean) mIsRedefinedClass.invoke(null) )
markTestFailed("Error: the class was not redefined\n");
}
if ( ! IndyRedefineClass.checkStatus() )
markTestFailed("Error: failures in native code. Please see verbose log");
return true;
}
public static void main(String[] args) {
MlvmTest.launch(args);
}
}
| gpl-2.0 |
marcel-dancak/QGIS | python/plugins/db_manager/db_plugins/postgis/plugins/versioning/dlg_versioning.py | 12091 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : Versioning plugin for DB Manager
Description : Set up versioning support for a table
Date : Mar 12, 2012
copyright : (C) 2012 by Giuseppe Sucameli
email : brush.tyler@gmail.com
Based on PG_Manager by Martin Dobias <wonder.sk@gmail.com> (GPLv2 license)
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QDialog, QDialogButtonBox, QMessageBox, QApplication
from .ui_DlgVersioning import Ui_DlgVersioning
from .....dlg_db_error import DlgDbError
from ....plugin import BaseError, Table
class DlgVersioning(QDialog, Ui_DlgVersioning):
def __init__(self, item, parent=None):
QDialog.__init__(self, parent)
self.item = item
self.setupUi(self)
self.db = self.item.database()
self.schemas = self.db.schemas()
self.hasSchemas = self.schemas is not None
self.buttonBox.accepted.connect(self.onOK)
self.buttonBox.helpRequested.connect(self.showHelp)
self.populateSchemas()
self.populateTables()
if isinstance(item, Table):
index = self.cboTable.findText(self.item.name)
if index >= 0:
self.cboTable.setCurrentIndex(index)
self.cboSchema.currentIndexChanged.connect(self.populateTables)
# updates of SQL window
self.cboSchema.currentIndexChanged.connect(self.updateSql)
self.cboTable.currentIndexChanged.connect(self.updateSql)
self.chkCreateCurrent.stateChanged.connect(self.updateSql)
self.editPkey.textChanged.connect(self.updateSql)
self.editStart.textChanged.connect(self.updateSql)
self.editEnd.textChanged.connect(self.updateSql)
self.editUser.textChanged.connect(self.updateSql)
self.updateSql()
def populateSchemas(self):
self.cboSchema.clear()
if not self.hasSchemas:
self.hideSchemas()
return
index = -1
for schema in self.schemas:
self.cboSchema.addItem(schema.name)
if hasattr(self.item, 'schema') and schema.name == self.item.schema().name:
index = self.cboSchema.count() - 1
self.cboSchema.setCurrentIndex(index)
def hideSchemas(self):
self.cboSchema.setEnabled(False)
def populateTables(self):
self.tables = []
schemas = self.db.schemas()
if schemas is not None:
schema_name = self.cboSchema.currentText()
matching_schemas = [x for x in schemas if x.name == schema_name]
tables = matching_schemas[0].tables() if len(matching_schemas) > 0 else []
else:
tables = self.db.tables()
self.cboTable.clear()
for table in tables:
if table.type == table.VectorType: # contains geometry column?
self.tables.append(table)
self.cboTable.addItem(table.name)
def get_escaped_name(self, schema, table, suffix):
name = self.db.connector.quoteId(u"%s%s" % (table, suffix))
schema_name = self.db.connector.quoteId(schema) if schema else None
return u"%s.%s" % (schema_name, name) if schema_name else name
def updateSql(self):
if self.cboTable.currentIndex() < 0 or len(self.tables) < self.cboTable.currentIndex():
return
self.table = self.tables[self.cboTable.currentIndex()]
self.schematable = self.table.quotedName()
self.current = self.chkCreateCurrent.isChecked()
self.colPkey = self.db.connector.quoteId(self.editPkey.text())
self.colStart = self.db.connector.quoteId(self.editStart.text())
self.colEnd = self.db.connector.quoteId(self.editEnd.text())
self.colUser = self.db.connector.quoteId(self.editUser.text())
self.columns = [self.db.connector.quoteId(x.name) for x in self.table.fields()]
self.colOrigPkey = None
for constr in self.table.constraints():
if constr.type == constr.TypePrimaryKey:
self.origPkeyName = self.db.connector.quoteId(constr.name)
self.colOrigPkey = [self.db.connector.quoteId(x_y[1].name) for x_y in iter(list(constr.fields().items()))]
break
if self.colOrigPkey is None:
self.txtSql.setPlainText("Table doesn't have a primary key!")
self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
return
elif len(self.colOrigPkey) > 1:
self.txtSql.setPlainText("Table has multicolumn primary key!")
self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
return
# take first (and only column of the pkey)
self.colOrigPkey = self.colOrigPkey[0]
# define view, function, rule and trigger names
self.view = self.get_escaped_name(self.table.schemaName(), self.table.name, "_current")
self.func_at_time = self.get_escaped_name(self.table.schemaName(), self.table.name, "_at_time")
self.func_update = self.get_escaped_name(self.table.schemaName(), self.table.name, "_update")
self.func_insert = self.get_escaped_name(self.table.schemaName(), self.table.name, "_insert")
self.rule_del = self.get_escaped_name(None, self.table.name, "_del")
self.trigger_update = self.get_escaped_name(None, self.table.name, "_update")
self.trigger_insert = self.get_escaped_name(None, self.table.name, "_insert")
sql = []
# modify table: add serial column, start time, end time
sql.append(self.sql_alterTable())
# add primary key to the table
sql.append(self.sql_setPkey())
sql.append(self.sql_currentView())
# add X_at_time, X_update, X_delete functions
sql.append(self.sql_functions())
# add insert, update trigger, delete rule
sql.append(self.sql_triggers())
# add _current view + updatable
# if self.current:
sql.append(self.sql_updatesView())
self.txtSql.setPlainText(u'\n\n'.join(sql))
self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
return sql
def showHelp(self):
helpText = u"""In this dialog you can set up versioning support for a table. The table will be modified so that all changes will be recorded: there will be a column with start time and end time. Every row will have its start time, end time is assigned when the feature gets deleted. When a row is modified, the original data is marked with end time and new row is created. With this system, it's possible to get back to state of the table any time in history. When selecting rows from the table, you will always have to specify at what time do you want the rows."""
QMessageBox.information(self, "Help", helpText)
def sql_alterTable(self):
return u"ALTER TABLE %s ADD %s serial, ADD %s timestamp, ADD %s timestamp, ADD %s varchar;" % (
self.schematable, self.colPkey, self.colStart, self.colEnd, self.colUser)
def sql_setPkey(self):
return u"ALTER TABLE %s DROP CONSTRAINT %s, ADD PRIMARY KEY (%s);" % (
self.schematable, self.origPkeyName, self.colPkey)
def sql_currentView(self):
cols = ",".join(self.columns)
return u"CREATE VIEW %(view)s AS SELECT %(cols)s FROM %(schematable)s WHERE %(end)s IS NULL;" % \
{'view': self.view, 'cols': cols, 'schematable': self.schematable, 'end': self.colEnd}
def sql_functions(self):
cols = ",".join(self.columns)
old_cols = ",".join([u"OLD." + x for x in self.columns])
sql = u"""
CREATE OR REPLACE FUNCTION %(func_at_time)s(timestamp)
RETURNS SETOF %(view)s AS
$$
SELECT %(cols)s FROM %(schematable)s WHERE
( SELECT CASE WHEN %(end)s IS NULL THEN (%(start)s <= $1) ELSE (%(start)s <= $1 AND %(end)s > $1) END );
$$
LANGUAGE 'sql';
CREATE OR REPLACE FUNCTION %(func_update)s()
RETURNS TRIGGER AS
$$
BEGIN
IF OLD.%(end)s IS NOT NULL THEN
RETURN NULL;
END IF;
IF NEW.%(end)s IS NULL THEN
INSERT INTO %(schematable)s (%(cols)s, %(start)s, %(end)s) VALUES (%(oldcols)s, OLD.%(start)s, current_timestamp);
NEW.%(start)s = current_timestamp;
NEW.%(user)s = current_user;
END IF;
RETURN NEW;
END;
$$
LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION %(func_insert)s()
RETURNS trigger AS
$$
BEGIN
if NEW.%(start)s IS NULL then
NEW.%(start)s = now();
NEW.%(end)s = null;
NEW.%(user)s = current_user;
end if;
RETURN NEW;
END;
$$
LANGUAGE 'plpgsql';""" % {'view': self.view, 'schematable': self.schematable, 'cols': cols, 'oldcols': old_cols,
'start': self.colStart, 'end': self.colEnd, 'user': self.colUser, 'func_at_time': self.func_at_time,
'func_update': self.func_update, 'func_insert': self.func_insert}
return sql
def sql_triggers(self):
return u"""
CREATE RULE %(rule_del)s AS ON DELETE TO %(schematable)s
DO INSTEAD UPDATE %(schematable)s SET %(end)s = current_timestamp WHERE %(pkey)s = OLD.%(pkey)s AND %(end)s IS NULL;
CREATE TRIGGER %(trigger_update)s BEFORE UPDATE ON %(schematable)s
FOR EACH ROW EXECUTE PROCEDURE %(func_update)s();
CREATE TRIGGER %(trigger_insert)s BEFORE INSERT ON %(schematable)s
FOR EACH ROW EXECUTE PROCEDURE %(func_insert)s();""" % \
{'rule_del': self.rule_del, 'trigger_update': self.trigger_update, 'trigger_insert': self.trigger_insert,
'func_update': self.func_update, 'func_insert': self.func_insert, 'schematable': self.schematable,
'pkey': self.colPkey, 'end': self.colEnd}
def sql_updatesView(self):
cols = ",".join(self.columns)
new_cols = ",".join([u"NEW." + x for x in self.columns])
assign_cols = ",".join([u"%s = NEW.%s" % (x, x) for x in self.columns])
return u"""
CREATE OR REPLACE RULE "_DELETE" AS ON DELETE TO %(view)s DO INSTEAD
DELETE FROM %(schematable)s WHERE %(origpkey)s = old.%(origpkey)s;
CREATE OR REPLACE RULE "_INSERT" AS ON INSERT TO %(view)s DO INSTEAD
INSERT INTO %(schematable)s (%(cols)s) VALUES (%(newcols)s) RETURNING %(cols)s;
CREATE OR REPLACE RULE "_UPDATE" AS ON UPDATE TO %(view)s DO INSTEAD
UPDATE %(schematable)s SET %(assign)s WHERE %(origpkey)s = NEW.%(origpkey)s;""" % {'view': self.view,
'schematable': self.schematable,
'cols': cols, 'newcols': new_cols,
'assign': assign_cols,
'origpkey': self.colOrigPkey}
def onOK(self):
# execute and commit the code
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
sql = u"\n".join(self.updateSql())
self.db.connector._execute_and_commit(sql)
except BaseError as e:
DlgDbError.showError(e, self)
return
finally:
QApplication.restoreOverrideCursor()
QMessageBox.information(self, "DB Manager", "Versioning was successfully created.")
self.accept()
| gpl-2.0 |
stweil/Froxlor | lib/functions/filedir/function.makeChownWithNewStats.php | 1435 | <?php
/**
* This file is part of the Froxlor project.
* Copyright (c) 2010 the Froxlor Team (see authors).
*
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code. You can also view the
* COPYING file online at http://files.froxlor.org/misc/COPYING.txt
*
* @copyright (c) the authors
* @author Froxlor team <team@froxlor.org> (2010-)
* @license GPLv2 http://files.froxlor.org/misc/COPYING.txt
* @package Functions
*
*/
/**
* chowns either awstats or webalizer folder,
* either with webserver-user or - if fcgid
* is used - the customers name, #258
*
* @param array $row array if panel_customers
*
* @return void
*/
function makeChownWithNewStats($row) {
// get correct user
if ((Settings::Get('system.mod_fcgid') == '1' || Settings::Get('phpfpm.enabled') == '1')
&& isset($row['deactivated'])
&& $row['deactivated'] == '0'
) {
$user = $row['loginname'];
$group = $row['loginname'];
} else {
$user = $row['guid'];
$group = $row['guid'];
}
// get correct directory
$dir = $row['documentroot'];
if (Settings::Get('system.awstats_enabled') == '1') {
$dir .= '/awstats/';
} else {
$dir .= '/webalizer/';
}
// only run chown if directory exists
if (file_exists($dir)) {
// run chown
safe_exec('chown -R '.escapeshellarg($user).':'.escapeshellarg($group).' '.escapeshellarg(makeCorrectDir($dir)));
}
}
| gpl-2.0 |
alexkasko/openjdk-icedtea7 | jdk/src/share/classes/sun/security/provider/certpath/ReverseBuilder.java | 20065 | /*
* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.provider.certpath;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Principal;
import java.security.cert.CertificateException;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.PKIXCertPathChecker;
import java.security.cert.PKIXParameters;
import java.security.cert.PKIXReason;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.security.cert.X509CertSelector;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import javax.security.auth.x500.X500Principal;
import sun.security.util.Debug;
import sun.security.x509.Extension;
import sun.security.x509.PKIXExtensions;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.PolicyMappingsExtension;
/**
* This class represents a reverse builder, which is able to retrieve
* matching certificates from CertStores and verify a particular certificate
* against a ReverseState.
*
* @since 1.4
* @author Sean Mullan
* @author Yassir Elley
*/
class ReverseBuilder extends Builder {
private Debug debug = Debug.getInstance("certpath");
Set<String> initPolicies;
/**
* Initialize the builder with the input parameters.
*
* @param params the parameter set used to build a certification path
*/
ReverseBuilder(PKIXBuilderParameters buildParams,
X500Principal targetSubjectDN) {
super(buildParams, targetSubjectDN);
Set<String> initialPolicies = buildParams.getInitialPolicies();
initPolicies = new HashSet<String>();
if (initialPolicies.isEmpty()) {
// if no initialPolicies are specified by user, set
// initPolicies to be anyPolicy by default
initPolicies.add(PolicyChecker.ANY_POLICY);
} else {
for (String policy : initialPolicies) {
initPolicies.add(policy);
}
}
}
/**
* Retrieves all certs from the specified CertStores that satisfy the
* requirements specified in the parameters and the current
* PKIX state (name constraints, policy constraints, etc).
*
* @param currentState the current state.
* Must be an instance of <code>ReverseState</code>
* @param certStores list of CertStores
*/
Collection<X509Certificate> getMatchingCerts
(State currState, List<CertStore> certStores)
throws CertStoreException, CertificateException, IOException
{
ReverseState currentState = (ReverseState) currState;
if (debug != null)
debug.println("In ReverseBuilder.getMatchingCerts.");
/*
* The last certificate could be an EE or a CA certificate
* (we may be building a partial certification path or
* establishing trust in a CA).
*
* Try the EE certs before the CA certs. It will be more
* common to build a path to an end entity.
*/
Collection<X509Certificate> certs =
getMatchingEECerts(currentState, certStores);
certs.addAll(getMatchingCACerts(currentState, certStores));
return certs;
}
/*
* Retrieves all end-entity certificates which satisfy constraints
* and requirements specified in the parameters and PKIX state.
*/
private Collection<X509Certificate> getMatchingEECerts
(ReverseState currentState, List<CertStore> certStores)
throws CertStoreException, CertificateException, IOException {
/*
* Compose a CertSelector to filter out
* certs which do not satisfy requirements.
*
* First, retrieve clone of current target cert constraints,
* and then add more selection criteria based on current validation state.
*/
X509CertSelector sel = (X509CertSelector) targetCertConstraints.clone();
/*
* Match on issuer (subject of previous cert)
*/
sel.setIssuer(currentState.subjectDN);
/*
* Match on certificate validity date.
*/
sel.setCertificateValid(date);
/*
* Policy processing optimizations
*/
if (currentState.explicitPolicy == 0)
sel.setPolicy(getMatchingPolicies());
/*
* If previous cert has a subject key identifier extension,
* use it to match on authority key identifier extension.
*/
/*if (currentState.subjKeyId != null) {
AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension(
(KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID),
null, null);
sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue());
}*/
/*
* Require EE certs
*/
sel.setBasicConstraints(-2);
/* Retrieve matching certs from CertStores */
HashSet<X509Certificate> eeCerts = new HashSet<X509Certificate>();
addMatchingCerts(sel, certStores, eeCerts, true);
if (debug != null) {
debug.println("ReverseBuilder.getMatchingEECerts got " + eeCerts.size()
+ " certs.");
}
return eeCerts;
}
/*
* Retrieves all CA certificates which satisfy constraints
* and requirements specified in the parameters and PKIX state.
*/
private Collection<X509Certificate> getMatchingCACerts
(ReverseState currentState, List<CertStore> certStores)
throws CertificateException, CertStoreException, IOException {
/*
* Compose a CertSelector to filter out
* certs which do not satisfy requirements.
*/
X509CertSelector sel = new X509CertSelector();
/*
* Match on issuer (subject of previous cert)
*/
sel.setIssuer(currentState.subjectDN);
/*
* Match on certificate validity date.
*/
sel.setCertificateValid(date);
/*
* Match on target subject name (checks that current cert's
* name constraints permit it to certify target).
* (4 is the integer type for DIRECTORY name).
*/
sel.addPathToName(4, targetCertConstraints.getSubjectAsBytes());
/*
* Policy processing optimizations
*/
if (currentState.explicitPolicy == 0)
sel.setPolicy(getMatchingPolicies());
/*
* If previous cert has a subject key identifier extension,
* use it to match on authority key identifier extension.
*/
/*if (currentState.subjKeyId != null) {
AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension(
(KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID),
null, null);
sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue());
}*/
/*
* Require CA certs
*/
sel.setBasicConstraints(0);
/* Retrieve matching certs from CertStores */
ArrayList<X509Certificate> reverseCerts =
new ArrayList<X509Certificate>();
addMatchingCerts(sel, certStores, reverseCerts, true);
/* Sort remaining certs using name constraints */
Collections.sort(reverseCerts, new PKIXCertComparator());
if (debug != null)
debug.println("ReverseBuilder.getMatchingCACerts got " +
reverseCerts.size() + " certs.");
return reverseCerts;
}
/*
* This inner class compares 2 PKIX certificates according to which
* should be tried first when building a path to the target. For
* now, the algorithm is to look at name constraints in each cert and those
* which constrain the path closer to the target should be
* ranked higher. Later, we may want to consider other components,
* such as key identifiers.
*/
class PKIXCertComparator implements Comparator<X509Certificate> {
private Debug debug = Debug.getInstance("certpath");
public int compare(X509Certificate cert1, X509Certificate cert2) {
/*
* if either cert certifies the target, always
* put at head of list.
*/
if (cert1.getSubjectX500Principal().equals(targetSubjectDN)) {
return -1;
}
if (cert2.getSubjectX500Principal().equals(targetSubjectDN)) {
return 1;
}
int targetDist1;
int targetDist2;
try {
X500Name targetSubjectName = X500Name.asX500Name(targetSubjectDN);
targetDist1 = Builder.targetDistance(
null, cert1, targetSubjectName);
targetDist2 = Builder.targetDistance(
null, cert2, targetSubjectName);
} catch (IOException e) {
if (debug != null) {
debug.println("IOException in call to Builder.targetDistance");
e.printStackTrace();
}
throw new ClassCastException
("Invalid target subject distinguished name");
}
if (targetDist1 == targetDist2)
return 0;
if (targetDist1 == -1)
return 1;
if (targetDist1 < targetDist2)
return -1;
return 1;
}
}
/**
* Verifies a matching certificate.
*
* This method executes any of the validation steps in the PKIX path validation
* algorithm which were not satisfied via filtering out non-compliant
* certificates with certificate matching rules.
*
* If the last certificate is being verified (the one whose subject
* matches the target subject, then the steps in Section 6.1.4 of the
* Certification Path Validation algorithm are NOT executed,
* regardless of whether or not the last cert is an end-entity
* cert or not. This allows callers to certify CA certs as
* well as EE certs.
*
* @param cert the certificate to be verified
* @param currentState the current state against which the cert is verified
* @param certPathList the certPathList generated thus far
*/
void verifyCert(X509Certificate cert, State currState,
List<X509Certificate> certPathList)
throws GeneralSecurityException
{
if (debug != null) {
debug.println("ReverseBuilder.verifyCert(SN: "
+ Debug.toHexString(cert.getSerialNumber())
+ "\n Subject: " + cert.getSubjectX500Principal() + ")");
}
ReverseState currentState = (ReverseState) currState;
/* we don't perform any validation of the trusted cert */
if (currentState.isInitial()) {
return;
}
// Don't bother to verify untrusted certificate more.
currentState.untrustedChecker.check(cert,
Collections.<String>emptySet());
/*
* check for looping - abort a loop if
* ((we encounter the same certificate twice) AND
* ((policyMappingInhibited = true) OR (no policy mapping
* extensions can be found between the occurences of the same
* certificate)))
* in order to facilitate the check to see if there are
* any policy mapping extensions found between the occurences
* of the same certificate, we reverse the certpathlist first
*/
if ((certPathList != null) && (!certPathList.isEmpty())) {
List<X509Certificate> reverseCertList =
new ArrayList<X509Certificate>();
for (X509Certificate c : certPathList) {
reverseCertList.add(0, c);
}
boolean policyMappingFound = false;
for (X509Certificate cpListCert : reverseCertList) {
X509CertImpl cpListCertImpl = X509CertImpl.toImpl(cpListCert);
PolicyMappingsExtension policyMappingsExt =
cpListCertImpl.getPolicyMappingsExtension();
if (policyMappingsExt != null) {
policyMappingFound = true;
}
if (debug != null)
debug.println("policyMappingFound = " + policyMappingFound);
if (cert.equals(cpListCert)){
if ((buildParams.isPolicyMappingInhibited()) ||
(!policyMappingFound)){
if (debug != null)
debug.println("loop detected!!");
throw new CertPathValidatorException("loop detected");
}
}
}
}
/* check if target cert */
boolean finalCert = cert.getSubjectX500Principal().equals(targetSubjectDN);
/* check if CA cert */
boolean caCert = (cert.getBasicConstraints() != -1 ? true : false);
/* if there are more certs to follow, verify certain constraints */
if (!finalCert) {
/* check if CA cert */
if (!caCert)
throw new CertPathValidatorException("cert is NOT a CA cert");
/* If the certificate was not self-issued, verify that
* remainingCerts is greater than zero
*/
if ((currentState.remainingCACerts <= 0) && !X509CertImpl.isSelfIssued(cert)) {
throw new CertPathValidatorException
("pathLenConstraint violated, path too long", null,
null, -1, PKIXReason.PATH_TOO_LONG);
}
/*
* Check keyUsage extension (only if CA cert and not final cert)
*/
KeyChecker.verifyCAKeyUsage(cert);
} else {
/*
* If final cert, check that it satisfies specified target
* constraints
*/
if (targetCertConstraints.match(cert) == false) {
throw new CertPathValidatorException("target certificate " +
"constraints check failed");
}
}
/*
* Check revocation.
*/
if (buildParams.isRevocationEnabled()) {
currentState.crlChecker.check(cert,
currentState.pubKey,
currentState.crlSign);
}
/* Check name constraints if this is not a self-issued cert */
if (finalCert || !X509CertImpl.isSelfIssued(cert)){
if (currentState.nc != null){
try {
if (!currentState.nc.verify(cert)){
throw new CertPathValidatorException
("name constraints check failed", null, null, -1,
PKIXReason.INVALID_NAME);
}
} catch (IOException ioe){
throw new CertPathValidatorException(ioe);
}
}
}
/*
* Check policy
*/
X509CertImpl certImpl = X509CertImpl.toImpl(cert);
currentState.rootNode = PolicyChecker.processPolicies
(currentState.certIndex, initPolicies,
currentState.explicitPolicy, currentState.policyMapping,
currentState.inhibitAnyPolicy,
buildParams.getPolicyQualifiersRejected(), currentState.rootNode,
certImpl, finalCert);
/*
* Check CRITICAL private extensions
*/
Set<String> unresolvedCritExts = cert.getCriticalExtensionOIDs();
if (unresolvedCritExts == null) {
unresolvedCritExts = Collections.<String>emptySet();
}
/*
* Check that the signature algorithm is not disabled.
*/
currentState.algorithmChecker.check(cert, unresolvedCritExts);
for (PKIXCertPathChecker checker : currentState.userCheckers) {
checker.check(cert, unresolvedCritExts);
}
/*
* Look at the remaining extensions and remove any ones we have
* already checked. If there are any left, throw an exception!
*/
if (!unresolvedCritExts.isEmpty()) {
unresolvedCritExts.remove(PKIXExtensions.BasicConstraints_Id.toString());
unresolvedCritExts.remove(PKIXExtensions.NameConstraints_Id.toString());
unresolvedCritExts.remove(PKIXExtensions.CertificatePolicies_Id.toString());
unresolvedCritExts.remove(PKIXExtensions.PolicyMappings_Id.toString());
unresolvedCritExts.remove(PKIXExtensions.PolicyConstraints_Id.toString());
unresolvedCritExts.remove(PKIXExtensions.InhibitAnyPolicy_Id.toString());
unresolvedCritExts.remove(PKIXExtensions.SubjectAlternativeName_Id.toString());
unresolvedCritExts.remove(PKIXExtensions.KeyUsage_Id.toString());
unresolvedCritExts.remove(PKIXExtensions.ExtendedKeyUsage_Id.toString());
if (!unresolvedCritExts.isEmpty())
throw new CertPathValidatorException
("Unrecognized critical extension(s)", null, null, -1,
PKIXReason.UNRECOGNIZED_CRIT_EXT);
}
/*
* Check signature.
*/
if (buildParams.getSigProvider() != null) {
cert.verify(currentState.pubKey, buildParams.getSigProvider());
} else {
cert.verify(currentState.pubKey);
}
}
/**
* Verifies whether the input certificate completes the path.
* This checks whether the cert is the target certificate.
*
* @param cert the certificate to test
* @return a boolean value indicating whether the cert completes the path.
*/
boolean isPathCompleted(X509Certificate cert) {
return cert.getSubjectX500Principal().equals(targetSubjectDN);
}
/** Adds the certificate to the certPathList
*
* @param cert the certificate to be added
* @param certPathList the certification path list
*/
void addCertToPath(X509Certificate cert,
LinkedList<X509Certificate> certPathList) {
certPathList.addLast(cert);
}
/** Removes final certificate from the certPathList
*
* @param certPathList the certification path list
*/
void removeFinalCertFromPath(LinkedList<X509Certificate> certPathList) {
certPathList.removeLast();
}
}
| gpl-2.0 |
odomin2/ait642-Dominguez-project2- | Task 13 Detect Desing Smells/Monopoly/src/edu/towson/cis/cosc603/project2/monopoly/gui/TestDiceRollDialog.java | 2533 | package edu.towson.cis.cosc603.project2.monopoly.gui;
import java.awt.Container;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class TestDiceRollDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton btnOK, btnCancel;
private JTextField txtDiceRoll;
private int[] diceRoll;
public TestDiceRollDialog(Frame parent) {
super(parent);
setTitle("Dice Roll Dialog");
txtDiceRoll = new JTextField(2);
btnOK = new JButton("OK");
btnCancel = new JButton("Cancel");
setModal(true);
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(2, 2));
contentPane.add(new JLabel("Amount"));
contentPane.add(txtDiceRoll);
contentPane.add(btnOK);
contentPane.add(btnCancel);
btnCancel.addActionListener(new ActionListener(){
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
TestDiceRollDialog.this.hide();
diceRoll = new int[2];
diceRoll[0] = 0;
diceRoll[1] = 0;
}
});
btnOK.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
int amount = 0;
try{
amount = Integer.parseInt(txtDiceRoll.getText());
} catch(NumberFormatException nfe) {
JOptionPane.showMessageDialog(TestDiceRollDialog.this,
"Amount should be an integer", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(amount > 0) {
diceRoll = new int[2];
if((amount % 2) == 0) {
diceRoll[0] = amount / 2;
diceRoll[1] = amount / 2;
}
else {
diceRoll[0] = amount / 2;
diceRoll[1] = (amount / 2) + 1;
}
}
hide();
}
});
this.pack();
}
public int[] getDiceRoll() {
return diceRoll;
}
}
| gpl-3.0 |
chirag52999/thinkAgain | node_modules/grunt-bower-installer/node_modules/bower/node_modules/inquirer/node_modules/cli-color/node_modules/es5-ext/test/number/to-integer.js | 271 | 'use strict';
module.exports = function (t, a) {
a(t({}), 0, "NaN");
a(t(20), 20, "Positive integer");
a(t('-20'), -20, "String negative integer");
a(t(Infinity), Infinity, "Infinity");
a(t(15.343), 15, "Float");
a(t(-15.343), -15, "Negative float");
};
| gpl-3.0 |
IronBrushTattoo/cj | packages/traveling-ruby/packaging/vendor/ruby/2.1.0/gems/chronic-0.10.2/lib/chronic/pointer.rb | 734 | module Chronic
class Pointer < Tag
# Scan an Array of Token objects and apply any necessary Pointer
# tags to each token.
#
# tokens - An Array of tokens to scan.
# options - The Hash of options specified in Chronic::parse.
#
# Returns an Array of tokens.
def self.scan(tokens, options)
tokens.each do |token|
if t = scan_for_all(token) then token.tag(t) end
end
end
# token - The Token object we want to scan.
#
# Returns a new Pointer object.
def self.scan_for_all(token)
scan_for token, self,
{
/\bpast\b/ => :past,
/\b(?:future|in)\b/ => :future,
}
end
def to_s
'pointer-' << @type.to_s
end
end
end
| gpl-3.0 |
rjnl/moodle26 | mod/assign/classes/event/statement_accepted.php | 2663 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* mod_assign statement accepted event.
*
* @package mod_assign
* @copyright 2013 Frédéric Massart
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_assign\event;
defined('MOODLE_INTERNAL') || die();
/**
* mod_assign statement accepted event class.
*
* @package mod_assign
* @since Moodle 2.6
* @copyright 2013 Frédéric Massart
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class statement_accepted extends \core\event\base {
/**
* Legacy log data.
*
* @var array
*/
protected $legacylogdata;
/**
* Returns description of what happened.
*
* @return string
*/
public function get_description() {
return "The user {$this->userid} has accepted the statement of the submission {$this->objectid}.";
}
/**
* Return legacy data for add_to_log().
*
* @return array
*/
protected function get_legacy_logdata() {
return $this->legacylogdata;
}
/**
* Return localised event name.
*
* @return string
*/
public static function get_name() {
return get_string('event_statement_accepted', 'mod_assign');
}
/**
* Get URL related to the action.
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/mod/assign/view.php', array('id' => $this->context->instanceid));
}
/**
* Init method.
*
* @return void
*/
protected function init() {
$this->data['crud'] = 'r';
$this->data['level'] = self::LEVEL_PARTICIPATING;
$this->data['objecttable'] = 'assign_submission';
}
/**
* Sets the legacy event log data.
*
* @param stdClass $legacylogdata legacy log data.
* @return void
*/
public function set_legacy_logdata($legacylogdata) {
$this->legacylogdata = $legacylogdata;
}
}
| gpl-3.0 |
HexHive/datashield | compiler/llvm/projects/compiler-rt/test/asan/TestCases/Windows/aligned_mallocs.cc | 624 | // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: %run %t
#include <windows.h>
#define CHECK_ALIGNED(ptr,alignment) \
do { \
if (((uintptr_t)(ptr) % (alignment)) != 0) \
return __LINE__; \
} \
while(0)
int main(void) {
int *p = (int*)_aligned_malloc(1024 * sizeof(int), 32);
CHECK_ALIGNED(p, 32);
p[512] = 0;
_aligned_free(p);
p = (int*)_aligned_malloc(128, 128);
CHECK_ALIGNED(p, 128);
p = (int*)_aligned_realloc(p, 2048 * sizeof(int), 128);
CHECK_ALIGNED(p, 128);
p[1024] = 0;
if (_aligned_msize(p, 128, 0) != 2048 * sizeof(int))
return __LINE__;
_aligned_free(p);
return 0;
}
| gpl-3.0 |
ta2-1/pootle | pootle/static/js/admin/AdminRouter.js | 464 | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import Backbone from 'backbone';
const AdminRouter = Backbone.Router.extend({
routes: {
'?q=:searchQuery': 'main',
'': 'main',
':id(/)': 'edit',
},
});
export default AdminRouter;
| gpl-3.0 |
skippy/vault | vault/dynamic_system_view.go | 1941 | package vault
import (
"time"
"github.com/hashicorp/vault/logical"
)
type dynamicSystemView struct {
core *Core
mountEntry *MountEntry
}
func (d dynamicSystemView) DefaultLeaseTTL() time.Duration {
def, _ := d.fetchTTLs()
return def
}
func (d dynamicSystemView) MaxLeaseTTL() time.Duration {
_, max := d.fetchTTLs()
return max
}
func (d dynamicSystemView) SudoPrivilege(path string, token string) bool {
// Resolve the token policy
te, err := d.core.tokenStore.Lookup(token)
if err != nil {
d.core.logger.Error("core: failed to lookup token", "error", err)
return false
}
// Ensure the token is valid
if te == nil {
d.core.logger.Error("entry not found for given token")
return false
}
// Construct the corresponding ACL object
acl, err := d.core.policyStore.ACL(te.Policies...)
if err != nil {
d.core.logger.Error("failed to retrieve ACL for token's policies", "token_policies", te.Policies, "error", err)
return false
}
// The operation type isn't important here as this is run from a path the
// user has already been given access to; we only care about whether they
// have sudo
_, rootPrivs := acl.AllowOperation(logical.ReadOperation, path)
return rootPrivs
}
// TTLsByPath returns the default and max TTLs corresponding to a particular
// mount point, or the system default
func (d dynamicSystemView) fetchTTLs() (def, max time.Duration) {
def = d.core.defaultLeaseTTL
max = d.core.maxLeaseTTL
if d.mountEntry.Config.DefaultLeaseTTL != 0 {
def = d.mountEntry.Config.DefaultLeaseTTL
}
if d.mountEntry.Config.MaxLeaseTTL != 0 {
max = d.mountEntry.Config.MaxLeaseTTL
}
return
}
// Tainted indicates that the mount is in the process of being removed
func (d dynamicSystemView) Tainted() bool {
return d.mountEntry.Tainted
}
// CachingDisabled indicates whether to use caching behavior
func (d dynamicSystemView) CachingDisabled() bool {
return d.core.cachingDisabled
}
| mpl-2.0 |
Acidburn0zzz/servo | tests/wpt/web-platform-tests/html/canvas/offscreen/drawing-rectangles-to-the-canvas/2d.strokeRect.globalcomposite.worker.js | 829 | // DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py.
// OffscreenCanvas test in a worker:2d.strokeRect.globalcomposite
// Description:strokeRect is not affected by globalCompositeOperation
// Note:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");
var t = async_test("strokeRect is not affected by globalCompositeOperation");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
ctx.globalCompositeOperation = 'source-in';
ctx.strokeStyle = '#f00';
ctx.lineWidth = 50;
ctx.strokeRect(25, 24, 50, 2);
_assertPixel(offscreenCanvas, 50,25, 0,0,0,0, "50,25", "0,0,0,0");
t.done();
});
done();
| mpl-2.0 |
tas50/packer | vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go | 21335 | package s3manager
import (
"bytes"
"fmt"
"io"
"sort"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
)
// MaxUploadParts is the maximum allowed number of parts in a multi-part upload
// on Amazon S3.
const MaxUploadParts = 10000
// MinUploadPartSize is the minimum allowed part size when uploading a part to
// Amazon S3.
const MinUploadPartSize int64 = 1024 * 1024 * 5
// DefaultUploadPartSize is the default part size to buffer chunks of a
// payload into.
const DefaultUploadPartSize = MinUploadPartSize
// DefaultUploadConcurrency is the default number of goroutines to spin up when
// using Upload().
const DefaultUploadConcurrency = 5
// A MultiUploadFailure wraps a failed S3 multipart upload. An error returned
// will satisfy this interface when a multi part upload failed to upload all
// chucks to S3. In the case of a failure the UploadID is needed to operate on
// the chunks, if any, which were uploaded.
//
// Example:
//
// u := s3manager.NewUploader(opts)
// output, err := u.upload(input)
// if err != nil {
// if multierr, ok := err.(s3manager.MultiUploadFailure); ok {
// // Process error and its associated uploadID
// fmt.Println("Error:", multierr.Code(), multierr.Message(), multierr.UploadID())
// } else {
// // Process error generically
// fmt.Println("Error:", err.Error())
// }
// }
//
type MultiUploadFailure interface {
awserr.Error
// Returns the upload id for the S3 multipart upload that failed.
UploadID() string
}
// So that the Error interface type can be included as an anonymous field
// in the multiUploadError struct and not conflict with the error.Error() method.
type awsError awserr.Error
// A multiUploadError wraps the upload ID of a failed s3 multipart upload.
// Composed of BaseError for code, message, and original error
//
// Should be used for an error that occurred failing a S3 multipart upload,
// and a upload ID is available. If an uploadID is not available a more relevant
type multiUploadError struct {
awsError
// ID for multipart upload which failed.
uploadID string
}
// Error returns the string representation of the error.
//
// See apierr.BaseError ErrorWithExtra for output format
//
// Satisfies the error interface.
func (m multiUploadError) Error() string {
extra := fmt.Sprintf("upload id: %s", m.uploadID)
return awserr.SprintError(m.Code(), m.Message(), extra, m.OrigErr())
}
// String returns the string representation of the error.
// Alias for Error to satisfy the stringer interface.
func (m multiUploadError) String() string {
return m.Error()
}
// UploadID returns the id of the S3 upload which failed.
func (m multiUploadError) UploadID() string {
return m.uploadID
}
// UploadOutput represents a response from the Upload() call.
type UploadOutput struct {
// The URL where the object was uploaded to.
Location string
// The version of the object that was uploaded. Will only be populated if
// the S3 Bucket is versioned. If the bucket is not versioned this field
// will not be set.
VersionID *string
// The ID for a multipart upload to S3. In the case of an error the error
// can be cast to the MultiUploadFailure interface to extract the upload ID.
UploadID string
}
// WithUploaderRequestOptions appends to the Uploader's API request options.
func WithUploaderRequestOptions(opts ...request.Option) func(*Uploader) {
return func(u *Uploader) {
u.RequestOptions = append(u.RequestOptions, opts...)
}
}
// The Uploader structure that calls Upload(). It is safe to call Upload()
// on this structure for multiple objects and across concurrent goroutines.
// Mutating the Uploader's properties is not safe to be done concurrently.
type Uploader struct {
// The buffer size (in bytes) to use when buffering data into chunks and
// sending them as parts to S3. The minimum allowed part size is 5MB, and
// if this value is set to zero, the DefaultUploadPartSize value will be used.
PartSize int64
// The number of goroutines to spin up in parallel per call to Upload when
// sending parts. If this is set to zero, the DefaultUploadConcurrency value
// will be used.
//
// The concurrency pool is not shared between calls to Upload.
Concurrency int
// Setting this value to true will cause the SDK to avoid calling
// AbortMultipartUpload on a failure, leaving all successfully uploaded
// parts on S3 for manual recovery.
//
// Note that storing parts of an incomplete multipart upload counts towards
// space usage on S3 and will add additional costs if not cleaned up.
LeavePartsOnError bool
// MaxUploadParts is the max number of parts which will be uploaded to S3.
// Will be used to calculate the partsize of the object to be uploaded.
// E.g: 5GB file, with MaxUploadParts set to 100, will upload the file
// as 100, 50MB parts.
// With a limited of s3.MaxUploadParts (10,000 parts).
//
// Defaults to package const's MaxUploadParts value.
MaxUploadParts int
// The client to use when uploading to S3.
S3 s3iface.S3API
// List of request options that will be passed down to individual API
// operation requests made by the uploader.
RequestOptions []request.Option
}
// NewUploader creates a new Uploader instance to upload objects to S3. Pass In
// additional functional options to customize the uploader's behavior. Requires a
// client.ConfigProvider in order to create a S3 service client. The session.Session
// satisfies the client.ConfigProvider interface.
//
// Example:
// // The session the S3 Uploader will use
// sess := session.Must(session.NewSession())
//
// // Create an uploader with the session and default options
// uploader := s3manager.NewUploader(sess)
//
// // Create an uploader with the session and custom options
// uploader := s3manager.NewUploader(session, func(u *s3manager.Uploader) {
// u.PartSize = 64 * 1024 * 1024 // 64MB per part
// })
func NewUploader(c client.ConfigProvider, options ...func(*Uploader)) *Uploader {
u := &Uploader{
S3: s3.New(c),
PartSize: DefaultUploadPartSize,
Concurrency: DefaultUploadConcurrency,
LeavePartsOnError: false,
MaxUploadParts: MaxUploadParts,
}
for _, option := range options {
option(u)
}
return u
}
// NewUploaderWithClient creates a new Uploader instance to upload objects to S3. Pass in
// additional functional options to customize the uploader's behavior. Requires
// a S3 service client to make S3 API calls.
//
// Example:
// // The session the S3 Uploader will use
// sess := session.Must(session.NewSession())
//
// // S3 service client the Upload manager will use.
// s3Svc := s3.New(sess)
//
// // Create an uploader with S3 client and default options
// uploader := s3manager.NewUploaderWithClient(s3Svc)
//
// // Create an uploader with S3 client and custom options
// uploader := s3manager.NewUploaderWithClient(s3Svc, func(u *s3manager.Uploader) {
// u.PartSize = 64 * 1024 * 1024 // 64MB per part
// })
func NewUploaderWithClient(svc s3iface.S3API, options ...func(*Uploader)) *Uploader {
u := &Uploader{
S3: svc,
PartSize: DefaultUploadPartSize,
Concurrency: DefaultUploadConcurrency,
LeavePartsOnError: false,
MaxUploadParts: MaxUploadParts,
}
for _, option := range options {
option(u)
}
return u
}
// Upload uploads an object to S3, intelligently buffering large files into
// smaller chunks and sending them in parallel across multiple goroutines. You
// can configure the buffer size and concurrency through the Uploader's parameters.
//
// Additional functional options can be provided to configure the individual
// upload. These options are copies of the Uploader instance Upload is called from.
// Modifying the options will not impact the original Uploader instance.
//
// Use the WithUploaderRequestOptions helper function to pass in request
// options that will be applied to all API operations made with this uploader.
//
// It is safe to call this method concurrently across goroutines.
//
// Example:
// // Upload input parameters
// upParams := &s3manager.UploadInput{
// Bucket: &bucketName,
// Key: &keyName,
// Body: file,
// }
//
// // Perform an upload.
// result, err := uploader.Upload(upParams)
//
// // Perform upload with options different than the those in the Uploader.
// result, err := uploader.Upload(upParams, func(u *s3manager.Uploader) {
// u.PartSize = 10 * 1024 * 1024 // 10MB part size
// u.LeavePartsOnError = true // Don't delete the parts if the upload fails.
// })
func (u Uploader) Upload(input *UploadInput, options ...func(*Uploader)) (*UploadOutput, error) {
return u.UploadWithContext(aws.BackgroundContext(), input, options...)
}
// UploadWithContext uploads an object to S3, intelligently buffering large
// files into smaller chunks and sending them in parallel across multiple
// goroutines. You can configure the buffer size and concurrency through the
// Uploader's parameters.
//
// UploadWithContext is the same as Upload with the additional support for
// Context input parameters. The Context must not be nil. A nil Context will
// cause a panic. Use the context to add deadlining, timeouts, etc. The
// UploadWithContext may create sub-contexts for individual underlying requests.
//
// Additional functional options can be provided to configure the individual
// upload. These options are copies of the Uploader instance Upload is called from.
// Modifying the options will not impact the original Uploader instance.
//
// Use the WithUploaderRequestOptions helper function to pass in request
// options that will be applied to all API operations made with this uploader.
//
// It is safe to call this method concurrently across goroutines.
func (u Uploader) UploadWithContext(ctx aws.Context, input *UploadInput, opts ...func(*Uploader)) (*UploadOutput, error) {
i := uploader{in: input, cfg: u, ctx: ctx}
for _, opt := range opts {
opt(&i.cfg)
}
i.cfg.RequestOptions = append(i.cfg.RequestOptions, request.WithAppendUserAgent("S3Manager"))
return i.upload()
}
// UploadWithIterator will upload a batched amount of objects to S3. This operation uses
// the iterator pattern to know which object to upload next. Since this is an interface this
// allows for custom defined functionality.
//
// Example:
// svc:= s3manager.NewUploader(sess)
//
// objects := []BatchUploadObject{
// {
// Object: &s3manager.UploadInput {
// Key: aws.String("key"),
// Bucket: aws.String("bucket"),
// },
// },
// }
//
// iter := &s3manager.UploadObjectsIterator{Objects: objects}
// if err := svc.UploadWithIterator(aws.BackgroundContext(), iter); err != nil {
// return err
// }
func (u Uploader) UploadWithIterator(ctx aws.Context, iter BatchUploadIterator, opts ...func(*Uploader)) error {
var errs []Error
for iter.Next() {
object := iter.UploadObject()
if _, err := u.UploadWithContext(ctx, object.Object, opts...); err != nil {
s3Err := Error{
OrigErr: err,
Bucket: object.Object.Bucket,
Key: object.Object.Key,
}
errs = append(errs, s3Err)
}
if object.After == nil {
continue
}
if err := object.After(); err != nil {
s3Err := Error{
OrigErr: err,
Bucket: object.Object.Bucket,
Key: object.Object.Key,
}
errs = append(errs, s3Err)
}
}
if len(errs) > 0 {
return NewBatchError("BatchedUploadIncomplete", "some objects have failed to upload.", errs)
}
return nil
}
// internal structure to manage an upload to S3.
type uploader struct {
ctx aws.Context
cfg Uploader
in *UploadInput
readerPos int64 // current reader position
totalSize int64 // set to -1 if the size is not known
bufferPool sync.Pool
}
// internal logic for deciding whether to upload a single part or use a
// multipart upload.
func (u *uploader) upload() (*UploadOutput, error) {
u.init()
if u.cfg.PartSize < MinUploadPartSize {
msg := fmt.Sprintf("part size must be at least %d bytes", MinUploadPartSize)
return nil, awserr.New("ConfigError", msg, nil)
}
// Do one read to determine if we have more than one part
reader, _, part, err := u.nextReader()
if err == io.EOF { // single part
return u.singlePart(reader)
} else if err != nil {
return nil, awserr.New("ReadRequestBody", "read upload data failed", err)
}
mu := multiuploader{uploader: u}
return mu.upload(reader, part)
}
// init will initialize all default options.
func (u *uploader) init() {
if u.cfg.Concurrency == 0 {
u.cfg.Concurrency = DefaultUploadConcurrency
}
if u.cfg.PartSize == 0 {
u.cfg.PartSize = DefaultUploadPartSize
}
if u.cfg.MaxUploadParts == 0 {
u.cfg.MaxUploadParts = MaxUploadParts
}
u.bufferPool = sync.Pool{
New: func() interface{} { return make([]byte, u.cfg.PartSize) },
}
// Try to get the total size for some optimizations
u.initSize()
}
// initSize tries to detect the total stream size, setting u.totalSize. If
// the size is not known, totalSize is set to -1.
func (u *uploader) initSize() {
u.totalSize = -1
switch r := u.in.Body.(type) {
case io.Seeker:
n, err := aws.SeekerLen(r)
if err != nil {
return
}
u.totalSize = n
// Try to adjust partSize if it is too small and account for
// integer division truncation.
if u.totalSize/u.cfg.PartSize >= int64(u.cfg.MaxUploadParts) {
// Add one to the part size to account for remainders
// during the size calculation. e.g odd number of bytes.
u.cfg.PartSize = (u.totalSize / int64(u.cfg.MaxUploadParts)) + 1
}
}
}
// nextReader returns a seekable reader representing the next packet of data.
// This operation increases the shared u.readerPos counter, but note that it
// does not need to be wrapped in a mutex because nextReader is only called
// from the main thread.
func (u *uploader) nextReader() (io.ReadSeeker, int, []byte, error) {
type readerAtSeeker interface {
io.ReaderAt
io.ReadSeeker
}
switch r := u.in.Body.(type) {
case readerAtSeeker:
var err error
n := u.cfg.PartSize
if u.totalSize >= 0 {
bytesLeft := u.totalSize - u.readerPos
if bytesLeft <= u.cfg.PartSize {
err = io.EOF
n = bytesLeft
}
}
reader := io.NewSectionReader(r, u.readerPos, n)
u.readerPos += n
return reader, int(n), nil, err
default:
part := u.bufferPool.Get().([]byte)
n, err := readFillBuf(r, part)
u.readerPos += int64(n)
return bytes.NewReader(part[0:n]), n, part, err
}
}
func readFillBuf(r io.Reader, b []byte) (offset int, err error) {
for offset < len(b) && err == nil {
var n int
n, err = r.Read(b[offset:])
offset += n
}
return offset, err
}
// singlePart contains upload logic for uploading a single chunk via
// a regular PutObject request. Multipart requests require at least two
// parts, or at least 5MB of data.
func (u *uploader) singlePart(buf io.ReadSeeker) (*UploadOutput, error) {
params := &s3.PutObjectInput{}
awsutil.Copy(params, u.in)
params.Body = buf
// Need to use request form because URL generated in request is
// used in return.
req, out := u.cfg.S3.PutObjectRequest(params)
req.SetContext(u.ctx)
req.ApplyOptions(u.cfg.RequestOptions...)
if err := req.Send(); err != nil {
return nil, err
}
url := req.HTTPRequest.URL.String()
return &UploadOutput{
Location: url,
VersionID: out.VersionId,
}, nil
}
// internal structure to manage a specific multipart upload to S3.
type multiuploader struct {
*uploader
wg sync.WaitGroup
m sync.Mutex
err error
uploadID string
parts completedParts
}
// keeps track of a single chunk of data being sent to S3.
type chunk struct {
buf io.ReadSeeker
part []byte
num int64
}
// completedParts is a wrapper to make parts sortable by their part number,
// since S3 required this list to be sent in sorted order.
type completedParts []*s3.CompletedPart
func (a completedParts) Len() int { return len(a) }
func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a completedParts) Less(i, j int) bool { return *a[i].PartNumber < *a[j].PartNumber }
// upload will perform a multipart upload using the firstBuf buffer containing
// the first chunk of data.
func (u *multiuploader) upload(firstBuf io.ReadSeeker, firstPart []byte) (*UploadOutput, error) {
params := &s3.CreateMultipartUploadInput{}
awsutil.Copy(params, u.in)
// Create the multipart
resp, err := u.cfg.S3.CreateMultipartUploadWithContext(u.ctx, params, u.cfg.RequestOptions...)
if err != nil {
return nil, err
}
u.uploadID = *resp.UploadId
// Create the workers
ch := make(chan chunk, u.cfg.Concurrency)
for i := 0; i < u.cfg.Concurrency; i++ {
u.wg.Add(1)
go u.readChunk(ch)
}
// Send part 1 to the workers
var num int64 = 1
ch <- chunk{buf: firstBuf, part: firstPart, num: num}
// Read and queue the rest of the parts
for u.geterr() == nil && err == nil {
num++
// This upload exceeded maximum number of supported parts, error now.
if num > int64(u.cfg.MaxUploadParts) || num > int64(MaxUploadParts) {
var msg string
if num > int64(u.cfg.MaxUploadParts) {
msg = fmt.Sprintf("exceeded total allowed configured MaxUploadParts (%d). Adjust PartSize to fit in this limit",
u.cfg.MaxUploadParts)
} else {
msg = fmt.Sprintf("exceeded total allowed S3 limit MaxUploadParts (%d). Adjust PartSize to fit in this limit",
MaxUploadParts)
}
u.seterr(awserr.New("TotalPartsExceeded", msg, nil))
break
}
var reader io.ReadSeeker
var nextChunkLen int
var part []byte
reader, nextChunkLen, part, err = u.nextReader()
if err != nil && err != io.EOF {
u.seterr(awserr.New(
"ReadRequestBody",
"read multipart upload data failed",
err))
break
}
if nextChunkLen == 0 {
// No need to upload empty part, if file was empty to start
// with empty single part would of been created and never
// started multipart upload.
break
}
ch <- chunk{buf: reader, part: part, num: num}
}
// Close the channel, wait for workers, and complete upload
close(ch)
u.wg.Wait()
complete := u.complete()
if err := u.geterr(); err != nil {
return nil, &multiUploadError{
awsError: awserr.New(
"MultipartUpload",
"upload multipart failed",
err),
uploadID: u.uploadID,
}
}
return &UploadOutput{
Location: aws.StringValue(complete.Location),
VersionID: complete.VersionId,
UploadID: u.uploadID,
}, nil
}
// readChunk runs in worker goroutines to pull chunks off of the ch channel
// and send() them as UploadPart requests.
func (u *multiuploader) readChunk(ch chan chunk) {
defer u.wg.Done()
for {
data, ok := <-ch
if !ok {
break
}
if u.geterr() == nil {
if err := u.send(data); err != nil {
u.seterr(err)
}
}
}
}
// send performs an UploadPart request and keeps track of the completed
// part information.
func (u *multiuploader) send(c chunk) error {
params := &s3.UploadPartInput{
Bucket: u.in.Bucket,
Key: u.in.Key,
Body: c.buf,
UploadId: &u.uploadID,
SSECustomerAlgorithm: u.in.SSECustomerAlgorithm,
SSECustomerKey: u.in.SSECustomerKey,
PartNumber: &c.num,
}
resp, err := u.cfg.S3.UploadPartWithContext(u.ctx, params, u.cfg.RequestOptions...)
// put the byte array back into the pool to conserve memory
u.bufferPool.Put(c.part)
if err != nil {
return err
}
n := c.num
completed := &s3.CompletedPart{ETag: resp.ETag, PartNumber: &n}
u.m.Lock()
u.parts = append(u.parts, completed)
u.m.Unlock()
return nil
}
// geterr is a thread-safe getter for the error object
func (u *multiuploader) geterr() error {
u.m.Lock()
defer u.m.Unlock()
return u.err
}
// seterr is a thread-safe setter for the error object
func (u *multiuploader) seterr(e error) {
u.m.Lock()
defer u.m.Unlock()
u.err = e
}
// fail will abort the multipart unless LeavePartsOnError is set to true.
func (u *multiuploader) fail() {
if u.cfg.LeavePartsOnError {
return
}
params := &s3.AbortMultipartUploadInput{
Bucket: u.in.Bucket,
Key: u.in.Key,
UploadId: &u.uploadID,
}
_, err := u.cfg.S3.AbortMultipartUploadWithContext(u.ctx, params, u.cfg.RequestOptions...)
if err != nil {
logMessage(u.cfg.S3, aws.LogDebug, fmt.Sprintf("failed to abort multipart upload, %v", err))
}
}
// complete successfully completes a multipart upload and returns the response.
func (u *multiuploader) complete() *s3.CompleteMultipartUploadOutput {
if u.geterr() != nil {
u.fail()
return nil
}
// Parts must be sorted in PartNumber order.
sort.Sort(u.parts)
params := &s3.CompleteMultipartUploadInput{
Bucket: u.in.Bucket,
Key: u.in.Key,
UploadId: &u.uploadID,
MultipartUpload: &s3.CompletedMultipartUpload{Parts: u.parts},
}
resp, err := u.cfg.S3.CompleteMultipartUploadWithContext(u.ctx, params, u.cfg.RequestOptions...)
if err != nil {
u.seterr(err)
u.fail()
}
return resp
}
| mpl-2.0 |
gody01/SuiteCRM | modules/AOR_Reports/AOR_Report_Before.js | 8787 | $(document).ready(function(){
SUGAR.util.doWhen("typeof $('#fieldTree').tree != 'undefined'", function(){
var $moduleTree = $('#fieldTree').tree({
data: {},
dragAndDrop: false,
selectable: false,
onDragStop: function(node, e,thing){
// var target = $(document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset));
// if(node.type != 'field'){
// return;
// }
// if(target.closest('#fieldLines').length > 0){
// addNodeToFields(node);
// updateChartDimensionSelects();
// }else if(target.closest('#conditionLines').length > 0){
// addNodeToConditions(node);
// }
},
onCanMoveTo: function(){
return false;
}
});
function loadTreeData(module, node){
var _node = node;
$.getJSON('index.php',
{
'module' : 'AOR_Reports',
'action' : 'getModuleTreeData',
'aor_module' : module,
'view' : 'JSON'
},
function(relData){
processTreeData(relData, _node);
}
);
}
var treeDataLeafs = [];
var dropFieldLine = function(node) {
addNodeToFields(node);
updateChartDimensionSelects();
};
var dropConditionLine = function(node) {
var newConditionLine = addNodeToConditions(node);
LogicalOperatorHandler.hideUnnecessaryLogicSelects();
ConditionOrderHandler.setConditionOrders();
ParenthesisHandler.addParenthesisLineIdent();
return newConditionLine;
};
var showTreeDataLeafs = function(treeDataLeafs, module, module_name, module_path_display) {
if (typeof module_name == 'undefined' || !module_name) {
module_name = module;
}
if (typeof module_path_display == 'undefined' || !module_path_display) {
module_path_display = module_name;
}
$('#module-name').html('(<span title="' + module_path_display + '">' + module_name + '</span>)');
$('#fieldTreeLeafs').remove();
$('#detailpanel_fields_select').append(
'<div id="fieldTreeLeafs" class="dragbox aor_dragbox" title="'
+ SUGAR.language.translate('AOR_Reports', 'LBL_TOOLTIP_DRAG_DROP_ELEMS')
+ '"></div>'
);
$('#fieldTreeLeafs').tree({
data: treeDataLeafs,
dragAndDrop: true,
selectable: true,
onCanSelectNode: function(node) {
if($('#report-editview-footer .toggle-detailpanel_fields').hasClass('active')) {
dropFieldLine(node);
}
else if($('#report-editview-footer .toggle-detailpanel_conditions').hasClass('active')) {
dropConditionLine(node);
}
},
onDragMove: function() {
$('.drop-area').addClass('highlighted');
},
onDragStop: function(node, e,thing){
$('.drop-area').removeClass('highlighted');
var target = $(document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset));
if(node.type != 'field'){
return;
}
if(target.closest('#fieldLines').length > 0){
dropFieldLine(node);
}else if(target.closest('#aor_conditionLines').length > 0){
var conditionLineTarget = ConditionOrderHandler.getConditionLineByPageEvent(e);
var conditionLineNew = dropConditionLine(node);
if(conditionLineTarget) {
ConditionOrderHandler.putPositionedConditionLines(conditionLineTarget, conditionLineNew);
ConditionOrderHandler.setConditionOrders();
}
ParenthesisHandler.addParenthesisLineIdent();
}
else if(target.closest('.tab-toggler').length > 0) {
target.closest('.tab-toggler').click();
if(target.closest('.tab-toggler').hasClass('toggle-detailpanel_fields')) {
dropFieldLine(node);
}
else if (target.closest('.tab-toggler').hasClass('toggle-detailpanel_conditions')) {
dropConditionLine(node);
}
}
},
onCanMoveTo: function(){
return false;
}
});
};
function loadTreeLeafData(node) {
var module = node.module;
var module_name = node.name;
var module_path_display = node.module_path_display;
if (!treeDataLeafs[module_path_display]) {
$.getJSON('index.php',
{
'module': 'AOR_Reports',
'action': 'getModuleFields',
'aor_module': node.module,
'view': 'JSON'
},
function (fieldData) {
var treeData = [];
for (var field in fieldData) {
if (fieldData.hasOwnProperty(field) && field !== '') {
treeData.push(
{
id: field,
label: fieldData[field],
'load_on_demand': false,
type: 'field',
module: node.module,
module_path: node.module_path,
module_path_display: node.module_path_display
});
}
}
treeDataLeafs[module_path_display] = treeData;
showTreeDataLeafs(treeDataLeafs[module_path_display], module, module_name, module_path_display);
}
);
} else {
showTreeDataLeafs(treeDataLeafs[module_path_display], module, module_name, module_path_display);
}
}
function processTreeData(relData, node){
var treeData = [];
for (var field in relData) {
if (relData.hasOwnProperty(field)) {
// We don't want to show the parent module as child of itself
if (node && relData[field].type === 'module') {
continue;
}
var modulePath = '';
var modulePathDisplay = '';
if (relData[field].type === 'relationship') {
modulePath = field;
if (node) {
if (node.module_path) {
modulePath = node.module_path + ":" + field;
}
modulePathDisplay = node.module_path_display + " : " + relData[field].module_label;
} else {
modulePathDisplay = $('#report_module option:selected').text() + ' : ' + relData[field].module_label;
}
} else {
if (node) {
modulePath = node.module_path;
modulePathDisplay = node.module_path_display;
} else {
modulePathDisplay = relData[field].module_label;
}
}
var newNode = {
id: field,
label: relData[field].module_label,
load_on_demand: true,
type: relData[field].type,
module: relData[field].module,
module_path: modulePath,
module_path_display: modulePathDisplay
};
treeData.push(newNode);
}
}
$('#fieldTree').tree('loadData',treeData, node);
if(node){
if(node.opened){
$('#fieldTree').tree('openNode', node);
}
setNodeSelected(node);
node.loaded = true;
}
}
function setNodeSelected(node){
$('.jqtree-selected').removeClass('jqtree-selected');
$('#fieldTree').tree('addToSelection', node);
}
$('#fieldTree').on(
'click',
'.jqtree-toggler, .jqtree-title', //
function(event) {
var node = $(this).closest('li.jqtree_common').data('node');
node.opened = !$(this).hasClass('jqtree-title');
if(!node.loaded) {
loadTreeData(node.module, node);
}
loadTreeLeafData(node);
setNodeSelected(node);
return true;
}
);
var clearTreeDataFields = function() {
$('#module-name').html('');
$('#fieldTreeLeafs').html('');
}
$('#report_module').change(function(){
report_module = $(this).val();
loadTreeData($(this).val());
clearTreeDataFields();
clearFieldLines();
clearConditionLines();
clearChartLines();
});
$('#addChartButton').click(function(){
loadChartLine({});
updateChartDimensionSelects();
});
report_module = $('#report_module').val();
loadTreeData($('#report_module').val());
$.each(fieldLines,function(key,val){
loadFieldLine(val);
});
$.each(conditionLines,function(key,val){
loadConditionLine(val);
});
$.each(chartLines,function(key,val){
loadChartLine(val);
});
updateChartDimensionSelects();
});
});
| agpl-3.0 |
cgvarela/tigase-server | src/main/java/tigase/server/package-info.java | 98 | /**
* The main package with top level API for server side components.
*/
package tigase.server;
| agpl-3.0 |
christophd/camel | core/camel-core/src/test/java/org/apache/camel/component/bean/MethodCallBeanTypeFunctionScopeTest.java | 1921 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.bean;
import org.apache.camel.BeanScope;
import org.apache.camel.builder.RouteBuilder;
public class MethodCallBeanTypeFunctionScopeTest extends SimpleLanguageBeanFunctionScopeTest {
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:single").choice().when().method(MyBean.class, BeanScope.Singleton).to("mock:result")
.otherwise().to("mock:other");
from("direct:proto").choice().when().method(MyBean.class, BeanScope.Prototype).to("mock:result")
.otherwise().to("mock:other");
from("direct:request")
.to("direct:sub")
.to("direct:sub")
.to("direct:sub");
from("direct:sub").choice().when().method(MyBean.class, BeanScope.Request).to("mock:result")
.otherwise().to("mock:other");
}
};
}
}
| apache-2.0 |
YuryBY/pentaho-kettle | ui/src/org/pentaho/di/ui/trans/steps/excelinput/ExcelInputDialog.java | 102644 | //CHECKSTYLE:FileLength:OFF
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.excelinput;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.vfs.FileObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.fileinput.FileInputList;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.spreadsheet.KCell;
import org.pentaho.di.core.spreadsheet.KCellType;
import org.pentaho.di.core.spreadsheet.KSheet;
import org.pentaho.di.core.spreadsheet.KWorkbook;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPreviewFactory;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.excelinput.ExcelInputField;
import org.pentaho.di.trans.steps.excelinput.ExcelInputMeta;
import org.pentaho.di.trans.steps.excelinput.SpreadSheetType;
import org.pentaho.di.trans.steps.excelinput.WorkbookFactory;
import org.pentaho.di.ui.core.dialog.EnterListDialog;
import org.pentaho.di.ui.core.dialog.EnterNumberDialog;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.ui.trans.steps.textfileinput.DirectoryDialogButtonListenerFactory;
import org.pentaho.di.ui.trans.steps.textfileinput.VariableButtonListenerFactory;
public class ExcelInputDialog extends BaseStepDialog implements StepDialogInterface {
private static Class<?> PKG = ExcelInputMeta.class; // for i18n purposes, needed by Translator2!!
/**
* Marker put on tab to indicate attention required
*/
private static final String TAB_FLAG = "!";
private static final String[] YES_NO_COMBO = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wFileTab, wSheetTab, wContentTab, wErrorTab, wFieldsTab;
private Composite wFileComp, wSheetComp, wContentComp, wErrorComp, wFieldsComp;
private FormData fdFileComp, fdSheetComp, fdContentComp, fdFieldsComp;
private Label wlStatusMessage;
private Label wlFilename;
private Button wbbFilename; // Browse: add file or directory
private Button wbdFilename; // Delete
private Button wbeFilename; // Edit
private Button wbaFilename; // Add or change
private TextVar wFilename;
private FormData fdlStatusMessage;
private FormData fdlFilename, fdbFilename, fdbdFilename, fdbeFilename, fdbaFilename, fdFilename;
private Label wlFilenameList;
private TableView wFilenameList;
private FormData fdlFilenameList, fdFilenameList;
private Label wlFilemask;
private Text wFilemask;
private FormData fdlFilemask, fdFilemask;
private Label wlExcludeFilemask;
private TextVar wExcludeFilemask;
private FormData fdlExcludeFilemask, fdExcludeFilemask;
private Group gAccepting;
private FormData fdAccepting;
private Label wlAccFilenames;
private Button wAccFilenames;
private FormData fdlAccFilenames, fdAccFilenames;
private Label wlAccField;
private CCombo wAccField;
private FormData fdlAccField, fdAccField;
private Label wlAccStep;
private CCombo wAccStep;
private FormData fdlAccStep, fdAccStep;
private Button wbShowFiles;
private FormData fdbShowFiles;
private Label wlSheetnameList;
private TableView wSheetnameList;
private FormData fdlSheetnameList;
private Button wbGetSheets;
private FormData fdbGetSheets;
private Label wlHeader;
private Button wHeader;
private FormData fdlHeader, fdHeader;
private Label wlNoempty;
private Button wNoempty;
private FormData fdlNoempty, fdNoempty;
private Label wlStoponempty;
private Button wStoponempty;
private FormData fdlStoponempty, fdStoponempty;
private Label wlInclFilenameField;
private Text wInclFilenameField;
private FormData fdlInclFilenameField, fdInclFilenameField;
private Label wlInclSheetnameField;
private Text wInclSheetnameField;
private FormData fdlInclSheetnameField, fdInclSheetnameField;
private Label wlInclRownumField;
private Text wInclRownumField;
private FormData fdlInclRownumField, fdInclRownumField;
private Label wlInclSheetRownumField;
private Text wInclSheetRownumField;
private FormData fdlInclSheetRownumField, fdInclSheetRownumField;
private Label wlLimit;
private Text wLimit;
private FormData fdlLimit, fdLimit;
private Label wlSpreadSheetType;
private CCombo wSpreadSheetType;
private FormData fdlSpreadSheetType, fdSpreadSheetType;
private Label wlEncoding;
private CCombo wEncoding;
private FormData fdlEncoding, fdEncoding;
private Button wbGetFields;
private TableView wFields;
private FormData fdFields;
// ERROR HANDLING...
private Label wlStrictTypes;
private Button wStrictTypes;
private FormData fdlStrictTypes, fdStrictTypes;
private Label wlErrorIgnored;
private Button wErrorIgnored;
private FormData fdlErrorIgnored, fdErrorIgnored;
private Label wlSkipErrorLines;
private Button wSkipErrorLines;
private FormData fdlSkipErrorLines, fdSkipErrorLines;
// New entries for intelligent error handling AKA replay functionality
// Bad files destination directory
private Label wlWarningDestDir;
private Button wbbWarningDestDir; // Browse: add file or directory
private Button wbvWarningDestDir; // Variable
private Text wWarningDestDir;
private FormData fdlWarningDestDir, fdbWarningDestDir, fdbvWarningDestDir, fdWarningDestDir;
private Label wlWarningExt;
private Text wWarningExt;
private FormData fdlWarningDestExt, fdWarningDestExt;
// Error messages files destination directory
private Label wlErrorDestDir;
private Button wbbErrorDestDir; // Browse: add file or directory
private Button wbvErrorDestDir; // Variable
private Text wErrorDestDir;
private FormData fdlErrorDestDir, fdbErrorDestDir, fdbvErrorDestDir, fdErrorDestDir;
private Label wlErrorExt;
private Text wErrorExt;
private FormData fdlErrorDestExt, fdErrorDestExt;
// Line numbers files destination directory
private Label wlLineNrDestDir;
private Button wbbLineNrDestDir; // Browse: add file or directory
private Button wbvLineNrDestDir; // Variable
private Text wLineNrDestDir;
private FormData fdlLineNrDestDir, fdbLineNrDestDir, fdbvLineNrDestDir, fdLineNrDestDir;
private Label wlLineNrExt;
private Text wLineNrExt;
private FormData fdlLineNrDestExt, fdLineNrDestExt;
private ExcelInputMeta input;
private int middle;
private int margin;
private boolean gotEncodings = false;
private FormData fdlAddResult, fdAddFileResult, fdAddResult;
private Group wAddFileResult;
private Label wlAddResult;
private Button wAddResult;
private ModifyListener lsMod;
private CTabItem wAdditionalFieldsTab;
private Composite wAdditionalFieldsComp;
private FormData fdAdditionalFieldsComp;
private Label wlShortFileFieldName;
private FormData fdlShortFileFieldName;
private Text wShortFileFieldName;
private FormData fdShortFileFieldName;
private Label wlPathFieldName;
private FormData fdlPathFieldName;
private Text wPathFieldName;
private FormData fdPathFieldName;
private Label wlIsHiddenName;
private FormData fdlIsHiddenName;
private Text wIsHiddenName;
private FormData fdIsHiddenName;
private Label wlLastModificationTimeName;
private FormData fdlLastModificationTimeName;
private Text wLastModificationTimeName;
private FormData fdLastModificationTimeName;
private Label wlUriName;
private FormData fdlUriName;
private Text wUriName;
private FormData fdUriName;
private Label wlRootUriName;
private FormData fdlRootUriName;
private Text wRootUriName;
private FormData fdRootUriName;
private Label wlExtensionFieldName;
private FormData fdlExtensionFieldName;
private Text wExtensionFieldName;
private FormData fdExtensionFieldName;
private Label wlSizeFieldName;
private FormData fdlSizeFieldName;
private Text wSizeFieldName;
private FormData fdSizeFieldName;
public ExcelInputDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
super( parent, (BaseStepMeta) in, transMeta, sname );
input = (ExcelInputMeta) in;
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
props.setLook( shell );
setShellImage( shell, input );
lsMod = new ModifyListener() {
public void modifyText( ModifyEvent e ) {
input.setChanged();
checkAlerts();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "ExcelInputDialog.DialogTitle" ) );
middle = props.getMiddlePct();
margin = Const.MARGIN;
// Stepname line
wlStepname = new Label( shell, SWT.RIGHT );
wlStepname.setText( BaseMessages.getString( PKG, "System.Label.StepName" ) );
props.setLook( wlStepname );
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment( 0, 0 );
fdlStepname.top = new FormAttachment( 0, margin );
fdlStepname.right = new FormAttachment( middle, -margin );
wlStepname.setLayoutData( fdlStepname );
wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wStepname.setText( stepname );
props.setLook( wStepname );
wStepname.addModifyListener( lsMod );
fdStepname = new FormData();
fdStepname.left = new FormAttachment( middle, 0 );
fdStepname.top = new FormAttachment( 0, margin );
fdStepname.right = new FormAttachment( 100, 0 );
wStepname.setLayoutData( fdStepname );
// Status Message
wlStatusMessage = new Label( shell, SWT.RIGHT );
wlStatusMessage.setText( "(This Space To Let)" );
wlStatusMessage.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
props.setLook( wlStatusMessage );
fdlStatusMessage = new FormData();
fdlStatusMessage.left = new FormAttachment( 0, 0 );
fdlStatusMessage.top = new FormAttachment( wlStepname, margin );
fdlStatusMessage.right = new FormAttachment( middle, -margin );
wlStatusMessage.setLayoutData( fdlStatusMessage );
// Tabs
wTabFolder = new CTabFolder( shell, SWT.BORDER );
props.setLook( wTabFolder, Props.WIDGET_STYLE_TAB );
//
// START OF FILE TAB /
//
wFileTab = new CTabItem( wTabFolder, SWT.NONE );
wFileTab.setText( BaseMessages.getString( PKG, "ExcelInputDialog.FileTab.TabTitle" ) );
wFileComp = new Composite( wTabFolder, SWT.NONE );
props.setLook( wFileComp );
FormLayout fileLayout = new FormLayout();
fileLayout.marginWidth = 3;
fileLayout.marginHeight = 3;
wFileComp.setLayout( fileLayout );
// spreadsheet engine type
wlSpreadSheetType = new Label( wFileComp, SWT.RIGHT );
wlSpreadSheetType.setText( BaseMessages.getString( PKG, "ExcelInputDialog.SpreadSheetType.Label" ) );
props.setLook( wlSpreadSheetType );
fdlSpreadSheetType = new FormData();
fdlSpreadSheetType.left = new FormAttachment( 0, 0 );
fdlSpreadSheetType.right = new FormAttachment( middle, -margin );
fdlSpreadSheetType.top = new FormAttachment( 0, 0 );
wlSpreadSheetType.setLayoutData( fdlSpreadSheetType );
wSpreadSheetType = new CCombo( wFileComp, SWT.BORDER | SWT.READ_ONLY );
wSpreadSheetType.setEditable( true );
props.setLook( wSpreadSheetType );
wSpreadSheetType.addModifyListener( lsMod );
fdSpreadSheetType = new FormData();
fdSpreadSheetType.left = new FormAttachment( middle, 0 );
fdSpreadSheetType.right = new FormAttachment( 100, 0 );
fdSpreadSheetType.top = new FormAttachment( 0, 0 );
wSpreadSheetType.setLayoutData( fdSpreadSheetType );
for ( SpreadSheetType type : SpreadSheetType.values() ) {
wSpreadSheetType.add( type.getDescription() );
}
// Filename line
wlFilename = new Label( wFileComp, SWT.RIGHT );
wlFilename.setText( BaseMessages.getString( PKG, "ExcelInputDialog.Filename.Label" ) );
props.setLook( wlFilename );
fdlFilename = new FormData();
fdlFilename.left = new FormAttachment( 0, 0 );
fdlFilename.top = new FormAttachment( wSpreadSheetType, margin );
fdlFilename.right = new FormAttachment( middle, -margin );
wlFilename.setLayoutData( fdlFilename );
wbbFilename = new Button( wFileComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbbFilename );
wbbFilename.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) );
wbbFilename.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.BrowseForFileOrDirAndAdd" ) );
fdbFilename = new FormData();
fdbFilename.right = new FormAttachment( 100, 0 );
fdbFilename.top = new FormAttachment( wSpreadSheetType, margin );
wbbFilename.setLayoutData( fdbFilename );
wbaFilename = new Button( wFileComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbaFilename );
wbaFilename.setText( BaseMessages.getString( PKG, "ExcelInputDialog.FilenameAdd.Button" ) );
wbaFilename.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.FilenameAdd.Tooltip" ) );
fdbaFilename = new FormData();
fdbaFilename.right = new FormAttachment( wbbFilename, -margin );
fdbaFilename.top = new FormAttachment( wSpreadSheetType, margin );
wbaFilename.setLayoutData( fdbaFilename );
wFilename = new TextVar( transMeta, wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wFilename );
wFilename.addModifyListener( lsMod );
fdFilename = new FormData();
fdFilename.left = new FormAttachment( middle, 0 );
fdFilename.right = new FormAttachment( wbaFilename, -margin );
fdFilename.top = new FormAttachment( wSpreadSheetType, margin );
wFilename.setLayoutData( fdFilename );
wlFilemask = new Label( wFileComp, SWT.RIGHT );
wlFilemask.setText( BaseMessages.getString( PKG, "ExcelInputDialog.Filemask.Label" ) );
props.setLook( wlFilemask );
fdlFilemask = new FormData();
fdlFilemask.left = new FormAttachment( 0, 0 );
fdlFilemask.top = new FormAttachment( wFilename, margin );
fdlFilemask.right = new FormAttachment( middle, -margin );
wlFilemask.setLayoutData( fdlFilemask );
wFilemask = new Text( wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wFilemask );
wFilemask.addModifyListener( lsMod );
fdFilemask = new FormData();
fdFilemask.left = new FormAttachment( middle, 0 );
fdFilemask.top = new FormAttachment( wFilename, margin );
fdFilemask.right = new FormAttachment( wbaFilename, -margin );
wFilemask.setLayoutData( fdFilemask );
wlExcludeFilemask = new Label( wFileComp, SWT.RIGHT );
wlExcludeFilemask.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ExcludeFilemask.Label" ) );
props.setLook( wlExcludeFilemask );
fdlExcludeFilemask = new FormData();
fdlExcludeFilemask.left = new FormAttachment( 0, 0 );
fdlExcludeFilemask.top = new FormAttachment( wFilemask, margin );
fdlExcludeFilemask.right = new FormAttachment( middle, -margin );
wlExcludeFilemask.setLayoutData( fdlExcludeFilemask );
wExcludeFilemask = new TextVar( transMeta, wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wExcludeFilemask );
wExcludeFilemask.addModifyListener( lsMod );
fdExcludeFilemask = new FormData();
fdExcludeFilemask.left = new FormAttachment( middle, 0 );
fdExcludeFilemask.top = new FormAttachment( wFilemask, margin );
fdExcludeFilemask.right = new FormAttachment( wFilename, 0, SWT.RIGHT );
wExcludeFilemask.setLayoutData( fdExcludeFilemask );
// Filename list line
wlFilenameList = new Label( wFileComp, SWT.RIGHT );
wlFilenameList.setText( BaseMessages.getString( PKG, "ExcelInputDialog.FilenameList.Label" ) );
props.setLook( wlFilenameList );
fdlFilenameList = new FormData();
fdlFilenameList.left = new FormAttachment( 0, 0 );
fdlFilenameList.top = new FormAttachment( wExcludeFilemask, margin );
fdlFilenameList.right = new FormAttachment( middle, -margin );
wlFilenameList.setLayoutData( fdlFilenameList );
// Buttons to the right of the screen...
wbdFilename = new Button( wFileComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbdFilename );
wbdFilename.setText( BaseMessages.getString( PKG, "ExcelInputDialog.FilenameDelete.Button" ) );
wbdFilename.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.FilenameDelete.Tooltip" ) );
fdbdFilename = new FormData();
fdbdFilename.right = new FormAttachment( 100, 0 );
fdbdFilename.top = new FormAttachment( wExcludeFilemask, 40 );
wbdFilename.setLayoutData( fdbdFilename );
wbeFilename = new Button( wFileComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbeFilename );
wbeFilename.setText( BaseMessages.getString( PKG, "ExcelInputDialog.FilenameEdit.Button" ) );
wbeFilename.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.FilenameEdit.Tooltip" ) );
fdbeFilename = new FormData();
fdbeFilename.right = new FormAttachment( 100, 0 );
fdbeFilename.left = new FormAttachment( wbdFilename, 0, SWT.LEFT );
fdbeFilename.top = new FormAttachment( wbdFilename, margin );
wbeFilename.setLayoutData( fdbeFilename );
wbShowFiles = new Button( wFileComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbShowFiles );
wbShowFiles.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ShowFiles.Button" ) );
fdbShowFiles = new FormData();
fdbShowFiles.left = new FormAttachment( middle, 0 );
fdbShowFiles.bottom = new FormAttachment( 100, -margin );
wbShowFiles.setLayoutData( fdbShowFiles );
// Accepting filenames group
//
gAccepting = new Group( wFileComp, SWT.SHADOW_ETCHED_IN );
gAccepting.setText( BaseMessages.getString( PKG, "ExcelInputDialog.AcceptingGroup.Label" ) );
FormLayout acceptingLayout = new FormLayout();
acceptingLayout.marginWidth = 3;
acceptingLayout.marginHeight = 3;
gAccepting.setLayout( acceptingLayout );
props.setLook( gAccepting );
// Accept filenames from previous steps?
//
wlAccFilenames = new Label( gAccepting, SWT.RIGHT );
wlAccFilenames.setText( BaseMessages.getString( PKG, "ExcelInputDialog.AcceptFilenames.Label" ) );
props.setLook( wlAccFilenames );
fdlAccFilenames = new FormData();
fdlAccFilenames.top = new FormAttachment( 0, margin );
fdlAccFilenames.left = new FormAttachment( 0, 0 );
fdlAccFilenames.right = new FormAttachment( middle, -margin );
wlAccFilenames.setLayoutData( fdlAccFilenames );
wAccFilenames = new Button( gAccepting, SWT.CHECK );
wAccFilenames.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.AcceptFilenames.Tooltip" ) );
props.setLook( wAccFilenames );
fdAccFilenames = new FormData();
fdAccFilenames.top = new FormAttachment( 0, margin );
fdAccFilenames.left = new FormAttachment( middle, 0 );
fdAccFilenames.right = new FormAttachment( 100, 0 );
wAccFilenames.setLayoutData( fdAccFilenames );
wAccFilenames.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
setFlags();
}
} );
// Which step to read from?
wlAccStep = new Label( gAccepting, SWT.RIGHT );
wlAccStep.setText( BaseMessages.getString( PKG, "ExcelInputDialog.AcceptStep.Label" ) );
props.setLook( wlAccStep );
fdlAccStep = new FormData();
fdlAccStep.top = new FormAttachment( wAccFilenames, margin );
fdlAccStep.left = new FormAttachment( 0, 0 );
fdlAccStep.right = new FormAttachment( middle, -margin );
wlAccStep.setLayoutData( fdlAccStep );
wAccStep = new CCombo( gAccepting, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wAccStep.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.AcceptStep.Tooltip" ) );
props.setLook( wAccStep );
fdAccStep = new FormData();
fdAccStep.top = new FormAttachment( wAccFilenames, margin );
fdAccStep.left = new FormAttachment( middle, 0 );
fdAccStep.right = new FormAttachment( 100, 0 );
wAccStep.setLayoutData( fdAccStep );
// Which field?
//
wlAccField = new Label( gAccepting, SWT.RIGHT );
wlAccField.setText( BaseMessages.getString( PKG, "ExcelInputDialog.AcceptField.Label" ) );
props.setLook( wlAccField );
fdlAccField = new FormData();
fdlAccField.top = new FormAttachment( wAccStep, margin );
fdlAccField.left = new FormAttachment( 0, 0 );
fdlAccField.right = new FormAttachment( middle, -margin );
wlAccField.setLayoutData( fdlAccField );
wAccField = new CCombo( gAccepting, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
RowMetaInterface previousFields;
try {
previousFields = transMeta.getPrevStepFields( stepMeta );
} catch ( KettleStepException e ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "ExcelInputDialog.ErrorDialog.UnableToGetInputFields.Title" ),
BaseMessages.getString( PKG, "ExcelInputDialog.ErrorDialog.UnableToGetInputFields.Message" ), e );
previousFields = new RowMeta();
}
wAccField.setItems( previousFields.getFieldNames() );
wAccField.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.AcceptField.Tooltip" ) );
props.setLook( wAccField );
fdAccField = new FormData();
fdAccField.top = new FormAttachment( wAccStep, margin );
fdAccField.left = new FormAttachment( middle, 0 );
fdAccField.right = new FormAttachment( 100, 0 );
wAccField.setLayoutData( fdAccField );
// Fill in the source steps...
List<StepMeta> prevSteps = transMeta.findPreviousSteps( transMeta.findStep( stepname ) );
for ( StepMeta prevStep : prevSteps ) {
wAccStep.add( prevStep.getName() );
}
fdAccepting = new FormData();
fdAccepting.left = new FormAttachment( middle, 0 );
fdAccepting.right = new FormAttachment( 100, 0 );
fdAccepting.bottom = new FormAttachment( wbShowFiles, -margin * 2 );
// fdAccepting.bottom = new FormAttachment(wAccStep, margin);
gAccepting.setLayoutData( fdAccepting );
ColumnInfo[] colinfo = new ColumnInfo[5];
colinfo[0] =
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.FileDir.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false );
colinfo[0].setUsingVariables( true );
colinfo[1] =
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Wildcard.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false );
colinfo[1].setToolTip( BaseMessages.getString( PKG, "ExcelInputDialog.Wildcard.Tooltip" ) );
colinfo[2] =
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Files.ExcludeWildcard.Column" ),
ColumnInfo.COLUMN_TYPE_TEXT, false );
colinfo[2].setUsingVariables( true );
colinfo[3] =
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Required.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO,
YES_NO_COMBO );
colinfo[3].setToolTip( BaseMessages.getString( PKG, "ExcelInputDialog.Required.Tooltip" ) );
colinfo[4] =
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.IncludeSubDirs.Column" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, YES_NO_COMBO );
colinfo[4].setToolTip( BaseMessages.getString( PKG, "ExcelInputDialog.IncludeSubDirs.Tooltip" ) );
wFilenameList =
new TableView( transMeta, wFileComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, input
.getFileName().length, lsMod, props );
props.setLook( wFilenameList );
fdFilenameList = new FormData();
fdFilenameList.left = new FormAttachment( middle, 0 );
fdFilenameList.right = new FormAttachment( wbdFilename, -margin );
fdFilenameList.top = new FormAttachment( wExcludeFilemask, margin );
fdFilenameList.bottom = new FormAttachment( gAccepting, -margin );
wFilenameList.setLayoutData( fdFilenameList );
fdFileComp = new FormData();
fdFileComp.left = new FormAttachment( 0, 0 );
fdFileComp.top = new FormAttachment( 0, 0 );
fdFileComp.right = new FormAttachment( 100, 0 );
fdFileComp.bottom = new FormAttachment( 100, 0 );
wFileComp.setLayoutData( fdFileComp );
wFileComp.layout();
wFileTab.setControl( wFileComp );
//
// / END OF FILE TAB
//
//
// START OF SHEET TAB /
//
wSheetTab = new CTabItem( wTabFolder, SWT.NONE );
wSheetTab.setText( BaseMessages.getString( PKG, "ExcelInputDialog.SheetsTab.TabTitle" ) );
wSheetComp = new Composite( wTabFolder, SWT.NONE );
props.setLook( wSheetComp );
FormLayout sheetLayout = new FormLayout();
sheetLayout.marginWidth = 3;
sheetLayout.marginHeight = 3;
wSheetComp.setLayout( sheetLayout );
wbGetSheets = new Button( wSheetComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbGetSheets );
wbGetSheets.setText( BaseMessages.getString( PKG, "ExcelInputDialog.GetSheets.Button" ) );
fdbGetSheets = new FormData();
fdbGetSheets.left = new FormAttachment( middle, 0 );
fdbGetSheets.bottom = new FormAttachment( 100, -margin );
wbGetSheets.setLayoutData( fdbGetSheets );
wlSheetnameList = new Label( wSheetComp, SWT.RIGHT );
wlSheetnameList.setText( BaseMessages.getString( PKG, "ExcelInputDialog.SheetNameList.Label" ) );
props.setLook( wlSheetnameList );
fdlSheetnameList = new FormData();
fdlSheetnameList.left = new FormAttachment( 0, 0 );
fdlSheetnameList.top = new FormAttachment( wFilename, margin );
fdlSheetnameList.right = new FormAttachment( middle, -margin );
wlSheetnameList.setLayoutData( fdlSheetnameList );
ColumnInfo[] shinfo = new ColumnInfo[3];
shinfo[0] =
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.SheetName.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false );
shinfo[1] =
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.StartRow.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false );
shinfo[2] =
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.StartColumn.Column" ), ColumnInfo.COLUMN_TYPE_TEXT,
false );
wSheetnameList =
new TableView( transMeta, wSheetComp, SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER, shinfo, input
.getSheetName().length, lsMod, props );
props.setLook( wSheetnameList );
fdFilenameList = new FormData();
fdFilenameList.left = new FormAttachment( middle, 0 );
fdFilenameList.right = new FormAttachment( 100, 0 );
fdFilenameList.top = new FormAttachment( 0, 0 );
fdFilenameList.bottom = new FormAttachment( wbGetSheets, -margin );
wSheetnameList.setLayoutData( fdFilenameList );
wSheetnameList.addModifyListener( new ModifyListener() {
public void modifyText( ModifyEvent arg0 ) {
checkAlerts();
}
} );
fdSheetComp = new FormData();
fdSheetComp.left = new FormAttachment( 0, 0 );
fdSheetComp.top = new FormAttachment( 0, 0 );
fdSheetComp.right = new FormAttachment( 100, 0 );
fdSheetComp.bottom = new FormAttachment( 100, 0 );
wSheetComp.setLayoutData( fdSheetComp );
wSheetComp.layout();
wSheetTab.setControl( wSheetComp );
//
// / END OF SHEET TAB
//
//
// START OF CONTENT TAB/
// /
wContentTab = new CTabItem( wTabFolder, SWT.NONE );
wContentTab.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ContentTab.TabTitle" ) );
FormLayout contentLayout = new FormLayout();
contentLayout.marginWidth = 3;
contentLayout.marginHeight = 3;
wContentComp = new Composite( wTabFolder, SWT.NONE );
props.setLook( wContentComp );
wContentComp.setLayout( contentLayout );
// Header checkbox
wlHeader = new Label( wContentComp, SWT.RIGHT );
wlHeader.setText( BaseMessages.getString( PKG, "ExcelInputDialog.Header.Label" ) );
props.setLook( wlHeader );
fdlHeader = new FormData();
fdlHeader.left = new FormAttachment( 0, 0 );
fdlHeader.top = new FormAttachment( 0, 0 );
fdlHeader.right = new FormAttachment( middle, -margin );
wlHeader.setLayoutData( fdlHeader );
wHeader = new Button( wContentComp, SWT.CHECK );
props.setLook( wHeader );
fdHeader = new FormData();
fdHeader.left = new FormAttachment( middle, 0 );
fdHeader.top = new FormAttachment( 0, 0 );
fdHeader.right = new FormAttachment( 100, 0 );
wHeader.setLayoutData( fdHeader );
wHeader.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
setFlags();
}
} );
wlNoempty = new Label( wContentComp, SWT.RIGHT );
wlNoempty.setText( BaseMessages.getString( PKG, "ExcelInputDialog.NoEmpty.Label" ) );
props.setLook( wlNoempty );
fdlNoempty = new FormData();
fdlNoempty.left = new FormAttachment( 0, 0 );
fdlNoempty.top = new FormAttachment( wHeader, margin );
fdlNoempty.right = new FormAttachment( middle, -margin );
wlNoempty.setLayoutData( fdlNoempty );
wNoempty = new Button( wContentComp, SWT.CHECK );
props.setLook( wNoempty );
wNoempty.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.NoEmpty.Tooltip" ) );
fdNoempty = new FormData();
fdNoempty.left = new FormAttachment( middle, 0 );
fdNoempty.top = new FormAttachment( wHeader, margin );
fdNoempty.right = new FormAttachment( 100, 0 );
wNoempty.setLayoutData( fdNoempty );
wlStoponempty = new Label( wContentComp, SWT.RIGHT );
wlStoponempty.setText( BaseMessages.getString( PKG, "ExcelInputDialog.StopOnEmpty.Label" ) );
props.setLook( wlStoponempty );
fdlStoponempty = new FormData();
fdlStoponempty.left = new FormAttachment( 0, 0 );
fdlStoponempty.top = new FormAttachment( wNoempty, margin );
fdlStoponempty.right = new FormAttachment( middle, -margin );
wlStoponempty.setLayoutData( fdlStoponempty );
wStoponempty = new Button( wContentComp, SWT.CHECK );
props.setLook( wStoponempty );
wStoponempty.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.StopOnEmpty.Tooltip" ) );
fdStoponempty = new FormData();
fdStoponempty.left = new FormAttachment( middle, 0 );
fdStoponempty.top = new FormAttachment( wNoempty, margin );
fdStoponempty.right = new FormAttachment( 100, 0 );
wStoponempty.setLayoutData( fdStoponempty );
wlLimit = new Label( wContentComp, SWT.RIGHT );
wlLimit.setText( BaseMessages.getString( PKG, "ExcelInputDialog.Limit.Label" ) );
props.setLook( wlLimit );
fdlLimit = new FormData();
fdlLimit.left = new FormAttachment( 0, 0 );
fdlLimit.top = new FormAttachment( wStoponempty, margin );
fdlLimit.right = new FormAttachment( middle, -margin );
wlLimit.setLayoutData( fdlLimit );
wLimit = new Text( wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wLimit );
wLimit.addModifyListener( lsMod );
fdLimit = new FormData();
fdLimit.left = new FormAttachment( middle, 0 );
fdLimit.top = new FormAttachment( wStoponempty, margin );
fdLimit.right = new FormAttachment( 100, 0 );
wLimit.setLayoutData( fdLimit );
wlEncoding = new Label( wContentComp, SWT.RIGHT );
wlEncoding.setText( BaseMessages.getString( PKG, "ExcelInputDialog.Encoding.Label" ) );
props.setLook( wlEncoding );
fdlEncoding = new FormData();
fdlEncoding.left = new FormAttachment( 0, 0 );
fdlEncoding.top = new FormAttachment( wLimit, margin );
fdlEncoding.right = new FormAttachment( middle, -margin );
wlEncoding.setLayoutData( fdlEncoding );
wEncoding = new CCombo( wContentComp, SWT.BORDER | SWT.READ_ONLY );
wEncoding.setEditable( true );
props.setLook( wEncoding );
wEncoding.addModifyListener( lsMod );
fdEncoding = new FormData();
fdEncoding.left = new FormAttachment( middle, 0 );
fdEncoding.top = new FormAttachment( wLimit, margin );
fdEncoding.right = new FormAttachment( 100, 0 );
wEncoding.setLayoutData( fdEncoding );
wEncoding.addFocusListener( new FocusListener() {
public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
}
public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT );
shell.setCursor( busy );
setEncodings();
shell.setCursor( null );
busy.dispose();
}
} );
//
// START OF AddFileResult GROUP
//
wAddFileResult = new Group( wContentComp, SWT.SHADOW_NONE );
props.setLook( wAddFileResult );
wAddFileResult.setText( BaseMessages.getString( PKG, "ExcelInputDialog.AddFileResult.Label" ) );
FormLayout AddFileResultgroupLayout = new FormLayout();
AddFileResultgroupLayout.marginWidth = 10;
AddFileResultgroupLayout.marginHeight = 10;
wAddFileResult.setLayout( AddFileResultgroupLayout );
wlAddResult = new Label( wAddFileResult, SWT.RIGHT );
wlAddResult.setText( BaseMessages.getString( PKG, "ExcelInputDialog.AddResult.Label" ) );
props.setLook( wlAddResult );
fdlAddResult = new FormData();
fdlAddResult.left = new FormAttachment( 0, 0 );
fdlAddResult.top = new FormAttachment( wEncoding, margin );
fdlAddResult.right = new FormAttachment( middle, -margin );
wlAddResult.setLayoutData( fdlAddResult );
wAddResult = new Button( wAddFileResult, SWT.CHECK );
props.setLook( wAddResult );
wAddResult.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.AddResult.Tooltip" ) );
fdAddResult = new FormData();
fdAddResult.left = new FormAttachment( middle, 0 );
fdAddResult.top = new FormAttachment( wEncoding, margin );
wAddResult.setLayoutData( fdAddResult );
fdAddFileResult = new FormData();
fdAddFileResult.left = new FormAttachment( 0, margin );
fdAddFileResult.top = new FormAttachment( wEncoding, margin );
fdAddFileResult.right = new FormAttachment( 100, -margin );
wAddFileResult.setLayoutData( fdAddFileResult );
//
// / END OF AddFileResult GROUP
//
fdContentComp = new FormData();
fdContentComp.left = new FormAttachment( 0, 0 );
fdContentComp.top = new FormAttachment( 0, 0 );
fdContentComp.right = new FormAttachment( 100, 0 );
fdContentComp.bottom = new FormAttachment( 100, 0 );
wContentComp.setLayoutData( fdContentComp );
wContentComp.layout();
wContentTab.setControl( wContentComp );
//
// / END OF CONTENT TAB
//
//
// / START OF CONTENT TAB
//
addErrorTab();
// Fields tab...
//
wFieldsTab = new CTabItem( wTabFolder, SWT.NONE );
wFieldsTab.setText( BaseMessages.getString( PKG, "ExcelInputDialog.FieldsTab.TabTitle" ) );
FormLayout fieldsLayout = new FormLayout();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
wFieldsComp = new Composite( wTabFolder, SWT.NONE );
wFieldsComp.setLayout( fieldsLayout );
wbGetFields = new Button( wFieldsComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbGetFields );
wbGetFields.setText( BaseMessages.getString( PKG, "ExcelInputDialog.GetFields.Button" ) );
setButtonPositions( new Button[] { wbGetFields }, margin, null );
final int FieldsRows = input.getField().length;
int FieldsWidth = 600;
int FieldsHeight = 150;
ColumnInfo[] colinf =
new ColumnInfo[] {
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Name.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Type.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO,
ValueMeta.getTypes() ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Length.Column" ), ColumnInfo.COLUMN_TYPE_TEXT,
false ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Precision.Column" ), ColumnInfo.COLUMN_TYPE_TEXT,
false ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.TrimType.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO,
ValueMeta.trimTypeDesc ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Repeat.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO,
new String[] {
BaseMessages.getString( PKG, "System.Combo.Yes" ),
BaseMessages.getString( PKG, "System.Combo.No" ) } ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Format.Column" ), ColumnInfo.COLUMN_TYPE_FORMAT, 2 ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Currency.Column" ), ColumnInfo.COLUMN_TYPE_TEXT ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Decimal.Column" ), ColumnInfo.COLUMN_TYPE_TEXT ),
new ColumnInfo(
BaseMessages.getString( PKG, "ExcelInputDialog.Grouping.Column" ), ColumnInfo.COLUMN_TYPE_TEXT ) };
colinf[5].setToolTip( BaseMessages.getString( PKG, "ExcelInputDialog.Repeat.Tooltip" ) );
wFields =
new TableView( transMeta, wFieldsComp, SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props );
wFields.setSize( FieldsWidth, FieldsHeight );
wFields.addModifyListener( new ModifyListener() {
public void modifyText( ModifyEvent arg0 ) {
checkAlerts();
}
} );
fdFields = new FormData();
fdFields.left = new FormAttachment( 0, 0 );
fdFields.top = new FormAttachment( 0, 0 );
fdFields.right = new FormAttachment( 100, 0 );
fdFields.bottom = new FormAttachment( wbGetFields, -margin );
wFields.setLayoutData( fdFields );
fdFieldsComp = new FormData();
fdFieldsComp.left = new FormAttachment( 0, 0 );
fdFieldsComp.top = new FormAttachment( 0, 0 );
fdFieldsComp.right = new FormAttachment( 100, 0 );
fdFieldsComp.bottom = new FormAttachment( 100, 0 );
wFieldsComp.setLayoutData( fdFieldsComp );
wFieldsComp.layout();
wFieldsTab.setControl( wFieldsComp );
props.setLook( wFieldsComp );
addAdditionalFieldsTab();
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment( 0, 0 );
fdTabFolder.top = new FormAttachment( wlStatusMessage, margin );
fdTabFolder.right = new FormAttachment( 100, 0 );
fdTabFolder.bottom = new FormAttachment( 100, -50 );
wTabFolder.setLayoutData( fdTabFolder );
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
wPreview = new Button( shell, SWT.PUSH );
wPreview.setText( BaseMessages.getString( PKG, "ExcelInputDialog.PreviewRows.Button" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
setButtonPositions( new Button[] { wOK, wPreview, wCancel }, margin, wTabFolder );
// Add listeners
lsOK = new Listener() {
public void handleEvent( Event e ) {
ok();
}
};
lsPreview = new Listener() {
public void handleEvent( Event e ) {
preview();
}
};
lsCancel = new Listener() {
public void handleEvent( Event e ) {
cancel();
}
};
wOK.addListener( SWT.Selection, lsOK );
wPreview.addListener( SWT.Selection, lsPreview );
wCancel.addListener( SWT.Selection, lsCancel );
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
wFilename.addSelectionListener( lsDef );
wLimit.addSelectionListener( lsDef );
wInclRownumField.addSelectionListener( lsDef );
wInclFilenameField.addSelectionListener( lsDef );
wInclSheetnameField.addSelectionListener( lsDef );
wAccField.addSelectionListener( lsDef );
// Add the file to the list of files...
SelectionAdapter selA = new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
wFilenameList.add( new String[] {
wFilename.getText(), wFilemask.getText(), wExcludeFilemask.getText(),
ExcelInputMeta.RequiredFilesCode[0], ExcelInputMeta.RequiredFilesCode[0] } );
wFilename.setText( "" );
wFilemask.setText( "" );
wExcludeFilemask.setText( "" );
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
wFilenameList.optWidth( true );
checkAlerts();
}
};
wbaFilename.addSelectionListener( selA );
wFilename.addSelectionListener( selA );
// Delete files from the list of files...
wbdFilename.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
int[] idx = wFilenameList.getSelectionIndices();
wFilenameList.remove( idx );
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
checkAlerts();
}
} );
// Edit the selected file & remove from the list...
wbeFilename.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
int idx = wFilenameList.getSelectionIndex();
if ( idx >= 0 ) {
String[] string = wFilenameList.getItem( idx );
wFilename.setText( string[0] );
wFilemask.setText( string[1] );
wExcludeFilemask.setText( string[2] );
wFilenameList.remove( idx );
}
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
}
} );
// Show the files that are selected at this time...
wbShowFiles.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
showFiles();
}
} );
// Whenever something changes, set the tooltip to the expanded version of the filename:
wFilename.addModifyListener( new ModifyListener() {
public void modifyText( ModifyEvent e ) {
wFilename.setToolTipText( transMeta.environmentSubstitute( wFilename.getText() ) );
}
} );
// Listen to the Browse... button
wbbFilename.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
if ( !Const.isEmpty( wFilemask.getText() ) || !Const.isEmpty( wExcludeFilemask.getText() ) ) // A mask: a
// directory!
{
DirectoryDialog dialog = new DirectoryDialog( shell, SWT.OPEN );
if ( wFilename.getText() != null ) {
String fpath = transMeta.environmentSubstitute( wFilename.getText() );
dialog.setFilterPath( fpath );
}
if ( dialog.open() != null ) {
String str = dialog.getFilterPath();
wFilename.setText( str );
}
} else {
FileDialog dialog = new FileDialog( shell, SWT.OPEN );
String[] extentions = new String[] { "*.xls;*.XLS", "*" };
SpreadSheetType type = SpreadSheetType.getStpreadSheetTypeByDescription( wSpreadSheetType.getText() );
switch ( type ) {
case POI:
extentions = new String[] { "*.xls;*.XLS;*.xlxs;*.XLSX", "*" };
break;
case ODS:
extentions = new String[] { "*.ods;*.ODS;", "*" };
break;
case JXL:
default:
extentions = new String[] { "*.xls;*.XLS", "*" };
break;
}
dialog.setFilterExtensions( extentions );
if ( wFilename.getText() != null ) {
String fname = transMeta.environmentSubstitute( wFilename.getText() );
dialog.setFileName( fname );
}
dialog.setFilterNames( new String[] {
BaseMessages.getString( PKG, "ExcelInputDialog.FilterNames.ExcelFiles" ),
BaseMessages.getString( PKG, "System.FileType.AllFiles" ) } );
if ( dialog.open() != null ) {
String str = dialog.getFilterPath() + System.getProperty( "file.separator" ) + dialog.getFileName();
wFilename.setText( str );
}
}
}
} );
// Get a list of the sheetnames.
wbGetSheets.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
getSheets();
}
} );
wbGetFields.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
getFields();
}
} );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
wTabFolder.setSelection( 0 );
// Set the shell size, based upon previous time...
setSize();
getData( input );
input.setChanged( changed );
wFields.optWidth( true );
checkAlerts(); // resyncing after setup
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
public void setFlags() {
wbGetFields.setEnabled( wHeader.getSelection() );
boolean accept = wAccFilenames.getSelection();
wlAccField.setEnabled( accept );
wAccField.setEnabled( accept );
wlAccStep.setEnabled( accept );
wAccStep.setEnabled( accept );
wlFilename.setEnabled( !accept );
wbbFilename.setEnabled( !accept ); // Browse: add file or directory
wbdFilename.setEnabled( !accept ); // Delete
wbeFilename.setEnabled( !accept ); // Edit
wbaFilename.setEnabled( !accept ); // Add or change
wFilename.setEnabled( !accept );
wlFilenameList.setEnabled( !accept );
wFilenameList.setEnabled( !accept );
wlFilemask.setEnabled( !accept );
wlExcludeFilemask.setEnabled( !accept );
wExcludeFilemask.setEnabled( !accept );
wFilemask.setEnabled( !accept );
wbShowFiles.setEnabled( !accept );
// wPreview.setEnabled(!accept); // Keep this one: you can do preview on defined files in the files section.
// Error handling tab...
wlSkipErrorLines.setEnabled( wErrorIgnored.getSelection() );
wSkipErrorLines.setEnabled( wErrorIgnored.getSelection() );
wlErrorDestDir.setEnabled( wErrorIgnored.getSelection() );
wErrorDestDir.setEnabled( wErrorIgnored.getSelection() );
wlErrorExt.setEnabled( wErrorIgnored.getSelection() );
wErrorExt.setEnabled( wErrorIgnored.getSelection() );
wbbErrorDestDir.setEnabled( wErrorIgnored.getSelection() );
wbvErrorDestDir.setEnabled( wErrorIgnored.getSelection() );
wlWarningDestDir.setEnabled( wErrorIgnored.getSelection() );
wWarningDestDir.setEnabled( wErrorIgnored.getSelection() );
wlWarningExt.setEnabled( wErrorIgnored.getSelection() );
wWarningExt.setEnabled( wErrorIgnored.getSelection() );
wbbWarningDestDir.setEnabled( wErrorIgnored.getSelection() );
wbvWarningDestDir.setEnabled( wErrorIgnored.getSelection() );
wlLineNrDestDir.setEnabled( wErrorIgnored.getSelection() );
wLineNrDestDir.setEnabled( wErrorIgnored.getSelection() );
wlLineNrExt.setEnabled( wErrorIgnored.getSelection() );
wLineNrExt.setEnabled( wErrorIgnored.getSelection() );
wbbLineNrDestDir.setEnabled( wErrorIgnored.getSelection() );
wbvLineNrDestDir.setEnabled( wErrorIgnored.getSelection() );
}
/**
* Read the data from the ExcelInputMeta object and show it in this dialog.
*
* @param meta
* The ExcelInputMeta object to obtain the data from.
*/
public void getData( ExcelInputMeta meta ) {
if ( meta.getFileName() != null ) {
wFilenameList.removeAll();
for ( int i = 0; i < meta.getFileName().length; i++ ) {
wFilenameList.add( new String[] {
meta.getFileName()[i], meta.getFileMask()[i], meta.getExludeFileMask()[i],
meta.getRequiredFilesDesc( meta.getFileRequired()[i] ),
meta.getRequiredFilesDesc( meta.getIncludeSubFolders()[i] ) } );
}
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
wFilenameList.optWidth( true );
}
wAccFilenames.setSelection( meta.isAcceptingFilenames() );
if ( meta.getAcceptingField() != null && !meta.getAcceptingField().equals( "" ) ) {
wAccField.select( wAccField.indexOf( meta.getAcceptingField() ) );
}
if ( meta.getAcceptingStepName() != null && !meta.getAcceptingStepName().equals( "" ) ) {
wAccStep.select( wAccStep.indexOf( meta.getAcceptingStepName() ) );
}
wHeader.setSelection( meta.startsWithHeader() );
wNoempty.setSelection( meta.ignoreEmptyRows() );
wStoponempty.setSelection( meta.stopOnEmpty() );
if ( meta.getFileField() != null ) {
wInclFilenameField.setText( meta.getFileField() );
}
if ( meta.getSheetField() != null ) {
wInclSheetnameField.setText( meta.getSheetField() );
}
if ( meta.getSheetRowNumberField() != null ) {
wInclSheetRownumField.setText( meta.getSheetRowNumberField() );
}
if ( meta.getRowNumberField() != null ) {
wInclRownumField.setText( meta.getRowNumberField() );
}
wLimit.setText( "" + meta.getRowLimit() );
wEncoding.setText( Const.NVL( meta.getEncoding(), "" ) );
wSpreadSheetType.setText( meta.getSpreadSheetType().getDescription() );
wAddResult.setSelection( meta.isAddResultFile() );
if ( isDebug() ) {
logDebug( "getting fields info..." );
}
for ( int i = 0; i < meta.getField().length; i++ ) {
TableItem item = wFields.table.getItem( i );
String field = meta.getField()[i].getName();
String type = meta.getField()[i].getTypeDesc();
String length = "" + meta.getField()[i].getLength();
String prec = "" + meta.getField()[i].getPrecision();
String trim = meta.getField()[i].getTrimTypeDesc();
String rep =
meta.getField()[i].isRepeated() ? BaseMessages.getString( PKG, "System.Combo.Yes" ) : BaseMessages
.getString( PKG, "System.Combo.No" );
String format = meta.getField()[i].getFormat();
String currency = meta.getField()[i].getCurrencySymbol();
String decimal = meta.getField()[i].getDecimalSymbol();
String grouping = meta.getField()[i].getGroupSymbol();
if ( field != null ) {
item.setText( 1, field );
}
if ( type != null ) {
item.setText( 2, type );
}
if ( length != null ) {
item.setText( 3, length );
}
if ( prec != null ) {
item.setText( 4, prec );
}
if ( trim != null ) {
item.setText( 5, trim );
}
if ( rep != null ) {
item.setText( 6, rep );
}
if ( format != null ) {
item.setText( 7, format );
}
if ( currency != null ) {
item.setText( 8, currency );
}
if ( decimal != null ) {
item.setText( 9, decimal );
}
if ( grouping != null ) {
item.setText( 10, grouping );
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth( true );
logDebug( "getting sheets info..." );
for ( int i = 0; i < meta.getSheetName().length; i++ ) {
TableItem item = wSheetnameList.table.getItem( i );
String sheetname = meta.getSheetName()[i];
String startrow = "" + meta.getStartRow()[i];
String startcol = "" + meta.getStartColumn()[i];
if ( sheetname != null ) {
item.setText( 1, sheetname );
}
if ( startrow != null ) {
item.setText( 2, startrow );
}
if ( startcol != null ) {
item.setText( 3, startcol );
}
}
wSheetnameList.removeEmptyRows();
wSheetnameList.setRowNums();
wSheetnameList.optWidth( true );
// Error handling fields...
wErrorIgnored.setSelection( meta.isErrorIgnored() );
wStrictTypes.setSelection( meta.isStrictTypes() );
wSkipErrorLines.setSelection( meta.isErrorLineSkipped() );
if ( meta.getWarningFilesDestinationDirectory() != null ) {
wWarningDestDir.setText( meta.getWarningFilesDestinationDirectory() );
}
if ( meta.getBadLineFilesExtension() != null ) {
wWarningExt.setText( meta.getBadLineFilesExtension() );
}
if ( meta.getErrorFilesDestinationDirectory() != null ) {
wErrorDestDir.setText( meta.getErrorFilesDestinationDirectory() );
}
if ( meta.getErrorFilesExtension() != null ) {
wErrorExt.setText( meta.getErrorFilesExtension() );
}
if ( meta.getLineNumberFilesDestinationDirectory() != null ) {
wLineNrDestDir.setText( meta.getLineNumberFilesDestinationDirectory() );
}
if ( meta.getLineNumberFilesExtension() != null ) {
wLineNrExt.setText( meta.getLineNumberFilesExtension() );
}
if ( meta.getPathField() != null ) {
wPathFieldName.setText( meta.getPathField() );
}
if ( meta.getShortFileNameField() != null ) {
wShortFileFieldName.setText( meta.getShortFileNameField() );
}
if ( meta.getPathField() != null ) {
wPathFieldName.setText( meta.getPathField() );
}
if ( meta.isHiddenField() != null ) {
wIsHiddenName.setText( meta.isHiddenField() );
}
if ( meta.getLastModificationDateField() != null ) {
wLastModificationTimeName.setText( meta.getLastModificationDateField() );
}
if ( meta.getUriField() != null ) {
wUriName.setText( meta.getUriField() );
}
if ( meta.getRootUriField() != null ) {
wRootUriName.setText( meta.getRootUriField() );
}
if ( meta.getExtensionField() != null ) {
wExtensionFieldName.setText( meta.getExtensionField() );
}
if ( meta.getSizeField() != null ) {
wSizeFieldName.setText( meta.getSizeField() );
}
setFlags();
wStepname.selectAll();
wStepname.setFocus();
}
private void cancel() {
stepname = null;
input.setChanged( changed );
dispose();
}
private void ok() {
if ( Const.isEmpty( wStepname.getText() ) ) {
return;
}
getInfo( input );
dispose();
}
private void getInfo( ExcelInputMeta meta ) {
stepname = wStepname.getText(); // return value
// copy info to Meta class (input)
meta.setRowLimit( Const.toLong( wLimit.getText(), 0 ) );
meta.setEncoding( wEncoding.getText() );
meta.setSpreadSheetType( SpreadSheetType.values()[wSpreadSheetType.getSelectionIndex()] );
meta.setFileField( wInclFilenameField.getText() );
meta.setSheetField( wInclSheetnameField.getText() );
meta.setSheetRowNumberField( wInclSheetRownumField.getText() );
meta.setRowNumberField( wInclRownumField.getText() );
meta.setAddResultFile( wAddResult.getSelection() );
meta.setStartsWithHeader( wHeader.getSelection() );
meta.setIgnoreEmptyRows( wNoempty.getSelection() );
meta.setStopOnEmpty( wStoponempty.getSelection() );
meta.setAcceptingFilenames( wAccFilenames.getSelection() );
meta.setAcceptingField( wAccField.getText() );
meta.setAcceptingStepName( wAccStep.getText() );
meta.searchInfoAndTargetSteps( transMeta.findPreviousSteps( transMeta.findStep( stepname ) ) );
int nrfiles = wFilenameList.nrNonEmpty();
int nrsheets = wSheetnameList.nrNonEmpty();
int nrfields = wFields.nrNonEmpty();
meta.allocate( nrfiles, nrsheets, nrfields );
meta.setFileName( wFilenameList.getItems( 0 ) );
meta.setFileMask( wFilenameList.getItems( 1 ) );
meta.setExcludeFileMask( wFilenameList.getItems( 2 ) );
meta.setFileRequired( wFilenameList.getItems( 3 ) );
meta.setIncludeSubFolders( wFilenameList.getItems( 4 ) );
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < nrsheets; i++ ) {
TableItem item = wSheetnameList.getNonEmpty( i );
meta.getSheetName()[i] = item.getText( 1 );
meta.getStartRow()[i] = Const.toInt( item.getText( 2 ), 0 );
meta.getStartColumn()[i] = Const.toInt( item.getText( 3 ), 0 );
}
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < nrfields; i++ ) {
TableItem item = wFields.getNonEmpty( i );
meta.getField()[i] = new ExcelInputField();
meta.getField()[i].setName( item.getText( 1 ) );
meta.getField()[i].setType( ValueMeta.getType( item.getText( 2 ) ) );
String slength = item.getText( 3 );
String sprec = item.getText( 4 );
meta.getField()[i].setTrimType( ExcelInputMeta.getTrimTypeByDesc( item.getText( 5 ) ) );
meta.getField()[i].setRepeated( BaseMessages.getString( PKG, "System.Combo.Yes" ).equalsIgnoreCase(
item.getText( 6 ) ) );
meta.getField()[i].setLength( Const.toInt( slength, -1 ) );
meta.getField()[i].setPrecision( Const.toInt( sprec, -1 ) );
meta.getField()[i].setFormat( item.getText( 7 ) );
meta.getField()[i].setCurrencySymbol( item.getText( 8 ) );
meta.getField()[i].setDecimalSymbol( item.getText( 9 ) );
meta.getField()[i].setGroupSymbol( item.getText( 10 ) );
}
// Error handling fields...
meta.setStrictTypes( wStrictTypes.getSelection() );
meta.setErrorIgnored( wErrorIgnored.getSelection() );
meta.setErrorLineSkipped( wSkipErrorLines.getSelection() );
meta.setWarningFilesDestinationDirectory( wWarningDestDir.getText() );
meta.setBadLineFilesExtension( wWarningExt.getText() );
meta.setErrorFilesDestinationDirectory( wErrorDestDir.getText() );
meta.setErrorFilesExtension( wErrorExt.getText() );
meta.setLineNumberFilesDestinationDirectory( wLineNrDestDir.getText() );
meta.setLineNumberFilesExtension( wLineNrExt.getText() );
meta.setShortFileNameField( wShortFileFieldName.getText() );
meta.setPathField( wPathFieldName.getText() );
meta.setIsHiddenField( wIsHiddenName.getText() );
meta.setLastModificationDateField( wLastModificationTimeName.getText() );
meta.setUriField( wUriName.getText() );
meta.setRootUriField( wRootUriName.getText() );
meta.setExtensionField( wExtensionFieldName.getText() );
meta.setSizeField( wSizeFieldName.getText() );
}
private void addErrorTab() {
//
// START OF ERROR TAB /
// /
wErrorTab = new CTabItem( wTabFolder, SWT.NONE );
wErrorTab.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ErrorTab.TabTitle" ) );
FormLayout errorLayout = new FormLayout();
errorLayout.marginWidth = 3;
errorLayout.marginHeight = 3;
wErrorComp = new Composite( wTabFolder, SWT.NONE );
props.setLook( wErrorComp );
wErrorComp.setLayout( errorLayout );
// ERROR HANDLING...
// ErrorIgnored?
wlStrictTypes = new Label( wErrorComp, SWT.RIGHT );
wlStrictTypes.setText( BaseMessages.getString( PKG, "ExcelInputDialog.StrictTypes.Label" ) );
props.setLook( wlStrictTypes );
fdlStrictTypes = new FormData();
fdlStrictTypes.left = new FormAttachment( 0, 0 );
fdlStrictTypes.top = new FormAttachment( 0, margin );
fdlStrictTypes.right = new FormAttachment( middle, -margin );
wlStrictTypes.setLayoutData( fdlStrictTypes );
wStrictTypes = new Button( wErrorComp, SWT.CHECK );
props.setLook( wStrictTypes );
wStrictTypes.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.StrictTypes.Tooltip" ) );
fdStrictTypes = new FormData();
fdStrictTypes.left = new FormAttachment( middle, 0 );
fdStrictTypes.top = new FormAttachment( 0, margin );
wStrictTypes.setLayoutData( fdStrictTypes );
Control previous = wStrictTypes;
// ErrorIgnored?
wlErrorIgnored = new Label( wErrorComp, SWT.RIGHT );
wlErrorIgnored.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ErrorIgnored.Label" ) );
props.setLook( wlErrorIgnored );
fdlErrorIgnored = new FormData();
fdlErrorIgnored.left = new FormAttachment( 0, 0 );
fdlErrorIgnored.top = new FormAttachment( previous, margin );
fdlErrorIgnored.right = new FormAttachment( middle, -margin );
wlErrorIgnored.setLayoutData( fdlErrorIgnored );
wErrorIgnored = new Button( wErrorComp, SWT.CHECK );
props.setLook( wErrorIgnored );
wErrorIgnored.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.ErrorIgnored.Tooltip" ) );
fdErrorIgnored = new FormData();
fdErrorIgnored.left = new FormAttachment( middle, 0 );
fdErrorIgnored.top = new FormAttachment( previous, margin );
wErrorIgnored.setLayoutData( fdErrorIgnored );
previous = wErrorIgnored;
wErrorIgnored.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
setFlags();
}
} );
// Skip error lines?
wlSkipErrorLines = new Label( wErrorComp, SWT.RIGHT );
wlSkipErrorLines.setText( BaseMessages.getString( PKG, "ExcelInputDialog.SkipErrorLines.Label" ) );
props.setLook( wlSkipErrorLines );
fdlSkipErrorLines = new FormData();
fdlSkipErrorLines.left = new FormAttachment( 0, 0 );
fdlSkipErrorLines.top = new FormAttachment( previous, margin );
fdlSkipErrorLines.right = new FormAttachment( middle, -margin );
wlSkipErrorLines.setLayoutData( fdlSkipErrorLines );
wSkipErrorLines = new Button( wErrorComp, SWT.CHECK );
props.setLook( wSkipErrorLines );
wSkipErrorLines.setToolTipText( BaseMessages.getString( PKG, "ExcelInputDialog.SkipErrorLines.Tooltip" ) );
fdSkipErrorLines = new FormData();
fdSkipErrorLines.left = new FormAttachment( middle, 0 );
fdSkipErrorLines.top = new FormAttachment( previous, margin );
wSkipErrorLines.setLayoutData( fdSkipErrorLines );
previous = wSkipErrorLines;
// Bad lines files directory + extention
// WarningDestDir line
wlWarningDestDir = new Label( wErrorComp, SWT.RIGHT );
wlWarningDestDir.setText( BaseMessages.getString( PKG, "ExcelInputDialog.WarningDestDir.Label" ) );
props.setLook( wlWarningDestDir );
fdlWarningDestDir = new FormData();
fdlWarningDestDir.left = new FormAttachment( 0, 0 );
fdlWarningDestDir.top = new FormAttachment( previous, margin * 4 );
fdlWarningDestDir.right = new FormAttachment( middle, -margin );
wlWarningDestDir.setLayoutData( fdlWarningDestDir );
wbbWarningDestDir = new Button( wErrorComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbbWarningDestDir );
wbbWarningDestDir.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) );
wbbWarningDestDir.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.BrowseForDir" ) );
fdbWarningDestDir = new FormData();
fdbWarningDestDir.right = new FormAttachment( 100, 0 );
fdbWarningDestDir.top = new FormAttachment( previous, margin * 4 );
wbbWarningDestDir.setLayoutData( fdbWarningDestDir );
wbvWarningDestDir = new Button( wErrorComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbvWarningDestDir );
wbvWarningDestDir.setText( BaseMessages.getString( PKG, "System.Button.Variable" ) );
wbvWarningDestDir.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.VariableToDir" ) );
fdbvWarningDestDir = new FormData();
fdbvWarningDestDir.right = new FormAttachment( wbbWarningDestDir, -margin );
fdbvWarningDestDir.top = new FormAttachment( previous, margin * 4 );
wbvWarningDestDir.setLayoutData( fdbvWarningDestDir );
wWarningExt = new Text( wErrorComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wWarningExt );
wWarningExt.addModifyListener( lsMod );
fdWarningDestExt = new FormData();
fdWarningDestExt.left = new FormAttachment( wbvWarningDestDir, -150 );
fdWarningDestExt.right = new FormAttachment( wbvWarningDestDir, -margin );
fdWarningDestExt.top = new FormAttachment( previous, margin * 4 );
wWarningExt.setLayoutData( fdWarningDestExt );
wlWarningExt = new Label( wErrorComp, SWT.RIGHT );
wlWarningExt.setText( BaseMessages.getString( PKG, "System.Label.Extension" ) );
props.setLook( wlWarningExt );
fdlWarningDestExt = new FormData();
fdlWarningDestExt.top = new FormAttachment( previous, margin * 4 );
fdlWarningDestExt.right = new FormAttachment( wWarningExt, -margin );
wlWarningExt.setLayoutData( fdlWarningDestExt );
wWarningDestDir = new Text( wErrorComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wWarningDestDir );
wWarningDestDir.addModifyListener( lsMod );
fdWarningDestDir = new FormData();
fdWarningDestDir.left = new FormAttachment( middle, 0 );
fdWarningDestDir.right = new FormAttachment( wlWarningExt, -margin );
fdWarningDestDir.top = new FormAttachment( previous, margin * 4 );
wWarningDestDir.setLayoutData( fdWarningDestDir );
// Listen to the Browse... button
wbbWarningDestDir.addSelectionListener( DirectoryDialogButtonListenerFactory.getSelectionAdapter(
shell, wWarningDestDir ) );
// Listen to the Variable... button
wbvWarningDestDir.addSelectionListener( VariableButtonListenerFactory.getSelectionAdapter(
shell, wWarningDestDir, transMeta ) );
// Whenever something changes, set the tooltip to the expanded version of the directory:
wWarningDestDir.addModifyListener( getModifyListenerTooltipText( wWarningDestDir ) );
// Error lines files directory + extention
previous = wWarningDestDir;
// ErrorDestDir line
wlErrorDestDir = new Label( wErrorComp, SWT.RIGHT );
wlErrorDestDir.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ErrorDestDir.Label" ) );
props.setLook( wlErrorDestDir );
fdlErrorDestDir = new FormData();
fdlErrorDestDir.left = new FormAttachment( 0, 0 );
fdlErrorDestDir.top = new FormAttachment( previous, margin );
fdlErrorDestDir.right = new FormAttachment( middle, -margin );
wlErrorDestDir.setLayoutData( fdlErrorDestDir );
wbbErrorDestDir = new Button( wErrorComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbbErrorDestDir );
wbbErrorDestDir.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) );
wbbErrorDestDir.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.BrowseForDir" ) );
fdbErrorDestDir = new FormData();
fdbErrorDestDir.right = new FormAttachment( 100, 0 );
fdbErrorDestDir.top = new FormAttachment( previous, margin );
wbbErrorDestDir.setLayoutData( fdbErrorDestDir );
wbvErrorDestDir = new Button( wErrorComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbvErrorDestDir );
wbvErrorDestDir.setText( BaseMessages.getString( PKG, "System.Button.Variable" ) );
wbvErrorDestDir.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.VariableToDir" ) );
fdbvErrorDestDir = new FormData();
fdbvErrorDestDir.right = new FormAttachment( wbbErrorDestDir, -margin );
fdbvErrorDestDir.top = new FormAttachment( previous, margin );
wbvErrorDestDir.setLayoutData( fdbvErrorDestDir );
wErrorExt = new Text( wErrorComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wErrorExt );
wErrorExt.addModifyListener( lsMod );
fdErrorDestExt = new FormData();
fdErrorDestExt.left = new FormAttachment( wbvErrorDestDir, -150 );
fdErrorDestExt.right = new FormAttachment( wbvErrorDestDir, -margin );
fdErrorDestExt.top = new FormAttachment( previous, margin );
wErrorExt.setLayoutData( fdErrorDestExt );
wlErrorExt = new Label( wErrorComp, SWT.RIGHT );
wlErrorExt.setText( BaseMessages.getString( PKG, "System.Label.Extension" ) );
props.setLook( wlErrorExt );
fdlErrorDestExt = new FormData();
fdlErrorDestExt.top = new FormAttachment( previous, margin );
fdlErrorDestExt.right = new FormAttachment( wErrorExt, -margin );
wlErrorExt.setLayoutData( fdlErrorDestExt );
wErrorDestDir = new Text( wErrorComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wErrorDestDir );
wErrorDestDir.addModifyListener( lsMod );
fdErrorDestDir = new FormData();
fdErrorDestDir.left = new FormAttachment( middle, 0 );
fdErrorDestDir.right = new FormAttachment( wlErrorExt, -margin );
fdErrorDestDir.top = new FormAttachment( previous, margin );
wErrorDestDir.setLayoutData( fdErrorDestDir );
// Listen to the Browse... button
wbbErrorDestDir.addSelectionListener( DirectoryDialogButtonListenerFactory.getSelectionAdapter(
shell, wErrorDestDir ) );
// Listen to the Variable... button
wbvErrorDestDir.addSelectionListener( VariableButtonListenerFactory.getSelectionAdapter(
shell, wErrorDestDir, transMeta ) );
// Whenever something changes, set the tooltip to the expanded version of the directory:
wErrorDestDir.addModifyListener( getModifyListenerTooltipText( wErrorDestDir ) );
// Line numbers files directory + extention
previous = wErrorDestDir;
// LineNrDestDir line
wlLineNrDestDir = new Label( wErrorComp, SWT.RIGHT );
wlLineNrDestDir.setText( BaseMessages.getString( PKG, "ExcelInputDialog.LineNrDestDir.Label" ) );
props.setLook( wlLineNrDestDir );
fdlLineNrDestDir = new FormData();
fdlLineNrDestDir.left = new FormAttachment( 0, 0 );
fdlLineNrDestDir.top = new FormAttachment( previous, margin );
fdlLineNrDestDir.right = new FormAttachment( middle, -margin );
wlLineNrDestDir.setLayoutData( fdlLineNrDestDir );
wbbLineNrDestDir = new Button( wErrorComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbbLineNrDestDir );
wbbLineNrDestDir.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) );
wbbLineNrDestDir.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.BrowseForDir" ) );
fdbLineNrDestDir = new FormData();
fdbLineNrDestDir.right = new FormAttachment( 100, 0 );
fdbLineNrDestDir.top = new FormAttachment( previous, margin );
wbbLineNrDestDir.setLayoutData( fdbLineNrDestDir );
wbvLineNrDestDir = new Button( wErrorComp, SWT.PUSH | SWT.CENTER );
props.setLook( wbvLineNrDestDir );
wbvLineNrDestDir.setText( BaseMessages.getString( PKG, "System.Button.Variable" ) );
wbvLineNrDestDir.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.VariableToDir" ) );
fdbvLineNrDestDir = new FormData();
fdbvLineNrDestDir.right = new FormAttachment( wbbLineNrDestDir, -margin );
fdbvLineNrDestDir.top = new FormAttachment( previous, margin );
wbvLineNrDestDir.setLayoutData( fdbvLineNrDestDir );
wLineNrExt = new Text( wErrorComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wLineNrExt );
wLineNrExt.addModifyListener( lsMod );
fdLineNrDestExt = new FormData();
fdLineNrDestExt.left = new FormAttachment( wbvLineNrDestDir, -150 );
fdLineNrDestExt.right = new FormAttachment( wbvLineNrDestDir, -margin );
fdLineNrDestExt.top = new FormAttachment( previous, margin );
wLineNrExt.setLayoutData( fdLineNrDestExt );
wlLineNrExt = new Label( wErrorComp, SWT.RIGHT );
wlLineNrExt.setText( BaseMessages.getString( PKG, "System.Label.Extension" ) );
props.setLook( wlLineNrExt );
fdlLineNrDestExt = new FormData();
fdlLineNrDestExt.top = new FormAttachment( previous, margin );
fdlLineNrDestExt.right = new FormAttachment( wLineNrExt, -margin );
wlLineNrExt.setLayoutData( fdlLineNrDestExt );
wLineNrDestDir = new Text( wErrorComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wLineNrDestDir );
wLineNrDestDir.addModifyListener( lsMod );
fdLineNrDestDir = new FormData();
fdLineNrDestDir.left = new FormAttachment( middle, 0 );
fdLineNrDestDir.right = new FormAttachment( wlLineNrExt, -margin );
fdLineNrDestDir.top = new FormAttachment( previous, margin );
wLineNrDestDir.setLayoutData( fdLineNrDestDir );
// Listen to the Browse... button
wbbLineNrDestDir.addSelectionListener( DirectoryDialogButtonListenerFactory.getSelectionAdapter(
shell, wLineNrDestDir ) );
// Listen to the Variable... button
wbvLineNrDestDir.addSelectionListener( VariableButtonListenerFactory.getSelectionAdapter(
shell, wLineNrDestDir, transMeta ) );
// Whenever something changes, set the tooltip to the expanded version of the directory:
wLineNrDestDir.addModifyListener( getModifyListenerTooltipText( wLineNrDestDir ) );
wErrorComp.layout();
wErrorTab.setControl( wErrorComp );
//
// / END OF CONTENT TAB
//
}
/**
* Preview the data generated by this step. This generates a transformation using this step & a dummy and previews it.
*
*/
private void preview() {
// Create the excel reader step...
ExcelInputMeta oneMeta = new ExcelInputMeta();
getInfo( oneMeta );
if ( oneMeta.isAcceptingFilenames() ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "ExcelInputDialog.Dialog.SpecifyASampleFile.Message" ) ); // Nothing
// found
// that
// matches
// your
// criteria
mb.setText( BaseMessages.getString( PKG, "ExcelInputDialog.Dialog.SpecifyASampleFile.Title" ) ); // Sorry!
mb.open();
return;
}
TransMeta previewMeta =
TransPreviewFactory.generatePreviewTransformation( transMeta, oneMeta, wStepname.getText() );
EnterNumberDialog numberDialog =
new EnterNumberDialog( shell, props.getDefaultPreviewSize(), BaseMessages.getString(
PKG, "ExcelInputDialog.PreviewSize.DialogTitle" ), BaseMessages.getString(
PKG, "ExcelInputDialog.PreviewSize.DialogMessage" ) );
int previewSize = numberDialog.open();
if ( previewSize > 0 ) {
TransPreviewProgressDialog progressDialog =
new TransPreviewProgressDialog(
shell, previewMeta, new String[] { wStepname.getText() }, new int[] { previewSize } );
progressDialog.open();
Trans trans = progressDialog.getTrans();
String loggingText = progressDialog.getLoggingText();
if ( !progressDialog.isCancelled() ) {
if ( trans.getResult() != null && trans.getResult().getNrErrors() > 0 ) {
EnterTextDialog etd =
new EnterTextDialog(
shell, BaseMessages.getString( PKG, "System.Dialog.PreviewError.Title" ), BaseMessages
.getString( PKG, "System.Dialog.PreviewError.Message" ), loggingText, true );
etd.setReadOnly();
etd.open();
}
}
PreviewRowsDialog prd =
new PreviewRowsDialog(
shell, transMeta, SWT.NONE, wStepname.getText(), progressDialog.getPreviewRowsMeta( wStepname
.getText() ), progressDialog.getPreviewRows( wStepname.getText() ), loggingText );
prd.open();
}
}
/**
* Get the names of the sheets from the Excel workbooks and let the user select some or all of them.
*
*/
public void getSheets() {
List<String> sheetnames = new ArrayList<String>();
ExcelInputMeta info = new ExcelInputMeta();
getInfo( info );
FileInputList fileList = info.getFileList( transMeta );
for ( FileObject fileObject : fileList.getFiles() ) {
try {
KWorkbook workbook =
WorkbookFactory.getWorkbook( info.getSpreadSheetType(), KettleVFS.getFilename( fileObject ), info
.getEncoding() );
int nrSheets = workbook.getNumberOfSheets();
for ( int j = 0; j < nrSheets; j++ ) {
KSheet sheet = workbook.getSheet( j );
String sheetname = sheet.getName();
if ( Const.indexOfString( sheetname, sheetnames ) < 0 ) {
sheetnames.add( sheetname );
}
}
workbook.close();
} catch ( Exception e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "System.Dialog.Error.Title" ), BaseMessages.getString(
PKG, "ExcelInputDialog.ErrorReadingFile.DialogMessage", KettleVFS.getFilename( fileObject ) ), e );
}
}
// Put it in an array:
String[] lst = sheetnames.toArray( new String[sheetnames.size()] );
// Let the user select the sheet-names...
EnterListDialog esd = new EnterListDialog( shell, SWT.NONE, lst );
String[] selection = esd.open();
if ( selection != null ) {
for ( int j = 0; j < selection.length; j++ ) {
wSheetnameList.add( new String[] { selection[j], "" } );
}
wSheetnameList.removeEmptyRows();
wSheetnameList.setRowNums();
wSheetnameList.optWidth( true );
checkAlerts();
}
}
/**
* Get the list of fields in the Excel workbook and put the result in the fields table view.
*/
public void getFields() {
RowMetaInterface fields = new RowMeta();
ExcelInputMeta info = new ExcelInputMeta();
getInfo( info );
int clearFields = SWT.YES;
if ( wFields.nrNonEmpty() > 0 ) {
MessageBox messageBox = new MessageBox( shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_QUESTION );
messageBox.setMessage( BaseMessages.getString( PKG, "ExcelInputDialog.ClearFieldList.DialogMessage" ) );
messageBox.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ClearFieldList.DialogTitle" ) );
clearFields = messageBox.open();
if ( clearFields == SWT.CANCEL ) {
return;
}
}
FileInputList fileList = info.getFileList( transMeta );
for ( FileObject file : fileList.getFiles() ) {
try {
KWorkbook workbook =
WorkbookFactory.getWorkbook( info.getSpreadSheetType(), KettleVFS.getFilename( file ), info
.getEncoding() );
int nrSheets = workbook.getNumberOfSheets();
for ( int j = 0; j < nrSheets; j++ ) {
KSheet sheet = workbook.getSheet( j );
// See if it's a selected sheet:
int sheetIndex;
if ( info.readAllSheets() ) {
sheetIndex = 0;
} else {
sheetIndex = Const.indexOfString( sheet.getName(), info.getSheetName() );
}
if ( sheetIndex >= 0 ) {
// We suppose it's the complete range we're looking for...
//
int rownr = 0;
int startcol = 0;
if ( info.readAllSheets() ) {
if ( info.getStartColumn().length == 1 ) {
startcol = info.getStartColumn()[0];
}
if ( info.getStartRow().length == 1 ) {
rownr = info.getStartRow()[0];
}
} else {
rownr = info.getStartRow()[sheetIndex];
startcol = info.getStartColumn()[sheetIndex];
}
boolean stop = false;
for ( int colnr = startcol; colnr < 256 && !stop; colnr++ ) {
try {
String fieldname = null;
int fieldtype = ValueMetaInterface.TYPE_NONE;
KCell cell = sheet.getCell( colnr, rownr );
if ( cell == null ) {
stop = true;
} else {
if ( cell.getType() != KCellType.EMPTY ) {
// We found a field.
fieldname = cell.getContents();
}
// System.out.println("Fieldname = "+fieldname);
KCell below = sheet.getCell( colnr, rownr + 1 );
if ( below != null ) {
if ( below.getType() == KCellType.BOOLEAN ) {
fieldtype = ValueMetaInterface.TYPE_BOOLEAN;
} else if ( below.getType() == KCellType.DATE ) {
fieldtype = ValueMetaInterface.TYPE_DATE;
} else if ( below.getType() == KCellType.LABEL ) {
fieldtype = ValueMetaInterface.TYPE_STRING;
} else if ( below.getType() == KCellType.NUMBER ) {
fieldtype = ValueMetaInterface.TYPE_NUMBER;
} else {
fieldtype = ValueMetaInterface.TYPE_STRING;
}
} else {
fieldtype = ValueMetaInterface.TYPE_STRING;
}
if ( Const.isEmpty( fieldname ) ) {
stop = true;
} else {
if ( fieldtype != ValueMetaInterface.TYPE_NONE ) {
ValueMetaInterface field = ValueMetaFactory.createValueMeta( fieldname, fieldtype );
fields.addValueMeta( field );
}
}
}
} catch ( ArrayIndexOutOfBoundsException aioobe ) {
// System.out.println("index out of bounds at column "+colnr+" : "+aioobe.toString());
stop = true;
}
}
}
}
workbook.close();
} catch ( Exception e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "System.Dialog.Error.Title" ), BaseMessages
.getString( PKG, "ExcelInputDialog.ErrorReadingFile2.DialogMessage", KettleVFS.getFilename( file ), e
.toString() ), e );
}
}
if ( fields.size() > 0 ) {
if ( clearFields == SWT.YES ) {
wFields.clearAll( false );
}
for ( int j = 0; j < fields.size(); j++ ) {
ValueMetaInterface field = fields.getValueMeta( j );
wFields.add( new String[] { field.getName(), field.getTypeDesc(), "", "", "none", "N" } );
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth( true );
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_WARNING );
mb.setMessage( BaseMessages.getString( PKG, "ExcelInputDialog.UnableToFindFields.DialogMessage" ) );
mb.setText( BaseMessages.getString( PKG, "ExcelInputDialog.UnableToFindFields.DialogTitle" ) );
mb.open();
}
checkAlerts();
}
private void showFiles() {
ExcelInputMeta eii = new ExcelInputMeta();
getInfo( eii );
String[] files = eii.getFilePaths( transMeta );
if ( files.length > 0 ) {
EnterSelectionDialog esd =
new EnterSelectionDialog( shell, files,
BaseMessages.getString( PKG, "ExcelInputDialog.FilesRead.DialogTitle" ),
BaseMessages.getString( PKG, "ExcelInputDialog.FilesRead.DialogMessage" ) );
esd.setViewOnly();
esd.open();
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "ExcelInputDialog.NoFilesFound.DialogMessage" ) );
mb.setText( BaseMessages.getString( PKG, "System.Dialog.Error.Title" ) );
mb.open();
}
}
private void setEncodings() {
// Encoding of the text file:
if ( !gotEncodings ) {
gotEncodings = true;
wEncoding.removeAll();
List<Charset> values = new ArrayList<Charset>( Charset.availableCharsets().values() );
for ( int i = 0; i < values.size(); i++ ) {
Charset charSet = values.get( i );
wEncoding.add( charSet.displayName() );
}
// Now select the default!
String defEncoding = Const.getEnvironmentVariable( "file.encoding", "UTF-8" );
int idx = Const.indexOfString( defEncoding, wEncoding.getItems() );
if ( idx >= 0 ) {
wEncoding.select( idx );
}
}
}
/**
* It is perfectly permissible to put away an incomplete step definition. However, to assist the user in setting up
* the full kit, this method is invoked whenever data changes in the dialog. It scans the dialog's model looking for
* missing and/or inconsistent data. Tabs needing attention are visually flagged and attention messages are displayed
* in the statusMessage line (a la Eclipse).
*
* Since there's only one statusMessage line, messages are prioritized. As each higher-level item is corrected, the
* next lower level message is displayed.
*
* @author Tim Holloway <timh@mousetech.com>
* @since 15-FEB-2008
*/
private void checkAlerts() {
logDebug( "checkAlerts" );
// # Check the fields tab. At least one field is required.
// # Check the Sheets tab. At least one sheet is required.
// # Check the Files tab.
final boolean fieldsOk = wFields.nrNonEmpty() != 0;
final boolean sheetsOk = wSheetnameList.nrNonEmpty() != 0;
final boolean filesOk =
wFilenameList.nrNonEmpty() != 0
|| ( wAccFilenames.getSelection() && !Const.isEmpty( wAccField.getText() ) );
String msgText = ""; // Will clear status if no actions.
// Assign the highest-priority action message.
if ( !fieldsOk ) {
// TODO: NLS
msgText = ( BaseMessages.getString( PKG, "ExcelInputDialog.AddFields" ) );
} else if ( !sheetsOk ) {
// TODO: NLS
msgText = ( BaseMessages.getString( PKG, "ExcelInputDialog.AddSheets" ) );
} else if ( !filesOk ) {
// TODO: NLS
msgText = ( BaseMessages.getString( PKG, "ExcelInputDialog.AddFilenames" ) );
}
tagTab( !fieldsOk, wFieldsTab, BaseMessages.getString( PKG, "ExcelInputDialog.FieldsTab.TabTitle" ) );
tagTab( !sheetsOk, wSheetTab, BaseMessages.getString( PKG, "ExcelInputDialog.SheetsTab.TabTitle" ) );
tagTab( !filesOk, wFileTab, BaseMessages.getString( PKG, "ExcelInputDialog.FileTab.TabTitle" ) );
wPreview.setEnabled( fieldsOk && sheetsOk && filesOk );
wlStatusMessage.setText( msgText );
}
/**
* Hilight (or not) tab to indicate if action is required.
*
* @param hilightMe
* <code>true</code> to highlight, <code>false</code> if not.
* @param tabItem
* Tab to highlight
* @param tabCaption
* Tab text (normally fetched from resource).
*/
private void tagTab( boolean hilightMe, CTabItem tabItem, String tabCaption ) {
if ( hilightMe ) {
tabItem.setText( TAB_FLAG + tabCaption );
} else {
tabItem.setText( tabCaption );
}
}
private void addAdditionalFieldsTab() {
//
// START OF ADDITIONAL FIELDS TAB /
//
wAdditionalFieldsTab = new CTabItem( wTabFolder, SWT.NONE );
wAdditionalFieldsTab.setText( BaseMessages.getString( PKG, "ExcelInputDialog.AdditionalFieldsTab.TabTitle" ) );
wAdditionalFieldsComp = new Composite( wTabFolder, SWT.NONE );
props.setLook( wAdditionalFieldsComp );
FormLayout fieldsLayout = new FormLayout();
fieldsLayout.marginWidth = 3;
fieldsLayout.marginHeight = 3;
wAdditionalFieldsComp.setLayout( fieldsLayout );
wlInclFilenameField = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlInclFilenameField.setText( BaseMessages.getString( PKG, "ExcelInputDialog.InclFilenameField.Label" ) );
props.setLook( wlInclFilenameField );
fdlInclFilenameField = new FormData();
fdlInclFilenameField.left = new FormAttachment( 0, 0 );
fdlInclFilenameField.top = new FormAttachment( wStepname, margin );
fdlInclFilenameField.right = new FormAttachment( middle, -margin );
wlInclFilenameField.setLayoutData( fdlInclFilenameField );
wInclFilenameField = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wInclFilenameField );
wInclFilenameField.addModifyListener( lsMod );
fdInclFilenameField = new FormData();
fdInclFilenameField.left = new FormAttachment( middle, 0 );
fdInclFilenameField.top = new FormAttachment( wStepname, margin );
fdInclFilenameField.right = new FormAttachment( 100, 0 );
wInclFilenameField.setLayoutData( fdInclFilenameField );
wlInclSheetnameField = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlInclSheetnameField.setText( BaseMessages.getString( PKG, "ExcelInputDialog.InclSheetnameField.Label" ) );
props.setLook( wlInclSheetnameField );
fdlInclSheetnameField = new FormData();
fdlInclSheetnameField.left = new FormAttachment( 0, 0 );
fdlInclSheetnameField.top = new FormAttachment( wInclFilenameField, margin );
fdlInclSheetnameField.right = new FormAttachment( middle, -margin );
wlInclSheetnameField.setLayoutData( fdlInclSheetnameField );
wInclSheetnameField = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wInclSheetnameField );
wInclSheetnameField.addModifyListener( lsMod );
fdInclSheetnameField = new FormData();
fdInclSheetnameField.left = new FormAttachment( middle, 0 );
fdInclSheetnameField.top = new FormAttachment( wInclFilenameField, margin );
fdInclSheetnameField.right = new FormAttachment( 100, 0 );
wInclSheetnameField.setLayoutData( fdInclSheetnameField );
wlInclSheetRownumField = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlInclSheetRownumField.setText( BaseMessages.getString( PKG, "ExcelInputDialog.InclSheetRownumField.Label" ) );
props.setLook( wlInclSheetRownumField );
fdlInclSheetRownumField = new FormData();
fdlInclSheetRownumField.left = new FormAttachment( 0, 0 );
fdlInclSheetRownumField.top = new FormAttachment( wInclSheetnameField, margin );
fdlInclSheetRownumField.right = new FormAttachment( middle, -margin );
wlInclSheetRownumField.setLayoutData( fdlInclSheetRownumField );
wInclSheetRownumField = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wInclSheetRownumField );
wInclSheetRownumField.addModifyListener( lsMod );
fdInclSheetRownumField = new FormData();
fdInclSheetRownumField.left = new FormAttachment( middle, 0 );
fdInclSheetRownumField.top = new FormAttachment( wInclSheetnameField, margin );
fdInclSheetRownumField.right = new FormAttachment( 100, 0 );
wInclSheetRownumField.setLayoutData( fdInclSheetRownumField );
wlInclRownumField = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlInclRownumField.setText( BaseMessages.getString( PKG, "ExcelInputDialog.InclRownumField.Label" ) );
props.setLook( wlInclRownumField );
fdlInclRownumField = new FormData();
fdlInclRownumField.left = new FormAttachment( 0, 0 );
fdlInclRownumField.top = new FormAttachment( wInclSheetRownumField, margin );
fdlInclRownumField.right = new FormAttachment( middle, -margin );
wlInclRownumField.setLayoutData( fdlInclRownumField );
wInclRownumField = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wInclRownumField );
wInclRownumField.addModifyListener( lsMod );
fdInclRownumField = new FormData();
fdInclRownumField.left = new FormAttachment( middle, 0 );
fdInclRownumField.top = new FormAttachment( wInclSheetRownumField, margin );
fdInclRownumField.right = new FormAttachment( 100, 0 );
wInclRownumField.setLayoutData( fdInclRownumField );
// ShortFileFieldName line
wlShortFileFieldName = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlShortFileFieldName.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ShortFileFieldName.Label" ) );
props.setLook( wlShortFileFieldName );
fdlShortFileFieldName = new FormData();
fdlShortFileFieldName.left = new FormAttachment( 0, 0 );
fdlShortFileFieldName.top = new FormAttachment( wInclRownumField, margin );
fdlShortFileFieldName.right = new FormAttachment( middle, -margin );
wlShortFileFieldName.setLayoutData( fdlShortFileFieldName );
wShortFileFieldName = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wShortFileFieldName );
wShortFileFieldName.addModifyListener( lsMod );
fdShortFileFieldName = new FormData();
fdShortFileFieldName.left = new FormAttachment( middle, 0 );
fdShortFileFieldName.right = new FormAttachment( 100, -margin );
fdShortFileFieldName.top = new FormAttachment( wInclRownumField, margin );
wShortFileFieldName.setLayoutData( fdShortFileFieldName );
// ExtensionFieldName line
wlExtensionFieldName = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlExtensionFieldName.setText( BaseMessages.getString( PKG, "ExcelInputDialog.ExtensionFieldName.Label" ) );
props.setLook( wlExtensionFieldName );
fdlExtensionFieldName = new FormData();
fdlExtensionFieldName.left = new FormAttachment( 0, 0 );
fdlExtensionFieldName.top = new FormAttachment( wShortFileFieldName, margin );
fdlExtensionFieldName.right = new FormAttachment( middle, -margin );
wlExtensionFieldName.setLayoutData( fdlExtensionFieldName );
wExtensionFieldName = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wExtensionFieldName );
wExtensionFieldName.addModifyListener( lsMod );
fdExtensionFieldName = new FormData();
fdExtensionFieldName.left = new FormAttachment( middle, 0 );
fdExtensionFieldName.right = new FormAttachment( 100, -margin );
fdExtensionFieldName.top = new FormAttachment( wShortFileFieldName, margin );
wExtensionFieldName.setLayoutData( fdExtensionFieldName );
// PathFieldName line
wlPathFieldName = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlPathFieldName.setText( BaseMessages.getString( PKG, "ExcelInputDialog.PathFieldName.Label" ) );
props.setLook( wlPathFieldName );
fdlPathFieldName = new FormData();
fdlPathFieldName.left = new FormAttachment( 0, 0 );
fdlPathFieldName.top = new FormAttachment( wExtensionFieldName, margin );
fdlPathFieldName.right = new FormAttachment( middle, -margin );
wlPathFieldName.setLayoutData( fdlPathFieldName );
wPathFieldName = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wPathFieldName );
wPathFieldName.addModifyListener( lsMod );
fdPathFieldName = new FormData();
fdPathFieldName.left = new FormAttachment( middle, 0 );
fdPathFieldName.right = new FormAttachment( 100, -margin );
fdPathFieldName.top = new FormAttachment( wExtensionFieldName, margin );
wPathFieldName.setLayoutData( fdPathFieldName );
// SizeFieldName line
wlSizeFieldName = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlSizeFieldName.setText( BaseMessages.getString( PKG, "ExcelInputDialog.SizeFieldName.Label" ) );
props.setLook( wlSizeFieldName );
fdlSizeFieldName = new FormData();
fdlSizeFieldName.left = new FormAttachment( 0, 0 );
fdlSizeFieldName.top = new FormAttachment( wPathFieldName, margin );
fdlSizeFieldName.right = new FormAttachment( middle, -margin );
wlSizeFieldName.setLayoutData( fdlSizeFieldName );
wSizeFieldName = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wSizeFieldName );
wSizeFieldName.addModifyListener( lsMod );
fdSizeFieldName = new FormData();
fdSizeFieldName.left = new FormAttachment( middle, 0 );
fdSizeFieldName.right = new FormAttachment( 100, -margin );
fdSizeFieldName.top = new FormAttachment( wPathFieldName, margin );
wSizeFieldName.setLayoutData( fdSizeFieldName );
// IsHiddenName line
wlIsHiddenName = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlIsHiddenName.setText( BaseMessages.getString( PKG, "ExcelInputDialog.IsHiddenName.Label" ) );
props.setLook( wlIsHiddenName );
fdlIsHiddenName = new FormData();
fdlIsHiddenName.left = new FormAttachment( 0, 0 );
fdlIsHiddenName.top = new FormAttachment( wSizeFieldName, margin );
fdlIsHiddenName.right = new FormAttachment( middle, -margin );
wlIsHiddenName.setLayoutData( fdlIsHiddenName );
wIsHiddenName = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wIsHiddenName );
wIsHiddenName.addModifyListener( lsMod );
fdIsHiddenName = new FormData();
fdIsHiddenName.left = new FormAttachment( middle, 0 );
fdIsHiddenName.right = new FormAttachment( 100, -margin );
fdIsHiddenName.top = new FormAttachment( wSizeFieldName, margin );
wIsHiddenName.setLayoutData( fdIsHiddenName );
// LastModificationTimeName line
wlLastModificationTimeName = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlLastModificationTimeName.setText( BaseMessages.getString(
PKG, "ExcelInputDialog.LastModificationTimeName.Label" ) );
props.setLook( wlLastModificationTimeName );
fdlLastModificationTimeName = new FormData();
fdlLastModificationTimeName.left = new FormAttachment( 0, 0 );
fdlLastModificationTimeName.top = new FormAttachment( wIsHiddenName, margin );
fdlLastModificationTimeName.right = new FormAttachment( middle, -margin );
wlLastModificationTimeName.setLayoutData( fdlLastModificationTimeName );
wLastModificationTimeName = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wLastModificationTimeName );
wLastModificationTimeName.addModifyListener( lsMod );
fdLastModificationTimeName = new FormData();
fdLastModificationTimeName.left = new FormAttachment( middle, 0 );
fdLastModificationTimeName.right = new FormAttachment( 100, -margin );
fdLastModificationTimeName.top = new FormAttachment( wIsHiddenName, margin );
wLastModificationTimeName.setLayoutData( fdLastModificationTimeName );
// UriName line
wlUriName = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlUriName.setText( BaseMessages.getString( PKG, "ExcelInputDialog.UriName.Label" ) );
props.setLook( wlUriName );
fdlUriName = new FormData();
fdlUriName.left = new FormAttachment( 0, 0 );
fdlUriName.top = new FormAttachment( wLastModificationTimeName, margin );
fdlUriName.right = new FormAttachment( middle, -margin );
wlUriName.setLayoutData( fdlUriName );
wUriName = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wUriName );
wUriName.addModifyListener( lsMod );
fdUriName = new FormData();
fdUriName.left = new FormAttachment( middle, 0 );
fdUriName.right = new FormAttachment( 100, -margin );
fdUriName.top = new FormAttachment( wLastModificationTimeName, margin );
wUriName.setLayoutData( fdUriName );
// RootUriName line
wlRootUriName = new Label( wAdditionalFieldsComp, SWT.RIGHT );
wlRootUriName.setText( BaseMessages.getString( PKG, "ExcelInputDialog.RootUriName.Label" ) );
props.setLook( wlRootUriName );
fdlRootUriName = new FormData();
fdlRootUriName.left = new FormAttachment( 0, 0 );
fdlRootUriName.top = new FormAttachment( wUriName, margin );
fdlRootUriName.right = new FormAttachment( middle, -margin );
wlRootUriName.setLayoutData( fdlRootUriName );
wRootUriName = new Text( wAdditionalFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wRootUriName );
wRootUriName.addModifyListener( lsMod );
fdRootUriName = new FormData();
fdRootUriName.left = new FormAttachment( middle, 0 );
fdRootUriName.right = new FormAttachment( 100, -margin );
fdRootUriName.top = new FormAttachment( wUriName, margin );
wRootUriName.setLayoutData( fdRootUriName );
fdAdditionalFieldsComp = new FormData();
fdAdditionalFieldsComp.left = new FormAttachment( 0, 0 );
fdAdditionalFieldsComp.top = new FormAttachment( wStepname, margin );
fdAdditionalFieldsComp.right = new FormAttachment( 100, 0 );
fdAdditionalFieldsComp.bottom = new FormAttachment( 100, 0 );
wAdditionalFieldsComp.setLayoutData( fdAdditionalFieldsComp );
wAdditionalFieldsComp.layout();
wAdditionalFieldsTab.setControl( wAdditionalFieldsComp );
//
// / END OF ADDITIONAL FIELDS TAB
//
}
}
| apache-2.0 |
tubemogul/druid | extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/firehose/cloudfiles/StaticCloudFilesFirehoseFactory.java | 4772 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.firehose.cloudfiles;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.metamx.common.CompressionUtils;
import com.metamx.common.logger.Logger;
import com.metamx.common.parsers.ParseException;
import io.druid.data.input.Firehose;
import io.druid.data.input.FirehoseFactory;
import io.druid.data.input.impl.FileIteratingFirehose;
import io.druid.data.input.impl.StringInputRowParser;
import io.druid.storage.cloudfiles.CloudFilesByteSource;
import io.druid.storage.cloudfiles.CloudFilesObjectApiProxy;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class StaticCloudFilesFirehoseFactory implements FirehoseFactory<StringInputRowParser>
{
private static final Logger log = new Logger(StaticCloudFilesFirehoseFactory.class);
private final CloudFilesApi cloudFilesApi;
private final List<CloudFilesBlob> blobs;
@JsonCreator
public StaticCloudFilesFirehoseFactory(
@JacksonInject("objectApi") CloudFilesApi cloudFilesApi,
@JsonProperty("blobs") CloudFilesBlob[] blobs
)
{
this.cloudFilesApi = cloudFilesApi;
this.blobs = ImmutableList.copyOf(blobs);
}
@JsonProperty
public List<CloudFilesBlob> getBlobs()
{
return blobs;
}
@Override
public Firehose connect(StringInputRowParser stringInputRowParser) throws IOException, ParseException
{
Preconditions.checkNotNull(cloudFilesApi, "null cloudFilesApi");
final LinkedList<CloudFilesBlob> objectQueue = Lists.newLinkedList(blobs);
return new FileIteratingFirehose(
new Iterator<LineIterator>()
{
@Override
public boolean hasNext()
{
return !objectQueue.isEmpty();
}
@Override
public LineIterator next()
{
final CloudFilesBlob nextURI = objectQueue.poll();
final String region = nextURI.getRegion();
final String container = nextURI.getContainer();
final String path = nextURI.getPath();
log.info("Retrieving file from region[%s], container[%s] and path [%s]",
region, container, path
);
CloudFilesObjectApiProxy objectApi = new CloudFilesObjectApiProxy(
cloudFilesApi, region, container);
final CloudFilesByteSource byteSource = new CloudFilesByteSource(objectApi, path);
try {
final InputStream innerInputStream = byteSource.openStream();
final InputStream outerInputStream = path.endsWith(".gz")
? CompressionUtils.gzipInputStream(innerInputStream)
: innerInputStream;
return IOUtils.lineIterator(
new BufferedReader(
new InputStreamReader(outerInputStream, Charsets.UTF_8)));
}
catch (IOException e) {
log.error(e,
"Exception opening container[%s] blob[%s] from region[%s]",
container, path, region
);
throw Throwables.propagate(e);
}
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
},
stringInputRowParser
);
}
}
| apache-2.0 |
mglukhikh/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/VcsManagerConfigurable.java | 5963 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.configurable;
import com.intellij.application.options.colors.fileStatus.FileStatusColorsConfigurable;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurableEP;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.VcsConfigurableProvider;
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl;
import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictConfigurable;
import com.intellij.openapi.vcs.changes.ui.IgnoredSettingsPanel;
import com.intellij.openapi.vcs.impl.VcsDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
import java.util.Set;
import static com.intellij.openapi.options.ex.ConfigurableWrapper.wrapConfigurable;
import static com.intellij.util.ArrayUtil.toObjectArray;
import static com.intellij.util.ObjectUtils.notNull;
import static com.intellij.util.containers.ContainerUtil.*;
public class VcsManagerConfigurable extends SearchableConfigurable.Parent.Abstract implements Configurable.NoScroll {
@NotNull private final Project myProject;
private VcsDirectoryConfigurationPanel myMappings;
private VcsGeneralConfigurationConfigurable myGeneralPanel;
public VcsManagerConfigurable(@NotNull Project project) {
myProject = project;
}
@Override
public JComponent createComponent() {
myMappings = new VcsDirectoryConfigurationPanel(myProject);
return myMappings;
}
@Override
public boolean hasOwnContent() {
return true;
}
@Override
public boolean isModified() {
return myMappings != null && myMappings.isModified();
}
@Override
public void apply() throws ConfigurationException {
super.apply();
myMappings.apply();
}
@Override
public void reset() {
super.reset();
myMappings.reset();
}
@Override
public void disposeUIResources() {
super.disposeUIResources();
if (myMappings != null) {
myMappings.disposeUIResources();
}
if (myGeneralPanel != null) {
myGeneralPanel.disposeUIResources();
}
myMappings = null;
}
@Override
public String getDisplayName() {
return VcsBundle.message("version.control.main.configurable.name");
}
@Override
@NotNull
public String getHelpTopic() {
return "project.propVCSSupport.Mappings";
}
@Override
@NotNull
public String getId() {
return getHelpTopic();
}
@Override
protected Configurable[] buildConfigurables() {
myGeneralPanel = new VcsGeneralConfigurationConfigurable(myProject, this);
List<Configurable> result = newArrayList();
result.add(myGeneralPanel);
result.add(new VcsBackgroundOperationsConfigurable(myProject));
if (!myProject.isDefault()) {
result.add(new IgnoredSettingsPanel(myProject));
}
result.add(new IssueNavigationConfigurationPanel(myProject));
if (!myProject.isDefault()) {
result.add(new ChangelistConflictConfigurable(ChangeListManagerImpl.getInstanceImpl(myProject)));
}
result.add(new CommitDialogConfigurable(myProject));
result.add(new ShelfProjectConfigurable(myProject));
for (VcsConfigurableProvider provider : VcsConfigurableProvider.EP_NAME.getExtensions()) {
addIfNotNull(result, provider.getConfigurable(myProject));
}
result.add(new FileStatusColorsConfigurable());
Set<String> projectConfigurableIds = map2Set(myProject.getExtensions(Configurable.PROJECT_CONFIGURABLE), ep -> ep.id);
for (VcsDescriptor descriptor : ProjectLevelVcsManager.getInstance(myProject).getAllVcss()) {
if (!projectConfigurableIds.contains(getVcsConfigurableId(descriptor.getDisplayName()))) {
result.add(wrapConfigurable(new VcsConfigurableEP(myProject, descriptor)));
}
}
return toObjectArray(result, Configurable.class);
}
@Nullable
public VcsDirectoryConfigurationPanel getMappings() {
return myMappings;
}
@NotNull
public static String getVcsConfigurableId(@NotNull String displayName) {
return "vcs." + displayName;
}
private static class VcsConfigurableEP extends ConfigurableEP<Configurable> {
private static final int WEIGHT = -500;
@NotNull private final VcsDescriptor myDescriptor;
public VcsConfigurableEP(@NotNull Project project, @NotNull VcsDescriptor descriptor) {
super(project);
myDescriptor = descriptor;
displayName = descriptor.getDisplayName();
id = getVcsConfigurableId(descriptor.getDisplayName());
groupWeight = WEIGHT;
}
@NotNull
@Override
protected ConfigurableEP.ObjectProducer createProducer() {
return new ObjectProducer() {
@Override
protected Object createElement() {
return notNull(ProjectLevelVcsManager.getInstance(getProject()).findVcsByName(myDescriptor.getName())).getConfigurable();
}
@Override
protected boolean canCreateElement() {
return true;
}
@Override
protected Class<?> getType() {
return SearchableConfigurable.class;
}
};
}
}
}
| apache-2.0 |
fanhattan/ExoPlayer | library/src/main/java/com/google/android/exoplayer2/text/SubtitleInputBuffer.java | 1466 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.text;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
/**
* A {@link DecoderInputBuffer} for a {@link SubtitleDecoder}.
*/
public final class SubtitleInputBuffer extends DecoderInputBuffer
implements Comparable<SubtitleInputBuffer> {
/**
* An offset that must be added to the subtitle's event times after it's been decoded, or
* {@link Format#OFFSET_SAMPLE_RELATIVE} if {@link #timeUs} should be added.
*/
public long subsampleOffsetUs;
public SubtitleInputBuffer() {
super(DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_NORMAL);
}
@Override
public int compareTo(SubtitleInputBuffer other) {
long delta = timeUs - other.timeUs;
if (delta == 0) {
return 0;
}
return delta > 0 ? 1 : -1;
}
}
| apache-2.0 |
sheofir/aws-sdk-java | aws-java-sdk-swf-libraries/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowWorker.java | 7969 | /*
* Copyright 2012-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowDefinitionFactoryFactory;
import com.amazonaws.services.simpleworkflow.flow.worker.GenericWorkflowWorker;
public class WorkflowWorker implements WorkerBase {
private final GenericWorkflowWorker genericWorker;
private final POJOWorkflowDefinitionFactoryFactory factoryFactory = new POJOWorkflowDefinitionFactoryFactory();
private final Collection<Class<?>> workflowImplementationTypes = new ArrayList<Class<?>>();
public WorkflowWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll) {
genericWorker = new GenericWorkflowWorker(service, domain, taskListToPoll);
genericWorker.setWorkflowDefinitionFactoryFactory(factoryFactory);
}
@Override
public AmazonSimpleWorkflow getService() {
return genericWorker.getService();
}
@Override
public String getDomain() {
return genericWorker.getDomain();
}
@Override
public boolean isRegisterDomain() {
return genericWorker.isRegisterDomain();
}
@Override
public void setRegisterDomain(boolean registerDomain) {
genericWorker.setRegisterDomain(registerDomain);
}
@Override
public long getDomainRetentionPeriodInDays() {
return genericWorker.getDomainRetentionPeriodInDays();
}
@Override
public void setDomainRetentionPeriodInDays(long domainRetentionPeriodInDays) {
genericWorker.setDomainRetentionPeriodInDays(domainRetentionPeriodInDays);
}
@Override
public String getTaskListToPoll() {
return genericWorker.getTaskListToPoll();
}
@Override
public double getMaximumPollRatePerSecond() {
return genericWorker.getMaximumPollRatePerSecond();
}
@Override
public void setMaximumPollRatePerSecond(double maximumPollRatePerSecond) {
genericWorker.setMaximumPollRatePerSecond(maximumPollRatePerSecond);
}
@Override
public int getMaximumPollRateIntervalMilliseconds() {
return genericWorker.getMaximumPollRateIntervalMilliseconds();
}
@Override
public void setMaximumPollRateIntervalMilliseconds(int maximumPollRateIntervalMilliseconds) {
genericWorker.setMaximumPollRateIntervalMilliseconds(maximumPollRateIntervalMilliseconds);
}
@Override
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return genericWorker.getUncaughtExceptionHandler();
}
@Override
public void setUncaughtExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler) {
genericWorker.setUncaughtExceptionHandler(uncaughtExceptionHandler);
}
@Override
public String getIdentity() {
return genericWorker.getIdentity();
}
@Override
public void setIdentity(String identity) {
genericWorker.setIdentity(identity);
}
@Override
public long getPollBackoffInitialInterval() {
return genericWorker.getPollBackoffInitialInterval();
}
@Override
public void setPollBackoffInitialInterval(long backoffInitialInterval) {
genericWorker.setPollBackoffInitialInterval(backoffInitialInterval);
}
@Override
public long getPollBackoffMaximumInterval() {
return genericWorker.getPollBackoffMaximumInterval();
}
@Override
public void setPollBackoffMaximumInterval(long backoffMaximumInterval) {
genericWorker.setPollBackoffMaximumInterval(backoffMaximumInterval);
}
@Override
public boolean isDisableServiceShutdownOnStop() {
return genericWorker.isDisableServiceShutdownOnStop();
}
@Override
public void setDisableServiceShutdownOnStop(boolean disableServiceShutdownOnStop) {
genericWorker.setDisableServiceShutdownOnStop(disableServiceShutdownOnStop);
}
@Override
public double getPollBackoffCoefficient() {
return genericWorker.getPollBackoffCoefficient();
}
@Override
public void setPollBackoffCoefficient(double backoffCoefficient) {
genericWorker.setPollBackoffCoefficient(backoffCoefficient);
}
@Override
public int getPollThreadCount() {
return genericWorker.getPollThreadCount();
}
@Override
public void setPollThreadCount(int threadCount) {
genericWorker.setPollThreadCount(threadCount);
}
@Override
public void registerTypesToPoll() {
genericWorker.registerTypesToPoll();
}
@Override
public void start() {
genericWorker.start();
}
@Override
public void shutdown() {
genericWorker.shutdown();
}
@Override
public void shutdownNow() {
genericWorker.shutdownNow();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return genericWorker.awaitTermination(timeout, unit);
}
@Override
public boolean isRunning() {
return genericWorker.isRunning();
}
@Override
public void suspendPolling() {
genericWorker.suspendPolling();
}
@Override
public void resumePolling() {
genericWorker.resumePolling();
}
public void setWorkflowImplementationTypes(Collection<Class<?>> workflowImplementationTypes)
throws InstantiationException, IllegalAccessException {
for (Class<?> workflowImplementationType : workflowImplementationTypes) {
addWorkflowImplementationType(workflowImplementationType);
}
}
public Collection<Class<?>> getWorkflowImplementationTypes() {
return workflowImplementationTypes;
}
public void addWorkflowImplementationType(Class<?> workflowImplementationType) throws InstantiationException, IllegalAccessException {
factoryFactory.addWorkflowImplementationType(workflowImplementationType);
}
public void addWorkflowImplementationType(Class<?> workflowImplementationType, DataConverter converter) throws InstantiationException, IllegalAccessException {
factoryFactory.addWorkflowImplementationType(workflowImplementationType, converter);
}
@Override
public String toString() {
return this.getClass().getSimpleName() + "[genericWorker=" + genericWorker + ", wokflowImplementationTypes="
+ workflowImplementationTypes + "]";
}
@Override
public boolean shutdownAndAwaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return genericWorker.shutdownAndAwaitTermination(timeout, unit);
}
public DataConverter getDataConverter() {
return factoryFactory.getDataConverter();
}
public void setDefaultConverter(DataConverter converter) {
factoryFactory.setDataConverter(converter);
}
@Override
public void setDisableTypeRegistrationOnStart(boolean disableTypeRegistrationOnStart) {
genericWorker.setDisableTypeRegistrationOnStart(disableTypeRegistrationOnStart);
}
@Override
public boolean isDisableTypeRegistrationOnStart() {
return genericWorker.isDisableTypeRegistrationOnStart();
}
}
| apache-2.0 |
Fudan-University/sakai | basiclti/tsugi-util/src/java/org/tsugi/basiclti/BasicLTIProviderUtil.java | 2782 | /*
* $URL$
* $Id$
*
* Copyright (c) 2008-2016 Charles R. Severance
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.tsugi.basiclti;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
public class BasicLTIProviderUtil {
private static Logger M_log = LoggerFactory.getLogger(BasicLTIProviderUtil.class);
public static final String EMAIL_TRUSTED_CONSUMER = "basiclti.provider.email.trusted.consumers";
public static final String HIGHLY_TRUSTED_CONSUMER = "basiclti.provider.highly.trusted.consumers";
public static boolean isHighlyTrustedConsumer(Map payload) {
String oauth_consumer_key = (String) payload.get("oauth_consumer_key");
boolean isHighlyTrustedConsumer = findTrustedConsumer(oauth_consumer_key, HIGHLY_TRUSTED_CONSUMER);
if (M_log.isDebugEnabled()) {
M_log.debug("Consumer=" + oauth_consumer_key);
M_log.debug("Trusted=" + isHighlyTrustedConsumer);
}
return isHighlyTrustedConsumer;
}
public static boolean isEmailTrustedConsumer(Map payload) {
String oauth_consumer_key = (String) payload.get("oauth_consumer_key");
return isEmailTrustedConsumer(oauth_consumer_key);
}
public static boolean isEmailTrustedConsumer(String oauth_consumer_key) {
boolean isEmailTrustedConsumer = findTrustedConsumer(oauth_consumer_key, EMAIL_TRUSTED_CONSUMER);
if (M_log.isDebugEnabled()) {
M_log.debug("Consumer=" + oauth_consumer_key);
M_log.debug("EmailTrusted=" + isEmailTrustedConsumer);
}
return isEmailTrustedConsumer;
}
private static boolean findTrustedConsumer(String oauth_consumer_key, String trustedConsumerProp) {
boolean isTrusted = false;
ServerConfigurationService cnf = (ServerConfigurationService) ComponentManager
.get(ServerConfigurationService.class);
final String trustedConsumersConfig = cnf.getString(trustedConsumerProp, null);
if (BasicLTIUtil.isNotBlank(trustedConsumersConfig)) {
List<String> consumersList = Arrays.asList(trustedConsumersConfig.split(":"));
if (consumersList.contains(oauth_consumer_key)) {
isTrusted = true;
}
}
return isTrusted;
}
}
| apache-2.0 |