repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
megadix/jfcm | src/main/java/org/megadix/jfcm/Constants.java | 1130 | /*
JFCM (Java Fuzzy Congnitive Maps)
Copyright (C) De Franciscis Dimitri - www.megadix.it
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option) any
later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc., 59
Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.megadix.jfcm;
public class Constants {
/**
* Pre-defined {@link ConceptActivator} implementations
*/
public enum ConceptActivatorTypes {
CAUCHY,
GAUSS,
INTERVAL,
LINEAR,
NARY,
SIGMOID,
SIGNUM,
TANH
}
}
| lgpl-2.1 |
kajona/kajonacms | module_system/admin/AdminBatchaction.php | 2868 | <?php
/*"******************************************************************************************************
* (c) 2007-2016 by Kajona, www.kajona.de *
* Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt *
*-------------------------------------------------------------------------------------------------------*
* $Id$ *
********************************************************************************************************/
namespace Kajona\System\Admin;
/**
* A massaction is a single, descriptive object to be rendered by the admin-toolkit.
* Each action may be called iterative for a set of systemid.
* The action is triggered by an ajax-request, the target-url is specified by the respective property.
* The target-url should provide a %systemid% element, being replaced before the triggering of the request.
*
*
* @author [email protected]
* @since 4.0
* @package module_system
*/
class AdminBatchaction {
private $strIcon;
private $strTitle;
private $strTargetUrl;
private $bitRenderInfo;
private $strOnClickHandler = "";
function __construct($strIcon, $strTargetUrl, $strTitle, $bitRenderInfo = false) {
$this->strIcon = $strIcon;
$this->strTargetUrl = $strTargetUrl;
$this->strTitle = $strTitle;
$this->bitRenderInfo = $bitRenderInfo;
$this->updateOnClick();
}
private function updateOnClick()
{
$this->strOnClickHandler = "require('lists').triggerAction('{$this->strTitle}', '{$this->strTargetUrl}', ".($this->getBitRenderInfo() ? "1" : "0").");";
}
public function setStrIcon($strIcon) {
$this->strIcon = $strIcon;
}
public function getStrIcon() {
return $this->strIcon;
}
public function setStrTargetUrl($strTargetUrl) {
$this->updateOnClick();
$this->strTargetUrl = $strTargetUrl;
}
public function getStrTargetUrl() {
return $this->strTargetUrl;
}
public function setStrTitle($strTitle) {
$this->updateOnClick();
$this->strTitle = $strTitle;
}
public function getStrTitle() {
return $this->strTitle;
}
public function setBitRenderInfo($bitRenderInfo)
{
$this->updateOnClick();
$this->bitRenderInfo = (bool) $bitRenderInfo;
}
public function getBitRenderInfo()
{
return $this->bitRenderInfo;
}
/**
* @return mixed
*/
public function getStrOnClickHandler()
{
return $this->strOnClickHandler;
}
/**
* @param mixed $strOnClickHandler
*/
public function setStrOnClickHandler($strOnClickHandler)
{
$this->strOnClickHandler = $strOnClickHandler;
}
}
| lgpl-2.1 |
rammstein/0install | tests/testdriver.py | 14498 | #!/usr/bin/env python
from basetest import BaseTest, StringIO
import sys, tempfile, os, logging
import unittest
sys.path.insert(0, '..')
from zeroinstall.injector import model, gpg, namespaces, reader, run, fetch
from zeroinstall.injector.requirements import Requirements
from zeroinstall.injector.driver import Driver
from zeroinstall.support import basedir, tasks
import data
foo_iface_uri = 'http://foo'
logger = logging.getLogger()
def recalculate(driver):
driver.need_download()
def download_and_execute(driver, prog_args, main = None, dry_run = True):
downloaded = driver.solve_and_download_impls()
if downloaded:
tasks.wait_for_blocker(downloaded)
run.execute_selections(driver.solver.selections, prog_args, stores = driver.config.stores, main = main, dry_run = dry_run)
class TestDriver(BaseTest):
def setUp(self):
BaseTest.setUp(self)
stream = tempfile.TemporaryFile(mode = 'w+b')
stream.write(data.thomas_key)
stream.seek(0)
gpg.import_key(stream)
stream.close()
def cache_iface(self, name, data):
cached_ifaces = basedir.save_cache_path('0install.net',
'interfaces')
f = open(os.path.join(cached_ifaces, model.escape(name)), 'w')
f.write(data)
f.close()
def testNoNeedDl(self):
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
assert driver.need_download()
driver = Driver(requirements = Requirements(os.path.abspath('Foo.xml')), config = self.config)
assert not driver.need_download()
assert driver.solver.ready
def testUnknownAlg(self):
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<implementation main='.' id='unknown=123' version='1.0'>
<archive href='http://foo/foo.tgz' size='100'/>
</implementation>
</interface>""" % foo_iface_uri)
self.config.fetcher = fetch.Fetcher(self.config)
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
try:
assert driver.need_download()
download_and_execute(driver, [])
except model.SafeException as ex:
assert "No digests for http://foo 1.0" in str(ex), ex
def testDownload(self):
tmp = tempfile.NamedTemporaryFile(mode = 'wt')
tmp.write(
"""<?xml version="1.0" ?>
<interface
main='ThisBetterNotExist'
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<implementation version='1.0' id='/bin'/>
</interface>""")
tmp.flush()
driver = Driver(requirements = Requirements(tmp.name), config = self.config)
old, sys.stdout = sys.stdout, StringIO()
try:
download_and_execute(driver, ['Hello'])
out = sys.stdout.getvalue()
finally:
sys.stdout = old
assert "[dry-run] would execute: /bin/ThisBetterNotExist Hello\n" == out, out
tmp.close()
def testNoMain(self):
tmp = tempfile.NamedTemporaryFile(mode = 'wt')
tmp.write(
"""<?xml version="1.0" ?>
<interface
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<implementation version='1.0' id='/bin'/>
</interface>""")
tmp.flush()
driver = Driver(requirements = Requirements(tmp.name), config = self.config)
try:
download_and_execute(driver, ['Hello'])
assert 0
except model.SafeException as ex:
assert "No run command" in str(ex), ex
tmp.close()
def testNeedDL(self):
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="0"
uri="%s"
main='ThisBetterNotExist'
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<implementation version='1.0' id='sha1=123'>
<archive href='http://foo/foo.tgz' size='100'/>
</implementation>
</interface>""" % foo_iface_uri)
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
self.config.network_use = model.network_full
recalculate(driver)
assert driver.need_download()
assert driver.solver.ready
def testBinding(self):
local_impl = os.path.dirname(os.path.abspath(__file__))
tmp = tempfile.NamedTemporaryFile(mode = 'wt')
tmp.write(
"""<?xml version="1.0" ?>
<interface
main='testdriver.py'
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Bar</name>
<summary>Bar</summary>
<description>Bar</description>
<group>
<requires interface='%s'>
<environment name='FOO_PATH' insert='.'/>
<environment name='BAR_PATH' insert='.' default='/a:/b'/>
<environment name='NO_PATH' value='val'/>
<environment name='XDG_DATA_DIRS' insert='.'/>
</requires>
<environment name='SELF_GROUP' insert='group' mode='replace'/>
<implementation version='1.0' id='%s'>
<environment name='SELF_IMPL' insert='impl' mode='replace'/>
</implementation>
</group>
</interface>""" % (foo_iface_uri, local_impl))
tmp.flush()
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="0"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<implementation version='1.0' id='sha1=123'/>
</interface>""" % foo_iface_uri)
cached_impl = basedir.save_cache_path('0install.net',
'implementations',
'sha1=123')
driver = Driver(requirements = Requirements(tmp.name), config = self.config)
self.config.network_use = model.network_offline
os.environ['FOO_PATH'] = "old"
old, sys.stdout = sys.stdout, StringIO()
try:
download_and_execute(driver, ['Hello'])
finally:
sys.stdout = old
self.assertEqual(cached_impl + '/.:old',
os.environ['FOO_PATH'])
self.assertEqual(cached_impl + '/.:/a:/b',
os.environ['BAR_PATH'])
self.assertEqual('val', os.environ['NO_PATH'])
self.assertEqual(os.path.join(local_impl, 'group'), os.environ['SELF_GROUP'])
self.assertEqual(os.path.join(local_impl, 'impl'), os.environ['SELF_IMPL'])
del os.environ['FOO_PATH']
if 'XDG_DATA_DIRS' in os.environ:
del os.environ['XDG_DATA_DIRS']
os.environ['BAR_PATH'] = '/old'
old, sys.stdout = sys.stdout, StringIO()
try:
download_and_execute(driver, ['Hello'])
finally:
sys.stdout = old
self.assertEqual(cached_impl + '/.',
os.environ['FOO_PATH'])
self.assertEqual(cached_impl + '/.:/old',
os.environ['BAR_PATH'])
self.assertEqual(cached_impl + '/.:/usr/local/share:/usr/share',
os.environ['XDG_DATA_DIRS'])
def testFeeds(self):
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="0"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<feed src='http://bar'/>
</interface>""" % foo_iface_uri)
self.cache_iface('http://bar',
"""<?xml version="1.0" ?>
<interface last-modified="0"
uri="http://bar"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<feed-for interface='%s'/>
<name>Bar</name>
<summary>Bar</summary>
<description>Bar</description>
<implementation version='1.0' id='sha1=123' main='dummy'>
<archive href='foo' size='10'/>
</implementation>
</interface>""" % foo_iface_uri)
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
self.config.network_use = model.network_full
recalculate(driver)
assert driver.solver.ready
foo_iface = self.config.iface_cache.get_interface(foo_iface_uri)
self.assertEqual('sha1=123', driver.solver.selections.selections[foo_iface.uri].id)
def testBadConfig(self):
path = basedir.save_config_path(namespaces.config_site,
namespaces.config_prog)
glob = os.path.join(path, 'global')
assert not os.path.exists(glob)
stream = open(glob, 'w')
stream.write('hello!')
stream.close()
logger.setLevel(logging.ERROR)
Driver(requirements = Requirements(foo_iface_uri), config = self.config)
logger.setLevel(logging.WARN)
def testNoLocal(self):
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="1110752708"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<feed src='/etc/passwd'/>
</interface>""" % foo_iface_uri)
self.config.network_use = model.network_offline
try:
self.config.iface_cache.get_interface(foo_iface_uri)
assert False
except reader.InvalidInterface as ex:
assert 'Invalid feed URL' in str(ex)
def testDLfeed(self):
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="1110752708"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<feed src='http://example.com'/>
</interface>""" % foo_iface_uri)
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
self.config.network_use = model.network_full
assert driver.need_download()
feed = self.config.iface_cache.get_feed(foo_iface_uri)
feed.feeds = [model.Feed('/BadFeed', None, False)]
logger.setLevel(logging.ERROR)
assert driver.need_download() # Triggers warning
logger.setLevel(logging.WARN)
def testBestUnusable(self):
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="1110752708"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<implementation id='sha1=123' version='1.0' arch='odd-weird' main='dummy'/>
</interface>""" % foo_iface_uri)
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
self.config.network_use = model.network_offline
recalculate(driver)
assert not driver.solver.ready, driver.implementation
try:
download_and_execute(driver, [])
assert False
except model.SafeException as ex:
assert "No usable implementations" in str(ex), ex
def testNoArchives(self):
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="1110752708"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<implementation id='sha1=123' version='1.0' main='dummy'/>
</interface>""" % foo_iface_uri)
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
recalculate(driver)
assert not driver.solver.ready
def testCycle(self):
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="1110752708"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<group>
<requires interface='%s'/>
<implementation id='sha1=123' version='1.0'>
<archive href='foo' size='10'/>
</implementation>
</group>
</interface>""" % (foo_iface_uri, foo_iface_uri))
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
recalculate(driver)
def testConstraints(self):
self.cache_iface('http://bar',
"""<?xml version="1.0" ?>
<interface last-modified="1110752708"
uri="http://bar"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Bar</name>
<summary>Bar</summary>
<description>Bar</description>
<implementation id='sha1=100' version='1.0'>
<archive href='foo' size='10'/>
</implementation>
<implementation id='sha1=150' stability='developer' version='1.5'>
<archive href='foo' size='10'/>
</implementation>
<implementation id='sha1=200' version='2.0'>
<archive href='foo' size='10'/>
</implementation>
</interface>""")
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="1110752708"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<group main='dummy'>
<requires interface='http://bar'>
<version/>
</requires>
<implementation id='sha1=123' version='1.0'>
<archive href='foo' size='10'/>
</implementation>
</group>
</interface>""" % foo_iface_uri)
driver = Driver(requirements = Requirements(foo_iface_uri), config = self.config)
self.config.network_use = model.network_full
#logger.setLevel(logging.DEBUG)
recalculate(driver)
#logger.setLevel(logging.WARN)
foo_iface = self.config.iface_cache.get_interface(foo_iface_uri)
bar_iface = self.config.iface_cache.get_interface('http://bar')
assert driver.solver.selections.selections[bar_iface.uri].id == 'sha1=200'
dep, = driver.solver.selections.selections[foo_iface.uri].dependencies
assert dep.interface == 'http://bar'
assert len(dep.restrictions) == 1
restriction = dep.restrictions[0]
restriction.before = model.parse_version('2.0')
recalculate(driver)
assert driver.solver.selections.selections[bar_iface.uri].id == 'sha1=100'
restriction.not_before = model.parse_version('1.5')
recalculate(driver)
assert driver.solver.selections.selections[bar_iface.uri].id == 'sha1=150'
def testSource(self):
iface_cache = self.config.iface_cache
foo = iface_cache.get_interface('http://foo/Binary.xml')
self.import_feed(foo.uri, 'Binary.xml')
foo_src = iface_cache.get_interface('http://foo/Source.xml')
self.import_feed(foo_src.uri, 'Source.xml')
compiler = iface_cache.get_interface('http://foo/Compiler.xml')
self.import_feed(compiler.uri, 'Compiler.xml')
self.config.freshness = 0
self.config.network_use = model.network_full
driver = Driver(requirements = Requirements('http://foo/Binary.xml'), config = self.config)
tasks.wait_for_blocker(driver.solve_with_downloads())
assert driver.solver.selections.selections[foo.uri].id == 'sha1=123'
# Now ask for source instead
driver.requirements.source = True
driver.requirements.command = 'compile'
tasks.wait_for_blocker(driver.solve_with_downloads())
assert driver.solver.ready, driver.solver.get_failure_reason()
assert driver.solver.selections.selections[foo.uri].id == 'sha1=234' # The source
assert driver.solver.selections.selections[compiler.uri].id == 'sha1=345' # A binary needed to compile it
if __name__ == '__main__':
unittest.main()
| lgpl-2.1 |
mrijk/gimp-sharp | plug-ins/SliceTool/Dialog.cs | 5513 | // The Slice Tool plug-in
// Copyright (C) 2004-2016 Maurits Rijk
//
// Dialog.cs
//
// 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.
//
using System;
using System.IO;
using System.Reflection;
using Gtk;
namespace Gimp.SliceTool
{
public class Dialog : GimpDialog
{
public Preview Preview {private set; get;}
Format _format;
readonly SliceData _sliceData;
readonly Image _image;
readonly Drawable _drawable;
string _filename = null;
public Dialog(Image image, Drawable drawable, SliceData sliceData) :
base(_("Slice Tool"), _("SliceTool"),
IntPtr.Zero, 0, null, _("SliceTool"),
Stock.SaveAs, (Gtk.ResponseType) 2,
Stock.Save, (Gtk.ResponseType) 3,
Stock.Close, ResponseType.Close)
{
_image = image;
_drawable = drawable;
_sliceData = sliceData;
SetTitle(null);
var vbox = new VBox(false, 12) {BorderWidth = 12};
VBox.PackStart(vbox, true, true, 0);
var hbox = new HBox();
vbox.PackStart(hbox, true, true, 0);
var preview = CreatePreview(drawable, sliceData);
var toolbox = Preview.CreateToolbox(sliceData);
hbox.PackStart(toolbox, false, true, 0);
hbox.PackStart(preview, true, true, 0);
hbox = new HBox();
vbox.PackStart(hbox, true, true, 0);
hbox.PackStart(new CoordinatesDisplay(Preview), false, false, 0);
hbox = new HBox(false, 24);
vbox.PackStart(hbox, true, true, 0);
var properties = new CellPropertiesFrame(sliceData.Rectangles);
hbox.PackStart(properties, false, true, 0);
vbox = new VBox(false, 12);
hbox.PackStart(vbox, false, true, 0);
var rollover = new RolloversFrame(sliceData);
vbox.PackStart(rollover, false, true, 0);
_format = new Format(sliceData.Rectangles);
_format.Extension = System.IO.Path.GetExtension(image.Name).ToLower();
vbox.PackStart(_format, false, true, 0);
vbox = new VBox(false, 12);
hbox.PackStart(vbox, false, true, 0);
var save = new SaveSettingsButton(this, sliceData);
vbox.PackStart(save, false, true, 0);
var load = new LoadSettingsButton(this, sliceData);
vbox.PackStart(load, false, true, 0);
var preferences = new PreferencesButton(_("Preferences"), Preview);
vbox.PackStart(preferences, false, true, 0);
sliceData.Rectangles.SelectedRectangleChanged += delegate {Redraw();};
sliceData.Init(drawable);
}
void SetTitle(string filename)
{
_filename = filename; // Fix me!
string p = (filename == null)
? _("<Untitled>") : System.IO.Path.GetFileName(filename);
Title = string.Format(_("Slice Tool 0.7 - {0}"), p);
}
Widget CreatePreview(Drawable drawable, SliceData sliceData)
{
var window = new ScrolledWindow();
window.SetSizeRequest(600, 400);
var alignment = new Alignment(0.5f, 0.5f, 0, 0);
Preview = new Preview(drawable, sliceData)
{WidthRequest = drawable.Width, HeightRequest = drawable.Height};
alignment.Add(Preview);
window.AddWithViewport(alignment);
return window;
}
public void Redraw()
{
Preview.QueueDraw();
}
public void DialogRun(ResponseType type)
{
if ((int) type == 2 || ((int) type == 3 && _filename == null))
{
var fc = new FileChooserDialog(_("HTML Save As"), this,
FileChooserAction.Save,
"Cancel", ResponseType.Cancel,
"Save", ResponseType.Accept);
if (fc.Run() == (int) ResponseType.Accept)
{
string filename = fc.Filename;
if (System.IO.File.Exists(filename))
{
var message = new FileExistsDialog(filename);
if (!message.IsYes())
{
return;
}
}
SetTitle(filename);
Save(filename);
}
fc.Destroy();
}
else // type == 3
{
Save(_filename);
}
}
void SaveBlank(string path)
{
var assembly = Assembly.GetExecutingAssembly();
var input = assembly.GetManifestResourceStream("blank.png");
var reader = new BinaryReader(input);
var buffer = reader.ReadBytes((int) input.Length);
string fileName = path + System.IO.Path.DirectorySeparatorChar +
"blank.png";
var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
var writer = new BinaryWriter(fs);
writer.Write(buffer);
writer.Close();
}
void Save(string filename)
{
try
{
_sliceData.Save(filename, _format.Apply, _image, _drawable);
SaveBlank(System.IO.Path.GetDirectoryName(filename));
}
catch (Exception)
{
var message = new MessageDialog(null, DialogFlags.DestroyWithParent,
MessageType.Error, ButtonsType.Close,
_("Can't save to ") + filename);
message.Run();
message.Destroy();
}
}
}
}
| lgpl-2.1 |
martijnvermaat/rpclib | src/rpclib/__init__.py | 1232 |
#
# rpclib - Copyright (C) Rpclib contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
#
__version__ = '2.8.0-beta'
from rpclib._base import AuxMethodContext
from rpclib._base import TransportContext
from rpclib._base import EventContext
from rpclib._base import MethodContext
from rpclib._base import MethodDescriptor
from rpclib._base import EventManager
import sys
if sys.version > '3':
def _bytes_join(val, joiner=''):
return bytes(joiner).join(val)
else:
def _bytes_join(val, joiner=''):
return joiner.join(val)
| lgpl-2.1 |
Thomas-Mielke-Software/ECTImport | buchungctrl.cpp | 626 | // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
#include "stdafx.h"
#include "buchungctrl.h"
/////////////////////////////////////////////////////////////////////////////
// CBuchungctrl
IMPLEMENT_DYNCREATE(CBuchungctrl, CWnd)
/////////////////////////////////////////////////////////////////////////////
// CBuchungctrl properties
/////////////////////////////////////////////////////////////////////////////
// CBuchungctrl operations
| lgpl-2.1 |
pombredanne/libming | java_ext/SWFText.java | 2392 | //
// Description:
// SWFText Class
//
// Authors:
// Jonathan Shore <[email protected]>
// Based on php wrapper developed by <[email protected]>
//
// Copyright:
// Copyright 2001 E-Publishing Group Inc. Permission is granted to use or
// modify this code provided that the original copyright notice is included.
//
// This software is distributed with no warranty of liability, merchantability,
// or fitness for a specific purpose.
//
//
// SWFText Class
// text region
//
// Notes
// -
//
public class SWFText extends SWFObject implements SWFTextI {
public SWFText ()
throws SWFException
{
setHandle (nNew());
}
protected void finalize()
throws Throwable
{
nDestroy (handle);
super.finalize();
}
public void setFont (SWFFontI font)
throws SWFException
{
font.eval();
nSetFont (handle, font.getHandle());
preserve (font);
}
public void setColor (int r, int g, int b, int alpha)
{ nSetColor (handle, r,g,b, alpha); }
public void setColor (SWFColor color)
{ nSetColor (handle, color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); }
public void addString (String text)
{ nAddString (handle, text); }
public void setHeight (float height)
{ nSetHeight (handle, height); }
public void setSpacing (float spacing)
{ nSetSpacing (handle, spacing); }
public float getAscent()
{ return nGetAscent (handle); }
public float getDescent()
{ return nGetDescent (handle); }
public float getLeading()
{ return nGetLeading (handle); }
public void moveTo (float x, float y)
{ nMoveTo (handle, x,y); }
// native methods
protected native int nNew ();
protected native void nDestroy (int handle);
protected native void nSetFont (int handle, int Hfont);
protected native void nSetColor (int handle, int r, int g, int b, int alpha);
protected native void nAddString (int handle, String text);
protected native void nSetHeight (int handle, float height);
protected native void nSetSpacing (int handle, float spacing);
protected native float nGetAscent(int handle);
protected native float nGetDescent(int handle);
protected native float nGetLeading(int handle);
protected native void nMoveTo (int handle, float x, float y);
};
| lgpl-2.1 |
karamanolev/Libble.Logchecker | Libble.Logchecker.Core/Properties/AssemblyInfo.cs | 1385 | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Logchecker.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Logchecker.Core")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b0d7a6ad-e2a1-4ecc-9475-589ccfb22646")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| lgpl-2.1 |
lxde/lxqt-notificationd | config/translations/lxqt-config-notificationd_bg.ts | 8678 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="bg">
<context>
<name>AdvancedSettings</name>
<message>
<location filename="../advancedsettings.ui" line="67"/>
<source>Sizes</source>
<translation>Размер</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="75"/>
<source>Width:</source>
<translation>Ширина:</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="82"/>
<location filename="../advancedsettings.ui" line="106"/>
<source> px</source>
<translation> px</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="99"/>
<source>Spacing:</source>
<translation>Отстояние:</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="118"/>
<source>Duration</source>
<translation>Продължителност</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="130"/>
<source>Some notifications set their own on-screen duration.</source>
<translation>Някои известия задават собствена продължителност на показване.</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="142"/>
<source>Default duration:</source>
<translation>Продължителност по подразбиране:</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="149"/>
<source> sec</source>
<translation> s</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="177"/>
<source>Screen</source>
<translation>Екран</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="183"/>
<source>When unchecked the notification will always show on primary screen</source>
<translation>Ако опцията не е избрана известията ще се показват на главния екран</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="186"/>
<source>Show notifications on screen with the mouse</source>
<translation>Показване на известията на екрана с мишката</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="196"/>
<source>Do Not Disturb</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="202"/>
<source>Only save notifications</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="17"/>
<source>Unattended Notifications</source>
<translation>Непрочетени съобщения</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="25"/>
<source>How many to save:</source>
<translation>Брой на запазени съобщения:</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="39"/>
<location filename="../advancedsettings.ui" line="49"/>
<source>Application name is on the top of notification.</source>
<translation>Разположение на името на приложението отгоре на известието.</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="42"/>
<source>Ignore these applications:</source>
<translation>Игнориране на тези приложения:</translation>
</message>
<message>
<location filename="../advancedsettings.ui" line="52"/>
<source>app1,app2,app3</source>
<translation>app1,app2,app3</translation>
</message>
</context>
<context>
<name>BasicSettings</name>
<message>
<location filename="../basicsettings.ui" line="17"/>
<source>Position on screen</source>
<translation>Позиция на екрана</translation>
</message>
<message>
<location filename="../basicsettings.ui" line="176"/>
<source>Preview</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="63"/>
<source><b>Warning:</b> notifications daemon is slow to respond.
Keep trying to connect…</source>
<translation><b>Предупреждение:</b> Демонът на известията отговаря забавено.
Продължаване с опитите за свързване…</translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="72"/>
<source><b>Warning:</b> No notifications daemon is running.
A fallback will be used.</source>
<translation><b>Предупреждение:</b> Не се изпълнява демон за известия.
Ще бъде използван резервен процес.</translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="75"/>
<source><b>Warning:</b> A third-party notifications daemon (%1) is running.
These settings won't have any effect on it!</source>
<translation><b>Предупреждение:</b> Изпълнява се демон за известия на трета страна (%1).
Ще бъде използван резервен процес!</translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="137"/>
<source>at top left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="139"/>
<source>at top center</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="141"/>
<source>at top right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="143"/>
<source>at center left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="145"/>
<source>at center right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="147"/>
<source>at bottom left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="149"/>
<source>at bottom center</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="151"/>
<source>at bottom right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="153"/>
<source>Notification demo </source>
<translation>Демо известие </translation>
</message>
<message>
<location filename="../basicsettings.cpp" line="154"/>
<source>This is a test notification.
All notifications will now appear here on LXQt.</source>
<translation>Това е тестово известие.
Всички известия вече ще се показват тук в LXQt.</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../mainwindow.cpp" line="41"/>
<source>Desktop Notifications</source>
<translation>Известия на работния плот</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="44"/>
<source>General Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="48"/>
<source>Position</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| lgpl-2.1 |
EqAfrica/machinekit | src/emc/rs274ngc/previewmodule.cc | 45698 | // This is a component of AXIS, a front-end for emc
// Copyright 2004, 2005, 2006 Jeff Epler <[email protected]> and
// Chris Radek <[email protected]>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <Python.h>
#include <structmember.h>
#include <google/protobuf/message_lite.h>
#include <machinetalk/generated/types.pb.h>
#include <machinetalk/generated/message.pb.h>
using namespace google::protobuf;
#include "rs274ngc.hh"
#include "rs274ngc_interp.hh"
#include "interp_return.hh"
#include "canon.hh"
#include "config.h" // LINELEN
#include "czmq.h"
#include "pbutil.hh" // hal/haltalk
static zctx_t *z_context;
static void *z_preview, *z_status; // sockets
static const char *istat_topic = "status";
static int batch_limit = 100;
static const char *p_client = "preview"; //NULL; // single client for now
static pb::Container istat, output;
static size_t n_containers, n_messages, n_bytes;
// #define REPLY_TIMEOUT 3000 //ms
// #define UPDATE_TIMEOUT 3000 //ms
int _task = 0; // control preview behaviour when remapping
// publish an interpreter status change.
static void publish_istat(pb::InterpreterStateType state)
{
static pb::InterpreterStateType last_state = pb::INTERP_STATE_UNSET;
int retval;
if (state ^ last_state) {
istat.set_type(pb::MT_INTERP_STAT);
istat.set_interp_state(state);
istat.set_interp_name("preview");
// NB: this will also istat.Clear()
retval = send_pbcontainer(istat_topic, istat, z_status);
assert(retval == 0);
last_state = state; // change tracking
}
}
// send off a preview frame if sufficent preview frames accumulated, or flushing
// is is assumed a repeated submessage preview was just added
static void send_preview(const char *client, bool flush = false)
{
int retval;
n_messages++;
if ((output.preview_size() > batch_limit) || flush) {
n_containers++;
n_bytes += output.ByteSize();
output.set_type(pb::MT_PREVIEW);
retval = send_pbcontainer(client, output, z_preview);
assert(retval == 0);
}
}
static int z_init(void)
{
if (!z_context)
z_context = zctx_new ();
// const char *uri = getenv("PREVIEW_URI");
// if (uri) z_preview_uri = uri;
// uri = getenv("STATUS_URI");
// if (uri) z_status_uri = uri;
if (getenv("BATCH"))
batch_limit = atoi(getenv("BATCH"));
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
z_preview = zsocket_new (z_context, ZMQ_XPUB);
#if 0
rc = zsocket_bind(z_preview, z_preview_uri);
assert (rc != 0);
#endif
z_status = zsocket_new (z_context, ZMQ_XPUB);
assert(z_status);
#if 0
rc = zsocket_bind(z_status, z_status_uri);
assert (rc != 0);
#endif
note_printf(istat, "interpreter startup pid=%d", getpid());
publish_istat(pb::INTERP_IDLE);
return 0;
}
// called on module unload
static void z_shutdown(void)
{
fprintf(stderr, "preview: socket shutdown\n");
if (n_containers > 0)
{
fprintf(stderr, "preview: %zu containers %zu preview msgs %zu bytes avg=%zu bytes/container\n",
n_containers, n_messages, n_bytes, n_bytes/n_containers);
}
zctx_destroy(&z_context);
}
char _parameter_file_name[LINELEN];
extern "C" void initinterpreter();
extern "C" void initemccanon();
extern "C" struct _inittab builtin_modules[];
struct _inittab builtin_modules[] = {
{ (char *) "interpreter", initinterpreter },
{ (char *) "emccanon", initemccanon },
// any others...
{ NULL, NULL }
};
static PyObject *int_array(int *arr, int sz) {
PyObject *res = PyTuple_New(sz);
for(int i = 0; i < sz; i++) {
PyTuple_SET_ITEM(res, i, PyInt_FromLong(arr[i]));
}
return res;
}
typedef struct {
PyObject_HEAD
double settings[ACTIVE_SETTINGS];
int gcodes[ACTIVE_G_CODES];
int mcodes[ACTIVE_M_CODES];
} LineCode;
static PyObject *LineCode_gcodes(LineCode *l) {
return int_array(l->gcodes, ACTIVE_G_CODES);
}
static PyObject *LineCode_mcodes(LineCode *l) {
return int_array(l->mcodes, ACTIVE_M_CODES);
}
static PyGetSetDef LineCodeGetSet[] = {
{(char*)"gcodes", (getter)LineCode_gcodes},
{(char*)"mcodes", (getter)LineCode_mcodes},
{NULL, NULL},
};
static PyMemberDef LineCodeMembers[] = {
{(char*)"sequence_number", T_INT, offsetof(LineCode, gcodes[0]), READONLY},
{(char*)"feed_rate", T_DOUBLE, offsetof(LineCode, settings[1]), READONLY},
{(char*)"speed", T_DOUBLE, offsetof(LineCode, settings[2]), READONLY},
{(char*)"motion_mode", T_INT, offsetof(LineCode, gcodes[1]), READONLY},
{(char*)"block", T_INT, offsetof(LineCode, gcodes[2]), READONLY},
{(char*)"plane", T_INT, offsetof(LineCode, gcodes[3]), READONLY},
{(char*)"cutter_side", T_INT, offsetof(LineCode, gcodes[4]), READONLY},
{(char*)"units", T_INT, offsetof(LineCode, gcodes[5]), READONLY},
{(char*)"distance_mode", T_INT, offsetof(LineCode, gcodes[6]), READONLY},
{(char*)"feed_mode", T_INT, offsetof(LineCode, gcodes[7]), READONLY},
{(char*)"origin", T_INT, offsetof(LineCode, gcodes[8]), READONLY},
{(char*)"tool_length_offset", T_INT, offsetof(LineCode, gcodes[9]), READONLY},
{(char*)"retract_mode", T_INT, offsetof(LineCode, gcodes[10]), READONLY},
{(char*)"path_mode", T_INT, offsetof(LineCode, gcodes[11]), READONLY},
{(char*)"stopping", T_INT, offsetof(LineCode, mcodes[1]), READONLY},
{(char*)"spindle", T_INT, offsetof(LineCode, mcodes[2]), READONLY},
{(char*)"toolchange", T_INT, offsetof(LineCode, mcodes[3]), READONLY},
{(char*)"mist", T_INT, offsetof(LineCode, mcodes[4]), READONLY},
{(char*)"flood", T_INT, offsetof(LineCode, mcodes[5]), READONLY},
{(char*)"overrides", T_INT, offsetof(LineCode, mcodes[6]), READONLY},
{NULL}
};
static PyTypeObject LineCodeType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"gcode.linecode", /*tp_name*/
sizeof(LineCode), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
0, /*tp_methods*/
LineCodeMembers, /*tp_members*/
LineCodeGetSet, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
PyType_GenericNew, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
static PyObject *callback;
static int interp_error;
static int last_sequence_number;
static bool metric;
static double _pos_x, _pos_y, _pos_z, _pos_a, _pos_b, _pos_c, _pos_u, _pos_v, _pos_w;
EmcPose tool_offset;
static InterpBase *pinterp;
#define interp_new (*pinterp)
#define callmethod(o, m, f, ...) PyObject_CallMethod((o), (char*)(m), (char*)(f), ## __VA_ARGS__)
static void maybe_new_line(int sequence_number=interp_new.sequence_number());
static void maybe_new_line(int sequence_number) {
if(!pinterp) return;
if(interp_error) return;
if(sequence_number == last_sequence_number)
return;
return ;; // not used - leaks memory
LineCode *new_line_code =
(LineCode*)(PyObject_New(LineCode, &LineCodeType));
interp_new.active_settings(new_line_code->settings);
interp_new.active_g_codes(new_line_code->gcodes);
interp_new.active_m_codes(new_line_code->mcodes);
new_line_code->gcodes[0] = sequence_number;
last_sequence_number = sequence_number;
// PyObject *result =
// callmethod(callback, "next_line", "O", new_line_code);
// Py_DECREF(new_line_code);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
}
void NURBS_FEED(int line_number, std::vector<CONTROL_POINT> nurbs_control_points, unsigned int k) {
double u = 0.0;
unsigned int n = nurbs_control_points.size() - 1;
double umax = n - k + 2;
unsigned int div = nurbs_control_points.size()*15;
std::vector<unsigned int> knot_vector = knot_vector_creator(n, k);
PLANE_POINT P1;
while (u+umax/div < umax) {
PLANE_POINT P1 = nurbs_point(u+umax/div,k,nurbs_control_points,knot_vector);
STRAIGHT_FEED(line_number, P1.X,P1.Y, _pos_z, _pos_a, _pos_b, _pos_c, _pos_u, _pos_v, _pos_w);
u = u + umax/div;
}
P1.X = nurbs_control_points[n].X;
P1.Y = nurbs_control_points[n].Y;
STRAIGHT_FEED(line_number, P1.X,P1.Y, _pos_z, _pos_a, _pos_b, _pos_c, _pos_u, _pos_v, _pos_w);
knot_vector.clear();
}
void ARC_FEED(int line_number,
double first_end, double second_end, double first_axis,
double second_axis, int rotation, double axis_end_point,
double a_position, double b_position, double c_position,
double u_position, double v_position, double w_position) {
// XXX: set _pos_*
if(metric) {
first_end /= 25.4;
second_end /= 25.4;
first_axis /= 25.4;
second_axis /= 25.4;
axis_end_point /= 25.4;
u_position /= 25.4;
v_position /= 25.4;
w_position /= 25.4;
}
maybe_new_line(line_number);
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "arc_feed", "ffffifffffff",
// first_end, second_end, first_axis, second_axis,
// rotation, axis_end_point,
// a_position, b_position, c_position,
// u_position, v_position, w_position);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_ARC_FEED);
p->set_line_number(line_number);
p->set_first_end(first_end);
p->set_second_end(second_end);
p->set_first_axis(first_axis);
p->set_second_axis(second_axis);
p->set_rotation(rotation);
p->set_axis_end_point(axis_end_point);
pb::Position *pos = p->mutable_pos();
pos->set_a(a_position);
pos->set_b(b_position);
pos->set_c(c_position);
pos->set_u(u_position);
pos->set_v(v_position);
pos->set_w(w_position);
send_preview(p_client);
}
void STRAIGHT_FEED(int line_number,
double x, double y, double z,
double a, double b, double c,
double u, double v, double w) {
_pos_x=x; _pos_y=y; _pos_z=z;
_pos_a=a; _pos_b=b; _pos_c=c;
_pos_u=u; _pos_v=v; _pos_w=w;
if(metric) { x /= 25.4; y /= 25.4; z /= 25.4; u /= 25.4; v /= 25.4; w /= 25.4; }
maybe_new_line(line_number);
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "straight_feed", "fffffffff",
// x, y, z, a, b, c, u, v, w);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_STRAIGHT_FEED);
p->set_line_number(line_number);
pb::Position *pos = p->mutable_pos();
pos->set_x(x);
pos->set_y(y);
pos->set_z(z);
pos->set_a(a);
pos->set_b(b);
pos->set_c(c);
pos->set_u(u);
pos->set_v(v);
pos->set_w(w);
send_preview(p_client);
}
void STRAIGHT_TRAVERSE(int line_number,
double x, double y, double z,
double a, double b, double c,
double u, double v, double w) {
_pos_x=x; _pos_y=y; _pos_z=z;
_pos_a=a; _pos_b=b; _pos_c=c;
_pos_u=u; _pos_v=v; _pos_w=w;
if(metric) { x /= 25.4; y /= 25.4; z /= 25.4; u /= 25.4; v /= 25.4; w /= 25.4; }
maybe_new_line(line_number);
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "straight_traverse", "fffffffff",
// x, y, z, a, b, c, u, v, w);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_STRAIGHT_TRAVERSE);
p->set_line_number(line_number);
pb::Position *pos = p->mutable_pos();
pos->set_x(x);
pos->set_y(y);
pos->set_z(z);
pos->set_a(a);
pos->set_b(b);
pos->set_c(c);
pos->set_u(u);
pos->set_v(v);
pos->set_w(w);
send_preview(p_client);
}
void SET_G5X_OFFSET(int g5x_index,
double x, double y, double z,
double a, double b, double c,
double u, double v, double w) {
if(metric) { x /= 25.4; y /= 25.4; z /= 25.4; u /= 25.4; v /= 25.4; w /= 25.4; }
maybe_new_line();
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "set_g5x_offset", "ifffffffff",
// g5x_index, x, y, z, a, b, c, u, v, w);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_SET_G5X_OFFSET);
// p->set_line_number(line_number);
p->set_g5_index(g5x_index);
pb::Position *pos = p->mutable_pos();
pos->set_x(x);
pos->set_y(y);
pos->set_z(z);
pos->set_a(a);
pos->set_b(b);
pos->set_c(c);
pos->set_u(u);
pos->set_v(v);
pos->set_w(w);
send_preview(p_client);
}
void SET_G92_OFFSET(double x, double y, double z,
double a, double b, double c,
double u, double v, double w) {
if(metric) { x /= 25.4; y /= 25.4; z /= 25.4; u /= 25.4; v /= 25.4; w /= 25.4; }
maybe_new_line();
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "set_g92_offset", "fffffffff",
// x, y, z, a, b, c, u, v, w);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_SET_G92_OFFSET);
// p->set_line_number(line_number);
pb::Position *pos = p->mutable_pos();
pos->set_x(x);
pos->set_y(y);
pos->set_z(z);
pos->set_a(a);
pos->set_b(b);
pos->set_c(c);
pos->set_u(u);
pos->set_v(v);
pos->set_w(w);
send_preview(p_client);
}
void SET_XY_ROTATION(double t) {
maybe_new_line();
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "set_xy_rotation", "f", t);
// if(result == NULL) interp_error ++;
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_SET_G92_OFFSET);
// p->set_line_number(line_number);
p->set_xy_rotation(t);
send_preview(p_client);
};
void USE_LENGTH_UNITS(CANON_UNITS u) { metric = u == CANON_UNITS_MM; }
void SELECT_PLANE(CANON_PLANE pl) {
maybe_new_line();
// if(interp_error) return;
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_SELECT_PLANE);
p->set_plane(pl);
send_preview(p_client);
// PyObject *result =
// callmethod(callback, "set_plane", "i", pl);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
}
void SET_TRAVERSE_RATE(double rate) {
maybe_new_line();
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "set_traverse_rate", "f", rate);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_SET_TRAVERSE_RATE);
// p->set_line_number(line_number);
p->set_rate(rate);
send_preview(p_client);
}
void SET_FEED_MODE(int mode) {
#if 0
maybe_new_line();
if(interp_error) return;
PyObject *result =
callmethod(callback, "set_feed_mode", "i", mode);
if(result == NULL) interp_error ++;
Py_XDECREF(result);
#endif
}
void CHANGE_TOOL(int pocket) {
maybe_new_line();
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "change_tool", "i", pocket);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_CHANGE_TOOL);
// p->set_line_number(line_number);
p->set_pocket(pocket);
send_preview(p_client);
}
void CHANGE_TOOL_NUMBER(int pocket) {
maybe_new_line();
if(interp_error) return;
}
/* XXX: This needs to be re-thought. Sometimes feed rate is not in linear
* units--e.g., it could be inverse time feed mode. in that case, it's wrong
* to convert from mm to inch here. but the gcode time estimate gets inverse
* time feed wrong anyway..
*/
void SET_FEED_RATE(double rate) {
maybe_new_line();
if(interp_error) return;
if(metric) rate /= 25.4;
// PyObject *result =
// callmethod(callback, "set_feed_rate", "f", rate);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_SET_FEED_RATE);
// p->set_line_number(line_number);
p->set_rate(rate);
send_preview(p_client);
}
void DWELL(double time) {
maybe_new_line();
// if(interp_error) return;
// PyObject *result =
// callmethod(callback, "dwell", "f", time);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_DWELL);
// p->set_line_number(line_number);
p->set_time(time);
send_preview(p_client);
}
void MESSAGE(char *comment) {
maybe_new_line();
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "message", "s", comment);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_MESSAGE);
// p->set_line_number(line_number);
p->set_text(comment);
send_preview(p_client);
}
void LOG(char *s) {}
void LOGOPEN(char *f) {}
void LOGAPPEND(char *f) {}
void LOGCLOSE() {}
void COMMENT(const char *comment) {
maybe_new_line();
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "comment", "s", comment);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_COMMENT);
// p->set_line_number(line_number);
p->set_text(comment);
send_preview(p_client);
}
void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, EmcPose offset, double diameter,
double frontangle, double backangle, int orientation) {
}
void USE_TOOL_LENGTH_OFFSET(EmcPose offset) {
tool_offset = offset;
maybe_new_line();
if(interp_error) return;
if(metric) {
offset.tran.x /= 25.4; offset.tran.y /= 25.4; offset.tran.z /= 25.4;
offset.u /= 25.4; offset.v /= 25.4; offset.w /= 25.4; }
// PyObject *result = callmethod(callback, "tool_offset", "ddddddddd", offset.tran.x, offset.tran.y, offset.tran.z,
// offset.a, offset.b, offset.c, offset.u, offset.v, offset.w);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_USE_TOOL_OFFSET);
// p->set_line_number(line_number);
pb::Position *pos = p->mutable_pos();
pos->set_x(offset.tran.x);
pos->set_y(offset.tran.y);
pos->set_z(offset.tran.z);
pos->set_a(offset.a);
pos->set_b(offset.b);
pos->set_c(offset.c);
pos->set_u(offset.u);
pos->set_v(offset.v);
pos->set_w(offset.w);
send_preview(p_client);
}
void SET_FEED_REFERENCE(double reference) { }
void SET_CUTTER_RADIUS_COMPENSATION(double radius) {}
void START_CUTTER_RADIUS_COMPENSATION(int direction) {}
void STOP_CUTTER_RADIUS_COMPENSATION(int direction) {}
void START_SPEED_FEED_SYNCH() {}
void START_SPEED_FEED_SYNCH(double sync, bool vel) {}
void STOP_SPEED_FEED_SYNCH() {}
void START_SPINDLE_COUNTERCLOCKWISE(int line) {}
void START_SPINDLE_CLOCKWISE(int line) {}
void SET_SPINDLE_MODE(double) {}
void STOP_SPINDLE_TURNING(int l) {}
void SET_SPINDLE_SPEED(double rpm) {}
void ORIENT_SPINDLE(double d, int i) {}
void WAIT_SPINDLE_ORIENT_COMPLETE(double timeout) {}
void PROGRAM_STOP() {}
void PROGRAM_END() {}
void FINISH() {}
void PALLET_SHUTTLE() {}
void SELECT_POCKET(int pocket, int tool) {}
void UPDATE_TAG(StateTag tag) {}
void OPTIONAL_PROGRAM_STOP() {}
void START_CHANGE() {}
int GET_EXTERNAL_TC_FAULT() {return 0;}
int GET_EXTERNAL_TC_REASON() {return 0;}
extern bool GET_BLOCK_DELETE(void) {
int bd = 0;
if(interp_error) return 0;
// PyObject *result =
// callmethod(callback, "get_block_delete", "");
// if(result == NULL) {
// interp_error++;
// } else {
// bd = PyObject_IsTrue(result);
// }
// Py_XDECREF(result);
return bd;
}
void CANON_ERROR(const char *fmt, ...) {};
void CLAMP_AXIS(CANON_AXIS axis) {}
bool GET_OPTIONAL_PROGRAM_STOP() { return false;}
void SET_OPTIONAL_PROGRAM_STOP(bool state) {}
void SPINDLE_RETRACT_TRAVERSE() {}
void SPINDLE_RETRACT() {}
void STOP_CUTTER_RADIUS_COMPENSATION() {}
void USE_NO_SPINDLE_FORCE() {}
void SET_BLOCK_DELETE(bool enabled) {}
void DISABLE_FEED_OVERRIDE() {}
void DISABLE_FEED_HOLD() {}
void ENABLE_FEED_HOLD() {}
void DISABLE_SPEED_OVERRIDE() {}
void ENABLE_FEED_OVERRIDE() {}
void ENABLE_SPEED_OVERRIDE() {}
void MIST_OFF() {}
void FLOOD_OFF() {}
void MIST_ON() {}
void FLOOD_ON() {}
void CLEAR_AUX_OUTPUT_BIT(int bit, int line) {}
void SET_AUX_OUTPUT_BIT(int bit, int line) {}
void SET_AUX_OUTPUT_VALUE(int index, double value) {}
void CLEAR_MOTION_OUTPUT_BIT(int bit, int line) {}
void SET_MOTION_OUTPUT_BIT(int bit, int line) {}
void SET_MOTION_OUTPUT_VALUE(int index, double value) {}
void TURN_PROBE_ON() {}
void TURN_PROBE_OFF(unsigned char probe_type) {}
int UNLOCK_ROTARY(int line_no, int axis) {return 0;}
int LOCK_ROTARY(int line_no, int axis) {return 0;}
void INTERP_ABORT(int reason,const char *message) {}
void PLUGIN_CALL(int len, const char *call) {}
void IO_PLUGIN_CALL(int len, const char *call) {}
void STRAIGHT_PROBE(int line_number,
double x, double y, double z,
double a, double b, double c,
double u, double v, double w, unsigned char probe_type) {
_pos_x=x; _pos_y=y; _pos_z=z;
_pos_a=a; _pos_b=b; _pos_c=c;
_pos_u=u; _pos_v=v; _pos_w=w;
if(metric) { x /= 25.4; y /= 25.4; z /= 25.4; u /= 25.4; v /= 25.4; w /= 25.4; }
maybe_new_line(line_number);
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "straight_probe", "fffffffff",
// x, y, z, a, b, c, u, v, w);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_STRAIGHT_PROBE);
p->set_line_number(line_number);
pb::Position *pos = p->mutable_pos();
pos->set_x(x);
pos->set_y(y);
pos->set_z(z);
pos->set_a(a);
pos->set_b(b);
pos->set_c(c);
pos->set_u(u);
pos->set_v(v);
pos->set_w(w);
send_preview(p_client);
}
void RIGID_TAP(int line_number,
double x, double y, double z) {
if(metric) { x /= 25.4; y /= 25.4; z /= 25.4; }
maybe_new_line(line_number);
if(interp_error) return;
// PyObject *result =
// callmethod(callback, "rigid_tap", "fff",
// x, y, z);
// if(result == NULL) interp_error ++;
// Py_XDECREF(result);
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_RIGID_TAP);
p->set_line_number(line_number);
pb::Position *pos = p->mutable_pos();
pos->set_x(x);
pos->set_y(y);
pos->set_z(z);
send_preview(p_client);
}
double GET_EXTERNAL_MOTION_CONTROL_TOLERANCE() { return 0.1; }
double GET_EXTERNAL_PROBE_POSITION_X() { return _pos_x; }
double GET_EXTERNAL_PROBE_POSITION_Y() { return _pos_y; }
double GET_EXTERNAL_PROBE_POSITION_Z() { return _pos_z; }
double GET_EXTERNAL_PROBE_POSITION_A() { return _pos_a; }
double GET_EXTERNAL_PROBE_POSITION_B() { return _pos_b; }
double GET_EXTERNAL_PROBE_POSITION_C() { return _pos_c; }
double GET_EXTERNAL_PROBE_POSITION_U() { return _pos_u; }
double GET_EXTERNAL_PROBE_POSITION_V() { return _pos_v; }
double GET_EXTERNAL_PROBE_POSITION_W() { return _pos_w; }
double GET_EXTERNAL_PROBE_VALUE() { return 0.0; }
int GET_EXTERNAL_PROBE_TRIPPED_VALUE() { return 0; }
double GET_EXTERNAL_POSITION_X() { return _pos_x; }
double GET_EXTERNAL_POSITION_Y() { return _pos_y; }
double GET_EXTERNAL_POSITION_Z() { return _pos_z; }
double GET_EXTERNAL_POSITION_A() { return _pos_a; }
double GET_EXTERNAL_POSITION_B() { return _pos_b; }
double GET_EXTERNAL_POSITION_C() { return _pos_c; }
double GET_EXTERNAL_POSITION_U() { return _pos_u; }
double GET_EXTERNAL_POSITION_V() { return _pos_v; }
double GET_EXTERNAL_POSITION_W() { return _pos_w; }
void INTERP_UPDATE_END_POINT(double x, double y, double z,
double a, double b, double c,
double u, double v, double w)
{
_pos_x = x;
_pos_y = y;
_pos_z = z;
_pos_a = a;
_pos_b = b;
_pos_c = c;
_pos_u = u;
_pos_v = v;
_pos_w = w;
};
void INIT_CANON() {}
void GET_EXTERNAL_PARAMETER_FILE_NAME(char *name, int max_size) {
PyObject *result = PyObject_GetAttrString(callback, "parameter_file");
if(!result) { name[0] = 0; return; }
char *s = PyString_AsString(result);
if(!s) { name[0] = 0; return; }
memset(name, 0, max_size);
strncpy(name, s, max_size - 1);
}
int GET_EXTERNAL_LENGTH_UNIT_TYPE() { return CANON_UNITS_INCHES; }
CANON_TOOL_TABLE GET_EXTERNAL_TOOL_TABLE(int pocket) {
CANON_TOOL_TABLE t = {-1,{{0,0,0},0,0,0,0,0,0},0,0,0,0};
if(interp_error) return t;
// PyObject *result =
// callmethod(callback, "get_tool", "i", pocket);
// if(result == NULL ||
// !PyArg_ParseTuple(result, "iddddddddddddi", &t.toolno, &t.offset.tran.x, &t.offset.tran.y, &t.offset.tran.z,
// &t.offset.a, &t.offset.b, &t.offset.c, &t.offset.u, &t.offset.v, &t.offset.w,
// &t.diameter, &t.frontangle, &t.backangle, &t.orientation))
// interp_error ++;
// Py_XDECREF(result);
return t;
}
int GET_EXTERNAL_DIGITAL_INPUT(int index, int def) { return def; }
double GET_EXTERNAL_ANALOG_INPUT(int index, double def) { return def; }
int WAIT(int index, int input_type, int wait_type, double timeout, int line) { return 0;}
static void user_defined_function(int num, double arg1, double arg2, double arg3,
double arg4, double arg5, double arg6, double arg7) {
if(interp_error) return;
maybe_new_line();
PyObject *result =
callmethod(callback, "user_defined_function",
"idd", num, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
if(result == NULL) interp_error++;
Py_XDECREF(result);
}
void SET_FEED_REFERENCE(int ref) {}
int GET_EXTERNAL_QUEUE_EMPTY() { return true; }
CANON_DIRECTION GET_EXTERNAL_SPINDLE() { return 0; }
int GET_EXTERNAL_TOOL_SLOT() { return 0; }
int GET_EXTERNAL_SELECTED_TOOL_SLOT() { return 0; }
double GET_EXTERNAL_FEED_RATE() { return 1; }
double GET_EXTERNAL_TRAVERSE_RATE() { return 0; }
int GET_EXTERNAL_FLOOD() { return 0; }
int GET_EXTERNAL_MIST() { return 0; }
CANON_PLANE GET_EXTERNAL_PLANE() { return 1; }
double GET_EXTERNAL_SPEED() { return 0; }
int GET_EXTERNAL_POCKETS_MAX() { return CANON_POCKETS_MAX; }
void DISABLE_ADAPTIVE_FEED() {}
void ENABLE_ADAPTIVE_FEED() {}
int GET_EXTERNAL_FEED_OVERRIDE_ENABLE() {return 1;}
int GET_EXTERNAL_SPINDLE_OVERRIDE_ENABLE() {return 1;}
int GET_EXTERNAL_ADAPTIVE_FEED_ENABLE() {return 0;}
int GET_EXTERNAL_FEED_HOLD_ENABLE() {return 1;}
int GET_EXTERNAL_AXIS_MASK() {
if(interp_error) return 7;
// PyObject *result =
// callmethod(callback, "get_axis_mask", "");
// if(!result) { interp_error ++; return 7 /* XYZABC */; }
// if(!PyInt_Check(result)) { interp_error ++; return 7 /* XYZABC */; }
// int mask = PyInt_AsLong(result);
// Py_DECREF(result);
return 0x3f; // XYZABC mask;
}
double GET_EXTERNAL_TOOL_LENGTH_XOFFSET() {
return tool_offset.tran.x;
}
double GET_EXTERNAL_TOOL_LENGTH_YOFFSET() {
return tool_offset.tran.y;
}
double GET_EXTERNAL_TOOL_LENGTH_ZOFFSET() {
return tool_offset.tran.z;
}
double GET_EXTERNAL_TOOL_LENGTH_AOFFSET() {
return tool_offset.a;
}
double GET_EXTERNAL_TOOL_LENGTH_BOFFSET() {
return tool_offset.b;
}
double GET_EXTERNAL_TOOL_LENGTH_COFFSET() {
return tool_offset.c;
}
double GET_EXTERNAL_TOOL_LENGTH_UOFFSET() {
return tool_offset.u;
}
double GET_EXTERNAL_TOOL_LENGTH_VOFFSET() {
return tool_offset.v;
}
double GET_EXTERNAL_TOOL_LENGTH_WOFFSET() {
return tool_offset.w;
}
static bool PyInt_CheckAndError(const char *func, PyObject *p) {
if(PyInt_Check(p)) return true;
PyErr_Format(PyExc_TypeError,
"%s: Expected int, got %s", func, p->ob_type->tp_name);
return false;
}
static bool PyFloat_CheckAndError(const char *func, PyObject *p) {
if(PyFloat_Check(p)) return true;
PyErr_Format(PyExc_TypeError,
"%s: Expected float, got %s", func, p->ob_type->tp_name);
return false;
}
double GET_EXTERNAL_ANGLE_UNITS() {
// PyObject *result =
// callmethod(callback, "get_external_angular_units", "");
// if(result == NULL) interp_error++;
double dresult = 1.0;
// if(!result || !PyFloat_CheckAndError("get_external_angle_units", result)) {
// interp_error++;
// } else {
// dresult = PyFloat_AsDouble(result);
// }
// Py_XDECREF(result);
return dresult;
}
double GET_EXTERNAL_LENGTH_UNITS() {
// PyObject *result =
// callmethod(callback, "get_external_length_units", "");
// if(result == NULL) interp_error++;
double dresult = 0.03937007874016;
// if(!result || !PyFloat_CheckAndError("get_external_length_units", result)) {
// interp_error++;
// } else {
// dresult = PyFloat_AsDouble(result);
// }
// Py_XDECREF(result);
return dresult;
}
static bool check_abort() {
PyObject *result =
callmethod(callback, "check_abort", "");
if(!result) return 1;
if(PyObject_IsTrue(result)) {
Py_DECREF(result);
PyErr_Format(PyExc_KeyboardInterrupt, "Load aborted");
return 1;
}
Py_DECREF(result);
return 0;
}
USER_DEFINED_FUNCTION_TYPE USER_DEFINED_FUNCTION[USER_DEFINED_FUNCTION_NUM];
CANON_MOTION_MODE motion_mode;
void SET_MOTION_CONTROL_MODE(CANON_MOTION_MODE mode, double tolerance) { motion_mode = mode; }
void SET_MOTION_CONTROL_MODE(double tolerance) { }
void SET_MOTION_CONTROL_MODE(CANON_MOTION_MODE mode) { motion_mode = mode; }
CANON_MOTION_MODE GET_EXTERNAL_MOTION_CONTROL_MODE() { return motion_mode; }
void SET_NAIVECAM_TOLERANCE(double tolerance) { }
void SET_INTERP_PARAMS(int call_level, int remap_level) { };
#define RESULT_OK (result == INTERP_OK || result == INTERP_EXECUTE_FINISH)
static PyObject *parse_file(PyObject *self, PyObject *args) {
char *f;
char *unitcode=0, *initcode=0, *interpname=0;
int error_line_offset = 0;
struct timeval t0, t1;
int wait = 1;
if(!PyArg_ParseTuple(args, "sO|sss", &f, &callback, &unitcode, &initcode, &interpname))
return NULL;
if(pinterp) {
delete pinterp;
pinterp = 0;
}
if(interpname && *interpname)
pinterp = interp_from_shlib(interpname);
if(!pinterp)
pinterp = new Interp;
for(int i=0; i<USER_DEFINED_FUNCTION_NUM; i++)
USER_DEFINED_FUNCTION[i] = user_defined_function;
gettimeofday(&t0, NULL);
metric=false;
interp_error = 0;
last_sequence_number = -1;
_pos_x = _pos_y = _pos_z = _pos_a = _pos_b = _pos_c = 0;
_pos_u = _pos_v = _pos_w = 0;
interp_new.init();
interp_new.open(f);
note_printf(istat, "open '%s'", f);
publish_istat(pb::INTERP_RUNNING);
maybe_new_line();
pb::Preview *p = output.add_preview();
p->set_type(pb::PV_SOURCE_CONTEXT);
p->set_stype(pb::ST_NGC_FILE);
p->set_filename(f);
p->set_line_number(interp_new.sequence_number());
int result = INTERP_OK;
if(unitcode) {
result = interp_new.read(unitcode);
if(!RESULT_OK) goto out_error;
result = interp_new.execute();
}
if(initcode && RESULT_OK) {
result = interp_new.read(initcode);
if(!RESULT_OK) goto out_error;
result = interp_new.execute();
}
while(!interp_error && RESULT_OK) {
error_line_offset = 1;
result = interp_new.read();
gettimeofday(&t1, NULL);
if(t1.tv_sec > t0.tv_sec + wait) {
if(check_abort()) return NULL;
t0 = t1;
}
if(!RESULT_OK) break;
error_line_offset = 0;
result = interp_new.execute();
}
publish_istat(pb::INTERP_IDLE);
send_preview(p_client, true);
out_error:
if(pinterp) pinterp->close();
if(interp_error) {
if(!PyErr_Occurred()) {
PyErr_Format(PyExc_RuntimeError,
"interp_error > 0 but no Python exception set");
}
return NULL;
}
PyErr_Clear();
maybe_new_line();
if(PyErr_Occurred()) { interp_error = 1; goto out_error; }
PyObject *retval = PyTuple_New(2);
PyTuple_SetItem(retval, 0, PyInt_FromLong(result));
PyTuple_SetItem(retval, 1, PyInt_FromLong(last_sequence_number + error_line_offset));
return retval;
}
static int maxerror = -1;
static char savedError[LINELEN+1];
static PyObject *rs274_strerror(PyObject *s, PyObject *o) {
int err;
if(!PyArg_ParseTuple(o, "i", &err)) return NULL;
interp_new.error_text(err, savedError, LINELEN);
return PyString_FromString(savedError);
}
static PyObject *rs274_calc_extents(PyObject *self, PyObject *args) {
double min_x = 9e99, min_y = 9e99, min_z = 9e99,
min_xt = 9e99, min_yt = 9e99, min_zt = 9e99,
max_x = -9e99, max_y = -9e99, max_z = -9e99,
max_xt = -9e99, max_yt = -9e99, max_zt = -9e99;
for(int i=0; i<PySequence_Length(args); i++) {
PyObject *si = PyTuple_GetItem(args, i);
if(!si) return NULL;
int j;
double xs, ys, zs, xe, ye, ze, xt, yt, zt;
for(j=0; j<PySequence_Length(si); j++) {
PyObject *sj = PySequence_GetItem(si, j);
PyObject *unused;
int r;
if(PyTuple_Size(sj) == 4)
r = PyArg_ParseTuple(sj,
"O(dddOOOOOO)(dddOOOOOO)(ddd):calc_extents item",
&unused,
&xs, &ys, &zs, &unused, &unused, &unused, &unused, &unused, &unused,
&xe, &ye, &ze, &unused, &unused, &unused, &unused, &unused, &unused,
&xt, &yt, &zt);
else
r = PyArg_ParseTuple(sj,
"O(dddOOOOOO)(dddOOOOOO)O(ddd):calc_extents item",
&unused,
&xs, &ys, &zs, &unused, &unused, &unused, &unused, &unused, &unused,
&xe, &ye, &ze, &unused, &unused, &unused, &unused, &unused, &unused,
&unused, &xt, &yt, &zt);
Py_DECREF(sj);
if(!r) return NULL;
max_x = std::max(max_x, xs);
max_y = std::max(max_y, ys);
max_z = std::max(max_z, zs);
min_x = std::min(min_x, xs);
min_y = std::min(min_y, ys);
min_z = std::min(min_z, zs);
max_xt = std::max(max_xt, xs+xt);
max_yt = std::max(max_yt, ys+yt);
max_zt = std::max(max_zt, zs+zt);
min_xt = std::min(min_xt, xs+xt);
min_yt = std::min(min_yt, ys+yt);
min_zt = std::min(min_zt, zs+zt);
}
if(j > 0) {
max_x = std::max(max_x, xe);
max_y = std::max(max_y, ye);
max_z = std::max(max_z, ze);
min_x = std::min(min_x, xe);
min_y = std::min(min_y, ye);
min_z = std::min(min_z, ze);
max_xt = std::max(max_xt, xe+xt);
max_yt = std::max(max_yt, ye+yt);
max_zt = std::max(max_zt, ze+zt);
min_xt = std::min(min_xt, xe+xt);
min_yt = std::min(min_yt, ye+yt);
min_zt = std::min(min_zt, ze+zt);
}
}
return Py_BuildValue("[ddd][ddd][ddd][ddd]",
min_x, min_y, min_z, max_x, max_y, max_z,
min_xt, min_yt, min_zt, max_xt, max_yt, max_zt);
}
#if PY_VERSION_HEX < 0x02050000
#define PyObject_GetAttrString(o,s) \
PyObject_GetAttrString((o),const_cast<char*>((s)))
#define PyArg_VaParse(o,f,a) \
PyArg_VaParse((o),const_cast<char*>((f)),(a))
#endif
static bool get_attr(PyObject *o, const char *attr_name, int *v) {
PyObject *attr = PyObject_GetAttrString(o, attr_name);
if(attr && PyInt_CheckAndError(attr_name, attr)) {
*v = PyInt_AsLong(attr);
Py_DECREF(attr);
return true;
}
Py_XDECREF(attr);
return false;
}
static bool get_attr(PyObject *o, const char *attr_name, double *v) {
PyObject *attr = PyObject_GetAttrString(o, attr_name);
if(attr && PyFloat_CheckAndError(attr_name, attr)) {
*v = PyFloat_AsDouble(attr);
Py_DECREF(attr);
return true;
}
Py_XDECREF(attr);
return false;
}
static bool get_attr(PyObject *o, const char *attr_name, const char *fmt, ...) {
bool result = false;
va_list ap;
va_start(ap, fmt);
PyObject *attr = PyObject_GetAttrString(o, attr_name);
if(attr) result = PyArg_VaParse(attr, fmt, ap);
va_end(ap);
Py_XDECREF(attr);
return result;
}
static void unrotate(double &x, double &y, double c, double s) {
double tx = x * c + y * s;
y = -x * s + y * c;
x = tx;
}
static void rotate(double &x, double &y, double c, double s) {
double tx = x * c - y * s;
y = x * s + y * c;
x = tx;
}
static PyObject *rs274_arc_to_segments(PyObject *self, PyObject *args) {
PyObject *canon;
double x1, y1, cx, cy, z1, a, b, c, u, v, w;
double o[9], n[9], g5xoffset[9], g92offset[9];
int rot, plane;
int X, Y, Z;
double rotation_cos, rotation_sin;
int max_segments = 128;
if(!PyArg_ParseTuple(args, "Oddddiddddddd|i:arcs_to_segments",
&canon, &x1, &y1, &cx, &cy, &rot, &z1, &a, &b, &c, &u, &v, &w, &max_segments)) return NULL;
if(!get_attr(canon, "lo", "ddddddddd:arcs_to_segments lo", &o[0], &o[1], &o[2],
&o[3], &o[4], &o[5], &o[6], &o[7], &o[8]))
return NULL;
if(!get_attr(canon, "plane", &plane)) return NULL;
if(!get_attr(canon, "rotation_cos", &rotation_cos)) return NULL;
if(!get_attr(canon, "rotation_sin", &rotation_sin)) return NULL;
if(!get_attr(canon, "g5x_offset_x", &g5xoffset[0])) return NULL;
if(!get_attr(canon, "g5x_offset_y", &g5xoffset[1])) return NULL;
if(!get_attr(canon, "g5x_offset_z", &g5xoffset[2])) return NULL;
if(!get_attr(canon, "g5x_offset_a", &g5xoffset[3])) return NULL;
if(!get_attr(canon, "g5x_offset_b", &g5xoffset[4])) return NULL;
if(!get_attr(canon, "g5x_offset_c", &g5xoffset[5])) return NULL;
if(!get_attr(canon, "g5x_offset_u", &g5xoffset[6])) return NULL;
if(!get_attr(canon, "g5x_offset_v", &g5xoffset[7])) return NULL;
if(!get_attr(canon, "g5x_offset_w", &g5xoffset[8])) return NULL;
if(!get_attr(canon, "g92_offset_x", &g92offset[0])) return NULL;
if(!get_attr(canon, "g92_offset_y", &g92offset[1])) return NULL;
if(!get_attr(canon, "g92_offset_z", &g92offset[2])) return NULL;
if(!get_attr(canon, "g92_offset_a", &g92offset[3])) return NULL;
if(!get_attr(canon, "g92_offset_b", &g92offset[4])) return NULL;
if(!get_attr(canon, "g92_offset_c", &g92offset[5])) return NULL;
if(!get_attr(canon, "g92_offset_u", &g92offset[6])) return NULL;
if(!get_attr(canon, "g92_offset_v", &g92offset[7])) return NULL;
if(!get_attr(canon, "g92_offset_w", &g92offset[8])) return NULL;
if(plane == 1) {
X=0; Y=1; Z=2;
} else if(plane == 3) {
X=2; Y=0; Z=1;
} else {
X=1; Y=2; Z=0;
}
n[X] = x1;
n[Y] = y1;
n[Z] = z1;
n[3] = a;
n[4] = b;
n[5] = c;
n[6] = u;
n[7] = v;
n[8] = w;
for(int ax=0; ax<9; ax++) o[ax] -= g5xoffset[ax];
unrotate(o[0], o[1], rotation_cos, rotation_sin);
for(int ax=0; ax<9; ax++) o[ax] -= g92offset[ax];
double theta1 = atan2(o[Y]-cy, o[X]-cx);
double theta2 = atan2(n[Y]-cy, n[X]-cx);
if(rot < 0) {
while(theta2 - theta1 > -CIRCLE_FUZZ) theta2 -= 2*M_PI;
} else {
while(theta2 - theta1 < CIRCLE_FUZZ) theta2 += 2*M_PI;
}
// if multi-turn, add the right number of full circles
if(rot < -1) theta2 += 2*M_PI*(rot+1);
if(rot > 1) theta2 += 2*M_PI*(rot-1);
int steps = std::max(3, int(max_segments * fabs(theta1 - theta2) / M_PI));
double rsteps = 1. / steps;
PyObject *segs = PyList_New(steps);
double dtheta = theta2 - theta1;
double d[9] = {0, 0, 0, n[3]-o[3], n[4]-o[4], n[5]-o[5], n[6]-o[6], n[7]-o[7], n[8]-o[8]};
d[Z] = n[Z] - o[Z];
double tx = o[X] - cx, ty = o[Y] - cy, dc = cos(dtheta*rsteps), ds = sin(dtheta*rsteps);
for(int i=0; i<steps-1; i++) {
double f = (i+1) * rsteps;
double p[9];
rotate(tx, ty, dc, ds);
p[X] = tx + cx;
p[Y] = ty + cy;
p[Z] = o[Z] + d[Z] * f;
p[3] = o[3] + d[3] * f;
p[4] = o[4] + d[4] * f;
p[5] = o[5] + d[5] * f;
p[6] = o[6] + d[6] * f;
p[7] = o[7] + d[7] * f;
p[8] = o[8] + d[8] * f;
for(int ax=0; ax<9; ax++) p[ax] += g92offset[ax];
rotate(p[0], p[1], rotation_cos, rotation_sin);
for(int ax=0; ax<9; ax++) p[ax] += g5xoffset[ax];
PyList_SET_ITEM(segs, i,
Py_BuildValue("ddddddddd", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]));
}
for(int ax=0; ax<9; ax++) n[ax] += g92offset[ax];
rotate(n[0], n[1], rotation_cos, rotation_sin);
for(int ax=0; ax<9; ax++) n[ax] += g5xoffset[ax];
PyList_SET_ITEM(segs, steps-1,
Py_BuildValue("ddddddddd", n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8]));
return segs;
}
static PyObject *bind_sockets(PyObject *self, PyObject *args) {
char *preview_uri, *status_uri;
if(!PyArg_ParseTuple(args, "ss", &preview_uri, &status_uri))
return NULL;
int rc;
rc = zsocket_bind(z_preview, preview_uri);
if(!rc) {
PyErr_Format(PyExc_RuntimeError,
"binding preview socket to '%s' failed", preview_uri);
return NULL;
}
rc = zsocket_bind(z_status, status_uri);
if(!rc) {
PyErr_Format(PyExc_RuntimeError,
"binding status socket to '%s' failed", status_uri);
return NULL;
}
// usleep(300 *1000); // avoid slow joiner syndrome
return Py_BuildValue("(ss)",
zsocket_last_endpoint(z_preview),
zsocket_last_endpoint(z_status));
}
static PyMethodDef gcode_methods[] = {
{"parse", (PyCFunction)parse_file, METH_VARARGS, "Parse a G-Code file"},
{"strerror", (PyCFunction)rs274_strerror, METH_VARARGS,
"Convert a numeric error to a string"},
{"calc_extents", (PyCFunction)rs274_calc_extents, METH_VARARGS,
"Calculate information about extents of gcode"},
{"arc_to_segments", (PyCFunction)rs274_arc_to_segments, METH_VARARGS,
"Convert an arc to straight segments"},
{"bind", (PyCFunction)bind_sockets, METH_VARARGS, "pass an IP address and return a tuple (status uri, preview uri)"},
{NULL}
};
PyMODINIT_FUNC
initpreview(void) {
PyObject *m = Py_InitModule3("preview", gcode_methods,
"Protobuf ppreview interface to EMC rs274ngc interpreter");
PyType_Ready(&LineCodeType);
PyModule_AddObject(m, "linecode", (PyObject*)&LineCodeType);
PyObject_SetAttrString(m, "MAX_ERROR", PyInt_FromLong(maxerror));
PyObject_SetAttrString(m, "MIN_ERROR",
PyInt_FromLong(INTERP_MIN_ERROR));
z_init();
Py_AtExit(z_shutdown);
}
// vim:ts=8:sts=4:sw=4:et:
| lgpl-2.1 |
raedle/univis | lib/springframework-1.2.8/src/org/springframework/web/context/support/ServletContextResourceLoader.java | 2052 | /*
* Copyright 2002-2005 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.web.context.support;
import javax.servlet.ServletContext;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
/**
* ResourceLoader implementation that resolves paths as ServletContext
* resources, for use outside a WebApplicationContext (for example,
* in a HttpServletBean or GenericFilterBean subclass).
*
* <p>Within a WebApplicationContext, resource paths are automatically
* resolved as ServletContext resources by the context implementation.
*
* @author Juergen Hoeller
* @since 1.0.2
* @see #getResourceByPath
* @see ServletContextResource
* @see org.springframework.web.context.WebApplicationContext
* @see org.springframework.web.servlet.HttpServletBean
* @see org.springframework.web.filter.GenericFilterBean
*/
public class ServletContextResourceLoader extends DefaultResourceLoader {
private final ServletContext servletContext;
/**
* Create a new ServletContextResourceLoader.
* @param servletContext the ServletContext to load resources with
*/
public ServletContextResourceLoader(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* This implementation supports file paths beneath the root of the web application.
* @see ServletContextResource
*/
protected Resource getResourceByPath(String path) {
return new ServletContextResource(this.servletContext, path);
}
}
| lgpl-2.1 |
Morik/WCF | wcfsetup/install/files/lib/system/search/acp/ACPSearchHandler.class.php | 4001 | <?php
namespace wcf\system\search\acp;
use wcf\data\acp\search\provider\ACPSearchProvider;
use wcf\system\application\ApplicationHandler;
use wcf\system\cache\builder\ACPSearchProviderCacheBuilder;
use wcf\system\exception\ImplementationException;
use wcf\system\SingletonFactory;
/**
* Handles ACP Search.
*
* @author Alexander Ebert
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Search\Acp
*/
class ACPSearchHandler extends SingletonFactory {
/**
* list of application abbreviations
* @var string[]
*/
public $abbreviations = [];
/**
* list of acp search provider
* @var ACPSearchProvider[]
*/
protected $cache = null;
/**
* @inheritDoc
*/
protected function init() {
$this->cache = ACPSearchProviderCacheBuilder::getInstance()->getData();
}
/**
* Returns a list of search result collections for given query.
*
* @param string $query
* @param integer $limit
* @param string $providerName
* @return ACPSearchResultList[]
* @throws ImplementationException
*/
public function search($query, $limit = 10, $providerName = '') {
$data = [];
if ($providerName) $maxResultsPerProvider = $limit;
else $maxResultsPerProvider = ceil($limit / 2);
$totalResultCount = 0;
foreach ($this->cache as $acpSearchProvider) {
if ($providerName && $acpSearchProvider->providerName != $providerName) continue;
$className = $acpSearchProvider->className;
if (!is_subclass_of($className, IACPSearchResultProvider::class)) {
throw new ImplementationException($className, IACPSearchResultProvider::class);
}
/** @var IACPSearchResultProvider $provider */
$provider = new $className();
$results = $provider->search($query);
if (!empty($results)) {
$resultList = new ACPSearchResultList($acpSearchProvider->providerName);
foreach ($results as $result) {
$resultList->addResult($result);
}
// sort list and reduce results
$resultList->sort();
$resultList->reduceResultsTo($maxResultsPerProvider);
$data[] = $resultList;
$totalResultCount += count($resultList);
}
}
// reduce results per collection until we match the limit
while ($totalResultCount > $limit) {
// calculate highest value
$max = 0;
foreach ($data as $resultList) {
$max = max($max, count($resultList));
}
// remove one result per result list with hits the $max value
foreach ($data as $index => $resultList) {
// break if we hit the $limit during reduction
if ($totalResultCount == $limit) {
break;
}
$count = count($resultList);
if ($count == $max) {
$resultList->reduceResults(1);
$totalResultCount--;
// the last element of this result was removed
if ($count == 1) {
unset($data[$index]);
}
}
}
}
// sort all result lists
foreach ($data as $resultList) {
$resultList->sort();
}
return $data;
}
/**
* Returns a list of application abbreviations.
*
* @param string $suffix
* @return string[]
*/
public function getAbbreviations($suffix = '') {
if (empty($this->abbreviations)) {
// append the 'WCF' pseudo application
$this->abbreviations[] = 'wcf';
// get running application
$this->abbreviations[] = ApplicationHandler::getInstance()->getAbbreviation(ApplicationHandler::getInstance()->getActiveApplication()->packageID);
// get dependent applications
foreach (ApplicationHandler::getInstance()->getDependentApplications() as $application) {
$this->abbreviations[] = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
}
}
if (!empty($suffix)) {
$abbreviations = [];
foreach ($this->abbreviations as $abbreviation) {
$abbreviations[] = $abbreviation . $suffix;
}
return $abbreviations;
}
return $this->abbreviations;
}
}
| lgpl-2.1 |
cyndis/qtgstreamer | elements/gstqtvideosink/qwidgetvideosinkdelegate.cpp | 2434 | /*
Copyright (C) 2010 George Kiagiadakis <[email protected]>
Copyright (C) 2012 Collabora Ltd. <[email protected]>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This 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 Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qwidgetvideosinkdelegate.h"
#include <QtGui/QPainter>
QWidgetVideoSinkDelegate::QWidgetVideoSinkDelegate(GstQtVideoSinkBase* sink, QObject* parent)
: QtVideoSinkDelegate(sink, parent)
{
}
QWidgetVideoSinkDelegate::~QWidgetVideoSinkDelegate()
{
setWidget(NULL);
}
QWidget *QWidgetVideoSinkDelegate::widget() const
{
return m_widget.data();
}
void QWidgetVideoSinkDelegate::setWidget(QWidget *widget)
{
GST_LOG_OBJECT(m_sink, "Setting \"widget\" property to %"GST_PTR_FORMAT, widget);
if (m_widget) {
m_widget.data()->removeEventFilter(this);
m_widget.data()->setAttribute(Qt::WA_OpaquePaintEvent, m_opaquePaintEventAttribute);
m_widget.data()->update();
m_widget = QWeakPointer<QWidget>();
}
if (widget) {
widget->installEventFilter(this);
m_opaquePaintEventAttribute = widget->testAttribute(Qt::WA_OpaquePaintEvent);
widget->setAttribute(Qt::WA_OpaquePaintEvent, true);
widget->update();
m_widget = widget;
}
}
bool QWidgetVideoSinkDelegate::eventFilter(QObject *filteredObject, QEvent *event)
{
if (filteredObject == m_widget.data()) {
switch(event->type()) {
case QEvent::Paint:
{
QPainter painter(m_widget.data());
paint(&painter, m_widget.data()->rect());
return true;
}
default:
return false;
}
} else {
return QtVideoSinkDelegate::eventFilter(filteredObject, event);
}
}
void QWidgetVideoSinkDelegate::update()
{
if (m_widget) {
m_widget.data()->update();
}
}
| lgpl-2.1 |
hdeling/sofa | SofaKernel/framework/framework_test/helper/system/FileMonitor_test.cpp | 7897 | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <gtest/gtest.h>
#include <exception>
#include <algorithm>
#include <vector>
using std::vector ;
#include <fstream>
using std::ofstream ;
#include <string>
using std::string ;
#include <sofa/helper/system/FileMonitor.h>
using sofa::helper::system::FileEventListener ;
using sofa::helper::system::FileMonitor ;
#ifdef WIN32
#include <windows.h>
#endif
static std::string getPath(std::string s) {
return std::string(FRAMEWORK_TEST_RESOURCES_DIR) + std::string("/") + s;
}
void createAFilledFile(const string filename, unsigned int rep){
ofstream file1 ;
file1.open(filename.c_str(), ofstream::out) ;
//throw_when(!file1.is_open()) ;
string sample = "#include<TODOD> int main(int argc...){ ... }\n}" ;
for(unsigned int i=0;i<rep;i++){
file1.write(sample.c_str(), sample.size()) ;
}
file1.close();
}
void waitForFileEvents()
{
// on windows we use file date, which resoution is assumed (by us) to be below this value in ms
#ifdef WIN32
Sleep(100);
#endif
}
class MyFileListener : public FileEventListener
{
public:
vector<string> m_files ;
virtual void fileHasChanged(const std::string& filename){
//std::cout << "FileHasChanged: " << filename << std::endl ;
m_files.push_back(filename) ;
}
};
TEST(FileMonitor, addFileNotExist_test)
{
MyFileListener listener ;
// Should refuse to add a file that does not exists
EXPECT_EQ( FileMonitor::addFile(getPath("nonexisting.txt"), &listener), -1 ) ;
FileMonitor::removeListener(&listener) ;
}
TEST(FileMonitor, addFileNotExist2_test)
{
MyFileListener listener ;
// Should refuse to add a file that does not exists
EXPECT_EQ( FileMonitor::addFile(getPath(""),"nonexisting.txt", &listener), -1 ) ;
FileMonitor::removeListener(&listener) ;
}
TEST(FileMonitor, addFileExist_test)
{
MyFileListener listener ;
// create the file
createAFilledFile(getPath("existing.txt"), 1) ;
// Add an existing file.It should work.
EXPECT_EQ( FileMonitor::addFile(getPath("existing.txt"), &listener), 1 ) ;
FileMonitor::removeListener(&listener) ;
}
TEST(FileMonitor, addFileTwice_test)
{
MyFileListener listener ;
// Add an existing file.It should work.
FileMonitor::addFile(getPath("existing.txt"), &listener);
// Retry to add an existing file. It should fail.
EXPECT_EQ( FileMonitor::addFile(getPath("existing.txt"), &listener), 1 ) ;
// change the file content..
createAFilledFile(getPath("existing.txt"), 10) ;
waitForFileEvents();
FileMonitor::updates(2) ;
// The listener should be notified 1 times with the same event.
EXPECT_EQ( listener.m_files.size(), 1u) ;
FileMonitor::removeListener(&listener) ;
}
TEST(FileMonitor, noUpdate_test)
{
MyFileListener listener ;
// Add an existing file.It should work.
FileMonitor::addFile(getPath("existing.txt"), &listener) ;
EXPECT_EQ( listener.m_files.size(), 0u) ;
FileMonitor::removeListener(&listener) ;
}
TEST(FileMonitor, updateNoChange_test)
{
MyFileListener listener ;
FileMonitor::addFile(getPath("existing.txt"), &listener) ;
waitForFileEvents();
FileMonitor::updates(2) ;
EXPECT_EQ( listener.m_files.size(), 0u) ;
FileMonitor::removeListener(&listener) ;
}
TEST(FileMonitor, fileChange_test)
{
MyFileListener listener ;
FileMonitor::addFile(getPath("existing.txt"), &listener) ;
//waitForFileEvents();
//FileMonitor::updates(2) ;
// change the file content..
createAFilledFile(getPath("existing.txt"), 10) ;
waitForFileEvents();
FileMonitor::updates(2) ;
EXPECT_EQ( listener.m_files.size(), 1u) ;
FileMonitor::removeListener(&listener) ;
}
TEST(FileMonitor, fileChangeTwice_test)
{
MyFileListener listener ;
FileMonitor::addFile(getPath("existing.txt"), &listener) ;
//FileMonitor::updates(2) ;
// change the file content 2x to test if the events are coalesced.
listener.m_files.clear() ;
createAFilledFile(getPath("existing.txt"), 100) ;
createAFilledFile(getPath("existing.txt"), 200) ;
waitForFileEvents();
FileMonitor::updates(2) ;
EXPECT_EQ( listener.m_files.size(), 1u) ;
FileMonitor::removeListener(&listener) ;
}
TEST(FileMonitor, fileListenerRemoved_test)
{
MyFileListener listener1 ;
MyFileListener listener2 ;
FileMonitor::addFile(getPath("existing.txt"), &listener1) ;
FileMonitor::addFile(getPath("existing.txt"), &listener2) ;
//FileMonitor::updates(2) ;
// change the file content 2x to test if the events are coalesced.
listener1.m_files.clear() ;
listener2.m_files.clear() ;
createAFilledFile(getPath("existing.txt"), 200) ;
FileMonitor::removeFileListener(getPath("existing.txt"), &listener1) ;
waitForFileEvents();
FileMonitor::updates(2) ;
EXPECT_EQ( listener1.m_files.size(), 0u) ;
EXPECT_EQ( listener2.m_files.size(), 1u) ;
FileMonitor::removeListener(&listener1) ;
FileMonitor::removeListener(&listener2) ;
}
TEST(FileMonitor, listenerRemoved_test)
{
MyFileListener listener1 ;
MyFileListener listener2 ;
FileMonitor::addFile(getPath("existing.txt"), &listener1) ;
FileMonitor::addFile(getPath("existing.txt"), &listener2) ;
//FileMonitor::updates(2) ;
// change the file content 2x to test if the events are coalesced.
listener1.m_files.clear() ;
listener2.m_files.clear() ;
createAFilledFile(getPath("existing.txt"), 200) ;
FileMonitor::removeListener(&listener1) ;
waitForFileEvents();
FileMonitor::updates(2) ;
EXPECT_EQ( listener1.m_files.size(), 0u) ;
EXPECT_EQ( listener2.m_files.size(), 1u) ;
FileMonitor::removeListener(&listener1) ;
FileMonitor::removeListener(&listener2) ;
}
TEST(FileMonitor, fileChange2_test)
{
MyFileListener listener ;
FileMonitor::addFile(getPath(""),"existing.txt", &listener) ;
//waitForFileEvents();
//FileMonitor::updates(2) ;
// change the file content..
createAFilledFile(getPath("existing.txt"), 10) ;
waitForFileEvents();
FileMonitor::updates(2) ;
EXPECT_EQ( listener.m_files.size(), 1u) ;
FileMonitor::removeListener(&listener) ;
}
| lgpl-2.1 |
mdclyburn/hume | Audio/Audio.cpp | 999 | /*
Hume Library
Copyright (C) 2015 Marshall Clyburn
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include "Audio.h"
namespace hume
{
Audio::Audio()
{
}
Audio::~Audio()
{
}
void set_volume(const uint8_t volume)
{
Mix_VolumeMusic(((float) volume / 100) * 128);
return;
}
}
| lgpl-2.1 |
simplesamlphp/saml2 | src/SAML2/XML/mdrpi/AbstractMdrpiElement.php | 554 | <?php
declare(strict_types=1);
namespace SimpleSAML\SAML2\XML\mdrpi;
use SimpleSAML\XML\AbstractXMLElement;
/**
* Abstract class to be implemented by all the classes in this namespace
*
* @link: http://docs.oasis-open.org/security/saml/Post2.0/saml-metadata-rpi/v1.0/saml-metadata-rpi-v1.0.pdf
*
* @package simplesamlphp/saml2
*/
abstract class AbstractMdrpiElement extends AbstractXMLElement
{
/** @var string */
public const NS = 'urn:oasis:names:tc:SAML:metadata:rpi';
/** @var string */
public const NS_PREFIX = 'mdrpi';
}
| lgpl-2.1 |
CoffeeJack/ElderTracker | app/modules/photos/lib/FlickrAPIRetriever.php | 1927 | <?php
class FlickrAPIRetriever extends URLDataRetriever {
protected $DEFAULT_PARSER_CLASS = 'FlickrDataParser';
protected $extraFields = array(
'description', 'date_upload', 'date_taken', 'owner_name', 'original_format',
'last_update', 'geo', 'tags', 'machine_tags', 'o_dims', 'views', 'media');
// not used
// 'icon_server' , 'license', 'path_alias',
protected function initRequest() {
parent::initRequest();
if ($limit = $this->getOption('limit')) {
$this->addFilter('per_page', $limit);
}
$start = $this->getOption('start');
if (strlen($start)) {
$start = ($start / $limit);
$this->addFilter('page', $start+1);
}
}
protected function init($args) {
parent::init($args);
$this->setContext('retriever','api');
$this->setBaseUrl('http://api.flickr.com/services/rest/');
if (!isset($args['API_KEY'])) {
throw new KurogoConfigurationException("Flickr API_KEY required");
}
$this->addFilter('api_key', $args['API_KEY']);
if (isset($args['USER'])) {
$this->setContext('type', 'photos');
$this->addFilter('method','flickr.photos.search');
$this->addFilter('user_id', $args['USER']);
}
if (isset($args['PHOTOSET'])) {
$this->setContext('type', 'photoset');
$this->addFilter('method','flickr.photosets.getPhotos');
$this->addFilter('photoset_id', $args['PHOTOSET']);
}
if (isset($args['GROUP'])) {
$this->setContext('type', 'photos');
$this->addFilter('method','flickr.photos.search');
$this->addFilter('group_id', $args['GROUP']);
}
$this->addFilter('extras', implode(',', $this->extraFields));
$this->addFilter('format', 'php_serial');
}
}
| lgpl-2.1 |
kazuyaujihara/NCDK | NCDK.LegacyTests/Smiles/SMARTS/Parser/SMARTSSearchTest.cs | 69279 | /* Copyright (C) 2004-2007 Egon Willighagen <[email protected]>
*
* Contact: [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NCDK.Aromaticities;
using NCDK.Common.Base;
using NCDK.Graphs;
using NCDK.IO;
using NCDK.Isomorphisms;
using NCDK.Tools.Manipulator;
using System;
using System.Diagnostics;
using System.Linq;
namespace NCDK.Smiles.SMARTS.Parser
{
/// <summary>
/// Unit test routines for the SMARTS substructure search.
/// </summary>
// @author Dazhi Jiao
// @cdk.module test-smarts
// @cdk.require ant1.6
[TestClass()]
public class SMARTSSearchTest : CDKTestCase
{
private UniversalIsomorphismTester uiTester = new UniversalIsomorphismTester();
internal static IAtomContainer CreateFromSmiles(string smiles)
{
return CreateFromSmiles(smiles, false);
}
internal static IAtomContainer SmilesAtomTyped(string smiles)
{
IAtomContainer molecule = CreateFromSmiles(smiles, false);
AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule);
return molecule;
}
internal static IAtomContainer CreateFromSmiles(string smiles, bool perserveAromaticity)
{
var sp = new SmilesParser(CDK.Builder, !perserveAromaticity);
return sp.ParseSmiles(smiles);
}
internal static SMARTSQueryTool CreateFromSmarts(string smarts)
{
SMARTSQueryTool sqt = new SMARTSQueryTool(smarts);
return sqt;
}
internal static int[] Match(SMARTSQueryTool sqt, IAtomContainer m)
{
bool status = sqt.Matches(m);
if (status)
{
return new int[] { sqt.MatchesCount, sqt.GetUniqueMatchingAtoms().Count() };
}
else
{
return new int[] { 0, 0 };
}
}
internal static int[] Match(string smarts, string smiles)
{
return Match(CreateFromSmarts(smarts), CreateFromSmiles(smiles));
}
[TestMethod()]
public void TestMoleculeFromSDF()
{
var filename = "cnssmarts.sdf";
var ins = ResourceLoader.GetAsStream(GetType(), filename);
DefaultChemObjectReader reader = new MDLV2000Reader(ins);
var content = reader.Read(CDK.Builder.NewChemFile());
var cList = ChemFileManipulator.GetAllAtomContainers(content).ToReadOnlyList();
IAtomContainer atomContainer = cList[0];
SMARTSQueryTool sqt = new SMARTSQueryTool("[NX3;h1,h2,H1,H2;!$(NC=O)]");
bool status = sqt.Matches(atomContainer);
Assert.AreEqual(true, status);
int nmatch = sqt.MatchesCount;
int nqmatch = sqt.GetUniqueMatchingAtoms().Count();
Assert.AreEqual(3, nmatch);
Assert.AreEqual(3, nqmatch);
sqt.Smarts = "[ND3]";
status = sqt.Matches(atomContainer);
Assert.AreEqual(false, status);
}
[TestMethod()]
public void TestRGraphBond()
{
var query = SMARTSParser.Parse("CC=O");
Debug.WriteLine("Query c:c: " + query.ToString());
var sp = CDK.SmilesParser;
var atomContainer = sp.ParseSmiles("CCC=O"); // benzene, aromatic
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestAromaticBond()
{
var query = SMARTSParser.Parse("c:c");
Debug.WriteLine("Query c:c: " + query.ToString());
var sp = new SmilesParser(CDK.Builder, false);
var atomContainer = sp.ParseSmiles("c1ccccc1"); // benzene, aromatic
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C1CCCCC1"); // hexane, not aromatic
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestSingleBond()
{
var query = SMARTSParser.Parse("C-C");
Debug.WriteLine("Query C-C: " + query.ToString());
var sp = CDK.SmilesParser;
var atomContainer = sp.ParseSmiles("CCC");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C=C");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C#C");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestDoubleBond()
{
var query = SMARTSParser.Parse("C=C");
Debug.WriteLine("Query C=C: " + query.ToString());
var sp = CDK.SmilesParser;
var atomContainer = sp.ParseSmiles("CCC");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C=C");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C#C");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestTripleBond()
{
var query = SMARTSParser.Parse("C#C");
Debug.WriteLine("Query C#C: " + query.ToString());
var sp = CDK.SmilesParser;
var atomContainer = sp.ParseSmiles("CCC");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C=C");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C#C");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestAnyOrderBond()
{
var query = SMARTSParser.Parse("C~C");
Debug.WriteLine("Query C~C: " + query.ToString());
var sp = CDK.SmilesParser;
var atomContainer = sp.ParseSmiles("CCC");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C=C");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("C#C");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestAnyAtom()
{
var query = SMARTSParser.Parse("C*C");
Debug.WriteLine("Query C*C: " + query.ToString());
var sp = CDK.SmilesParser;
var atomContainer = sp.ParseSmiles("CCC");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("CNC");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("CCN");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestAliphaticAtom()
{
var query = SMARTSParser.Parse("CAC");
Debug.WriteLine("Query CAC: " + query.ToString());
var sp = CDK.SmilesParser;
var atomContainer = sp.ParseSmiles("CCC");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("CNC");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("c1ccccc1"); // benzene, aromatic
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestAromaticAtom()
{
var query = SMARTSParser.Parse("aaa");
Debug.WriteLine("Query CaC: " + query.ToString());
var sp = new SmilesParser(CDK.Builder, false);
var atomContainer = sp.ParseSmiles("CCC");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("c1ccccc1"); // benzene, aromatic
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
}
[TestMethod()]
public void TestSymbolQueryAtom()
{
var query = SMARTSParser.Parse("CCC");
Debug.WriteLine("Query CAC: " + query.ToString());
var sp = CDK.SmilesParser;
var atomContainer = sp.ParseSmiles("CCC");
Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("CNC");
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
atomContainer = sp.ParseSmiles("c1ccccc1"); // benzene, aromatic
Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));
}
/// <summary>
/// From http://www.daylight.com/dayhtml_tutorials/languages/smarts/index.html
/// </summary>
[TestMethod()]
public void TestPropertyCharge1()
{
int[] results = Match("[+1]", "[OH-].[Mg+2]");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyCharge2()
{
int[] results = Match("[+1]", "COCC(O)Cn1ccnc1[N+](=O)[O-]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyCharge3()
{
int[] results = Match("[+1]", "[NH4+]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyCharge4()
{
int[] results = Match("[+1]", "CN1C(=O)N(C)C(=O)C(N(C)C=N2)=C12");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyCharge5()
{
int[] results = Match("[+1]", "[Cl-].[Cl-].NC(=O)c2cc[n+](COC[n+]1ccccc1C=NO)cc2");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyAromatic1()
{
int[] results = Match("[a]", "c1cc(C)c(N)cc1");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestPropertyAromatic2()
{
int[] results = Match("[a]", "c1c(C)c(N)cnc1");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestPropertyAromatic3()
{
int[] results = Match("[a]", "c1(C)c(N)cco1");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void TestPropertyAromatic4()
{
int[] results = Match("[a]", "c1c(C)c(N)c[nH]1");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void TestPropertyAromatic5()
{
int[] results = Match("[a]", "O=n1ccccc1");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestPropertyAromatic6()
{
int[] results = Match("[a]", "[O-][n+]1ccccc1");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestPropertyAromatic7()
{
int[] results = Match("[a]", "c1ncccc1C1CCCN1C");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestPropertyAromatic8()
{
int[] results = Match("[a]", "c1ccccc1C(=O)OC2CC(N3C)CCC3C2C(=O)OC");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestPropertyAliphatic1()
{
int[] results = Match("[A]", "c1cc(C)c(N)cc1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyAliphatic2()
{
int[] results = Match("[A]", "CCO");
Assert.AreEqual(3, results[0]);
Assert.AreEqual(3, results[1]);
}
[TestMethod()]
public void TestPropertyAliphatic3()
{
int[] results = Match("[A]", "C=CC=CC=C");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestPropertyAliphatic4()
{
int[] results = Match("[A]", "CC(C)(C)C");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void TestPropertyAliphatic5()
{
int[] results = Match("[A]", "CCN(CC)C(=O)C1CN(C)C2CC3=CNc(ccc4)c3c4C2=C1");
Assert.AreEqual(15, results[0]);
Assert.AreEqual(15, results[1]);
}
[TestMethod()]
public void TestPropertyAliphatic6()
{
int[] results = Match("[A]", "N12CCC36C1CC(C(C2)=CCOC4CC5=O)C4C3N5c7ccccc76");
Assert.AreEqual(19, results[0]);
Assert.AreEqual(19, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicNumber1()
{
int[] results = Match("[#6]", "c1cc(C)c(N)cc1");
Assert.AreEqual(7, results[0]);
Assert.AreEqual(7, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicNumber2()
{
int[] results = Match("[#6]", "CCO");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicNumber3()
{
int[] results = Match("[#6]", "C=CC=CC=C-O");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicNumber4()
{
int[] results = Match("[#6]", "CC(C)(C)C");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicNumber5()
{
int[] results = Match("[#6]", "COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34");
Assert.AreEqual(20, results[0]);
Assert.AreEqual(20, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicNumber6()
{
int[] results = Match("[#6]", "C123C5C(O)C=CC2C(N(C)CC1)Cc(ccc4O)c3c4O5");
Assert.AreEqual(17, results[0]);
Assert.AreEqual(17, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicNumber7()
{
int[] results = Match("[#6]", "C123C5C(OC(=O)C)C=CC2C(N(C)CC1)Cc(ccc4OC(=O)C)c3c4O5");
Assert.AreEqual(21, results[0]);
Assert.AreEqual(21, results[1]);
}
// @cdk.bug 2686473
[TestMethod()]
public void TestPropertyAtomicNumber8()
{
int[] results = Match("[#16]", "COC1C(C(C(C(O1)CO)OC2C(C(C(C(O2)CO)S)O)O)O)O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 2686473
[TestMethod()]
public void TestPropertyAtomicNumber9()
{
int[] results = Match("[#6]", "[*]");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyR1()
{
int[] results = Match("[R2]", "N12CCC36C1CC(C(C2)=CCOC4CC5=O)C4C3N5c7ccccc76");
Assert.AreEqual(7, results[0]);
Assert.AreEqual(7, results[1]);
}
[TestMethod()]
public void TestPropertyR2()
{
SMARTSQueryTool sqt = CreateFromSmarts("[R2]");
sqt.UseSmallestSetOfSmallestRings(); // default for daylight
int[] results = Match(sqt, CreateFromSmiles("COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34"));
Assert.AreEqual(6, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod(), Ignore()] // This feature was removed - essential rings aren't useful really
public void TestPropertyR2_essentialRings()
{
SMARTSQueryTool sqt = CreateFromSmarts("[R2]");
sqt.UseEssentialRings();
int[] results = Match(sqt, CreateFromSmiles("COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34"));
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod(), Ignore()] // This feature is pending but will be the combinded in an 'OpenSMARTS'" + " configuration which uses the relevant rings.
public void TestPropertyR2_relevantRings()
{
SMARTSQueryTool sqt = CreateFromSmarts("[R2]");
sqt.UseRelevantRings();
int[] results = Match(sqt, CreateFromSmiles("COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34"));
Assert.AreEqual(8, results[0]);
Assert.AreEqual(8, results[1]);
}
[TestMethod()]
public void TestPropertyR3()
{
int[] results = Match("[R2]", "C123C5C(O)C=CC2C(N(C)CC1)Cc(ccc4O)c3c4O5");
Assert.AreEqual(4, results[0]);
Assert.AreEqual(4, results[1]);
}
[TestMethod()]
public void TestPropertyR4()
{
int[] results = Match("[R2]", "C123C5C(OC(=O)C)C=CC2C(N(C)CC1)Cc(ccc4OC(=O)C)c3c4O5");
Assert.AreEqual(4, results[0]);
Assert.AreEqual(4, results[1]);
}
[TestMethod()]
public void TestPropertyR5()
{
int[] results = Match("[R2]", "C1C(C)=C(C=CC(C)=CC=CC(C)=CCO)C(C)(C)C1");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyr1()
{
int[] results = Match("[r5]", "N12CCC36C1CC(C(C2)=CCOC4CC5=O)C4C3N5c7ccccc76");
Assert.AreEqual(9, results[0]);
Assert.AreEqual(9, results[1]);
}
[TestMethod()]
public void TestPropertyr2()
{
int[] results = Match("[r5]", "COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyr3()
{
int[] results = Match("[r5]", "C123C5C(O)C=CC2C(N(C)CC1)Cc(ccc4O)c3c4O5");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void TestPropertyr4()
{
int[] results = Match("[r5]", "C123C5C(OC(=O)C)C=CC2C(N(C)CC1)Cc(ccc4OC(=O)C)c3c4O5");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void TestPropertyr5()
{
int[] results = Match("[r5]", "C1C(C)=C(C=CC(C)=CC=CC(C)=CCO)C(C)(C)C1");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void QuadBond()
{
int[] results = Match("*$*", "[Re]$[Re]");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyValence1()
{
int[] results = Match("[v4]", "C");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyValence2()
{
int[] results = Match("[v4]", "CCO");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyValence3()
{
int[] results = Match("[v4]", "[NH4+]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyValence4()
{
int[] results = Match("[v4]", "CC1(C)SC2C(NC(=O)Cc3ccccc3)C(=O)N2C1C(=O)O");
Assert.AreEqual(16, results[0]);
Assert.AreEqual(16, results[1]);
}
[TestMethod()]
public void TestPropertyValence5()
{
int[] results = Match("[v4]", "[Cl-].[Cl-].NC(=O)c2cc[n+](COC[n+]1ccccc1C=NO)cc2");
Assert.AreEqual(16, results[0]);
Assert.AreEqual(16, results[1]);
}
[TestMethod()]
public void TestPropertyX1()
{
int[] results = Match("[X2]", "CCO");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyX2()
{
int[] results = Match("[X2]", "O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyX3()
{
int[] results = Match("[X2]", "CCC(=O)CC");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyX4()
{
int[] results = Match("[X2]", "FC(Cl)=C=C(Cl)F");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyX5()
{
int[] results = Match("[X2]", "COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34");
Assert.AreEqual(3, results[0]);
Assert.AreEqual(3, results[1]);
}
[TestMethod()]
public void TestPropertyX6()
{
int[] results = Match("[X2]", "C123C5C(O)C=CC2C(N(C)CC1)Cc(ccc4O)c3c4O5");
Assert.AreEqual(3, results[0]);
Assert.AreEqual(3, results[1]);
}
[TestMethod()]
public void TestPropertyD1()
{
int[] results = Match("[D2]", "CCO");
Assert.AreEqual(1, results[0]);
}
[TestMethod()]
public void TestPropertyD2()
{
int[] results = Match("[D2]", "O");
Assert.AreEqual(0, results[0]);
}
[TestMethod()]
public void TestPropertyD3()
{
int[] results = Match("[D2]", "CCC(=O)CC");
Assert.AreEqual(2, results[0]);
}
[TestMethod()]
public void TestPropertyD4()
{
int[] results = Match("[D2]", "FC(Cl)=C=C(Cl)F");
Assert.AreEqual(1, results[0]);
}
[TestMethod()]
public void TestPropertyD5()
{
int[] results = Match("[D2]", "COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34");
Assert.AreEqual(12, results[0]);
}
[TestMethod()]
public void TestPropertyD6()
{
int[] results = Match("[D2]", "C123C5C(O)C=CC2C(N(C)CC1)Cc(ccc4O)c3c4O5");
Assert.AreEqual(8, results[0]);
}
// @cdk.bug 2489417
[TestMethod()]
public void TestPropertyD7()
{
int[] results = Match("[ND3]", "CCN([H])([H])");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
// @cdk.bug 2489417
[TestMethod()]
public void TestPropertyD8()
{
int[] results = Match("[OD1]", "CO[H]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 2489417
[TestMethod()]
public void TestPropertyD9()
{
int[] results;
results = Match("[OD1H]", "CO");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 2489417
[TestMethod()]
public void TestPropertyD10()
{
int[] results;
results = Match("[OD1H]", "CO[H]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 2489417
[TestMethod()]
public void TestPropertyD11()
{
int[] results;
results = Match("[OD1H]-*", "CCO");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
/// <summary>
/// With '*' matching 'H', this smarts matches twice 'OC' and 'O[H]'.
/// </summary>
// @cdk.bug 2489417
[TestMethod()]
public void TestPropertyD12()
{
int[] results;
results = Match("[OD1H]-*", "CCO[H]");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyHAtom1()
{
int[] results = Match("[H]", "[H+].[Cl-]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyHAtom2()
{
int[] results = Match("[H]", "[2H]");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyHAtom3()
{
int[] results = Match("[H]", "[H][H]");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyHAtom4()
{
int[] results = Match("[H]", "[CH4]");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyHAtom5()
{
int[] results = Match("[H]", "[H]C([H])([H])[H]");
Assert.AreEqual(4, results[0]);
Assert.AreEqual(4, results[1]);
}
[TestMethod()]
public void TestPropertyHTotal1()
{
int[] results = Match("[H1]", "CCO");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyHTotal2()
{
int[] results = Match("[H1]", "[2H]C#C");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyHTotal3()
{
int[] results = Match("[H1]", "[H]C(C)(C)C");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyHTotal4()
{
int[] results = Match("[H1]", "COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34");
Assert.AreEqual(11, results[0]);
Assert.AreEqual(11, results[1]);
}
[TestMethod()]
public void TestPropertyHTotal5()
{
int[] results = Match("[H1]", "C123C5C(O)C=CC2C(N(C)CC1)Cc(ccc4O)c3c4O5");
Assert.AreEqual(10, results[0]);
Assert.AreEqual(10, results[1]);
}
[TestMethod()]
public void TestPropertyHTotal6()
{
int[] results = Match("[H1]", "[H][H]");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyAnyAtom1()
{
int[] results = Match("[*]", "C");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyAnyAtom2()
{
int[] results = Match("[*]", "[2H]C");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyAnyAtom3()
{
int[] results = Match("[*]", "[1H][1H]");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestPropertyAnyAtom4()
{
int[] results = Match("[*]", "[1H]C([1H])([1H])[1H]");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void TestPropertyAnyAtom5()
{
int[] results = Match("[*]", "[H][H]");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
/// <summary>
// @throws Exception
// @cdk.bug 2489533
/// </summary>
[TestMethod()]
public void TestPropertyAnyAtom6()
{
int[] result = Match("*", "CO");
Assert.AreEqual(2, result[0]);
Assert.AreEqual(2, result[1]);
}
/// <summary>
/// Bug was mistaken - '*' does match explicit H but in DEPICTMATCH H's are
/// suppressed by default.
/// </summary>
// @cdk.bug 2489533
[TestMethod()]
public void TestPropertyAnyAtom7()
{
int[] result = Match("*", "CO[H]");
Assert.AreEqual(3, result[0]);
Assert.AreEqual(3, result[1]);
}
/// <summary>
/// Bug was mistaken - '*' does match explicit H but in DEPICTMATCH H's are
/// suppressed by default.
/// </summary>
// @cdk.bug 2489533
[TestMethod()]
public void TestPropertyAnyAtom8()
{
int[] result = Match("*", "[H]C([H])([H])[H]");
Assert.AreEqual(5, result[0]);
Assert.AreEqual(5, result[1]);
}
/// <summary>
/// Bug was mistaken - '*' does match explicit H but in DEPICTMATCH H's are
/// suppressed by default.
/// </summary>
// @cdk.bug 2489533
[TestMethod()]
public void TestPropertyAnyAtom9()
{
int[] result = Match("*", "CCCC([2H])[H]");
Assert.AreEqual(6, result[0]);
Assert.AreEqual(6, result[1]);
}
[TestMethod()]
public void TestPropertyAtomicMass1()
{
int[] results = Match("[13C]", "[13C]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicMass2()
{
int[] results = Match("[13C]", "[C]");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicMass3()
{
int[] results = Match("[13*]", "[13C]Cl");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicMass4()
{
int[] results = Match("[12C]", "CCl");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
// @cdk.bug 2490336
[TestMethod()]
public void TestPropertyAtomicMass5()
{
int[] results = Match("[2H]", "CCCC([2H])[H]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicMass6()
{
int[] results = Match("[H]", "CCCC([2H])[H]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPropertyAtomicMass7()
{
int[] results = Match("[3H]", "CCCC([2H])([3H])[3H]");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestBondSingle1()
{
int[] results = Match("CC", "C=C");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestBondSingle2()
{
int[] results = Match("CC", "C#C");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestBondSingle3()
{
int[] results = Match("CC", "CCO");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestBondSingle4()
{
int[] results = Match("CC", "C1C(C)=C(C=CC(C)=CC=CC(C)=CCO)C(C)(C)C1");
Assert.AreEqual(28, results[0]);
Assert.AreEqual(14, results[1]);
}
[TestMethod()]
public void TestBondSingle5()
{
int[] results = Match("CC", "CC1(C)SC2C(NC(=O)Cc3ccccc3)C(=O)N2C1C(=O)O");
Assert.AreEqual(14, results[0]);
Assert.AreEqual(7, results[1]);
}
[TestMethod()]
public void TestBondAny1()
{
int[] results = Match("C~C", "C=C");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestBondAny2()
{
int[] results = Match("C~C", "C#C");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestBondAny3()
{
int[] results = Match("C~C", "CCO");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestBondAny4()
{
int[] results = Match("C~C", "C1C(C)=C(C=CC(C)=CC=CC(C)=CCO)C(C)(C)C1");
Assert.AreEqual(38, results[0]);
Assert.AreEqual(19, results[1]);
}
[TestMethod()]
public void TestBondAny5()
{
int[] results = Match("[C,c]~[C,c]", "CC1(C)SC2C(NC(=O)Cc3ccccc3)C(=O)N2C1C(=O)O");
Assert.AreEqual(28, results[0]);
Assert.AreEqual(14, results[1]);
}
[TestMethod()]
public void TestBondRing1()
{
int[] results = Match("C@C", "C=C");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestBondRing2()
{
int[] results = Match("C@C", "C#C");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestBondRing3()
{
int[] results = Match("C@C", "C1CCCCC1");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(6, results[1]);
}
[TestMethod()]
public void TestBondRing4()
{
int[] results = Match("[C,c]@[C,c]", "c1ccccc1Cc1ccccc1");
Assert.AreEqual(24, results[0]);
Assert.AreEqual(12, results[1]);
}
[TestMethod()]
public void TestBondRing5()
{
int[] results = Match("[C,c]@[C,c]", "CCN(CC)C(=O)C1CN(C)C2CC3=CNc(ccc4)c3c4C2=C1");
Assert.AreEqual(30, results[0]);
Assert.AreEqual(15, results[1]);
}
[TestMethod()]
public void TestBondRing6()
{
int[] results = Match("[C,c]@[C,c]", "N12CCC36C1CC(C(C2)=CCOC4CC5=O)C4C3N5c7ccccc76");
Assert.AreEqual(44, results[0]);
Assert.AreEqual(22, results[1]);
}
[TestMethod()]
public void TestBondStereo1()
{
int[] results = Match("F/?C=C/Cl", "F/C=C/Cl");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestBondStereo2()
{
int[] results = Match("F/?C=C/Cl", "FC=C/Cl");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestBondStereo3()
{
int[] results = Match("F/?C=C/Cl", "FC=CCl");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestBondStereo4()
{
int[] results = Match("F/?C=C/Cl", "F\\C=C/Cl");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestLogicalNot1()
{
int[] results = Match("[!c]", "c1cc(C)c(N)cc1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestLogicalNot2()
{
int[] results = Match("[!c]", "c1c(C)c(N)cnc1");
Assert.AreEqual(3, results[0]);
Assert.AreEqual(3, results[1]);
}
[TestMethod()]
public void TestLogicalNot3()
{
int[] results = Match("[!c]", "c1(C)c(N)cco1");
Assert.AreEqual(3, results[0]);
Assert.AreEqual(3, results[1]);
}
[TestMethod()]
public void TestLogicalNot4()
{
int[] results = Match("[!c]", "c1c(C)c(N)c[nH]1");
Assert.AreEqual(3, results[0]);
Assert.AreEqual(3, results[1]);
}
[TestMethod()]
public void TestLogicalNot5()
{
int[] results = Match("[!c]", "O=n1ccccc1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestLogicalNot6()
{
int[] results = Match("[!c]", "[O-][n+]1ccccc1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestLogicalNot7()
{
int[] results = Match("[!c]", "c1ncccc1C1CCCN1C");
Assert.AreEqual(7, results[0]);
Assert.AreEqual(7, results[1]);
}
[TestMethod()]
public void TestLogicalNot8()
{
int[] results = Match("[!c]", "c1ccccc1C(=O)OC2CC(N3C)CCC3C2C(=O)OC");
Assert.AreEqual(16, results[0]);
Assert.AreEqual(16, results[1]);
}
[TestMethod()]
public void TestLogicalOr1()
{
int[] results = Match("[N,O,o]", "c1cc(C)c(N)cc1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestLogicalOr2()
{
int[] results = Match("[N,O,o]", "c1c(C)c(N)cnc1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestLogicalOr3()
{
int[] results = Match("[N,O,o]", "c1(C)c(N)cco1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestLogicalOr4()
{
int[] results = Match("[N,O,o]", "c1c(C)c(N)c[nH]1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestLogicalOr5()
{
int[] results = Match("[N,O,o]", "O=n1ccccc1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestLogicalOr6()
{
int[] results = Match("[N,O,o]", "[O-][n+]1ccccc1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestLogicalOr7()
{
int[] results = Match("[N,O,o]", "c1ncccc1C1CCCN1C");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestLogicalOr8()
{
int[] results = Match("[N,O,o]", "c1ccccc1C(=O)OC2CC(N3C)CCC3C2C(=O)OC");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
[TestMethod()]
public void TestLogicalOr9()
{
int[] results = Match("[N]=[N]-,=[N]", "CCCC(=O)C=C");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestLogicalOr10()
{
int[] results = Match("[N;$([N!X4])]!@;-[N;$([N!X4])]", "CCCC(=O)C=C");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestLogicalOr11()
{
int[] results = Match("[#6]!:;=[#6][#6](=O)[!O]", "CCCC(=O)C=C");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestLogicalOr12()
{
int[] results = Match("C=,#C", "C=CCC#C");
Assert.AreEqual(4, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestLogicalOrHighAnd1()
{
int[] results = Match("[N,#6&+1,+0]", "CCN(CC)C(=O)C1CN(C)C2CC3=CNc(ccc4)c3c4C2=C1");
Assert.AreEqual(24, results[0]);
Assert.AreEqual(24, results[1]);
}
[TestMethod()]
public void TestLogicalOrHighAnd2()
{
int[] results = Match("[N,#6&+1,+0]", "N12CCC36C1CC(C(C2)=CCOC4CC5=O)C4C3N5c7ccccc76");
Assert.AreEqual(25, results[0]);
Assert.AreEqual(25, results[1]);
}
[TestMethod()]
public void TestLogicalOrHighAnd3()
{
int[] results = Match("[N,#6&+1,+0]", "COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34");
Assert.AreEqual(24, results[0]);
Assert.AreEqual(24, results[1]);
}
[TestMethod()]
public void TestLogicalOrHighAnd4()
{
int[] results = Match("[N,#6&+1,+0]", "C123C5C(O)C=CC2C(N(C)CC1)Cc(ccc4O)c3c4O5");
Assert.AreEqual(21, results[0]);
Assert.AreEqual(21, results[1]);
}
[TestMethod()]
public void TestLogicalOrHighAnd5()
{
int[] results = Match("[N,#6&+1,+0]", "N1N([Hg-][O+]=C1N=Nc2ccccc2)c3ccccc3");
Assert.AreEqual(17, results[0]);
Assert.AreEqual(17, results[1]);
}
[TestMethod()]
public void TestLogicalOrHighAnd6()
{
int[] results = Match("[N,#6&+1,+0]", "[Na+].[Na+].[O-]C(=O)c1ccccc1c2c3ccc([O-])cc3oc4cc(=O)ccc24");
Assert.AreEqual(23, results[0]);
}
[TestMethod()]
public void TestLogicalOrHighAnd7()
{
int[] results = Match("[N,#6&+1,+0]", "[Cl-].Clc1ccc([I+]c2cccs2)cc1");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(12, results[1]);
}
[TestMethod()]
public void TestLogicalOrLowAnd1()
{
int[] results = Match("[#7,C;+0,+1]", "CCN(CC)C(=O)C1CN(C)C2CC3=CNc(ccc4)c3c4C2=C1");
Assert.AreEqual(15, results[0]);
Assert.AreEqual(15, results[1]);
}
[TestMethod()]
public void TestLogicalOrLowAnd2()
{
int[] results = Match("[#7,C;+0,+1]", "N12CCC36C1CC(C(C2)=CCOC4CC5=O)C4C3N5c7ccccc76");
Assert.AreEqual(17, results[0]);
Assert.AreEqual(17, results[1]);
}
[TestMethod()]
public void TestLogicalOrLowAnd3()
{
int[] results = Match("[#7,C;+0,+1]", "COc1cc2c(ccnc2cc1)C(O)C4CC(CC3)C(C=C)CN34");
Assert.AreEqual(13, results[0]);
Assert.AreEqual(13, results[1]);
}
[TestMethod()]
public void TestLogicalOrLowAnd4()
{
int[] results = Match("[#7,C;+0,+1]", "C123C5C(O)C=CC2C(N(C)CC1)Cc(ccc4O)c3c4O5");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(12, results[1]);
}
[TestMethod()]
public void TestLogicalOrLowAnd5()
{
int[] results = Match("[#7,C;+0,+1]", "N1N([Hg-][O+]=C1N=Nc2ccccc2)c3ccccc3");
Assert.AreEqual(5, results[0]);
Assert.AreEqual(5, results[1]);
}
/// <summary>
/// The CDK aromaticity detection differs from Daylight - by persevering
/// aromaticity from the SMILES we can match correctly.
/// </summary>
[TestMethod()]
public void TestLogicalOrLowAnd6()
{
SMARTSQueryTool sqt = CreateFromSmarts("[#7,C;+0,+1]");
IAtomContainer smi = CreateFromSmiles("[Na+].[Na+].[O-]C(=O)c1ccccc1c2c3ccc([O-])cc3oc4cc(=O)ccc24");
int[] results = Match(sqt, smi);
Assert.AreEqual(1, results[0]);
}
[TestMethod()]
public void TestLogicalOrLowAnd6_cdkAromaticity()
{
SMARTSQueryTool sqt = CreateFromSmarts("[#7,C;+0,+1]");
IAtomContainer smi = CreateFromSmiles("[Na+].[Na+].[O-]C(=O)c1ccccc1c2c3ccc([O-])cc3oc4cc(=O)ccc24");
sqt.SetAromaticity(new Aromaticity(ElectronDonation.CDKModel, Cycles.CDKAromaticSetFinder));
AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(smi);
int[] results = Match(sqt, smi);
Assert.AreEqual(8, results[0]);
}
[TestMethod()]
public void TestLogicalOrLowAnd7()
{
int[] results = Match("[#7,C;+0,+1]", "[Cl-].Clc1ccc([I+]c2cccs2)cc1");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestRing1()
{
int[] results = Match("C1CCCCC1", "C1CCCCC1CCCC");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestRing2()
{
int[] results = Match("C1CCCCC1", "C1CCCCC1C1CCCCC1");
Assert.AreEqual(24, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestRing3()
{
int[] results = Match("C1CCCCC1", "C1CCCC12CCCCC2");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestRing4()
{
int[] results = Match("C1CCCCC1", "c1ccccc1O");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestRing5()
{
int[] results = Match("C1CCCCC1", "c1ccccc1CCCCCC");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestRing_large()
{
int[] results = Match("C%10CCCCC%10", "C1CCCCC1O");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestRing_large2()
{
int[] results = Match("C%99CCCCC%99", "C1CCCCC1O");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestRing_large3()
{
int[] results = Match("C%991CCCCC%99CCCC1", "C12CCCCC2CCCC1");
Assert.AreEqual(4, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestRing6()
{
int[] results = Match("C1CCCCC1", "CCCCCC");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestAromaticRing1()
{
int[] results = Match("c1ccccc1", "c1ccccc1");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAromaticRing2()
{
int[] results = Match("c1ccccc1", "c1cccc2c1cccc2");
Assert.AreEqual(24, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestAromaticRing3()
{
int[] results = Match("c1ccccn1", "c1cccc2c1cccc2");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestAromaticRing4()
{
int[] results = Match("c1ccccn1", "c1cccc2c1cccn2");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid1()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(C)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid2()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CCCNC(N)=N)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid3()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CC(N)=O)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid4()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CC(O)=O)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid5()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CS)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid6()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CCC(N)=O)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid7()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CCC(O)=O)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid8()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC([H])C(O)=O");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestAminoAcid9()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CC1=CNC=N1)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid10()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(C(CC)C)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid11()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CC(C)C)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid12()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CCCCN)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid13()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CCSC)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid14()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CC1=CC=CC=C1)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid15()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "OC(C1CCCN1)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid16()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CO)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid17()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(C(C)O)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid18()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CC1=CNC2=C1C=CC=C2)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid19()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(CC1=CC=C(O)C=C1)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestAminoAcid20()
{
int[] results = Match("[NX3,NX4+][CX4H]([*])[CX3](=[OX1])[O,N]", "NC(C(C)C)C(O)=O");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestCyclicUreas()
{
int[] results = Match("[$(C1CNC(=O)N1)]", "N1C(=O)NCC1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
// @cdk.bug 1967468
[TestMethod()]
public void TestAcyclicUreas()
{
int[] results = Match("[$(CC);$(C1CNC(=O)N1)]", "C1CC1NC(=O)Nc2ccccc2");
// int[] results = Match("[$([CR][NR][CR](=O)[NR])]", "C1CC1NC(=O)Nc2ccccc2");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
// @cdk.bug 1985811
[TestMethod()]
public void TestIndoleAgainstIndole()
{
int[] results = Match("c1ccc2cc[nH]c2(c1)", "C1(NC=C2)=C2C=CC=C1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
results = Match("c1ccc2cc[nH]c2(c1)", "c1ccc2cc[nH]c2(c1)");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 1985811
[TestMethod()]
public void TestPyridineAgainstPyridine()
{
int[] results = Match("c1ccncc1", "c1ccncc1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
results = Match("c1ccncc1", "C1=NC=CC=C1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestGroup5Elements()
{
int[] results = Match("[V,Cr,Mn,Nb,Mo,Tc,Ta,W,Re]", "[W]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestPeriodicGroupNumber()
{
int[] results = Match("[G14]", "CCN");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
results = Match("[G14,G15]", "CCN");
Assert.AreEqual(3, results[0]);
Assert.AreEqual(3, results[1]);
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestInvalidPeriodicGroupNumber()
{
Match("[G19]", "CCN");
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestInvalidPeriodicGroupNumber_2()
{
Match("[G0]", "CCN");
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestInvalidPeriodicGroupNumber_3()
{
Match("[G345]", "CCN");
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestNonPeriodicGroupNumber()
{
Match("[G]", "CCN"); // Should throw an exception if G is not followed by a number
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestNonPeriodicGroupNumber_2()
{
Match("[GA]", "CCN"); // Should throw an exception if G is not followed by a number
}
[TestMethod()]
public void TestNonCHHeavyAtom()
{
int[] results = Match("[#X]", "CCN");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
results = Match("[#X]", "CCNC(=O)CCSF");
Assert.AreEqual(4, results[0]);
Assert.AreEqual(4, results[1]);
results = Match("C#[#X]", "CCNC(=O)C#N");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
results = Match("C#[#X]", "CCNC(=O)C#C");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestHybridizationNumber()
{
int[] results = Match(CreateFromSmarts("[^1]"), SmilesAtomTyped("CCN"));
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
results = Match(CreateFromSmarts("[^1]"), SmilesAtomTyped("N#N"));
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
results = Match(CreateFromSmarts("[^1&N]"), SmilesAtomTyped("CC#C"));
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
results = Match(CreateFromSmarts("[^1&N]"), SmilesAtomTyped("CC#N"));
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
results = Match(CreateFromSmarts("[^1&N,^2&C]"), SmilesAtomTyped("CC(=O)CC(=O)CC#N"));
Assert.AreEqual(3, results[0]);
Assert.AreEqual(3, results[1]);
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestBadHybridizationNumber()
{
Match("[^]", "CCN"); // Should throw an exception if ^ is not followed by a number
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestBadHybridizationNumber_2()
{
Match("[^X]", "CCN"); // Should throw an exception if ^ is not followed by a number
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestBadHybridizationNumber_3()
{
Match("[^0]", "CCN"); // Should throw an exception if ^ is not followed by a number
}
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void TestBadHybridizationNumber_4()
{
Match("[^9]", "CCN"); // Should throw an exception if ^ is not followed by a number
}
// @cdk.bug 2589807
[TestMethod()]
public void TestAromAliArom()
{
int[] results = Match("c-c", "COC1CN(CCC1NC(=O)C2=CC(=C(C=C2OC)N)Cl)CCCOC3=CC=C(C=C3)F");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
IAtomContainer m = CreateFromSmiles("c1ccccc1c2ccccc2");
// note - missing explicit single bond, SMILES preserves the
// aromatic specification but in this case we want the single
// bond. as the molecule as assigned bond orders we can easily
// remove the flags and reassign them correctly
foreach (var bond in m.Bonds)
bond.IsAromatic = false;
AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m);
Aromaticity.CDKLegacy.Apply(m);
results = Match(CreateFromSmarts("c-c"), m);
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
results = Match("c-c", "c1ccccc1-c1ccccc1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
results = Match("cc", "c1ccccc1-c1ccccc1");
Assert.AreEqual(26, results[0]);
Assert.AreEqual(13, results[1]);
results = Match("cc", "c1ccccc1c2ccccc2");
Assert.AreEqual(26, results[0]);
Assert.AreEqual(13, results[1]);
}
[TestMethod()]
public void TestUnspecifiedBond()
{
int[] results = Match("CC", "CCc1ccccc1");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(1, results[1]);
results = Match("[#6][#6]", "CCc1ccccc1");
Assert.AreEqual(16, results[0]);
Assert.AreEqual(8, results[1]);
results = Match("[#6]-[#6]", "CCc1ccccc1");
Assert.AreEqual(4, results[0]);
Assert.AreEqual(2, results[1]);
results = Match("[#6]:[#6]", "CCc1ccccc1");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(6, results[1]);
results = Match("cc", "CCc1ccccc1");
Assert.AreEqual(12, results[0]);
Assert.AreEqual(6, results[1]);
results = Match("c-c", "CCc1ccccc1");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
results = Match("c-C", "CCc1ccccc1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 2587204
[TestMethod()]
public void TestLactamSimple()
{
int[] results = Match("[R0][ND3R][CR]=O", "N1(CC)C(=O)CCCC1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 2587204
[TestMethod()]
public void TestLactamRecursive()
{
int[] results = Match("[R0]-[$([NRD3][CR]=O)]", "N1(CC)C(=O)CCCC1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
[TestMethod()]
public void TestLactamRecursiveAlternate()
{
int[] results = Match("[!R]-[$([NRD3][CR]=O)]", "N1(CC)C(=O)CCCC1");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 2898399
[TestMethod()]
public void TestHydrogen()
{
int[] results = Match("[H]", "[H]");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
// @cdk.bug 2898399
[TestMethod()]
public void TestLeadingHydrogen()
{
int[] results = Match("[H][C@@]1(CCC(C)=CC1=O)C(C)=C", "[H][C@@]1(CCC(C)=CC1=O)C(C)=C");
Assert.AreEqual(1, results[0]);
Assert.AreEqual(1, results[1]);
}
/// <summary>
/// Note that this test passes, and really indicates that
/// the SMARTS below is not a correct one for vinylogous
/// esters
/// </summary>
// @cdk.bug 2871303
[TestMethod()]
public void TestVinylogousEster()
{
int[] results = Match("[#6X3](=[OX1])[#6X3]=,:[#6X3][#6;!$(C=[O,N,S])]", "c1ccccc1C=O");
Assert.AreEqual(2, results[0]);
Assert.AreEqual(2, results[1]);
}
/// <summary>
/// Check that bond order query respects aromaticity.
/// </summary>
[TestMethod()]
public void TestBondOrderQueryKekuleVsSmiles()
{
int[] results = Match("[#6]=[#6]", "c1ccccc1c2ccccc2");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
results = Match("[#6]=[#6]", "C1=C(C=CC=C1)C2=CC=CC=C2");
Assert.AreEqual(0, results[0]);
Assert.AreEqual(0, results[1]);
}
[TestMethod()]
public void TestSubstructureBug20141125()
{
int[] results = Match("[#6]S[#6]", "CSCCSCO");
Assert.AreEqual(4, results[0]);
Assert.AreEqual(2, results[1]);
}
[TestMethod()]
public void TestSubstructureBug20141125_2()
{
int[] results = Match("[#6]S[#6]", "CSCCSC(O)CCCSCC");
Assert.AreEqual(6, results[0]);
Assert.AreEqual(3, results[1]);
}
/// <summary>
/// Checks that when no number is specified for ring member ship any ring
/// atom is matched.
/// </summary>
// @cdk.bug 1168
[TestMethod()]
public void UnspecifiedRingMembership()
{
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 0 }, Match("[#6+0&R]=[#6+0&!R]", "C1=C2CCCC2CCC1")));
}
[TestMethod()]
public void Cyclopropane()
{
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 0 }, Match("**(*)*", "C1CC1")));
}
[TestMethod()]
public void ComponentGrouping1()
{
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 0 }, Match("[#8].[#8]", "O")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 2, 1 }, Match("[#8].[#8]", "O=O")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 2, 1 }, Match("[#8].[#8]", "OCCO")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 2, 1 }, Match("[#8].[#8]", "O.CCO")));
}
[TestMethod()]
public void ComponentGrouping2()
{
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 0 }, Match("([#8].[#8])", "O")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 2, 1 }, Match("([#8].[#8])", "O=O")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 2, 1 }, Match("([#8].[#8])", "OCCO")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 0 }, Match("([#8].[#8])", "O.CCO")));
}
[TestMethod()]
public void ComponentGrouping3()
{
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 0 }, Match("([#8]).([#8])", "O")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 0 }, Match("([#8]).([#8])", "O=O")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 0 }, Match("([#8]).([#8])", "OCCO")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 2, 1 }, Match("([#8]).([#8])", "O.CCO")));
}
/// <summary>
/// Ensure 'r' without a size is equivalent to !R0 and R.
/// </summary>
// @cdk.bug 1364
[TestMethod()]
public void Bug1364()
{
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 7, 7 }, Match("[!R0!R1]", "C[C@]12CC3CC([NH2+]CC(=O)NCC4CC4)(C1)C[C@@](C)(C3)C2")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 7, 7 }, Match("[R!R1]", "C[C@]12CC3CC([NH2+]CC(=O)NCC4CC4)(C1)C[C@@](C)(C3)C2")));
Assert.IsTrue(Compares.AreDeepEqual(new int[] { 7, 7 }, Match("[r!R1]", "C[C@]12CC3CC([NH2+]CC(=O)NCC4CC4)(C1)C[C@@](C)(C3)C2")));
}
}
}
| lgpl-2.1 |
raedle/univis | lib/springframework-1.2.8/src/org/springframework/jdbc/support/JdbcUtils.java | 13849 | /*
* Copyright 2002-2005 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.support;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.datasource.DataSourceUtils;
/**
* Generic utility methods for working with JDBC. Mainly for internal use
* within the framework, but also useful for custom JDBC access code.
*
* @author Thomas Risberg
* @author Juergen Hoeller
*/
public abstract class JdbcUtils {
private static final Log logger = LogFactory.getLog(JdbcUtils.class);
/**
* Close the given JDBC Connection and ignore any thrown exception.
* This is useful for typical finally blocks in manual JDBC code.
* @param con the JDBC Connection to close
*/
public static void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
}
catch (SQLException ex) {
logger.error("Could not close JDBC Connection", ex);
}
catch (Throwable ex) {
// We don't trust the JDBC driver: It might throw RuntimeException or Error.
logger.error("Unexpected exception on closing JDBC Connection", ex);
}
}
}
/**
* Close the given JDBC Statement and ignore any thrown exception.
* This is useful for typical finally blocks in manual JDBC code.
* @param stmt the JDBC Statement to close
*/
public static void closeStatement(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException ex) {
logger.warn("Could not close JDBC Statement", ex);
}
catch (Throwable ex) {
// We don't trust the JDBC driver: It might throw RuntimeException or Error.
logger.error("Unexpected exception on closing JDBC Statement", ex);
}
}
}
/**
* Close the given JDBC ResultSet and ignore any thrown exception.
* This is useful for typical finally blocks in manual JDBC code.
* @param rs the JDBC ResultSet to close
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
}
catch (SQLException ex) {
logger.warn("Could not close JDBC ResultSet", ex);
}
catch (Throwable ex) {
// We don't trust the JDBC driver: It might throw RuntimeException or Error.
logger.error("Unexpected exception on closing JDBC ResultSet", ex);
}
}
}
/**
* Retrieve a JDBC column value from a ResultSet, using the most appropriate
* value type. The returned value should be a detached value object, not having
* any ties to the active ResultSet: in particular, it should not be a Blob or
* Clob object but rather a byte array respectively String representation.
* <p>Uses the <code>getObject(index)</code> method, but includes additional "hacks"
* to get around Oracle 10g returning a non-standard object for its TIMESTAMP
* datatype and a <code>java.sql.Date</code> for DATE columns leaving out the
* time portion: These columns will explicitly be extracted as standard
* <code>java.sql.Timestamp</code> object.
* @param rs is the ResultSet holding the data
* @param index is the column index
* @return the value object
* @see java.sql.Blob
* @see java.sql.Clob
* @see java.sql.Timestamp
* @see oracle.sql.TIMESTAMP
*/
public static Object getResultSetValue(ResultSet rs, int index) throws SQLException {
Object obj = rs.getObject(index);
if (obj instanceof Blob) {
obj = rs.getBytes(index);
}
else if (obj instanceof Clob) {
obj = rs.getString(index);
}
else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.TIMESTAMP")) {
obj = rs.getTimestamp(index);
}
else if (obj != null && obj instanceof java.sql.Date) {
if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) {
obj = rs.getTimestamp(index);
}
}
return obj;
}
/**
* Extract database meta data via the given DatabaseMetaDataCallback.
* <p>This method will open a connection to the database and retrieve the database metadata.
* Since this method is called before the exception translation feature is configured for
* a datasource, this method can not rely on the SQLException translation functionality.
* <p>Any exceptions will be wrapped in a MetaDataAccessException. This is a checked exception
* and any calling code should catch and handle this exception. You can just log the
* error and hope for the best, but there is probably a more serious error that will
* reappear when you try to access the database again.
* @param dataSource the DataSource to extract metadata for
* @param action callback that will do the actual work
* @return object containing the extracted information, as returned by
* the DatabaseMetaDataCallback's <code>processMetaData</code> method
* @throws MetaDataAccessException if meta data access failed
*/
public static Object extractDatabaseMetaData(DataSource dataSource, DatabaseMetaDataCallback action)
throws MetaDataAccessException {
Connection con = null;
try {
con = DataSourceUtils.getConnection(dataSource);
if (con == null) {
// should only happen in test environments
throw new MetaDataAccessException("Connection returned by DataSource [" + dataSource + "] was null");
}
DatabaseMetaData metaData = con.getMetaData();
if (metaData == null) {
// should only happen in test environments
throw new MetaDataAccessException("DatabaseMetaData returned by Connection [" + con + "] was null");
}
return action.processMetaData(metaData);
}
catch (CannotGetJdbcConnectionException ex) {
throw new MetaDataAccessException("Could not get Connection for extracting meta data", ex);
}
catch (SQLException ex) {
throw new MetaDataAccessException("Error while extracting DatabaseMetaData", ex);
}
catch (AbstractMethodError err) {
throw new MetaDataAccessException(
"JDBC DatabaseMetaData method not implemented by JDBC driver - upgrade your driver", err);
}
finally {
DataSourceUtils.releaseConnection(con, dataSource);
}
}
/**
* Call the specified method on DatabaseMetaData for the given DataSource,
* and extract the invocation result.
* @param dataSource the DataSource to extract meta data for
* @param metaDataMethodName the name of the DatabaseMetaData method to call
* @return the object returned by the specified DatabaseMetaData method
* @throws MetaDataAccessException if we couldn't access the DatabaseMetaData
* or failed to invoke the specified method
* @see java.sql.DatabaseMetaData
*/
public static Object extractDatabaseMetaData(DataSource dataSource, final String metaDataMethodName)
throws MetaDataAccessException {
return extractDatabaseMetaData(dataSource,
new DatabaseMetaDataCallback() {
public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
try {
Method method = dbmd.getClass().getMethod(metaDataMethodName, (Class[]) null);
return method.invoke(dbmd, (Object[]) null);
}
catch (NoSuchMethodException ex) {
throw new MetaDataAccessException("No method named '" + metaDataMethodName +
"' found on DatabaseMetaData instance [" + dbmd + "]", ex);
}
catch (IllegalAccessException ex) {
throw new MetaDataAccessException(
"Could not access DatabaseMetaData method '" + metaDataMethodName + "'", ex);
}
catch (InvocationTargetException ex) {
if (ex.getTargetException() instanceof SQLException) {
throw (SQLException) ex.getTargetException();
}
throw new MetaDataAccessException(
"Invocation of DatabaseMetaData method '" + metaDataMethodName + "' failed", ex);
}
}
});
}
/**
* Return whether the given JDBC driver supports JDBC 2.0 batch updates.
* <p>Typically invoked right before execution of a given set of statements:
* to decide whether the set of SQL statements should be executed through
* the JDBC 2.0 batch mechanism or simply in a traditional one-by-one fashion.
* <p>Logs a warning if the "supportsBatchUpdates" methods throws an exception
* and simply returns false in that case.
* @param con the Connection to check
* @return whether JDBC 2.0 batch updates are supported
* @see java.sql.DatabaseMetaData#supportsBatchUpdates
*/
public static boolean supportsBatchUpdates(Connection con) {
try {
DatabaseMetaData dbmd = con.getMetaData();
if (dbmd != null) {
if (dbmd.supportsBatchUpdates()) {
if (logger.isDebugEnabled()) {
logger.debug("JDBC driver supports batch updates");
}
return true;
}
else {
if (logger.isDebugEnabled()) {
logger.debug("JDBC driver does not support batch updates");
}
}
}
}
catch (SQLException ex) {
logger.warn("JDBC driver 'supportsBatchUpdates' method threw exception", ex);
}
catch (AbstractMethodError err) {
logger.warn("JDBC driver does not support JDBC 2.0 'supportsBatchUpdates' method", err);
}
return false;
}
/**
* Count the occurrences of the character <code>placeholder</code> in an SQL string
* <code>str</code>. The character <code>placeholder</code> is not counted if it
* appears within a literal as determined by the <code>delim</code> that is passed in.
* Delegates to the overloaded method that takes a String with multiple delimiters.
* @param str string to search in. Returns 0 if this is null.
* @param placeholder the character to search for and count
* @param delim the delimiter for character literals
*/
public static int countParameterPlaceholders(String str, char placeholder, char delim) {
return countParameterPlaceholders(str, placeholder, "" + delim);
}
/**
* Count the occurrences of the character <code>placeholder</code> in an SQL string
* <code>str</code>. The character <code>placeholder</code> is not counted if it
* appears within a literal as determined by the <code>delimiters</code> that are passed in.
* <p>Examples: If one of the delimiters is the single quote, and the character to count the
* occurrences of is the question mark, then:
* <p><code>The big ? 'bad wolf?'</code> gives a count of one.<br>
* <code>The big ?? bad wolf</code> gives a count of two.<br>
* <code>The big 'ba''ad?' ? wolf</code> gives a count of one.
* <p>The grammar of the string passed in should obey the rules of the JDBC spec
* which is close to no rules at all: one placeholder per parameter, and it should
* be valid SQL for the target database.
* @param str string to search in. Returns 0 if this is null
* @param placeholder the character to search for and count.
* @param delimiters the delimiters for character literals.
*/
public static int countParameterPlaceholders(String str, char placeholder, String delimiters) {
int count = 0;
boolean insideLiteral = false;
int activeLiteral = -1;
for (int i = 0; str != null && i < str.length(); i++) {
if (str.charAt(i) == placeholder) {
if (!insideLiteral)
count++;
}
else {
if (delimiters.indexOf(str.charAt(i)) > -1) {
if (!insideLiteral) {
insideLiteral = true;
activeLiteral = delimiters.indexOf(str.charAt(i));
}
else {
if (activeLiteral == delimiters.indexOf(str.charAt(i))) {
insideLiteral = false;
activeLiteral = -1;
}
}
}
}
}
return count;
}
/**
* Check that a SQL type is numeric.
* @param sqlType the SQL type to be checked
* @return if the type is numeric
*/
public static boolean isNumeric(int sqlType) {
return Types.BIT == sqlType || Types.BIGINT == sqlType || Types.DECIMAL == sqlType ||
Types.DOUBLE == sqlType || Types.FLOAT == sqlType || Types.INTEGER == sqlType ||
Types.NUMERIC == sqlType || Types.REAL == sqlType || Types.SMALLINT == sqlType ||
Types.TINYINT == sqlType;
}
/**
* Translate a SQL type into one of a few values:
* All string types are translated to String.
* All integer types are translated to Integer.
* All real types are translated to Double.
* All other types are left untouched.
* @param sqlType the type to be translated into a simpler type
* @return the new SQL type
* @deprecated This is only used by deprecated constructors in
* SqlFunction and will be removed alongside those constructors.
* @see org.springframework.jdbc.object.SqlFunction#SqlFunction(javax.sql.DataSource, String, int)
*/
public static int translateType(int sqlType) {
int retType = sqlType;
if (Types.CHAR == sqlType || Types.VARCHAR == sqlType) {
retType = Types.VARCHAR;
}
else if (Types.BIT == sqlType || Types.TINYINT == sqlType || Types.SMALLINT == sqlType ||
Types.INTEGER == sqlType) {
retType = Types.INTEGER;
}
else if (Types.DECIMAL == sqlType || Types.DOUBLE == sqlType || Types.FLOAT == sqlType ||
Types.NUMERIC == sqlType || Types.REAL == sqlType) {
retType = Types.NUMERIC;
}
return retType;
}
}
| lgpl-2.1 |
Anatoscope/sofa | applications/plugins/Compliant/numericalsolver/ModulusSolver.cpp | 6468 | #include "ModulusSolver.h"
#include "EigenSparseResponse.h"
#include <sofa/core/ObjectFactory.h>
#include "../utils/anderson.h"
#include "../utils/nlnscg.h"
#include "../utils/scoped.h"
#include "../constraint/CoulombConstraint.h"
#include "../constraint/UnilateralConstraint.h"
#include <Eigen/SparseCholesky>
#include "../utils/sub_kkt.inl"
namespace utils {
template<class Matrix>
struct sub_kkt::traits< Eigen::SimplicialLDLT<Matrix, Eigen::Upper> > {
typedef Eigen::SimplicialLDLT<Matrix, Eigen::Upper> solver_type;
static void factor(solver_type& solver, const rmat& matrix) {
// ldlt expects a cmat so we transpose to ease the conversion
solver.compute(matrix.triangularView<Eigen::Lower>().transpose());
if( solver.info() != Eigen::Success ) {
std::cerr << "error during LDLT factorization !" << std::endl;
std::cerr << matrix << std::endl;
}
}
static void solve(const solver_type& solver, vec& res, const vec& rhs) {
res = solver.solve(rhs);
}
};
}
namespace sofa {
namespace component {
namespace linearsolver {
SOFA_DECL_CLASS(ModulusSolver)
int ModulusSolverClass = core::RegisterObject("Modulus solver").add< ModulusSolver >();
ModulusSolver::ModulusSolver()
: omega(initData(&omega,
(real)1.0,
"omega",
"magic stuff")),
anderson(initData(&anderson, unsigned(0),
"anderson",
"anderson acceleration history size, 0 if none")),
nlnscg(initData(&nlnscg, false,
"nlnscg",
"nlnscg acceleration"))
{
}
ModulusSolver::~ModulusSolver() {
}
void ModulusSolver::factor(const system_type& sys) {
// build unilateral mask
unilateral = vec::Zero(sys.n);
// build system TODO hardcoded regularization
sub.projected_kkt(sys, 1e-14, true);
const vec Hdiag_inv = sys.P * sys.H.diagonal().cwiseInverse();
diagonal = vec::Zero(sys.n);
// change diagonal compliance
const real omega = this->omega.getValue();
// compute diagonal + homogenize tangent values
{
unsigned off = 0;
for(unsigned i = 0, n = sys.constraints.size(); i < n; ++i) {
const unsigned dim = sys.compliant[i]->getMatrixSize();
for(unsigned j = off, je = off + dim; j < je; ++j) {
diagonal(j) = sys.J.row(j).dot( Hdiag_inv.asDiagonal() * sys.J.row(j).transpose());
}
typedef linearsolver::CoulombConstraintBase proj_type;
Constraint* c = sys.constraints[i].projector.get();
// unilateral mask
if( c ) {
unilateral.segment(off, dim).setOnes();
}
if( c && proj_type::checkConstraintType(c) ) {
assert( dim % 3 == 0 && "non vec3 dofs not handled");
for(unsigned j = 0, je = dim / 3; j < je; ++j) {
// set both tangent values to max tangent value to
// avoid friction anisotropy
const unsigned t1 = off + 3 * j + 1;
const unsigned t2 = off + 3 * j + 2;
const SReal value = std::max(diagonal(t1),
diagonal(t2));
diagonal(t1) = value;
diagonal(t2) = value;
}
}
off += dim;
}
assert( off == sys.n );
}
// update system matrix (2, 2 block) with diagonal
for(unsigned i = 0; i < sys.n; ++i) {
sub.matrix.coeffRef(sub.primal.cols() + i,
sub.primal.cols() + i) += unilateral(i) * (-omega * diagonal(i));
}
// factor the modified kkt
sub.factor( solver );
// std::clog << unilateral.transpose() << std::endl;
}
template<class View>
static void project(View&& view, const ModulusSolver::system_type& sys, bool correct) {
unsigned off = 0;
for(unsigned i = 0, n = sys.constraints.size(); i < n; ++i) {
const unsigned dim = sys.compliant[i]->getMatrixSize();
const linearsolver::Constraint* proj = sys.constraints[i].projector.get();
if( proj ) {
proj->project(&view[off], dim, 0, correct);
}
off += dim;
}
assert( off == view.size() );
}
// good luck with that :p
void ModulusSolver::solve(vec& res,
const system_type& sys,
const vec& rhs) const {
if( !sys.n ) {
sub.solve(solver, res, rhs);
return;
}
vec constant, tmp;
constant.resize(sys.size() );
tmp.resize(sys.size() );
constant.head(sys.m) = rhs.head(sys.m);
constant.tail(sys.n) = - rhs.tail(sys.n);
// y = (x, z)
vec y = vec::Zero( sys.size() );
// TODO warm start ?
vec zabs;
vec old;
real error;
// TODO
const bool correct = false;
const real omega = this->omega.getValue();
const real precision = this->precision.getValue();
// // utils::anderson accel(sys.n, anderson.getValue(), diagonal);
// utils::nlnscg accel(sys.n, diagonal);
unsigned k;
const unsigned kmax = iterations.getValue();
// const bool use_accel = anderson.getValue();
for(k = 0; k < kmax; ++k) {
old = y.tail(sys.n);
// |z| = 2 * P(z) - z
zabs = y.tail(sys.n);
project( zabs, sys, correct );
zabs = 2 * zabs - y.tail(sys.n);
// don't consider bilateral constraints
zabs = zabs.array() * unilateral.array();
tmp = constant;
// TODO only non-projection constraints?
tmp.head(sys.m) += sys.J.transpose() * zabs;
tmp.tail(sys.n) += sys.C * zabs - omega * diagonal.cwiseProduct(zabs);
// solve in place
sub.solve(solver, y, tmp);
error = (old - y.tail(sys.n)).norm();
if( error <= precision ) break;
}
if( this->f_printLog.getValue() ) {
serr << "fixed point error: " << error << "\titerations: " << k << sendl;
}
// and that should be it ?
res.head(sys.m) = y.head(sys.m);
res.tail(sys.n) = (y.tail(sys.n) + zabs);
}
}
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/GenerationTargetToStdout.java | 889 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.tool.schema.internal.exec;
/**
* GenerationTarget implementation for handling generation to System.out
*
* @author Steve Ebersole
*/
public class GenerationTargetToStdout implements GenerationTarget {
private final String delimiter;
public GenerationTargetToStdout(String delimiter) {
this.delimiter = delimiter;
}
public GenerationTargetToStdout() {
this ( null );
}
@Override
public void prepare() {
// nothing to do
}
@Override
public void accept(String command) {
if ( delimiter != null ) {
command += delimiter;
}
System.out.println( command );
}
@Override
public void release() {
}
}
| lgpl-2.1 |
sim-x/simx | src/simx/InputHandler.C | 4605 | // Copyright (c) 2012. Los Alamos National Security, LLC.
// This material was produced under U.S. Government contract DE-AC52-06NA25396
// for Los Alamos National Laboratory (LANL), which is operated by Los Alamos
// National Security, LLC for the U.S. Department of Energy. The U.S. Government
// has rights to use, reproduce, and distribute this software.
// NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY,
// EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.
// If software is modified to produce derivative works, such modified software should
// be clearly marked, so as not to confuse it with the version available from LANL.
// Additionally, this library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License v 2.1 as published by the
// Free Software Foundation. Accordingly, this library is distributed in the hope that
// it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt for more details.
//--------------------------------------------------------------------------
// File: InputHandler.C
// Module: simx
// Author: Lukas Kroc, Sunil Thulasidasan
// Created: Feb 7 2005
//
// Description: Create and manage inputs
//
// @@
//
//--------------------------------------------------------------------------
#include "simx/InputHandler.h"
#include "simx/Entity.h"
#include "simx/logger.h"
#include "Common/Assert.h"
#include "Config/Configuration.h"
#include "boost/lexical_cast.hpp"
//#include <boost/make_shared.hpp>
#include <list>
#include <map>
using namespace std;
using namespace Config;
namespace simx {
/// explicit instantiation of templates to use
template class InputHandler<int>;
template class InputHandler<std::string>;
template<typename ObjectIdent>
void InputHandler<ObjectIdent>::loadProfile( const ProfileID profileId, boost::shared_ptr<Input> input )
{
#ifdef DEBUG
Logger::debug3() << "InputHandler: loading profile " << profileId << endl;
#endif
// obtain the appropriate profile set (contains all profileIds in that set)
const Config::Configuration::ConfigSet& cset = gConfig.GetConfigurationSet(fProfileSetName);
if (cset.size() == 0)
{
Logger::warn() << "InputHandler: no config set " << fProfileSetName << ", no profiles made"
<< " for profileId " << profileId << endl;
return;
}
// turn the set into a map ProfileID->profile subset
// TODO: this really is needed only once per run
map<std::string, Config::Configuration::ConfigMap*> profileMap;
for (Config::Configuration::ConfigSet::iterator it = cset.begin();
it != cset.end();
++it)
{
if( !profileMap.insert(*it).second )
{
Logger::warn() << "InputHandler: profile " << it->first << " occurs multiple times in set "
<< fProfileSetName << endl;
}
}
// make sure you follow through PARENT profile hiesrarchy (a tree structure)
// make a list of Profiles so that the very top-one in the hierarchy is first etc...
list<Config::Configuration::ConfigMap*> profileList;
string profileStr = boost::lexical_cast<string>(profileId);
while( true )
{
Config::Configuration::ConfigMap* profilePtr = profileMap[ profileStr ];
if( !profilePtr )
{
Logger::error() << "InputHandler: profile " << profileStr << " does not exist in set "
<< fProfileSetName << endl;
break;
}
// add the profile to the list
#ifdef DEBUG
Logger::debug3() << "InputHandler: adding " << profileStr << " to the profileList" << endl;
#endif
profileList.push_front( profilePtr );
// look for its parent
Config::Configuration::ConfigMap::const_iterator par_it = profilePtr->find("PARENT");
if( par_it == profilePtr->end() )
{
// end of profile hierarchy
break;
}
profileStr = par_it->second;
}
ProfileHolder profileHolder; // this object will have all name-value pairs from the
// whole profile hierarchy, descendants overwriting
// parent values
// now go through the list and initialize the profileSource input by
// merging all subsets, following the PARENT hierarchy from top to bottom
for(list<Config::Configuration::ConfigMap*>::iterator iter = profileList.begin();
iter != profileList.end();
++iter)
{
SMART_ASSERT( *iter );
profileHolder.add( (*iter)->begin(), (*iter)->end() );
}
// finally, read in the profile
SMART_ASSERT( input );
input->readProfile( profileHolder );
}
} // namespace
| lgpl-2.1 |
FedoraScientific/salome-gui | src/SalomeApp/pluginsdemo/smesh_plugins.py | 1230 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
# Copyright (C) 2010-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See http://www.salome-platform.org/ or email : [email protected]
#
# Author : Guillaume Boulant (EDF)
import salome_pluginsmanager
DEMO_IS_ACTIVATED = True
from minmax_plugin import *
# register the function in the plugin manager
if DEMO_IS_ACTIVATED:
salome_pluginsmanager.AddFunction('Get min or max value of control',
'Get min or max value of control',
minmax)
| lgpl-2.1 |
kitsilanosoftware/JavaScriptCore | tests/mozilla/ecma/Expressions/11.2.1-5.js | 4802 | /* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Mozilla Communicator client code, released March
* 31, 1998.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
*/
/**
File Name: 11.2.1-5.js
ECMA Section: 11.2.1 Property Accessors
Description:
Properties are accessed by name, using either the dot notation:
MemberExpression . Identifier
CallExpression . Identifier
or the bracket notation: MemberExpression [ Expression ]
CallExpression [ Expression ]
The dot notation is explained by the following syntactic conversion:
MemberExpression . Identifier
is identical in its behavior to
MemberExpression [ <identifier-string> ]
and similarly
CallExpression . Identifier
is identical in its behavior to
CallExpression [ <identifier-string> ]
where <identifier-string> is a string literal containing the same sequence
of characters as the Identifier.
The production MemberExpression : MemberExpression [ Expression ] is
evaluated as follows:
1. Evaluate MemberExpression.
2. Call GetValue(Result(1)).
3. Evaluate Expression.
4. Call GetValue(Result(3)).
5. Call ToObject(Result(2)).
6. Call ToString(Result(4)).
7. Return a value of type Reference whose base object is Result(5) and
whose property name is Result(6).
The production CallExpression : CallExpression [ Expression ] is evaluated
in exactly the same manner, except that the contained CallExpression is
evaluated in step 1.
Author: [email protected]
Date: 12 november 1997
*/
var SECTION = "11.2.1-5";
var VERSION = "ECMA_1";
startTest();
var TITLE = "Property Accessors";
writeHeaderToLog( SECTION + " "+TITLE );
var testcases = new Array();
// go through all Native Function objects, methods, and properties and get their typeof.
var PROPERTY = new Array();
var p = 0;
// try to access properties of primitive types
PROPERTY[p++] = new Property( new String("hi"), "hi", "hi", NaN );
PROPERTY[p++] = new Property( new Number(NaN), NaN, "NaN", NaN );
PROPERTY[p++] = new Property( new Number(3), 3, "3", 3 );
PROPERTY[p++] = new Property( new Boolean(true), true, "true", 1 );
PROPERTY[p++] = new Property( new Boolean(false), false, "false", 0 );
for ( var i = 0, RESULT; i < PROPERTY.length; i++ ) {
testcases[tc++] = new TestCase( SECTION,
PROPERTY[i].object + ".valueOf()",
PROPERTY[i].value,
eval( "PROPERTY[i].object.valueOf()" ) );
testcases[tc++] = new TestCase( SECTION,
PROPERTY[i].object + ".toString()",
PROPERTY[i].string,
eval( "PROPERTY[i].object.toString()" ) );
}
test();
function test() {
for ( tc=0; tc < testcases.length; tc++ ) {
testcases[tc].passed = writeTestCaseResult(
testcases[tc].expect,
testcases[tc].actual,
testcases[tc].description +" = "+
testcases[tc].actual );
testcases[tc].reason += ( testcases[tc].passed ) ? "" : "wrong value ";
}
stopTest();
return ( testcases );
}
function MyObject( value ) {
this.value = value;
this.stringValue = value +"";
this.numberValue = Number(value);
return this;
}
function Property( object, value, string, number ) {
this.object = object;
this.string = String(value);
this.number = Number(value);
this.value = value;
} | lgpl-2.1 |
miurahr/eb4j | eb4j-core/src/main/java/fuku/eb4j/util/HexUtil.java | 2464 | package fuku.eb4j.util;
import java.util.Locale;
/**
* HEXユーティリティクラス。
*
* @author Hisaya FUKUMOTO
*/
public class HexUtil {
/**
* コンストラクタ。
*
*/
private HexUtil() {
super();
}
/**
* 指定された値を16進数表現で返します。
*
* @param val 値
* @return 16進数表現の文字列
*/
public static String toHexString(long val) {
return toHexString(val, 6);
}
/**
* 指定された値を16進数表現で返します。
*
* @param val 値
* @param length 桁数
* @return 16進数表現の文字列
*/
public static String toHexString(long val, int length) {
return toHexString(Long.toHexString(val), length);
}
/**
* 指定された値を16進数表現で返します。
*
* @param val 値
* @return 16進数表現の文字列
*/
public static String toHexString(int val) {
return toHexString(val, 4);
}
/**
* 指定された値を16進数表現で返します。
*
* @param val 値
* @param length 桁数
* @return 16進数表現の文字列
*/
public static String toHexString(int val, int length) {
return toHexString(Integer.toHexString(val), length);
}
/**
* 指定された値を16進数表現で返します。
*
* @param val 値
* @return 16進数表現の文字列
*/
public static String toHexString(byte val) {
return toHexString(val, 2);
}
/**
* 指定された値を16進数表現で返します。
*
* @param val 値
* @param length 桁数
* @return 16進数表現の文字列
*/
public static String toHexString(byte val, int length) {
return toHexString(Integer.toHexString(val&0xff), length);
}
/**
* 指定された16進数文字列を大文字に変換し、指定桁数以下の場合は先頭に0を付加します。
*
* @param str 文字列
* @param length 桁数
* @return 変換後の文字列
*/
public static String toHexString(String str, int length) {
StringBuilder buf = new StringBuilder(str.toUpperCase(Locale.ENGLISH));
int len = length - str.length();
for (int i=0; i<len; i++) {
buf.insert(0, '0');
}
return buf.toString();
}
}
// end of HexUtil.java
| lgpl-2.1 |
nkreipke/nhibernate-core | src/NHibernate.Test/Async/Stateless/StatelessSessionFixture.cs | 6054 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by AsyncGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Threading;
using NHibernate.AdoNet;
using NHibernate.Criterion;
using NHibernate.Engine;
using NUnit.Framework;
namespace NHibernate.Test.Stateless
{
using System.Threading.Tasks;
[TestFixture]
public class StatelessSessionFixtureAsync : TestCase
{
protected override string MappingsAssembly
{
get { return "NHibernate.Test"; }
}
protected override IList Mappings
{
get { return new[] {"Stateless.Document.hbm.xml"}; }
}
protected override void OnTearDown()
{
using (ISession s = OpenSession())
{
s.Delete("from Document");
s.Delete("from Paper");
}
}
[Test]
public async Task CreateUpdateReadDeleteAsync()
{
Document doc;
DateTime? initVersion;
using (IStatelessSession ss = Sfi.OpenStatelessSession())
{
ITransaction tx;
using (tx = ss.BeginTransaction())
{
doc = new Document("blah blah blah", "Blahs");
await (ss.InsertAsync(doc));
Assert.IsNotNull(doc.LastModified);
initVersion = doc.LastModified;
Assert.IsTrue(initVersion.HasValue);
await (tx.CommitAsync());
}
Thread.Sleep(1100); // Ensure version increment (some dialects lack fractional seconds).
using (tx = ss.BeginTransaction())
{
doc.Text = "blah blah blah .... blah";
await (ss.UpdateAsync(doc));
Assert.IsTrue(doc.LastModified.HasValue);
Assert.AreNotEqual(initVersion, doc.LastModified);
await (tx.CommitAsync());
}
using (tx = ss.BeginTransaction())
{
doc.Text = "blah blah blah .... blah blay";
await (ss.UpdateAsync(doc));
await (tx.CommitAsync());
}
var doc2 = await (ss.GetAsync<Document>("Blahs"));
Assert.AreEqual("Blahs", doc2.Name);
Assert.AreEqual(doc.Text, doc2.Text);
doc2 = (Document) await (ss.CreateQuery("from Document where text is not null").UniqueResultAsync());
Assert.AreEqual("Blahs", doc2.Name);
Assert.AreEqual(doc.Text, doc2.Text);
doc2 = (Document) await (ss.CreateSQLQuery("select * from Document").AddEntity(typeof (Document)).UniqueResultAsync());
Assert.AreEqual("Blahs", doc2.Name);
Assert.AreEqual(doc.Text, doc2.Text);
doc2 = await (ss.CreateCriteria<Document>().UniqueResultAsync<Document>());
Assert.AreEqual("Blahs", doc2.Name);
Assert.AreEqual(doc.Text, doc2.Text);
doc2 = (Document) await (ss.CreateCriteria(typeof (Document)).UniqueResultAsync());
Assert.AreEqual("Blahs", doc2.Name);
Assert.AreEqual(doc.Text, doc2.Text);
using (tx = ss.BeginTransaction())
{
await (ss.DeleteAsync(doc));
await (tx.CommitAsync());
}
}
}
[Test]
public async Task HqlBulkAsync()
{
IStatelessSession ss = Sfi.OpenStatelessSession();
ITransaction tx = ss.BeginTransaction();
var doc = new Document("blah blah blah", "Blahs");
await (ss.InsertAsync(doc));
var paper = new Paper {Color = "White"};
await (ss.InsertAsync(paper));
await (tx.CommitAsync());
tx = ss.BeginTransaction();
int count =
await (ss.CreateQuery("update Document set Name = :newName where Name = :oldName").SetString("newName", "Foos").SetString(
"oldName", "Blahs").ExecuteUpdateAsync());
Assert.AreEqual(1, count, "hql-delete on stateless session");
count = await (ss.CreateQuery("update Paper set Color = :newColor").SetString("newColor", "Goldenrod").ExecuteUpdateAsync());
Assert.AreEqual(1, count, "hql-delete on stateless session");
await (tx.CommitAsync());
tx = ss.BeginTransaction();
count = await (ss.CreateQuery("delete Document").ExecuteUpdateAsync());
Assert.AreEqual(1, count, "hql-delete on stateless session");
count = await (ss.CreateQuery("delete Paper").ExecuteUpdateAsync());
Assert.AreEqual(1, count, "hql-delete on stateless session");
await (tx.CommitAsync());
ss.Close();
}
[Test]
public async Task InitIdAsync()
{
Paper paper;
using (IStatelessSession ss = Sfi.OpenStatelessSession())
{
ITransaction tx;
using (tx = ss.BeginTransaction())
{
paper = new Paper {Color = "White"};
await (ss.InsertAsync(paper));
Assert.IsTrue(paper.Id != 0);
await (tx.CommitAsync());
}
using (tx = ss.BeginTransaction())
{
await (ss.DeleteAsync(await (ss.GetAsync<Paper>(paper.Id))));
await (tx.CommitAsync());
}
}
}
[Test]
public async Task RefreshAsync()
{
Paper paper;
using (IStatelessSession ss = Sfi.OpenStatelessSession())
{
using (ITransaction tx = ss.BeginTransaction())
{
paper = new Paper {Color = "whtie"};
await (ss.InsertAsync(paper));
await (tx.CommitAsync());
}
}
using (IStatelessSession ss = Sfi.OpenStatelessSession())
{
using (ITransaction tx = ss.BeginTransaction())
{
var p2 = await (ss.GetAsync<Paper>(paper.Id));
p2.Color = "White";
await (ss.UpdateAsync(p2));
await (tx.CommitAsync());
}
}
using (IStatelessSession ss = Sfi.OpenStatelessSession())
{
using (ITransaction tx = ss.BeginTransaction())
{
Assert.AreEqual("whtie", paper.Color);
await (ss.RefreshAsync(paper));
Assert.AreEqual("White", paper.Color);
await (ss.DeleteAsync(paper));
await (tx.CommitAsync());
}
}
}
[Test]
public void HavingDetachedCriteriaThenCanGetExecutableCriteriaFromStatelessSessionAsync()
{
var dc = DetachedCriteria.For<Paper>();
using (IStatelessSession ss = Sfi.OpenStatelessSession())
{
ICriteria criteria = null;
Assert.That(() => criteria = dc.GetExecutableCriteria(ss), Throws.Nothing);
Assert.That(() => criteria.ListAsync(), Throws.Nothing);
}
}
}
} | lgpl-2.1 |
gordonwatts/LINQtoROOT | LINQToTTree/LINQToTTreeLib/Statements/StatementLoopOverGood.cs | 6168 |
using LinqToTTreeInterfacesLib;
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQToTTreeLib.Statements
{
/// <summary>
/// Loop over a set of indicies only if they are marked "true" in the accompanying array.
/// </summary>
public class StatementLoopOverGood : StatementInlineBlockBase, IStatementLoop
{
private IValue _indiciesToCheck;
private IValue _indexIsGood;
private IDeclaredParameter _index;
/// <summary>
/// Simple loop over a set of indicies, passing on only those that satisfy the actual index.
/// </summary>
/// <param name="indiciesToCheck"></param>
/// <param name="indexIsGood"></param>
/// <param name="index"></param>
public StatementLoopOverGood(IValue indiciesToCheck, IValue indexIsGood, IDeclaredParameter index)
{
if (indiciesToCheck == null)
throw new ArgumentNullException("indiciesToCheck");
if (indexIsGood == null)
throw new ArgumentNullException("indexIsGood");
if (index == null)
throw new ArgumentNullException("index");
_indiciesToCheck = indiciesToCheck;
_indexIsGood = indexIsGood;
_index = index;
}
/// <summary>
/// Get back the index variables.
/// </summary>
public IEnumerable<IDeclaredParameter> LoopIndexVariable
{
get { return new IDeclaredParameter[] { _index }; }
}
/// <summary>
/// Since statements are protected by an if, we shouldn't let them float out of the block.
/// </summary>
public override bool AllowNormalBubbleUp { get { return false; } }
/// <summary>
/// Render the loop and if statement...
/// </summary>
/// <returns></returns>
public override System.Collections.Generic.IEnumerable<string> CodeItUp()
{
yield return string.Format("for (int index=0; index < {0}.size(); index++)", _indiciesToCheck.RawValue);
yield return "{";
yield return string.Format(" if ({0}[index])", _indexIsGood.RawValue);
yield return " {";
yield return string.Format(" int {0} = {1}[index];", _index.RawValue, _indiciesToCheck.RawValue);
foreach (var l in RenderInternalCode())
{
yield return " " + l;
}
yield return " }";
yield return "}";
}
/// <summary>
/// Return the index variables for this loop.
/// </summary>
public override IEnumerable<IDeclaredParameter> InternalResultVarialbes
{
get
{
return new IDeclaredParameter[] { _index };
}
}
/// <summary>
/// Return all declared variables in this guy
/// </summary>
public new IEnumerable<IDeclaredParameter> DeclaredVariables
{
get
{
return base.DeclaredVariables
.Concat(new IDeclaredParameter[] { _index });
}
}
/// <summary>
/// Return a list of all dependent variables. Will not include the counter
/// </summary>
/// <remarks>We calculate this on the fly as we have no good way to know when we've been modified</remarks>
public override IEnumerable<string> DependentVariables
{
get
{
var dependents = base.DependentVariables
.Concat(_indiciesToCheck.Dependants.Select(p => p.RawValue))
;
return new HashSet<string>(dependents);
}
}
/// <summary>
/// Try to combine two of these guys
/// </summary>
/// <param name="statement"></param>
/// <returns></returns>
public override bool TryCombineStatement(IStatement statement, ICodeOptimizationService opt)
{
if (statement == null)
throw new ArgumentNullException();
if (this == statement)
throw new ArgumentException("Can't comebine with self!");
var otherLoop = statement as StatementLoopOverGood;
if (otherLoop == null)
return false;
// Are they the same? _index is independent and we can alter it.
if (otherLoop._indexIsGood.RawValue == _indexIsGood.RawValue
&& otherLoop._indiciesToCheck.RawValue == _indiciesToCheck.RawValue)
{
if (!(opt.TryRenameVarialbeOneLevelUp(otherLoop._index.RawValue, _index)))
return false;
Combine(otherLoop, opt);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Rename the variables here.
/// </summary>
/// <param name="origName"></param>
/// <param name="newName"></param>
public override void RenameVariable(string origName, string newName)
{
_index.RenameRawValue(origName, newName);
_indexIsGood.RenameRawValue(origName, newName);
_indiciesToCheck.RenameRawValue(origName, newName);
RenameBlockVariables(origName, newName);
}
/// <summary>
/// Check to see if we can get past the various statements.
/// </summary>
/// <param name="followStatement"></param>
/// <returns></returns>
public override bool CommutesWithGatingExpressions(ICMStatementInfo followStatement)
{
var varsAffected = followStatement.ResultVariables.Intersect(_indexIsGood.Dependants.Concat(_indiciesToCheck.Dependants).Select(p => p.RawValue));
return !varsAffected.Any();
}
}
}
| lgpl-2.1 |
pentaho/pentaho-commons-xul | core/src/main/java/org/pentaho/ui/xul/containers/XulColumn.java | 1009 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.ui.xul.containers;
import org.pentaho.ui.xul.XulContainer;
/**
* User: nbaker Date: Apr 14, 2009
*/
public interface XulColumn extends XulContainer {
}
| lgpl-2.1 |
trainboy2019/1.7modrecove4r2 | src/main/java/com/camp/block/OverworldAmethyst.java | 1917 | package com.camp.block;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.camp.creativetabs.CreativeTabsManager;
import com.camp.item.ItemManager;
//import com.bedrockminer.tutorial.Main;
import com.camp.lib.StringLibrary;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class OverworldAmethyst extends Block {
private Item drop;
private int meta;
private int least_quantity;
private int most_quantity;
protected OverworldAmethyst(String unlocalizedName, Material mat, Item drop, int meta, int least_quantity, int most_quantity) {
super(mat);
this.drop = drop;
this.meta = meta;
this.least_quantity = 1;
this.most_quantity = 2;
this.setLightLevel(0.0F);
this.setBlockName(unlocalizedName);
this.setBlockTextureName(StringLibrary.MODID + ":" + "overworld_" + "amethyst");
this.setCreativeTab(CreativeTabsManager.tabBlock);
}
protected OverworldAmethyst(String unlocalizedName, Material mat, Item drop, int least_quantity, int most_quantity) {
this(unlocalizedName, mat, drop, 0, least_quantity, most_quantity);
}
protected OverworldAmethyst(String unlocalizedName, Material mat, Item drop) {
this(unlocalizedName, mat, drop, 1, 1);
}
@Override
public Item getItemDropped(int meta, Random random, int fortune) {
return ItemManager.amethystGem;
}
@Override
public int damageDropped(int meta) {
return meta;
}
@Override
public int quantityDropped(int meta, int fortune, Random random) {
if (this.least_quantity >= this.most_quantity)
return this.least_quantity;
return this.least_quantity + random.nextInt(this.most_quantity - this.least_quantity + fortune + 1);
}
} | lgpl-2.1 |
clescot/jguard | jguard-jee/src/main/java/net/sf/jguard/jee/listeners/SessionAttributeListener.java | 4042 | /*
jGuard is a security framework based on top of jaas (java authentication and authorization security).
it is written for web applications, to resolve simply, access control problems.
http://sourceforge.net/projects/jguard/
Copyright (C) 2004 Charles Lescot
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
jGuard project home page:
http://sourceforge.net/projects/jguard/
*/
package net.sf.jguard.jee.listeners;
import net.sf.jguard.core.authentication.LoginContextWrapperImpl;
import net.sf.jguard.core.authentication.StatefulAuthenticationServicePoint;
import net.sf.jguard.core.authentication.credentials.JGuardCredential;
import net.sf.jguard.core.authentication.exception.AuthenticationException;
import net.sf.jguard.core.authentication.manager.AuthenticationManager;
import net.sf.jguard.core.authentication.manager.JGuardAuthenticationManagerMarkups;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
/**
* Audit JGuard Subject of http sessions, generating log for Subject changes
*
* @author Frederico Borelli
* @see net.sf.jguard.core.audit.AuditManager
*/
public class SessionAttributeListener implements HttpSessionAttributeListener {
static public final Logger logger = LoggerFactory.getLogger(SessionAttributeListener.class);
public void attributeAdded(HttpSessionBindingEvent event) {
if (event.getName().equals(StatefulAuthenticationServicePoint.LOGIN_CONTEXT_WRAPPER)) {
JGuardCredential identity;
try {
identity = getIdentityCredential(event);
logger.info("subject with identityCredential=" + identity + " is created ");
} catch (AuthenticationException ex) {
logger.warn(ex.getMessage());
}
}
}
private JGuardCredential getIdentityCredential(final HttpSessionBindingEvent event) throws AuthenticationException {
Subject subject = ((LoginContextWrapperImpl) event.getValue()).getSubject();
AuthenticationManager authenticationManager = (AuthenticationManager) event.getSession().getServletContext().getAttribute(JGuardAuthenticationManagerMarkups.AUTHENTICATION_MANAGER.getLabel());
return authenticationManager.getIdentityCredential(subject);
}
public void attributeRemoved(HttpSessionBindingEvent event) {
if (event.getName().equals(StatefulAuthenticationServicePoint.LOGIN_CONTEXT_WRAPPER)) {
JGuardCredential identity;
try {
identity = getIdentityCredential(event);
logger.info("subject with identityCredential=" + identity + " is removed ");
} catch (AuthenticationException ex) {
logger.warn(ex.getMessage());
}
}
}
public void attributeReplaced(HttpSessionBindingEvent event) {
if (event.getName().equals(StatefulAuthenticationServicePoint.LOGIN_CONTEXT_WRAPPER)) {
JGuardCredential identity;
try {
identity = getIdentityCredential(event);
logger.info("subject with identityCredential=" + identity + " is replaced ");
} catch (AuthenticationException ex) {
logger.warn(ex.getMessage());
}
}
}
}
| lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsj/itemj132.java | 159 | package fr.toss.FF7itemsj;
public class itemj132 extends FF7itemsjbase {
public itemj132(int id) {
super(id);
setUnlocalizedName("itemj132");
}
}
| lgpl-2.1 |
lynxis/libavg | src/video/VideoInfo.cpp | 3039 | //
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "VideoInfo.h"
#include "../base/Exception.h"
namespace avg {
using namespace std;
VideoInfo::VideoInfo()
{
}
VideoInfo::VideoInfo(string sContainerFormat, float duration, int bitrate, bool bHasVideo,
bool bHasAudio)
: m_sContainerFormat(sContainerFormat),
m_Duration(duration),
m_Bitrate(bitrate),
m_bHasVideo(bHasVideo),
m_bHasAudio(bHasAudio)
{
}
void VideoInfo::setVideoData(const IntPoint& size, const string& sPixelFormat,
int numFrames, float streamFPS, const string& sVCodec,
bool bUsesVDPAU, float duration)
{
AVG_ASSERT(m_bHasVideo);
m_Size = size;
m_sPixelFormat = sPixelFormat;
m_NumFrames = numFrames;
m_StreamFPS = streamFPS;
m_sVCodec = sVCodec;
m_bUsesVDPAU = bUsesVDPAU;
m_VideoDuration = duration;
}
void VideoInfo::setAudioData(const string& sACodec, int sampleRate, int numAudioChannels,
float duration)
{
AVG_ASSERT(m_bHasAudio);
m_sACodec = sACodec;
m_SampleRate = sampleRate;
m_NumAudioChannels = numAudioChannels;
m_AudioDuration = duration;
}
float getStreamFPS(AVStream* pStream)
{
float fps;
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 42, 0)
if (pStream->avg_frame_rate.den != 0) {
fps = float(av_q2d(pStream->avg_frame_rate));
} else {
#endif
if (pStream->r_frame_rate.den != 0) {
fps = float(av_q2d(pStream->r_frame_rate));
} else {
float duration = float(pStream->duration)*float(av_q2d(pStream->time_base));
fps = pStream->nb_frames/duration;
}
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 42, 0)
}
#endif
AVG_ASSERT(fps < 10000);
/*
cerr << "getStreamFPS: fps= " << fps << endl;
cerr << " r_frame_rate num: " << m_pVStream->r_frame_rate.num << ", den: " << m_pVStream->r_frame_rate.den << endl;
cerr << " avg_frame_rate: num: " << m_pVStream->avg_frame_rate.num << ", den: " << m_pVStream->avg_frame_rate.den << endl;
cerr << " numFrames= " << getNumFrames() << ", duration= "
<< getDuration(SS_VIDEO) << endl;
*/
return fps;
}
}
| lgpl-2.1 |
migumar2/libCSD | libcds/src/static/sequence/wt_coder_binary.cpp | 2542 | /* wt_coder_binary.cpp
* Copyright (C) 2008, Francisco Claude, all rights reserved.
*
* wt_coder_binary definition
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <wt_coder_binary.h>
namespace cds_static
{
wt_coder_binary::wt_coder_binary(const Array & a, Mapper *am) {
//am->use();
uint maxv = 0;
for(size_t i=0;i<a.getLength();i++)
maxv = max(maxv,a[i]);
h = bits(maxv);
//am->unuse();
}
wt_coder_binary::wt_coder_binary(uint * seq, size_t n, Mapper * am) {
uint max_v = 0;
for(uint i=0;i<n;i++)
max_v = max(am->map(seq[i]),max_v);
h=bits(max_v);
}
wt_coder_binary::wt_coder_binary(uchar * seq, size_t n, Mapper * am) {
uint max_v = 0;
for(uint i=0;i<n;i++)
max_v = max(am->map((uint)seq[i]),max_v);
h=bits(max_v);
}
wt_coder_binary::wt_coder_binary() {}
wt_coder_binary::~wt_coder_binary() {}
bool wt_coder_binary::is_set(uint symbol, uint l) const
{
if((1<<(h-l-1))&symbol) return true;
return false;
}
bool wt_coder_binary::done(uint symbol, uint l) const
{
if(l==h) return true;
return false;
}
size_t wt_coder_binary::getSize() const
{
return sizeof(wt_coder_binary);
}
void wt_coder_binary::save(ofstream & fp) const
{
uint wr = WT_CODER_BINARY_HDR;
saveValue(fp,wr);
saveValue(fp,h);
}
wt_coder_binary * wt_coder_binary::load(ifstream & fp) {
uint rd = loadValue<uint>(fp);
if(rd!=WT_CODER_BINARY_HDR) return NULL;
wt_coder_binary * ret = new wt_coder_binary();
ret->h = loadValue<uint>(fp);
return ret;
}
};
| lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsk/itemk233.java | 159 | package fr.toss.FF7itemsk;
public class itemk233 extends FF7itemskbase {
public itemk233(int id) {
super(id);
setUnlocalizedName("itemk233");
}
}
| lgpl-2.1 |
dannysu/ocvolume-web | news.php | 2212 | <html>
<link rel="stylesheet" href="contentpage.css" type="text/css">
<body>
<table>
<tr>
<td class="news"><b>
February 15, 2004 - Changed from LGPL to BSD license and various updates.
</b></td>
</tr>
<tr>
<td>
This is the first update in a while. OCV license changed from LGPL to BSD license, which gives much more freedom. The links page had several dead links, and they are either fixed or removed.<br>
<br>
I (Danny) am starting to work on improvements for original OCV code, but this time coding it in C. There may be a Java API once and if I do finish. My aim is to have a working Hidden Markov Model module for training and try to make the recognizer less speaker dependent.
</td>
</tr>
<tr><td><br> </td></tr>
<tr>
<td class="news"><b>
June 28, 2002 - First release of complete package
</b></td>
</tr>
<tr>
<td>
We release the complete package to the public. Although this initial package contains only an Isolated Word Recognizer, it will become more sophisticated as we add more capability to the engine.
</td>
</tr>
<tr><td><br> </td></tr>
<tr>
<td class="news"><b>
May 23, 2002 - Completion of Vector Quantization component
</b></td>
</tr>
<tr>
<td>
We finished programming the Feature Extraction component and use it to extract Mel-Frequency Cepstral Coefficients from speech signal.
</td>
</tr>
<tr><td><br> </td></tr>
<tr>
<td class="news"><b>
May 16, 2002 - Completion of Feature Extraction component
</b></td>
</tr>
<tr>
<td>
We finished programming the Feature Extraction component and use it to extract Mel-Frequency Cepstral Coefficients from speech signal.
</td>
</tr>
<tr><td><br> </td></tr>
<tr>
<td class="news"><b>
May 5, 2002 - Completion of Hidden Markov Models component
</b></td>
</tr>
<tr>
<td>
We finished programming the Discrete Hidden Markov Models for our speech recognition engine.
<br><br>
EDIT: It was found that our HMM module can't be used for recognition. We need better understanding of HMM.
</td>
</tr>
<tr><td><br> </td></tr>
<tr>
<td class="news"><b>
March 28, 2002 - Project started
</b></td>
</tr>
<tr>
<td>
We started doing preliminary research on speech recognition.
</td>
</tr>
<tr><td><br> </td></tr>
</table>
</body></html>
| lgpl-2.1 |
cacheonix/cacheonix-core | src/org/cacheonix/impl/util/SingletonSet.java | 1802 | /*
* Cacheonix Systems licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm
*
* 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.cacheonix.impl.util;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
public final class SingletonSet<E> extends AbstractSet<E> implements Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 3193687207550431679L;
private final E element;
public SingletonSet(final E o) {
element = o;
}
public Iterator<E> iterator() {
return new Iterator<E>() {
private boolean hasNext = true;
public boolean hasNext() {
return hasNext;
}
public E next() {
if (hasNext) {
hasNext = false;
return element;
}
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public int size() {
return 1;
}
public E getElement() {
return element;
}
public boolean contains(final Object o) {
return !(o == null || element == null) && element.equals(o);
}
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | libraries/libcss/src/main/java/org/pentaho/reporting/libraries/css/selectors/conditions/IdCSSCondition.java | 2433 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.libraries.css.selectors.conditions;
import org.w3c.css.sac.AttributeCondition;
/**
* Creation-Date: 24.11.2005, 19:54:48
*
* @author Thomas Morgner
*/
public class IdCSSCondition implements AttributeCondition, CSSCondition {
private String value;
public IdCSSCondition( final String value ) {
this.value = value;
}
/**
* An integer indicating the type of <code>Condition</code>.
*/
public short getConditionType() {
return SAC_ID_CONDITION;
}
/**
* Returns the <a href="http://www.w3.org/TR/REC-xml-names/#dt-NSName">namespace URI</a> of this attribute condition.
* <p><code>NULL</code> if : <ul> <li>this attribute condition can match any namespace. <li>this attribute is an id
* attribute. </ul>
*/
public String getNamespaceURI() {
return null;
}
/**
* Returns <code>true</code> if the attribute must have an explicit value in the original document, <code>false</code>
* otherwise.
*/
public final boolean getSpecified() {
return false;
}
public String getValue() {
return value;
}
/**
* Returns the <a href="http://www.w3.org/TR/REC-xml-names/#NT-LocalPart">local part</a> of the <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">qualified name</a> of this attribute. <p><code>NULL</code>
* if : <ul> <li><p>this attribute condition can match any attribute. <li><p>this attribute is a class attribute.
* <li><p>this attribute is an id attribute. <li><p>this attribute is a pseudo-class attribute. </ul>
*/
public String getLocalName() {
return null;
}
}
| lgpl-2.1 |
jbossws/jbossws-cxf | modules/testsuite/cxf-tests/src/test/java/org/jboss/test/ws/jaxws/cxf/jms/HelloWorldImpl.java | 1548 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, 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.test.ws.jaxws.cxf.jms;
import javax.jws.WebService;
@WebService
(
portName = "HelloWorldImplPort",
serviceName = "HelloWorldServiceLocal",
wsdlLocation = "META-INF/wsdl/HelloWorldService.wsdl",
endpointInterface = "org.jboss.test.ws.jaxws.cxf.jms.HelloWorld",
targetNamespace = "http://org.jboss.ws/jaxws/cxf/jms"
)
public class HelloWorldImpl implements HelloWorld
{
public String echo(String input)
{
System.out.println("input: " + input);
return input;
}
}
| lgpl-2.1 |
FernCreek/tinymce | modules/alloy/src/test/ts/browser/ui/slotcontainer/SlotContainerTest.ts | 7232 | import { ApproxStructure, Assertions, Chain, Step } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { Result } from '@ephox/katamari';
import * as GuiFactory from 'ephox/alloy/api/component/GuiFactory';
import { Button } from 'ephox/alloy/api/ui/Button';
import { Input } from 'ephox/alloy/api/ui/Input';
import { SlotContainer } from 'ephox/alloy/api/ui/SlotContainer';
import * as GuiSetup from 'ephox/alloy/api/testhelpers/GuiSetup';
UnitTest.asynctest('SlotContainerTest', (success, failure) => {
GuiSetup.setup((store, doc, body) => {
return GuiFactory.build(
SlotContainer.sketch((parts) => ({
dom: {
tag: 'div',
classes: [ 'test-slot-container' ]
},
components: [
parts.slot('inputA', Input.sketch({ inputClasses: [ 'slot-input' ] })),
{
dom: {
tag: 'p',
classes: [ 'something-else' ],
innerHtml: 'Hello'
}
},
{
dom: {
tag: 'div',
classes: [ 'slot-wrapper' ]
},
components: [
parts.slot('buttonB', Button.sketch({
dom: {
tag: 'button',
classes: [ 'slot-button' ],
innerHtml: 'Patchy button'
},
action: store.adder('slot-button')
}))
]
}
]
}))
);
}, (doc, body, gui, component, store) => {
const cGetSlot = (slot: string) => Chain.binder(() => {
return SlotContainer.getSlot(component, slot).fold(
() => Result.error('Could not find slot: ' + slot),
Result.value
);
});
const sAssertSlotStructure = (label: string, slot: string, expectedStructure) => Chain.asStep({ }, [
cGetSlot(slot),
Chain.op((c) => {
Assertions.assertStructure(
label,
ApproxStructure.build(expectedStructure),
c.element()
);
})
]);
const sAssertButtonShowing = (label) => sAssertSlotStructure(label, 'buttonB', (s, str, arr) => {
return s.element('button', {
attrs: {
'aria-hidden': str.none()
},
styles: {
display: str.none()
}
});
});
const sAssertButtonHidden = (label) => sAssertSlotStructure(label, 'buttonB', (s, str, arr) => {
return s.element('button', {
attrs: {
'aria-hidden': str.is('true')
},
styles: {
display: str.is('none')
}
});
});
const sAssertInputShowing = (label) => sAssertSlotStructure(label, 'inputA', (s, str, arr) => {
return s.element('input', {
attrs: {
'aria-hidden': str.none()
},
styles: {
display: str.none()
}
});
});
const sAssertInputHidden = (label) => sAssertSlotStructure(label, 'inputA', (s, str, arr) => {
return s.element('input', {
attrs: {
'aria-hidden': str.is('true')
},
styles: {
display: str.is('none')
}
});
});
const cSlotShowing = (slot: string) => Chain.mapper(() => {
return SlotContainer.isShowing(component, slot);
});
const sAssertSlotShowing = (slot: string, expectedShowing: boolean) => (label: string) => Chain.asStep({}, [
cSlotShowing(slot),
Assertions.cAssertEq('SlotContainer.isShowing(_,"' + slot + '") !== ' + expectedShowing + ' - ' + label, expectedShowing)
]);
const sAssertButtonSlotShowing = sAssertSlotShowing('buttonB', true);
const sAssertButtonSlotHidden = sAssertSlotShowing('buttonB', false);
const sAssertInputSlotShowing = sAssertSlotShowing('inputA', true);
const sAssertInputSlotHidden = sAssertSlotShowing('inputA', false);
const cGetSlotNames = () => Chain.mapper(() => {
return SlotContainer.getSlotNames(component);
});
const sAssertGetSlotNames = (label: string, expectedSlots: string[]) => Chain.asStep({}, [
cGetSlotNames(),
Assertions.cAssertEq(label, expectedSlots)
]);
const sShowSlot = (slot: string) => Step.sync(() => {
SlotContainer.showSlot(component, slot);
});
const sHideSlot = (slot: string) => Step.sync(() => {
SlotContainer.hideSlot(component, slot);
});
const sHideAllSlots = () => Step.sync(() => {
SlotContainer.hideAllSlots(component);
});
return [
Assertions.sAssertStructure(
'Checking initial structure',
ApproxStructure.build((s, str, arr) => {
return s.element('div', {
classes: [ arr.has('test-slot-container') ],
children: [
s.element('input', { classes: [ arr.has('slot-input') ] }),
s.element('p', { classes: [ arr.has('something-else') ] }),
s.element('div', {
classes: [ arr.has('slot-wrapper') ],
children: [
s.element('button', {
classes: [ arr.has('slot-button') ]
})
]
})
]
});
}),
component.element()
),
sAssertButtonShowing('button: Before any APIs are called'),
sAssertInputShowing('input: Before any APIs are called'),
sAssertInputSlotShowing('before any APIs are called'),
sAssertButtonSlotShowing('before any APIs are called'),
sHideSlot('buttonB'),
sAssertButtonHidden('button: After SlotContainer.hideSlot(_, button)'),
sAssertButtonSlotHidden('After SlotContainer.hideSlot(_, button)'),
sAssertInputShowing('input: After SlotContainer.hideSlot(_, button)'),
sAssertInputSlotShowing('After SlotContainer.hideSlot(_, button)'),
sShowSlot('buttonB'),
sAssertButtonShowing('button: After SlotContainer.showSlot(_, button)'),
sAssertButtonSlotShowing('After SlotContainer.showSlot(_, button)'),
sAssertInputShowing('input: After SlotContainer.showSlot(_, button)'),
sAssertInputSlotShowing('After SlotContainer.showSlot(_, button)'),
sHideSlot('inputA'),
sAssertButtonShowing('button: After SlotContainer.hideSlot(_, input)'),
sAssertButtonSlotShowing('After SlotContainer.hideSlot(_, input)'),
sAssertInputHidden('input: After SlotContainer.hideSlot(_, input)'),
sAssertInputSlotHidden('After SlotContainer.hideSlot(_, input)'),
sShowSlot('inputA'),
sAssertButtonShowing('button: After SlotContainer.showSlot(_, input)'),
sAssertInputShowing('input: After SlotContainer.showSlot(_, input)'),
sAssertInputSlotShowing('After SlotContainer.showSlot(_, input)'),
sAssertButtonSlotShowing('After SlotContainer.showSlot(_, input)'),
sHideAllSlots(),
sAssertButtonHidden('button: After SlotContainer.hideAllSlots(_)'),
sAssertInputHidden('input: After SlotContainer.hideAllSlots(_)'),
sAssertInputSlotHidden('After SlotContainer.hideAllSlots(_)'),
sAssertButtonSlotHidden('After SlotContainer.hideAllSlots(_)'),
sAssertGetSlotNames('checking the list slots', ['inputA', 'buttonB']),
];
}, () => { success(); }, failure);
});
| lgpl-2.1 |
AbandonedCart/PCSX2Android | pcsx2/System/SysThreadBase.cpp | 9492 | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 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 PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "System.h"
#include "SysThreads.h"
// --------------------------------------------------------------------------------------
// SysThreadBase *External Thread* Implementations
// (Called form outside the context of this thread)
// --------------------------------------------------------------------------------------
SysThreadBase::SysThreadBase() :
m_ExecMode( ExecMode_NoThreadYet )
, m_ExecModeMutex()
{
}
SysThreadBase::~SysThreadBase() throw()
{
}
void SysThreadBase::Start()
{
_parent::Start();
Sleep( 1 );
pxAssertDev( (m_ExecMode == ExecMode_Closing) || (m_ExecMode == ExecMode_Closed),
"Unexpected thread status during SysThread startup."
);
m_sem_event.Post();
}
void SysThreadBase::OnStart()
{
if( !pxAssertDev( m_ExecMode == ExecMode_NoThreadYet, "SysSustainableThread:Start(): Invalid execution mode" ) ) return;
m_sem_Resume.Reset();
m_sem_ChangingExecMode.Reset();
FrankenMutex( m_ExecModeMutex );
FrankenMutex( m_RunningLock );
_parent::OnStart();
}
// Suspends emulation and closes the emulation state (including plugins) at the next PS2 vsync,
// and returns control to the calling thread; or does nothing if the core is already suspended.
//
// Parameters:
// isNonblocking - if set to true then the function will not block for emulation suspension.
// Defaults to false if parameter is not specified. Performing non-blocking suspension
// is mostly useful for starting certain non-Emu related gui activities (improves gui
// responsiveness).
//
// Returns:
// The previous suspension state; true if the thread was running or false if it was
// suspended.
//
// Exceptions:
// CancelEvent - thrown if the thread is already in a Paused or Closing state. Because
// actions that pause emulation typically rely on plugins remaining loaded/active,
// Suspension must cancel itself forcefully or risk crashing whatever other action is
// in progress.
//
void SysThreadBase::Suspend( bool isBlocking )
{
if (!pxAssertDev(!IsSelf(),"Suspend/Resume are not allowed from this thread.")) return;
if (!IsRunning()) return;
// shortcut ExecMode check to avoid deadlocking on redundant calls to Suspend issued
// from Resume or OnResumeReady code.
if( m_ExecMode == ExecMode_Closed ) return;
{
ScopedLock locker( m_ExecModeMutex );
switch( m_ExecMode )
{
// Check again -- status could have changed since above.
case ExecMode_Closed: return;
case ExecMode_Pausing:
case ExecMode_Paused:
if( !isBlocking )
throw Exception::CancelEvent( L"Cannot suspend in non-blocking fashion: Another thread is pausing the VM state." );
m_ExecMode = ExecMode_Closing;
m_sem_Resume.Post();
m_sem_ChangingExecMode.Wait();
break;
case ExecMode_Opened:
m_ExecMode = ExecMode_Closing;
break;
}
pxAssertDev( m_ExecMode == ExecMode_Closing, "ExecMode should be nothing other than Closing..." );
m_sem_event.Post();
}
if( isBlocking )
m_RunningLock.Wait();
}
// Returns:
// The previous suspension state; true if the thread was running or false if it was
// closed, not running, or paused.
//
void SysThreadBase::Pause()
{
if( IsSelf() || !IsRunning() ) return;
// shortcut ExecMode check to avoid deadlocking on redundant calls to Suspend issued
// from Resume or OnResumeReady code.
if( (m_ExecMode == ExecMode_Closed) || (m_ExecMode == ExecMode_Paused) ) return;
{
ScopedLock locker( m_ExecModeMutex );
// Check again -- status could have changed since above.
if( (m_ExecMode == ExecMode_Closed) || (m_ExecMode == ExecMode_Paused) ) return;
if( m_ExecMode == ExecMode_Opened )
m_ExecMode = ExecMode_Pausing;
pxAssertDev( m_ExecMode == ExecMode_Pausing, "ExecMode should be nothing other than Pausing..." );
m_sem_event.Post();
}
m_RunningLock.Wait();
}
// Resumes the core execution state, or does nothing is the core is already running. If
// settings were changed, resets will be performed as needed and emulation state resumed from
// memory savestates.
//
// Note that this is considered a non-blocking action. Most times the state is safely resumed
// on return, but in the case of re-entrant or nested message handling the function may return
// before the thread has resumed. If you need explicit behavior tied to the completion of the
// Resume, you'll need to bind callbacks to either OnResumeReady or OnResumeInThread.
//
// Exceptions:
// PluginInitError - thrown if a plugin fails init (init is performed on the current thread
// on the first time the thread is resumed from it's initial idle state)
// ThreadCreationError - Insufficient system resources to create thread.
//
void SysThreadBase::Resume()
{
if( IsSelf() ) return;
if( m_ExecMode == ExecMode_Opened ) return;
ScopedLock locker( m_ExecModeMutex );
// Implementation Note:
// The entire state coming out of a Wait is indeterminate because of user input
// and pending messages being handled. So after each call we do some seemingly redundant
// sanity checks against m_ExecMode/m_Running status, and if something doesn't feel
// right, we should abort; the user may have canceled the action before it even finished.
switch( m_ExecMode )
{
case ExecMode_Opened: return;
case ExecMode_NoThreadYet:
{
Start();
if( !m_running || (m_ExecMode == ExecMode_NoThreadYet) )
throw Exception::ThreadCreationError(this);
if( m_ExecMode == ExecMode_Opened ) return;
}
// fall through...
case ExecMode_Closing:
case ExecMode_Pausing:
// we need to make sure and wait for the emuThread to enter a fully suspended
// state before continuing...
m_RunningLock.Wait();
if( !m_running ) return;
if( (m_ExecMode != ExecMode_Closed) && (m_ExecMode != ExecMode_Paused) ) return;
if( !GetCorePlugins().AreLoaded() ) return;
break;
}
pxAssertDev( (m_ExecMode == ExecMode_Closed) || (m_ExecMode == ExecMode_Paused),
"SysThreadBase is not in a closed/paused state? wtf!" );
OnResumeReady();
m_ExecMode = ExecMode_Opened;
m_sem_Resume.Post();
}
// --------------------------------------------------------------------------------------
// SysThreadBase *Worker* Implementations
// (Called from the context of this thread only)
// --------------------------------------------------------------------------------------
void SysThreadBase::OnStartInThread()
{
m_RunningLock.Acquire();
_parent::OnStartInThread();
m_ExecMode = ExecMode_Closing;
}
void SysThreadBase::OnCleanupInThread()
{
m_ExecMode = ExecMode_NoThreadYet;
_parent::OnCleanupInThread();
m_RunningLock.Release();
}
void SysThreadBase::OnSuspendInThread() {}
void SysThreadBase::OnResumeInThread( bool isSuspended ) {}
// Tests for Pause and Suspend/Close requests. If the thread is trying to be paused or
// closed, it will enter a wait/holding pattern here in this method until the managing
// thread releases it. Use the return value to detect if changes to the thread's state
// may have been changed (based on the rule that other threads are not allowed to modify
// this thread's state without pausing or closing it first, to prevent race conditions).
//
// Return value:
// TRUE if the thread was paused or closed; FALSE if the thread
// continued execution unimpeded.
bool SysThreadBase::StateCheckInThread()
{
switch( m_ExecMode )
{
#ifdef PCSX2_DEVBUILD // optimize out handlers for these cases in release builds.
case ExecMode_NoThreadYet:
// threads should never have this state set while the thread is in any way
// active or alive. (for obvious reasons!!)
pxFailDev( "Invalid execution state detected." );
return false;
#endif
case ExecMode_Opened:
// Other cases don't need TestCancel() because its built into the various
// threading wait/signal actions.
TestCancel();
return false;
// -------------------------------------
case ExecMode_Pausing:
{
OnPauseInThread();
m_ExecMode = ExecMode_Paused;
m_RunningLock.Release();
}
// fallthrough...
case ExecMode_Paused:
while( m_ExecMode == ExecMode_Paused )
m_sem_Resume.WaitWithoutYield();
m_RunningLock.Acquire();
if( m_ExecMode != ExecMode_Closing )
{
OnResumeInThread( false );
break;
}
m_sem_ChangingExecMode.Post();
// fallthrough if we're switching to closing state...
// -------------------------------------
case ExecMode_Closing:
{
OnSuspendInThread();
m_ExecMode = ExecMode_Closed;
m_RunningLock.Release();
}
// fallthrough...
case ExecMode_Closed:
while( m_ExecMode == ExecMode_Closed )
m_sem_Resume.WaitWithoutYield();
m_RunningLock.Acquire();
OnResumeInThread( true );
break;
jNO_DEFAULT;
}
return true;
}
| lgpl-3.0 |
daleasberry/ojil-android | src/main/java/com/github/ojil/android/ImageFactoryAndroidSpi.java | 816 | package com.github.ojil.android;
import android.graphics.Bitmap;
import com.github.ojil.core.Image;
import com.github.ojil.core.ImageFactory;
import com.github.ojil.core.ImageType;
public class ImageFactoryAndroidSpi implements ImageFactory<Bitmap> {
@Override
public Image<Integer, Bitmap> createImage(int width, int height, ImageType type) {
Image<Integer, Bitmap> newImage = null;
switch (type) {
case INT_RGB:
newImage = new RgbImageAndroid(width, height);
break;
default:
throw new RuntimeException("Not yet implemented");
}
return newImage;
}
@Override
public Image<Integer, Bitmap> createImage(Bitmap platformImage) {
return new RgbImageAndroid(platformImage);
}
} | lgpl-3.0 |
noahvans/mariadb-connector-net | Source/MariaDB.Data/MySqlPool.cs | 10435 | // This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
// for more details.
//
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using MariaDB.Data.Common;
namespace MariaDB.Data.MySqlClient
{
/// <summary>
/// Summary description for MySqlPool.
/// </summary>
internal sealed class MySqlPool
{
private List<Driver> inUsePool;
private Queue<Driver> idlePool;
private MySqlConnectionStringBuilder settings;
private uint minSize;
private uint maxSize;
private bool beingCleared;
private int available;
private AutoResetEvent autoEvent;
private void EnqueueIdle(Driver driver)
{
driver.IdleSince = DateTime.Now;
idlePool.Enqueue(driver);
}
public MySqlPool(MySqlConnectionStringBuilder settings)
{
minSize = settings.MinimumPoolSize;
maxSize = settings.MaximumPoolSize;
available = (int)maxSize;
autoEvent = new AutoResetEvent(false);
if (minSize > maxSize)
minSize = maxSize;
this.settings = settings;
inUsePool = new List<Driver>((int)maxSize);
idlePool = new Queue<Driver>((int)maxSize);
// prepopulate the idle pool to minSize
for (int i = 0; i < minSize; i++)
EnqueueIdle(CreateNewPooledConnection());
}
#region Properties
public MySqlConnectionStringBuilder Settings
{
get { return settings; }
set { settings = value; }
}
/// <summary>
/// It is assumed that this property will only be used from inside an active
/// lock.
/// </summary>
private bool HasIdleConnections
{
get { return idlePool.Count > 0; }
}
private int NumConnections
{
get { return idlePool.Count + inUsePool.Count; }
}
/// <summary>
/// Indicates whether this pool is being cleared.
/// </summary>
public bool BeingCleared
{
get { return beingCleared; }
}
internal Hashtable ServerProperties { get; set; }
#endregion Properties
/// <summary>
/// It is assumed that this method is only called from inside an active lock.
/// </summary>
private Driver GetPooledConnection()
{
Driver driver = null;
// if we don't have an idle connection but we have room for a new
// one, then create it here.
lock ((idlePool as ICollection).SyncRoot)
{
if (HasIdleConnections)
driver = idlePool.Dequeue();
}
// Obey the connection timeout
if (driver != null)
{
try
{
driver.ResetTimeout((int)Settings.ConnectionTimeout * 1000);
}
catch (Exception)
{
driver.Close();
driver = null;
}
}
if (driver != null)
{
// first check to see that the server is still alive
if (!driver.Ping())
{
driver.Close();
driver = null;
}
else if (settings.ConnectionReset)
// if the user asks us to ping/reset pooled connections
// do so now
driver.Reset();
}
if (driver == null)
driver = CreateNewPooledConnection();
Debug.Assert(driver != null);
lock ((inUsePool as ICollection).SyncRoot)
{
inUsePool.Add(driver);
}
return driver;
}
/// <summary>
/// It is assumed that this method is only called from inside an active lock.
/// </summary>
private Driver CreateNewPooledConnection()
{
Debug.Assert((maxSize - NumConnections) > 0, "Pool out of sync.");
Driver driver = Driver.Create(settings);
driver.Pool = this;
return driver;
}
public void ReleaseConnection(Driver driver)
{
lock ((inUsePool as ICollection).SyncRoot)
{
if (inUsePool.Contains(driver))
inUsePool.Remove(driver);
}
if (driver.ConnectionLifetimeExpired() || beingCleared)
{
driver.Close();
Debug.Assert(!idlePool.Contains(driver));
}
else
{
lock ((idlePool as ICollection).SyncRoot)
{
EnqueueIdle(driver);
}
}
Interlocked.Increment(ref available);
autoEvent.Set();
}
/// <summary>
/// Removes a connection from the in use pool. The only situations where this method
/// would be called are when a connection that is in use gets some type of fatal exception
/// or when the connection is being returned to the pool and it's too old to be
/// returned.
/// </summary>
/// <param name="driver"></param>
public void RemoveConnection(Driver driver)
{
lock ((inUsePool as ICollection).SyncRoot)
{
if (inUsePool.Contains(driver))
{
inUsePool.Remove(driver);
Interlocked.Increment(ref available);
autoEvent.Set();
}
}
// if we are being cleared and we are out of connections then have
// the manager destroy us.
if (beingCleared && NumConnections == 0)
MySqlPoolManager.RemoveClearedPool(this);
}
private Driver TryToGetDriver()
{
int count = Interlocked.Decrement(ref available);
if (count < 0)
{
Interlocked.Increment(ref available);
return null;
}
try
{
Driver driver = GetPooledConnection();
return driver;
}
catch (Exception ex)
{
Interlocked.Increment(ref available);
throw ex;
}
}
public Driver GetConnection()
{
int fullTimeOut = (int)settings.ConnectionTimeout * 1000;
int timeOut = fullTimeOut;
DateTime start = DateTime.Now;
while (timeOut > 0)
{
Driver driver = TryToGetDriver();
if (driver != null) return driver;
// We have no tickets right now, lets wait for one.
if (!autoEvent.WaitOne(timeOut)) break;
timeOut = fullTimeOut - (int)DateTime.Now.Subtract(start).TotalMilliseconds;
}
throw new MySqlException(ResourceStrings.TimeoutGettingConnection);
}
/// <summary>
/// Clears this pool of all idle connections and marks this pool and being cleared
/// so all other connections are closed when they are returned.
/// </summary>
internal void Clear()
{
lock ((idlePool as ICollection).SyncRoot)
{
// first, mark ourselves as being cleared
beingCleared = true;
// then we remove all connections sitting in the idle pool
while (idlePool.Count > 0)
{
Driver d = idlePool.Dequeue();
d.Close();
}
// there is nothing left to do here. Now we just wait for all
// in use connections to be returned to the pool. When they are
// they will be closed. When the last one is closed, the pool will
// be destroyed.
}
}
/// <summary>
/// Remove expired drivers from the idle pool
/// </summary>
/// <returns></returns>
/// <remarks>
/// Closing driver is a potentially lengthy operation involving network
/// IO. Therefore we do not close expired drivers while holding
/// idlePool.SyncRoot lock. We just remove the old drivers from the idle
/// queue and return them to the caller. The caller will need to close
/// them (or let GC close them)
/// </remarks>
internal List<Driver> RemoveOldIdleConnections()
{
List<Driver> oldDrivers = new List<Driver>();
DateTime now = DateTime.Now;
lock ((idlePool as ICollection).SyncRoot)
{
// The drivers appear to be ordered by their age, i.e it is
// sufficient to remove them until the first element is not
// too old.
while (idlePool.Count > minSize)
{
Driver d = idlePool.Peek();
DateTime expirationTime = d.IdleSince.Add(
new TimeSpan(0, 0, MySqlPoolManager.maxConnectionIdleTime));
if (expirationTime.CompareTo(now) < 0)
{
oldDrivers.Add(d);
idlePool.Dequeue();
}
else
{
break;
}
}
}
return oldDrivers;
}
}
} | lgpl-3.0 |
Builders-SonarSource/sonarqube-bis | server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/batch/BatchReportDirectoryHolderImpl.java | 1392 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.computation.task.projectanalysis.batch;
import java.io.File;
import java.util.Objects;
public class BatchReportDirectoryHolderImpl implements MutableBatchReportDirectoryHolder {
private File directory;
@Override
public void setDirectory(File newDirectory) {
this.directory = Objects.requireNonNull(newDirectory);
}
@Override
public File getDirectory() {
if (this.directory == null) {
throw new IllegalStateException("Directory has not been set yet");
}
return this.directory;
}
}
| lgpl-3.0 |
osbitools/OsBiToolsSpringWs | OsBiWsCoreShared/src/test/java/com/osbitools/ws/core/shared/csv/CsvGenerator.java | 4140 | /*
* Open Source Business Intelligence Tools - http://www.osbitools.com/
*
* Copyright 2014-2018 IvaLab Inc. and by respective contributors (see below).
*
* Released under the LGPL v3 or higher
* See http://www.gnu.org/licenses/lgpl-3.0.html
*
* Date: 2014-11-07
*
* Contributors:
*
* Igor Peonte <[email protected]>
*
*/
package com.osbitools.ws.core.shared.csv;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.osbitools.ws.core.shared.common.CoreSharedTestConstants;
/**
* Generate files for test purposes in test config csv directory
*
* @author "Igor Peonte <[email protected]>"
*
*/
public class CsvGenerator {
private static final String CSV_DIR = CoreSharedTestConstants.WORK_CSV_DIR + File.separator;
private static final String FNAME1 = "temp1.csv";
private static final String FNAME2 = "temp2.csv";
private static final int REC_NUM = 100;
private static final int RAND_RANGE = REC_NUM / 10;
private static final int WORD_LEN = 3;
private static final char[][] alphabets =
new char[][] { "abcdefghijklmnopqrstuvwxyz".toCharArray(),
"абвгдежзклмнопрстуфхцчшщэюя".toCharArray() };
public static void main(String[] args) throws IOException {
File d = new File(CoreSharedTestConstants.WORK_CSV_DIR);
if (!d.exists() && !d.mkdirs()) {
System.err.println("Unable create " + CoreSharedTestConstants.WORK_CSV_DIR + " directory.");
System.exit(1);
}
// genSort1();
// genSort2();
getSql();
}
public static void genSort1() throws IOException {
// Generate sort1.csv with 2 columns.
// First column is random 3 letters localized value and second
// is random number in range <number of records>/10
String fname = CSV_DIR + FNAME1;
FileWriter out = new FileWriter(fname, false);
out.write("CSTR,CINT,CNUM,CDATE\n");
for (int i = 0; i < REC_NUM; i++) {
char[] word = genRandWord();
out.write(new String(word) + "," + (int) (Math.random() * RAND_RANGE) + "," +
Math.random() * RAND_RANGE + "," + ((int) (Math.random() * 12) + 1) + "/" +
((int) (Math.random() * 25) + 1) + "/" + (2000 + (int) (Math.random() * 12)) + "\n");
}
out.close();
System.out.println(REC_NUM + " records successfully written to " + fname);
}
public static void genSort2() throws IOException {
String fname = CSV_DIR + FNAME2;
// Generate 4 random words
int rw_len = 4;
char[][] rwords = new char[rw_len][];
for (int i = 0; i < rw_len; i++)
rwords[i] = genRandWord();
FileWriter out = new FileWriter(fname, false);
out.write("CSTR\n");
for (int i = 0; i < REC_NUM; i++) {
char[] word = rwords[(int) (Math.random() * rw_len)];
out.write(new String(word) + "\n");
}
out.close();
System.out.println(REC_NUM + " records successfully written to " + fname);
}
static void getSql() throws IOException {
String fname = CSV_DIR + FNAME1 + ".sql";
FileWriter out = new FileWriter(fname, false);
for (int i = 0; i < REC_NUM; i++) {
char[] word = genRandWord();
out.write("INSERT INTO TEST_DATA(CSTR,CINT,CNUM,CDATE) VALUES('" + new String(word) +
"'," + (int) (Math.random() * RAND_RANGE) + "," + Math.random() * RAND_RANGE + ",'" +
((2000 + (int) (Math.random() * 12) + "-" + ((int) (Math.random() * 12) + 1)) + "-" +
((int) (Math.random() * 25) + 1)) +
"');\n");
}
out.close();
System.out.println(REC_NUM + " records successfully written to " + fname);
}
static char[] genRandWord() {
int anum = alphabets.length;
// Pick alphabet
char[] alphabet = alphabets[(int) (Math.random() * anum)];
char[] word = new char[WORD_LEN];
for (int j = 0; j < WORD_LEN; j++) {
char letter = alphabet[(int) (Math.random() * anum)];
// pick case
if (Math.random() * 2 < 1)
letter = Character.toLowerCase(letter);
else
letter = Character.toUpperCase(letter);
word[j] = letter;
}
return word;
}
}
| lgpl-3.0 |
i4004/Simplify.Web | src/Simplify.Web.Tests/TestEntities/TestModelMaxLength.cs | 185 | using Simplify.Web.ModelBinding.Attributes;
namespace Simplify.Web.Tests.TestEntities
{
public class TestModelMaxLength
{
[MaxLength(2)]
public string Prop1 { get; set; }
}
} | lgpl-3.0 |
herculeshssj/orcamento | orcamento/src/main/java/br/com/hslife/orcamento/entity/CategoriaInvestimento.java | 4564 | /***
Copyright (c) 2012 - 2021 Hércules S. S. José
Este arquivo é parte do programa Orçamento Doméstico.
Orçamento Doméstico é um software livre; você pode redistribui-lo e/ou
modificá-lo dentro dos termos da Licença Pública Geral Menor GNU como
publicada pela Fundação do Software Livre (FSF); na versão 3.0 da
Licença.
Este programa é distribuído na esperança que possa ser útil, mas SEM
NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer
MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral Menor
GNU em português para maiores detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral Menor GNU sob
o nome de "LICENSE" junto com este programa, se não, acesse o site do
projeto no endereco https://github.com/herculeshssj/orcamento ou escreva
para a Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor,
Boston, MA 02110-1301, USA.
Para mais informações sobre o programa Orçamento Doméstico e seu autor
entre em contato pelo e-mail [email protected], ou ainda escreva
para Hércules S. S. José, Rua José dos Anjos, 160 - Bl. 3 Apto. 304 -
Jardim Alvorada - CEP: 26261-130 - Nova Iguaçu, RJ, Brasil.
***/
package br.com.hslife.orcamento.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import br.com.hslife.orcamento.enumeration.TipoInvestimento;
import br.com.hslife.orcamento.util.EntityPersistenceUtil;
import br.com.hslife.orcamento.util.Util;
@Entity
@Table(name="categoriainvestimento")
@SuppressWarnings("serial")
public class CategoriaInvestimento extends EntityPersistence {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(length=50, nullable=false)
private String descricao;
@Column
private boolean ativo;
@Column(length=10, nullable=false)
@Enumerated(EnumType.STRING)
private TipoInvestimento tipoInvestimento;
/*** Atributos usados para a Carteira de Investimento ***/
@Transient
private List<Investimento> investimentos = new ArrayList<>();
@Transient
private double totalInvestimento = 0.0;
/*** Atributos usados para a Carteira de Investimento ***/
public CategoriaInvestimento() {
ativo = true;
}
@Override
public String getLabel() {
return this.descricao;
}
@Override
public void validate() {
EntityPersistenceUtil.validaTamanhoCampoStringObrigatorio("Descrição", this.descricao, 50);
EntityPersistenceUtil.validaCampoNulo("Tipo de investimento", this.tipoInvestimento);
}
public Long getId() {
return id;
}
/*
* Calcula o percentual de cada investimento contido na categoria.
* Usado no resumo Carteira de Investimento
*/
public void calcularPercentuaisInvestimento() {
if (this.investimentos != null && !this.investimentos.isEmpty()) {
// Calcula o total investido
for (Investimento i : this.investimentos) {
this.totalInvestimento += i.getValorInvestimento();
}
// Seta em cada investimento o seu respectivo percentual
for (Investimento in : this.investimentos) {
double valorInvestimento = in.getValorInvestimento();
// Previne problemas com operação com zero
if (this.totalInvestimento != 0 & valorInvestimento != 0) {
in.setPercentualInvestimento(Util.arredondar( (valorInvestimento / this.totalInvestimento) * 100 ));
}
}
}
}
public void setId(Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
public TipoInvestimento getTipoInvestimento() {
return tipoInvestimento;
}
public void setTipoInvestimento(TipoInvestimento tipoInvestimento) {
this.tipoInvestimento = tipoInvestimento;
}
public List<Investimento> getInvestimentos() {
return investimentos;
}
public void setInvestimentos(List<Investimento> investimentos) {
this.investimentos = investimentos;
}
public double getTotalInvestimento() {
return totalInvestimento;
}
}
| lgpl-3.0 |
rmage/gnvc-ims | src/java/com/app/wms/engine/db/exceptions/WsDaoException.java | 389 | package com.app.wms.engine.db.exceptions;
public class WsDaoException extends DaoException
{
/**
* Method 'WsDaoException'
*
* @param message
*/
public WsDaoException(String message)
{
super(message);
}
/**
* Method 'WsDaoException'
*
* @param message
* @param cause
*/
public WsDaoException(String message, Throwable cause)
{
super(message, cause);
}
}
| lgpl-3.0 |
jorj1988/debugify | spec/helper.rb | 93 | $: << File.join(File.dirname(__FILE__), '..', 'App')
require 'pry'
require 'Project/Project' | lgpl-3.0 |
svn2github/dynamicreports-jasper | dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/group/ColumnGroupBuilder.java | 2892 | /**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2015 Ricardo Mariaca
* http://www.dynamicreports.org
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.report.builder.group;
import net.sf.dynamicreports.report.base.column.DRValueColumn;
import net.sf.dynamicreports.report.builder.column.ValueColumnBuilder;
import net.sf.dynamicreports.report.constant.Constants;
import net.sf.dynamicreports.report.definition.datatype.DRIDataType;
import org.apache.commons.lang3.Validate;
/**
* @author Ricardo Mariaca ([email protected])
*/
public class ColumnGroupBuilder extends GroupBuilder<ColumnGroupBuilder> {
private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;
private DRValueColumn<?> column;
protected ColumnGroupBuilder(ValueColumnBuilder<?, ?> column) {
Validate.notNull(column, "column must not be null");
this.column = column.build();
init();
}
protected ColumnGroupBuilder(String name, ValueColumnBuilder<?, ?> column) {
super(name);
Validate.notNull(column, "column must not be null");
this.column = column.build();
init();
}
@SuppressWarnings("unchecked")
private void init() {
@SuppressWarnings("rawtypes")
DRIDataType dataType = column.getComponent().getDataType();
getObject().getValueField().setDataType(dataType);
getObject().getValueField().setStyle(column.getComponent().getStyle());
getObject().getValueField().setPattern(column.getComponent().getPattern());
getObject().getValueField().setPatternExpression(column.getComponent().getPatternExpression());
getObject().getValueField().setHorizontalAlignment(column.getComponent().getHorizontalAlignment());
getObject().setTitleExpression(column.getTitleExpression());
getObject().setTitleStyle(column.getTitleStyle());
getObject().setTitleWidth(column.getComponent().getWidth());
}
public ColumnGroupBuilder setHideColumn(Boolean hideColumn) {
getObject().setHideColumn(hideColumn);
return this;
}
@Override
protected void configure() {
setValueExpression(column);
super.configure();
}
}
| lgpl-3.0 |
Arcavias/arcavias-core | controller/frontend/tests/Controller/Frontend/Service/DefaultTest.php | 4831 | <?php
/**
* @copyright Copyright (c) Metaways Infosystems GmbH, 2012
* @license LGPLv3, http://www.arcavias.com/en/license
*/
class Controller_Frontend_Service_DefaultTest extends MW_Unittest_Testcase
{
private $_object;
private static $_basket;
protected function setUp()
{
$this->_object = new Controller_Frontend_Service_Default( TestHelper::getContext() );
}
public static function setUpBeforeClass()
{
$orderManager = MShop_Order_Manager_Factory::createManager( TestHelper::getContext() );
$orderBaseMgr = $orderManager->getSubManager( 'base' );
self::$_basket = $orderBaseMgr->createItem();
}
protected function tearDown()
{
unset( $this->_object );
}
public function testGetServices()
{
$orderManager = MShop_Order_Manager_Factory::createManager( TestHelper::getContext() );
$basket = $orderManager->getSubManager( 'base' )->createItem();
$services = $this->_object->getServices( 'delivery', $basket );
$this->assertGreaterThan( 0, count( $services ) );
foreach( $services as $service ) {
$this->assertInstanceOf( 'MShop_Service_Item_Interface', $service );
}
}
public function testGetServicesCache()
{
$orderManager = MShop_Order_Manager_Factory::createManager( TestHelper::getContext() );
$basket = $orderManager->getSubManager( 'base' )->createItem();
$this->_object->getServices( 'delivery', $basket );
$services = $this->_object->getServices( 'delivery', $basket );
$this->assertGreaterThan( 0, count( $services ) );
}
public function testGetServiceAttributes()
{
$service = $this->_getServiceItem();
$attributes = $this->_object->getServiceAttributes( 'delivery', $service->getId(), self::$_basket );
$this->assertEquals( 0, count( $attributes ) );
}
public function testGetServiceAttributesCache()
{
$orderManager = MShop_Order_Manager_Factory::createManager( TestHelper::getContext() );
$basket = $orderManager->getSubManager( 'base' )->createItem();
$services = $this->_object->getServices( 'delivery', $basket );
if( ( $service = reset( $services ) ) === false ) {
throw new Exception( 'No service item found' );
}
$attributes = $this->_object->getServiceAttributes( 'delivery', $service->getId(), self::$_basket );
$this->assertEquals( 0, count( $attributes ) );
}
public function testGetServiceAttributesNoItems()
{
$this->setExpectedException( 'Controller_Frontend_Service_Exception' );
$this->_object->getServiceAttributes( 'invalid', -1, self::$_basket );
}
public function testGetServicePrice()
{
$orderManager = MShop_Order_Manager_Factory::createManager( TestHelper::getContext() );
$basket = $orderManager->getSubManager( 'base' )->createItem();
$service = $this->_getServiceItem();
$price = $this->_object->getServicePrice( 'delivery', $service->getId(), $basket );
$this->assertEquals( '12.95', $price->getValue() );
$this->assertEquals( '1.99', $price->getCosts() );
}
public function testGetServicePriceCache()
{
$orderManager = MShop_Order_Manager_Factory::createManager( TestHelper::getContext() );
$basket = $orderManager->getSubManager( 'base' )->createItem();
$services = $this->_object->getServices( 'delivery', $basket );
if( ( $service = reset( $services ) ) === false ) {
throw new Exception( 'No service item found' );
}
$price = $this->_object->getServicePrice( 'delivery', $service->getId(), $basket );
$this->assertEquals( '12.95', $price->getValue() );
$this->assertEquals( '1.99', $price->getCosts() );
}
public function testGetServicePriceNoItems()
{
$orderManager = MShop_Order_Manager_Factory::createManager( TestHelper::getContext() );
$basket = $orderManager->getSubManager( 'base' )->createItem();
$this->setExpectedException( 'Controller_Frontend_Service_Exception' );
$this->_object->getServicePrice( 'invalid', -1, $basket );
}
public function testCheckServiceAttributes()
{
$service = $this->_getServiceItem();
$attributes = $this->_object->checkServiceAttributes( 'delivery', $service->getId(), array() );
$this->assertEquals( array(), $attributes );
}
/**
* @return MShop_Order_Item_Base_Interface
*/
protected function _getServiceItem()
{
$serviceManager = MShop_Service_Manager_Factory::createManager( TestHelper::getContext() );
$search = $serviceManager->createSearch( true );
$expr = array(
$search->getConditions(),
$search->compare( '==', 'service.provider', 'Default' ),
$search->compare( '==', 'service.type.domain', 'service' ),
$search->compare( '==', 'service.type.code', 'delivery' ),
);
$search->setConditions( $search->combine( '&&', $expr ) );
$services = $serviceManager->searchItems( $search );
if( ( $service = reset( $services ) ) === false ) {
throw new Exception( 'No service item found' );
}
return $service;
}
}
| lgpl-3.0 |
awltech/eclipse-optimus | net.atos.optimus.m2m.javaxmi.parent/net.atos.optimus.m2m.javaxmi.operation/src/main/java/net/atos/optimus/m2m/javaxmi/operation/instructions/builders/complex/DoStatementBuilder.java | 2557 | /**
* Optimus, framework for Model Transformation
*
* Copyright (C) 2013 Worldline or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.atos.optimus.m2m.javaxmi.operation.instructions.builders.complex;
import org.eclipse.gmt.modisco.java.DoStatement;
import org.eclipse.gmt.modisco.java.Expression;
import org.eclipse.gmt.modisco.java.Statement;
import org.eclipse.gmt.modisco.java.emf.JavaFactory;
/**
* A builder dedicated to create do statement of modisco model
*
* @author tnachtergaele <[email protected]>
*
*
*/
public class DoStatementBuilder {
/** The build do statement */
private DoStatement buildDoStatement;
/**
* Give a do statement builder
*
* @return a new do statement builder.
*/
public static DoStatementBuilder builder() {
return new DoStatementBuilder();
}
/**
* Private constructor
*
*/
private DoStatementBuilder() {
this.buildDoStatement = JavaFactory.eINSTANCE.createDoStatement();
}
/**
* Build a do statement of modisco model
*
* @return a new do statement of modisco model.
*/
public DoStatement build() {
return this.buildDoStatement;
}
/**
* Set the expression of the do statement under construction
*
* @param expression
* the expression of the do statement under construction.
* @return the builder.
*/
public DoStatementBuilder setExpression(Expression expression) {
this.buildDoStatement.setExpression(expression);
return this;
}
/**
* Set the body of the do statement under construction
*
* @param body
* the body of the do statement under construction.
* @return the builder.
*/
public DoStatementBuilder setBody(Statement body) {
this.buildDoStatement.setBody(body);
return this;
}
}
| lgpl-3.0 |
AshwinJay/StreamCruncher | demo_src/streamcruncher/test/func/h2/H2TimeWF1ChainedPartitionTest.java | 1170 | package streamcruncher.test.func.h2;
import java.util.List;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import streamcruncher.test.TestGroupNames;
import streamcruncher.test.func.BatchResult;
import streamcruncher.test.func.generic.TimeWF1ChainedPartitionTest;
/*
* Author: Ashwin Jayaprakash Date: Oct 3, 2006 Time: 10:55:32 PM
*/
public class H2TimeWF1ChainedPartitionTest extends TimeWF1ChainedPartitionTest {
@Override
@BeforeGroups(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, value = { TestGroupNames.SC_TEST_H2 }, groups = { TestGroupNames.SC_TEST_H2 })
public void init() throws Exception {
super.init();
}
@Test(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, groups = { TestGroupNames.SC_TEST_H2 })
protected void performTest() throws Exception {
List<BatchResult> results = test();
}
@Override
@AfterGroups(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, value = { TestGroupNames.SC_TEST_H2 }, groups = { TestGroupNames.SC_TEST_H2 })
public void discard() {
super.discard();
}
}
| lgpl-3.0 |
MinecraftModArchive/Runes-And-Silver | src/main/java/Runes/Entites/ModelEnt.java | 6708 | /*
* Copyright (c) 2014 Silas Otoko.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see <http://www.gnu.org/licenses>.
*/
package runes.Runes.Entites;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelIronGolem;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityIronGolem;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ModelEnt extends ModelBase
{
public boolean isCarrying;
/** The head model for the iron golem. */
public ModelRenderer ironGolemHead;
/** The body model for the iron golem. */
public ModelRenderer ironGolemBody;
/** The right arm model for the iron golem. */
public ModelRenderer ironGolemRightArm;
/** The left arm model for the iron golem. */
public ModelRenderer ironGolemLeftArm;
/** The left leg model for the Iron Golem. */
public ModelRenderer ironGolemLeftLeg;
/** The right leg model for the Iron Golem. */
public ModelRenderer ironGolemRightLeg;
public ModelEnt()
{
this(0.0F);
}
public ModelEnt(float par1)
{
this(par1, -7.0F);
}
public ModelEnt(float par1, float par2)
{
short short1 = 128;
short short2 = 128;
this.ironGolemHead = (new ModelRenderer(this)).setTextureSize(short1, short2);
this.ironGolemHead.setRotationPoint(0.0F, 0.0F + par2, -2.0F);
this.ironGolemHead.setTextureOffset(0, 0).addBox(-4.0F, -12.0F, -5.5F, 8, 10, 8, par1);
this.ironGolemHead.setTextureOffset(24, 0).addBox(-1.0F, -5.0F, -7.5F, 2, 4, 2, par1);
this.ironGolemBody = (new ModelRenderer(this)).setTextureSize(short1, short2);
this.ironGolemBody.setRotationPoint(0.0F, 0.0F + par2, 0.0F);
this.ironGolemBody.setTextureOffset(0, 40).addBox(-9.0F, -2.0F, -6.0F, 18, 12, 11, par1);
this.ironGolemBody.setTextureOffset(0, 70).addBox(-4.5F, 10.0F, -3.0F, 9, 5, 6, par1 + 0.5F);
this.ironGolemRightArm = (new ModelRenderer(this)).setTextureSize(short1, short2);
this.ironGolemRightArm.setRotationPoint(0.0F, -7.0F, 0.0F);
this.ironGolemRightArm.setTextureOffset(60, 21).addBox(-13.0F, -2.5F, -3.0F, 4, 30, 6, par1);
this.ironGolemLeftArm = (new ModelRenderer(this)).setTextureSize(short1, short2);
this.ironGolemLeftArm.setRotationPoint(0.0F, -7.0F, 0.0F);
this.ironGolemLeftArm.setTextureOffset(60, 58).addBox(9.0F, -2.5F, -3.0F, 4, 30, 6, par1);
this.ironGolemLeftLeg = (new ModelRenderer(this, 0, 22)).setTextureSize(short1, short2);
this.ironGolemLeftLeg.setRotationPoint(-4.0F, 18.0F + par2, 0.0F);
this.ironGolemLeftLeg.setTextureOffset(37, 0).addBox(-3.5F, -3.0F, -3.0F, 6, 16, 5, par1);
this.ironGolemRightLeg = (new ModelRenderer(this, 0, 22)).setTextureSize(short1, short2);
this.ironGolemRightLeg.mirror = true;
this.ironGolemRightLeg.setTextureOffset(60, 0).setRotationPoint(5.0F, 18.0F + par2, 0.0F);
this.ironGolemRightLeg.addBox(-3.5F, -3.0F, -3.0F, 6, 16, 5, par1);
}
/**
* Sets the models various rotation angles then renders the model.
*/
public void render(Entity par1Entity, float par2, float par3, float par4, float par5, float par6, float par7)
{
this.setRotationAngles(par2, par3, par4, par5, par6, par7, par1Entity);
this.ironGolemHead.render(par7);
this.ironGolemBody.render(par7);
this.ironGolemLeftLeg.render(par7);
this.ironGolemRightLeg.render(par7);
this.ironGolemRightArm.render(par7);
this.ironGolemLeftArm.render(par7);
}
/**
* Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms
* and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how
* "far" arms and legs can swing at most.
*/
public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity par7Entity)
{
this.ironGolemHead.rotateAngleY = par4 / (180F / (float)Math.PI);
this.ironGolemHead.rotateAngleX = par5 / (180F / (float)Math.PI);
this.ironGolemLeftLeg.rotateAngleX = -1.5F * this.func_78172_a(par1, 13.0F) * par2;
this.ironGolemRightLeg.rotateAngleX = 1.5F * this.func_78172_a(par1, 13.0F) * par2;
this.ironGolemLeftLeg.rotateAngleY = 0.0F;
this.ironGolemRightLeg.rotateAngleY = 0.0F;
}
/**
* Used for easily adding entity-dependent animations. The second and third float params here are the same second
* and third as in the setRotationAngles method.
*/
public void setLivingAnimations(EntityLivingBase par1EntityLivingBase, float par2, float par3, float par4)
{
EntityForestWalker entityforestwalker = (EntityForestWalker)par1EntityLivingBase;
int i = entityforestwalker.getAttackTimer();
if (i > 0)
{
this.ironGolemRightArm.rotateAngleX = -2.0F + 1.5F * this.func_78172_a((float)i - par4, 10.0F);
this.ironGolemLeftArm.rotateAngleX = -2.0F + 1.5F * this.func_78172_a((float)i - par4, 10.0F);
}
else
{
if (this.isCarrying)
{
this.ironGolemRightArm.rotateAngleX = -0.5F;
this.ironGolemLeftArm.rotateAngleX = -0.5F;
this.ironGolemRightArm.rotateAngleZ = 0.05F;
this.ironGolemLeftArm.rotateAngleZ = -0.05F;
}
else
{
this.ironGolemRightArm.rotateAngleX = (-0.2F + 1.5F * this.func_78172_a(par2, 13.0F)) * par3;
this.ironGolemLeftArm.rotateAngleX = (-0.2F - 1.5F * this.func_78172_a(par2, 13.0F)) * par3;
}
}
}
private float func_78172_a(float par1, float par2)
{
return (Math.abs(par1 % par2 - par2 * 0.5F) - par2 * 0.25F) / (par2 * 0.25F);
}
} | lgpl-3.0 |
Javlo/javlo | src/main/java/org/javlo/service/syncro/exception/SynchroNonFatalException.java | 467 | package org.javlo.service.syncro.exception;
public class SynchroNonFatalException extends Exception {
private static final long serialVersionUID = 2603047944162614611L;
public SynchroNonFatalException() {
super();
}
public SynchroNonFatalException(String message, Throwable cause) {
super(message, cause);
}
public SynchroNonFatalException(String message) {
super(message);
}
public SynchroNonFatalException(Throwable cause) {
super(cause);
}
}
| lgpl-3.0 |
EntityAPIDev/EntityAPI | modules/v1_8_R1/src/main/java/org/entityapi/nms/v1_8_R1/entity/ControllableZombieEntity.java | 5963 | /*
* Copyright (C) EntityAPI Team
*
* This file is part of EntityAPI.
*
* EntityAPI 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.
*
* EntityAPI 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 EntityAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package org.entityapi.nms.v1_8_R1.entity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import org.entityapi.api.entity.DespawnReason;
import org.entityapi.api.entity.EntitySound;
import org.entityapi.api.entity.mind.attribute.*;
import org.entityapi.api.entity.type.ControllableZombie;
import org.entityapi.api.entity.type.nms.ControllableZombieHandle;
import org.entityapi.api.events.Action;
import org.entityapi.api.utils.EntityUtil;
public class ControllableZombieEntity extends EntityZombie implements ControllableZombieHandle {
private final ControllableZombie controllableEntity;
public ControllableZombieEntity(World world, ControllableZombie controllableEntity) {
super(world);
this.controllableEntity = controllableEntity;
EntityUtil.clearGoals(this);
}
@Override
public ControllableZombie getControllableEntity() {
return this.controllableEntity;
}
// All ControllableEntities should use new AI
@Override
protected boolean bk() {
return true;
}
// EntityInsentient - Most importantly stops NMS goal selectors from ticking
@Override
protected void bn() {
++this.aV;
this.w();
this.getEntitySenses().a();
//this.targetSelector.a();
//this.goalSelector.a();
this.getNavigation().f();
this.bp();
this.getControllerMove().c();
this.getControllerLook().a();
this.getControllerJump().b();
}
@Override
public void move(double d0, double d1, double d2) {
if (this.controllableEntity != null && this.controllableEntity.isStationary()) {
return;
}
super.move(d0, d1, d2);
}
@Override
public void h() {
super.h();
if (this.controllableEntity != null) {
this.controllableEntity.getMind().getAttribute(TickAttribute.class).call(this.controllableEntity);
this.controllableEntity.getMind().tick();
}
}
@Override
public void collide(Entity entity) {
if (this.controllableEntity == null) {
super.collide(entity);
return;
}
if (!this.controllableEntity.getMind().getAttribute(CollideAttribute.class).call(this.controllableEntity, entity.getBukkitEntity()).isCancelled()) {
super.collide(entity);
}
}
@Override
public boolean a(EntityHuman entity) {
if (this.controllableEntity == null || !(entity.getBukkitEntity() instanceof Player)) {
return super.c(entity);
}
return !this.controllableEntity.getMind().getAttribute(InteractAttribute.class).call(this.controllableEntity, entity.getBukkitEntity(), Action.RIGHT_CLICK).isCancelled();
}
@Override
public boolean damageEntity(DamageSource damageSource, float v) {
if (this.controllableEntity != null && damageSource.getEntity() != null && damageSource.getEntity().getBukkitEntity() instanceof Player) {
return !this.controllableEntity.getMind().getAttribute(InteractAttribute.class).call(this.controllableEntity, damageSource.getEntity().getBukkitEntity(), Action.LEFT_CLICK).isCancelled();
}
return super.damageEntity(damageSource, v);
}
@Override
public void e(float xMotion, float zMotion) {
float[] motion = new float[]{xMotion, (float) this.motY, zMotion};
if (this.controllableEntity != null) {
ControlledRidingAttribute controlledRidingAttribute = this.controllableEntity.getMind().getAttribute(ControlledRidingAttribute.class);
if (controlledRidingAttribute != null) {
controlledRidingAttribute.onRide(motion);
}
}
this.motY = motion[1];
super.e(motion[0], motion[2]);
}
@Override
public void g(double x, double y, double z) {
if (this.controllableEntity != null) {
Vector velocity = this.controllableEntity.getMind().getAttribute(PushAttribute.class).call(this.controllableEntity, new Vector(x, y, z)).getPushVelocity();
x = velocity.getX();
y = velocity.getY();
z = velocity.getZ();
}
super.g(x, y, z);
}
@Override
public void die(DamageSource damagesource) {
if (this.controllableEntity != null) {
this.controllableEntity.getEntityManager().despawn(this.controllableEntity, DespawnReason.DEATH);
}
super.die(damagesource);
}
@Override
protected String t() {
return this.controllableEntity == null ? "mob.zombie.say" : this.controllableEntity.getSound(EntitySound.IDLE);
}
@Override
protected String aT() {
return this.controllableEntity == null ? "mob.zombie.hurt" : this.controllableEntity.getSound(EntitySound.HURT);
}
@Override
protected String aU() {
return this.controllableEntity == null ? "mob.zombie.death" : this.controllableEntity.getSound(EntitySound.DEATH);
}
@Override
protected void a(int i, int j, int k, Block block) {
this.makeSound(this.controllableEntity == null ? "mob.zombie.step" : this.controllableEntity.getSound(EntitySound.STEP), 0.15F, 1.0F);
}
} | lgpl-3.0 |
huangye177/spring4probe | src/main/java/rest/yummynoodlebar/core/events/UpdateEvent.java | 80 | package rest.yummynoodlebar.core.events;
public abstract class UpdateEvent {
}
| lgpl-3.0 |
optimaize/nameapi-client-java | src/main/java/org/nameapi/client/services/development/exceptionthrower/ExceptionType.java | 531 | package org.nameapi.client.services.development.exceptionthrower;
/**
* Types that the server throws.
*/
public enum ExceptionType {
InvalidInput,
AccessDeniedNoSuchAccount,
// AccessDeniedRequestLimitExceeded,
// AccessDeniedTooManyConcurrentRequests,
InternalServerError,
;
/**
* Developer: Call this before doing a switch on an enum value.
*/
public static void assertSize(int size) {
assert values().length == size : "Update the code calling this with "+size+"!";
}
}
| lgpl-3.0 |
BackupTheBerlios/cppparser | src/scalpel/cpp/syntax_nodes/expressions.hpp | 5842 | /*
Scalpel - Source Code Analysis, Libre and PortablE Library
Copyright © 2008 - 2010 Florian Goujeon
This file is part of Scalpel.
Scalpel is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Scalpel 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 Scalpel. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SCALPEL_CPP_SYNTAX_NODES_EXPRESSIONS_HPP
#define SCALPEL_CPP_SYNTAX_NODES_EXPRESSIONS_HPP
#include "cast_expression.hpp"
#include "common.hpp"
namespace scalpel { namespace cpp { namespace syntax_nodes
{
//primary expressions
typedef
list_node
<
cast_expression,
common_nodes::arrow_and_asterisk
>
pm_ptr_expression
;
typedef
list_node
<
pm_ptr_expression,
common_nodes::dot_and_asterisk
>
pm_ref_expression
;
typedef
list_node
<
pm_ref_expression,
common_nodes::percent
>
modulo_expression
;
typedef
list_node
<
modulo_expression,
common_nodes::slash
>
divisive_expression
;
typedef
list_node
<
divisive_expression,
common_nodes::asterisk
>
multiplicative_expression
;
typedef
list_node
<
multiplicative_expression,
common_nodes::minus
>
subtractive_expression
;
typedef
list_node
<
subtractive_expression,
common_nodes::plus
>
additive_expression
;
typedef
list_node
<
additive_expression,
common_nodes::double_left_angle_bracket
>
left_shift_expression
;
typedef
list_node
<
left_shift_expression,
common_nodes::double_right_angle_bracket
>
right_shift_expression
;
typedef
list_node
<
right_shift_expression,
common_nodes::left_angle_bracket_and_equal
>
less_than_or_equal_to_expression
;
typedef
list_node
<
less_than_or_equal_to_expression,
common_nodes::left_angle_bracket
>
less_than_expression
;
typedef
list_node
<
less_than_expression,
common_nodes::right_angle_bracket_and_equal
>
greater_than_or_equal_to_expression
;
typedef
list_node
<
greater_than_or_equal_to_expression,
common_nodes::right_angle_bracket
>
greater_than_expression
;
typedef
list_node
<
greater_than_expression,
common_nodes::inequal
>
inequality_expression
;
typedef
list_node
<
inequality_expression,
common_nodes::double_equal
>
equality_expression
;
typedef
list_node
<
equality_expression,
common_nodes::ampersand
>
and_expression
;
typedef
list_node
<
and_expression,
common_nodes::circumflex
>
exclusive_or_expression
;
typedef
list_node
<
exclusive_or_expression,
common_nodes::pipe
>
inclusive_or_expression
;
typedef
list_node
<
inclusive_or_expression,
common_nodes::double_ampersand
>
logical_and_expression
;
typedef
list_node
<
logical_and_expression,
common_nodes::double_pipe
>
logical_or_expression_t
;
struct logical_or_expression: public logical_or_expression_t
{
logical_or_expression()
{
}
logical_or_expression(const logical_or_expression& o):
logical_or_expression_t(o)
{
}
logical_or_expression(logical_or_expression&& o):
logical_or_expression_t(o)
{
}
};
//round bracketed expressions
typedef
sequence_node
<
predefined_text_node<str::opening_round_bracket>,
optional_node<space>,
right_shift_expression,
optional_node<space>,
predefined_text_node<str::closing_round_bracket>
>
round_bracketed_right_shift_expression
;
typedef
sequence_node
<
predefined_text_node<str::opening_round_bracket>,
optional_node<space>,
greater_than_expression,
optional_node<space>,
predefined_text_node<str::closing_round_bracket>
>
round_bracketed_greater_than_expression
;
//same expressions used as template arguments
typedef
alternative_node
<
round_bracketed_right_shift_expression,
left_shift_expression
>
template_argument_right_shift_expression
;
typedef
list_node
<
template_argument_right_shift_expression,
common_nodes::left_angle_bracket_and_equal
>
template_argument_less_than_or_equal_to_expression
;
typedef
list_node
<
template_argument_less_than_or_equal_to_expression,
common_nodes::left_angle_bracket
>
template_argument_less_than_expression
;
typedef
list_node
<
template_argument_less_than_expression,
common_nodes::right_angle_bracket_and_equal
>
template_argument_greater_than_or_equal_to_expression
;
typedef
alternative_node
<
round_bracketed_greater_than_expression,
template_argument_greater_than_or_equal_to_expression
>
template_argument_greater_than_expression
;
typedef
list_node
<
template_argument_greater_than_expression,
common_nodes::inequal
>
template_argument_inequality_expression
;
typedef
list_node
<
template_argument_inequality_expression,
common_nodes::double_equal
>
template_argument_equality_expression
;
typedef
list_node
<
template_argument_equality_expression,
common_nodes::ampersand
>
template_argument_and_expression
;
typedef
list_node
<
template_argument_and_expression,
common_nodes::circumflex
>
template_argument_exclusive_or_expression
;
typedef
list_node
<
template_argument_exclusive_or_expression,
common_nodes::pipe
>
template_argument_inclusive_or_expression
;
typedef
list_node
<
template_argument_inclusive_or_expression,
common_nodes::double_ampersand
>
template_argument_logical_and_expression
;
typedef
list_node
<
template_argument_logical_and_expression,
common_nodes::double_pipe
>
template_argument_logical_or_expression
;
}}} //namespace scalpel::cpp::syntax_nodes
#endif
| lgpl-3.0 |
qstokkink/py-ipv8 | stresstest/bootstrap_rtt.py | 4488 | import time
from asyncio import ensure_future, get_event_loop
from random import randint
from socket import gethostbyname
# Check if we are running from the root directory
# If not, modify our path so that we can import IPv8
try:
import ipv8
del ipv8
except ImportError:
import __scriptpath__ # noqa: F401
from ipv8.community import Community, _DEFAULT_ADDRESSES, _DNS_ADDRESSES
from ipv8.configuration import get_default_configuration
from ipv8.keyvault.crypto import ECCrypto
from ipv8.peer import Peer
from ipv8.requestcache import NumberCache, RequestCache
from ipv8_service import IPv8, _COMMUNITIES
INSTANCES = []
CHECK_QUEUE = []
RESULTS = {}
CONST_REQUESTS = 10
class PingCache(NumberCache):
def __init__(self, community, hostname, address, starttime):
super(PingCache, self).__init__(community.request_cache, u"introping", community.global_time)
self.hostname = hostname
self.address = address
self.starttime = starttime
self.community = community
@property
def timeout_delay(self):
return 5.0
def on_timeout(self):
self.community.finish_ping(self, False)
class MyCommunity(Community):
master_peer = Peer(ECCrypto().generate_key(u"medium"))
def __init__(self, *args, **kwargs):
super(MyCommunity, self).__init__(*args, **kwargs)
self.request_cache = RequestCache()
def unload(self):
self.request_cache.shutdown()
super(MyCommunity, self).unload()
def finish_ping(self, cache, include=True):
global RESULTS
print(cache.hostname, cache.address, time.time() - cache.starttime)
if include:
if (cache.hostname, cache.address) in RESULTS:
RESULTS[(cache.hostname, cache.address)].append(time.time() - cache.starttime)
else:
RESULTS[(cache.hostname, cache.address)] = [time.time() - cache.starttime]
elif (cache.hostname, cache.address) not in RESULTS:
RESULTS[(cache.hostname, cache.address)] = []
self.next_ping()
def next_ping(self):
global CHECK_QUEUE
if CHECK_QUEUE:
hostname, address = CHECK_QUEUE.pop()
packet = self.create_introduction_request(address)
self.request_cache.add(PingCache(self, hostname, address, time.time()))
self.endpoint.send(address, packet)
else:
get_event_loop().stop()
def introduction_response_callback(self, peer, dist, payload):
if self.request_cache.has(u"introping", payload.identifier):
cache = self.request_cache.pop(u"introping", payload.identifier)
self.finish_ping(cache)
def started(self):
global CHECK_QUEUE
dnsmap = {}
for (address, port) in _DNS_ADDRESSES:
try:
ip = gethostbyname(address)
dnsmap[(ip, port)] = address
except OSError:
pass
UNKNOWN_NAME = '*'
for (ip, port) in _DEFAULT_ADDRESSES:
hostname = dnsmap.get((ip, port), None)
if not hostname:
hostname = UNKNOWN_NAME
UNKNOWN_NAME = UNKNOWN_NAME + '*'
CHECK_QUEUE.append((hostname, (ip, port)))
CHECK_QUEUE = CHECK_QUEUE * CONST_REQUESTS
self.next_ping()
_COMMUNITIES['MyCommunity'] = MyCommunity
async def start_communities():
configuration = get_default_configuration()
configuration['keys'] = [{
'alias': "my peer",
'generation': u"medium",
'file': u"ec1.pem"
}]
configuration['port'] = 12000 + randint(0, 10000)
configuration['overlays'] = [{
'class': 'MyCommunity',
'key': "my peer",
'walkers': [],
'initialize': {},
'on_start': [('started', )]
}]
ipv8 = IPv8(configuration)
await ipv8.start()
INSTANCES.append(ipv8)
ensure_future(start_communities())
get_event_loop().run_forever()
with open('summary.txt', 'w') as f:
f.write('HOST_NAME ADDRESS REQUESTS RESPONSES')
for key in RESULTS:
hostname, address = key
f.write('\n%s %s:%d %d %d' % (hostname, address[0], address[1], CONST_REQUESTS, len(RESULTS[key])))
with open('walk_rtts.txt', 'w') as f:
f.write('HOST_NAME ADDRESS RTT')
for key in RESULTS:
hostname, address = key
for rtt in RESULTS[key]:
f.write('\n%s %s:%d %f' % (hostname, address[0], address[1], rtt))
| lgpl-3.0 |
biotextmining/processes | src/main/java/com/silicolife/textmining/processes/ir/patentpipeline/components/retrievalmodules/wipo/help/WIPOXMLSAXPHandler.java | 1769 | package com.silicolife.textmining.processes.ir.patentpipeline.components.retrievalmodules.wipo.help;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.silicolife.textmining.core.interfaces.core.document.IPublication;
public class WIPOXMLSAXPHandler extends DefaultHandler{
String tempString;
IPublication pub;
String authors;
public WIPOXMLSAXPHandler(IPublication pub){
this.pub=pub;
}
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException{
//no operation
}
public void endElement(String s, String s1, String element) throws SAXException{
if (element.equalsIgnoreCase("date")){
if (pub.getFulldate()==null||pub.getFulldate().isEmpty()){
pub.setYeardate(tempString);
}
}
if (element.equalsIgnoreCase("invention-title")){
if (pub.getTitle()==null||pub.getTitle().isEmpty()){
pub.setTitle(tempString);
}
}
if (element.equalsIgnoreCase("name")){
if (authors==null||authors.isEmpty()){
//pub.setAuthors(tempString);
authors=tempString;
}
else if(!authors.contains(tempString)){
//pub.setAuthors(pub.getAuthors()+" AND "+tempString);
authors=authors+" AND "+tempString;
}
}
if (element.equalsIgnoreCase("abstract")){
if (pub.getAbstractSection()==null||pub.getAbstractSection().isEmpty()){
pub.setAbstractSection(tempString);
}
}
if (element.equalsIgnoreCase("applicants")){
if (pub.getAuthors()==null||pub.getAuthors().isEmpty()){
pub.setAuthors(authors);
}
}
}
public void characters(char[] ac, int i, int j) throws SAXException {
tempString=new String(ac,i,j);//initialize the string with the correspondent information
}
}
| lgpl-3.0 |
tabuto/j2dgf | src/com/tabuto/j2dgf/Drawable.java | 916 | /**
* @author Francesco di Dio
* Date: 19 Novembre 2010 18.14
* Titolo: Drawable.java
* Versione: 0.6.3 Rev.a:
*/
package com.tabuto.j2dgf;
import java.awt.Graphics;
/**
* Interface <code>Drawable</code> is an abstraction representing something can be draw on a J2DGF package.
*
* @author tabuto83
*
* @version 0.6.3
*
* @see Sprite
*/
public interface Drawable {
/**
* Represent the graphics of the object implements the Drawable interface.
* @param g Graphics
*/
public void drawMe(Graphics g);
/**
* Override this method to implements the routines to move your object
*/
public void move();
/**
* Override this method to implements the actions in order to activate the drawable object
*/
public void Activate();
/**
* Override this method to implements the actions in order to deactivate the drawable object
*/
public void Deactivate();
}
| lgpl-3.0 |
robcowell/dynamicreports | dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/chart/XyChartSerieBuilder.java | 4263 | /**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2012 Ricardo Mariaca
* http://dynamicreports.sourceforge.net
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.report.builder.chart;
import net.sf.dynamicreports.report.base.chart.dataset.DRXyChartSerie;
import net.sf.dynamicreports.report.builder.FieldBuilder;
import net.sf.dynamicreports.report.builder.VariableBuilder;
import net.sf.dynamicreports.report.builder.column.ValueColumnBuilder;
import net.sf.dynamicreports.report.builder.expression.Expressions;
import net.sf.dynamicreports.report.constant.Constants;
import net.sf.dynamicreports.report.definition.expression.DRIExpression;
import org.apache.commons.lang3.Validate;
/**
* @author Ricardo Mariaca ([email protected])
*/
public class XyChartSerieBuilder extends AbstractChartSerieBuilder<XyChartSerieBuilder, DRXyChartSerie> {
private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;
protected XyChartSerieBuilder(ValueColumnBuilder<?, ? extends Number> column) {
super(new DRXyChartSerie());
setYValue(column);
getObject().setLabelExpression(column.getColumn().getTitleExpression());
}
protected XyChartSerieBuilder(FieldBuilder<? extends Number> field) {
super(new DRXyChartSerie());
setYValue(field);
}
protected XyChartSerieBuilder(DRIExpression<? extends Number> valueExpression) {
super(new DRXyChartSerie());
setYValue(valueExpression);
}
protected XyChartSerieBuilder(VariableBuilder<? extends Number> variable) {
super(new DRXyChartSerie());
setYValue(variable);
}
//x
public XyChartSerieBuilder setXValue(ValueColumnBuilder<?, ? extends Number> column) {
Validate.notNull(column, "column must not be null");
getObject().setXValueExpression(column.getColumn());
return this;
}
public XyChartSerieBuilder setXValue(FieldBuilder<? extends Number> field) {
Validate.notNull(field, "field must not be null");
getObject().setXValueExpression(field.build());
return this;
}
public XyChartSerieBuilder setXValue(DRIExpression<? extends Number> valueExpression) {
getObject().setXValueExpression(valueExpression);
return this;
}
public XyChartSerieBuilder setXValue(VariableBuilder<? extends Number> variable) {
Validate.notNull(variable, "variable must not be null");
getObject().setXValueExpression(variable.build());
return this;
}
//y
public XyChartSerieBuilder setYValue(ValueColumnBuilder<?, ? extends Number> column) {
Validate.notNull(column, "column must not be null");
getObject().setYValueExpression(column.getColumn());
return this;
}
public XyChartSerieBuilder setYValue(FieldBuilder<? extends Number> field) {
Validate.notNull(field, "field must not be null");
getObject().setYValueExpression(field.build());
return this;
}
public XyChartSerieBuilder setYValue(DRIExpression<? extends Number> valueExpression) {
getObject().setYValueExpression(valueExpression);
return this;
}
public XyChartSerieBuilder setYValue(VariableBuilder<? extends Number> variable) {
Validate.notNull(variable, "variable must not be null");
getObject().setYValueExpression(variable.build());
return this;
}
//label
public XyChartSerieBuilder setLabel(String label) {
getObject().setLabelExpression(Expressions.text(label));
return this;
}
public XyChartSerieBuilder setLabel(DRIExpression<String> labelExpression) {
getObject().setLabelExpression(labelExpression);
return this;
}
public DRXyChartSerie getChartSerie() {
return build();
}
}
| lgpl-3.0 |
js-works/js-surface | boxroom/archive/js-surface-2018-08-30_before-redesign/src/modules/core/main/api/useRef.ts | 187 | import useState from './useState'
export default function useRef<T>(initialValue?: T): { current: T } {
const [ret] = useState(() => ({ current: initialValue}))
return ret as any
}
| lgpl-3.0 |
dmulloy2/PacketWrapper | PacketWrapper/src/main/java/com/comphenix/packetwrapper/WrapperLoginClientCustomPayload.java | 1806 | /**
* This file is part of PacketWrapper.
* Copyright (C) 2012-2015 Kristian S. Strangeland
* Copyright (C) 2015 dmulloy2
*
* PacketWrapper is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PacketWrapper is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with PacketWrapper. If not, see <http://www.gnu.org/licenses/>.
*/
package com.comphenix.packetwrapper;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
public class WrapperLoginClientCustomPayload extends AbstractPacket {
public static final PacketType TYPE = PacketType.Login.Client.CUSTOM_PAYLOAD;
public WrapperLoginClientCustomPayload() {
super(new PacketContainer(TYPE), TYPE);
handle.getModifier().writeDefaults();
}
public WrapperLoginClientCustomPayload(PacketContainer packet) {
super(packet, TYPE);
}
/**
* Retrieve Message ID.
* <p>
* Notes: should match ID from server.
* @return The current Message ID
*/
public int getMessageId() {
return handle.getIntegers().read(0);
}
/**
* Set Message ID.
* @param value - new value.
*/
public void setMessageId(int value) {
handle.getIntegers().write(0, value);
}
// Cannot find type for b
// Cannot find type for b
}
| lgpl-3.0 |
openbase/jul | pattern/trigger/src/main/java/org/openbase/jul/pattern/trigger/Trigger.java | 1479 |
package org.openbase.jul.pattern.trigger;
/*-
* #%L
* JUL Pattern Trigger
* %%
* Copyright (C) 2015 - 2022 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import org.openbase.jul.exception.NotAvailableException;
import org.openbase.jul.iface.Activatable;
import org.openbase.jul.pattern.Observer;
import org.openbase.type.domotic.state.ActivationStateType;
import org.openbase.type.domotic.state.ActivationStateType.ActivationState;
/**
* @author <a href="mailto:[email protected]">Divine Threepwood</a>
*/
public interface Trigger extends Activatable {
ActivationStateType.ActivationState getActivationState() throws NotAvailableException;
void removeObserver(final Observer<Trigger, ActivationState> observer);
void addObserver(final Observer<Trigger, ActivationState> observer);
}
| lgpl-3.0 |
myd7349/Ongoing-Study | cpp/OpenCV/hand-written-signature-cutter/hand-written-signature-cutter.cpp | 5061 | #include <cstdlib>
#include <iostream>
#include <sstream>
#include <vector>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <tinyfiledialogs/tinyfiledialogs.h>
#include "../../common.h"
namespace
{
bool isInteractiveMode = false;
cv::String GetInputFileName(int argc, char * const argv[])
{
if (argc >= 2)
return argv[1];
const char *patterns[] =
{
"*.bmp",
"*.jpg",
"*.jpeg",
"*.png",
};
return tinyfd_openFileDialog(
"Select the original signature:",
NULL,
ARRAYSIZE(patterns),
patterns,
"Image Files (*.bmp;*.jpg;*.jpeg;*.png)",
0
);
}
cv::String GetOutputFileName(int argc, char * const argv[])
{
if (argc >= 3)
return argv[2];
return tinyfd_saveFileDialog(
"Where to save the processed signature?",
NULL,
0,
NULL,
NULL
);
}
void ShowImage(cv::String title, cv::InputArray image)
{
if (isInteractiveMode)
cv::imshow(title, image);
}
void ShowError(cv::String title, cv::String text)
{
if (isInteractiveMode)
{
tinyfd_messageBox(
title.c_str(),
text.c_str(),
"ok",
"error",
0
);
}
else
{
std::cerr << title << ": " << text << '\n';
}
}
void WaitKey()
{
cv::waitKey();
}
}
int main(int argc, char *argv[])
{
isInteractiveMode = argc < 3;
cv::String inputFile = GetInputFileName(argc, argv);
if (inputFile.empty())
{
ShowError("Error", "Operation cancelled!");
return EXIT_FAILURE;
}
auto rawSignature = cv::imread(inputFile);
if (rawSignature.empty())
{
ShowError("Failed to load original signature", inputFile);
return EXIT_FAILURE;
}
if (isInteractiveMode)
std::atexit(WaitKey);
ShowImage("Source signature", rawSignature);
cv::Mat intermediateImage;
cv::cvtColor(rawSignature, intermediateImage, cv::COLOR_BGR2GRAY);
ShowImage("Gray signature", intermediateImage);
cv::threshold(intermediateImage, intermediateImage, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
ShowImage("Binary signature", intermediateImage);
std::vector<std::vector<cv::Point>> contours;
#if 0
cv::findContours(intermediateImage, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
if (!contours.empty())
contours.pop_back();
#else
cv::bitwise_not(intermediateImage, intermediateImage);
ShowImage("Invert black and white", intermediateImage);
cv::findContours(intermediateImage, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
#endif
cv::Rect boundingBox;
for (decltype(contours)::size_type i = 0; i < contours.size(); ++i)
{
boundingBox |= cv::boundingRect(contours[i]);
std::cout << boundingBox << std::endl;
}
#ifndef NDEBUG
rawSignature.copyTo(intermediateImage);
cv::rectangle(intermediateImage, boundingBox, cv::Scalar(255, 0, 255, 128));
ShowImage("Bounding box", intermediateImage);
#endif
if (!boundingBox.empty())
{
cv::Mat destSignature = rawSignature(boundingBox);
ShowImage("Final", destSignature);
cv::String outputFile = GetOutputFileName(argc, argv);
if (outputFile.empty())
{
ShowError("Error", "Operation cancelled!");
return EXIT_FAILURE;
}
if (!cv::imwrite(outputFile, destSignature))
{
ShowError("Failed to write to the target file", outputFile);
return EXIT_FAILURE;
}
}
return 0;
}
// References:
// https://www.quora.com/How-can-I-detect-an-object-from-static-image-and-crop-it-from-the-image-using-openCV
// https://stackoverflow.com/questions/13538748/crop-black-edges-with-opencv
// https://stackoverflow.com/questions/17141535/how-to-use-the-otsu-threshold-in-opencv
// https://docs.opencv.org/3.1.0/df/d0d/tutorial_find_contours.html
// https://stackoverflow.com/questions/8449378/finding-contours-in-opencv
// https://homepages.inf.ed.ac.uk/rbf/HIPR2/dilate.htm
// https://stackoverflow.com/questions/44383209/how-to-detect-edge-and-crop-an-image-in-python
// https://www.learnopencv.com/filling-holes-in-an-image-using-opencv-python-c/
// https://stackoverflow.com/questions/1716274/fill-the-holes-in-opencv
// https://www.learnopencv.com/filling-holes-in-an-image-using-opencv-python-c/
// https://www.geometrictools.com/Source/ComputationalGeometry.html
// [graphicsmagick how to remove transparent area and shrink the canvas size of a 32-bit image](https://stackoverflow.com/questions/19827613/graphicsmagick-how-to-remove-transparent-area-and-shrink-the-canvas-size-of-a-32)
// > gm convert input.png -trim +repage output.png
| lgpl-3.0 |
georgy404/ardrone_dcs | ardrone_rviz_plugins/src/info_panel/ros_thread_ip.cpp | 2609 | /**
* This file is part of ardrone_dcs.
*
* ros_thread_ip is part of info panel rviz plugin.
* It's provide thread for communicate with ROS system.
*
* Copyright 2016 Georgy Konovalov <[email protected]> (SFEDU)
**/
#include "info_panel/ros_thread_ip.h"
RosThreadIP::RosThreadIP()
{
}
RosThreadIP::~RosThreadIP()
{
if(ros::isStarted()) {
ros::shutdown();
ros::waitForShutdown();
}
thread->wait();
}
bool RosThreadIP::init()
{
thread = new QThread();
this->moveToThread(thread);
connect(thread, SIGNAL(started()), this, SLOT(run()));
nh = new ros::NodeHandle();
if (!ros::master::check())
return false;
ros::start();
ros::Time::init();
// Init subscribe
mode_sub = nh->subscribe("/ardrone/mode", 10, &RosThreadIP::ModeCallback, this);
navdata_sub = nh->subscribe("/ardrone/navdata", 10, &RosThreadIP::NavDataCallback, this);
imu_sub = nh->subscribe("/ardrone/imu", 10, &RosThreadIP::ImuCallback, this);
thread->start();
return true;
}
// --- ROS subscribe functions
void RosThreadIP::ModeCallback(const ardrone_msgs::Mode::ConstPtr &msg)
{
QString modeStr;
if(msg->mode == ardrone_msgs::Mode::MODE_MANUAL)
modeStr = "Manual";
else // (msg->mode == ardrone_msgs::Mode::MODE_AUTO)
modeStr = "Auto";
emit receiveMode(modeStr);
}
void RosThreadIP::NavDataCallback(const ardrone_autonomy::Navdata::ConstPtr &msg)
{
emit receiveNavData(msg->batteryPercent, msg->vx/1000.0, msg->vy/1000.0, msg->vz/1000.0);
emit receivedDroneState(msg->state);
}
void RosThreadIP::ImuCallback(const sensor_msgs::Imu::ConstPtr &msg)
{
emit receiveImu(msg->angular_velocity.z);
}
// --- Tf listener functions
void RosThreadIP::ListenTFTransform()
{
double x, y, z;
double roll, pitch, yaw;
tf::StampedTransform transform;
try {
tf_pose_listener.lookupTransform("odom", "base_link", ros::Time(0), transform);
// get pose
x = transform.getOrigin().x();
y = transform.getOrigin().y();
z = transform.getOrigin().z();
// get angles
tf::Matrix3x3 m(transform.getRotation());
m.getRPY(roll, pitch, yaw);
}
catch (tf::TransformException ex) {
std::cerr.flush();
std::cerr << ex.what() << std::endl;
ros::Duration(1.0).sleep();
}
emit receiveCoords(x, y, z, yaw);
}
// --- ROS thread function
void RosThreadIP::run()
{
ros::Rate rate(10);
while (ros::ok()) {
ListenTFTransform();
ros::spinOnce();
rate.sleep();
}
}
| lgpl-3.0 |
happyprg/elasticsearch_sample | src/test/java/io/searchbox/core/search/facet/TermsFacetIntegrationTest.java | 3297 | package io.searchbox.core.search.facet;
import io.searchbox.client.JestResult;
import io.searchbox.common.AbstractIntegrationTest;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.facet.FacetBuilders;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
/**
* @author ferhat
*/
@ElasticsearchIntegrationTest.ClusterScope(scope = ElasticsearchIntegrationTest.Scope.SUITE, numNodes = 1)
public class TermsFacetIntegrationTest extends AbstractIntegrationTest {
@Test
public void testQuery() throws IOException {
createIndex("terms_facet");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.facet(FacetBuilders.termsFacet("tag").field("tag").size(10)).facet(FacetBuilders.termsFacet("user").field("user").size(10));
String query = searchSourceBuilder.toString();
for (int i = 0; i < 2; i++) {
Index index = new Index.Builder("{\"tag\":\"value\", \"user\":\"root\"}")
.index("terms_facet")
.type("document")
.refresh(true)
.build();
client.execute(index);
}
Index index = new Index.Builder("{\"tag\":\"test\", \"user\":\"none\"}")
.index("terms_facet")
.type("document")
.refresh(true)
.build();
client.execute(index);
Search search = (Search) new Search.Builder(query)
.addIndex("terms_facet")
.addType("document")
.build();
JestResult result = client.execute(search);
List<TermsFacet> termsFacets = result.getFacets(TermsFacet.class);
assertEquals(2, termsFacets.size());
TermsFacet termsFacetFirst = termsFacets.get(0);
assertEquals("tag", termsFacetFirst.getName());
assertTrue(3L == termsFacetFirst.getTotal());
assertTrue(0L == termsFacetFirst.getMissing());
assertTrue(0L == termsFacetFirst.getOther());
assertTrue(termsFacetFirst.terms().size() == 2);
assertEquals("value", termsFacetFirst.terms().get(0).getName());
assertTrue(2 == termsFacetFirst.terms().get(0).getCount());
assertEquals("test", termsFacetFirst.terms().get(1).getName());
assertTrue(1 == termsFacetFirst.terms().get(1).getCount());
TermsFacet termsFacetSecond = termsFacets.get(1);
assertEquals("user", termsFacetSecond.getName());
assertTrue(3L == termsFacetSecond.getTotal());
assertTrue(0L == termsFacetSecond.getMissing());
assertTrue(0L == termsFacetSecond.getOther());
assertTrue(termsFacetSecond.terms().size() == 2);
assertEquals("root", termsFacetSecond.terms().get(0).getName());
assertTrue(2 == termsFacetSecond.terms().get(0).getCount());
assertEquals("none", termsFacetSecond.terms().get(1).getName());
assertTrue(1 == termsFacetSecond.terms().get(1).getCount());
}
}
| lgpl-3.0 |
philjord/jnif | jnif/src/nif/compound/NifByteColor4.java | 821 | package nif.compound;
import java.io.IOException;
import java.nio.ByteBuffer;
import nif.ByteConvert;
public class NifByteColor4
{
/**
* <compound name="ByteColor4">
<add name="r" type="byte">Red color component.</add>
<add name="g" type="byte">Green color component.</add>
<add name="b" type="byte">Blue color component.</add>
<add name="a" type="byte">Alpha color component.</add>
</compound>
*/
public byte r;
public byte g;
public byte b;
public byte a;
public NifByteColor4(ByteBuffer stream) throws IOException
{
r = ByteConvert.readByte(stream);
g = ByteConvert.readByte(stream);
b = ByteConvert.readByte(stream);
a = ByteConvert.readByte(stream);
}
public String toString()
{
return "[NPByteColor4]" + r + " " + g + " " + b;
}
}
| lgpl-3.0 |
dtmoodie/FCVMLT | subprojects/dicomLoader/imebra/src/dataHandlerStringDS.cpp | 5137 | /*
Imebra 2011 build 2013-09-04_11-02-26
Imebra: a C++ Dicom library
Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 by Paolo Brandoli/Binarno s.p.
All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-------------------
If you want to use Imebra commercially then you have to buy the commercial
support available at http://imebra.com
After you buy the commercial support then you can use Imebra according
to the terms described in the Imebra Commercial License Version 1.
A copy of the Imebra Commercial License Version 1 is available in the
documentation pages.
Imebra is available at http://imebra.com
The author can be contacted by email at [email protected] or by mail at
the following address:
Paolo Brandoli
Rakuseva 14
1000 Ljubljana
Slovenia
*/
/*! \file dataHandlerStringDS.cpp
\brief Implementation of the class dataHandlerStringDS.
*/
#include <sstream>
#include <iomanip>
#include "../../base/include/exception.h"
#include "../include/dataHandlerStringDS.h"
namespace puntoexe
{
namespace imebra
{
namespace handlers
{
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
//
// dataHandlerStringDS
//
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Get the value as a signed long.
// Overwritten to use getDouble()
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
imbxInt32 dataHandlerStringDS::getSignedLong(const imbxUint32 index) const
{
PUNTOEXE_FUNCTION_START(L"dataHandlerStringDS::getSignedLong");
return (imbxInt32)getDouble(index);
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Get the value as an unsigned long.
// Overwritten to use getDouble()
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
imbxUint32 dataHandlerStringDS::getUnsignedLong(const imbxUint32 index) const
{
PUNTOEXE_FUNCTION_START(L"dataHandlerStringDS::getUnsignedLong");
return (imbxInt32)getDouble(index);
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Set the value as a signed long.
// Overwritten to use setDouble()
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerStringDS::setSignedLong(const imbxUint32 index, const imbxInt32 value)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerStringDS::setSignedLong");
setDouble(index, (double)value);
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Set the value as an unsigned long.
// Overwritten to use setDouble()
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerStringDS::setUnsignedLong(const imbxUint32 index, const imbxUint32 value)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerStringDS::setUnsignedLong");
setDouble(index, (double)value);
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Overwrite setDouble so the value is written in the
// exponential form if needed
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerStringDS::setDouble(const imbxUint32 index, const double value)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerStringDS::setDouble");
std::wostringstream convStream;
convStream << value;
setUnicodeString(index, convStream.str());
PUNTOEXE_FUNCTION_END();
}
imbxUint8 dataHandlerStringDS::getPaddingByte() const
{
return 0x20;
}
imbxUint32 dataHandlerStringDS::getUnitSize() const
{
return 0;
}
imbxUint32 dataHandlerStringDS::maxSize() const
{
return 16;
}
} // namespace handlers
} // namespace imebra
} // namespace puntoexe
| lgpl-3.0 |
sevoan/EmployeeList | employeedialog.cpp | 10981 | #include <QDebug>
#include <QSpinBox>
#include <QComboBox>
#include <QLineEdit>
#include <QPushButton>
#include <QTableWidget>
#include <QDialogButtonBox>
#include <algorithm>
#include "ui_employeedialog.h"
#include "formvalidator.h"
#include "employeedialog_p.h"
#include "employeedialog.h"
#include "weekloaddialog.h"
#include "formvalidatorrules.h"
#include "nationality.h"
#include "employee.h"
#define LOAD_FIRST_COLUMN_WIDTH 250
Q_DECLARE_METATYPE(Gender)
Q_DECLARE_METATYPE(WeekLoad)
Q_DECLARE_METATYPE(Nationality)
Q_DECLARE_METATYPE(PositionType)
EmployeeDialogPrivate::EmployeeDialogPrivate(EmployeeDialog* qq) :
q_ptr(qq),
employeeManager(Q_NULLPTR),
nationalityManager(Q_NULLPTR),
weekLoadDialog(new WeekLoadDialog(qq)),
formValidator(new FormValidator())
{
connect(weekLoadDialog.data(), &WeekLoadDialog::addWeekLoad,
this, &EmployeeDialogPrivate::addWeekLoad);
}
EmployeeDialogPrivate::~EmployeeDialogPrivate()
{
}
void EmployeeDialogPrivate::init()
{
Q_Q(EmployeeDialog);
connect(q, &EmployeeDialog::rejected, this, &EmployeeDialogPrivate::resetFields);
auto ui = q->ui;
// Setup line edit rules
auto lineEditRules = FormValidatorRules::lineEditRules();
auto comboBoxRules = FormValidatorRules::comboBoxRules();
formValidator->appendView(ui->nameEdit, lineEditRules);
formValidator->appendView(ui->positionNameEdit, lineEditRules);
formValidator->appendView(ui->educationEdit, lineEditRules);
formValidator->appendView(ui->specializationEdit, lineEditRules);
// Setup combobox
formValidator->appendView(ui->nationalityBox, comboBoxRules);
// Begin validate
formValidator->startValidation();
}
void EmployeeDialogPrivate::initFieldsByDefault()
{
Q_Q(EmployeeDialog);
auto ui = q->ui;
ui->genderBox->addItem(GenderString(Gender::Male), QVariant::fromValue(Gender::Male));
ui->genderBox->addItem(GenderString(Gender::Female), QVariant::fromValue(Gender::Female));
if (nationalityManager != Q_NULLPTR) {
auto nationalities = nationalityManager->nationalities();
if (nationalities.isEmpty())
qDebug() << "Warning here's no nationalities";
for (const Nationality& nationality : nationalities)
ui->nationalityBox->addItem(nationality.value(),
QVariant::fromValue(nationality));
} else {
qDebug() << "Please provide natinality manager to EmployeeDialog";
}
ui->positionTypeBox->addItem(PositionTypeString(PositionType::Primary),
QVariant::fromValue(PositionType::Primary));
ui->positionTypeBox->addItem(PositionTypeString(PositionType::Secondary),
QVariant::fromValue(PositionType::Secondary));
ui->birthYearEdit->setValue(ui->birthYearEdit->minimum());
ui->experienceEdit->setValue(ui->experienceEdit->minimum());
ui->worksFromYearEdit->setValue(ui->worksFromYearEdit->minimum());
}
void EmployeeDialogPrivate::resetFields()
{
Q_Q(EmployeeDialog);
auto ui = q->ui;
formValidator->stopValidation();
ui->idBox->setValue(-1);
ui->nameEdit->clear();
ui->birthYearEdit->clear();
ui->genderBox->clear();
ui->nationalityBox->clear();
ui->positionNameEdit->clear();
ui->educationEdit->clear();
ui->specializationEdit->clear();
ui->positionTypeBox->clear();
ui->experienceEdit->clear();
ui->worksFromYearEdit->clear();
ui->teachesEdit->clear();
ui->studingInAbsentiaEdit->clear();
ui->retrainingInformationEdit->clear();
ui->conclusionsEdit->clear();
// Reset week load table
int weekLoadRowCount = ui->weekLoadsTable->rowCount();
while (weekLoadRowCount--)
ui->weekLoadsTable->removeRow(weekLoadRowCount);
formValidator->startValidation();
}
Employee EmployeeDialogPrivate::mapEmployeeInputs()
{
Q_Q(EmployeeDialog);
auto ui = q->ui;
Employee employee;
employee.setId(ui->idBox->value());
employee.setName(ui->nameEdit->text());
employee.setBirthYear(ui->birthYearEdit->value());
auto gender = ui->genderBox->currentData().value<Gender>();
employee.setGender(gender);
auto nationality = ui->nationalityBox->currentData().value<Nationality>();
employee.setNationality(nationality);
employee.setPositionName(ui->positionNameEdit->text());
employee.setEducation(ui->educationEdit->text());
employee.setSpecialization(ui->specializationEdit->text());
auto positionType = ui->positionTypeBox->currentData().value<PositionType>();
employee.setPositionType(positionType);
employee.setExperience(ui->experienceEdit->value());
employee.setWorksFromYear(ui->worksFromYearEdit->value());
employee.setTeaches(ui->teachesEdit->text());
employee.setStudingInAbsentia(ui->studingInAbsentiaEdit->text());
employee.setRetrainingInfo(ui->retrainingInformationEdit->text());
employee.setConclusions(ui->conclusionsEdit->text());
// Load employee week load from table widget
QVector<WeekLoad> weekLoadList;
for (int rowIndex = 0; rowIndex < ui->weekLoadsTable->rowCount(); ++rowIndex) {
auto subjectItem = ui->weekLoadsTable->item(rowIndex, 0);
weekLoadList << subjectItem->data(Qt::UserRole).value<WeekLoad>();
}
employee.setWeekLoads(weekLoadList);
return employee;
}
template<class T>
void EmployeeDialogPrivate::setComboboxActiveData(QComboBox* comboBox, T data)
{
int count = comboBox->count();
for (int index = 0; index < count; ++index) {
QVariant underlyingData = comboBox->itemData(index);
if (underlyingData.value<T>() == data) {
comboBox->setCurrentIndex(index);
return;
}
}
}
void EmployeeDialogPrivate::saveOrUpdate()
{
Q_Q(EmployeeDialog);
bool valid = formValidator->validateAll();
if (!valid)
return;
if (employeeManager == Q_NULLPTR) {
qDebug() << "employee manager isn't set";
return;
}
Employee employee = mapEmployeeInputs();
if (dialogType == Type::ADD)
employeeManager->appendEmployee(employee);
else if (dialogType == Type::EDIT)
employeeManager->updateEmployee(employee);
q->hide();
}
void EmployeeDialogPrivate::showWeekLoadDialog()
{
weekLoadDialog->show();
}
void EmployeeDialogPrivate::addWeekLoad(const WeekLoad& load)
{
Q_Q(EmployeeDialog);
auto ui = q->ui;
// Put values directly to table widget model
QTableWidgetItem* subjectName = new QTableWidgetItem(load.subject());
QTableWidgetItem* class1_4 = new QTableWidgetItem(QString::number(load.class1_4()));
QTableWidgetItem* class5_9 = new QTableWidgetItem(QString::number(load.class5_9()));
QTableWidgetItem* class10_11 = new QTableWidgetItem(QString::number(load.class10_11()));
class1_4->setTextAlignment(Qt::AlignCenter);
class5_9->setTextAlignment(Qt::AlignCenter);
class10_11->setTextAlignment(Qt::AlignCenter);
int newRowIndex = ui->weekLoadsTable->rowCount();
ui->weekLoadsTable->insertRow(newRowIndex);
ui->weekLoadsTable->setItem(newRowIndex, 0, subjectName);
ui->weekLoadsTable->setItem(newRowIndex, 1, class1_4);
ui->weekLoadsTable->setItem(newRowIndex, 2, class5_9);
ui->weekLoadsTable->setItem(newRowIndex, 3, class10_11);
// Save entire model in first column
subjectName->setData(Qt::UserRole, QVariant::fromValue(load));
}
void EmployeeDialogPrivate::removeSelectedWeekLoad()
{
Q_Q(EmployeeDialog);
auto ui = q->ui;
QVector<int> sortedIndices;
auto selectedIndices = ui->weekLoadsTable->selectionModel()->selectedRows();
for (auto index : selectedIndices)
sortedIndices << index.row();
std::sort(sortedIndices.begin(), sortedIndices.end(), std::less<int>());
int index = sortedIndices.size();
while (index--) {
int rowIndexToRemove = sortedIndices.at(index);
ui->weekLoadsTable->removeRow(rowIndexToRemove);
}
}
EmployeeDialog::EmployeeDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::EmployeeDialog),
d_ptr(new EmployeeDialogPrivate(this))
{
Q_D(EmployeeDialog);
ui->setupUi(this);
connect(ui->resultButtons, &QDialogButtonBox::accepted,
d, &EmployeeDialogPrivate::saveOrUpdate);
// Register signals here because dialog ui can't connect directly to D-Pointer slots
connect(ui->addLoadButton, &QPushButton::clicked,
d, &EmployeeDialogPrivate::showWeekLoadDialog);
connect(ui->removeLoadButton, &QPushButton::clicked,
d, &EmployeeDialogPrivate::removeSelectedWeekLoad);
QStringList weekLoadLabels;
weekLoadLabels << tr("Subject") << tr("1-4") << tr("5-9") << tr("10-11");
ui->weekLoadsTable->setHorizontalHeaderLabels(weekLoadLabels);
ui->weekLoadsTable->setColumnWidth(0, LOAD_FIRST_COLUMN_WIDTH);
d->init();
}
EmployeeDialog::~EmployeeDialog()
{
delete ui;
delete d_ptr;
}
void EmployeeDialog::setEmployeeManager(EmployeeManager* manager)
{
Q_D(EmployeeDialog);
d->employeeManager = manager;
}
void EmployeeDialog::show()
{
QWidget::show();
ui->nameEdit->setFocus();
}
void EmployeeDialog::hide()
{
Q_D(EmployeeDialog);
d->resetFields();
QDialog::hide();
}
void EmployeeDialog::setNationalityManager(NationalityManager* manager)
{
Q_D(EmployeeDialog);
d->nationalityManager = manager;
}
void EmployeeDialog::showAddEmployee()
{
Q_D(EmployeeDialog);
d->initFieldsByDefault();
setWindowTitle(tr("Add employee"));
d->dialogType = EmployeeDialogPrivate::Type::ADD;
QDialog::show();
}
void EmployeeDialog::showEditEmployee(const Employee& employee)
{
Q_D(EmployeeDialog);
d->initFieldsByDefault();
d->dialogType = EmployeeDialogPrivate::Type::EDIT;
setWindowTitle(tr("Edit employee"));
ui->idBox->setValue(employee.id());
ui->nameEdit->setText(employee.name());
ui->birthYearEdit->setValue(employee.birthYear());
// Gender
d->setComboboxActiveData(ui->genderBox, employee.gender());
// Nationality
d->setComboboxActiveData(ui->nationalityBox, employee.nationality());
ui->positionNameEdit->setText(employee.positionName());
ui->educationEdit->setText(employee.education());
ui->specializationEdit->setText(employee.specialization());
// Position type
d->setComboboxActiveData(ui->positionTypeBox, employee.positionType());
ui->experienceEdit->setValue(employee.experience());
ui->worksFromYearEdit->setValue(employee.worksFromYear());
ui->teachesEdit->setText(employee.teaches());
ui->studingInAbsentiaEdit->setText(employee.studingInAbsentia());
ui->retrainingInformationEdit->setText(employee.retrainingInformation());
ui->conclusionsEdit->setText(employee.conclusions());
for (auto weekLoad : employee.weekLoads())
d->addWeekLoad(weekLoad);
QDialog::show();
}
| lgpl-3.0 |
jeyboy/rubyn | tools/html/html_selector.cpp | 7970 | #include "html_selector.h"
#include "html_tag.h"
#include <qdebug.h>
using namespace Html;
const QHash<QByteArray, QByteArray> Selector::attr_predifinitions = QHash<QByteArray, QByteArray>{
{"text", HTML_ATTR_TYPE}, {"submit", HTML_ATTR_TYPE}, {"reset", HTML_ATTR_TYPE}, {"radio", HTML_ATTR_TYPE},
{"password", HTML_ATTR_TYPE}, {"image", HTML_ATTR_TYPE}, {"hidden", HTML_ATTR_TYPE}, {"file", HTML_ATTR_TYPE},
{"checkbox", HTML_ATTR_TYPE}, {"button", HTML_ATTR_TYPE}, {"week", HTML_ATTR_TYPE}, {"month", HTML_ATTR_TYPE},
{"url", HTML_ATTR_TYPE}, {"time", HTML_ATTR_TYPE}, {"tel", HTML_ATTR_TYPE}, {"search", HTML_ATTR_TYPE},
{"range", HTML_ATTR_TYPE}, {"number", HTML_ATTR_TYPE}, {"email", HTML_ATTR_TYPE}, {"datetime-local", HTML_ATTR_TYPE},
{"datetime", HTML_ATTR_TYPE}, {"date", HTML_ATTR_TYPE}, {"color", HTML_ATTR_TYPE}
};
bool Selector::addPredicate(const SState & state, const QByteArray & token) {
switch(state) {
case st_tag: { _token_id = Tag::tagID(token.toLower(), false); break;}
case st_id: { _attrs.insert(attr_id, QPair<char, QByteArray>(sel_attr_eq, token)); break; }
case st_class: { SELECTOR_PROCEED_CLASSES(sel_attr_eq, token); break;}
case st_attr_type: {
bool ok;
int level = token.toInt(&ok, 10);
if (ok)
pos_limit = level - 1; //INFO: convert to zero based index
else {
QByteArray lower_token = token.toLower();
if (attr_predifinitions.contains(lower_token))
_attrs.insert(attr_predifinitions[lower_token], QPair<char, QByteArray>(sel_attr_eq, lower_token));
else
_attrs.insert(lower_token, QPair<char, QByteArray>(sel_attr_eq, tkn_any_elem));
}
break;}
default: return false;
}
return true;
}
void Selector::addAttr(const QByteArray & name, const QByteArray & val, const char & rel) {
if (val.isEmpty()) {
_attrs.insert(name.toLower(), QPair<char, QByteArray>(sel_attr_eq, tkn_any_elem));
} else {
QByteArray lower_name = name.toLower();
if (lower_name == attr_class) {
SELECTOR_PROCEED_CLASSES(rel, val);
} else
_attrs.insert(lower_name, QPair<char, QByteArray>(rel, val));
}
}
Selector::Selector(const STurn & turn, Selector * prev)
: _token_id(Tag::tg_any), turn(turn), pos_limit(-1), prev(prev), next(0), has_error(false), error(0)
{
if (prev) prev -> next = this;
}
Selector::Selector(const char * predicate) : _token_id(Tag::tg_any), turn(any),
pos_limit(-1), prev(0), next(0), has_error(false), error(0)
{
SState state = st_tag;
Selector * selector = this;
const char * pdata = predicate, * stoken = pdata, * etoken = 0, * rel = 0, * sval = 0;
bool in_attr = false;
while(*pdata) {
switch(state) {
case st_in_name: {
if (*stoken == *pdata && *(pdata - 1) != '\\') {
state = st_attr;
stoken++; etoken = pdata;
}
break;}
case st_in_val: {
if (*sval == *pdata && *(pdata - 1) != '\\') {
sval++;
SELECTOR_ADD_ATTR(0);
state = st_attr;
}
break;}
default: {
switch(*pdata) {
case sel_id_token:
case sel_class_token: {
SELECTOR_ADD_PREDICATE(pdata + 1)
state = (SState)*pdata;
break;}
case sel_attr_match2:{
if (!in_attr)
goto continue_mark;
}
case sel_attr_eq:
case sel_attr_begin:
case sel_attr_begin2:
case sel_attr_end:
case sel_attr_not: {
attr_rel_mark:
state = st_attr_value;
if (!etoken) // if name surrounded by quotes we should ignore this etoken
etoken = pdata;
rel = pdata;
sval = pdata + 1;
break;}
case sel_attr_token_end: {
in_attr = false;
SELECTOR_ADD_ATTR(pdata + 1);
state = st_tag;
break;}
case sel_attr_token: {
in_attr = true;
rel = 0;
SELECTOR_ADD_PREDICATE(pdata + 1)
state = st_attr;
break;}
case sel_attr_type_token: {
if (!in_attr) {
SELECTOR_ADD_PREDICATE(pdata + 1)
state = (SState)*pdata;
}
break;}
case sel_cont1_token:
case sel_cont2_token: {
if (!in_attr)
SELECTOR_PARSE_ERROR(LSTR("quotas is not possible outside of attrs"));
if (state == st_attr_value)
state = st_in_val;
else
state = st_in_name;
break;}
case sel_rel_any: {
if (*(pdata + 1) != sel_rel_any) { // ignore multiple spaces
if (in_attr) {
SELECTOR_ADD_ATTR(pdata + 1);
state = st_attr;
} else {
SELECTOR_ADD_PREDICATE(pdata + 1);
if (!rel) {
selector = new Selector((STurn)*pdata, selector);
rel = pdata;
}
state = st_tag;
}
}
break;}
case sel_rel_prev_sibling: {
if (state != st_tag || (state == st_tag && (*(pdata - 1) != sel_rel_any || *(pdata + 1) != sel_rel_any)))
goto continue_mark;
}
case sel_rel_attr_match: {
if (in_attr)
goto attr_rel_mark;
}
case sel_rel_prev_parent:
case sel_rel_next_sibling:
case sel_rel_parent: {
if (!in_attr) {
if (!rel && selector -> prev) // if (!rel)
selector = new Selector((STurn)*pdata, selector);
else if (!rel || *rel == sel_rel_any)
selector -> turn = (STurn)*pdata;
else
SELECTOR_PARSE_ERROR(LSTR("couple of relations inputed: ") % *pdata);
rel = pdata;
stoken = pdata + 1;
state = st_tag;
}
else SELECTOR_PARSE_ERROR(LSTR("incorrect relation in attributes: ") % *pdata);
break;}
case sel_attr_separator: {
// selector = new Selector(selector -> turn, selector -> prev);
// stoken = pdata + 1;
// state = st_tag;
SELECTOR_PARSE_ERROR(LSTR("incorrect relation: ") % *pdata);
break;}
default:;
}
}
}
continue_mark:
pdata++;
}
SELECTOR_ADD_PREDICATE(0);
}
| lgpl-3.0 |
blowfishpro/B9PartSwitch | B9PartSwitch/PartSwitch/PartModifiers/AttachNodeMover.cs | 3439 | using System;
using UnityEngine;
namespace B9PartSwitch.PartSwitch.PartModifiers
{
public class AttachNodeMover : PartModifierBase, IPartAspectLock
{
public readonly AttachNode attachNode;
private readonly Vector3 position;
private readonly ILinearScaleProvider linearScaleProvider;
public AttachNodeMover(AttachNode attachNode, Vector3 position, ILinearScaleProvider linearScaleProvider)
{
attachNode.ThrowIfNullArgument(nameof(attachNode));
linearScaleProvider.ThrowIfNullArgument(nameof(linearScaleProvider));
this.attachNode = attachNode;
this.position = position;
this.linearScaleProvider = linearScaleProvider;
}
public object PartAspectLock => attachNode.id + "---position";
public override string Description => $"attach node '{attachNode.id}' position";
public override void ActivateOnStartEditor() => SetAttachNodePosition();
public override void ActivateOnStartFlight() => SetAttachNodePosition();
// TweakScale resets node positions, therefore we need to wait a frame and fix them
public override void ActivateOnStartFinishedEditor() => SetAttachNodePosition();
public override void ActivateOnStartFinishedFlight() => SetAttachNodePosition();
public override void ActivateOnSwitchEditor() => SetAttachNodePositionAndMoveParts();
public override void ActivateOnSwitchFlight() => SetAttachNodePosition();
public override void DeactivateOnSwitchEditor() => UnsetAttachNodePositionAndMoveParts();
public override void DeactivateOnSwitchFlight() => UnsetAttachNodePosition();
private void SetAttachNodePositionAndMoveParts()
{
Vector3 offset = (position * linearScaleProvider.LinearScale) - attachNode.position;
SetAttachNodePosition();
if (!HighLogic.LoadedSceneIsEditor) return;
if (attachNode.owner.parent != null && attachNode.owner.parent == attachNode.attachedPart)
{
offset = attachNode.owner.transform.localRotation * offset;
attachNode.owner.transform.localPosition -= offset;
}
else if (attachNode.attachedPart != null)
{
attachNode.attachedPart.transform.localPosition += offset;
}
}
private void UnsetAttachNodePositionAndMoveParts()
{
Vector3 offset = (attachNode.originalPosition * linearScaleProvider.LinearScale) - attachNode.position;
UnsetAttachNodePosition();
if (!HighLogic.LoadedSceneIsEditor) return;
if (attachNode.owner.parent != null && attachNode.owner.parent == attachNode.attachedPart)
{
offset = attachNode.owner.transform.localRotation * offset;
attachNode.owner.transform.localPosition -= offset;
}
else if (attachNode.attachedPart != null)
{
attachNode.attachedPart.transform.localPosition += offset;
}
}
private void SetAttachNodePosition()
{
attachNode.position = position * linearScaleProvider.LinearScale;
}
private void UnsetAttachNodePosition()
{
attachNode.position = attachNode.originalPosition * linearScaleProvider.LinearScale;
}
}
}
| lgpl-3.0 |
AtomicBlom/RobotPlates | src/main/java/net/binaryvibrance/robotplates/program/instructionset/action/ActionDetectPlayer.java | 2751 | package net.binaryvibrance.robotplates.program.instructionset.action;
import net.binaryvibrance.robotplates.api.programming.IHaveInstructions;
import net.binaryvibrance.robotplates.api.programming.IInstruction;
import net.binaryvibrance.robotplates.entity.BaseRobotPlatesEntityRobot;
import net.binaryvibrance.robotplates.program.ProgramState;
import net.minecraft.command.IEntitySelector;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import java.util.*;
public class ActionDetectPlayer implements IInstruction, IHaveInstructions {
private Iterator<EntityPlayer> iterator;
private List<IInstruction> instructions;
public ActionDetectPlayer() {
instructions = new LinkedList<IInstruction>();
}
@Override
public List<IInstruction> execute(ProgramState state) {
BaseRobotPlatesEntityRobot robot = state.getRobot();
World world = state.getWorld();
int range = robot.getDetectionRange();
AxisAlignedBB boundingBox = AxisAlignedBB.getBoundingBox(
robot.posX - range, robot.posY - range, robot.posZ - range,
robot.posX + range, robot.posY + range, robot.posZ + range);
IEntitySelector selector = new IEntitySelector() {
@Override
public boolean isEntityApplicable(Entity entity) {
return entity instanceof EntityPlayer;
}
};
final Vec3 robotLocation = Vec3.createVectorHelper(robot.posX, robot.posY, robot.posZ);
TreeSet<EntityPlayer> list = new TreeSet<EntityPlayer>(new Comparator<EntityPlayer>() {
@Override
public int compare(EntityPlayer entity, EntityPlayer entity2) {
Vec3 entity1Pos = Vec3.createVectorHelper(entity.posX, entity.posY, entity.posZ);
Vec3 entity2Pos = Vec3.createVectorHelper(entity2.posX, entity2.posY, entity2.posZ);
double entity1Distance = robotLocation.distanceTo(entity1Pos);
double entity2Distance = robotLocation.distanceTo(entity2Pos);
if (entity1Distance < entity2Distance) {
return -1;
} else if (entity1Distance > entity2Distance) {
return 1;
}
return 0;
}
});
//FIXME: Correct for square bounding box, verify against sphere.
List entities = world.getEntitiesWithinAABBExcludingEntity(robot, boundingBox, selector);
if (entities != null) {
for (Object o : entities) {
if (o instanceof EntityPlayer) {
list.add((EntityPlayer) o);
}
}
}
iterator = list.iterator();
if (iterator.hasNext()) {
state.setState(EntityPlayer.class, iterator.next());
} else {
state.removeState(EntityPlayer.class);
}
return instructions;
}
@Override
public void addInstruction(IInstruction instruction) {
instructions.add(instruction);
}
}
| lgpl-3.0 |
B3Partners/b3p-commons-csw | src/main/jaxb/jaxb-ri-20090708/lib/jaxb-impl.src/com/sun/xml/bind/v2/runtime/AssociationMap.java | 5129 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.bind.v2.runtime;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
/**
* Bi-directional map between elements, inner peers,
* and outer peers.
*
* <p>
* TODO: this should be rewritten for efficiency.
*
* @since 2.0
*
* @author
* Kohsuke Kawaguchi ([email protected])
*/
public final class AssociationMap<XmlNode> {
final static class Entry<XmlNode> {
/** XML element. */
private XmlNode element;
/** inner peer, or null. */
private Object inner;
/** outer peer, or null. */
private Object outer;
public XmlNode element() {
return element;
}
public Object inner() {
return inner;
}
public Object outer() {
return outer;
}
}
private final Map<XmlNode,Entry<XmlNode>> byElement = new IdentityHashMap<XmlNode,Entry<XmlNode>>();
private final Map<Object,Entry<XmlNode>> byPeer = new IdentityHashMap<Object,Entry<XmlNode>>();
private final Set<XmlNode> usedNodes = new HashSet<XmlNode>();
/** Records the new element<->inner peer association. */
public void addInner( XmlNode element, Object inner ) {
Entry<XmlNode> e = byElement.get(element);
if(e!=null) {
if(e.inner!=null)
byPeer.remove(e.inner);
e.inner = inner;
} else {
e = new Entry<XmlNode>();
e.element = element;
e.inner = inner;
}
byElement.put(element,e);
Entry<XmlNode> old = byPeer.put(inner,e);
if(old!=null) {
if(old.outer!=null)
byPeer.remove(old.outer);
if(old.element!=null)
byElement.remove(old.element);
}
}
/** Records the new element<->outer peer association. */
public void addOuter( XmlNode element, Object outer ) {
Entry<XmlNode> e = byElement.get(element);
if(e!=null) {
if(e.outer!=null)
byPeer.remove(e.outer);
e.outer = outer;
} else {
e = new Entry<XmlNode>();
e.element = element;
e.outer = outer;
}
byElement.put(element,e);
Entry<XmlNode> old = byPeer.put(outer,e);
if(old!=null) {
old.outer=null;
if(old.inner==null)
// remove this entry
byElement.remove(old.element);
}
}
public void addUsed( XmlNode n ) {
usedNodes.add(n);
}
public Entry<XmlNode> byElement( Object e ) {
return byElement.get(e);
}
public Entry<XmlNode> byPeer( Object o ) {
return byPeer.get(o);
}
public Object getInnerPeer( XmlNode element ) {
Entry e = byElement(element);
if(e==null) return null;
else return e.inner;
}
public Object getOuterPeer( XmlNode element ) {
Entry e = byElement(element);
if(e==null) return null;
else return e.outer;
}
}
| lgpl-3.0 |
jmwright/cadquery-freecad-module | ThirdParty/cqparts/display/web.py | 6725 |
import os
import sys
import inspect
import tempfile
import shutil
import jinja2
import time
# web content
if sys.version_info[0] >= 3:
# python 3.x
import http.server as SimpleHTTPServer
import socketserver as SocketServer
else:
# python 2.x
import SimpleHTTPServer
import SocketServer
import threading
import webbrowser
import logging
log = logging.getLogger(__name__)
from ..utils import working_dir
from .environment import map_environment, DisplayEnvironment
# Get this file's location
_this_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# Set template web-content directory
# note: can be changed prior to calling web_display()
#
# >>> from cqparts.display import web
# >>> web.TEMPLATE_CONTENT_DIR = './my/alternative/template'
# >>> web.web_display(some_thing)
#
# This would typically be used for testing, or development purposes.
TEMPLATE_CONTENT_DIR = os.path.join(_this_path, 'web-template')
SocketServer.TCPServer.allow_reuse_address = True # stops crash on re-use of port
@map_environment(
# named 'cmdline'?
# This is a fallback display environment if no other method is available.
# Therefore it's assumed that the environment that's been detected is a
# no-frills command line.
name='cmdline',
order=99,
condition=lambda: True, # fallback
)
class WebDisplayEnv(DisplayEnvironment):
"""
Display given component in a browser window
This display exports the model, then exposes a http service on *localhost*
for a browser to use.
The http service does not know when the browser window has been closed, so
it will continue to serve the model's data until the user halts the
process with a :class:`KeyboardInterrupt` (by pressing ``Ctrl+C``)
When run, you should see output similar to::
>>> from cqparts.display import WebDisplayEnv
>>> from cqparts_misc.basic.primatives import Cube
>>> WebDisplayEnv().display(Cube())
press [ctrl+c] to stop server
127.0.0.1 - - [27/Dec/2017 16:06:37] "GET / HTTP/1.1" 200 -
Created new window in existing browser session.
127.0.0.1 - - [27/Dec/2017 16:06:39] "GET /model/out.gltf HTTP/1.1" 200 -
127.0.0.1 - - [27/Dec/2017 16:06:39] "GET /model/out.bin HTTP/1.1" 200 -
A new browser window should appear with a render that looks like:
.. image:: /_static/img/web_display.cube.png
Then, when you press ``Ctrl+C``, you should see::
^C[server shutdown successfully]
and any further request on the opened browser window will return
an errorcode 404 (file not found), because the http service has stopped.
"""
def display_callback(self, component, port=9041, autorotate=False):
"""
:param component: the component to render
:type component: :class:`Component <cqparts.Component>`
:param port: port to expose http service on
:type port: :class:`int`
:param autorotate: if ``True``, rendered component will rotate
as if on a turntable.
:type autorotate: :class:`bool`
"""
# Verify Parameter(s)
from .. import Component
if not isinstance(component, Component):
raise TypeError("given component must be a %r, not a %r" % (
Component, type(component)
))
# Create temporary file to host files
temp_dir = tempfile.mkdtemp()
host_dir = os.path.join(temp_dir, 'html')
print("host temp folder: %s" % host_dir)
# Copy template content to temporary location
shutil.copytree(TEMPLATE_CONTENT_DIR, host_dir)
# Export model
exporter = component.exporter('gltf')
exporter(
filename=os.path.join(host_dir, 'model', 'out.gltf'),
embed=False,
)
# Modify templated content
# index.html
with open(os.path.join(host_dir, 'index.html'), 'r') as fh:
index_template = jinja2.Template(fh.read())
with open(os.path.join(host_dir, 'index.html'), 'w') as fh:
# camera location & target
cam_t = [
(((a + b) / 2.0) / 1000) # midpoint (unit: meters)
for (a, b) in zip(exporter.scene_min, exporter.scene_max)
]
cam_p = [
(((b - a) * 1.0) / 1000) + t # max point * 200% (unit: meters)
for (a, b, t) in zip(exporter.scene_min, exporter.scene_max, cam_t)
]
# write
xzy = lambda a: (a[0], a[2], -a[1]) # x,z,y coordinates (not x,y,z)
fh.write(index_template.render(
model_filename='model/out.gltf',
autorotate = str(autorotate).lower(),
camera_target=','.join("%g" % (val) for val in xzy(cam_t)),
camera_pos=','.join("%g" % (val) for val in xzy(cam_p)),
))
try:
# Start web-service (loop forever)
server = SocketServer.ThreadingTCPServer(
server_address=("0.0.0.0", port),
RequestHandlerClass=SimpleHTTPServer.SimpleHTTPRequestHandler,
)
server_addr = "http://%s:%i/" % server.server_address
def thread_target():
with working_dir(host_dir):
server.serve_forever()
print("serving: %s" % server_addr)
sys.stdout.flush()
server_thread = threading.Thread(target=thread_target)
server_thread.daemon = True
server_thread.start()
# Open in browser
print("opening in browser: %s" % server_addr)
sys.stdout.flush()
webbrowser.open(server_addr)
# workaround for https://github.com/dcowden/cadquery/issues/211
import signal
def _handler_sigint(signum, frame):
raise KeyboardInterrupt()
signal.signal(signal.SIGINT, _handler_sigint)
print("press [ctrl+c] to stop server")
sys.stdout.flush()
while True: # wait for Ctrl+C
time.sleep(1)
except KeyboardInterrupt:
log.info("\n[keyboard interrupt]")
sys.stdout.flush()
finally:
# Stop web-service
server.shutdown()
server.server_close()
server_thread.join()
print("[server shutdown successfully]")
# Delete temporary content
if os.path.exists(os.path.join(host_dir, 'cqparts-display.txt')):
# just making sure we're deleting the right folder
shutil.rmtree(temp_dir)
| lgpl-3.0 |
Builders-SonarSource/sonarqube-bis | server/sonar-server/src/main/java/org/sonar/server/platform/db/EmbeddedDatabaseFactory.java | 1973 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db;
import com.google.common.annotations.VisibleForTesting;
import org.picocontainer.Startable;
import org.sonar.api.config.Settings;
import org.sonar.api.database.DatabaseProperties;
import static org.apache.commons.lang.StringUtils.startsWith;
public class EmbeddedDatabaseFactory implements Startable {
private static final String URL_PREFIX = "jdbc:h2:tcp:";
private final Settings settings;
private EmbeddedDatabase embeddedDatabase;
public EmbeddedDatabaseFactory(Settings settings) {
this.settings = settings;
}
@Override
public void start() {
if (embeddedDatabase == null) {
String jdbcUrl = settings.getString(DatabaseProperties.PROP_URL);
if (startsWith(jdbcUrl, URL_PREFIX)) {
embeddedDatabase = createEmbeddedDatabase();
embeddedDatabase.start();
}
}
}
@Override
public void stop() {
if (embeddedDatabase != null) {
embeddedDatabase.stop();
embeddedDatabase = null;
}
}
@VisibleForTesting
EmbeddedDatabase createEmbeddedDatabase() {
return new EmbeddedDatabase(settings);
}
}
| lgpl-3.0 |
teamCarel/EyeTracker | src/shared_modules/audio/__init__.py | 5306 | '''
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) 2012-2017 Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
---------------------------------------------------------------------------~(*)
'''
import platform,sys,os
os_name = platform.system()
from time import sleep
import subprocess as sp
import signal
#logging
import logging
logger = logging.getLogger(__name__)
audio_modes = ('voice and sound', 'sound only','voice only','silent')
default_audio_mode = audio_modes[0]
audio_mode = default_audio_mode
def set_audio_mode(new_mode):
'''a save way to set the audio mode
'''
if new_mode in ('voice and sound', 'silent','voice only', 'sound only'):
global audio_mode
audio_mode = new_mode
# OS specific audio players via terminal
if os_name == "Linux":
# if getattr(sys, 'frozen', False):
# # we are running in a |PyInstaller| bundle
# ffmpeg_bin = os.path.join(sys._MEIPASS,'avconv')
# else:
# # we are running in a normal Python environment
ffmpeg_bin = "avconv"
arecord_bin = 'arecord'
if platform.linux_distribution()[0] in ('Ubuntu', 'debian'):
def beep():
if 'sound' in audio_mode:
try:
sp.Popen(["paplay", "/usr/share/sounds/ubuntu/stereo/message.ogg"])
except OSError:
logger.warning("Soundfile not found.")
def tink():
if 'sound' in audio_mode:
try:
sp.Popen(["paplay", "/usr/share/sounds/ubuntu/stereo/button-pressed.ogg"])
except OSError:
logger.warning("Soundfile not found.")
def say(message):
if 'voice' in audio_mode:
try:
sp.Popen(["spd-say", message])
except OSError:
install_warning = "could not say: '{}'. Please install spd-say if you want Pupil capture to speek to you."
logger.warning(install_warning.format(message))
else:
def beep():
if 'sound' in audio_mode:
print('\a')
def tink():
if 'sound' in audio_mode:
print('\a')
def say(message):
if 'sound' in audio_mode:
print('\a')
print(message)
class Audio_Input_Dict(dict):
"""docstring for Audio_Input_Dict"""
def __init__(self):
super().__init__()
self['No Audio'] = -1
try:
ret = sp.check_output([arecord_bin,"-l"]).decode(sys.stdout.encoding)
except OSError:
logger.warning("Could not enumerate audio input devices. Calling arecord failed.")
return
'''
**** List of CAPTURE Hardware Devices ****
card 0: AudioPCI [Ensoniq AudioPCI], device 0: ES1371/1 [ES1371 DAC2/ADC]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 1: C930e [Logitech Webcam C930e], device 0: USB Audio [USB Audio]
Subdevices: 1/1
Subdevice #0: subdevice #0
'''
# logger.debug(ret)
lines = ret.split("\n")
# logger.debug(lines)
devices = [l.split(',')[0] for l in lines[1:] if not l.startswith(" ") and l]
logger.debug(devices)
device_names = [w.split(":")[-1][1:] for w in devices]
device_ids = [w.split(":")[0][-1] for w in devices]
for d,idx in zip(device_names,device_ids):
self[d] = idx
elif os_name == "Darwin":
class Audio_Input_Dict(dict):
"""docstring for Audio_Input_Dict"""
def __init__(self):
super().__init__()
self['No Audio'] = -1
self['Default Mic'] = 0
def beep():
if 'sound' in audio_mode:
sp.Popen(["afplay", "/System/Library/Sounds/Pop.aiff"])
def tink():
if 'sound' in audio_mode:
sp.Popen(["afplay", "/System/Library/Sounds/Tink.aiff"])
def say(message):
if 'voice' in audio_mode:
sp.Popen(["say", message, "-v" "Victoria"])
else:
def beep():
if 'sound' in audio_mode:
print('\a')
def tink():
if 'sound' in audio_mode:
print('\a')
def say(message):
if 'voice' in audio_mode:
print('\a')
print(message)
class Audio_Input_Dict(dict):
"""docstring for Audio_Input_Dict"""
def __init__(self):
super().__init__()
self['No Audio'] = -1
class Audio_Capture(object):
"""docstring for audio_capture"""
def __init__(self, audio_src_idx=0, out_file='out.wav'):
super().__init__()
logger.debug("Audio Capture not implemented on this OS")
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
print(Audio_Input_Dict())
# beep()
# sleep(1)
# tink()
# cap = Audio_Capture('test.mp3')
# say("Hello, I am Pupil's audio module.")
# sleep(3)
# cap = None
| lgpl-3.0 |
HOMlab/QN-ACTR-Release | QN-ACTR Java/src/jmt/gui/common/definitions/MeasureDefinition.java | 8141 | /**
* Copyright (C) 2006, Laboratorio di Valutazione delle Prestazioni - Politecnico di Milano
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package jmt.gui.common.definitions;
import java.util.Vector;
import jmt.framework.gui.graph.MeasureValue;
/**
* <p>Title: Measure Definition Interface</p>
* <p>Description: This interface is implemented by each measure definition data structure. It is
* provided to allow ResultsWindow not to be directly linked to underlayng data structure, allowing
* two or more different kind of result data structure. Actually it can be useful to have one
* measure data structure that reads data from the engine and one that loads a saved file.</p>
*
* @author Bertoli Marco
* Date: 23-set-2005
* Time: 23.14.55
*
* Modified by Ashanka (May 2010):
* Patch: Multi-Sink Perf. Index
* Description: Added new Performance index for the capturing the
* 1. global response time (ResponseTime per Sink)
* 2. global throughput (Throughput per Sink)
* each sink per class.
*/
public interface MeasureDefinition {
/**
* Constants used fot the getMeasureState method
*/
public static final int MEASURE_IN_PROGRESS = 0;
public static final int MEASURE_SUCCESS = 1;
public static final int MEASURE_FAILED = 2;
public static final int MEASURE_NO_SAMPLES = 3;
/**
* Adds a MeasureListener to listen to measure change events for given measure.
* Each measure can have ONLY one MeasureListener to avoid unnecessary computational
* efforts to manage a pool of listeners.
* @param measureIndex index of the measure that this listener should listen
* @param listener listener to add or null to remove old one.
*/
public void addMeasureListener(int measureIndex, MeasureListener listener);
/**
* Returns total number of measures
* @return number of measures
*/
public int getMeasureNumber();
/**
* Returns the station name of a given measure
* @param measureIndex index of the measure
* @return station name
*/
public String getStationName(int measureIndex);
/**
* Returns the class name of a given measure
* @param measureIndex index of the measure
* @return class name
*/
public String getClassName(int measureIndex);
/**
* Returns the alpha of a given measure
* @param measureIndex index of the measure
* @return alpha
*/
public double getAlpha(int measureIndex);
/**
* Returns the precision of a given measure
* @param measureIndex index of the measure
* @return precision
*/
public double getPrecision(int measureIndex);
/**
* Returns number of analized samples for a given measure
* @param measureIndex index of the measure
* @return number of analized samples
*/
public int getAnalizedSamples(int measureIndex);
/**
* Returns the name of a given measure
* @param measureIndex index of the measure
* @return name of the measure
*/
public String getName(int measureIndex);
/**
* Returns the vector of Temporary values of a given measure. Each element of the vector
* is an instance of <code>Value</code> interface.
* @param measureIndex index of the measure
* @return vector of termporary values until now
*/
public Vector<MeasureValue> getValues(int measureIndex);
/**
* Returns the state of a measure, that can be MEASURE_IN_PROGRESS, MEASURE_NO_SAMPLES,
* MEASURE_FAILED, MEASURE_SUCCESS
* @param measureIndex index of the measure
* @return measure state
*/
public int getMeasureState(int measureIndex);
/**
* Returns the type of a measure
* @param measureIndex index of the measure
* @return measure type
*/
public int getMeasureType(int measureIndex);
/**
* Returns an array with the measureIndex of every queue length measure
* @return an array with measures' index
*/
public int[] getQueueLengthMeasures();
/**
* Returns an array with the measureIndex of every throughput measure
* @return an array with measures' index
*/
public int[] getThroughputMeasures();
/**
* Returns an array with the measureIndex of every drop rate measure
* @return an array with measures' index
*/
public int[] getDropRateMeasures();
/**
* Returns an array with the measureIndex of every queue time measure
* @return an array with measures' index
*/
public int[] getQueueTimeMeasures();
/**
* Returns an array with the measureIndex of every residence time measure
* @return an array with measures' index
*/
public int[] getResidenceTimeMeasures();
/**
* Returns an array with the measureIndex of every response time measure
* @return an array with measures' index
*/
public int[] getResponseTimeMeasures();
/**
* Returns an array with the measureIndex of every utilization measure
* @return an array with measures' index
*/
public int[] getUtilizationMeasures();
/**
* Returns an array with the measureIndex of every system response time measure
* @return an array with measures' index
*/
public int[] getSystemResponseTimeMeasures();
/**
* Returns an array with the measureIndex of every system throughput measure
* @return an array with measures' index
*/
public int[] getSystemThroughputMeasures();
/**
* Returns an array with the measureIndex of every system drop rate measure
* @return an array with measures' index
*/
public int[] getSystemDropRateMeasures();
/**
* Returns an array with the measureIndex of every customer number measure
* @return an array with measures' index
*/
public int[] getCustomerNumberMeasures();
//Added by ASHANKA START
//Added a new performance index for the JSIM Graph Simulation tool
//This is System Power given by the formula: System/System Response Time
/**
* Returns an array with the measureIndex of every system power measure
* @return an array with measures' index
*/
public int[] getSystemPowerMeasures();
//Added by ASHANKA STOP
public int[] getResponsetimePerSinkMeasures();
public int[] getThroughputPerSinkMeasures();
/**
* Returns the node type of a given measure
* @param measureIndex index of the measure
* @return name of the measure
*/
public String getNodeType(int measureIndex);
/**
* Sets a ProgressTimeListener to listen to progress time change events. This is unique.
* @param listener listener to be set or null to unset previous one
*/
public void setProgressTimeListener(ProgressTimeListener listener);
/**
* Returns if simulation has finished, so results are fixed
* @return true iff simulation has finished
*/
public boolean isSimulationFinished();
/**
* Returns simulation polling interval. This is the time elapsed between two temp values.
* @return simulation polling interval in seconds
*/
public double getPollingInterval();
/**
* Returns current simulation progress time
* @return current progress time
*/
public double getProgressTime();
// --- Listener Interfaces ------------------------------------------------------------------------
/**
* Interface used to specify a listener on a measure. This is useful to
* implement a GUI with a reactive approch.
*/
public interface MeasureListener {
public void measureChanged(Vector measureValues, boolean finished);
}
/**
* Interface used to specify a listener on progress time. This is useful to
* implement a GUI with a reactive approch.
*/
public interface ProgressTimeListener {
public void timeChanged(double progressTime);
}
}
| lgpl-3.0 |
SAMPProjects/Open-SAMP-API | src/Open-SAMP-API/Client/VehicleFunctions.cpp | 5892 | #include "VehicleFunctions.hpp"
#include "MemoryFunctions.hpp"
#include "PlayerFunctions.hpp"
#include "GTAStructs.hpp"
#include <Shared/PipeMessages.hpp>
EXPORT unsigned int Client::VehicleFunctions::GetVehiclePointer()
{
unsigned int ptr = 0;
if (MemoryFunctions::ReadMemory(0xBA18FC, 4, &ptr) != 4)
return 0;
return ptr;
}
EXPORT int Client::VehicleFunctions::GetVehicleSpeed(float factor)
{
DWORD ptr = GetVehiclePointer();
if (ptr == NULL)
return -1;
float x = 0.0, y = 0.0, z = 0.0;
if (MemoryFunctions::ReadMemory(ptr + 0x44, 4, &x) != 4)
return -1;
if (MemoryFunctions::ReadMemory(ptr + 0x48, 4, &y) != 4)
return -1;
if (MemoryFunctions::ReadMemory(ptr + 0x4C, 4, &z) != 4)
return -1;
float speed = sqrt((x*x) + (y*y) + (z*z)) * (float)100.0 * factor;
return (int)speed;
}
EXPORT float Client::VehicleFunctions::GetVehicleHealth()
{
DWORD ptr = GetVehiclePointer();
if (ptr == NULL)
return -1.0f;
float health = 0.0f;
if (MemoryFunctions::ReadMemory(ptr + 0x4C0, 4, &health) != 4)
return -1.0f;
return health;
}
EXPORT int Client::VehicleFunctions::GetVehicleModelId()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
int dwVehicleId = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x22, 2, &dwVehicleId);
return dwVehicleId;
}
EXPORT int Client::VehicleFunctions::GetVehicleModelName(char* &name, int max_len)
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
strcpy_s(name, max_len, GTAStructs::vehicles[GetVehicleModelId() - 400].c_str());
return 1;
}
EXPORT int Client::VehicleFunctions::GetVehicleModelNameById(int vehicleID, char* &name, int max_len)
{
strcpy_s(name, max_len, GTAStructs::vehicles[vehicleID - 400].c_str());
return 1;
}
EXPORT int Client::VehicleFunctions::GetVehicleType()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return -1;
int dwVehicleType = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x590, 1, &dwVehicleType);
return dwVehicleType;
}
EXPORT int Client::VehicleFunctions::GetVehicleFreeSeats(int &seatFL, int &seatFR, int &seatRL, int &seatRR)
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
seatFL = IsVehicleSeatUsed(1);
seatFR = IsVehicleSeatUsed(2);
seatRL = IsVehicleSeatUsed(3);
seatRR = IsVehicleSeatUsed(4);
return 1;
}
EXPORT INT Client::VehicleFunctions::GetVehicleFirstColor()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return -1;
int dwColor = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x434, 1, &dwColor);
return dwColor;
}
EXPORT INT Client::VehicleFunctions::GetVehicleSecondColor()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return -1;
int dwColor = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x435, 1, &dwColor);
return dwColor;
}
EXPORT int Client::VehicleFunctions::GetVehicleColor(int &color1, int &color2)
{
color1 = -1;
color2 = -1;
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
color1 = GetVehicleFirstColor();
color2 = GetVehicleSecondColor();
return 1;
}
EXPORT int Client::VehicleFunctions::IsVehicleSeatUsed(int seat)
{
DWORD dwVehiclePtr = GetVehiclePointer();
if (!dwVehiclePtr)
return 0;
DWORD dwSeatPointer;
seat = seat - 1;
if (seat >= 0 && seat <= 8)
MemoryFunctions::ReadMemory(dwVehiclePtr + 0x460 + seat * 4, 4, &dwSeatPointer);
else
return 0;
if (dwSeatPointer)
return 1;
return 0;
}
EXPORT int Client::VehicleFunctions::IsVehicleLocked()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
int dwDoorLockState = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x4F8, 4, &dwDoorLockState);
return (dwDoorLockState >> 1) & 1;
}
EXPORT int Client::VehicleFunctions::IsVehicleHornEnabled()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
int dwHornState = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x514, 1, &dwHornState);
return dwHornState;
}
EXPORT int Client::VehicleFunctions::IsVehicleSirenEnabled()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
int dwSirenState = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x42D, 1, &dwSirenState);
return (dwSirenState >> 7) & 1;
}
EXPORT int Client::VehicleFunctions::IsVehicleAlternateSirenEnabled()
{
return IsVehicleHornEnabled() && IsVehicleSirenEnabled();
}
EXPORT int Client::VehicleFunctions::IsVehicleEngineEnabled()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
int dwEngineState = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x428, 1, &dwEngineState);
return (dwEngineState >> 4) & 1;
}
EXPORT int Client::VehicleFunctions::IsVehicleLightEnabled()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
int dwLightState = 0;
MemoryFunctions::ReadMemory(GetVehiclePointer() + 0x4A8, 1, (char *)&dwLightState);
return !((dwLightState >> 3) & 1);
}
EXPORT int Client::VehicleFunctions::IsVehicleCar()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
if (GetVehicleType() != 0)
return 0;
for (int i = 0; i < ARRAYSIZE(GTAStructs::planeIDs); i++)
if (GetVehicleModelId() == GTAStructs::planeIDs[i])
return 0;
return 1;
}
EXPORT int Client::VehicleFunctions::IsVehiclePlane()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
if (GetVehicleType() != 0)
return 0;
for (int i = 0; i < ARRAYSIZE(GTAStructs::planeIDs); i++)
if (GetVehicleModelId() == GTAStructs::planeIDs[i])
return 1;
return 0;
}
EXPORT int Client::VehicleFunctions::IsVehicleBoat()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
if (GetVehicleType() != 5)
return 0;
return GetVehicleType() == 5;
}
EXPORT int Client::VehicleFunctions::IsVehicleTrain()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
return GetVehicleType() == 6;
}
EXPORT int Client::VehicleFunctions::IsVehicleBike()
{
if (!PlayerFunctions::IsPlayerInAnyVehicle())
return 0;
return GetVehicleType() == 9;
}
| lgpl-3.0 |
SINGROUP/pycp2k | pycp2k/classes/_minbas_analysis1.py | 1115 | from pycp2k.inputsection import InputSection
from ._each261 import _each261
from ._minbas_cube1 import _minbas_cube1
from ._mos_molden3 import _mos_molden3
class _minbas_analysis1(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
self.Log_print_key = None
self.Eps_filter = None
self.Full_orthogonalization = None
self.Bond_order = None
self.EACH = _each261()
self.MINBAS_CUBE = _minbas_cube1()
self.MOS_MOLDEN = _mos_molden3()
self._name = "MINBAS_ANALYSIS"
self._keywords = {'Bond_order': 'BOND_ORDER', 'Eps_filter': 'EPS_FILTER', 'Log_print_key': 'LOG_PRINT_KEY', 'Add_last': 'ADD_LAST', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS', 'Full_orthogonalization': 'FULL_ORTHOGONALIZATION', 'Filename': 'FILENAME'}
self._subsections = {'MINBAS_CUBE': 'MINBAS_CUBE', 'MOS_MOLDEN': 'MOS_MOLDEN', 'EACH': 'EACH'}
self._attributes = ['Section_parameters']
| lgpl-3.0 |
kasthack/kasthack.vksharp | Sources/kasthack.vksharp/Shared/DataTypes/Entities/City.cs | 235 | namespace kasthack.vksharp.DataTypes.Entities {
public class DatabaseCity : DatabaseEntry {
public string Area { get; set; }
public string Region { get; set; }
public bool Important { get; set; }
}
}
| lgpl-3.0 |
Builders-SonarSource/sonarqube-bis | server/sonar-server/src/main/java/org/sonar/server/setting/ws/ValuesAction.java | 12480 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.setting.ws;
import com.google.common.base.Splitter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Settings;
import org.sonarqube.ws.Settings.ValuesWsResponse;
import org.sonarqube.ws.client.setting.ValuesRequest;
import static java.lang.String.format;
import static java.util.stream.Stream.concat;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.sonar.api.PropertyType.PROPERTY_SET;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.setting.SettingsWsParameters.ACTION_VALUES;
import static org.sonarqube.ws.client.setting.SettingsWsParameters.PARAM_COMPONENT;
import static org.sonarqube.ws.client.setting.SettingsWsParameters.PARAM_KEYS;
public class ValuesAction implements SettingsWsAction {
private static final Splitter COMMA_SPLITTER = Splitter.on(",");
private static final String COMMA_ENCODED_VALUE = "%2C";
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
private final PropertyDefinitions propertyDefinitions;
private final SettingsFinder settingsFinder;
private final SettingsPermissionPredicates settingsPermissionPredicates;
private final ScannerSettings scannerSettings;
public ValuesAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession, PropertyDefinitions propertyDefinitions, SettingsFinder settingsFinder,
SettingsPermissionPredicates settingsPermissionPredicates, ScannerSettings scannerSettings) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
this.propertyDefinitions = propertyDefinitions;
this.settingsFinder = settingsFinder;
this.settingsPermissionPredicates = settingsPermissionPredicates;
this.scannerSettings = scannerSettings;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_VALUES)
.setDescription("List settings values.<br>" +
"If no value has been set for a setting, then the default value is returned.<br>" +
"Requires 'Browse' permission when a component is specified<br/>",
"To access licensed settings, authentication is required<br/>" +
"To access secured settings, one of the following permissions is required: " +
"<ul>" +
"<li>'Execute Analysis'</li>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified component</li>" +
"</ul>")
.setResponseExample(getClass().getResource("values-example.json"))
.setSince("6.3")
.setHandler(this);
action.createParam(PARAM_COMPONENT)
.setDescription("Component key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_KEYS)
.setDescription("List of setting keys")
.setExampleValue("sonar.test.inclusions,sonar.dbcleaner.cleanDirectory");
}
@Override
public void handle(Request request, Response response) throws Exception {
writeProtobuf(doHandle(request), request, response);
}
private ValuesWsResponse doHandle(Request request) {
try (DbSession dbSession = dbClient.openSession(true)) {
ValuesRequest valuesRequest = toWsRequest(request);
Optional<ComponentDto> component = loadComponent(dbSession, valuesRequest);
Set<String> keys = loadKeys(valuesRequest);
Map<String, String> keysToDisplayMap = getKeysToDisplayMap(keys);
List<Setting> settings = loadSettings(dbSession, component, keysToDisplayMap.keySet());
return new ValuesResponseBuilder(settings, component, keysToDisplayMap).build();
}
}
private static ValuesRequest toWsRequest(Request request) {
ValuesRequest.Builder builder = ValuesRequest.builder()
.setComponent(request.param(PARAM_COMPONENT));
if (request.hasParam(PARAM_KEYS)) {
builder.setKeys(request.paramAsStrings(PARAM_KEYS));
}
return builder.build();
}
private Set<String> loadKeys(ValuesRequest valuesRequest) {
List<String> keys = valuesRequest.getKeys();
if (!keys.isEmpty()) {
return new HashSet<>(keys);
}
return concat(propertyDefinitions.getAll().stream().map(PropertyDefinition::key), scannerSettings.getScannerSettingKeys().stream()).collect(Collectors.toSet());
}
private Optional<ComponentDto> loadComponent(DbSession dbSession, ValuesRequest valuesRequest) {
String componentKey = valuesRequest.getComponent();
if (componentKey == null) {
return Optional.empty();
}
ComponentDto component = componentFinder.getByKey(dbSession, componentKey);
userSession.checkComponentPermission(USER, component);
return Optional.of(component);
}
private List<Setting> loadSettings(DbSession dbSession, Optional<ComponentDto> component, Set<String> keys) {
// List of settings must be kept in the following orders : default -> global -> component
List<Setting> settings = new ArrayList<>();
settings.addAll(loadDefaultSettings(keys));
settings.addAll(settingsFinder.loadGlobalSettings(dbSession, keys));
component.ifPresent(componentDto -> settings.addAll(settingsFinder.loadComponentSettings(dbSession, keys, componentDto).values()));
return settings.stream()
.filter(settingsPermissionPredicates.isSettingVisible(component))
.collect(Collectors.toList());
}
private List<Setting> loadDefaultSettings(Set<String> keys) {
return propertyDefinitions.getAll().stream()
.filter(definition -> keys.contains(definition.key()))
.filter(defaultProperty -> !isEmpty(defaultProperty.defaultValue()))
.map(Setting::createFromDefinition)
.collect(Collectors.toList());
}
private Map<String, String> getKeysToDisplayMap(Set<String> keys) {
return keys.stream()
.collect(Collectors.toMap(propertyDefinitions::validKey, Function.identity(),
(u, v) -> {
throw new IllegalArgumentException(format("'%s' and '%s' cannot be used at the same time as they refer to the same setting", u, v));
}));
}
private class ValuesResponseBuilder {
private final List<Setting> settings;
private final Optional<ComponentDto> requestedComponent;
private final ValuesWsResponse.Builder valuesWsBuilder = ValuesWsResponse.newBuilder();
private final Map<String, Settings.Setting.Builder> settingsBuilderByKey = new HashMap<>();
private final Map<String, Setting> settingsByParentKey = new HashMap<>();
private final Map<String, String> keysToDisplayMap;
ValuesResponseBuilder(List<Setting> settings, Optional<ComponentDto> requestedComponent, Map<String, String> keysToDisplayMap) {
this.settings = settings;
this.requestedComponent = requestedComponent;
this.keysToDisplayMap = keysToDisplayMap;
}
ValuesWsResponse build() {
processSettings();
settingsBuilderByKey.values().forEach(Settings.Setting.Builder::build);
return valuesWsBuilder.build();
}
private void processSettings() {
settings.forEach(setting -> {
Settings.Setting.Builder valueBuilder = getOrCreateValueBuilder(keysToDisplayMap.get(setting.getKey()));
setInherited(setting, valueBuilder);
setValue(setting, valueBuilder);
setParent(setting, valueBuilder);
});
}
private Settings.Setting.Builder getOrCreateValueBuilder(String key) {
return settingsBuilderByKey.computeIfAbsent(key, k -> valuesWsBuilder.addSettingsBuilder().setKey(key));
}
private void setInherited(Setting setting, Settings.Setting.Builder valueBuilder) {
boolean isDefault = setting.isDefault();
boolean isGlobal = !requestedComponent.isPresent();
boolean isOnComponent = requestedComponent.isPresent() && Objects.equals(setting.getComponentId(), requestedComponent.get().getId());
boolean isSet = isGlobal || isOnComponent;
valueBuilder.setInherited(isDefault || !isSet);
}
private void setValue(Setting setting, Settings.Setting.Builder valueBuilder) {
PropertyDefinition definition = setting.getDefinition();
String value = setting.getValue();
if (definition == null) {
valueBuilder.setValue(value);
return;
}
if (definition.type().equals(PROPERTY_SET)) {
valueBuilder.setFieldValues(createFieldValuesBuilder(filterVisiblePropertySets(setting.getPropertySets())));
} else if (definition.multiValues()) {
valueBuilder.setValues(createValuesBuilder(value));
} else {
valueBuilder.setValue(value);
}
}
private void setParent(Setting setting, Settings.Setting.Builder valueBuilder) {
Setting parent = settingsByParentKey.get(setting.getKey());
if (parent != null) {
String value = valueBuilder.getInherited() ? setting.getValue() : parent.getValue();
PropertyDefinition definition = setting.getDefinition();
if (definition == null) {
valueBuilder.setParentValue(value);
return;
}
if (definition.type().equals(PROPERTY_SET)) {
valueBuilder.setParentFieldValues(
createFieldValuesBuilder(valueBuilder.getInherited() ? filterVisiblePropertySets(setting.getPropertySets()) : filterVisiblePropertySets(parent.getPropertySets())));
} else if (definition.multiValues()) {
valueBuilder.setParentValues(createValuesBuilder(value));
} else {
valueBuilder.setParentValue(value);
}
}
settingsByParentKey.put(setting.getKey(), setting);
}
private Settings.Values.Builder createValuesBuilder(String value) {
List<String> values = COMMA_SPLITTER.splitToList(value).stream().map(v -> v.replace(COMMA_ENCODED_VALUE, ",")).collect(Collectors.toList());
return Settings.Values.newBuilder().addAllValues(values);
}
private Settings.FieldValues.Builder createFieldValuesBuilder(List<Map<String, String>> fieldValues) {
Settings.FieldValues.Builder builder = Settings.FieldValues.newBuilder();
for (Map<String, String> propertySetMap : fieldValues) {
builder.addFieldValuesBuilder().putAllValue(propertySetMap);
}
return builder;
}
private List<Map<String, String>> filterVisiblePropertySets(List<Map<String, String>> propertySets) {
List<Map<String, String>> filteredPropertySets = new ArrayList<>();
propertySets.forEach(map -> {
Map<String, String> set = new HashMap<>();
map.entrySet().stream()
.filter(entry -> settingsPermissionPredicates.isVisible(entry.getKey(), null, requestedComponent))
.forEach(entry -> set.put(entry.getKey(), entry.getValue()));
filteredPropertySets.add(set);
});
return filteredPropertySets;
}
}
}
| lgpl-3.0 |
Godin/sonar | server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPreOrderDepthTraversalTypeAwareCrawlerTest.java | 6937 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
public class ReportPreOrderDepthTraversalTypeAwareCrawlerTest {
private static final Component FILE_5 = component(FILE, 5);
private static final Component FILE_6 = component(FILE, 6);
private static final Component DIRECTORY_4 = component(DIRECTORY, 4, FILE_5, FILE_6);
private static final Component COMPONENT_TREE = component(PROJECT, 1, DIRECTORY_4);
private final CallRecorderTypeAwareVisitor projectVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.PROJECT, PRE_ORDER);
private final CallRecorderTypeAwareVisitor directoryVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.DIRECTORY, PRE_ORDER);
private final CallRecorderTypeAwareVisitor fileVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.FILE, PRE_ORDER);
private final DepthTraversalTypeAwareCrawler projectCrawler = new DepthTraversalTypeAwareCrawler(projectVisitor);
private final DepthTraversalTypeAwareCrawler directoryCrawler = new DepthTraversalTypeAwareCrawler(directoryVisitor);
private final DepthTraversalTypeAwareCrawler fileCrawler = new DepthTraversalTypeAwareCrawler(fileVisitor);
@Test(expected = NullPointerException.class)
public void visit_null_Component_throws_NPE() {
fileCrawler.visit(null);
}
@Test
public void visit_file_with_depth_FILE_calls_visit_file() {
Component component = component(FILE, 1);
fileCrawler.visit(component);
assertThat(fileVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", component),
reportCallRecord("visitFile", component));
}
@Test
public void visit_directory_with_depth_FILE_calls_visit_directory() {
Component component = component(DIRECTORY, 1);
fileCrawler.visit(component);
assertThat(fileVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", component),
reportCallRecord("visitDirectory", component));
}
@Test
public void visit_project_with_depth_FILE_calls_visit_project() {
Component component = component(PROJECT, 1);
fileCrawler.visit(component);
assertThat(fileVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", component),
reportCallRecord("visitProject", component));
}
@Test
public void visit_file_with_depth_DIRECTORY_does_not_call_visit_file_nor_visitAny() {
Component component = component(FILE, 1);
directoryCrawler.visit(component);
assertThat(directoryVisitor.callsRecords).isEmpty();
}
@Test
public void visit_directory_with_depth_DIRECTORY_calls_visit_directory() {
Component component = component(DIRECTORY, 1);
directoryCrawler.visit(component);
assertThat(directoryVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", component),
reportCallRecord("visitDirectory", component));
}
@Test
public void visit_project_with_depth_DIRECTORY_calls_visit_project() {
Component component = component(PROJECT, 1);
directoryCrawler.visit(component);
assertThat(directoryVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", component),
reportCallRecord("visitProject", component));
}
@Test
public void visit_file_with_depth_PROJECT_does_not_call_visit_file_nor_visitAny() {
Component component = component(FILE, 1);
projectCrawler.visit(component);
assertThat(projectVisitor.callsRecords).isEmpty();
}
@Test
public void visit_directory_with_depth_PROJECT_does_not_call_visit_directory_nor_visitAny() {
Component component = component(DIRECTORY, 1);
projectCrawler.visit(component);
assertThat(projectVisitor.callsRecords).isEmpty();
}
@Test
public void visit_project_with_depth_PROJECT_calls_visit_project_nor_visitAny() {
Component component = component(PROJECT, 1);
projectCrawler.visit(component);
assertThat(projectVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", component),
reportCallRecord("visitProject", component));
}
@Test
public void verify_visit_call_when_visit_tree_with_depth_FILE() {
fileCrawler.visit(COMPONENT_TREE);
assertThat(fileVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", COMPONENT_TREE),
reportCallRecord("visitProject", COMPONENT_TREE),
reportCallRecord("visitAny", DIRECTORY_4),
reportCallRecord("visitDirectory", DIRECTORY_4),
reportCallRecord("visitAny", FILE_5),
reportCallRecord("visitFile", FILE_5),
reportCallRecord("visitAny", FILE_6),
reportCallRecord("visitFile", FILE_6));
}
@Test
public void verify_visit_call_when_visit_tree_with_depth_DIRECTORY() {
directoryCrawler.visit(COMPONENT_TREE);
assertThat(directoryVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", COMPONENT_TREE),
reportCallRecord("visitProject", COMPONENT_TREE),
reportCallRecord("visitAny", DIRECTORY_4),
reportCallRecord("visitDirectory", DIRECTORY_4));
}
@Test
public void verify_visit_call_when_visit_tree_with_depth_PROJECT() {
projectCrawler.visit(COMPONENT_TREE);
assertThat(projectVisitor.callsRecords).containsExactly(
reportCallRecord("visitAny", COMPONENT_TREE),
reportCallRecord("visitProject", COMPONENT_TREE));
}
private static Component component(final Component.Type type, final int ref, final Component... children) {
return ReportComponent.builder(type, ref).addChildren(children).build();
}
private static CallRecord reportCallRecord(String methodName, Component component) {
return CallRecord.reportCallRecord(methodName, component.getReportAttributes().getRef());
}
}
| lgpl-3.0 |
MetaModels/core | src/CoreBundle/Resources/contao/languages/tr/tl_metamodel_dcasetting.php | 476 | <?php
/**
* Translations are managed using Transifex. To create a new translation
* or to help to maintain an existing one, please register at transifex.com.
*
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*
* @link https://www.transifex.com/signup/
* @link https://www.transifex.com/projects/p/$$project$$/language/$$lang$$/
*
* last-updated: 2018-02-06T02:10:11+01:00
*/
$GLOBALS['TL_LANG']['tl_metamodel_dcasetting']['toggle']['0'] = 'Değiştir';
| lgpl-3.0 |
JQIamo/artiq | artiq/frontend/artiq_coreboot.py | 1483 | #!/usr/bin/env python3
import argparse
import sys
import struct
from artiq.tools import verbosity_args, init_logger
from artiq.master.databases import DeviceDB
from artiq.coredevice.comm_mgmt import CommMgmt
def get_argparser():
parser = argparse.ArgumentParser(description="ARTIQ core device boot tool")
verbosity_args(parser)
parser.add_argument("--device-db", default="device_db.py",
help="device database file (default: '%(default)s')")
subparsers = parser.add_subparsers(dest="action")
p_reboot = subparsers.add_parser("reboot",
help="reboot the currently running firmware")
p_hotswap = subparsers.add_parser("hotswap",
help="load the specified firmware in RAM")
p_hotswap.add_argument("image", metavar="IMAGE", type=argparse.FileType("rb"),
help="runtime image to be executed")
return parser
def main():
args = get_argparser().parse_args()
init_logger(args)
core_addr = DeviceDB(args.device_db).get("core")["arguments"]["host"]
mgmt = CommMgmt(core_addr)
try:
if args.action == "reboot":
mgmt.reboot()
elif args.action == "hotswap":
mgmt.hotswap(args.image.read())
else:
print("An action needs to be specified.", file=sys.stderr)
sys.exit(1)
finally:
mgmt.close()
if __name__ == "__main__":
main()
| lgpl-3.0 |
svn2github/dynamicreports-jasper | dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/tableofcontents/TableOfContentsHeadingBuilder.java | 2720 | /**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2015 Ricardo Mariaca
* http://www.dynamicreports.org
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.report.builder.tableofcontents;
import net.sf.dynamicreports.report.base.DRTableOfContentsHeading;
import net.sf.dynamicreports.report.builder.AbstractBuilder;
import net.sf.dynamicreports.report.builder.expression.Expressions;
import net.sf.dynamicreports.report.constant.Constants;
import net.sf.dynamicreports.report.definition.expression.DRIExpression;
/**
* @author Ricardo Mariaca ([email protected])
*/
public class TableOfContentsHeadingBuilder extends AbstractBuilder<TableOfContentsHeadingBuilder, DRTableOfContentsHeading> {
private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;
public TableOfContentsHeadingBuilder() {
super(new DRTableOfContentsHeading());
}
public TableOfContentsHeadingBuilder setParentHeading(TableOfContentsHeadingBuilder parentHeading) {
if (parentHeading != null) {
getObject().setParentHeading(parentHeading.build());
}
else {
getObject().setParentHeading(null);
}
return this;
}
public TableOfContentsHeadingBuilder setLabel(String label) {
this.getObject().setLabelExpression(Expressions.text(label));
return this;
}
public TableOfContentsHeadingBuilder setLabel(DRIExpression<String> labelExpression) {
this.getObject().setLabelExpression(labelExpression);
return this;
}
public TableOfContentsHeadingBuilder setCustomValue(Object customValue) {
this.getObject().setCustomValueExpression(Expressions.value(customValue));
return this;
}
public TableOfContentsHeadingBuilder setCustomValue(DRIExpression<?> customValueExpression) {
this.getObject().setCustomValueExpression(customValueExpression);
return this;
}
public DRTableOfContentsHeading getTableOfContentsHeading() {
return build();
}
}
| lgpl-3.0 |
nbzwt/lanterna | src/main/java/com/googlecode/lanterna/terminal/DefaultTerminalFactory.java | 19566 | /*
* This file is part of lanterna (http://code.google.com/p/lanterna/).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2016 Martin
*/
package com.googlecode.lanterna.terminal;
import com.googlecode.lanterna.TerminalSize;
import com.googlecode.lanterna.screen.TerminalScreen;
import com.googlecode.lanterna.terminal.ansi.CygwinTerminal;
import com.googlecode.lanterna.terminal.ansi.TelnetTerminal;
import com.googlecode.lanterna.terminal.ansi.TelnetTerminalServer;
import com.googlecode.lanterna.terminal.ansi.UnixLikeTTYTerminal;
import com.googlecode.lanterna.terminal.ansi.UnixTerminal;
import com.googlecode.lanterna.terminal.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.nio.charset.Charset;
import java.util.EnumSet;
/**
* This TerminalFactory implementation uses a simple auto-detection mechanism for figuring out which terminal
* implementation to create based on characteristics of the system the program is running on.
* <p>
* Note that for all systems with a graphical environment present, the SwingTerminalFrame will be chosen. You can
* suppress this by calling setForceTextTerminal(true) on this factory.
* @author martin
*/
public class DefaultTerminalFactory implements TerminalFactory {
private static final OutputStream DEFAULT_OUTPUT_STREAM = System.out;
private static final InputStream DEFAULT_INPUT_STREAM = System.in;
private static final Charset DEFAULT_CHARSET = Charset.defaultCharset();
private final OutputStream outputStream;
private final InputStream inputStream;
private final Charset charset;
private TerminalSize initialTerminalSize;
private boolean forceTextTerminal;
private boolean preferTerminalEmulator;
private boolean forceAWTOverSwing;
private int telnetPort;
private int inputTimeout;
private String title;
private boolean autoOpenTerminalFrame;
private final EnumSet<TerminalEmulatorAutoCloseTrigger> autoCloseTriggers;
private TerminalEmulatorColorConfiguration colorConfiguration;
private TerminalEmulatorDeviceConfiguration deviceConfiguration;
private AWTTerminalFontConfiguration fontConfiguration;
private MouseCaptureMode mouseCaptureMode;
/**
* Creates a new DefaultTerminalFactory with all properties set to their defaults
*/
public DefaultTerminalFactory() {
this(DEFAULT_OUTPUT_STREAM, DEFAULT_INPUT_STREAM, DEFAULT_CHARSET);
}
/**
* Creates a new DefaultTerminalFactory with I/O and character set options customisable.
* @param outputStream Output stream to use for text-based Terminal implementations
* @param inputStream Input stream to use for text-based Terminal implementations
* @param charset Character set to assume the client is using
*/
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public DefaultTerminalFactory(OutputStream outputStream, InputStream inputStream, Charset charset) {
this.outputStream = outputStream;
this.inputStream = inputStream;
this.charset = charset;
this.forceTextTerminal = false;
this.preferTerminalEmulator = false;
this.forceAWTOverSwing = false;
this.telnetPort = -1;
this.inputTimeout = -1;
this.autoOpenTerminalFrame = true;
this.title = null;
this.autoCloseTriggers = EnumSet.of(TerminalEmulatorAutoCloseTrigger.CloseOnExitPrivateMode);
this.mouseCaptureMode = null;
//SwingTerminal will replace these null values for the default implementation if they are unchanged
this.colorConfiguration = null;
this.deviceConfiguration = null;
this.fontConfiguration = null;
}
@Override
public Terminal createTerminal() throws IOException {
// 3 different reasons for tty-based terminal:
// "explicit preference", "no alternative",
// ("because we can" - unless "rather not")
if (forceTextTerminal || GraphicsEnvironment.isHeadless() ||
(System.console() != null && !preferTerminalEmulator) ) {
// if tty but have no tty, but do have a port, then go telnet:
if( telnetPort > 0 && System.console() == null) {
return createTelnetTerminal();
}
if(isOperatingSystemWindows()) {
return createWindowsTerminal();
}
else {
return createUnixTerminal(outputStream, inputStream, charset);
}
}
else {
// while Lanterna's TerminalEmulator lacks mouse support:
// if user wanted mouse AND set a telnetPort, and didn't
// explicitly ask for a graphical Terminal, then go telnet:
if (!preferTerminalEmulator && mouseCaptureMode != null && telnetPort > 0) {
return createTelnetTerminal();
} else {
return createTerminalEmulator();
}
}
}
/**
* Creates a new terminal emulator window which will be either Swing-based or AWT-based depending on what is
* available on the system
* @return New terminal emulator exposed as a {@link Terminal} interface
*/
public Terminal createTerminalEmulator() {
Window window;
if(!forceAWTOverSwing && hasSwing()) {
window = createSwingTerminal();
}
else {
window = createAWTTerminal();
}
if(autoOpenTerminalFrame) {
window.setVisible(true);
}
return (Terminal)window;
}
public AWTTerminalFrame createAWTTerminal() {
return new AWTTerminalFrame(
title,
initialTerminalSize,
deviceConfiguration,
fontConfiguration,
colorConfiguration,
autoCloseTriggers.toArray(new TerminalEmulatorAutoCloseTrigger[autoCloseTriggers.size()]));
}
public SwingTerminalFrame createSwingTerminal() {
return new SwingTerminalFrame(
title,
initialTerminalSize,
deviceConfiguration,
fontConfiguration instanceof SwingTerminalFontConfiguration ? (SwingTerminalFontConfiguration)fontConfiguration : null,
colorConfiguration,
autoCloseTriggers.toArray(new TerminalEmulatorAutoCloseTrigger[autoCloseTriggers.size()]));
}
/**
* Creates a new TelnetTerminal
*
* Note: a telnetPort should have been set with setTelnetPort(),
* otherwise creation of TelnetTerminal will most likely fail.
*
* @return New terminal emulator exposed as a {@link Terminal} interface
*/
public TelnetTerminal createTelnetTerminal() {
try {
System.err.print("Waiting for incoming telnet connection on port "+telnetPort+" ... ");
System.err.flush();
TelnetTerminalServer tts = new TelnetTerminalServer(telnetPort);
TelnetTerminal rawTerminal = tts.acceptConnection();
tts.close(); // Just for single-shot: free up the port!
System.err.println("Ok, got it!");
if(mouseCaptureMode != null) {
rawTerminal.setMouseCaptureMode(mouseCaptureMode);
}
if(inputTimeout >= 0) {
rawTerminal.getInputDecoder().setTimeoutUnits(inputTimeout);
}
return rawTerminal;
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
private boolean hasSwing() {
try {
Class.forName("javax.swing.JComponent");
return true;
}
catch(Exception ignore) {
return false;
}
}
/**
* Sets a hint to the TerminalFactory of what size to use when creating the terminal. Most terminals are not created
* on request but for example the SwingTerminal and SwingTerminalFrame are and this value will be passed down on
* creation.
* @param initialTerminalSize Size (in rows and columns) of the newly created terminal
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setInitialTerminalSize(TerminalSize initialTerminalSize) {
this.initialTerminalSize = initialTerminalSize;
return this;
}
/**
* Controls whether a text-based Terminal shall be created even if the system
* supports a graphical environment
* @param forceTextTerminal If true, will always create a text-based Terminal
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setForceTextTerminal(boolean forceTextTerminal) {
this.forceTextTerminal = forceTextTerminal;
return this;
}
/**
* Controls whether a Swing or AWT TerminalFrame shall be preferred if the system
* has both a Console and a graphical environment
* @param preferTerminalEmulator If true, will prefer creating a graphical terminal emulator
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setPreferTerminalEmulator(boolean preferTerminalEmulator) {
this.preferTerminalEmulator = preferTerminalEmulator;
return this;
}
/**
* Primarily for debugging applications with mouse interactions:
* If no Console is available (e.g. from within an IDE), then fall
* back to TelnetTerminal on specified port.
*
* If both a non-null mouseCapture mode and a positive telnetPort
* are specified, then as long as Swing/AWT Terminal emulators do
* not support MouseCapturing, a TelnetTerminal will be preferred
* over the graphical Emulators.
*
* @param telnetPort the TCP/IP port on which to eventually wait for a connection.
* A value less or equal 0 disables creation of a TelnetTerminal.
* Note, that ports less than 1024 typically require system
* privileges to listen on.
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setTelnetPort(int telnetPort) {
this.telnetPort = telnetPort;
return this;
}
/**
* Only for StreamBasedTerminals: After seeing e.g. an Escape (but nothing
* else yet), wait up to the specified number of time units for more
* bytes to make up a complete sequence. This may be necessary on
* slow channels, or if some client terminal sends each byte of a
* sequence in its own TCP packet.
*
* @param inputTimeout how long to wait for possible completions of sequences.
* units are of a 1/4 second, so e.g. 12 would wait up to 3 seconds.
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setInputTimeout(int inputTimeout) {
this.inputTimeout = inputTimeout;
return this;
}
/**
* Normally when a graphical terminal emulator is created by the factory, it will create a
* {@link SwingTerminalFrame} unless Swing is not present in the system. Setting this property to {@code true} will
* make it create an {@link AWTTerminalFrame} even if Swing is present
* @param forceAWTOverSwing If {@code true}, will always create an {@link AWTTerminalFrame} over a
* {@link SwingTerminalFrame} if asked to create a graphical terminal emulator
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setForceAWTOverSwing(boolean forceAWTOverSwing) {
this.forceAWTOverSwing = forceAWTOverSwing;
return this;
}
/**
* Controls whether a SwingTerminalFrame shall be automatically shown (.setVisible(true)) immediately after
* creation. If {@code false}, you will manually need to call {@code .setVisible(true)} on the JFrame to actually
* see the terminal window. Default for this value is {@code true}.
* @param autoOpenTerminalFrame Automatically open SwingTerminalFrame after creation
*/
public void setAutoOpenTerminalEmulatorWindow(boolean autoOpenTerminalFrame) {
this.autoOpenTerminalFrame = autoOpenTerminalFrame;
}
/**
* Sets the title to use on created SwingTerminalFrames created by this factory
* @param title Title to use on created SwingTerminalFrames created by this factory
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setTerminalEmulatorTitle(String title) {
this.title = title;
return this;
}
/**
* Sets the auto-close trigger to use on created SwingTerminalFrames created by this factory. This will reset any
* previous triggers. If called with {@code null}, all triggers are cleared.
* @param autoCloseTrigger Auto-close trigger to use on created SwingTerminalFrames created by this factory, or {@code null} to clear all existing triggers
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setTerminalEmulatorFrameAutoCloseTrigger(TerminalEmulatorAutoCloseTrigger autoCloseTrigger) {
this.autoCloseTriggers.clear();
if(autoCloseTrigger != null) {
this.autoCloseTriggers.add(autoCloseTrigger);
}
return this;
}
/**
* Adds an auto-close trigger to use on created SwingTerminalFrames created by this factory
* @param autoCloseTrigger Auto-close trigger to add to the created SwingTerminalFrames created by this factory
* @return Reference to itself, so multiple calls can be chained
*/
public DefaultTerminalFactory addTerminalEmulatorFrameAutoCloseTrigger(TerminalEmulatorAutoCloseTrigger autoCloseTrigger) {
if(autoCloseTrigger != null) {
this.autoCloseTriggers.add(autoCloseTrigger);
}
return this;
}
/**
* Sets the color configuration to use on created SwingTerminalFrames created by this factory
* @param colorConfiguration Color configuration to use on created SwingTerminalFrames created by this factory
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setTerminalEmulatorColorConfiguration(TerminalEmulatorColorConfiguration colorConfiguration) {
this.colorConfiguration = colorConfiguration;
return this;
}
/**
* Sets the device configuration to use on created SwingTerminalFrames created by this factory
* @param deviceConfiguration Device configuration to use on created SwingTerminalFrames created by this factory
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setTerminalEmulatorDeviceConfiguration(TerminalEmulatorDeviceConfiguration deviceConfiguration) {
this.deviceConfiguration = deviceConfiguration;
return this;
}
/**
* Sets the font configuration to use on created SwingTerminalFrames created by this factory
* @param fontConfiguration Font configuration to use on created SwingTerminalFrames created by this factory
* @return Reference to itself, so multiple .set-calls can be chained
*/
public DefaultTerminalFactory setTerminalEmulatorFontConfiguration(AWTTerminalFontConfiguration fontConfiguration) {
this.fontConfiguration = fontConfiguration;
return this;
}
/**
* Sets the mouse capture mode the terminal should use. Please note that this is an extension which isn't widely
* supported!
*
* If both a non-null mouseCapture mode and a positive telnetPort
* are specified, then as long as Swing/AWT Terminal emulators do
* not support MouseCapturing, a TelnetTerminal will be preferred
* over the graphical Emulators.
*
* @param mouseCaptureMode Capture mode for mouse interactions
* @return Itself
*/
public DefaultTerminalFactory setMouseCaptureMode(MouseCaptureMode mouseCaptureMode) {
this.mouseCaptureMode = mouseCaptureMode;
return this;
}
/**
* create a Terminal and immediately wrap it up in a TerminalScreen
*/
public TerminalScreen createScreen() throws IOException {
return new TerminalScreen(createTerminal());
}
private Terminal createWindowsTerminal() throws IOException {
try {
Class<?> nativeImplementation = Class.forName("com.googlecode.lanterna.terminal.WindowsTerminal");
Constructor<?> constructor = nativeImplementation.getConstructor(InputStream.class, OutputStream.class, Charset.class, UnixLikeTTYTerminal.CtrlCBehaviour.class);
return (Terminal)constructor.newInstance(inputStream, outputStream, charset, UnixLikeTTYTerminal.CtrlCBehaviour.CTRL_C_KILLS_APPLICATION);
}
catch(Exception ignore) {
return createCygwinTerminal(outputStream, inputStream, charset);
}
}
private Terminal createCygwinTerminal(OutputStream outputStream, InputStream inputStream, Charset charset) throws IOException {
CygwinTerminal cygTerminal = new CygwinTerminal(inputStream, outputStream, charset);
if(inputTimeout >= 0) {
cygTerminal.getInputDecoder().setTimeoutUnits(inputTimeout);
}
return cygTerminal;
}
private Terminal createUnixTerminal(OutputStream outputStream, InputStream inputStream, Charset charset) throws IOException {
UnixTerminal unixTerminal;
try {
Class<?> nativeImplementation = Class.forName("com.googlecode.lanterna.terminal.NativeGNULinuxTerminal");
Constructor<?> constructor = nativeImplementation.getConstructor(InputStream.class, OutputStream.class, Charset.class, UnixLikeTTYTerminal.CtrlCBehaviour.class);
unixTerminal = (UnixTerminal)constructor.newInstance(inputStream, outputStream, charset, UnixLikeTTYTerminal.CtrlCBehaviour.CTRL_C_KILLS_APPLICATION);
}
catch(Exception ignore) {
unixTerminal = new UnixTerminal(inputStream, outputStream, charset);
}
if(mouseCaptureMode != null) {
unixTerminal.setMouseCaptureMode(mouseCaptureMode);
}
if(inputTimeout >= 0) {
unixTerminal.getInputDecoder().setTimeoutUnits(inputTimeout);
}
return unixTerminal;
}
/**
* Detects whether the running platform is Windows* by looking at the
* operating system name system property
*/
private static boolean isOperatingSystemWindows() {
return System.getProperty("os.name", "").toLowerCase().startsWith("windows");
}
}
| lgpl-3.0 |
burnoutcoin/go-burnout | core/types/bloom9.go | 3369 | // Copyright 2014 The go-burnout Authors
// This file is part of the go-burnout library.
//
// The go-burnout library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-burnout library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-burnout library. If not, see <http://www.gnu.org/licenses/>.
package types
import (
"fmt"
"math/big"
"github.com/burnoutcoin/go-burnout/common/hexutil"
"github.com/burnoutcoin/go-burnout/crypto"
)
type bytesBacked interface {
Bytes() []byte
}
const (
// BloomByteLength represents the number of bytes used in a header log bloom.
BloomByteLength = 256
// BloomBitLength represents the number of bits used in a header log bloom.
BloomBitLength = 8 * BloomByteLength
)
// Bloom represents a 2048 bit bloom filter.
type Bloom [BloomByteLength]byte
// BytesToBloom converts a byte slice to a bloom filter.
// It panics if b is not of suitable size.
func BytesToBloom(b []byte) Bloom {
var bloom Bloom
bloom.SetBytes(b)
return bloom
}
// SetBytes sets the content of b to the given bytes.
// It panics if d is not of suitable size.
func (b *Bloom) SetBytes(d []byte) {
if len(b) < len(d) {
panic(fmt.Sprintf("bloom bytes too big %d %d", len(b), len(d)))
}
copy(b[BloomByteLength-len(d):], d)
}
// Add adds d to the filter. Future calls of Test(d) will return true.
func (b *Bloom) Add(d *big.Int) {
bin := new(big.Int).SetBytes(b[:])
bin.Or(bin, bloom9(d.Bytes()))
b.SetBytes(bin.Bytes())
}
// Big converts b to a big integer.
func (b Bloom) Big() *big.Int {
return new(big.Int).SetBytes(b[:])
}
func (b Bloom) Bytes() []byte {
return b[:]
}
func (b Bloom) Test(test *big.Int) bool {
return BloomLookup(b, test)
}
func (b Bloom) TestBytes(test []byte) bool {
return b.Test(new(big.Int).SetBytes(test))
}
// MarshalText encodes b as a hex string with 0x prefix.
func (b Bloom) MarshalText() ([]byte, error) {
return hexutil.Bytes(b[:]).MarshalText()
}
// UnmarshalText b as a hex string with 0x prefix.
func (b *Bloom) UnmarshalText(input []byte) error {
return hexutil.UnmarshalFixedText("Bloom", input, b[:])
}
func CreateBloom(receipts Receipts) Bloom {
bin := new(big.Int)
for _, receipt := range receipts {
bin.Or(bin, LogsBloom(receipt.Logs))
}
return BytesToBloom(bin.Bytes())
}
func LogsBloom(logs []*Log) *big.Int {
bin := new(big.Int)
for _, log := range logs {
bin.Or(bin, bloom9(log.Address.Bytes()))
for _, b := range log.Topics {
bin.Or(bin, bloom9(b[:]))
}
}
return bin
}
func bloom9(b []byte) *big.Int {
b = crypto.Keccak256(b[:])
r := new(big.Int)
for i := 0; i < 6; i += 2 {
t := big.NewInt(1)
b := (uint(b[i+1]) + (uint(b[i]) << 8)) & 2047
r.Or(r, t.Lsh(t, b))
}
return r
}
var Bloom9 = bloom9
func BloomLookup(bin Bloom, topic bytesBacked) bool {
bloom := bin.Big()
cmp := bloom9(topic.Bytes()[:])
return bloom.And(bloom, cmp).Cmp(cmp) == 0
}
| lgpl-3.0 |
jswanljung/iris | lib/iris/tests/test_util.py | 14633 | # (C) British Crown Copyright 2010 - 2016, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test iris.util
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
import six
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import inspect
import unittest
import cf_units
import numpy as np
import iris.analysis
import iris.coords
import iris.tests.stock as stock
import iris.util
class TestMonotonic(unittest.TestCase):
def assertMonotonic(self, array, direction=None, **kwargs):
if direction is not None:
mono, dir = iris.util.monotonic(array, return_direction=True, **kwargs)
if not mono:
self.fail('Array was not monotonic:/n %r' % array)
if dir != np.sign(direction):
self.fail('Array was monotonic but not in the direction expected:'
'/n + requested direction: %s/n + resultant direction: %s' % (direction, dir))
else:
mono = iris.util.monotonic(array, **kwargs)
if not mono:
self.fail('Array was not monotonic:/n %r' % array)
def assertNotMonotonic(self, array, **kwargs):
mono = iris.util.monotonic(array, **kwargs)
if mono:
self.fail("Array was monotonic when it shouldn't be:/n %r" % array)
def test_monotonic_pve(self):
a = np.array([3, 4, 5.3])
self.assertMonotonic(a)
self.assertMonotonic(a, direction=1)
# test the reverse for negative monotonic.
a = a[::-1]
self.assertMonotonic(a)
self.assertMonotonic(a, direction=-1)
def test_not_monotonic(self):
b = np.array([3, 5.3, 4])
self.assertNotMonotonic(b)
def test_monotonic_strict(self):
b = np.array([3, 5.3, 4])
self.assertNotMonotonic(b, strict=True)
self.assertNotMonotonic(b)
b = np.array([3, 5.3, 5.3])
self.assertNotMonotonic(b, strict=True)
self.assertMonotonic(b, direction=1)
b = b[::-1]
self.assertNotMonotonic(b, strict=True)
self.assertMonotonic(b, direction=-1)
b = np.array([0.0])
self.assertRaises(ValueError, iris.util.monotonic, b)
self.assertRaises(ValueError, iris.util.monotonic, b, strict=True)
b = np.array([0.0, 0.0])
self.assertNotMonotonic(b, strict=True)
self.assertMonotonic(b)
class TestReverse(unittest.TestCase):
def test_simple(self):
a = np.arange(12).reshape(3, 4)
np.testing.assert_array_equal(a[::-1], iris.util.reverse(a, 0))
np.testing.assert_array_equal(a[::-1, ::-1], iris.util.reverse(a, [0, 1]))
np.testing.assert_array_equal(a[:, ::-1], iris.util.reverse(a, 1))
np.testing.assert_array_equal(a[:, ::-1], iris.util.reverse(a, [1]))
self.assertRaises(ValueError, iris.util.reverse, a, [])
self.assertRaises(ValueError, iris.util.reverse, a, -1)
self.assertRaises(ValueError, iris.util.reverse, a, 10)
self.assertRaises(ValueError, iris.util.reverse, a, [-1])
self.assertRaises(ValueError, iris.util.reverse, a, [0, -1])
def test_single(self):
a = np.arange(36).reshape(3, 4, 3)
np.testing.assert_array_equal(a[::-1], iris.util.reverse(a, 0))
np.testing.assert_array_equal(a[::-1, ::-1], iris.util.reverse(a, [0, 1]))
np.testing.assert_array_equal(a[:, ::-1, ::-1], iris.util.reverse(a, [1, 2]))
np.testing.assert_array_equal(a[..., ::-1], iris.util.reverse(a, 2))
self.assertRaises(ValueError, iris.util.reverse, a, -1)
self.assertRaises(ValueError, iris.util.reverse, a, 10)
self.assertRaises(ValueError, iris.util.reverse, a, [-1])
self.assertRaises(ValueError, iris.util.reverse, a, [0, -1])
class TestClipString(unittest.TestCase):
def setUp(self):
self.test_string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
self.rider = "**^^**$$..--__" # A good chance at being unique and not in the string to be tested!
def test_oversize_string(self):
# Test with a clip length that means the string will be clipped
clip_length = 109
result = iris.util.clip_string(self.test_string, clip_length, self.rider)
# Check the length is between what we requested ( + rider length) and the length of the original string
self.assertTrue(clip_length + len(self.rider) <= len(result) < len(self.test_string), "String was not clipped.")
# Also test the rider was added
self.assertTrue(self.rider in result, "Rider was not added to the string when it should have been.")
def test_undersize_string(self):
# Test with a clip length that is longer than the string
clip_length = 10999
result = iris.util.clip_string(self.test_string, clip_length, self.rider)
self.assertEqual(len(result), len(self.test_string), "String was clipped when it should not have been.")
# Also test that no rider was added on the end if the string was not clipped
self.assertFalse(self.rider in result, "Rider was adding to the string when it should not have been.")
def test_invalid_clip_lengths(self):
# Clip values less than or equal to zero are not valid
for clip_length in [0, -100]:
result = iris.util.clip_string(self.test_string, clip_length, self.rider)
self.assertEqual(len(result), len(self.test_string), "String was clipped when it should not have been.")
def test_default_values(self):
# Get the default values specified in the function
argspec = inspect.getargspec(iris.util.clip_string)
arg_dict = dict(zip(argspec.args[-2:], argspec.defaults))
result = iris.util.clip_string(self.test_string, arg_dict["clip_length"], arg_dict["rider"])
self.assertLess(len(result), len(self.test_string), "String was not clipped.")
rider_returned = result[-len(arg_dict["rider"]):]
self.assertEqual(rider_returned, arg_dict['rider'],
'Default rider was not applied.')
def test_trim_string_with_no_spaces(self):
clip_length = 200
no_space_string = "a" * 500
# Since this string has no spaces, clip_string will not be able to gracefully clip it
# but will instead clip it exactly where the user specified
result = iris.util.clip_string(no_space_string, clip_length, self.rider)
expected_length = clip_length + len(self.rider)
# Check the length of the returned string is equal to clip length + length of rider
self.assertEqual(
len(result),
expected_length,
'Mismatch in expected length of clipped string. Length was %s, '
'expected value is %s' % (len(result), expected_length))
class TestDescribeDiff(iris.tests.IrisTest):
def test_identical(self):
test_cube_a = stock.realistic_4d()
test_cube_b = stock.realistic_4d()
return_sio = six.StringIO()
iris.util.describe_diff(test_cube_a, test_cube_b, output_file=return_sio)
return_str = return_sio.getvalue()
self.assertString(return_str, 'compatible_cubes.str.txt')
def test_different(self):
# test incompatible attributes
test_cube_a = stock.realistic_4d()
test_cube_b = stock.realistic_4d()
test_cube_a.attributes['Conventions'] = 'CF-1.5'
test_cube_b.attributes['Conventions'] = 'CF-1.6'
return_sio = six.StringIO()
iris.util.describe_diff(test_cube_a, test_cube_b, output_file=return_sio)
return_str = return_sio.getvalue()
self.assertString(return_str, 'incompatible_attr.str.txt')
# test incompatible names
test_cube_a = stock.realistic_4d()
test_cube_b = stock.realistic_4d()
test_cube_a.standard_name = "relative_humidity"
return_sio = six.StringIO()
iris.util.describe_diff(test_cube_a, test_cube_b, output_file=return_sio)
return_str = return_sio.getvalue()
self.assertString(return_str, 'incompatible_name.str.txt')
# test incompatible unit
test_cube_a = stock.realistic_4d()
test_cube_b = stock.realistic_4d()
test_cube_a.units = cf_units.Unit('m')
return_sio = six.StringIO()
iris.util.describe_diff(test_cube_a, test_cube_b, output_file=return_sio)
return_str = return_sio.getvalue()
self.assertString(return_str, 'incompatible_unit.str.txt')
# test incompatible methods
test_cube_a = stock.realistic_4d()
test_cube_b = stock.realistic_4d().collapsed('model_level_number', iris.analysis.MEAN)
return_sio = six.StringIO()
iris.util.describe_diff(test_cube_a, test_cube_b, output_file=return_sio)
return_str = return_sio.getvalue()
self.assertString(return_str, 'incompatible_meth.str.txt')
def test_output_file(self):
# test incompatible attributes
test_cube_a = stock.realistic_4d()
test_cube_b = stock.realistic_4d().collapsed('model_level_number', iris.analysis.MEAN)
test_cube_a.attributes['Conventions'] = 'CF-1.5'
test_cube_b.attributes['Conventions'] = 'CF-1.6'
test_cube_a.standard_name = "relative_humidity"
test_cube_a.units = cf_units.Unit('m')
with self.temp_filename() as filename:
with open(filename, 'w') as f:
iris.util.describe_diff(test_cube_a, test_cube_b, output_file=f)
f.close()
self.assertFilesEqual(filename,
'incompatible_cubes.str.txt')
class TestAsCompatibleShape(tests.IrisTest):
def test_slice(self):
cube = tests.stock.realistic_4d()
sliced = cube[1, :, 2, :-2]
expected = cube[1:2, :, 2:3, :-2]
res = iris.util.as_compatible_shape(sliced, cube)
self.assertEqual(res, expected)
def test_transpose(self):
cube = tests.stock.realistic_4d()
transposed = cube.copy()
transposed.transpose()
expected = cube
res = iris.util.as_compatible_shape(transposed, cube)
self.assertEqual(res, expected)
def test_slice_and_transpose(self):
cube = tests.stock.realistic_4d()
sliced_and_transposed = cube[1, :, 2, :-2]
sliced_and_transposed.transpose()
expected = cube[1:2, :, 2:3, :-2]
res = iris.util.as_compatible_shape(sliced_and_transposed, cube)
self.assertEqual(res, expected)
def test_collapsed(self):
cube = tests.stock.realistic_4d()
collapsed = cube.collapsed('model_level_number', iris.analysis.MEAN)
expected_shape = list(cube.shape)
expected_shape[1] = 1
expected_data = collapsed.data.reshape(expected_shape)
res = iris.util.as_compatible_shape(collapsed, cube)
self.assertCML(res, ('util', 'as_compatible_shape_collapsed.cml'),
checksum=False)
self.assertMaskedArrayEqual(expected_data, res.data)
def test_reduce_dimensionality(self):
# Test that as_compatible_shape() can demote
# length one dimensions to scalars.
cube = tests.stock.realistic_4d()
src = cube[:, 2:3]
expected = reduced = cube[:, 2]
res = iris.util.as_compatible_shape(src, reduced)
self.assertEqual(res, expected)
def test_anonymous_dims(self):
cube = tests.stock.realistic_4d()
# Move all coords from dim_coords to aux_coords.
for coord in cube.dim_coords:
dim = cube.coord_dims(coord)
cube.remove_coord(coord)
cube.add_aux_coord(coord, dim)
sliced = cube[1, :, 2, :-2]
expected = cube[1:2, :, 2:3, :-2]
res = iris.util.as_compatible_shape(sliced, cube)
self.assertEqual(res, expected)
def test_scalar_auxcoord(self):
def dim_to_aux(cube, coord_name):
"""Convert coordinate on cube from DimCoord to AuxCoord."""
coord = cube.coord(coord_name)
coord = iris.coords.AuxCoord.from_coord(coord)
cube.replace_coord(coord)
cube = tests.stock.realistic_4d()
src = cube[:, :, 3]
dim_to_aux(src, 'grid_latitude')
expected = cube[:, :, 3:4]
dim_to_aux(expected, 'grid_latitude')
res = iris.util.as_compatible_shape(src, cube)
self.assertEqual(res, expected)
def test_2d_auxcoord_transpose(self):
dim_coord1 = iris.coords.DimCoord(range(3), long_name='first_dim')
dim_coord2 = iris.coords.DimCoord(range(4), long_name='second_dim')
aux_coord_2d = iris.coords.AuxCoord(np.arange(12).reshape(3, 4),
long_name='spanning')
aux_coord_2d_T = iris.coords.AuxCoord(np.arange(12).reshape(3, 4).T,
long_name='spanning')
src = iris.cube.Cube(
np.ones((3, 4)),
dim_coords_and_dims=[(dim_coord1, 0), (dim_coord2, 1)],
aux_coords_and_dims=[(aux_coord_2d, (0, 1))])
target = iris.cube.Cube(
np.ones((4, 3)),
dim_coords_and_dims=[(dim_coord1, 1), (dim_coord2, 0)],
aux_coords_and_dims=[(aux_coord_2d_T, (0, 1))])
res = iris.util.as_compatible_shape(src, target)
self.assertEqual(res[0], target[0])
if __name__ == '__main__':
unittest.main()
| lgpl-3.0 |
zerosync/zerodesk | doxygen/html/search/search.js | 22206 | // Search script generated by doxygen
// Copyright (C) 2009 by Dimitri van Heesch.
// The code in this file is loosly based on main.js, part of Natural Docs,
// which is Copyright (C) 2003-2008 Greg Valure
// Natural Docs is licensed under the GPL.
var indexSectionsWithContent =
{
0: "acdefghilmnoprstuz~",
1: "mz",
2: "u",
3: "mz",
4: "acdefghimoprstuz~",
5: "acdfghilmnopstuz"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "namespaces",
3: "files",
4: "functions",
5: "variables"
};
function convertToId(search)
{
var result = '';
for (i=0;i<search.length;i++)
{
var c = search.charAt(i);
var cn = c.charCodeAt(0);
if (c.match(/[a-z0-9\u0080-\uFFFF]/))
{
result+=c;
}
else if (cn<16)
{
result+="_0"+cn.toString(16);
}
else
{
result+="_"+cn.toString(16);
}
}
return result;
}
function getXPos(item)
{
var x = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
x += item.offsetLeft;
item = item.offsetParent;
}
}
return x;
}
function getYPos(item)
{
var y = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
y += item.offsetTop;
item = item.offsetParent;
}
}
return y;
}
/* A class handling everything associated with the search panel.
Parameters:
name - The name of the global variable that will be
storing this instance. Is needed to be able to set timeouts.
resultPath - path to use for external files
*/
function SearchBox(name, resultsPath, inFrame, label)
{
if (!name || !resultsPath) { alert("Missing parameters to SearchBox."); }
// ---------- Instance variables
this.name = name;
this.resultsPath = resultsPath;
this.keyTimeout = 0;
this.keyTimeoutLength = 500;
this.closeSelectionTimeout = 300;
this.lastSearchValue = "";
this.lastResultsPage = "";
this.hideTimeout = 0;
this.searchIndex = 0;
this.searchActive = false;
this.insideFrame = inFrame;
this.searchLabel = label;
// ----------- DOM Elements
this.DOMSearchField = function()
{ return document.getElementById("MSearchField"); }
this.DOMSearchSelect = function()
{ return document.getElementById("MSearchSelect"); }
this.DOMSearchSelectWindow = function()
{ return document.getElementById("MSearchSelectWindow"); }
this.DOMPopupSearchResults = function()
{ return document.getElementById("MSearchResults"); }
this.DOMPopupSearchResultsWindow = function()
{ return document.getElementById("MSearchResultsWindow"); }
this.DOMSearchClose = function()
{ return document.getElementById("MSearchClose"); }
this.DOMSearchBox = function()
{ return document.getElementById("MSearchBox"); }
// ------------ Event Handlers
// Called when focus is added or removed from the search field.
this.OnSearchFieldFocus = function(isActive)
{
this.Activate(isActive);
}
this.OnSearchSelectShow = function()
{
var searchSelectWindow = this.DOMSearchSelectWindow();
var searchField = this.DOMSearchSelect();
if (this.insideFrame)
{
var left = getXPos(searchField);
var top = getYPos(searchField);
left += searchField.offsetWidth + 6;
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
left -= searchSelectWindow.offsetWidth;
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
else
{
var left = getXPos(searchField);
var top = getYPos(searchField);
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
// stop selection hide timer
if (this.hideTimeout)
{
clearTimeout(this.hideTimeout);
this.hideTimeout=0;
}
return false; // to avoid "image drag" default event
}
this.OnSearchSelectHide = function()
{
this.hideTimeout = setTimeout(this.name +".CloseSelectionWindow()",
this.closeSelectionTimeout);
}
// Called when the content of the search field is changed.
this.OnSearchFieldChange = function(evt)
{
if (this.keyTimeout) // kill running timer
{
clearTimeout(this.keyTimeout);
this.keyTimeout = 0;
}
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 || e.keyCode==13)
{
if (e.shiftKey==1)
{
this.OnSearchSelectShow();
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
child.focus();
return;
}
}
return;
}
else if (window.frames.MSearchResults.searchResults)
{
var elem = window.frames.MSearchResults.searchResults.NavNext(0);
if (elem) elem.focus();
}
}
else if (e.keyCode==27) // Escape out of the search field
{
this.DOMSearchField().blur();
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
this.Activate(false);
return;
}
// strip whitespaces
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue != this.lastSearchValue) // search value has changed
{
if (searchValue != "") // non-empty search
{
// set timer for search update
this.keyTimeout = setTimeout(this.name + '.Search()',
this.keyTimeoutLength);
}
else // empty search field
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
}
}
}
this.SelectItemCount = function(id)
{
var count=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
count++;
}
}
return count;
}
this.SelectItemSet = function(id)
{
var i,j=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
var node = child.firstChild;
if (j==id)
{
node.innerHTML='•';
}
else
{
node.innerHTML=' ';
}
j++;
}
}
}
// Called when an search filter selection is made.
// set item with index id as the active item
this.OnSelectItem = function(id)
{
this.searchIndex = id;
this.SelectItemSet(id);
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue!="" && this.searchActive) // something was found -> do a search
{
this.Search();
}
}
this.OnSearchSelectKey = function(evt)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 && this.searchIndex<this.SelectItemCount()) // Down
{
this.searchIndex++;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==38 && this.searchIndex>0) // Up
{
this.searchIndex--;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==13 || e.keyCode==27)
{
this.OnSelectItem(this.searchIndex);
this.CloseSelectionWindow();
this.DOMSearchField().focus();
}
return false;
}
// --------- Actions
// Closes the results window.
this.CloseResultsWindow = function()
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.Activate(false);
}
this.CloseSelectionWindow = function()
{
this.DOMSearchSelectWindow().style.display = 'none';
}
// Performs a search.
this.Search = function()
{
this.keyTimeout = 0;
// strip leading whitespace
var searchValue = this.DOMSearchField().value.replace(/^ +/, "");
var code = searchValue.toLowerCase().charCodeAt(0);
var idxChar = searchValue.substr(0, 1).toLowerCase();
if ( 0xD800 <= code && code <= 0xDBFF && searchValue > 1) // surrogate pair
{
idxChar = searchValue.substr(0, 2);
}
var resultsPage;
var resultsPageWithSearch;
var hasResultsPage;
var idx = indexSectionsWithContent[this.searchIndex].indexOf(idxChar);
if (idx!=-1)
{
var hexCode=idx.toString(16);
resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html';
resultsPageWithSearch = resultsPage+'?'+escape(searchValue);
hasResultsPage = true;
}
else // nothing available for this search term
{
resultsPage = this.resultsPath + '/nomatches.html';
resultsPageWithSearch = resultsPage;
hasResultsPage = false;
}
window.frames.MSearchResults.location = resultsPageWithSearch;
var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow();
if (domPopupSearchResultsWindow.style.display!='block')
{
var domSearchBox = this.DOMSearchBox();
this.DOMSearchClose().style.display = 'inline';
if (this.insideFrame)
{
var domPopupSearchResults = this.DOMPopupSearchResults();
domPopupSearchResultsWindow.style.position = 'relative';
domPopupSearchResultsWindow.style.display = 'block';
var width = document.body.clientWidth - 8; // the -8 is for IE :-(
domPopupSearchResultsWindow.style.width = width + 'px';
domPopupSearchResults.style.width = width + 'px';
}
else
{
var domPopupSearchResults = this.DOMPopupSearchResults();
var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth;
var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1;
domPopupSearchResultsWindow.style.display = 'block';
left -= domPopupSearchResults.offsetWidth;
domPopupSearchResultsWindow.style.top = top + 'px';
domPopupSearchResultsWindow.style.left = left + 'px';
}
}
this.lastSearchValue = searchValue;
this.lastResultsPage = resultsPage;
}
// -------- Activation Functions
// Activates or deactivates the search panel, resetting things to
// their default values if necessary.
this.Activate = function(isActive)
{
if (isActive || // open it
this.DOMPopupSearchResultsWindow().style.display == 'block'
)
{
this.DOMSearchBox().className = 'MSearchBoxActive';
var searchField = this.DOMSearchField();
if (searchField.value == this.searchLabel) // clear "Search" term upon entry
{
searchField.value = '';
this.searchActive = true;
}
}
else if (!isActive) // directly remove the panel
{
this.DOMSearchBox().className = 'MSearchBoxInactive';
this.DOMSearchField().value = this.searchLabel;
this.searchActive = false;
this.lastSearchValue = ''
this.lastResultsPage = '';
}
}
}
// -----------------------------------------------------------------------
// The class that handles everything on the search results page.
function SearchResults(name)
{
// The number of matches from the last run of <Search()>.
this.lastMatchCount = 0;
this.lastKey = 0;
this.repeatOn = false;
// Toggles the visibility of the passed element ID.
this.FindChildElement = function(id)
{
var parentElement = document.getElementById(id);
var element = parentElement.firstChild;
while (element && element!=parentElement)
{
if (element.nodeName == 'DIV' && element.className == 'SRChildren')
{
return element;
}
if (element.nodeName == 'DIV' && element.hasChildNodes())
{
element = element.firstChild;
}
else if (element.nextSibling)
{
element = element.nextSibling;
}
else
{
do
{
element = element.parentNode;
}
while (element && element!=parentElement && !element.nextSibling);
if (element && element!=parentElement)
{
element = element.nextSibling;
}
}
}
}
this.Toggle = function(id)
{
var element = this.FindChildElement(id);
if (element)
{
if (element.style.display == 'block')
{
element.style.display = 'none';
}
else
{
element.style.display = 'block';
}
}
}
// Searches for the passed string. If there is no parameter,
// it takes it from the URL query.
//
// Always returns true, since other documents may try to call it
// and that may or may not be possible.
this.Search = function(search)
{
if (!search) // get search word from URL
{
search = window.location.search;
search = search.substring(1); // Remove the leading '?'
search = unescape(search);
}
search = search.replace(/^ +/, ""); // strip leading spaces
search = search.replace(/ +$/, ""); // strip trailing spaces
search = search.toLowerCase();
search = convertToId(search);
var resultRows = document.getElementsByTagName("div");
var matches = 0;
var i = 0;
while (i < resultRows.length)
{
var row = resultRows.item(i);
if (row.className == "SRResult")
{
var rowMatchName = row.id.toLowerCase();
rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_'
if (search.length<=rowMatchName.length &&
rowMatchName.substr(0, search.length)==search)
{
row.style.display = 'block';
matches++;
}
else
{
row.style.display = 'none';
}
}
i++;
}
document.getElementById("Searching").style.display='none';
if (matches == 0) // no results
{
document.getElementById("NoMatches").style.display='block';
}
else // at least one result
{
document.getElementById("NoMatches").style.display='none';
}
this.lastMatchCount = matches;
return true;
}
// return the first item with index index or higher that is visible
this.NavNext = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index++;
}
return focusItem;
}
this.NavPrev = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index--;
}
return focusItem;
}
this.ProcessKeys = function(e)
{
if (e.type == "keydown")
{
this.repeatOn = false;
this.lastKey = e.keyCode;
}
else if (e.type == "keypress")
{
if (!this.repeatOn)
{
if (this.lastKey) this.repeatOn = true;
return false; // ignore first keypress after keydown
}
}
else if (e.type == "keyup")
{
this.lastKey = 0;
this.repeatOn = false;
}
return this.lastKey!=0;
}
this.Nav = function(evt,itemIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
var newIndex = itemIndex-1;
var focusItem = this.NavPrev(newIndex);
if (focusItem)
{
var child = this.FindChildElement(focusItem.parentNode.parentNode.id);
if (child && child.style.display == 'block') // children visible
{
var n=0;
var tmpElem;
while (1) // search for last child
{
tmpElem = document.getElementById('Item'+newIndex+'_c'+n);
if (tmpElem)
{
focusItem = tmpElem;
}
else // found it!
{
break;
}
n++;
}
}
}
if (focusItem)
{
focusItem.focus();
}
else // return focus to search field
{
parent.document.getElementById("MSearchField").focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = itemIndex+1;
var focusItem;
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem && elem.style.display == 'block') // children visible
{
focusItem = document.getElementById('Item'+itemIndex+'_c0');
}
if (!focusItem) focusItem = this.NavNext(newIndex);
if (focusItem) focusItem.focus();
}
else if (this.lastKey==39) // Right
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'block';
}
else if (this.lastKey==37) // Left
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'none';
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
this.NavChild = function(evt,itemIndex,childIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
if (childIndex>0)
{
var newIndex = childIndex-1;
document.getElementById('Item'+itemIndex+'_c'+newIndex).focus();
}
else // already at first child, jump to parent
{
document.getElementById('Item'+itemIndex).focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = childIndex+1;
var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex);
if (!elem) // last child, jump to parent next parent
{
elem = this.NavNext(itemIndex+1);
}
if (elem)
{
elem.focus();
}
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
}
function setKeyActions(elem,action)
{
elem.setAttribute('onkeydown',action);
elem.setAttribute('onkeypress',action);
elem.setAttribute('onkeyup',action);
}
function setClassAttr(elem,attr)
{
elem.setAttribute('class',attr);
elem.setAttribute('className',attr);
}
function createResults()
{
var results = document.getElementById("SRResults");
for (var e=0; e<searchData.length; e++)
{
var id = searchData[e][0];
var srResult = document.createElement('div');
srResult.setAttribute('id','SR_'+id);
setClassAttr(srResult,'SRResult');
var srEntry = document.createElement('div');
setClassAttr(srEntry,'SREntry');
var srLink = document.createElement('a');
srLink.setAttribute('id','Item'+e);
setKeyActions(srLink,'return searchResults.Nav(event,'+e+')');
setClassAttr(srLink,'SRSymbol');
srLink.innerHTML = searchData[e][1][0];
srEntry.appendChild(srLink);
if (searchData[e][1].length==2) // single result
{
srLink.setAttribute('href',searchData[e][1][1][0]);
if (searchData[e][1][1][1])
{
srLink.setAttribute('target','_parent');
}
var srScope = document.createElement('span');
setClassAttr(srScope,'SRScope');
srScope.innerHTML = searchData[e][1][1][2];
srEntry.appendChild(srScope);
}
else // multiple results
{
srLink.setAttribute('href','javascript:searchResults.Toggle("SR_'+id+'")');
var srChildren = document.createElement('div');
setClassAttr(srChildren,'SRChildren');
for (var c=0; c<searchData[e][1].length-1; c++)
{
var srChild = document.createElement('a');
srChild.setAttribute('id','Item'+e+'_c'+c);
setKeyActions(srChild,'return searchResults.NavChild(event,'+e+','+c+')');
setClassAttr(srChild,'SRScope');
srChild.setAttribute('href',searchData[e][1][c+1][0]);
if (searchData[e][1][c+1][1])
{
srChild.setAttribute('target','_parent');
}
srChild.innerHTML = searchData[e][1][c+1][2];
srChildren.appendChild(srChild);
}
srEntry.appendChild(srChildren);
}
srResult.appendChild(srEntry);
results.appendChild(srResult);
}
}
| lgpl-3.0 |
WELTEN/xAPI-gae-tools | src/main/webapp/dist/js/views/view.js | 47875 | ////////
// Users
////////
window.UserView = Backbone.View.extend({
tagName: "li",
className: "dropdown user user-menu",
initialize:function () {
this.template = _.template(tpl.get('user'));
},
render:function () {
$(this.el).html(this.template(this.model));
return this;
}
});
window.UserSidebarView = Backbone.View.extend({
tagName: "div",
className: "user-panel",
initialize:function () {
this.template = _.template(tpl.get('user_sidebar'));
},
render:function () {
$(this.el).html(this.template(this.model));
return this;
}
});
window.ProgressView = Backbone.View.extend({
tagName: "section",
className: "col-lg-6 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'BarChart',
dataTable: this.data,
backgroundColor: { fill:'#76a7fa' },
options: {
title: 'You progress in this MOOC',
chartArea: {width: '50%'},
hAxis: {
title: 'Percentage',
minValue: 0,
maxValue: 100
}
}
});
this.$('.box-body').append(chart.render().el);
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['corechart', 'bar']
});
return this;
}
});
window.ActivityAreaChartView = Backbone.View.extend({
tagName: "section",
className: "col-lg-12 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'AreaChart',
dataTable: this.data,
options: {
title: 'MOOC activity',
chartArea: {width: '100%'},
hAxis: {
title: 'Time'
},
chart: {
interpolateNulls: true
}
}
});
this.$('.box-body').append(chart.render().el);
var closure = this;
$(window).resize(function(){
closure.drawVisualization();
});
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['corechart']
});
return this;
}
});
window.AnnotationChartView = Backbone.View.extend({
tagName: "section",
className: "col-lg-12 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'AnnotationChart',
dataTable: this.data,
options: {
title: 'MOOC activity',
displayAnnotations: false,
hAxis: {
title: 'Time'
},
chartArea: {
left: 0,
top: 0,
width: 100,
height: 150
}
}
});
this.$('.box-body').append(chart.render().el);
this.$('.box-body').attr("style","padding-right:30px;");
var closure = this;
$(window).resize(function(){
closure.drawVisualization();
});
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['annotationchart']
});
return this;
}
});
window.ColumnChartView = Backbone.View.extend({
tagName: "section",
className: "col-lg-12 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'ColumnChart',
dataTable: this.data,
options: {
//title: this.title,
chartArea: {width: '90%'},
'backgroundColor': 'transparent',
//,
//hAxis: {
// title: 'Percentage',
// minValue: 0,
// maxValue: 100
//}
}
});
this.$('.box-body').append(chart.render().el);
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['corechart', 'bar']
});
return this;
}
});
window.GaugeView = Backbone.View.extend({
tagName: "section",
className: "col-lg-6 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'Gauge',
dataTable: this.data,
backgroundColor: { fill:'#76a7fa' },
options: {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
}
});
this.$('.box-body').append(chart.render().el);
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['gauge']
});
return this;
}
});
window.CalendarView = Backbone.View.extend({
tagName: "section",
className: "col-lg-12 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv= options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'Calendar',
dataTable: this.data,
backgroundColor: { fill:'#76a7fa' },
options: {
width: '100%',
height:340,
calendar: {
monthLabel: {
fontName: 'Times-Roman',
fontSize: 12,
color: '#fff',
bold: true,
italic: true
},
monthOutlineColor: {
stroke: '#981b48',
strokeOpacity: 0.8,
strokeWidth: 2
},
unusedMonthOutlineColor: {
stroke: '#bc5679',
strokeOpacity: 0.8,
strokeWidth: 1
},
dayOfWeekLabel: {
fontName: 'Times-Roman',
fontSize: 12,
color: '#fff',
bold: true,
italic: true
},
yearLabel: {
fontName: 'Source Sans Pro',
fontSize: 32,
color: '#fff',
bold: true,
italic: true
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1
},
underYearSpace: 10,
underMonthSpace: 16
}
}
});
this.$('.box-body').append(chart.render().el);
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['calendar']
});
return this;
}
});
window.BubbleView = Backbone.View.extend({
tagName: "section",
className: "col-lg-10 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'BubbleChart',
dataTable: this.model,
options: {
// title: 'DropOutMonitor: Correlation between number of course launches, number of activities and number of users for all Moocs',
titlePosition :'none',
hAxis: {title: 'number of activities', logScale:true},
vAxis: {title: 'number of launches', logScale:true},
backgroundColor: { fill:'transparent' },
height:400,
bubble: {textStyle: {fontSize: 11}}
}
});
this.$('.box-body').append(chart.render().el);
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['calendar']
});
return this;
}
});
window.BubbleViewLang = Backbone.View.extend({
tagName: "section",
className: "col-lg-10 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'BubbleChart',
dataTable: this.model,
options: {
// title: 'DropOutMonitor: Correlation between number of course launches, number of activities and number of users for all Moocs',
titlePosition :'none',
hAxis: {title: 'number of registered users', logScale:true},
vAxis: {title: 'number of launches', logScale:true},
backgroundColor: { fill:'transparent' },
height:400,
bubble: {textStyle: {fontSize: 11}}
}
});
this.$('.box-body').append(chart.render().el);
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['calendar']
});
return this;
}
});
window.ResourcesConsumedView = Backbone.View.extend({
tagName: "section",
className: "col-lg-10 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'BarChart',
dataTable: this.data,
options: {
chart: {
title: 'Resources consumed'
},
bar: {groupWidth: "95%"},
legend: { position: 'top', maxLines: 3 },
backgroundColor: { fill:'transparent' },
bars: 'horizontal' // Required for Material Bar Charts.
}
});
this.$('.box-body').append(chart.render().el);
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['bar']
});
return this;
}
});
window.PerfomanceView = Backbone.View.extend({
tagName: "section",
className: "col-lg-6 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
},
drawVisualization: function () {
this.data = new google.visualization.DataTable(this.model);
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var chart = new Backbone.GoogleChart({
chartType: 'BarChart',
dataTable: this.data,
options: {
chart: {
title: 'Group vs. individual performance'
},
backgroundColor: { fill:'transparent' },
bars: 'horizontal' // Required for Material Bar Charts.
}
});
this.$('.box-body').append(chart.render().el);
},
render: function() {
google.load('visualization', '1', {
'callback': _.bind(this.drawVisualization, this),
'packages': ['bar']
});
return this;
}
});
window.DashBoardLearnerView = Backbone.View.extend({
tagName: "div",
className: "dashboard-learner",
initialize:function () {
this.template = _.template(tpl.get('dashboard-learner'));
},
render:function () {
$(this.el).html(this.template(this.model));
return this;
}
});
window.DashBoardTeacherView = Backbone.View.extend({
tagName: "div",
className: "dashboard-learner",
initialize:function () {
this.template = _.template(tpl.get('dashboard-teacher'));
},
render:function () {
$(this.el).html(this.template(this.model));
return this;
}
});
window.DashBoardAdminView = Backbone.View.extend({
tagName: "div",
className: "dashboard-learner",
initialize:function () {
this.template = _.template(tpl.get('dashboard-admin'));
},
render:function () {
$(this.el).html(this.template(this.model));
return this;
}
});
window.CourseItemView = Backbone.View.extend({
tagName: "li",
initialize:function () {
this.template = _.template(tpl.get('course-item'));
},
render:function () {
$(this.el).html(this.template(this.model));
return this;
}
});
window.TimeLineView = Backbone.View.extend({
tagName: "ul",
className: "timeline user-timeline",
initialize:function () {
this.template = _.template(tpl.get('timeline'));
},
render:function () {
$(this.el).html(this.template());
return this;
},
update: function(options){
}
});
window.TimeLineItemView = Backbone.View.extend({
tagName: "li",
initialize:function () {
this.template = _.template(tpl.get('timeline-item'));
},
render:function () {
var model = { model: this.model, verb: "this.model.toJSON().verbId" };
$(this.el).html(this.template(model));
$(document).i18n();
return this;
}
});
window.BarChartView = Backbone.View.extend({
tagName: "section",
className: "col-lg-12 connectedSortable ui-sortable",
xScale: null,
yScale: null,
margin: {},
barSvg: null,
height: 0,
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
$(this.el).html(this.template({ title: this.title, csv: this.csv }));
this.container = this.$('.box-body')[0];
$(this.container).html("");
this.margin = {top: 50, bottom: 50, left:150, right: 40};
if($( window ).width() < 760){
var width = $( window ).width()- 50 - this.margin.left - this.margin.right;
}else{
var width = $( window ).width() - 300 - this.margin.left - this.margin.right;
}
this.height = 400 - this.margin.top - this.margin.bottom;
this.xScale = d3.scale.linear().range([0, width]);
this.yScale = d3.scale.ordinal().rangeRoundBands([0, this.height], 1.8,0);
var numTicks = 5;
var xAxis = d3.svg.axis().scale(this.xScale)
.orient("top")
.tickSize((-this.height))
.ticks(numTicks);
var svg = d3.select(this.container).append("svg")
.attr("width", width+this.margin.left+this.margin.right)
.attr("height", this.height+this.margin.top+this.margin.bottom+50)
.attr("class", "base-svg")
;
this.barSvg = svg.append("g")
.attr("transform", "translate("+this.margin.left+","+this.margin.top+")")
.attr("class", "bar-svg");
var x = this.barSvg.append("g").attr("class", "x-axis");
},
update: function(options){
//var data = JSON.parse(options);
data = options;
var xMax = d3.max(data, function(d) { return d.rate; } );
var xMin = 0;
this.xScale.domain([xMin, xMax]);
this.yScale.domain(data.map(function(d) { return d.label; }));
var yScale = this.yScale;
var xScale = this.xScale;
d3.select(".base-svg").append("text")
.attr("x", this.margin.left)
.attr("y", (this.margin.top)/2)
.attr("text-anchor", "start")
.text(this.title)
.attr("class", "title");
var groups = this.barSvg.append("g").attr("class", "labels")
.selectAll("text")
.data(data)
.enter()
.append("g");
groups.append("text")
.attr("x", "0")
.attr("y", function(d) { return yScale(d.label); })
.text(function(d) { return d.label; })
.attr("text-anchor", "end")
.attr("dy", ".9em")
.attr("dx", "-.32em")
.attr("id", function(d,i) { return "label"+i; });
var bars = groups
.attr("class", "bars")
.append("rect")
.attr("width", function(d) { return xScale(d.rate); })
.attr("height", this.height/20)
.attr("x", xScale(xMin))
.attr("y", function(d) { return yScale(d.label); })
.attr("id", function(d,i) { return "bar"+i; });
groups.append("text")
.attr("x", function(d) { return xScale(d.rate); })
.attr("y", function(d) { return yScale(d.label); })
.text(function(d) { return d.rate; })
.attr("text-anchor", "end")
.attr("dy", "1.2em")
.attr("dx", "-.32em")
.attr("id", "precise-value");
bars
.on("mouseover", function() {
var currentGroup = d3.select(this.parentNode);
currentGroup.select("rect").style("fill", "brown");
currentGroup.select("text").style("font-weight", "bold");
})
.on("mouseout", function() {
var currentGroup = d3.select(this.parentNode);
currentGroup.select("rect").style("fill", "steelblue");
currentGroup.select("text").style("font-weight", "normal");
});
},
render: function(){
return this;
}
});
window.DropoutStudentView = Backbone.View.extend({
tagName: "section",
className: "col-lg-12 connectedSortable ui-sortable",
xScale: null,
yScale: null,
margin: {},
barSvg: null,
height: 0,
xatt : null,
yatt:null,
xAxis:null,
yAxis:null,
moocPath:null,
amountOfLines:null,
width:null,
initialize: function(options){
if(this.moocPath === null) {
this.moocPath = new MOOCpath();
}
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
this.container = this.$('.box-body')[0];
$(this.container).html("");
this.margin = {top: 25, right: 20, bottom: 40, left: 40};
width = $('.content').width() - this.margin.left - this.margin.right;
this.height = 300 - this.margin.top - this.margin.bottom;
var x = d3.scale.ordinal()
.rangeBands([0, width],1);
var y = d3.scale.linear()
.range([this.height, 0]);
this.xatt = x;
this.yatt = y;
this.xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
this.yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(20, ".");
svg = d3.select(this.container).append("svg")
.attr("width", width + this.margin.left + this.margin.right)
.attr("height", this.height + this.margin.top + this.margin.bottom)
.append("g")
.attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");
svg = d3.select(this.container).append("svg")
.attr("viewBox", "0 0 "+(width + this.margin.left + this.margin.right)+" "+(this.height + this.margin.top + this.margin.bottom))
.classed("svg-container", true)
.classed("svg-content-responsive", true)
.append("g")
.attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");
line = d3.svg.line()
.x(function(d) { return x(d.serial); })
.y(function(d) { return y(d.relativeTime); })
.interpolate('linear');
lineAll = d3.svg.line()
.x(function(d) { return x(d.serial); })
.y(function(d) { return y(d.relativeTimeCont); })
.interpolate('linear');
lineStudent = d3.svg.line()
.x(function(d) { return x(d.serial); })
.y(function(d) { return y(d.studentActivityCont); })
.interpolate('linear');
},
update: function(options){
if(this.moocPath === null){
this.moocPath = new MOOCpath();
this.moocPath.modelActivities = options.activityPath;
}
if (this.moocPath.modelActivities == null) {
this.moocPath.modelActivities = options.activityPath;
}
var x = this.xatt;
var y = this.yatt;
x.domain(this.moocPath.modelActivities.map(function(d) { return d.serial; }));
y.domain([0, this.moocPath.getHightYAxis()* parseInt(localStorage.getItem("scaleFactor"))]);
//INIT GRAPH
svg.append("g")
.attr("class", "xAxis")
.attr("id","StudentPathXaxis")
.attr("transform", "translate(0," + this.height + ")")
.call(this.xAxis)
.append("text")
.attr("x",$('.content').width()-50)
.attr("y",0)
.style("text-anchor","end")
.text("ACTIVITIES");
svg.append("g")
.attr("class", "yAxis")
.attr("id","StudentPathYaxis")
.call(this.yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 2)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("WEEKS (AFTER FIRST ACCESS ACTIVITY)")
.style("font-size","0.8em");
//END
//DRAW model line with icons and colors
svg.append("path")
.attr("class", "lineModel")
.attr("d", line(this.moocPath.modelActivities))
.attr('stroke', 'black')
.attr('stroke-width', 5)
.attr('fill', 'none');
svg.selectAll(".activity")
.data(this.moocPath.modelActivities)
.enter().append("circle")
.attr("class", "activity")
.attr("r", 3)
.attr("cx", function(d) { return x(d.serial); })
.attr("cy", function(d) { return y(d.relativeTime); })
.style("fill", "white");
//END
},
updateMyData: function(){
var x = this.xatt;
var y = this.yatt;
//DRAW STUDENT LINE
svg.append("path")
.attr("class", "lineStudent")
.attr("d", lineStudent(this.moocPath.getGraphStudentsActivitiesRelative()))
.attr('fill', 'none')
.attr('stroke', 'white')
.attr('stroke-width', 5);//wijziging
//wijziging opacity verwijderd
svg.selectAll(".activity2")
.data(this.moocPath.getGraphStudentsActivitiesRelative())
.enter().append("circle")
.attr("class", "activity2")
.attr("r", 5)
.attr("cx", function(d) { return x(d.serial);})
.attr("cy", function(d) { return y(d.studentActivityCont); })
.style("fill", function (d) {return getColorIcon(d.studentActivity);});
svg.selectAll(".activityFig")//wijziging deze programmablock heb ik van de model weggehaald en hier geplaatst
.data(this.moocPath.getGraphStudentsActivitiesRelative())
.enter().append("text")
.attr("x",function(d) { return x(d.serial)-7;})
.attr("y",this.height+32)
.attr("font-family","FontAwesome")
.attr('font-size', function(d) { return '1em';} )
.text(function(d) { return getCorrectFontAwesomeIcon(d.objectDefinition, d.verbId); })
.style("fill", function (d) {return getColorIcon(d.studentActivity);});
//END
},
addOtherStudent: function(data,i) {
var id = i;
var x = this.xatt;
var y = this.yatt;
var graphData = data;
var color = graphData.color;
svg.append("path")
.attr("class", "line"+id)
.attr("d", lineAll(graphData))
.attr('stroke', color)
.attr('stroke-width', 1)
.attr('fill', 'none')
.attr("opacity",0.7); //wijziging opacity toegevoegd: zo blijft de lijn van de student altijd goed zichtbaar
svg.selectAll(".activityAll"+ id)
.data(graphData)
.enter().append("circle")
.attr("class", "activityAll"+ id)
.attr("r", function(d){if(d.relativeTimeCont=== 0){return 0} else {return 1.5}})
.attr("cx", function(d) { return x(d.serial); })
.attr("cy", function(d) { return y(d.relativeTimeCont); })
.style("fill", function (d) {return getColorIcon(d.relativeTime);});
},
hideLines: function(firstSlider, secondSlider){
var amountOfLines = this.moocPath.studentTimeLinesActivities.length;//wijziging ik weet niet of ik deze al doorgestuurd had naar jou
if(amountOfLines<=this.moocPath.studentTimeLinesActivities.length){
for(var i = parseInt(Math.round(amountOfLines * (firstSlider/100))); i <= parseInt(Math.round(amountOfLines * (secondSlider/100))); i++){
(function(i) {
setTimeout(function() {
$(".line"+i).show();
$(".activityAll"+i).show();
},100);
})(i);
}
for(var i = 0; i <= parseInt(Math.round(amountOfLines * (firstSlider/100))); i++){
(function(i) {
setTimeout(function() {
$(".line"+i).hide();
$(".activityAll"+i).hide();
},100);
})(i);
}
for(var i = parseInt(Math.round(amountOfLines * (secondSlider/100))); i <= amountOfLines; i++){
(function(i) {
setTimeout(function() {
$(".line"+i).hide();
$(".activityAll"+i).hide();
},100);
})(i);
}
}
},
reScaleYAxis : function(){
this.initialize("This is ");
$(".box-title").html("Graphs representing who follows who in this course");
this.update();
this.updateMyData();
for(var i = 0; i<this.moocPath.studentTimeLinesActivities.length;i++){
this.addOtherStudent(this.moocPath.getNewStudentPathGraph(this.moocPath.studentTimeLinesActivities[i]),i);
}
this.hideLines($("#slider-range").slider("values",0),$("#slider-range").slider("values",1));
},
});
window.SandboxView2 = Backbone.View.extend({
tagName: "section",
className: "col-lg-12 connectedSortable ui-sortable",
initialize: function(options){
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
this.container = this.$('.box-body')[0];
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = this.x = d3.time.scale()
.range([0, width]);
var y = this.y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = this.line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = this.svg = d3.select(this.container).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Dagen na startactiviteit");
},
render: function(){
return this;
},
update: function(options){
moocPath.updateStudentPath(studentId, path);
var data = JSON.parse(options);
data.forEach(function(d) {
d.date = d.date;
//d.date = parseDate(d.date);
d.close = +d.close;
});
this.x.domain(d3.extent(data, function(d) { return d.date; }));
this.y.domain(d3.extent(data, function(d) { return d.close; }));
this.svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", this.line);
}
});
window.SandboxView3Followers = Backbone.View.extend({
tagName: "section",
className: "col-lg-12 connectedSortable ui-sortable",
initialize: function(options){
//_(this).bindAll('buildBase');
this.template = _.template(tpl.get('widget'));
this.title = options.title;
this.csv = options.csv;
$(this.el).html(this.template({ title: this.title, csv:this.csv }));
var w = window,
d = document,
e = d.documentElement,
g = this.$('.box-body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
this.container = this.$('.box-body')[0];
var width = 960,
height = 500;
this.force = d3.layout.force()
.charge(-140)
.linkDistance(80)
.size([width, height]);
this.svg = d3.select(this.container)
.append("svg")
.attr("width", width)
.attr("height", height);
var self = this;
function updateWindow(){
x = g.clientWidth;
y = g.clientHeight;
self.svg.attr("width", x).attr("height", y);
}
window.onresize = updateWindow;
},
render: function(){
return this;
},
update: function(data){
var self = this;
var graph = this.dataAnalysis(data);
var nodeMap = {};
this.maxConnections = 1;
graph.nodes.forEach(function(d) {
nodeMap[d.name] = d;
if (d.connections> self.maxConnections) self.maxConnections = d.connections;
});
graph.links.forEach(function(l) {
l.source = nodeMap[l.source];
l.target = nodeMap[l.target];
});
this.force.nodes(graph.nodes)
.links(graph.links)
.start();
var link = this.svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
;
var node = this.svg.selectAll(".node")
.data(graph.nodes);
var label = this.svg.selectAll(".label")
.data(graph.nodes);
var nodeEnter = node.enter().append("svg:circle")
.attr("class", "node")
.attr("r", function(d){
return 3 + d.connections * (30.0/self.maxConnections);
})
.call(this.force.drag);
node.append("title")
.text(function(d) { return d.name; });
//label = label.data(graph.nodes);
//label.enter().append("text")
// .call(this.force.drag)
// .attr("y", function(d) {
// return d.y-40;
// })
// .attr("x", function(d) {
// return d.x+10;
// })
// .text(function(d){
// return d.text
// });
this.force.on("tick", function(e) {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
//label.attr("x", function(d) { return d.x-20; })
// .attr("y", function(d) { return d.y-13; });
var k = 10 * e.alpha;
graph.nodes.forEach(function(o, i) {
o.y += i & 1 ? k : -k;
o.x += i & 2 ? k : -k;
});
}
);
self.svg.attr("width", "100%").attr("height", 600);
},
dataAnalysis: function(tripleObject){
var nodes = [];
var links = [];
tripleObject.followers.forEach(function(response) {
var item_nodes = {};
//item_nodes ["id"] = response.id;
item_nodes ["name"] = response.id;
item_nodes ["text"] = response.name;
item_nodes ["group"] = 1;
item_nodes ["connections"] = response.follows.length;
nodes.push(item_nodes);
var _id = response.id
response.follows.forEach(function(follow){
var item_links = {};
item_links["source"] = follow.id;
item_links["target"] = _id;
item_links["value"] = 3;
links.push(item_links);
});
});
var item2 = {
"nodes": nodes,
"links": links
};
return item2;
}
});
// loader settings
var opts = {
lines: 9, // The number of lines to draw
length: 9, // The length of each line
width: 5, // The line thickness
radius: 14, // The radius of the inner circle
color: '#EE3124', // #rgb or #rrggbb or array of colors
speed: 1.9, // Rounds per second
trail: 40, // Afterglow percentage
className: 'spinner' // The CSS class to assign to the spinner
};
function init() {
// trigger loader
var spinner = new Spinner(opts).spin(target);
// slow the json load intentionally, so we can see it every load
setTimeout(function() {
// load json data and trigger callback
d3.json(chartConfig.data_url, function(data) {
// stop spin.js loader
spinner.stop();
// instantiate chart within callback
chart(data);
});
}, 1500);
}
function MOOCpath(){
this.modelActivities ;//= getModelActivityPathFromJSON(); //Model as presented by the teacher
this.studentActivities = [];
this.studentTimeLinesActivities = []; // the activities of all the users
this.setStudentActivities = function(studentActivities){
//var studentActivities = [];
//$.ajax({
// type:"GET",
// dataType: "json",
// url: "LAD-Tools/StudentPath/newjson.json",
// //url: "https://2-dot-eco-xapi-production-server.appspot.com/data-proxy/query/result/studentPaths/eu.ecolearning.hub0:11/0",
// async:false,
// success: function(data){
// //studentActivities = data.studentActivities;
// studentActivities = data.rows;
// }
//});
for (var i = 0; i<studentActivities.length; i++){
var studentActivity = {};
studentActivity.objectId = studentActivities[i].c[0].v;
studentActivity.objectDefinition = studentActivities[i].c[1].v;
studentActivity.verbId = studentActivities[i].c[2].v;
studentActivity.RelativeTime = studentActivities[i].c[3].v + "";
this.studentActivities.push(studentActivity);
}
};
this.setStudentTimeLinesActivities = function(newStudent){
var studentActivities = [];
var student = {};
student.id = this.studentTimeLinesActivities.length;
var studentActivities=[];;
for(var i = 0; i < newStudent.length; i ++){
var studentActivity = {};
studentActivity.objectId = newStudent[i].c[0].v;
studentActivity.objectDefinition = newStudent[i].c[1].v;
studentActivity.verbId = newStudent[i].c[2].v;
studentActivity.RelativeTime = newStudent[i].c[3].v + "";
studentActivities.push(studentActivity);
}
student.timeLines = studentActivities;
this.studentTimeLinesActivities.push(student);
};
this.getNewStudentPathGraph = function(student){
var studentActivity = [];
for(var i = 0; i < this.modelActivities.length; i++){
var sar = {};
sar.serial = this.modelActivities[i].serial;
sar.objectDefinition = this.modelActivities[i].objectDefinition;
sar.verbId = this.modelActivities[i].verbId;
for(var j = 0; j < student.timeLines.length; j++){
if(this.modelActivities[i].objectId === student.timeLines[j].objectId){
sar.relativeTime = parseInt(student.timeLines[j].RelativeTime);
sar.relativeTimeCont = parseInt(student.timeLines[j].RelativeTime);
break;
} else {
sar.relativeTime = -1;
if(i > 0){
sar.relativeTimeCont = 0//studentActivity[i-1].relativeTimeCont;
}else{
sar.relativeTimeCont = 0;
}
}
}
studentActivity.push(sar);
}
studentActivity.color = getRandomColor();
return studentActivity;
};
/*
* transforms the data so that the user can be drawn on the visualisation
* @returns {Array}
*/
this.getGraphStudentsActivitiesRelative = function(){
var studentActivitiesRelative=[];
for(var i = 0; i < this.modelActivities.length; i++){
var sar = {};
sar.serial = this.modelActivities[i].serial;
sar.objectDefinition = this.modelActivities[i].objectDefinition;
sar.verbId = this.modelActivities[i].verbId;
for(var j = 0; j < this.studentActivities.length; j++){
if(this.modelActivities[i].objectId === this.studentActivities[j].objectId){
sar.studentActivity = parseInt(this.studentActivities[j].RelativeTime);
sar.studentActivityCont = parseInt(this.studentActivities[j].RelativeTime);
break;
}else {
sar.studentActivity = -1;
if(i>0){
sar.studentActivityCont = studentActivitiesRelative[i-1].studentActivityCont;
}
else{
sar.studentActivityCont = 0;
}
}
}
studentActivitiesRelative[i] = sar;
};
return studentActivitiesRelative;
};
/*
* Calculates the highest relative time
* Ex. This can be used to make the Y-Axis in a d3graph
* @returns {Number}highest value
*/
this.getHightYAxis = function(){
var highestValue = 0;
for(var i = 0; i < this.modelActivities.length; i++){
if(parseInt(this.modelActivities[i].relativeTime) > highestValue){
highestValue = parseInt(this.modelActivities[i].relativeTime);
}
}
/* console.log(this.modelActivities.length);
for(var i = 0; i < this.studentActivities.length; i++){
if(parseInt(this.studentActivities[i].RelativeTime) > highestValue){
highestValue = parseInt(this.studentActivities[i].RelativeTime);
}
}
console.log(this.studentActivities.length)
for(var i = 0; i < this.studentTimeLinesActivities.length; i++){
for(var j = 0; j < this.studentTimeLinesActivities[i].timeLines.length;j++){
if(parseInt(this.studentTimeLinesActivities[i].timeLines[j].RelativeTime) > highestValue){
highestValue = parseInt(this.studentTimeLinesActivities[i].timeLines[j].RelativeTime);
}
}
}
console.log(this.studentTimeLinesActivities.length); */
return highestValue;
};
};
//OTHER FUNCTIONS
/*
* Generates a random color
* @returns {String}
*/
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
//DATABASE CALLS
/*
* Read the activityPath from a JSON file.
*/
function getModelActivityPathFromJSON(){
var activityPath = [];
$.ajax({
type:"GET",
dataType: "json",
url: "LAD-Tools/StudentPath/activityPath.json",
async:false,
success: function(data){
activityPath = data.activityPath;
}
});
return activityPath;
}
function getColorIcon(relativeStudentTime){
if(relativeStudentTime === -1){
return "red";
}
else {
return "#006633";
}
}
/*
* returns the icon code for drawing the graph icons
*/
function getCorrectFontAwesomeIcon(objectDefinition, verbId){
if(objectDefinition === "http://activitystrea.ms/schema/1.0/video"){
return '\uf008';
}
if(objectDefinition === "http://activitystrea.ms/schema/1.0/task" && verbId === "http://activitystrea.ms/schema/1.0/access"){
return '\uf0ae';
}
if(objectDefinition === "http://activitystrea.ms/schema/1.0/task" && verbId === "http://activitystrea.ms/schema/1.0/submit"){
return '\uf1d9';
}
if(objectDefinition === "http://activitystrea.ms/schema/1.0/article"){
return '\uf0f6';
}
if(objectDefinition === "http://activitystrea.ms/schema/1.0/forum" && (verbId === "http://activitystrea.ms/schema/1.0/author" || verbId === "http://activitystrea.ms/schema/1.0/comment") ){
return '\uf0c0';
}
if(objectDefinition === "http://activitystrea.ms/schema/1.0/assessment" && verbId === "http://activitystrea.ms/schema/1.0/access"){
return '\uf14b';
}
if(objectDefinition === "http://activitystrea.ms/schema/1.0/assessment" && verbId === "http://activitystrea.ms/schema/1.0/submit"){
return '\uf1d8';
}
if(objectDefinition === "http://activitystrea.ms/schema/1.0/slide-deck" && verbId === "http://activitystrea.ms/schema/1.0/access"){
return '\uf1c4';
}
}
/*
* Transforms the JSON in data that draws all the users on the graph
* @returns {Array|MOOCpath.getAllStudentsPathGraph.studentTLActivities}
this.getAllStudentsPathGraph = function(){
var studentTLActivities=[];
for(var h = 0; h < this.studentTimeLinesActivities.length;h++){
var studentActivity = this.getNewStudentPathGraph(this.studentTimeLinesActivities[h]);
studentTLActivities.push(studentActivity);
}
return studentTLActivities;
};*/
/*
* This is the function to add a row to the graphModel
* @param {type} studentActivity:
* @returns {undefined}
this.addStudentTimeLineActivity = function(studentActivity){
this.studentTimeLinesActivities.push(studentActivity);
};
*/
/*
* transforms the json in actorobject with each an array of activities
* @returns {Array|MOOCpath.makeStudentTimeLines.studentList}
*/
// this.makeStudentTimeLines = function(){
// var studentList = [];
//GETTING UNIQUE STUDENTS FROM LIST
// if (this.studentTimeLinesActivities.length == 0) return 10;
// studentList.push({actorId:this.studentTimeLinesActivities[0].actorId,timeLines:[]});
// for(var i = 1; i<this.studentTimeLinesActivities.length; i++){
// var flag = false;
// for(var j = 0; j < studentList.length; j++){
// if(this.studentTimeLinesActivities[i].actorId === studentList[j].actorId){
// flag = true;
// }
// }
// if(flag === false){
// studentList.push({actorId: this.studentTimeLinesActivities[i].actorId,timeLines:[]});
// }
// }
// for(var i = 0; i < this.studentTimeLinesActivities.length; i++){
// for(var j = 0; j < studentList.length; j++){
// if(this.studentTimeLinesActivities[i].actorId === studentList[j].actorId){
// studentList[j].timeLines.push({objectId:this.studentTimeLinesActivities[i].objectId,objectDefinition:this.studentTimeLinesActivities[i].objectDefinition,verbId:this.studentTimeLinesActivities[i].verbId, relativeTime:this.studentTimeLinesActivities[i].RelativeTime});
// };
// }
// }
// return studentList;
// } ;
| lgpl-3.0 |
sysbiolux/IDARE | METANODE-CREATOR/src/main/java/idare/sbmlannotator/internal/SBMLAnnotationTaskFactory.java | 11146 | package idare.sbmlannotator.internal;
import idare.Properties.IDAREProperties;
import idare.imagenode.internal.IDAREImageNodeApp;
import idare.imagenode.internal.Services.JSBML.Annotation;
import idare.imagenode.internal.Services.JSBML.CVTerm;
import idare.imagenode.internal.Services.JSBML.CVTerm.Qualifier;
import idare.imagenode.internal.Services.JSBML.Model;
import idare.imagenode.internal.Services.JSBML.SBMLDocument;
import idare.imagenode.internal.Services.JSBML.SBMLManagerHolder;
import idare.imagenode.internal.Services.JSBML.Species;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.swing.JOptionPane;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.task.NetworkViewTaskFactory;
import org.cytoscape.util.swing.FileUtil;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.work.AbstractTaskFactory;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.TaskMonitor.Level;
public class SBMLAnnotationTaskFactory extends AbstractTaskFactory implements
NetworkViewTaskFactory {
protected CyApplicationManager cyAppMgr;
protected CyEventHelper eventHelper;
protected final FileUtil fileutil;
protected CySwingApplication cySwingApp;
private SBMLManagerHolder SBMLListener;
private IDAREImageNodeApp app;
public SBMLAnnotationTaskFactory(final CyApplicationManager applicationManager,
CyEventHelper eventHelper, FileUtil fileutil, CySwingApplication cySwingApp,SBMLManagerHolder SBMLListener, IDAREImageNodeApp app) {
this.cyAppMgr = applicationManager;
this.fileutil = fileutil;
this.eventHelper = eventHelper;
this.cySwingApp = cySwingApp;
this.SBMLListener = SBMLListener;
this.app = app;
}
@Override
public TaskIterator createTaskIterator() {
return createTask();
}
@Override
public boolean isReady()
{
return cyAppMgr.getCurrentNetwork() != null;
}
@Override
public TaskIterator createTaskIterator(CyNetworkView arg0) {
return createTask();
}
@Override
public boolean isReady(CyNetworkView arg0) {
return true;
}
private TaskIterator createTask()
{
HashSet<String> geneAnnotationURIs = new HashSet<String>();
HashSet<String> proteinAnnotationURIs = new HashSet<String>();
Map<String,Set<CVTerm>> ProtAnnot = new HashMap<String, Set<CVTerm>>();
String ProtAnnotDB = null;
String GeneAnnotDB = null;
Model model = null;
String SBMLTypeCol = null;
String SBMLIDCol = null;
String SBMLCompCol = null;
String SBMLInteractionCol = null;
SBMLDocument doc = null;
CyNetwork network = cyAppMgr.getCurrentNetwork();
if(network == null)
{
JOptionPane.showMessageDialog(null, "Please select a network to apply the SBML annotation to");
return null;
}
doc = SBMLListener.readSBML(network);
if(doc != null)
{
//Select the current Network
//If we want to read Gene nodes check whether there is a specific annotation.
Vector<String> diffvals = new Vector<String>();
for(CyColumn col : network.getDefaultNodeTable().getColumns())
{
diffvals.add(col.getName());
}
diffvals.remove(null);
diffvals.remove("");
if(diffvals.contains("sbml type"))
{
// we are in file parsed with the default sbml parser
SBMLTypeCol = "sbml type";
SBMLIDCol = "sbml id";
SBMLCompCol = "sbml compartment";
SBMLInteractionCol = "interaction type";
}
else if(diffvals.contains("sbml-type"))
{
//This is a cysbml parsed file.
SBMLTypeCol = "sbml-type";
SBMLIDCol = "id";
SBMLCompCol = "compartment";
SBMLInteractionCol = "sbml-interaction";
}
if(SBMLTypeCol == null)
{
//Otherwise: ask
Object sbmlTypeCol = JOptionPane.showInputDialog(cySwingApp.getJFrame(), "Select a column for the SBML Type",
"SBML Type Column Selection", JOptionPane.QUESTION_MESSAGE, null, diffvals.toArray(), diffvals.get(0));
if(sbmlTypeCol != null)
{
SBMLTypeCol = sbmlTypeCol.toString();
}
}
if(SBMLIDCol == null)
{
Object sbmlIDCol = JOptionPane.showInputDialog(cySwingApp.getJFrame(), "Select a column for the SBML ID",
"SBML ID Column Selection", JOptionPane.QUESTION_MESSAGE, null, diffvals.toArray(), diffvals.get(0));
if(sbmlIDCol != null)
{
SBMLIDCol = sbmlIDCol.toString();
}
}
if(SBMLCompCol == null)
{
Object sbmlCompCol = JOptionPane.showInputDialog(cySwingApp.getJFrame(), "Select a column for the SBML Compartment",
"SBML Compartment Column Selection", JOptionPane.QUESTION_MESSAGE, null, diffvals.toArray(), diffvals.get(0));
if(sbmlCompCol != null)
{
SBMLTypeCol = sbmlCompCol.toString();
}
}
if(SBMLInteractionCol == null)
{
Vector<String> edgecols = new Vector<String>();
for(CyColumn col : network.getDefaultEdgeTable().getColumns())
{
edgecols.add(col.getName());
}
edgecols.remove(null);
edgecols.remove("");
Object sbmlIntCol = JOptionPane.showInputDialog(cySwingApp.getJFrame(), "Select a column for the interaction Type",
"SBML Interaction Column Selection", JOptionPane.QUESTION_MESSAGE, null, edgecols.toArray(), edgecols.get(0));
if(sbmlIntCol != null)
{
SBMLInteractionCol = sbmlIntCol.toString();
}
}
if(SBMLIDCol == null || SBMLTypeCol == null || SBMLCompCol == null)
{
return null;
}
int confirmation = JOptionPane.showConfirmDialog(cySwingApp.getJFrame(), "Would you like to add Gene Nodes?");
if(confirmation == JOptionPane.YES_OPTION)
{
try
{
model = doc.getModel();
for (Species species : model.getListOfSpecies())
{
if(species.isSetAnnotation())
{
Annotation speciesAnnotation = species.getAnnotation();
List<CVTerm> CVTerms = speciesAnnotation.getListOfCVTerms();
//Checking whether it is annotated as polypeptide chain or as enzyme
if(species.getSBOTerm() == 14 || species.getSBOTerm() == 252)
{
if(!ProtAnnot.containsKey(species.getId()))
{
ProtAnnot.put(species.getId(), new HashSet<CVTerm>());
}
}
for(CVTerm cv : CVTerms)
{
//Ok, We have an enzyme (otherwise a species should not be 'Encoded' by anything)
if(cv.getBiologicalQualifierType() == Qualifier.BQB_IS_ENCODED_BY)
{
//isProtein = true;
if(!ProtAnnot.containsKey(species.getId()))
{
ProtAnnot.put(species.getId(), new HashSet<CVTerm>());
}
ProtAnnot.get(species.getId()).add(cv);
for(String ressource : cv.getResources())
{
//We assume, that we have a URI of the form: http://authority/database/Entry
readURIString(ressource, geneAnnotationURIs, true);
}
}
}
if(ProtAnnot.containsKey(species.getId()))
{
//if this is a protein
for(CVTerm cv : CVTerms)
{
// check which databases are used for the reference.
if(cv.getBiologicalQualifierType() == Qualifier.BQB_IS)
{
ProtAnnot.get(species.getId()).add(cv);
for(String ressource : cv.getResources())
{
//We assume, that we have a URI of the form: http://authority/database/Entry
//or urn:authority:database:entry
readURIString(ressource, proteinAnnotationURIs, true);
}
}
}
}
}
}
if(geneAnnotationURIs.size() > 0)
{
//this only happens if we actually obtain some protein species, so we need to setup the
//IDARE Node type row to assign the respective proteins.
Object GeneAnnotSelect = JOptionPane.showInputDialog(cySwingApp.getJFrame(), "Select a database for Gene Annotations",
"Database selection", JOptionPane.QUESTION_MESSAGE, null, geneAnnotationURIs.toArray(), geneAnnotationURIs.toArray()[0]);
if(GeneAnnotSelect != null)
{
GeneAnnotDB = GeneAnnotSelect.toString();
}
// System.out.println("The selected Database is : " + GeneAnnotDB);
if(GeneAnnotDB == null)
{
return null;
}
}
if(proteinAnnotationURIs.size() > 0)
{
if(network.getDefaultNodeTable().getColumn(IDAREProperties.SBML_NAME_STRING) != null)
{
geneAnnotationURIs.add(IDAREProperties.SBML_NAME_STRING);
}
//this only happens if we actually obtain some protein species, so we need to setup the
//IDARE Node type row to assign the respective proteins.
Object ProtAnnotSelect = JOptionPane.showInputDialog(cySwingApp.getJFrame(), "Select a database for Protein Annotations",
"Database selection", JOptionPane.QUESTION_MESSAGE, null, proteinAnnotationURIs.toArray(), proteinAnnotationURIs.toArray()[0]);
if(ProtAnnotSelect != null)
{
ProtAnnotDB = ProtAnnotSelect.toString();
}
// System.out.println("The selected Database is : " + ProtAnnotDB);
if(ProtAnnotDB == null)
{
return null;
}
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(cySwingApp.getJFrame(), "Error while determining Gene and Protein Information. \nSkipping Genes and Proteins", "Could not parse Genes/Proteins", JOptionPane.INFORMATION_MESSAGE);
}
}
TaskIterator SATF;
if(confirmation == JOptionPane.YES_OPTION)
{
SATF = new TaskIterator(new SBMLAnnotaterTask(cyAppMgr, doc ,true,eventHelper, GeneAnnotDB, ProtAnnotDB,ProtAnnot, SBMLTypeCol,SBMLIDCol,SBMLCompCol,SBMLInteractionCol,app));
}
else
{
SATF = new TaskIterator(new SBMLAnnotaterTask(cyAppMgr, doc ,false,eventHelper, null, ProtAnnotDB,ProtAnnot, SBMLTypeCol,SBMLIDCol,SBMLCompCol,SBMLInteractionCol,app));
}
return SATF;
}
return new TaskIterator(new Task() {
@Override
public void run(TaskMonitor taskMonitor) throws Exception {
// TODO Auto-generated method stub
taskMonitor.showMessage(Level.WARN, "No SBML File Selected");
taskMonitor.setTitle("SBML Annotation Unsuccessful");
taskMonitor.setStatusMessage("No SBML File selected");
}
@Override
public void cancel() {
// TODO Auto-generated method stub
}
});
}
protected void readURIString(String URI, Set<String> URICollection, boolean database)
{
int position = 0;
if(database)
{
position = 3;
}
else
{
position = 4;
}
if(URI.matches("http://.*/.*/.*"))
{
try
{
String entryname = URI.split("/")[position];
URICollection.add(entryname);
}
catch(IndexOutOfBoundsException ex)
{
//Do Nothing
}
}
if(URI.matches(".*:.*:.*:.*"))
{
try
{
String entryname = URI.split(":")[position - 1];
URICollection.add(entryname);
}
catch(IndexOutOfBoundsException ex)
{
//Do Nothing
}
}
}
}
| lgpl-3.0 |
joansmith/sonarqube | sonar-batch/src/main/java/org/sonar/batch/postjob/DefaultPostJobContext.java | 4306 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.postjob;
import org.sonar.batch.issue.tracking.TrackedIssue;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import javax.annotation.Nullable;
import org.sonar.api.batch.AnalysisMode;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.postjob.PostJobContext;
import org.sonar.api.batch.postjob.issue.Issue;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.config.Settings;
import org.sonar.api.rule.RuleKey;
import org.sonar.batch.index.BatchComponent;
import org.sonar.batch.index.BatchComponentCache;
import org.sonar.batch.issue.IssueCache;
public class DefaultPostJobContext implements PostJobContext {
private final Settings settings;
private final AnalysisMode analysisMode;
private final IssueCache cache;
private final BatchComponentCache resourceCache;
public DefaultPostJobContext(Settings settings, AnalysisMode analysisMode, IssueCache cache, BatchComponentCache resourceCache) {
this.settings = settings;
this.analysisMode = analysisMode;
this.cache = cache;
this.resourceCache = resourceCache;
}
@Override
public Settings settings() {
return settings;
}
@Override
public AnalysisMode analysisMode() {
return analysisMode;
}
@Override
public Iterable<Issue> issues() {
return Iterables.transform(Iterables.filter(cache.all(), new ResolvedPredicate(false)), new IssueTransformer());
}
@Override
public Iterable<Issue> resolvedIssues() {
return Iterables.transform(Iterables.filter(cache.all(), new ResolvedPredicate(true)), new IssueTransformer());
}
private class DefaultIssueWrapper implements Issue {
private final TrackedIssue wrapped;
public DefaultIssueWrapper(TrackedIssue wrapped) {
this.wrapped = wrapped;
}
@Override
public String key() {
return wrapped.key();
}
@Override
public RuleKey ruleKey() {
return wrapped.getRuleKey();
}
@Override
public String componentKey() {
return wrapped.componentKey();
}
@Override
public InputComponent inputComponent() {
BatchComponent component = resourceCache.get(wrapped.componentKey());
return component != null ? component.inputComponent() : null;
}
@Override
public Integer line() {
return wrapped.startLine();
}
@Override
public Double effortToFix() {
return wrapped.effortToFix();
}
@Override
public String message() {
return wrapped.getMessage();
}
@Override
public Severity severity() {
String severity = wrapped.severity();
return severity != null ? Severity.valueOf(severity) : null;
}
@Override
public boolean isNew() {
return wrapped.isNew();
}
}
private class IssueTransformer implements Function<TrackedIssue, Issue> {
@Override
public Issue apply(TrackedIssue input) {
return new DefaultIssueWrapper(input);
}
}
private static class ResolvedPredicate implements Predicate<TrackedIssue> {
private final boolean resolved;
private ResolvedPredicate(boolean resolved) {
this.resolved = resolved;
}
@Override
public boolean apply(@Nullable TrackedIssue issue) {
if (issue != null) {
return resolved ? issue.resolution() != null : issue.resolution() == null;
}
return false;
}
}
}
| lgpl-3.0 |
ourbest/sns_app | backend/migrations/0001_initial.py | 8648 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-10 09:15
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='App',
fields=[
('app_id', models.IntegerField(primary_key=True, serialize=False, verbose_name='ID')),
('app_name', models.CharField(max_length=32, verbose_name='名称')),
],
),
migrations.CreateModel(
name='AppUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30, verbose_name='名字')),
('cutt_user_id', models.IntegerField(verbose_name='生活圈用户ID')),
('memo', models.CharField(max_length=50, verbose_name='备注')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='添加时间')),
],
),
migrations.CreateModel(
name='PhoneDevice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('label', models.CharField(max_length=50, verbose_name='编号')),
('phone_num', models.CharField(max_length=20, verbose_name='手机号')),
('type', models.IntegerField(default=1, help_text='0 - 手机,1 - 虚拟机', verbose_name='类型')),
('model', models.CharField(max_length=20, verbose_name='型号')),
('system', models.CharField(max_length=50, verbose_name='系统和版本')),
('status', models.IntegerField(default=0, verbose_name='状态')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='添加时间')),
],
),
migrations.CreateModel(
name='SnsGroup',
fields=[
('group_id', models.CharField(max_length=50, primary_key=True, serialize=False, verbose_name='群ID')),
('type', models.IntegerField(default=0, verbose_name='类型')),
('group_name', models.CharField(max_length=50, verbose_name='群名')),
('group_user_count', models.IntegerField(default=0, verbose_name='群用户数')),
('status', models.IntegerField(default=0, verbose_name='状态')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='添加时间')),
],
),
migrations.CreateModel(
name='SnsGroupUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nick', models.CharField(max_length=50, verbose_name='昵称')),
('title', models.CharField(max_length=20, verbose_name='头衔')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='添加时间')),
('status', models.IntegerField(default=0, verbose_name='状态')),
('updated_at', models.DateTimeField(auto_now=True, verbose_name='修改时间')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.SnsGroup', verbose_name='群')),
],
),
migrations.CreateModel(
name='SnsUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30, verbose_name='显示名')),
('type', models.IntegerField(verbose_name='类型')),
('login_name', models.CharField(max_length=30, verbose_name='登录名')),
('passwd', models.CharField(max_length=30, verbose_name='密码')),
('status', models.IntegerField(default=0, verbose_name='状态')),
('memo', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('phone', models.CharField(max_length=30, verbose_name='电话')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')),
('bot_login_token', models.BinaryField(blank=True, null=True)),
('app', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.App', verbose_name='生活圈')),
('device', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='backend.PhoneDevice', verbose_name='设备')),
],
),
migrations.CreateModel(
name='SnsUserGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nick_name', models.CharField(max_length=50, verbose_name='备注名')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='加入时间')),
('status', models.IntegerField(default=0, verbose_name='状态')),
('active', models.IntegerField(default=0, verbose_name='可用')),
('last_post_at', models.DateTimeField(null=True, verbose_name='最后分发时间')),
('sns_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.SnsGroup', verbose_name='群')),
('sns_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.SnsUser', verbose_name='用户')),
],
),
migrations.CreateModel(
name='SnsUserInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.IntegerField(default=0, help_text='0 - QQ 1 - 微信')),
('uin', models.CharField(max_length=50)),
('user_id', models.CharField(max_length=50)),
('nick', models.CharField(max_length=100)),
('avatar', models.CharField(max_length=255)),
('memo', models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30, verbose_name='姓名')),
('email', models.CharField(max_length=50, verbose_name='邮箱')),
('status', models.IntegerField(default=0, verbose_name='状态')),
('passwd', models.CharField(max_length=50, verbose_name='密码')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
],
),
migrations.CreateModel(
name='UserActionLog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('action', models.CharField(max_length=20)),
('memo', models.CharField(max_length=255)),
('action_time', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.User')),
],
),
migrations.AddField(
model_name='snsuser',
name='owner',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='backend.User', verbose_name='所有者'),
),
migrations.AddField(
model_name='snsgroupuser',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.SnsUserInfo', verbose_name='用户'),
),
migrations.AddField(
model_name='phonedevice',
name='owner',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='backend.User', verbose_name='所有者'),
),
migrations.AddField(
model_name='appuser',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.User', verbose_name='属于'),
),
]
| lgpl-3.0 |
Pagesmith/pagesmith-core | htdocs/core/dalliance/js/spans.js | 4673 | /* jshint ignore:start */
/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */
//
// Dalliance Genome Explorer
// (c) Thomas Down 2006-2010
//
// spans.js: JavaScript Intset/Location port.
//
function Range(min, max)
{
if (typeof(min) != 'number' || typeof(max) != 'number')
throw 'Bad range ' + min + ',' + max;
this._min = min;
this._max = max;
}
Range.prototype.min = function() {
return this._min;
}
Range.prototype.max = function() {
return this._max;
}
Range.prototype.contains = function(pos) {
return pos >= this._min && pos <= this._max;
}
Range.prototype.isContiguous = function() {
return true;
}
Range.prototype.ranges = function() {
return [this];
}
Range.prototype._pushRanges = function(ranges) {
ranges.push(this);
}
Range.prototype.toString = function() {
return '[' + this._min + '-' + this._max + ']';
}
function _Compound(ranges) {
this._ranges = ranges;
// assert sorted?
}
_Compound.prototype.min = function() {
return this._ranges[0].min();
}
_Compound.prototype.max = function() {
return this._ranges[this._ranges.length - 1].max();
}
_Compound.prototype.contains = function(pos) {
// FIXME implement bsearch if we use this much.
for (var s = 0; s < this._ranges.length; ++s) {
if (this._ranges[s].contains(pos)) {
return true;
}
}
return false;
}
_Compound.prototype.isContiguous = function() {
return this._ranges.length > 1;
}
_Compound.prototype.ranges = function() {
return this._ranges;
}
_Compound.prototype._pushRanges = function(ranges) {
for (var ri = 0; ri < this._ranges.length; ++ri)
ranges.push(this._ranges[ri]);
}
_Compound.prototype.toString = function() {
var s = '';
for (var r = 0; r < this._ranges.length; ++r) {
if (r>0) {
s = s + ',';
}
s = s + this._ranges[r].toString();
}
return s;
}
function union(s0, s1) {
if (! (s0 instanceof Array)) {
s0 = [s0];
if (s1)
s0.push(s1);
}
if (s0.length == 0)
return null;
else if (s0.length == 1)
return s0[0];
var ranges = [];
for (var si = 0; si < s0.length; ++si)
s0[si]._pushRanges(ranges);
ranges = ranges.sort(_rangeOrder);
var oranges = [];
var current = ranges[0];
current = new Range(current._min, current._max); // Copy now so we don't have to later.
for (var i = 1; i < ranges.length; ++i) {
var nxt = ranges[i];
if (nxt._min > (current._max + 1)) {
oranges.push(current);
current = new Range(nxt._min, nxt._max);
} else {
if (nxt._max > current._max) {
current._max = nxt._max;
}
}
}
oranges.push(current);
if (oranges.length == 1) {
return oranges[0];
} else {
return new _Compound(oranges);
}
}
function intersection(s0, s1) {
var r0 = s0.ranges();
var r1 = s1.ranges();
var l0 = r0.length, l1 = r1.length;
var i0 = 0, i1 = 0;
var or = [];
while (i0 < l0 && i1 < l1) {
var s0 = r0[i0], s1 = r1[i1];
var lapMin = Math.max(s0.min(), s1.min());
var lapMax = Math.min(s0.max(), s1.max());
if (lapMax >= lapMin) {
or.push(new Range(lapMin, lapMax));
}
if (s0.max() > s1.max()) {
++i1;
} else {
++i0;
}
}
if (or.length == 0) {
return null; // FIXME
} else if (or.length == 1) {
return or[0];
} else {
return new _Compound(or);
}
}
function coverage(s) {
var tot = 0;
var rl = s.ranges();
for (var ri = 0; ri < rl.length; ++ri) {
var r = rl[ri];
tot += (r.max() - r.min() + 1);
}
return tot;
}
function rangeOrder(a, b)
{
if (a.min() < b.min()) {
return -1;
} else if (a.min() > b.min()) {
return 1;
} else if (a.max() < b.max()) {
return -1;
} else if (b.max() > a.max()) {
return 1;
} else {
return 0;
}
}
function _rangeOrder(a, b)
{
if (a._min < b._min) {
return -1;
} else if (a._min > b._min) {
return 1;
} else if (a._max < b._max) {
return -1;
} else if (b._max > a._max) {
return 1;
} else {
return 0;
}
}
if (typeof(module) !== 'undefined') {
module.exports = {
Range: Range,
union: union,
intersection: intersection,
coverage: coverage,
rangeOver: rangeOrder,
_rangeOrder: _rangeOrder
}
}
/* jshint ignore:end */
| lgpl-3.0 |
VahidN/PdfReport | Lib/DataAnnotations/IsVisibleAttribute.cs | 838 | using System;
namespace PdfRpt.DataAnnotations
{
/// <summary>
/// Defining how a property of MainTableDataSource should be rendered as a column's cell.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class IsVisibleAttribute : Attribute
{
/// <summary>
/// Defining how a property of MainTableDataSource should be rendered as a column's cell.
/// </summary>
/// <param name="isVisible">Determines exclusion or visibility of this column.</param>
public IsVisibleAttribute(bool isVisible)
{
IsVisible = isVisible;
}
/// <summary>
/// Defining a group of rows by including this filed in grouping.
/// </summary>
public bool IsVisible { private set; get; }
}
} | lgpl-3.0 |
stevleibelt/setup | bin/user_user_create.php | 1475 | <?php
/**
* @author stev leibelt <[email protected]>
* @since 2015-01-10
*/
use Setup\AbstractApplication;
use Setup\Command\User;
require_once __DIR__ . '/../vendor/autoload.php';
/**
* Class UserCreate
*/
class UserCreate extends AbstractApplication
{
/**
* @param array $arguments
* @throws Exception
*/
protected function execute(array $arguments = array())
{
$command = new User();
$users = require_once $arguments[0];
$command->create($users);
}
/**
* @param array $arguments
* @throws InvalidArgumentException
*/
protected function validateArguments(array $arguments = array())
{
if (count($arguments) != 1) {
throw new InvalidArgumentException(
'invalid number of arguments provided'
);
}
if (!is_file($arguments[0])) {
throw new InvalidArgumentException(
'provided configuration file path does not exist'
);
}
if (!is_readable($arguments[0])) {
throw new InvalidArgumentException(
'provided configuration file path is not readable'
);
}
//@todo validate configuration file
}
/**
* @return string
*/
protected function usage()
{
return basename(__FILE__) . ' <path to configuration file>';
}
}
$application = new UserCreate($argv);
$application->run(); | lgpl-3.0 |
molszewski/dante | module/AlgorithmsFramework/src/net/java/dante/algorithms/data/TileData.java | 247 | /*
* Created on 2006-09-11
*
* @author M.Olszewski
*/
package net.java.dante.algorithms.data;
/**
* Data of the map's tile.
*
* @author M.Olszewski
*/
public interface TileData extends SimpleObjectData
{
// Intentionally left empty.
} | lgpl-3.0 |
exo-codefest/2015-team-G | webapp/src/main/java/org/exoplatform/pinsmind/assets/mindboard.js | 708 | (function ($) {
$(document).ready(function () {
$('#btn-submit').click(function () {
$('#addNewIdeaForm').submit();
});
$('#newIdeaButton').click(function () {
var modal = $('#newIdeaModal');
modal.show();
modal.css("top", $(window).height()/2 -150);
modal.css("left", $(window).width()/2 + 150);
});
$('#closeNewIdeaButton').click(function () {
$('#newIdeaModal').hide();
});
$("#information").click(
function () {
var modal = $('#introductionModal');
modal.show();
modal.css("top", $(window).height()/2-300);
modal.css("left", $(window).width()/2);
});
$('#closeInfo').click(function () {
$('#introductionModal').hide();
});
});
})($); | lgpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.