code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
package org.menesty.ikea.ui.pages.ikea.order.dialog.invoice;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.paint.Color;
import org.menesty.ikea.i18n.I18n;
import org.menesty.ikea.i18n.I18nKeys;
import org.menesty.ikea.lib.service.parse.pdf.invoice.InvoiceParseResult;
import org.menesty.ikea.lib.service.parse.pdf.invoice.RawInvoiceItem;
import org.menesty.ikea.util.ColumnUtil;
import org.menesty.ikea.util.NumberUtil;
import java.math.BigDecimal;
/**
* Created by Menesty on
* 10/5/15.
* 22:16.
*/
class InvoiceInformationTableView extends TableView<InvoiceParseResult> {
public InvoiceInformationTableView() {
{
TableColumn<InvoiceParseResult, String> column = new TableColumn<>(I18n.UA.getString(I18nKeys.FILE_NAME));
column.setPrefWidth(100);
column.setCellValueFactory(ColumnUtil.column("invoiceInformation.fileName"));
getColumns().add(column);
}
{
TableColumn<InvoiceParseResult, String> column = new TableColumn<>(I18n.UA.getString(I18nKeys.INVOICE_NAME));
column.setPrefWidth(120);
column.setCellValueFactory(ColumnUtil.column("invoiceInformation.invoiceName"));
getColumns().add(column);
}
{
TableColumn<InvoiceParseResult, String> column = new TableColumn<>(I18n.UA.getString(I18nKeys.PARAGON_NUMBER));
column.setCellValueFactory(ColumnUtil.column("invoiceInformation.paragonNumber"));
column.setPrefWidth(90);
getColumns().add(column);
}
{
TableColumn<InvoiceParseResult, String> column = new TableColumn<>(I18n.UA.getString(I18nKeys.SELL_DATE));
column.setCellValueFactory(ColumnUtil.dateColumn("invoiceInformation.sellDate"));
column.setPrefWidth(110);
getColumns().add(column);
}
{
TableColumn<InvoiceParseResult, String> column = new TableColumn<>(I18n.UA.getString(I18nKeys.AMOUNT));
column.setCellValueFactory(ColumnUtil.number("invoiceInformation.payed"));
column.setPrefWidth(80);
getColumns().add(column);
}
{
TableColumn<InvoiceParseResult, String> column = new TableColumn<>(I18n.UA.getString(I18nKeys.ITEM_AMOUNT));
column.setCellValueFactory(param -> {
if (param.getValue() != null) {
BigDecimal itemsAmount = param.getValue().getRawInvoiceItems().stream().map(RawInvoiceItem::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
boolean same = itemsAmount.compareTo(param.getValue().getInvoiceInformation().getPayed()) == 0;
return new SimpleStringProperty(NumberUtil.toString(itemsAmount.doubleValue()) + (same ? "" : " "));
}
return new SimpleStringProperty("");
});
column.setCellFactory(param -> new TableCell<InvoiceParseResult, String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
this.setText(item);
setTextFill((!isEmpty() && item.endsWith(" ")) ? Color.RED : Color.BLACK);
}
}
});
column.setPrefWidth(120);
getColumns().add(column);
}
}
}
| menesty/ikea | src/main/java/org/menesty/ikea/ui/pages/ikea/order/dialog/invoice/InvoiceInformationTableView.java | Java | lgpl-3.0 | 3,254 |
<?php
/**
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public License, Version 3
* @author Rafał Wrzeszcz <rafal.wrzeszcz@wrzasq.pl>
* @copyright 2009 - 2011 (C) by Rafał Wrzeszcz - Wrzasq.pl.
* @version 0.0.3
* @since 0.0.1
* @package Hormon
* @subpackage Queries
*/
namespace Hormon\Queries;
/**
* INSERT statement that takes SELECT query as data source.
*
* @author Rafał Wrzeszcz <rafal.wrzeszcz@wrzasq.pl>
* @copyright 2009 - 2011 (C) by Rafał Wrzeszcz - Wrzasq.pl.
* @version 0.0.3
* @since 0.0.1
* @package Hormon
* @subpackage Queries
*/
interface InsertWithSelectQueryInterface extends InsertQueryInterface
{
/**
* Sets data source query.
*
* @param SelectQueryInterface $query Source query.
* @return InsertWithSelectQueryInterface Self instance.
* @version 0.0.3 Implements fluent interface.
* @since 0.0.1
*/
public function setSelect(SelectQueryInterface $query);
/**
* Gets data source query.
*
* @return SelectQueryInterface Source query.
* @version 0.0.1
* @since 0.0.1
*/
public function getSelect();
}
| chilloutdevelopment/Hormon | lib/Queries/InsertWithSelectQueryInterface.php | PHP | lgpl-3.0 | 1,152 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lazagne.config.constant import constant
from lazagne.config.module_info import ModuleInfo
from lazagne.config import homes
from binascii import hexlify
import traceback
try:
import jeepney.auth
# except ImportError:
except Exception:
pass
else:
# Thanks to @mitya57 for its Work around
def make_auth_external():
hex_uid = hexlify(str(make_auth_external.uid).encode('ascii'))
return b'AUTH EXTERNAL %b\r\n' % hex_uid
jeepney.auth.make_auth_external = make_auth_external
class Libsecret(ModuleInfo):
def __init__(self):
ModuleInfo.__init__(self, 'libsecret', 'wallet')
def run(self):
items = []
visited = set()
try:
import dbus
import secretstorage
import datetime
except ImportError as e:
self.error('libsecret: {0}'.format(e))
return []
for uid, session in homes.sessions():
try:
# List bus connection names
bus = dbus.bus.BusConnection(session)
if 'org.freedesktop.secrets' not in [str(x) for x in bus.list_names()]:
continue
except Exception:
self.error(traceback.format_exc())
continue
collections = None
try:
# Python 2.7
collections = list(secretstorage.collection.get_all_collections(bus))
except Exception:
pass
if not collections:
try:
# Python 3
from jeepney.io.blocking import open_dbus_connection
make_auth_external.uid = uid
bus = open_dbus_connection(session)
collections = secretstorage.get_all_collections(bus)
except Exception:
self.error(traceback.format_exc())
continue
for collection in collections:
if collection.is_locked():
continue
label = collection.get_label()
if label in visited:
continue
visited.add(label)
try:
storage = collection.get_all_items()
except Exception:
self.error(traceback.format_exc())
continue
for item in storage:
values = {
'created': str(datetime.datetime.fromtimestamp(item.get_created())),
'modified': str(datetime.datetime.fromtimestamp(item.get_modified())),
'content-type': item.get_secret_content_type(),
'label': item.get_label(),
'Password': item.get_secret().decode('utf8'),
'collection': label,
}
# for k, v in item.get_attributes().iteritems():
# values[unicode(k)] = unicode(v)
items.append(values)
if item.get_label().endswith('Safe Storage'):
constant.chrome_storage.append(item.get_secret())
try:
bus.flush()
bus.close()
except Exception:
pass
return items
| AlessandroZ/LaZagne | Linux/lazagne/softwares/wallet/libsecret.py | Python | lgpl-3.0 | 3,425 |
/*
* 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.
*/
import * as React from 'react';
import ComponentNavHeader from './ComponentNavHeader';
import ComponentNavMeta from './ComponentNavMeta';
import ComponentNavMenu from './ComponentNavMenu';
import ComponentNavBgTaskNotif from './ComponentNavBgTaskNotif';
import RecentHistory from '../../RecentHistory';
import * as theme from '../../../theme';
import ContextNavBar from '../../../../components/nav/ContextNavBar';
import { STATUSES } from '../../../../apps/background-tasks/constants';
import './ComponentNav.css';
interface Props {
branchLikes: T.BranchLike[];
currentBranchLike: T.BranchLike | undefined;
component: T.Component;
currentTask?: T.Task;
currentTaskOnSameBranch?: boolean;
isInProgress?: boolean;
isPending?: boolean;
location: {};
warnings: string[];
}
export default class ComponentNav extends React.PureComponent<Props> {
mounted = false;
componentDidMount() {
this.populateRecentHistory();
}
componentDidUpdate(prevProps: Props) {
if (this.props.component.key !== prevProps.component.key) {
this.populateRecentHistory();
}
}
populateRecentHistory = () => {
const { breadcrumbs } = this.props.component;
const { qualifier } = breadcrumbs[breadcrumbs.length - 1];
if (['TRK', 'VW', 'APP', 'DEV'].indexOf(qualifier) !== -1) {
RecentHistory.add(
this.props.component.key,
this.props.component.name,
qualifier.toLowerCase(),
this.props.component.organization
);
}
};
render() {
const { component, currentBranchLike, currentTask, isInProgress, isPending } = this.props;
let notifComponent;
if (isInProgress || isPending || (currentTask && currentTask.status === STATUSES.FAILED)) {
notifComponent = (
<ComponentNavBgTaskNotif
component={component}
currentTask={currentTask}
currentTaskOnSameBranch={this.props.currentTaskOnSameBranch}
isInProgress={isInProgress}
isPending={isPending}
/>
);
}
return (
<ContextNavBar
height={notifComponent ? theme.contextNavHeightRaw + 30 : theme.contextNavHeightRaw}
id="context-navigation"
notif={notifComponent}>
<div className="navbar-context-justified">
<ComponentNavHeader
branchLikes={this.props.branchLikes}
component={component}
currentBranchLike={currentBranchLike}
// to close dropdown on any location change
location={this.props.location}
/>
<ComponentNavMeta
branchLike={currentBranchLike}
component={component}
warnings={this.props.warnings}
/>
</div>
<ComponentNavMenu
branchLike={currentBranchLike}
component={component}
// to re-render selected menu item
location={this.props.location}
/>
</ContextNavBar>
);
}
}
| Godin/sonar | server/sonar-web/src/main/js/app/components/nav/component/ComponentNav.tsx | TypeScript | lgpl-3.0 | 3,786 |
package org.sglj.math.search;
public class TBinarySearch<T> {
public abstract class MonotoneFunction<R> {
protected abstract R f(T x);
}
}
| losvald/sglj | src/main/java/org/sglj/math/search/TBinarySearch.java | Java | lgpl-3.0 | 150 |
<?php
/**
*
* SnakeLinks 0.1.201107200446
* Copyright (c) 2011 Snooey.NET
*
* @brief admin class module file.
*
**/
class admin
{
/**
*
* @brief init module.
* @param object $args.
* @return null.
*
**/
function init($args=null)
{
}
}
?> | sople1/SnakeLinks | snakelinks/module/admin/admin.class.php | PHP | lgpl-3.0 | 298 |
<?php
/**
* Copyright (C) 2014 HB Agency
*
* @author Blair Winans <bwinans@hbagency.com>
* @author Adam Fisher <afisher@hbagency.com>
* @link http://www.hbagency.com
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*/
/**
* Table tl_form_submission
*/
$GLOBALS['TL_DCA']['tl_form_submission'] = array
(
// Config
'config' => array
(
'dataContainer' => 'Table',
'ptable' => 'tl_form',
'closed' => true,
'notEditable' => true,
'sql' => array
(
'keys' => array
(
'id' => 'primary',
'pid' => 'index'
)
)
),
// List
'list' => array
(
'sorting' => array
(
'mode' => 2,
'fields' => array('tstamp DESC', 'id DESC'),
'panelLayout' => 'filter;sort,search,limit'
),
'label' => array
(
'fields' => array('tstamp', 'id'),
'format' => '<span style="color:#b3b3b3;padding-right:3px">[%s]</span> Submission # %s',
'maxCharacters' => 96,
),
'global_operations' => array
(
'exportCSV' => array
(
'label' => &$GLOBALS['TL_LANG']['tl_form_submission']['exportCSV'],
'href' => 'key=exportCSV',
'icon' => 'system/modules/hb_formdata/assets/img/icon-csv-016.png',
'attributes' => 'onclick="Backend.getScrollOffset()"'
),
'exportExcel' => array
(
'label' => &$GLOBALS['TL_LANG']['tl_form_submission']['exportExcel'],
'href' => 'key=exportExcel',
'icon' => 'system/modules/hb_formdata/assets/img/icon-excel-016.png',
'attributes' => 'onclick="Backend.getScrollOffset()"'
),
'all' => array
(
'label' => &$GLOBALS['TL_LANG']['MSC']['all'],
'href' => 'act=select',
'class' => 'header_edit_all',
'attributes' => 'onclick="Backend.getScrollOffset()" accesskey="e"'
),
),
'operations' => array
(
'submissions' => array
(
'label' => &$GLOBALS['TL_LANG']['tl_form']['submissions'],
'href' => 'table=tl_form_submission_data',
'icon' => 'system/modules/hb_formdata/assets/img/icon-database-014.png'
),
'delete' => array
(
'label' => &$GLOBALS['TL_LANG']['tl_form_submission']['delete'],
'href' => 'act=delete',
'icon' => 'delete.gif',
'attributes' => 'onclick="if(!confirm(\'' . $GLOBALS['TL_LANG']['MSC']['deleteConfirm'] . '\'))return false;Backend.getScrollOffset()"'
),
'show' => array
(
'label' => &$GLOBALS['TL_LANG']['tl_form_submission']['show'],
'href' => 'act=show',
'icon' => 'show.gif'
)
)
),
// Fields
'fields' => array
(
'id' => array
(
'sql' => "int(10) unsigned NOT NULL auto_increment"
),
'pid' => array
(
'sql' => "int(10) unsigned NOT NULL"
),
'tstamp' => array
(
'label' => &$GLOBALS['TL_LANG']['tl_form_submission']['tstamp'],
'sorting' => true,
'flag' => 6,
'sql' => "int(10) unsigned NOT NULL default '0'"
),
)
);
| hb-agency/contao_hb_formdata | dca/tl_form_submission.php | PHP | lgpl-3.0 | 3,372 |
package element_list_extended;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the element_list_extended package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: element_list_extended
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Foo }
*
*/
public Foo createFoo() {
return new Foo();
}
/**
* Create an instance of {@link Foo.E }
*
*/
public Foo.E createFooE() {
return new Foo.E();
}
}
| dmak/jaxb-xew-plugin | src/test/generated_resources/element_list_extended/ObjectFactory.java | Java | lgpl-3.0 | 1,198 |
/*
BeepBeep, an event stream processor
Copyright (C) 2008-2018 Sylvain Hallé
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ca.uqac.lif.cep.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.junit.Test;
import ca.uqac.lif.cep.Connector;
import ca.uqac.lif.cep.Context;
import ca.uqac.lif.cep.Pushable;
import ca.uqac.lif.cep.functions.ApplyFunction;
import ca.uqac.lif.cep.tmf.SinkLast;
import ca.uqac.lif.xml.TextElement;
import ca.uqac.lif.xml.XPathExpression.XPathParseException;
import ca.uqac.lif.xml.XmlElement;
import ca.uqac.lif.xml.XmlElement.XmlParseException;
/**
* Unit tests for the XML processors
* @author Sylvain Hallé
*/
public class XmlTest
{
@Test
public void testSingle1()
{
ApplyFunction feeder = new ApplyFunction(ParseXml.instance);
Pushable in = feeder.getPushableInput(0);
assertNotNull(in);
SinkLast sink = new SinkLast(1);
Connector.connect(feeder, sink);
in.push("<a>123</a>");
Object[] os = sink.getLast();
assertNotNull(os);
assertEquals(1, os.length);
assertTrue(os[0] instanceof XmlElement);
}
@Test
public void testXPath1() throws XPathParseException, XmlParseException
{
ApplyFunction xpath = new ApplyFunction(new XPathFunction("a/b/text()"));
Pushable in = xpath.getPushableInput(0);
assertNotNull(in);
SinkLast sink = new SinkLast(1);
Connector.connect(xpath, sink);
in.push(XmlElement.parse("<a><b>1</b><b>2</b></a>"));
Object[] os = sink.getLast();
assertNotNull(os);
assertTrue(os[0] instanceof Collection<?>);
}
@Test
public void testXPath2() throws XPathParseException, XmlParseException
{
XPathFunction xpath = new XPathFunction("a[b=$x]/c/text()");
Object[] out = new Object[1];
Context c = new Context();
c.put("x", "1");
xpath.evaluate(new Object[] {XmlElement.parse("<a><b>1</b><c>2</c></a>")}, out, c);
assert (out[0] instanceof Collection<?>);
@SuppressWarnings("unchecked")
Collection<XmlElement> col = (Collection<XmlElement>) out[0];
assertEquals(1, col.size());
for (XmlElement xe : col)
{
assertTrue(xe instanceof TextElement);
assertEquals("2", xe.toString());
}
}
}
| liflab/beepbeep-3-palettes | Xml/src/ca/uqac/lif/cep/xml/XmlTest.java | Java | lgpl-3.0 | 2,927 |
<?php
/**
* @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
* @copyright Aimeos (aimeos.org), 2017-2022
*/
namespace Aimeos\Admin\JQAdm\Order;
class FactoryTest extends \PHPUnit\Framework\TestCase
{
private $context;
protected function setUp() : void
{
$this->context = \TestHelper::context();
$this->context->setView( \TestHelper::view() );
}
public function testCreateClient()
{
$client = \Aimeos\Admin\JQAdm\Order\Factory::create( $this->context );
$this->assertInstanceOf( '\\Aimeos\\Admin\\JQAdm\\Iface', $client );
}
public function testCreateClientName()
{
$client = \Aimeos\Admin\JQAdm\Order\Factory::create( $this->context, 'Standard' );
$this->assertInstanceOf( '\\Aimeos\\Admin\\JQAdm\\Iface', $client );
}
public function testCreateClientNameEmpty()
{
$this->expectException( '\\Aimeos\\Admin\\JQAdm\\Exception' );
\Aimeos\Admin\JQAdm\Order\Factory::create( $this->context, '' );
}
public function testCreateClientNameInvalid()
{
$this->expectException( '\\Aimeos\\Admin\\JQAdm\\Exception' );
\Aimeos\Admin\JQAdm\Order\Factory::create( $this->context, '%order' );
}
public function testCreateClientNameNotFound()
{
$this->expectException( '\\Aimeos\\Admin\\JQAdm\\Exception' );
\Aimeos\Admin\JQAdm\Order\Factory::create( $this->context, 'test' );
}
}
| aimeos/ai-admin-jqadm | tests/Admin/JQAdm/Order/FactoryTest.php | PHP | lgpl-3.0 | 1,336 |
/**
* This file is part of tapioca.cores.
*
* tapioca.cores 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.
*
* tapioca.cores 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 tapioca.cores. If not, see <http://www.gnu.org/licenses/>.
*/
package org.aksw.simba.tapioca.cores.preprocessing;
import java.util.ArrayList;
import java.util.List;
import org.aksw.simba.tapioca.cores.data.DatasetClassInfo;
import org.aksw.simba.tapioca.cores.data.DatasetDescription;
import org.aksw.simba.tapioca.cores.data.DatasetPropertyInfo;
import org.aksw.simba.tapioca.cores.data.DatasetSpecialClassesInfo;
import org.aksw.simba.tapioca.cores.data.DatasetTriplesCount;
import org.aksw.simba.tapioca.cores.data.DatasetVocabularies;
import org.aksw.simba.tapioca.cores.data.EVOID;
import org.aksw.simba.tapioca.cores.data.VOID;
import org.aksw.simba.tapioca.cores.extraction.AbstractExtractor;
import org.aksw.simba.tapioca.cores.extraction.RDF2ExtractionStreamer;
import org.aksw.simba.topicmodeling.preprocessing.docsupplier.DocumentSupplier;
import org.aksw.simba.topicmodeling.preprocessing.docsupplier.decorator.AbstractDocumentSupplierDecorator;
import org.aksw.simba.topicmodeling.utils.doc.Document;
import org.aksw.simba.topicmodeling.utils.doc.DocumentDescription;
import org.aksw.simba.topicmodeling.utils.doc.DocumentName;
import org.aksw.simba.topicmodeling.utils.doc.DocumentText;
import org.aksw.simba.topicmodeling.utils.doc.DocumentURI;
import org.apache.jena.riot.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.carrotsearch.hppc.ObjectLongOpenHashMap;
import com.carrotsearch.hppc.ObjectObjectOpenHashMap;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.vocabulary.DCTerms;
import com.hp.hpl.jena.vocabulary.RDF;
/**
* Parses the {@link DocumentText} as RDF VOID information (in turtle). Adds
* {@link DatasetClassInfo}, {@link DatasetPropertyInfo} and
* {@link DatasetVocabularies}. May add {@link DocumentURI},
* {@link DocumentName}, {@link DocumentDescription} if these information are
* found inside the VOID and the document does not already have the property.
*
* @author Michael Roeder (roeder@informatik.uni-leipzig.de)
*
*/
public class JenaBasedVoidParsingSupplierDecorator extends AbstractDocumentSupplierDecorator {
private static final Logger LOGGER = LoggerFactory.getLogger(JenaBasedVoidParsingSupplierDecorator.class);
// PipedRDFStream and PipedRDFIterator need to be on different threads
private RDF2ExtractionStreamer streamer = new RDF2ExtractionStreamer();
public JenaBasedVoidParsingSupplierDecorator(DocumentSupplier documentSource) {
super(documentSource);
}
@Override
protected Document prepareDocument(Document document) {
DocumentText text = document.getProperty(DocumentText.class);
if (text == null) {
LOGGER.warn("Couldn't get needed DocumentText property from document. Ignoring this document.");
} else {
parseVoid(document, text.getText());
}
return document;
}
private void parseVoid(Document document, String text) {
String baseURI = extractDatasetNameFromTTL(text);
if (baseURI == null) {
baseURI = "";
}
VoidParser parser = new VoidParser();
streamer.runExtraction(text, baseURI, Lang.TTL, parser);
parser.addVoidToDocument(document);
}
private String extractDatasetNameFromTTL(String text) {
int start = text.indexOf("\n\n<");
if (start < 0) {
return null;
}
start += 3;
int end = text.indexOf('>', start);
if (end < 0) {
return null;
} else {
return text.substring(start, end);
}
}
protected class VoidParser extends AbstractExtractor {
private ObjectObjectOpenHashMap<String, String> classes = new ObjectObjectOpenHashMap<String, String>();
private ObjectLongOpenHashMap<String> classCounts = new ObjectLongOpenHashMap<String>();
private ObjectObjectOpenHashMap<String, String> specialClasses = new ObjectObjectOpenHashMap<String, String>();
private ObjectLongOpenHashMap<String> specialClassesCounts = new ObjectLongOpenHashMap<String>();
private ObjectObjectOpenHashMap<String, String> properties = new ObjectObjectOpenHashMap<String, String>();
private ObjectLongOpenHashMap<String> propertyCounts = new ObjectLongOpenHashMap<String>();
private List<String> vocabularies = new ArrayList<String>();
private ObjectObjectOpenHashMap<String, DatasetDescription> datasetDescriptions = new ObjectObjectOpenHashMap<String, DatasetDescription>();
@Override
public void handleTriple(Triple triple) {
try {
Node subject = triple.getSubject();
Node predicate = triple.getPredicate();
Node object = triple.getObject();
if (object.equals(VOID.Dataset.asNode()) && (predicate.equals(RDF.type.asNode()))) {
String datasetUri = subject.getURI();
if (!datasetDescriptions.containsKey(datasetUri)) {
datasetDescriptions.put(datasetUri, new DatasetDescription(datasetUri));
}
} else if (predicate.equals(VOID.clazz.asNode())) {
classes.put(subject.getBlankNodeLabel(), object.isBlank() ? object.getBlankNodeLabel() : object.getURI());
} else if (predicate.equals(VOID.entities.asNode()) && object.isLiteral()) {
if (subject.isBlank()) {
classCounts.put(subject.getBlankNodeLabel(), parseLong(object));
}
} else if (predicate.equals(EVOID.specialClass.asNode())) {
specialClasses.put(subject.getBlankNodeLabel(), object.isBlank() ? object.getBlankNodeLabel() : object.getURI());
} else if (predicate.equals(EVOID.entities.asNode()) && object.isLiteral()) {
specialClassesCounts.put(subject.getBlankNodeLabel(), parseLong(object));
} else if (predicate.equals(VOID.property.asNode())) {
properties.put(subject.getBlankNodeLabel(), object.isBlank() ? object.getBlankNodeLabel() : object.getURI());
} else if (predicate.equals(VOID.triples.asNode()) && object.isLiteral()) {
if (subject.isURI()) {
if (datasetDescriptions.containsKey(subject.getURI())) {
datasetDescriptions.get(subject.getURI()).triples = parseLong(object);
}
} else {
propertyCounts.put(subject.getBlankNodeLabel(), parseLong(object));
}
} else if (predicate.equals(VOID.vocabulary.asNode())) {
vocabularies.add(object.toString());
} else if (predicate.equals(DCTerms.title.asNode())) {
String datasetUri = subject.getURI();
DatasetDescription description;
if (!datasetDescriptions.containsKey(datasetUri)) {
description = new DatasetDescription(datasetUri);
datasetDescriptions.put(datasetUri, description);
} else {
description = datasetDescriptions.get(datasetUri);
}
description.title = object.toString();
} else if (predicate.equals(VOID.subset.asNode())) {
String dataset1Uri = subject.getURI();
String dataset2Uri = object.getURI();
DatasetDescription description1, description2;
if (!datasetDescriptions.containsKey(dataset1Uri)) {
description1 = new DatasetDescription(dataset1Uri);
datasetDescriptions.put(dataset1Uri, description1);
} else {
description1 = datasetDescriptions.get(dataset1Uri);
}
if (!datasetDescriptions.containsKey(dataset2Uri)) {
description2 = new DatasetDescription(dataset2Uri);
datasetDescriptions.put(dataset1Uri, description2);
} else {
description2 = datasetDescriptions.get(dataset2Uri);
}
description1.addSubset(description2);
} else if (predicate.equals(DCTerms.description.asNode())) {
String datasetUri = subject.getURI();
DatasetDescription description;
if (!datasetDescriptions.containsKey(datasetUri)) {
description = new DatasetDescription(datasetUri);
datasetDescriptions.put(datasetUri, description);
} else {
description = datasetDescriptions.get(datasetUri);
}
description.description = object.toString();
}
} catch (Exception e) {
LOGGER.error("Couldn't parse the triple \"" + triple + "\".", e);
}
}
public void addVoidToDocument(Document document) {
ObjectLongOpenHashMap<String> countedURIs = new ObjectLongOpenHashMap<String>(classes.assigned);
long count;
for (int i = 0; i < classes.allocated.length; ++i) {
if (classes.allocated[i]) {
if (classCounts.containsKey((String) ((Object[]) classes.keys)[i])) {
count = classCounts.lget();
} else {
count = 0;
}
countedURIs.put((String) ((Object[]) classes.values)[i], count);
}
}
document.addProperty(new DatasetClassInfo(countedURIs));
countedURIs = new ObjectLongOpenHashMap<String>(specialClasses.assigned);
for (int i = 0; i < specialClasses.allocated.length; ++i) {
if (specialClasses.allocated[i]) {
if (specialClassesCounts.containsKey((String) ((Object[]) specialClasses.keys)[i])) {
count = specialClassesCounts.lget();
} else {
count = 0;
}
countedURIs.put((String) ((Object[]) specialClasses.values)[i], count);
}
}
document.addProperty(new DatasetSpecialClassesInfo(countedURIs));
countedURIs = new ObjectLongOpenHashMap<String>();
for (int i = 0; i < properties.allocated.length; ++i) {
if (properties.allocated[i]) {
if (propertyCounts.containsKey((String) ((Object[]) properties.keys)[i])) {
count = propertyCounts.lget();
} else {
count = 0;
}
countedURIs.put((String) ((Object[]) properties.values)[i], count);
}
}
document.addProperty(new DatasetPropertyInfo(countedURIs));
document.addProperty(new DatasetVocabularies(vocabularies.toArray(new String[vocabularies.size()])));
processDatasetInfos(document, datasetDescriptions);
}
private void processDatasetInfos(Document document,
ObjectObjectOpenHashMap<String, DatasetDescription> datasetDescriptions) {
DatasetDescription rootDataset = null;
if (datasetDescriptions.assigned == 1) {
for (int i = 0; (rootDataset == null) && (i < datasetDescriptions.allocated.length); ++i) {
if (datasetDescriptions.allocated[i]) {
rootDataset = (DatasetDescription) ((Object[]) datasetDescriptions.values)[i];
}
}
if (document.getProperty(DocumentURI.class) == null) {
document.addProperty(new DocumentURI(rootDataset.uri));
}
if ((rootDataset.title != null) && (document.getProperty(DocumentName.class) == null)) {
document.addProperty(new DocumentName(rootDataset.title));
}
if ((rootDataset.description != null) && (document.getProperty(DocumentDescription.class) == null)) {
document.addProperty(new DocumentDescription(rootDataset.description));
}
document.addProperty(new DatasetTriplesCount(rootDataset.triples));
} else if (datasetDescriptions.assigned > 1) {
DatasetDescription temp;
for (int i = 0; (rootDataset == null) && (i < datasetDescriptions.allocated.length); ++i) {
if (datasetDescriptions.allocated[i]) {
temp = (DatasetDescription) ((Object[]) datasetDescriptions.values)[i];
if ((temp.subsets != null) && (temp.subsets.size() > 0)) {
rootDataset = temp;
}
}
}
if (document.getProperty(DocumentURI.class) == null) {
document.addProperty(new DocumentURI(rootDataset.uri));
}
if ((document.getProperty(DocumentName.class) == null)) {
if (rootDataset.title == null) {
StringBuilder builder = new StringBuilder();
builder.append("merged (");
boolean first = true;
for (DatasetDescription subset : rootDataset.subsets) {
if (first) {
first = !first;
} else {
builder.append(',');
}
builder.append(subset.title != null ? subset.title : subset.uri);
}
builder.append(')');
document.addProperty(new DocumentName(builder.toString()));
} else {
document.addProperty(new DocumentName(rootDataset.title));
}
}
if (document.getProperty(DocumentDescription.class) == null) {
if (rootDataset.description == null) {
StringBuilder builder = new StringBuilder();
builder.append("merged description (");
for (DatasetDescription subset : rootDataset.subsets) {
builder.append('\n');
builder.append(subset.title != null ? subset.title : subset.uri);
builder.append(":\"");
builder.append(subset.description);
builder.append('"');
}
builder.append(')');
document.addProperty(new DocumentDescription(builder.toString()));
} else {
document.addProperty(new DocumentDescription(rootDataset.description));
}
}
long triples = 0;
if (rootDataset.triples == -1) {
for (DatasetDescription subset : rootDataset.subsets) {
triples += subset.triples;
}
} else {
triples = rootDataset.triples;
}
document.addProperty(new DatasetTriplesCount(triples));
} else {
LOGGER.warn("Couldn't find a URI for the dataset in document " + document.getDocumentId()
+ ". Document:(name=" + document.getProperty(DocumentName.class) + ")");
}
}
protected long parseLong(Node object) {
Object value = object.getLiteralValue();
if (value instanceof Integer) {
return (Integer) value;
} else if (value instanceof Long) {
return (Long) value;
} else {
LOGGER.error("Got an unknown literal type \"" + value.getClass().toString() + "\".");
}
return 0;
}
}
}
| AKSW/Tapioca | Tapioca_STP_code/tapioca.cores/src/main/java/org/aksw/simba/tapioca/cores/preprocessing/JenaBasedVoidParsingSupplierDecorator.java | Java | lgpl-3.0 | 13,827 |
package idare.subnetwork.internal.Tasks.SubsystemGeneration;
import idare.subnetwork.internal.NetworkViewSwitcher;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.view.layout.CyLayoutAlgorithm;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.work.Tunable;
import org.cytoscape.work.swing.GUITunableHandlerFactory;
public class SubnetworkCreationGUIHandlerFactory implements GUITunableHandlerFactory<SubnetworkCreationGUIHandler> {
/**
* Necessary fields for this Factory
*/
CyApplicationManager appmgr;
NetworkViewSwitcher nvs;
CyLayoutAlgorithmManager cyLayMgr;
String IDCol;
public SubnetworkCreationGUIHandlerFactory(NetworkViewSwitcher nvs, CyApplicationManager appmgr, CyLayoutAlgorithmManager cyLayMgr) {
super();
this.nvs = nvs;
this.appmgr = appmgr;
this.cyLayMgr = cyLayMgr;
}
@Override
public SubnetworkCreationGUIHandler createTunableHandler(Field arg0, Object arg1,
Tunable arg2) {
// TODO Auto-generated method stub
if(!SubNetworkProperties.class.isAssignableFrom(arg0.getType()))
{
// PrintFDebugger.Debugging(this, "Obtained a Request for tunable handling for type " + arg0.getType().getSimpleName() );
return null;
}
// PrintFDebugger.Debugging(this, "Generating new Handler");
return new SubnetworkCreationGUIHandler(arg0,arg1,arg2,nvs,appmgr.getCurrentNetworkView().getModel(), appmgr.getCurrentNetworkView(), getCurrentLayouts(), IDCol);
}
@Override
public SubnetworkCreationGUIHandler createTunableHandler(Method arg0,
Method arg1, Object arg2, Tunable arg3) {
if(!SubNetworkProperties.class.isAssignableFrom(arg0.getReturnType()))
{
// PrintFDebugger.Debugging(this, "Obtained a Request for tunable handling for type " + arg0.getReturnType().getSimpleName() );
return null;
}
// PrintFDebugger.Debugging(this, "Generating new Handler");
return new SubnetworkCreationGUIHandler(arg0,arg1,arg2,arg3,nvs,appmgr.getCurrentNetworkView().getModel(), appmgr.getCurrentNetworkView(), getCurrentLayouts(), IDCol);
}
private HashMap<String,CyLayoutAlgorithm> getCurrentLayouts()
{
HashMap<String,CyLayoutAlgorithm> layoutAlgos = new HashMap<String, CyLayoutAlgorithm>();
for(CyLayoutAlgorithm algo : cyLayMgr.getAllLayouts())
{
layoutAlgos.put(algo.getName(), algo);
}
return layoutAlgos;
}
public void setIDCol(String ColName)
{
IDCol = ColName;
}
}
| sysbiolux/IDARE | METANODE-CREATOR/src/main/java/idare/subnetwork/internal/Tasks/SubsystemGeneration/SubnetworkCreationGUIHandlerFactory.java | Java | lgpl-3.0 | 2,511 |
#ifndef STATICTYPE_HPP
#define STATICTYPE_HPP
/* $Id: statictype.hpp 507796 2016-07-21 17:25:37Z gouriano $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Eugene Vasilchenko
*
* File Description:
* Predefined types: INTEGER, BOOLEAN, VisibleString etc.
*
*/
#include "type.hpp"
BEGIN_NCBI_SCOPE
class CStaticDataType : public CDataType {
typedef CDataType CParent;
public:
void PrintASN(CNcbiOstream& out, int indent) const;
void PrintXMLSchema(CNcbiOstream& out, int indent, bool contents_only=false) const;
void PrintDTDElement(CNcbiOstream& out, bool contents_only=false) const;
TObjectPtr CreateDefault(const CDataValue& value) const;
AutoPtr<CTypeStrings> GetFullCType(void) const;
//virtual string GetDefaultCType(void) const;
virtual const char* GetDefaultCType(void) const = 0;
virtual const char* GetXMLContents(void) const = 0;
virtual bool PrintXMLSchemaContents(CNcbiOstream& out, int indent, const CDataMember* mem) const;
};
class CNullDataType : public CStaticDataType {
typedef CStaticDataType CParent;
public:
bool CheckValue(const CDataValue& value) const;
TObjectPtr CreateDefault(const CDataValue& value) const;
CTypeRef GetTypeInfo(void);
AutoPtr<CTypeStrings> GetFullCType(void) const;
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
virtual bool PrintXMLSchemaContents(CNcbiOstream& out, int indent, const CDataMember* mem) const;
};
class CBoolDataType : public CStaticDataType {
typedef CStaticDataType CParent;
public:
bool CheckValue(const CDataValue& value) const;
TObjectPtr CreateDefault(const CDataValue& value) const;
virtual string GetDefaultString(const CDataValue& value) const;
CTypeRef GetTypeInfo(void);
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
virtual string GetSchemaTypeString(void) const;
virtual bool PrintXMLSchemaContents(CNcbiOstream& out, int indent, const CDataMember* mem) const;
void PrintDTDExtra(CNcbiOstream& out) const;
};
class CRealDataType : public CStaticDataType {
typedef CStaticDataType CParent;
public:
CRealDataType(void);
bool CheckValue(const CDataValue& value) const;
TObjectPtr CreateDefault(const CDataValue& value) const;
virtual string GetDefaultString(const CDataValue& value) const;
const CTypeInfo* GetRealTypeInfo(void);
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
virtual string GetSchemaTypeString(void) const;
};
class CStringDataType : public CStaticDataType {
typedef CStaticDataType CParent;
public:
enum EType {
eStringTypeVisible,
eStringTypeUTF8
};
CStringDataType(EType type = eStringTypeVisible);
bool CheckValue(const CDataValue& value) const;
TObjectPtr CreateDefault(const CDataValue& value) const;
virtual string GetDefaultString(const CDataValue& value) const;
const CTypeInfo* GetRealTypeInfo(void);
bool NeedAutoPointer(const CTypeInfo* typeInfo) const;
AutoPtr<CTypeStrings> GetFullCType(void) const;
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
virtual string GetSchemaTypeString(void) const;
EType GetStringType(void) const
{
return m_Type;
}
protected:
EType m_Type;
};
class CStringStoreDataType : public CStringDataType {
typedef CStringDataType CParent;
public:
CStringStoreDataType(void);
const CTypeInfo* GetRealTypeInfo(void);
bool NeedAutoPointer(const CTypeInfo* typeInfo) const;
AutoPtr<CTypeStrings> GetFullCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
};
class CBitStringDataType : public CStaticDataType {
typedef CStaticDataType CParent;
public:
bool CheckValue(const CDataValue& value) const;
const CTypeInfo* GetRealTypeInfo(void);
bool NeedAutoPointer(const CTypeInfo* typeInfo) const;
AutoPtr<CTypeStrings> GetFullCType(void) const;
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
virtual bool PrintXMLSchemaContents(CNcbiOstream& out, int indent, const CDataMember* mem) const;
};
class COctetStringDataType : public CBitStringDataType {
typedef CBitStringDataType CParent;
public:
bool CheckValue(const CDataValue& value) const;
const CTypeInfo* GetRealTypeInfo(void);
bool NeedAutoPointer(const CTypeInfo* typeInfo) const;
AutoPtr<CTypeStrings> GetFullCType(void) const;
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
virtual string GetSchemaTypeString(void) const;
virtual bool IsCompressed(void) const;
protected:
virtual bool x_AsBitString(void) const;
};
class CBase64BinaryDataType : public COctetStringDataType {
typedef COctetStringDataType CParent;
public:
virtual string GetSchemaTypeString(void) const;
virtual bool IsCompressed(void) const;
protected:
virtual bool x_AsBitString(void) const;
};
class CIntDataType : public CStaticDataType {
typedef CStaticDataType CParent;
public:
CIntDataType(void);
bool CheckValue(const CDataValue& value) const;
TObjectPtr CreateDefault(const CDataValue& value) const;
virtual string GetDefaultString(const CDataValue& value) const;
CTypeRef GetTypeInfo(void);
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
virtual string GetSchemaTypeString(void) const;
};
class CBigIntDataType : public CIntDataType {
typedef CIntDataType CParent;
public:
CBigIntDataType(bool bAsnBigInt = false) : m_bAsnBigInt(bAsnBigInt) {
}
bool CheckValue(const CDataValue& value) const;
TObjectPtr CreateDefault(const CDataValue& value) const;
virtual string GetDefaultString(const CDataValue& value) const;
CTypeRef GetTypeInfo(void);
virtual AutoPtr<CTypeStrings> GetFullCType(void) const;
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
virtual string GetSchemaTypeString(void) const;
protected:
bool m_bAsnBigInt;
};
class CAnyContentDataType : public CStaticDataType {
public:
bool CheckValue(const CDataValue& value) const;
void PrintASN(CNcbiOstream& out, int indent) const;
void PrintXMLSchema(CNcbiOstream& out, int indent, bool contents_only=false) const;
void PrintDTDElement(CNcbiOstream& out, bool contents_only=false) const;
TObjectPtr CreateDefault(const CDataValue& value) const;
AutoPtr<CTypeStrings> GetFullCType(void) const;
virtual const char* GetDefaultCType(void) const;
virtual const char* GetASNKeyword(void) const;
virtual const char* GetDEFKeyword(void) const;
virtual const char* GetXMLContents(void) const;
};
END_NCBI_SCOPE
#endif
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/serial/datatool/statictype.hpp | C++ | lgpl-3.0 | 9,009 |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Peter Forstmeier" email="peter.forstmeier@t-online.de"/>
// <version>$Revision$</version>
// </file>
using System;
using System.Drawing;
using System.Windows.Forms;
using ICSharpCode.Core;
using ICSharpCode.Reports.Core;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Gui;
namespace ICSharpCode.Reports.Addin.ReportWizard{
/// <summary>
/// Description of ReportGenerator.
/// </summary>
public class BaseSettingsPanel : AbstractWizardPanel
{
private System.Windows.Forms.RadioButton radioPushModell;
private System.Windows.Forms.RadioButton radioPullModell;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox txtReportName;
private System.Windows.Forms.ComboBox cboGraphicsUnit;
private System.Windows.Forms.TextBox txtFileName;
private System.Windows.Forms.TextBox txtPath;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.RadioButton radioFormSheet;
private System.Windows.Forms.ErrorProvider errorProvider;
ReportStructure generator;
Properties customizer;
bool initDone;
public BaseSettingsPanel(){
InitializeComponent();
errorProvider = new ErrorProvider();
errorProvider.ContainerControl = this;
this.txtFileName.KeyUp += new KeyEventHandler(OnKeyUp);
Localize();
Init();
base.VisibleChanged += new EventHandler (ChangedEvent );
}
private void OnKeyUp (object sender,KeyEventArgs e) {
if (this.txtFileName.Text.Length == 0) {
this.errorProvider.SetError(this.txtFileName,"aaaaa");
this.EnableNext = false;
}else {
this.errorProvider.SetError(this.txtFileName,"");
}
}
private void Localize() {
this.radioFormSheet.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.ReportModel.FormSheet");
this.label1.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.ReportName");
this.label2.Text = ResourceService.GetString("Global.Path");
this.label3.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.ReportType");
this.label4.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.GraphicsUnit");
this.label5.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.FileName");
this.groupBox1.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.Group");
this.groupBox2.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.ReportModel");
this.radioPullModell.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.ReportModel.Pull");
this.radioPushModell.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.ReportModel.Push");
this.radioFormSheet.Text = ResourceService.GetString("SharpReport.Wizard.BaseSettings.ReportModel.FormSheet");
this.button1.Text = "...";
}
#region overrides
public override bool ReceiveDialogMessage(DialogMessage message){
if (message == DialogMessage.Finish) {
} else if ( message == DialogMessage.Next) {
base.EnableFinish = true;
}
this.UpdateGenerator();
return true;
}
#endregion
private void Init()
{
txtFileName.Text = GlobalValues.PlainFileName;
txtReportName.Text = GlobalValues.DefaultReportName;
this.cboGraphicsUnit.Items.AddRange(Enum.GetNames(typeof (GraphicsUnit)));
cboGraphicsUnit.SelectedIndex = cboGraphicsUnit.FindString(GraphicsUnit.Millimeter.ToString());
this.radioPullModell.Checked = true;
initDone = true;
}
private void ChangedEvent(object sender, EventArgs e){
if (initDone) {
this.UpdateGenerator();
SetSuccessor (this,new EventArgs());
}
}
private void UpdateGenerator ()
{
if (customizer == null) {
customizer = (Properties)base.CustomizationObject;
generator = (ReportStructure)customizer.Get("Generator");
}
generator.ReportName = txtReportName.Text;
if (!this.txtFileName.Text.EndsWith(GlobalValues.ReportExtension,StringComparison.OrdinalIgnoreCase)){
generator.FileName = txtFileName.Text + GlobalValues.ReportExtension;
} else {
generator.FileName = txtFileName.Text;
}
generator.Path = this.txtPath.Text;
generator.GraphicsUnit = (GraphicsUnit)Enum.Parse(typeof(GraphicsUnit),
this.cboGraphicsUnit.Text);
if (this.radioPullModell.Checked == true) {
base.NextWizardPanelID = "PullModel";
generator.DataModel = GlobalEnums.PushPullModel.PullData;
GoOn();
} else if (this.radioPushModell.Checked == true){
base.NextWizardPanelID = "PushModel";
generator.DataModel = GlobalEnums.PushPullModel.PushData;
GoOn();
} else if (this.radioFormSheet.Checked == true){
generator.DataModel = GlobalEnums.PushPullModel.FormSheet;
base.EnableNext = false;
base.IsLastPanel = true;
}
}
private void SetSuccessor(object sender, System.EventArgs e)
{
if (initDone) {
if (this.radioPullModell.Checked == true) {
base.NextWizardPanelID = "PullModel";
generator.DataModel = GlobalEnums.PushPullModel.PullData;
GoOn();
} else if (this.radioPushModell.Checked == true){
base.NextWizardPanelID = "PushModel";
generator.DataModel = GlobalEnums.PushPullModel.PushData;
GoOn();
} else if (this.radioFormSheet.Checked == true){
// generator.DataModel = GlobalEnums.PushPullModel.FormSheet;
base.EnableNext = false;
base.IsLastPanel = true;
}
base.EnableFinish = true;
}
}
private void GoOn (){
base.EnableNext = true;
base.IsLastPanel = false;
}
private void OnSelectFolder(object sender, System.EventArgs e)
{
using (FolderBrowserDialog fd = FileService.CreateFolderBrowserDialog("")) {
if (fd.ShowDialog() == DialogResult.OK) {
if (!String.IsNullOrEmpty(fd.SelectedPath)) {
if (!fd.SelectedPath.EndsWith(@"\",StringComparison.OrdinalIgnoreCase)){
this.txtPath.Text = fd.SelectedPath + @"\";
} else {
this.txtPath.Text = fd.SelectedPath;
}
}
}
}
}
#region Windows Forms Designer generated code
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent() {
this.radioFormSheet = new System.Windows.Forms.RadioButton();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtPath = new System.Windows.Forms.TextBox();
this.txtFileName = new System.Windows.Forms.TextBox();
this.cboGraphicsUnit = new System.Windows.Forms.ComboBox();
this.txtReportName = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.button1 = new System.Windows.Forms.Button();
this.radioPullModell = new System.Windows.Forms.RadioButton();
this.radioPushModell = new System.Windows.Forms.RadioButton();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// radioFormSheet
//
this.radioFormSheet.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.radioFormSheet.Location = new System.Drawing.Point(256, 16);
this.radioFormSheet.Name = "radioFormSheet";
this.radioFormSheet.Size = new System.Drawing.Size(80, 24);
this.radioFormSheet.TabIndex = 22;
this.radioFormSheet.CheckedChanged += new System.EventHandler(this.SetSuccessor);
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 160);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(80, 24);
this.label4.TabIndex = 15;
//
// label5
//
this.label5.Location = new System.Drawing.Point(8, 80);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(64, 24);
this.label5.TabIndex = 12;
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 40);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 16);
this.label1.TabIndex = 4;
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(72, 24);
this.label2.TabIndex = 12;
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 120);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 16);
this.label3.TabIndex = 14;
this.label3.Visible = false;
//
// txtPath
//
this.txtPath.Location = new System.Drawing.Point(112, 24);
this.txtPath.Name = "txtPath";
this.txtPath.Size = new System.Drawing.Size(224, 20);
this.txtPath.TabIndex = 13;
this.txtPath.Text = String.Empty;
this.txtPath.TextChanged += new System.EventHandler(this.ChangedEvent);
//
// txtFileName
//
this.txtFileName.Location = new System.Drawing.Point(120, 80);
this.txtFileName.Name = "txtFileName";
this.txtFileName.Size = new System.Drawing.Size(248, 20);
this.txtFileName.TabIndex = 11;
this.txtFileName.Text = String.Empty;
this.txtFileName.TextChanged += new System.EventHandler(this.ChangedEvent);
//
// cboGraphicsUnit
//
this.cboGraphicsUnit.Location = new System.Drawing.Point(112, 160);
this.cboGraphicsUnit.Name = "cboGraphicsUnit";
this.cboGraphicsUnit.Size = new System.Drawing.Size(248, 21);
this.cboGraphicsUnit.TabIndex = 17;
this.cboGraphicsUnit.TextChanged += new System.EventHandler(this.ChangedEvent);
this.cboGraphicsUnit.DropDownStyle = ComboBoxStyle.DropDownList;
//
// cboReportType
//
/*
this.cboReportType.Location = new System.Drawing.Point(112, 120);
this.cboReportType.Name = "cboReportType";
this.cboReportType.Size = new System.Drawing.Size(248, 21);
this.cboReportType.TabIndex = 16;
this.cboReportType.Visible = false;
this.cboReportType.SelectedIndexChanged += new System.EventHandler(this.ChangedEvent);
*/
//
// txtReportName
//
this.txtReportName.Location = new System.Drawing.Point(120, 40);
this.txtReportName.Name = "txtReportName";
this.txtReportName.Size = new System.Drawing.Size(248, 20);
this.txtReportName.TabIndex = 0;
this.txtReportName.Text = String.Empty;
this.txtReportName.TextChanged += new System.EventHandler(this.ChangedEvent);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.groupBox2);
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Controls.Add(this.cboGraphicsUnit);
// this.groupBox1.Controls.Add(this.cboReportType);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.txtPath);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Location = new System.Drawing.Point(8, 160);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(392, 192);
this.groupBox1.TabIndex = 10;
this.groupBox1.TabStop = false;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.radioFormSheet);
this.groupBox2.Controls.Add(this.radioPullModell);
this.groupBox2.Controls.Add(this.radioPushModell);
this.groupBox2.Location = new System.Drawing.Point(16, 56);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(360, 48);
this.groupBox2.TabIndex = 21;
this.groupBox2.TabStop = false;
//
// button1
//
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Location = new System.Drawing.Point(352, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(24, 21);
this.button1.TabIndex = 18;
this.button1.Click += new System.EventHandler(this.OnSelectFolder);
//
// radioPullModell
//
this.radioPullModell.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.radioPullModell.Location = new System.Drawing.Point(24, 16);
this.radioPullModell.Name = "radioPullModell";
this.radioPullModell.Size = new System.Drawing.Size(88, 24);
this.radioPullModell.TabIndex = 21;
this.radioPullModell.CheckedChanged += new System.EventHandler(this.SetSuccessor);
//
// radioPushModell
//
this.radioPushModell.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.radioPushModell.Location = new System.Drawing.Point(136, 16);
this.radioPushModell.Name = "radioPushModell";
this.radioPushModell.Size = new System.Drawing.Size(96, 24);
this.radioPushModell.TabIndex = 20;
this.radioPushModell.CheckedChanged += new System.EventHandler(this.SetSuccessor);
//
// BaseSettingsPanel
//
this.Controls.Add(this.label5);
this.Controls.Add(this.txtFileName);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtReportName);
this.Name = "BaseSettingsPanel";
this.Size = new System.Drawing.Size(424, 368);
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
| kingjiang/SharpDevelopLite | src/AddIns/Misc/SharpReport/ICSharpCode.Reports.Addin/Project/ReportWizard/WizardPanels/BaseSettingsPanel.cs | C# | lgpl-3.0 | 13,851 |
/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
* This file is part of sot-core.
* sot-core 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.
* sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --- SOT --- */
#include <sot/core/debug.hh>
#include <sot/core/feature-task.hh>
#include <sot/core/exception-feature.hh>
#include <sot/core/task.hh>
#include <dynamic-graph/pool.h>
using namespace std;
using namespace dynamicgraph::sot;
using namespace dynamicgraph;
#include <sot/core/factory.hh>
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(FeatureTask,"FeatureTask");
/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */
FeatureTask::
FeatureTask( const string& pointName )
: FeatureGeneric( pointName )
{
}
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
void FeatureTask::
display( std::ostream& os ) const
{
os << "Feature from task <" << getName();
if( taskPtr ) os << ": from task " << taskPtr->getName();
os << std::endl;
}
void FeatureTask::
commandLine( const std::string& cmdLine,
std::istringstream& cmdArgs,
std::ostream& os )
{
if( cmdLine == "help" )
{
os << "FeatureTask: "
<< " - task [<taskname>] " << std::endl;
}
else if( cmdLine == "task" )
{
cmdArgs >>std::ws;
if( cmdArgs.good() )
{
std::string name; cmdArgs >> name;
Task& task = dynamic_cast< Task & >
(dg::PoolStorage::getInstance()->getEntity( name ));
taskPtr = &task;
errorSIN.plug( &task.errorSOUT );
jacobianSIN.plug( &task.jacobianSOUT );
} else {
if( taskPtr ) os << "task = " << (*taskPtr) << std::endl;
else os << "task = NULL " <<std::endl;
}
}
else { Entity::commandLine( cmdLine,cmdArgs,os); }
}
/*
* Local variables:
* c-basic-offset: 2
* End:
*/
| proyan/sot-core | src/feature/feature-task.cpp | C++ | lgpl-3.0 | 3,127 |
package org.energy2d.model;
import org.energy2d.util.MiscUtil;
/**
* @author Charles Xie
*
*/
class FluidSolver2DImpl extends FluidSolver2D {
FluidSolver2DImpl(int nx, int ny) {
super(nx, ny);
}
void diffuse(int b, float[][] f0, float[][] f) {
// Copying a two-dimensional array is very fast: it takes less than 1% compared with the time for the relaxation solver below. Considering this, I chose clarity instead of swapping the arrays.
MiscUtil.copy(f0, f);
float hx = timeStep * viscosity * idxsq;
float hy = timeStep * viscosity * idysq;
float dn = 1f / (1 + 2 * (hx + hy));
for (int k = 0; k < relaxationSteps; k++) {
for (int i = 1; i < nx1; i++) {
for (int j = 1; j < ny1; j++) {
if (fluidity[i][j]) {
f[i][j] = (f0[i][j] + hx * (f[i - 1][j] + f[i + 1][j]) + hy * (f[i][j - 1] + f[i][j + 1])) * dn;
}
}
}
applyBoundary(b, f);
}
}
void advect(int b, float[][] f0, float[][] f) {
macCormack(b, f0, f);
}
// MacCormack
private void macCormack(int b, float[][] f0, float[][] f) {
float tx = 0.5f * timeStep / deltaX;
float ty = 0.5f * timeStep / deltaY;
for (int i = 1; i < nx1; i++) {
for (int j = 1; j < ny1; j++) {
if (fluidity[i][j]) {
f[i][j] = f0[i][j] - tx * (u0[i + 1][j] * f0[i + 1][j] - u0[i - 1][j] * f0[i - 1][j]) - ty * (v0[i][j + 1] * f0[i][j + 1] - v0[i][j - 1] * f0[i][j - 1]);
}
}
}
applyBoundary(b, f);
for (int i = 1; i < nx1; i++) {
for (int j = 1; j < ny1; j++) {
if (fluidity[i][j]) {
f0[i][j] = 0.5f * (f0[i][j] + f[i][j]) - 0.5f * tx * u0[i][j] * (f[i + 1][j] - f[i - 1][j]) - 0.5f * ty * v0[i][j] * (f[i][j + 1] - f[i][j - 1]);
}
}
}
MiscUtil.copy(f, f0);
applyBoundary(b, f);
}
}
| charxie/energy2d | energy2d/src/org/energy2d/model/FluidSolver2DImpl.java | Java | lgpl-3.0 | 1,745 |
/**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portlet.journal.model.impl;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.CacheModel;
import com.liferay.portlet.journal.model.JournalArticleImage;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
/**
* The cache model class for representing JournalArticleImage in entity cache.
*
* @author Brian Wing Shun Chan
* @see JournalArticleImage
* @generated
*/
public class JournalArticleImageCacheModel implements CacheModel<JournalArticleImage>,
Externalizable {
@Override
public String toString() {
StringBundler sb = new StringBundler(17);
sb.append("{articleImageId=");
sb.append(articleImageId);
sb.append(", groupId=");
sb.append(groupId);
sb.append(", articleId=");
sb.append(articleId);
sb.append(", version=");
sb.append(version);
sb.append(", elInstanceId=");
sb.append(elInstanceId);
sb.append(", elName=");
sb.append(elName);
sb.append(", languageId=");
sb.append(languageId);
sb.append(", tempImage=");
sb.append(tempImage);
sb.append("}");
return sb.toString();
}
@Override
public JournalArticleImage toEntityModel() {
JournalArticleImageImpl journalArticleImageImpl = new JournalArticleImageImpl();
journalArticleImageImpl.setArticleImageId(articleImageId);
journalArticleImageImpl.setGroupId(groupId);
if (articleId == null) {
journalArticleImageImpl.setArticleId(StringPool.BLANK);
}
else {
journalArticleImageImpl.setArticleId(articleId);
}
journalArticleImageImpl.setVersion(version);
if (elInstanceId == null) {
journalArticleImageImpl.setElInstanceId(StringPool.BLANK);
}
else {
journalArticleImageImpl.setElInstanceId(elInstanceId);
}
if (elName == null) {
journalArticleImageImpl.setElName(StringPool.BLANK);
}
else {
journalArticleImageImpl.setElName(elName);
}
if (languageId == null) {
journalArticleImageImpl.setLanguageId(StringPool.BLANK);
}
else {
journalArticleImageImpl.setLanguageId(languageId);
}
journalArticleImageImpl.setTempImage(tempImage);
journalArticleImageImpl.resetOriginalValues();
return journalArticleImageImpl;
}
@Override
public void readExternal(ObjectInput objectInput) throws IOException {
articleImageId = objectInput.readLong();
groupId = objectInput.readLong();
articleId = objectInput.readUTF();
version = objectInput.readDouble();
elInstanceId = objectInput.readUTF();
elName = objectInput.readUTF();
languageId = objectInput.readUTF();
tempImage = objectInput.readBoolean();
}
@Override
public void writeExternal(ObjectOutput objectOutput)
throws IOException {
objectOutput.writeLong(articleImageId);
objectOutput.writeLong(groupId);
if (articleId == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(articleId);
}
objectOutput.writeDouble(version);
if (elInstanceId == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(elInstanceId);
}
if (elName == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(elName);
}
if (languageId == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(languageId);
}
objectOutput.writeBoolean(tempImage);
}
public long articleImageId;
public long groupId;
public String articleId;
public double version;
public String elInstanceId;
public String elName;
public String languageId;
public boolean tempImage;
} | km-works/portal-rpc | portal-rpc-client/src/main/java/com/liferay/portlet/journal/model/impl/JournalArticleImageCacheModel.java | Java | lgpl-3.0 | 4,216 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import * as React from 'react';
import withIndexationGuard from '../../../components/hoc/withIndexationGuard';
import { PageContext } from '../indexation/PageUnavailableDueToIndexation';
import GlobalPageExtension from './GlobalPageExtension';
export function PortfoliosPage() {
return <GlobalPageExtension params={{ pluginKey: 'governance', extensionKey: 'portfolios' }} />;
}
export default withIndexationGuard(PortfoliosPage, PageContext.Portfolios);
| SonarSource/sonarqube | server/sonar-web/src/main/js/app/components/extensions/PortfoliosPage.tsx | TypeScript | lgpl-3.0 | 1,301 |
# This module consists of definitions of nodes representing elements of a tree
# of s-expressions.
module Nodes
# The base class of all nodes.
class Node
# The label used by the assembler for jmps, movs, etc.
attr_reader :label
# Substitutes dashes with underscores.
def label=(val)
@label = val.valid_c_symbol
end
# Returns an array of instructions evaluating the node and putting the
# result in EAX.
def evaluate(label_gen, symbol_table)
["mov eax, #{label}"]
end
end
# A segment of a list.
class ListNode < Node
attr_accessor :data, :succ
def initialize(data, succ)
@data = data
@succ = succ
end
end
# An s-expression.
class Sexp < Node
# All elements of the sexp.
attr_reader :elements
# Functions which accept an arbitrary number of arguments.
VarArgFuncs = %w{ list + - / * }
def initialize(elements)
@elements = elements
end
# All elements excluding the first.
def arguments
elements.drop 1
end
# If the first element is a Nodes::Symbol, it's name, otherwise first
# element's label.
def function
if first_elem_is_sym?
elements.first.name
else
elements.first.label
end
end
# True if the first element is a Nodes::Symbol.
def first_elem_is_sym?
elements.first.is_a? Nodes::Symbol
end
def evaluate(label_gen, symbol_table)
output = []
offset = 0
if VarArgFuncs.include? function
output << "push #{Constants::VAR_ARG_DELIM}"
offset += Constants::DWORD_SIZE
end
arguments.reverse.each do |node|
output += node.evaluate label_gen, symbol_table
output << 'push eax'
end
output += [ "call #{function_label(symbol_table)}",
"add esp, #{Constants::DWORD_SIZE * arguments.count + offset}" ]
end
private
def function_label(symbol_table)
if first_elem_is_sym?
name = elements.first.name
if symbol_table.include? name
symbol_table[name].label
else
name.valid_c_symbol
end
else
elements.first.label
end
end
end
# An atom. Not a list, in other words.
class Atom < Node
end
# A symbol which will be sought in the symbol table passed to
# Nodes::Symbol#evaluate.
class Symbol < Atom
# The lexeme of the symbol.
attr_reader :name
def initialize(name)
@name = name
end
def evaluate(label_gen, symbol_table)
Log.error "'#{name}' has no value" unless symbol_table.include? name
symbol_table[name].evaluate(label_gen, symbol_table)
end
end
# A symbol which will *not* be sought in the symbol table.
class QuotedSymbol < Atom
# The lexeme of the symbol.
attr_reader :name
def initialize(name)
@name = name
end
end
# A constant integer.
class Constant < Atom
attr_reader :value
def initialize(value)
@value = value
end
end
# A constant string.
class String < Atom
attr_reader :value
def initialize(value)
@value = value
end
end
# An empty list string.
class EmptyList < Atom
# Sets @label to 0.
def initialize
@label = '0'
end
def evaluate(label_gen, symbol_table)
[ "xor eax, eax" ]
end
end
# A set of conditions and their respective values.
class Cond < Node
# An option consisting of a condition and its value which will be
# evaluated when the condition evaluates to true.
class Option
attr_reader :cond, :value
def initialize(cond, value)
@cond = cond
@value = value
end
end
attr :options
def initialize
@options = []
end
# Adds a new Option instance to @options
def add_option(cond, value)
@options << Option.new(cond, value)
end
def evaluate(label_gen, symbol_table)
output = []
end_label = label_gen.add :end_cond
options.each do |opt|
next_opt_label = label_gen.add :cond_option
output += opt.cond.evaluate(label_gen, symbol_table) +
[ 'cmp eax, 0', "jz #{next_opt_label}" ] +
opt.value.evaluate(label_gen, symbol_table) +
[ "jmp #{end_label}", "#{next_opt_label}:" ]
end
output + [ 'mov eax, 0', "#{end_label}:" ]
end
end
# A lambda, an anonymous function.
class Lambda < Node
# A lambda's argument.
class Arg
attr_reader :name
# The offset from the EBP, after the lambda is being called.
attr_accessor :stack_offset
def initialize(name)
@name = name
end
def evaluate(label_gen, symbol_table)
[ "mov eax, [ebp+#{stack_offset}]" ]
end
end
attr_reader :args
attr_accessor :value
def initialize(args, value)
@args = args
@value = value
end
def evaluate(label_gen, symbol_table)
number = 0
args.each do |arg|
arg.stack_offset = (2 + number) * Constants::DWORD_SIZE
number += 1
end
args_hash = create_args_hash label_gen
value.evaluate(label_gen, symbol_table.merge(args_hash))
end
private
# Returns a hash of arguments' names pointing to Lambda::Arg instances.
# The result is to be merged with a symbol table during the evaluation
# of the lambda.
def create_args_hash(label_gen)
args.reduce({}) { |hash,arg| hash.merge({ arg.name => arg }) }
end
end
end
class String
# Substitutes dashes with underscores.
def valid_c_symbol
self.tr '-', '_'
end
end
| jstepien/mlisp | nodes.rb | Ruby | lgpl-3.0 | 5,147 |
/**
* @file
* @brief Source file for Cache class
* @author Jonathan Thomas <jonathan@openshot.org>
*
* @section LICENSE
*
* Copyright (c) 2008-2014 OpenShot Studios, LLC
* <http://www.openshotstudios.com/>. This file is part of
* OpenShot Library (libopenshot), an open-source project dedicated to
* delivering high quality video editing and animation solutions to the
* world. For more information visit <http://www.openshot.org/>.
*
* OpenShot Library (libopenshot) 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.
*
* OpenShot Library (libopenshot) 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 OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../include/CacheMemory.h"
using namespace std;
using namespace openshot;
// Default constructor, no max bytes
CacheMemory::CacheMemory() : CacheBase(0) {
// Set cache type name
cache_type = "CacheMemory";
range_version = 0;
needs_range_processing = false;
};
// Constructor that sets the max bytes to cache
CacheMemory::CacheMemory(long long int max_bytes) : CacheBase(max_bytes) {
// Set cache type name
cache_type = "CacheMemory";
range_version = 0;
needs_range_processing = false;
};
// Default destructor
CacheMemory::~CacheMemory()
{
frames.clear();
frame_numbers.clear();
ordered_frame_numbers.clear();
// remove critical section
delete cacheCriticalSection;
cacheCriticalSection = NULL;
}
// Calculate ranges of frames
void CacheMemory::CalculateRanges() {
// Only calculate when something has changed
if (needs_range_processing) {
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
// Sort ordered frame #s, and calculate JSON ranges
std::sort(ordered_frame_numbers.begin(), ordered_frame_numbers.end());
// Clear existing JSON variable
Json::Value ranges = Json::Value(Json::arrayValue);
// Increment range version
range_version++;
vector<long int>::iterator itr_ordered;
long int starting_frame = *ordered_frame_numbers.begin();
long int ending_frame = *ordered_frame_numbers.begin();
// Loop through all known frames (in sequential order)
for (itr_ordered = ordered_frame_numbers.begin(); itr_ordered != ordered_frame_numbers.end(); ++itr_ordered) {
long int frame_number = *itr_ordered;
if (frame_number - ending_frame > 1) {
// End of range detected
Json::Value range;
// Add JSON object with start/end attributes
// Use strings, since long ints are supported in JSON
stringstream start_str;
start_str << starting_frame;
stringstream end_str;
end_str << ending_frame;
range["start"] = start_str.str();
range["end"] = end_str.str();
ranges.append(range);
// Set new starting range
starting_frame = frame_number;
}
// Set current frame as end of range, and keep looping
ending_frame = frame_number;
}
// APPEND FINAL VALUE
Json::Value range;
// Add JSON object with start/end attributes
// Use strings, since long ints are not supported in JSON
stringstream start_str;
start_str << starting_frame;
stringstream end_str;
end_str << ending_frame;
range["start"] = start_str.str();
range["end"] = end_str.str();
ranges.append(range);
// Cache range JSON as string
json_ranges = ranges.toStyledString();
// Reset needs_range_processing
needs_range_processing = false;
}
}
// Add a Frame to the cache
void CacheMemory::Add(tr1::shared_ptr<Frame> frame)
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
long int frame_number = frame->number;
// Freshen frame if it already exists
if (frames.count(frame_number))
// Move frame to front of queue
MoveToFront(frame_number);
else
{
// Add frame to queue and map
frames[frame_number] = frame;
frame_numbers.push_front(frame_number);
ordered_frame_numbers.push_back(frame_number);
needs_range_processing = true;
// Clean up old frames
CleanUp();
}
}
// Get a frame from the cache (or NULL shared_ptr if no frame is found)
tr1::shared_ptr<Frame> CacheMemory::GetFrame(long int frame_number)
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
// Does frame exists in cache?
if (frames.count(frame_number))
// return the Frame object
return frames[frame_number];
else
// no Frame found
return tr1::shared_ptr<Frame>();
}
// Get the smallest frame number (or NULL shared_ptr if no frame is found)
tr1::shared_ptr<Frame> CacheMemory::GetSmallestFrame()
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
tr1::shared_ptr<openshot::Frame> f;
// Loop through frame numbers
deque<long int>::iterator itr;
long int smallest_frame = -1;
for(itr = frame_numbers.begin(); itr != frame_numbers.end(); ++itr)
{
if (*itr < smallest_frame || smallest_frame == -1)
smallest_frame = *itr;
}
// Return frame
f = GetFrame(smallest_frame);
return f;
}
// Gets the maximum bytes value
long long int CacheMemory::GetBytes()
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
long long int total_bytes = 0;
// Loop through frames, and calculate total bytes
deque<long int>::reverse_iterator itr;
for(itr = frame_numbers.rbegin(); itr != frame_numbers.rend(); ++itr)
{
total_bytes += frames[*itr]->GetBytes();
}
return total_bytes;
}
// Remove a specific frame
void CacheMemory::Remove(long int frame_number)
{
Remove(frame_number, frame_number);
}
// Remove range of frames
void CacheMemory::Remove(long int start_frame_number, long int end_frame_number)
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
// Loop through frame numbers
deque<long int>::iterator itr;
for(itr = frame_numbers.begin(); itr != frame_numbers.end();)
{
if (*itr >= start_frame_number && *itr <= end_frame_number)
{
// erase frame number
itr = frame_numbers.erase(itr);
}else
itr++;
}
// Loop through ordered frame numbers
vector<long int>::iterator itr_ordered;
for(itr_ordered = ordered_frame_numbers.begin(); itr_ordered != ordered_frame_numbers.end();)
{
if (*itr_ordered >= start_frame_number && *itr_ordered <= end_frame_number)
{
// erase frame number
frames.erase(*itr_ordered);
itr_ordered = ordered_frame_numbers.erase(itr_ordered);
}else
itr_ordered++;
}
// Needs range processing (since cache has changed)
needs_range_processing = true;
}
// Move frame to front of queue (so it lasts longer)
void CacheMemory::MoveToFront(long int frame_number)
{
// Does frame exists in cache?
if (frames.count(frame_number))
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
// Loop through frame numbers
deque<long int>::iterator itr;
for(itr = frame_numbers.begin(); itr != frame_numbers.end(); ++itr)
{
if (*itr == frame_number)
{
// erase frame number
frame_numbers.erase(itr);
// add frame number to 'front' of queue
frame_numbers.push_front(frame_number);
break;
}
}
}
}
// Clear the cache of all frames
void CacheMemory::Clear()
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
frames.clear();
frame_numbers.clear();
ordered_frame_numbers.clear();
}
// Count the frames in the queue
long int CacheMemory::Count()
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
// Return the number of frames in the cache
return frames.size();
}
// Clean up cached frames that exceed the number in our max_bytes variable
void CacheMemory::CleanUp()
{
// Do we auto clean up?
if (max_bytes > 0)
{
// Create a scoped lock, to protect the cache from multiple threads
const GenericScopedLock<CriticalSection> lock(*cacheCriticalSection);
while (GetBytes() > max_bytes && frame_numbers.size() > 20)
{
// Get the oldest frame number.
long int frame_to_remove = frame_numbers.back();
// Remove frame_number and frame
Remove(frame_to_remove);
}
}
}
// Generate JSON string of this object
string CacheMemory::Json() {
// Return formatted string
return JsonValue().toStyledString();
}
// Generate Json::JsonValue for this object
Json::Value CacheMemory::JsonValue() {
// Proccess range data (if anything has changed)
CalculateRanges();
// Create root json object
Json::Value root = CacheBase::JsonValue(); // get parent properties
root["type"] = cache_type;
stringstream range_version_str;
range_version_str << range_version;
root["version"] = range_version_str.str();
// Parse and append range data (if any)
Json::Value ranges;
Json::Reader reader;
bool success = reader.parse( json_ranges, ranges );
if (success)
root["ranges"] = ranges;
// return JsonValue
return root;
}
// Load JSON string into this object
void CacheMemory::SetJson(string value) throw(InvalidJSON) {
// Parse JSON string into JSON objects
Json::Value root;
Json::Reader reader;
bool success = reader.parse( value, root );
if (!success)
// Raise exception
throw InvalidJSON("JSON could not be parsed (or is invalid)", "");
try
{
// Set all values that match
SetJsonValue(root);
}
catch (exception e)
{
// Error parsing JSON (or missing keys)
throw InvalidJSON("JSON is invalid (missing keys or invalid data types)", "");
}
}
// Load Json::JsonValue into this object
void CacheMemory::SetJsonValue(Json::Value root) throw(InvalidFile, ReaderClosed) {
// Close timeline before we do anything (this also removes all open and closing clips)
Clear();
// Set parent data
CacheBase::SetJsonValue(root);
if (!root["type"].isNull())
cache_type = root["type"].asString();
} | nlsnho/libopenshot | src/CacheMemory.cpp | C++ | lgpl-3.0 | 10,641 |
<?php
require_once("smarty.php");
require_once("Db.php");
$DB= new DB_MYSQL();
session_start();
if(isset($_SESSION['userflag']) && $_SESSION['userflag'] == "admin")
{
$terms = $DB->get_all("select * from term");
$smarty->assign('Terms',$terms);
$smarty->display('showterms.html');
}
else
{
print("Access Denied");
echo "<script language=\"JavaScript\">alert(\"你好,请先登录!\");window.location.replace('../index.php');</script>";
}
?> | 2645Corp/2645-6 | include/showterms.php | PHP | lgpl-3.0 | 476 |
/*
* 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.reflect;
import java.util.Iterator;
import javax.xml.bind.JAXBException;
import org.xml.sax.SAXException;
/**
* Almost like {@link Iterator} but can throw JAXB specific exceptions.
* @author Kohsuke Kawaguchi
*/
public interface ListIterator<E> {
/**
* Works like {@link Iterator#hasNext()}.
*/
boolean hasNext();
/**
* Works like {@link Iterator#next()}.
*
* @throws SAXException
* if an error is found, reported, and we were told to abort
* @throws JAXBException
* if an error is found, reported, and we were told to abort
*/
E next() throws SAXException, JAXBException;
}
| B3Partners/b3p-commons-csw | src/main/jaxb/jaxb-ri-20090708/lib/jaxb-impl.src/com/sun/xml/bind/v2/runtime/reflect/ListIterator.java | Java | lgpl-3.0 | 2,632 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.qualitygate.ws;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.db.component.SnapshotDto;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.ProjectStatus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.utils.DateUtils.formatDateTime;
public class QualityGateDetailsFormatterTest {
private QualityGateDetailsFormatter underTest;
@Test
public void map_level_conditions_and_periods() throws IOException {
String measureData = IOUtils.toString(getClass().getResource("QualityGateDetailsFormatterTest/quality_gate_details.json"));
SnapshotDto snapshot = new SnapshotDto()
.setPeriodMode("last_version")
.setPeriodParam("2015-12-07")
.setPeriodDate(1449404331764L);
underTest = newQualityGateDetailsFormatter(measureData, snapshot);
ProjectStatus result = underTest.format();
assertThat(result.getStatus()).isEqualTo(ProjectStatusResponse.Status.ERROR);
// check conditions
assertThat(result.getConditionsCount()).isEqualTo(3);
List<ProjectStatusResponse.Condition> conditions = result.getConditionsList();
assertThat(conditions).extracting("status").containsExactly(
ProjectStatusResponse.Status.ERROR,
ProjectStatusResponse.Status.WARN,
ProjectStatusResponse.Status.OK);
assertThat(conditions).extracting("metricKey").containsExactly("new_coverage", "new_blocker_violations", "new_critical_violations");
assertThat(conditions).extracting("comparator").containsExactly(
ProjectStatusResponse.Comparator.LT,
ProjectStatusResponse.Comparator.GT,
ProjectStatusResponse.Comparator.GT);
assertThat(conditions).extracting("periodIndex").containsExactly(1, 1, 1);
assertThat(conditions).extracting("warningThreshold").containsOnly("80", "");
assertThat(conditions).extracting("errorThreshold").containsOnly("85", "0", "0");
assertThat(conditions).extracting("actualValue").containsExactly("82.2985024398452", "1", "0");
// check periods
assertThat(result.getPeriodsCount()).isOne();
List<ProjectStatusResponse.Period> periods = result.getPeriodsList();
assertThat(periods).extracting("index").containsExactly(1);
assertThat(periods).extracting("mode").containsExactly("last_version");
assertThat(periods).extracting("parameter").containsExactly("2015-12-07");
assertThat(periods.get(0).getDate()).isEqualTo(formatDateTime(snapshot.getPeriodDate()));
}
@Test
public void ignore_period_not_set_on_leak_period() throws IOException {
String measureData = IOUtils.toString(getClass().getResource("QualityGateDetailsFormatterTest/non_leak_period.json"));
SnapshotDto snapshot = new SnapshotDto()
.setPeriodMode("last_version")
.setPeriodParam("2015-12-07")
.setPeriodDate(1449404331764L);
underTest = newQualityGateDetailsFormatter(measureData, snapshot);
ProjectStatus result = underTest.format();
// check conditions
assertThat(result.getConditionsCount()).isOne();
List<ProjectStatusResponse.Condition> conditions = result.getConditionsList();
assertThat(conditions).extracting("status").containsExactly(ProjectStatusResponse.Status.ERROR);
assertThat(conditions).extracting("metricKey").containsExactly("new_coverage");
assertThat(conditions).extracting("comparator").containsExactly(ProjectStatusResponse.Comparator.LT);
assertThat(conditions).extracting("periodIndex").containsExactly(1);
assertThat(conditions).extracting("errorThreshold").containsOnly("85");
assertThat(conditions).extracting("actualValue").containsExactly("82.2985024398452");
}
@Test
public void fail_when_measure_level_is_unknown() {
String measureData = "{\n" +
" \"level\": \"UNKNOWN\",\n" +
" \"conditions\": [\n" +
" {\n" +
" \"metric\": \"new_coverage\",\n" +
" \"op\": \"LT\",\n" +
" \"period\": 1,\n" +
" \"warning\": \"80\",\n" +
" \"error\": \"85\",\n" +
" \"actual\": \"82.2985024398452\",\n" +
" \"level\": \"ERROR\"\n" +
" }\n" +
" ]\n" +
"}";
underTest = newQualityGateDetailsFormatter(measureData, new SnapshotDto());
assertThatThrownBy(() -> underTest.format())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Unknown quality gate status 'UNKNOWN'");
}
@Test
public void fail_when_measure_op_is_unknown() {
String measureData = "{\n" +
" \"level\": \"ERROR\",\n" +
" \"conditions\": [\n" +
" {\n" +
" \"metric\": \"new_coverage\",\n" +
" \"op\": \"UNKNOWN\",\n" +
" \"period\": 1,\n" +
" \"warning\": \"80\",\n" +
" \"error\": \"85\",\n" +
" \"actual\": \"82.2985024398452\",\n" +
" \"level\": \"ERROR\"\n" +
" }\n" +
" ]\n" +
"}";
underTest = newQualityGateDetailsFormatter(measureData, new SnapshotDto());
assertThatThrownBy(() -> underTest.format())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Unknown quality gate comparator 'UNKNOWN'");
}
private static QualityGateDetailsFormatter newQualityGateDetailsFormatter(@Nullable String measureData, @Nullable SnapshotDto snapshotDto) {
return new QualityGateDetailsFormatter(Optional.ofNullable(measureData), Optional.ofNullable(snapshotDto));
}
}
| SonarSource/sonarqube | server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/QualityGateDetailsFormatterTest.java | Java | lgpl-3.0 | 6,550 |
/*
* Copyright 2010-2015 Bastian Eicher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using NanoByte.Common.Native;
using NUnit.Framework;
namespace ZeroInstall.Store.Model
{
/// <summary>
/// Contains test methods for <see cref="Implementation"/>.
/// </summary>
[TestFixture]
public class ImplementationTest
{
#region Helpers
/// <summary>
/// Creates a fictive test <see cref="Implementation"/>.
/// </summary>
public static Implementation CreateTestImplementation()
{
return new Implementation
{
ID = "id", ManifestDigest = new ManifestDigest(sha256: "123"), Version = new ImplementationVersion("1.0"),
Architecture = new Architecture(OS.Windows, Cpu.I586), Languages = {"en-US"},
Main = "executable", DocDir = "doc", Stability = Stability.Developer,
Bindings = {EnvironmentBindingTest.CreateTestBinding()},
RetrievalMethods = {ArchiveTest.CreateTestArchive(), new Recipe {Steps = {ArchiveTest.CreateTestArchive()}}},
Commands = {CommandTest.CreateTestCommand1()}
};
}
#endregion
/// <summary>
/// Ensures that <see cref="Element.ContainsCommand"/> correctly checks for commands.
/// </summary>
[Test]
public void TestContainsCommand()
{
var implementation = CreateTestImplementation();
Assert.IsTrue(implementation.ContainsCommand(Command.NameRun));
Assert.IsFalse(implementation.ContainsCommand("other-command"));
}
/// <summary>
/// Ensures that <see cref="Element.GetCommand"/> and <see cref="Element.this"/> correctly retrieve commands.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "UnusedVariable")]
public void TestGetCommand()
{
var implementation = CreateTestImplementation();
Assert.AreEqual(implementation.Commands[0], implementation.GetCommand(Command.NameRun));
Assert.AreEqual(implementation.Commands[0], implementation[Command.NameRun]);
Assert.Throws<ArgumentNullException>(() => { var dummy = implementation.GetCommand(""); });
Assert.IsNull(implementation[""]);
Assert.IsNull(implementation.GetCommand("invalid"));
Assert.Throws<KeyNotFoundException>(() => { var dummy = implementation["invalid"]; });
}
/// <summary>
/// Ensures that <see cref="Implementation.Normalize"/> correctly identifies manifest digests in the ID tag.
/// </summary>
[Test]
public void TestNormalizeID()
{
var implementation = new Implementation {ID = "sha256=123"};
implementation.Normalize(FeedTest.Test1Uri);
Assert.AreEqual("123", implementation.ManifestDigest.Sha256);
implementation = new Implementation {ID = "sha256=wrong", ManifestDigest = new ManifestDigest(sha256: "correct")};
implementation.Normalize(FeedTest.Test1Uri);
Assert.AreEqual("correct", implementation.ManifestDigest.Sha256);
implementation = new Implementation {ID = "abc"};
implementation.Normalize(FeedTest.Test1Uri);
}
/// <summary>
/// Ensures that <see cref="Implementation.Normalize"/> correctly converts <see cref="Element.Main"/> and <see cref="Element.SelfTest"/> to <see cref="Command"/>s.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
public void TestNormalizeCommand()
{
var implementation = new Implementation {Main = "main", SelfTest = "test"};
implementation.Normalize(FeedTest.Test1Uri);
Assert.AreEqual("main", implementation[Command.NameRun].Path);
Assert.AreEqual("test", implementation[Command.NameTest].Path);
}
/// <summary>
/// Ensures that <see cref="Implementation.Normalize"/> correctly makes <see cref="ImplementationBase.LocalPath"/> absolute.
/// </summary>
[Test]
public void TestNormalizeLocalPath()
{
var localUri = new FeedUri(WindowsUtils.IsWindows ? @"C:\local\feed.xml" : "/local/feed.xml");
var implementation1 = new Implementation {ID = "./subdir"};
implementation1.Normalize(localUri);
Assert.AreEqual(
expected: WindowsUtils.IsWindows ? @"C:\local\.\subdir" : "/local/./subdir",
actual: implementation1.ID);
Assert.AreEqual(
expected: WindowsUtils.IsWindows ? @"C:\local\.\subdir" : "/local/./subdir",
actual: implementation1.LocalPath);
var implementation2 = new Implementation {ID = "./wrong", LocalPath = "subdir"};
implementation2.Normalize(localUri);
Assert.AreEqual(
expected: "./wrong",
actual: implementation2.ID);
Assert.AreEqual(
expected: WindowsUtils.IsWindows ? @"C:\local\subdir" : "/local/subdir",
actual: implementation2.LocalPath);
}
/// <summary>
/// Ensures that <see cref="Implementation.Normalize"/> rejects local paths in non-local feeds.
/// </summary>
[Test]
public void TestNormalizeRejectLocalPath()
{
var implmementation = new Implementation {LocalPath = "subdir"};
implmementation.Normalize(FeedTest.Test1Uri);
Assert.IsNull(implmementation.LocalPath);
}
/// <summary>
/// Ensures that <see cref="Implementation.Normalize"/> rejects relative <see cref="DownloadRetrievalMethod.Href"/>s in non-local feeds.
/// </summary>
[Test]
public void TestNormalizeRejectRelativeHref()
{
var relative = new Archive {Href = new Uri("relative", UriKind.Relative)};
var absolute = new Archive {Href = new Uri("http://server/absolute.zip", UriKind.Absolute)};
var implmementation = new Implementation {RetrievalMethods = {relative, absolute}};
implmementation.Normalize(FeedTest.Test1Uri);
CollectionAssert.AreEqual(
expected: new[] {absolute},
actual: implmementation.RetrievalMethods);
}
/// <summary>
/// Ensures that the class can be correctly cloned.
/// </summary>
[Test]
public void TestClone()
{
var implementation1 = CreateTestImplementation();
var implementation2 = implementation1.CloneImplementation();
// Ensure data stayed the same
Assert.AreEqual(implementation1, implementation2, "Cloned objects should be equal.");
Assert.AreEqual(implementation1.GetHashCode(), implementation2.GetHashCode(), "Cloned objects' hashes should be equal.");
Assert.IsFalse(ReferenceEquals(implementation1, implementation2), "Cloning should not return the same reference.");
}
}
}
| modulexcite/0install-win | src/Backend/UnitTests/Store/Model/ImplementationTest.cs | C# | lgpl-3.0 | 8,030 |
/*
* @BEGIN LICENSE
*
* Psi4: an open-source quantum chemistry software package
*
* Copyright (c) 2007-2018 The Psi4 Developers.
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* This file is part of Psi4.
*
* Psi4 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.
*
* Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* @END LICENSE
*/
#include "blas.h"
#include "index_iterator.h"
#include "mrccsd_t.h"
#include "special_matrices.h"
extern FILE* outfile;
namespace psi{ namespace psimrcc{
double MRCCSD_T::compute_AB_ooO_contribution_to_Heff_restricted(int u_abs,int V_abs,int x_abs,int Y_abs,int i_abs,int j_abs,int k_abs,int mu,BlockMatrix* T3)
{
double value = 0.0;
int i_sym = o->get_tuple_irrep(i_abs);
int j_sym = o->get_tuple_irrep(j_abs);
int k_sym = o->get_tuple_irrep(k_abs);
int ijk_sym = i_sym ^ j_sym ^ k_sym;
size_t i_rel = o->get_tuple_rel_index(i_abs);
size_t j_rel = o->get_tuple_rel_index(j_abs);
int x_sym = v->get_tuple_irrep(x_abs);
int y_sym = v->get_tuple_irrep(Y_abs);
int ij_sym = oo->get_tuple_irrep(i_abs,j_abs);
int jk_sym = oo->get_tuple_irrep(j_abs,k_abs);
int ik_sym = oo->get_tuple_irrep(i_abs,k_abs);
int uv_sym = oo->get_tuple_irrep(u_abs,V_abs);
int xy_sym = vv->get_tuple_irrep(x_abs,Y_abs);
size_t x_rel = v->get_tuple_rel_index(x_abs);
size_t y_rel = v->get_tuple_rel_index(Y_abs);
size_t ij_rel = oo->get_tuple_rel_index(i_abs,j_abs);
size_t ki_rel = oo->get_tuple_rel_index(k_abs,i_abs);
size_t kj_rel = oo->get_tuple_rel_index(k_abs,j_abs);
size_t xy_rel = vv->get_tuple_rel_index(x_abs,Y_abs);
if((j_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator e("[v]",i_sym);
for(e.first(); !e.end(); e.next()){
int e_sym = v->get_tuple_irrep(e.ind_abs<0>());
size_t e_rel = v->get_tuple_rel_index(e.ind_abs<0>());
if(uv_sym == xy_sym){
value += T3->get(e_sym,e_rel,xy_rel) * F2_ov[mu][i_sym][i_rel][e_rel];
}
}
}
if((i_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator e("[v]",j_sym);
for(e.first(); !e.end(); e.next()){
int e_sym = v->get_tuple_irrep(e.ind_abs<0>());
size_t e_rel = v->get_tuple_rel_index(e.ind_abs<0>());
if(uv_sym == xy_sym){
value -= T3->get(e_sym,e_rel,xy_rel) * F2_ov[mu][j_sym][j_rel][e_rel];
}
}
}
if(i_abs == u_abs){
CCIndexIterator e("[v]",ijk_sym ^ xy_sym);
for(e.first(); !e.end(); e.next()){
int e_sym = v->get_tuple_irrep(e.ind_abs<0>());
size_t e_rel = v->get_tuple_rel_index(e.ind_abs<0>());
int ve_sym = ov->get_tuple_irrep(V_abs,e.ind_abs<0>());
size_t ve_rel = ov->get_tuple_rel_index(V_abs,e.ind_abs<0>());
if(jk_sym == ve_sym){
value += T3->get(e_sym,e_rel,xy_rel) * W_OoOv[mu][jk_sym][kj_rel][ve_rel];
}
}
}
if(j_abs == u_abs){
CCIndexIterator e("[v]",ijk_sym ^ xy_sym);
for(e.first(); !e.end(); e.next()){
int e_sym = v->get_tuple_irrep(e.ind_abs<0>());
size_t e_rel = v->get_tuple_rel_index(e.ind_abs<0>());
int ve_sym = ov->get_tuple_irrep(V_abs,e.ind_abs<0>());
size_t ve_rel = ov->get_tuple_rel_index(V_abs,e.ind_abs<0>());
if(ik_sym == ve_sym){
value -= T3->get(e_sym,e_rel,xy_rel) * W_OoOv[mu][ik_sym][ki_rel][ve_rel];
}
}
}
if(k_abs == V_abs){
CCIndexIterator e("[v]",ijk_sym ^ xy_sym);
for(e.first(); !e.end(); e.next()){
int e_sym = v->get_tuple_irrep(e.ind_abs<0>());
size_t e_rel = v->get_tuple_rel_index(e.ind_abs<0>());
int ue_sym = ov->get_tuple_irrep(u_abs,e.ind_abs<0>());
size_t ue_rel = ov->get_tuple_rel_index(u_abs,e.ind_abs<0>());
if(ij_sym == ue_sym){
value += T3->get(e_sym,e_rel,xy_rel) * W_ooov[mu][ij_sym][ij_rel][ue_rel];
}
}
}
if((j_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator ef("[vv]",ijk_sym ^ x_sym);
for(ef.first(); !ef.end(); ef.next()){
int ief_sym = ovv->get_tuple_irrep(i_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
size_t fe_rel = vv->get_tuple_rel_index(ef.ind_abs<1>(),ef.ind_abs<0>());
size_t ief_rel = ovv->get_tuple_rel_index(i_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
if(y_sym == ief_sym){
value -= T3->get(x_sym,x_rel,fe_rel) * W_VoVv[mu][y_sym][y_rel][ief_rel];
}
}
}
if((i_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator ef("[vv]",ijk_sym ^ x_sym);
for(ef.first(); !ef.end(); ef.next()){
int jef_sym = ovv->get_tuple_irrep(j_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
size_t fe_rel = vv->get_tuple_rel_index(ef.ind_abs<1>(),ef.ind_abs<0>());
size_t jef_rel = ovv->get_tuple_rel_index(j_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
if(y_sym == jef_sym){
value += T3->get(x_sym,x_rel,fe_rel) * W_VoVv[mu][y_sym][y_rel][jef_rel];
}
}
}
if((j_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator ef("[vv]",ijk_sym ^ y_sym);
for(ef.first(); !ef.end(); ef.next()){
int e_sym = v->get_tuple_irrep(ef.ind_abs<0>());
int ief_sym = ovv->get_tuple_irrep(i_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
size_t e_rel = v->get_tuple_rel_index(ef.ind_abs<0>());
size_t fy_rel = vv->get_tuple_rel_index(ef.ind_abs<1>(),Y_abs);
size_t ief_rel = ovv->get_tuple_rel_index(i_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
if(x_sym == ief_sym){
value -= 0.5 * T3->get(e_sym,e_rel,fy_rel) * W_vovv[mu][x_sym][x_rel][ief_rel];
}
}
}
if((i_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator ef("[vv]",ijk_sym ^ y_sym);
for(ef.first(); !ef.end(); ef.next()){
int e_sym = v->get_tuple_irrep(ef.ind_abs<0>());
int jef_sym = ovv->get_tuple_irrep(j_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
size_t e_rel = v->get_tuple_rel_index(ef.ind_abs<0>());
size_t fy_rel = vv->get_tuple_rel_index(ef.ind_abs<1>(),Y_abs);
size_t jef_rel = ovv->get_tuple_rel_index(j_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
if(x_sym == jef_sym){
value += 0.5 * T3->get(e_sym,e_rel,fy_rel) * W_vovv[mu][x_sym][x_rel][jef_rel];
}
}
}
return value;
}
double MRCCSD_T::compute_AB_oOO_contribution_to_Heff_restricted(int u_abs,int V_abs,int x_abs,int Y_abs,int i_abs,int j_abs,int k_abs,int mu,BlockMatrix* T3)
{
double value = 0.0;
int i_sym = o->get_tuple_irrep(i_abs);
int j_sym = o->get_tuple_irrep(j_abs);
int k_sym = o->get_tuple_irrep(k_abs);
int ijk_sym = i_sym ^ j_sym ^ k_sym;
size_t j_rel = o->get_tuple_rel_index(j_abs);
size_t k_rel = o->get_tuple_rel_index(k_abs);
int x_sym = v->get_tuple_irrep(x_abs);
int y_sym = v->get_tuple_irrep(Y_abs);
int ij_sym = oo->get_tuple_irrep(i_abs,j_abs);
int ik_sym = oo->get_tuple_irrep(i_abs,k_abs);
int jk_sym = oo->get_tuple_irrep(j_abs,k_abs);
int uv_sym = oo->get_tuple_irrep(u_abs,V_abs);
int xy_sym = vv->get_tuple_irrep(x_abs,Y_abs);
size_t x_rel = v->get_tuple_rel_index(x_abs);
size_t y_rel = v->get_tuple_rel_index(Y_abs);
size_t ij_rel = oo->get_tuple_rel_index(i_abs,j_abs);
size_t ik_rel = oo->get_tuple_rel_index(i_abs,k_abs);
size_t jk_rel = oo->get_tuple_rel_index(j_abs,k_abs);
if((i_abs == u_abs) && (j_abs == V_abs)){
CCIndexIterator e("[v]",k_sym);
for(e.first(); !e.end(); e.next()){
size_t e_rel = v->get_tuple_rel_index(e.ind_abs<0>());
size_t ye_rel = vv->get_tuple_rel_index(Y_abs,e.ind_abs<0>());
if(uv_sym == xy_sym){
value += T3->get(x_sym,x_rel,ye_rel) * F2_OV[mu][k_sym][k_rel][e_rel];
}
}
}
if((i_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator e("[v]",j_sym);
for(e.first(); !e.end(); e.next()){
size_t e_rel = v->get_tuple_rel_index(e.ind_abs<0>());
size_t ye_rel = vv->get_tuple_rel_index(Y_abs,e.ind_abs<0>());
if(uv_sym == xy_sym){
value -= T3->get(x_sym,x_rel,ye_rel) * F2_OV[mu][j_sym][j_rel][e_rel];
}
}
}
if(i_abs == u_abs){
CCIndexIterator e("[v]",ijk_sym ^ xy_sym);
for(e.first(); !e.end(); e.next()){
int ve_sym = ov->get_tuple_irrep(V_abs,e.ind_abs<0>());
size_t ve_rel = ov->get_tuple_rel_index(V_abs,e.ind_abs<0>());
size_t ye_rel = vv->get_tuple_rel_index(Y_abs,e.ind_abs<0>());
if(jk_sym == ve_sym){
value -= T3->get(x_sym,x_rel,ye_rel) * W_OOOV[mu][jk_sym][jk_rel][ve_rel]; // Could be wrong, not in the CH2 example
}
}
}
if(k_abs == V_abs){
CCIndexIterator e("[v]",ijk_sym ^ xy_sym);
for(e.first(); !e.end(); e.next()){
int ue_sym = ov->get_tuple_irrep(u_abs,e.ind_abs<0>());
size_t ue_rel = ov->get_tuple_rel_index(u_abs,e.ind_abs<0>());
size_t ye_rel = vv->get_tuple_rel_index(Y_abs,e.ind_abs<0>());
if(ij_sym == ue_sym){
value += T3->get(x_sym,x_rel,ye_rel) * W_oOoV[mu][ij_sym][ij_rel][ue_rel];
}
}
}
if(j_abs == V_abs){
CCIndexIterator e("[v]",ijk_sym ^ xy_sym);
for(e.first(); !e.end(); e.next()){
int ue_sym = ov->get_tuple_irrep(u_abs,e.ind_abs<0>());
size_t ue_rel = ov->get_tuple_rel_index(u_abs,e.ind_abs<0>());
size_t ye_rel = vv->get_tuple_rel_index(Y_abs,e.ind_abs<0>());
if(ik_sym == ue_sym){
value -= T3->get(x_sym,x_rel,ye_rel) * W_oOoV[mu][ik_sym][ik_rel][ue_rel];
}
}
}
if((i_abs == u_abs) && (j_abs == V_abs)){
CCIndexIterator ef("[vv]",ijk_sym ^ x_sym);
for(ef.first(); !ef.end(); ef.next()){
int kef_sym = ovv->get_tuple_irrep(k_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
size_t ef_rel = vv->get_tuple_rel_index(ef.ind_abs<0>(),ef.ind_abs<1>());
size_t kef_rel = ovv->get_tuple_rel_index(k_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
if(y_sym == kef_sym){
value += 0.5 * T3->get(x_sym,x_rel,ef_rel) * W_VOVV[mu][y_sym][y_rel][kef_rel];
}
}
}
if((i_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator ef("[vv]",ijk_sym ^ x_sym);
for(ef.first(); !ef.end(); ef.next()){
int jef_sym = ovv->get_tuple_irrep(j_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
size_t ef_rel = vv->get_tuple_rel_index(ef.ind_abs<0>(),ef.ind_abs<1>());
size_t jef_rel = ovv->get_tuple_rel_index(j_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
if(y_sym == jef_sym){
value -= 0.5 * T3->get(x_sym,x_rel,ef_rel) * W_VOVV[mu][y_sym][y_rel][jef_rel];
}
}
}
if((i_abs == u_abs) && (j_abs == V_abs)){
CCIndexIterator ef("[vv]",ijk_sym ^ y_sym);
for(ef.first(); !ef.end(); ef.next()){
int e_sym = v->get_tuple_irrep(ef.ind_abs<0>());
int kef_sym = ovv->get_tuple_irrep(k_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
size_t e_rel = v->get_tuple_rel_index(ef.ind_abs<0>());
size_t yf_rel = vv->get_tuple_rel_index(Y_abs,ef.ind_abs<1>());
size_t kef_rel = ovv->get_tuple_rel_index(k_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
if(x_sym == kef_sym){
value += T3->get(e_sym,e_rel,yf_rel) * W_vOvV[mu][x_sym][x_rel][kef_rel];
}
}
}
if((i_abs == u_abs) && (k_abs == V_abs)){
CCIndexIterator ef("[vv]",ijk_sym ^ y_sym);
for(ef.first(); !ef.end(); ef.next()){
int e_sym = v->get_tuple_irrep(ef.ind_abs<0>());
int jef_sym = ovv->get_tuple_irrep(j_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
size_t e_rel = v->get_tuple_rel_index(ef.ind_abs<0>());
size_t yf_rel = vv->get_tuple_rel_index(Y_abs,ef.ind_abs<1>());
size_t jef_rel = ovv->get_tuple_rel_index(j_abs,ef.ind_abs<0>(),ef.ind_abs<1>());
if(x_sym == jef_sym){
value -= T3->get(e_sym,e_rel,yf_rel) * W_vOvV[mu][x_sym][x_rel][jef_rel];
}
}
}
return value;
}
}} /* End Namespaces */
| amjames/psi4 | psi4/src/psi4/psimrcc/mrccsd_t_heff_ab_restricted.cc | C++ | lgpl-3.0 | 12,364 |
/**
* This file is part of SensApp Acceptance.
*
* SensApp Acceptance 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.
*
* SensApp Acceptance 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 SensApp Acceptance. If not, see <http://www.gnu.org/licenses/>.
*/
package net.modelbased.sensapp.acceptance;
import java.io.File;
/**
* A reference to a property file on disk.
*/
public class EndPointsFile extends File {
private static final long serialVersionUID = 1L;
/**
* Create from the path to a property file.
*
* @param path the local path to the property file of interest
*/
public EndPointsFile(String path) {
super(path);
if (!path.endsWith(PROPERTIES_FILE_EXTENSION)) {
throw new IllegalArgumentException("Invalid path to a property file, expected '*.properties' but '" + path + "' was found.");
}
}
private static final String PROPERTIES_FILE_EXTENSION = ".properties";
}
| SINTEF-9012/sensapp-acceptance | src/main/java/net/modelbased/sensapp/acceptance/EndPointsFile.java | Java | lgpl-3.0 | 1,469 |
# -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com>
#
# Glances 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.
#
# Glances 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/>.
"""Manage the monitor list."""
# Import system lib
import re
import subprocess
# Import Glances lib
from glances.core.glances_logging import logger
from glances.core.glances_processes import glances_processes
class MonitorList(object):
"""This class describes the optional monitored processes list.
The monitored list is a list of 'important' processes to monitor.
The list (Python list) is composed of items (Python dict).
An item is defined (dict keys):
* description: Description of the processes (max 16 chars)
* regex: regular expression of the processes to monitor
* command: (optional) shell command for extended stat
* countmin: (optional) minimal number of processes
* countmax: (optional) maximum number of processes
"""
# Maximum number of items in the list
__monitor_list_max_size = 10
# The list
__monitor_list = []
def __init__(self, config):
"""Init the monitoring list from the configuration file."""
self.config = config
if self.config is not None and self.config.has_section('monitor'):
# Process monitoring list
self.__set_monitor_list('monitor', 'list')
else:
self.__monitor_list = []
def __set_monitor_list(self, section, key):
"""Init the monitored processes list.
The list is defined in the Glances configuration file.
"""
for l in range(1, self.__monitor_list_max_size + 1):
value = {}
key = "list_" + str(l) + "_"
try:
description = self.config.get_raw_option(section, key + "description")
regex = self.config.get_raw_option(section, key + "regex")
command = self.config.get_raw_option(section, key + "command")
countmin = self.config.get_raw_option(section, key + "countmin")
countmax = self.config.get_raw_option(section, key + "countmax")
except Exception as e:
logger.error("Cannot read monitored list: {0}".format(e))
pass
else:
if description is not None and regex is not None:
# Build the new item
value["description"] = description
try:
re.compile(regex)
except Exception:
continue
else:
value["regex"] = regex
value["command"] = command
value["countmin"] = countmin
value["countmax"] = countmax
value["count"] = None
value["result"] = None
# Add the item to the list
self.__monitor_list.append(value)
def __str__(self):
return str(self.__monitor_list)
def __repr__(self):
return self.__monitor_list
def __getitem__(self, item):
return self.__monitor_list[item]
def __len__(self):
return len(self.__monitor_list)
def __get__(self, item, key):
"""Meta function to return key value of item.
Return None if not defined or item > len(list)
"""
if item < len(self.__monitor_list):
try:
return self.__monitor_list[item][key]
except Exception:
return None
else:
return None
def update(self):
"""Update the command result attributed."""
# Only continue if monitor list is not empty
if len(self.__monitor_list) == 0:
return self.__monitor_list
# Iter upon the monitored list
for i in range(0, len(self.get())):
# Search monitored processes by a regular expression
processlist = glances_processes.getlist()
monitoredlist = [p for p in processlist if re.search(self.regex(i), p['cmdline']) is not None]
self.__monitor_list[i]['count'] = len(monitoredlist)
if self.command(i) is None:
# If there is no command specified in the conf file
# then display CPU and MEM %
self.__monitor_list[i]['result'] = 'CPU: {0:.1f}% | MEM: {1:.1f}%'.format(
sum([p['cpu_percent'] for p in monitoredlist]),
sum([p['memory_percent'] for p in monitoredlist]))
continue
else:
# Execute the user command line
try:
self.__monitor_list[i]['result'] = subprocess.check_output(self.command(i),
shell=True)
except subprocess.CalledProcessError:
self.__monitor_list[i]['result'] = _("Error: ") + self.command(i)
except Exception:
self.__monitor_list[i]['result'] = _("Cannot execute command")
return self.__monitor_list
def get(self):
"""Return the monitored list (list of dict)."""
return self.__monitor_list
def set(self, newlist):
"""Set the monitored list (list of dict)."""
self.__monitor_list = newlist
def getAll(self):
# Deprecated: use get()
return self.get()
def setAll(self, newlist):
# Deprecated: use set()
self.set(newlist)
def description(self, item):
"""Return the description of the item number (item)."""
return self.__get__(item, "description")
def regex(self, item):
"""Return the regular expression of the item number (item)."""
return self.__get__(item, "regex")
def command(self, item):
"""Return the stat command of the item number (item)."""
return self.__get__(item, "command")
def result(self, item):
"""Return the reult command of the item number (item)."""
return self.__get__(item, "result")
def countmin(self, item):
"""Return the minimum number of processes of the item number (item)."""
return self.__get__(item, "countmin")
def countmax(self, item):
"""Return the maximum number of processes of the item number (item)."""
return self.__get__(item, "countmax")
| nclsHart/glances | glances/core/glances_monitor_list.py | Python | lgpl-3.0 | 7,047 |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Matthew Ward" email="mrward@users.sourceforge.net"/>
// <version>$Revision$</version>
// </file>
using ICSharpCode.WixBinding;
using NUnit.Framework;
using System;
using System.IO;
using System.Xml;
namespace WixBinding.Tests.Document
{
/// <summary>
/// Tests that the only a directory with an Id of TARGETDIR is detected as
/// the root directory in a wix file.
/// </summary>
[TestFixture]
public class NonRootDirectoryTestFixture
{
XmlElement directory;
[SetUp]
public void SetUpFixture()
{
WixDocument doc = new WixDocument();
doc.LoadXml(GetWixXml());
directory = doc.RootDirectory;
}
[Test]
public void NoRootDirectoryFound()
{
Assert.IsNull(directory);
}
string GetWixXml()
{
return "<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>\r\n" +
"\t<Product Name='DialogTest' \r\n" +
"\t Version='1.0' \r\n" +
"\t Language='1013' \r\n" +
"\t Manufacturer='#develop' \r\n" +
"\t Id='????????-????-????-????-????????????'>\r\n" +
"\t\t<Package/>\r\n" +
"\t\t<Directory Id=\"TESTDIR\" SourceName=\"SourceDir\">\r\n" +
"\t\t</Directory>\r\n" +
"\t</Product>\r\n" +
"</Wix>";
}
}
}
| kingjiang/SharpDevelopLite | src/AddIns/BackendBindings/WixBinding/Test/Document/NonRootDirectoryTestFixture.cs | C# | lgpl-3.0 | 1,352 |
/*
* Copyright (c) 2017 NOVA, All rights reserved.
* This library is free software, licensed under GNU Lesser General Public License version 3
*
* This file is part of NOVA.
*
* NOVA 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.
*
* NOVA 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 NOVA. If not, see <http://www.gnu.org/licenses/>.
*/
package nova.testutils.mod;
import nova.core.loader.Mod;
/**
* @author ExE Boss
*/
@Mod(id = "testModWithMissingDependency", name = "Test Mod (Missing Depenendency)", version = "0.0.1", novaVersion = "0.1.0", dependencies = {"testMissingMod@f"})
public class TestModWithMissingDependency {
}
| NOVA-Team/NOVA-Core | modules/core/src/test/java/nova/testutils/mod/TestModWithMissingDependency.java | Java | lgpl-3.0 | 1,104 |
/* Animator Frame Rate Widget
*
* Controls the frame rate of a group of animators.
*/
#include "gtkmm.h"
#include <papyrus/affineanimator.h>
#include <papyrus-extras/factory.h>
#include <papyrus-gtkmm/animatorframeratewidget.h>
#include <papyrus-gtkmm/viewport.h>
#include <gtkmm.h>
class Example_AnimatorFrameRateWidget : public Gtk::Window
{
public:
Example_AnimatorFrameRateWidget();
virtual ~Example_AnimatorFrameRateWidget();
protected:
//Member widgets:
Papyrus::Gtk::AnimatorFrameRateWidget m_AnimatorFrameRateWidget;
Papyrus::Gtk::Viewport m_Viewport;
Papyrus::AffineAnimator::pointer m_AffineAnimator;
Papyrus::Group::pointer m_shape;
Gtk::VBox m_vbox;
Gtk::CheckButton m_check;
Gtk::Button m_reset;
void on_start_stop();
void on_reset();
};
//Called by DemoWindow;
Gtk::Window* do_AnimatorFrameRateWidget()
{
return new Example_AnimatorFrameRateWidget();
}
Example_AnimatorFrameRateWidget::Example_AnimatorFrameRateWidget()
{
m_shape = Papyrus::example_group( true, true );
m_Viewport.canvas()->add( m_shape );
m_Viewport.set_size_request( 300, 300 );
m_AffineAnimator = Papyrus::AffineAnimator::create();
m_AffineAnimator->add( m_shape );
m_AnimatorFrameRateWidget.add( m_AffineAnimator );
set_title("Animator Frame Rate Widget");
set_border_width(10);
m_vbox.pack_start( m_AnimatorFrameRateWidget );
m_vbox.pack_start( *Gtk::manage( new Gtk::HSeparator() ) );
m_vbox.pack_start( m_check );
m_vbox.pack_start( m_reset );
m_vbox.pack_start( m_Viewport );
m_check.set_label( "Start Animation");
m_check.signal_toggled().connect( sigc::mem_fun( *this, &Example_AnimatorFrameRateWidget::on_start_stop ) );
m_reset.set_label( "Reset" );
m_reset.signal_clicked().connect( sigc::mem_fun( *this, &Example_AnimatorFrameRateWidget::on_reset ) );
m_AffineAnimator->set_frame_rate( 20 );
m_AffineAnimator->set_rotate( M_PI/50 );
m_AffineAnimator->set_translate( 2.0, -2.0 );
m_AffineAnimator->set_bounce_frames( 40 );
this->add( m_vbox );
show_all();
}
Example_AnimatorFrameRateWidget::~Example_AnimatorFrameRateWidget()
{
}
void Example_AnimatorFrameRateWidget::on_start_stop()
{
if ( m_check.get_active() )
m_AffineAnimator->start();
else
m_AffineAnimator->stop();
}
void Example_AnimatorFrameRateWidget::on_reset()
{
// TODO fix
// m_shape->set_rotate( 0.0 );
// m_shape->set_translate( 0.0, 0.0 );
}
/***************************************************************************
* Copyright (C) 2009 by Rick L. Vinyard, Jr. *
* rvinyard@cs.nmsu.edu *
* *
* This file is part of the papyrus library. *
* *
* papyrus is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License *
* version 3.0 as published by the Free Software Foundation. *
* *
* papyrus 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 version 3.0 for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with the papyrus library. If not, see *
* <http://www.gnu.org/licenses/>. *
***************************************************************************/
| scott--/papyrus | demos/papyrus-gtkmm-demo/example_animatorframeratewidget.cpp | C++ | lgpl-3.0 | 3,909 |
package com.Orion.Armory.World.Common.WorldGen;
import com.Orion.Armory.World.Common.Config.WorldGenConfigs;
import cpw.mods.fml.common.IWorldGenerator;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenMinable;
import java.util.Random;
/**
* Created by Marc on 6-6-2015.
*/
public class WorldGenCommonOre implements IWorldGenerator
{
WorldGenMinable iMinable;
int iMeta;
int iMaxY;
int iMinY;
int iTriesPerChunk;
public WorldGenCommonOre(Block pBlockToGen, int pMeta, int pBlocksPerCluster)
{
this(pBlockToGen, pMeta, pBlocksPerCluster,0, -1);
}
public WorldGenCommonOre(Block pBlockToGen, int pMeta, int pBlocksPerCluster, int pMinY, int pMaxY)
{
this(pBlockToGen, pMeta, pBlocksPerCluster, pMinY, pMaxY, 4);
}
public WorldGenCommonOre(Block pBlockToGen, int pMeta, int pBlocksPerCluster, int pMinY, int pMaxY, int pTriesPerChunk)
{
iMinable = new WorldGenMinable(pBlockToGen, pMeta, pBlocksPerCluster, Blocks.stone);
iMeta = pMeta;
iMaxY = pMaxY;
iMinY = pMinY;
iTriesPerChunk = pTriesPerChunk;
}
@Override
public void generate(Random pRandom, int pChunkX, int pChunkZ, World pWorld, IChunkProvider pChunkGen, IChunkProvider pChunkProv) {
if (!WorldGenConfigs.doWorldGens)
return;
int tLocalMaxY = iMaxY;
int tLocalMinY = iMinY;
if (iMaxY == -1)
{
tLocalMaxY = pWorld.provider.getAverageGroundLevel() + 1;
}
if (tLocalMaxY < tLocalMinY)
{
return;
}
for (int tSpawnAttempt = 0; tSpawnAttempt < iTriesPerChunk; tSpawnAttempt ++)
{
Random tR = new Random();
float tChance = tR.nextFloat() * 4F;
switch (iMeta)
{
case 0:
if (tChance > WorldGenConfigs.CommonOres.spawnChanceForCopper)
return;
case 1:
if (tChance > WorldGenConfigs.CommonOres.spawnChanceForTin)
return;
case 2:
if (tChance > WorldGenConfigs.CommonOres.spawnChanceForSilver)
return;
case 3:
if (tChance > WorldGenConfigs.CommonOres.spawnChanceForLead)
return;
}
int tX = (pChunkX * 16) + tR.nextInt(16);
int tY = tLocalMinY + tR.nextInt(tLocalMaxY - tLocalMinY + 1);
int tZ = (pChunkZ * 16) + tR.nextInt(16);
iMinable.generate(pWorld, tR, tX ,tY, tZ);
}
}
}
| SmithsModding/World | src/Armory/World/com/Orion/Armory/World/Common/WorldGen/WorldGenCommonOre.java | Java | lgpl-3.0 | 2,791 |
/*
* This file is part of alphaTab.
* Copyright (c) 2014, Daniel Kuschny and Contributors, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or at your option any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
using System;
using System.Drawing;
namespace AlphaTab.Gdi
{
/// <summary>
/// http://www.geekymonkey.com/Programming/CSharp/RGB2HSL_HSL2RGB.htm
/// </summary>
public static class ColorTools
{
// Given H,S,L in range of 0-1
// Returns a Color (RGB struct) in range of 0-255
public static Color HSL2RGB(double h, double sl, double l)
{
double v;
double r, g, b;
r = l; // default to gray
g = l;
b = l;
v = (l <= 0.5) ? (l * (1.0 + sl)) : (l + sl - l * sl);
if (v > 0)
{
double m;
double sv;
int sextant;
double fract, vsf, mid1, mid2;
m = l + l - v;
sv = (v - m) / v;
h *= 6.0;
sextant = (int)h;
fract = h - sextant;
vsf = v * sv * fract;
mid1 = m + vsf;
mid2 = v - vsf;
switch (sextant)
{
case 0:
r = v;
g = mid1;
b = m;
break;
case 1:
r = mid2;
g = v;
b = m;
break;
case 2:
r = m;
g = v;
b = mid1;
break;
case 3:
r = m;
g = mid2;
b = v;
break;
case 4:
r = mid1;
g = m;
b = v;
break;
case 5:
r = v;
g = m;
b = mid2;
break;
}
}
return Color.FromArgb(Convert.ToByte(r * 255.0f), Convert.ToByte(g * 255.0f), Convert.ToByte(b * 255.0f));
}
// Given a Color (RGB Struct) in range of 0-255
// Return H,S,L in range of 0-1
public static void RGB2HSL(Color rgb, out double h, out double s, out double l)
{
double r = rgb.R / 255.0;
double g = rgb.G / 255.0;
double b = rgb.B / 255.0;
double v;
double m;
double vm;
double r2, g2, b2;
h = 0; // default to black
s = 0;
l = 0;
v = System.Math.Max(r, g);
v = System.Math.Max(v, b);
m = System.Math.Min(r, g);
m = System.Math.Min(m, b);
l = (m + v) / 2.0;
if (l <= 0.0)
{
return;
}
vm = v - m;
s = vm;
if (s > 0.0)
{
s /= (l <= 0.5) ? (v + m) : (2.0 - v - m);
}
else
{
return;
}
r2 = (v - r) / vm;
g2 = (v - g) / vm;
b2 = (v - b) / vm;
if (r == v)
{
h = (g == m ? 5.0 + b2 : 1.0 - g2);
}
else if (g == v)
{
h = (b == m ? 1.0 + r2 : 3.0 - b2);
}
else
{
h = (r == m ? 3.0 + g2 : 5.0 - r2);
}
h /= 6.0;
}
}
}
| dreamzor/alphaTab | Samples/CSharp/AlphaTab.WinForms/ColorTools.cs | C# | lgpl-3.0 | 4,326 |
/**
******************************************************************************
* @file spark_wiring.cpp
* @authors Satish Nair, Zachary Crockett, Zach Supalla, Mohit Bhoite and
* Brett Walach
* @version V1.0.0
* @date 13-March-2013
* @brief
******************************************************************************
Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <http://www.gnu.org/licenses/>.
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "spark_wiring.h"
#include "spark_wiring_interrupts.h"
#include "spark_wiring_usartserial.h"
#include "spark_wiring_spi.h"
#include "spark_wiring_i2c.h"
#include "watchdog_hal.h"
#include "delay_hal.h"
#include "pinmap_hal.h"
#include "system_task.h"
#include "enumclass.h"
/*
* @brief Set the mode of the pin to OUTPUT, INPUT, INPUT_PULLUP,
* or INPUT_PULLDOWN
*/
void pinMode(uint16_t pin, PinMode setMode)
{
if(pin >= TOTAL_PINS || setMode == PIN_MODE_NONE )
{
return;
}
// Safety check
if( !pinAvailable(pin) ) {
return;
}
HAL_Pin_Mode(pin, setMode);
}
/*
* @brief Returns the mode of the selected pin as type PinMode
*
* OUTPUT = 0
* INPUT = 1
* INPUT_PULLUP = 2
* INPUT_PULLDOWN = 3
* AF_OUTPUT_PUSHPULL = 4
* AF_OUTPUT_DRAIN = 5
* AN_INPUT = 6
* AN_OUTPUT = 7
* PIN_MODE_NONE = 255
*/
PinMode getPinMode(uint16_t pin)
{
return HAL_Get_Pin_Mode(pin);
}
#if HAL_PLATFORM_GEN == 3
/*
* @brief Set the drive strength of the pin for OUTPUT modes
*/
int pinSetDriveStrength(pin_t pin, DriveStrength drive)
{
if (pin >= TOTAL_PINS) {
return SYSTEM_ERROR_INVALID_ARGUMENT;
}
// Safety check
if (!pinAvailable(pin)) {
return SYSTEM_ERROR_INVALID_STATE;
}
auto mode = getPinMode(pin);
if (mode != OUTPUT && mode != OUTPUT_OPEN_DRAIN) {
return SYSTEM_ERROR_INVALID_STATE;
}
const hal_gpio_config_t conf = {
.size = sizeof(hal_gpio_config_t),
.version = HAL_GPIO_VERSION,
.mode = mode,
.set_value = 0,
.value = 0,
.drive_strength = particle::to_underlying(drive)
};
return HAL_Pin_Configure(pin, &conf, nullptr);
}
#endif // HAL_PLATFORM_GEN == 3
/*
* @brief Perform safety check on desired pin to see if it's already
* being used. Return 0 if used, otherwise return 1 if available.
*/
bool pinAvailable(uint16_t pin) {
if (pin >= TOTAL_PINS) {
return false;
}
// SPI safety check
#ifndef SPARK_WIRING_NO_SPI
if((pin == SCK || pin == MOSI || pin == MISO) && hal_spi_is_enabled(SPI.interface()) == true)
{
return false; // 'pin' is used
}
#endif
// I2C safety check
#ifndef SPARK_WIRING_NO_I2C
if((pin == SCL || pin == SDA) && hal_i2c_is_enabled(Wire.interface(), nullptr) == true)
{
return false; // 'pin' is used
}
#endif
#ifndef SPARK_WIRING_NO_USART_SERIAL
// Serial1 safety check
if((pin == RX || pin == TX) && hal_usart_is_enabled(Serial1.interface()) == true)
{
return false; // 'pin' is used
}
#endif
return true; // 'pin' is available
}
inline bool is_input_mode(PinMode mode) {
return mode == INPUT ||
mode == INPUT_PULLUP ||
mode == INPUT_PULLDOWN ||
mode == AN_INPUT;
}
/*
* @brief Sets a GPIO pin to HIGH or LOW.
*/
void digitalWrite(pin_t pin, uint8_t value)
{
PinMode mode = HAL_Get_Pin_Mode(pin);
if (mode==PIN_MODE_NONE || is_input_mode(mode))
return;
// Safety check
if( !pinAvailable(pin) ) {
return;
}
HAL_GPIO_Write(pin, value);
}
inline bool is_af_output_mode(PinMode mode) {
return mode == AF_OUTPUT_PUSHPULL ||
mode == AF_OUTPUT_DRAIN;
}
/*
* @brief Reads the value of a GPIO pin. Should return either 1 (HIGH) or 0 (LOW).
*/
int32_t digitalRead(pin_t pin)
{
PinMode mode = HAL_Get_Pin_Mode(pin);
if (is_af_output_mode(mode))
return LOW;
// Safety check
if( !pinAvailable(pin) ) {
return LOW;
}
return HAL_GPIO_Read(pin);
}
/*
* @brief Read the analog value of a pin.
* Should return a 16-bit value, 0-65536 (0 = LOW, 65536 = HIGH)
* Note: ADC is 12-bit. Currently it returns 0-4095
*/
int32_t analogRead(pin_t pin)
{
// Allow people to use 0-7 to define analog pins by checking to see if the values are too low.
#if defined(FIRST_ANALOG_PIN) && FIRST_ANALOG_PIN > 0
if(pin < FIRST_ANALOG_PIN)
{
pin = pin + FIRST_ANALOG_PIN;
}
#endif // defined(FIRST_ANALOG_PIN) && FIRST_ANALOG_PIN > 0
// Safety check
if( !pinAvailable(pin) ) {
return LOW;
}
if(HAL_Validate_Pin_Function(pin, PF_ADC)!=PF_ADC)
{
return LOW;
}
return hal_adc_read(pin);
}
/*
* @brief Should take an integer 0-255 and create a 500Hz PWM signal with a duty cycle from 0-100%.
* On Photon, DAC1 and DAC2 act as true analog outputs(values: 0 to 4095) using onchip DAC peripheral
*/
void analogWrite(pin_t pin, uint32_t value)
{
// Safety check
if (!pinAvailable(pin))
{
return;
}
if (HAL_Validate_Pin_Function(pin, PF_DAC) == PF_DAC)
{
HAL_DAC_Write(pin, value);
}
else if (HAL_Validate_Pin_Function(pin, PF_TIMER) == PF_TIMER)
{
PinMode mode = HAL_Get_Pin_Mode(pin);
if (mode != OUTPUT && mode != AF_OUTPUT_PUSHPULL)
{
return;
}
hal_pwm_write_ext(pin, value);
}
}
/*
* @brief Should take an integer 0-255 and create a PWM signal with a duty cycle from 0-100%
* and frequency from 1 to 65535 Hz.
*/
void analogWrite(pin_t pin, uint32_t value, uint32_t pwm_frequency)
{
// Safety check
if (!pinAvailable(pin))
{
return;
}
if (HAL_Validate_Pin_Function(pin, PF_TIMER) == PF_TIMER)
{
PinMode mode = HAL_Get_Pin_Mode(pin);
if (mode != OUTPUT && mode != AF_OUTPUT_PUSHPULL)
{
return;
}
hal_pwm_write_with_frequency_ext(pin, value, pwm_frequency);
}
}
uint8_t analogWriteResolution(pin_t pin, uint8_t value)
{
// Safety check
if (!pinAvailable(pin))
{
return 0;
}
if (HAL_Validate_Pin_Function(pin, PF_DAC) == PF_DAC)
{
HAL_DAC_Set_Resolution(pin, value);
return HAL_DAC_Get_Resolution(pin);
}
else if (HAL_Validate_Pin_Function(pin, PF_TIMER) == PF_TIMER)
{
hal_pwm_set_resolution(pin, value);
return hal_pwm_get_resolution(pin);
}
return 0;
}
uint8_t analogWriteResolution(pin_t pin)
{
// Safety check
if (!pinAvailable(pin))
{
return 0;
}
if (HAL_Validate_Pin_Function(pin, PF_DAC) == PF_DAC)
{
return HAL_DAC_Get_Resolution(pin);
}
else if (HAL_Validate_Pin_Function(pin, PF_TIMER) == PF_TIMER)
{
return hal_pwm_get_resolution(pin);
}
return 0;
}
uint32_t analogWriteMaxFrequency(pin_t pin)
{
// Safety check
if (!pinAvailable(pin))
{
return 0;
}
return hal_pwm_get_max_frequency(pin);
}
uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
uint8_t value = 0;
uint8_t i;
for (i = 0; i < 8; ++i) {
digitalWrite(clockPin, HIGH);
if (bitOrder == LSBFIRST)
value |= digitalRead(dataPin) << i;
else
value |= digitalRead(dataPin) << (7 - i);
digitalWrite(clockPin, LOW);
}
return value;
}
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
uint8_t i;
for (i = 0; i < 8; i++) {
if (bitOrder == LSBFIRST)
digitalWrite(dataPin, !!(val & (1 << i)));
else
digitalWrite(dataPin, !!(val & (1 << (7 - i))));
digitalWrite(clockPin, HIGH);
digitalWrite(clockPin, LOW);
}
}
/*
* @brief blocking call to measure a high or low pulse
* @returns uint32_t pulse width in microseconds up to 3 seconds,
* returns 0 on 3 second timeout error, or invalid pin.
*/
uint32_t pulseIn(pin_t pin, uint16_t value) {
// NO SAFETY CHECKS!!! WILD WILD WEST!!!
return HAL_Pulse_In(pin, value);
}
void setDACBufferred(pin_t pin, uint8_t state) {
HAL_DAC_Enable_Buffer(pin, state);
}
| spark/firmware | wiring_globals/src/spark_wiring_gpio.cpp | C++ | lgpl-3.0 | 8,686 |
package org.glydar.paraglydar.command.manager;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.glydar.paraglydar.command.Command;
import org.glydar.paraglydar.command.CommandExecutor;
import org.glydar.paraglydar.command.CommandOutcome;
import org.glydar.paraglydar.command.CommandSender;
import org.glydar.paraglydar.command.CommandSet;
import org.glydar.paraglydar.permissions.Permission;
public class MethodCommandExecutor implements CommandExecutor {
private final CommandSet instance;
private final Method method;
private final String usage;
private final Permission permission;
private final boolean hasRest;
private final int min;
private final int max;
public MethodCommandExecutor(CommandSet instance, Method method, Command annotation) {
this.instance = instance;
this.method = method;
this.permission = new Permission(annotation.permission(), annotation.permissionDefault());
this.usage = annotation.usage();
Class<?>[] parameterTypes = method.getParameterTypes();
this.hasRest = parameterTypes[parameterTypes.length - 1] == String[].class;
this.min = method.getParameterTypes().length - (hasRest ? 2 : 1);
if (hasRest) {
this.max = annotation.maxArgs();
}
else {
this.max = min;
}
method.setAccessible(true);
}
@Override
public String getUsage() {
return usage;
}
@Override
public Permission getPermission() {
return permission;
}
@Override
public int minArgs() {
return min;
}
@Override
public int maxArgs() {
return max;
}
@Override
public CommandOutcome execute(CommandSender sender, String[] args) {
if (!method.getParameterTypes()[0].isAssignableFrom(sender.getClass())) {
return CommandOutcome.UNSUPPORTED_SENDER;
}
CommandOutcome outcome;
try {
Object[] parameters;
if (hasRest) {
parameters = parametersWithRest(sender, args);
}
else {
parameters = parameters(sender, args);
}
outcome = (CommandOutcome) method.invoke(instance, parameters);
} catch (IllegalAccessException | IllegalArgumentException exc) {
outcome = CommandOutcome.ERROR;
System.out.println(exc);
throw new MethodCommandExecutorException(exc);
} catch (InvocationTargetException exc) {
outcome = CommandOutcome.ERROR;
System.out.println(exc);
throw new MethodCommandExecutorException(exc.getCause());
}
return outcome;
}
private Object[] parameters(CommandSender sender, String[] args) {
int parametersLength = method.getParameterTypes().length;
Object[] parameters = new Object[parametersLength];
parameters[0] = sender;
System.arraycopy(args, 0, parameters, 1, args.length);
return parameters;
}
private Object[] parametersWithRest(CommandSender sender, String[] args) {
int parametersLength = method.getParameterTypes().length;
int mandatoryArgsLength = parametersLength - 2;
int restLength = args.length - mandatoryArgsLength;
Object[] parameters = new Object[parametersLength];
String[] rest = new String[restLength];
parameters[0] = sender;
System.arraycopy(args, 0, parameters, 1, mandatoryArgsLength);
parameters[parametersLength - 1] = rest;
System.arraycopy(args, mandatoryArgsLength, rest, 0, restLength);
return parameters;
}
public static class MethodCommandExecutorException extends RuntimeException {
private static final long serialVersionUID = -3382178682196430836L;
public MethodCommandExecutorException(Throwable throwable) {
super(throwable);
}
}
}
| Glydar/Glydar.next | ParaGlydar/src/main/java/org/glydar/paraglydar/command/manager/MethodCommandExecutor.java | Java | lgpl-3.0 | 3,495 |
/*
* 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.ws;
import org.sonar.api.server.ws.WebService;
public class SystemWs implements WebService {
private final SystemWsAction[] actions;
public SystemWs(SystemWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/system");
for (SystemWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| joansmith/sonarqube | server/sonar-server/src/main/java/org/sonar/server/platform/ws/SystemWs.java | Java | lgpl-3.0 | 1,337 |
package es.ugr.osgiliath.test;
import java.util.ArrayList;
import es.ugr.osgiliath.evolutionary.basiccomponents.individuals.DoubleFitness;
import es.ugr.osgiliath.evolutionary.elements.FitnessCalculator;
import es.ugr.osgiliath.evolutionary.individual.Fitness;
import es.ugr.osgiliath.evolutionary.individual.Individual;
public class SOAPFitness implements FitnessCalculator{
FitnessCalculator fi;
public void activate(){
System.out.println("SOAP activated");
}
@Override
public DoubleFitness calculateFitness(Individual ind) {
// TODO Auto-generated method stub
System.out.println("ME LLAMAN CON SOAP");
return new DoubleFitness(new Double(39),true);
}
@Override
public ArrayList<Fitness> calculateFitnessForAll(ArrayList<Individual> inds) {
// TODO Auto-generated method stub
System.out.println("ME LLAMAN CON SOAP2");
ArrayList<Fitness> all = new ArrayList<Fitness>();
all.add(new DoubleFitness(new Double(39),true));
all.add(new DoubleFitness(new Double(39),true));
all.add(new DoubleFitness(new Double(39),true));
return all;
}
}
| fergunet/osgiliath | TestFitness/src/es/ugr/osgiliath/test/SOAPFitness.java | Java | lgpl-3.0 | 1,074 |
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package jsprit.core.algorithm.recreate;
import jsprit.core.problem.Location;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.job.Job;
import jsprit.core.problem.job.Service;
import jsprit.core.problem.job.Shipment;
import jsprit.core.problem.solution.route.VehicleRoute;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Insertion based on regret approach.
*
* <p>Basically calculates the insertion cost of the firstBest and the secondBest alternative. The score is then calculated as difference
* between secondBest and firstBest, plus additional scoring variables that can defined in this.ScoringFunction.
* The idea is that if the cost of the secondBest alternative is way higher than the first best, it seems to be important to insert this
* customer immediatedly. If difference is not that high, it might not impact solution if this customer is inserted later.
*
* @author stefan schroeder
*
*/
public class RegretInsertion extends AbstractInsertionStrategy {
static class ScoredJob {
private Job job;
private double score;
private InsertionData insertionData;
private VehicleRoute route;
private boolean newRoute;
ScoredJob(Job job, double score, InsertionData insertionData, VehicleRoute route, boolean isNewRoute) {
this.job = job;
this.score = score;
this.insertionData = insertionData;
this.route = route;
this.newRoute = isNewRoute;
}
public boolean isNewRoute() {
return newRoute;
}
public Job getJob() {
return job;
}
public double getScore() {
return score;
}
public InsertionData getInsertionData() {
return insertionData;
}
public VehicleRoute getRoute() {
return route;
}
}
static class BadJob extends ScoredJob {
BadJob(Job job) {
super(job, 0., null, null, false);
}
}
/**
* Scorer to include other impacts on score such as time-window length or distance to depot.
*
* @author schroeder
*
*/
static interface ScoringFunction {
public double score(InsertionData best, Job job);
}
/**
* Scorer that includes the length of the time-window when scoring a job. The wider the time-window, the lower the score.
*
* <p>This is the default scorer, i.e.: score = (secondBest - firstBest) + this.TimeWindowScorer.score(job)
*
* @author schroeder
*
*/
public static class DefaultScorer implements ScoringFunction {
private VehicleRoutingProblem vrp;
private double tw_param = - 0.5;
private double depotDistance_param = + 0.1;
private double minTimeWindowScore = - 100000;
public DefaultScorer(VehicleRoutingProblem vrp) {
this.vrp = vrp;
}
public void setTimeWindowParam(double tw_param){ this.tw_param = tw_param; }
public void setDepotDistanceParam(double depotDistance_param){ this.depotDistance_param = depotDistance_param; }
@Override
public double score(InsertionData best, Job job) {
double score;
if(job instanceof Service){
score = scoreService(best, job);
}
else if(job instanceof Shipment){
score = scoreShipment(best,job);
}
else throw new IllegalStateException("not supported");
return score;
}
private double scoreShipment(InsertionData best, Job job) {
Shipment shipment = (Shipment)job;
double maxDepotDistance_1 = Math.max(
getDistance(best.getSelectedVehicle().getStartLocation(),shipment.getPickupLocation()),
getDistance(best.getSelectedVehicle().getStartLocation(),shipment.getDeliveryLocation())
);
double maxDepotDistance_2 = Math.max(
getDistance(best.getSelectedVehicle().getEndLocation(),shipment.getPickupLocation()),
getDistance(best.getSelectedVehicle().getEndLocation(),shipment.getDeliveryLocation())
);
double maxDepotDistance = Math.max(maxDepotDistance_1,maxDepotDistance_2);
double minTimeToOperate = Math.min(shipment.getPickupTimeWindow().getEnd()-shipment.getPickupTimeWindow().getStart(),
shipment.getDeliveryTimeWindow().getEnd()-shipment.getDeliveryTimeWindow().getStart());
return Math.max(tw_param * minTimeToOperate,minTimeWindowScore) + depotDistance_param * maxDepotDistance;
}
private double scoreService(InsertionData best, Job job) {
double maxDepotDistance = Math.max(
getDistance(best.getSelectedVehicle().getStartLocation(), ((Service) job).getLocation()),
getDistance(best.getSelectedVehicle().getEndLocation(), ((Service) job).getLocation())
);
return Math.max(tw_param * (((Service)job).getTimeWindow().getEnd() - ((Service)job).getTimeWindow().getStart()),minTimeWindowScore) +
depotDistance_param * maxDepotDistance;
}
private double getDistance(Location loc1, Location loc2) {
return vrp.getTransportCosts().getTransportCost(loc1,loc2,0.,null,null);
}
@Override
public String toString() {
return "[name=defaultScorer][twParam="+tw_param+"][depotDistanceParam=" + depotDistance_param + "]";
}
}
private static Logger logger = LogManager.getLogger(RegretInsertion.class);
private ScoringFunction scoringFunction;
private JobInsertionCostsCalculator insertionCostsCalculator;
/**
* Sets the scoring function.
*
* <p>By default, the this.TimeWindowScorer is used.
*
* @param scoringFunction to score
*/
public void setScoringFunction(ScoringFunction scoringFunction) {
this.scoringFunction = scoringFunction;
}
public RegretInsertion(JobInsertionCostsCalculator jobInsertionCalculator, VehicleRoutingProblem vehicleRoutingProblem) {
super(vehicleRoutingProblem);
this.scoringFunction = new DefaultScorer(vehicleRoutingProblem);
this.insertionCostsCalculator = jobInsertionCalculator;
this.vrp = vehicleRoutingProblem;
logger.debug("initialise {}", this);
}
@Override
public String toString() {
return "[name=regretInsertion][additionalScorer="+scoringFunction+"]";
}
/**
* Runs insertion.
*
* <p>Before inserting a job, all unassigned jobs are scored according to its best- and secondBest-insertion plus additional scoring variables.
*
*/
@Override
public Collection<Job> insertUnassignedJobs(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) {
List<Job> badJobs = new ArrayList<Job>(unassignedJobs.size());
List<Job> jobs = new ArrayList<Job>(unassignedJobs);
while (!jobs.isEmpty()) {
List<Job> unassignedJobList = new ArrayList<Job>(jobs);
List<Job> badJobList = new ArrayList<Job>();
ScoredJob bestScoredJob = nextJob(routes, unassignedJobList, badJobList);
if(bestScoredJob != null){
if(bestScoredJob.isNewRoute()){
routes.add(bestScoredJob.getRoute());
}
insertJob(bestScoredJob.getJob(),bestScoredJob.getInsertionData(),bestScoredJob.getRoute());
jobs.remove(bestScoredJob.getJob());
}
for(Job bad : badJobList) {
jobs.remove(bad);
badJobs.add(bad);
}
}
return badJobs;
}
private ScoredJob nextJob(Collection<VehicleRoute> routes, List<Job> unassignedJobList, List<Job> badJobs) {
ScoredJob bestScoredJob = null;
for (Job unassignedJob : unassignedJobList) {
ScoredJob scoredJob = getScoredJob(routes,unassignedJob,insertionCostsCalculator,scoringFunction);
if(scoredJob instanceof BadJob){
badJobs.add(unassignedJob);
continue;
}
if(bestScoredJob == null) bestScoredJob = scoredJob;
else{
if(scoredJob.getScore() > bestScoredJob.getScore()){
bestScoredJob = scoredJob;
}
}
}
return bestScoredJob;
}
static ScoredJob getScoredJob(Collection<VehicleRoute> routes, Job unassignedJob, JobInsertionCostsCalculator insertionCostsCalculator, ScoringFunction scoringFunction) {
InsertionData best = null;
InsertionData secondBest = null;
VehicleRoute bestRoute = null;
double benchmark = Double.MAX_VALUE;
for (VehicleRoute route : routes) {
if (secondBest != null) {
benchmark = secondBest.getInsertionCost();
}
InsertionData iData = insertionCostsCalculator.getInsertionData(route, unassignedJob, NO_NEW_VEHICLE_YET, NO_NEW_DEPARTURE_TIME_YET, NO_NEW_DRIVER_YET, benchmark);
if (iData instanceof InsertionData.NoInsertionFound) continue;
if (best == null) {
best = iData;
bestRoute = route;
} else if (iData.getInsertionCost() < best.getInsertionCost()) {
secondBest = best;
best = iData;
bestRoute = route;
} else if (secondBest == null || (iData.getInsertionCost() < secondBest.getInsertionCost())) {
secondBest = iData;
}
}
VehicleRoute emptyRoute = VehicleRoute.emptyRoute();
InsertionData iData = insertionCostsCalculator.getInsertionData(emptyRoute, unassignedJob, NO_NEW_VEHICLE_YET, NO_NEW_DEPARTURE_TIME_YET, NO_NEW_DRIVER_YET, benchmark);
if (!(iData instanceof InsertionData.NoInsertionFound)) {
if (best == null) {
best = iData;
bestRoute = emptyRoute;
} else if (iData.getInsertionCost() < best.getInsertionCost()) {
secondBest = best;
best = iData;
bestRoute = emptyRoute;
} else if (secondBest == null || (iData.getInsertionCost() < secondBest.getInsertionCost())) {
secondBest = iData;
}
}
if(best == null){
return new RegretInsertion.BadJob(unassignedJob);
}
double score = score(unassignedJob, best, secondBest, scoringFunction);
ScoredJob scoredJob;
if(bestRoute == emptyRoute){
scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, true);
}
else scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, false);
return scoredJob;
}
static double score(Job unassignedJob, InsertionData best, InsertionData secondBest, ScoringFunction scoringFunction) {
if(best == null){
throw new IllegalStateException("cannot insert job " + unassignedJob.getId());
}
double score;
if(secondBest == null){ //either there is only one vehicle or there are more vehicles, but they cannot load unassignedJob
//if only one vehicle, I want the job to be inserted with min iCosts
//if there are more vehicles, I want this job to be prioritized since there are no alternatives
score = Integer.MAX_VALUE - best.getInsertionCost() + scoringFunction.score(best, unassignedJob);
}
else{
score = (secondBest.getInsertionCost()-best.getInsertionCost()) + scoringFunction.score(best, unassignedJob);
}
return score;
}
}
| KateDavis/jsprit | jsprit-core/src/main/java/jsprit/core/algorithm/recreate/RegretInsertion.java | Java | lgpl-3.0 | 12,664 |
/*
* Copyright (C) 2013 Intelligent Automation Inc.
*
* All Rights Reserved.
*/
package com.iai.proteus.views;
import gov.nasa.worldwind.geom.Sector;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IPerspectiveListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.services.ISourceProviderService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import com.iai.proteus.Activator;
import com.iai.proteus.map.MarkerSelection;
import com.iai.proteus.map.NotifyProperties;
import com.iai.proteus.map.SelectionNotifier;
import com.iai.proteus.map.SensorOfferingMarker;
import com.iai.proteus.model.map.IMapLayer;
import com.iai.proteus.model.map.WmsSavedMap;
import com.iai.proteus.model.services.Service;
import com.iai.proteus.model.services.ServiceType;
import com.iai.proteus.queryset.EventTopic;
import com.iai.proteus.queryset.FacetData;
import com.iai.proteus.queryset.QuerySetManager;
import com.iai.proteus.queryset.SosOfferingLayer;
import com.iai.proteus.queryset.SosOfferingLayerStats;
import com.iai.proteus.queryset.persist.v1.QuerySet;
import com.iai.proteus.queryset.persist.v1.QuerySetPersist;
import com.iai.proteus.ui.DiscoverPerspective;
import com.iai.proteus.ui.SwtUtil;
import com.iai.proteus.ui.UIUtil;
import com.iai.proteus.ui.queryset.QuerySetOpenState;
import com.iai.proteus.ui.queryset.QuerySetTab;
import com.iai.proteus.ui.queryset.SelectionProviderIntermediate;
import com.iai.proteus.ui.queryset.SensorOfferingItem;
/**
* Sensor discovery view
*
* @author Jakob Henriksson
*
*/
public class DiscoverView extends ViewPart
implements IPropertyChangeListener, IPerspectiveListener
{
public static final String ID = "com.iai.proteus.views.DiscoverView";
private static final Logger log = Logger.getLogger(DiscoverView.class);
// EventAdmin service for communicating with other views/modules
private EventAdmin eventAdminService;
// private static final Logger log = Logger.getLogger(DiscoverView.class);
// the tab folder object
private CTabFolder tabFolder;
// tool items
private ToolItem tbItemSensors;
private ToolItem tbItemMaps;
// selection provider intermediator
private SelectionProviderIntermediate intermediator;
static Menu chevronMenu = null;
private Image imgChart;
private Image imgMap;
private Image imgQuestion;
private QuerySetManager qm = QuerySetManager.getInstance();
/**
* Constructor
*
*/
public DiscoverView() {
intermediator = new SelectionProviderIntermediate();
// add this object as a perspective changed listener
PlatformUI.getWorkbench().getActiveWorkbenchWindow().addPerspectiveListener(this);
// images
imgChart = UIUtil.getImage("icons/fugue/chart.png");
imgMap = UIUtil.getImage("icons/fugue/map.png");
imgQuestion = UIUtil.getImage("icons/fugue/question-white.png");
// get EventAdmin service object
BundleContext ctx = Activator.getContext();
ServiceReference<EventAdmin> ref =
ctx.getServiceReference(EventAdmin.class);
eventAdminService = ctx.getService(ref);
}
/**
* Create part contents
*
*/
@Override
public void createPartControl(final Composite parent) {
// dispose listener
parent.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
if (imgChart != null)
imgChart.dispose();
if (imgMap != null)
imgMap.dispose();
if (imgQuestion != null)
imgQuestion.dispose();
}
});
final Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
// composite to hold two different toolbars
final Composite compositeToolbar = new Composite(composite, SWT.NONE);
compositeToolbar.setLayout(new GridLayout(2, false));
compositeToolbar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// add a toolbar
ToolBar toolBar = new ToolBar(compositeToolbar, SWT.FLAT | SWT.RIGHT);
toolBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
int minWidth = 0;
tbItemSensors = new ToolItem(toolBar, SWT.RADIO);
tbItemSensors.setText("Sensors");
tbItemSensors.setImage(imgChart);
tbItemSensors.setToolTipText("Discover and view sensor data");
// find minimum width
if (tbItemSensors.getWidth() > minWidth)
minWidth = tbItemSensors.getWidth();
// selected by default
tbItemSensors.setSelection(true);
tbItemMaps = new ToolItem(toolBar, SWT.RADIO);
tbItemMaps.setText("Maps");
tbItemMaps.setImage(imgMap);
tbItemMaps.setToolTipText("Find and view maps");
// default
tbItemMaps.setEnabled(true);
// find minimum width
if (tbItemMaps.getWidth() > minWidth)
minWidth = tbItemMaps.getWidth();
// add help toolbar
ToolBar toolBarHelp = new ToolBar(compositeToolbar, SWT.FLAT | SWT.RIGHT);
toolBarHelp.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
// tool bar item that shows some help information
final ToolItem tltmHelp = new ToolItem(toolBarHelp, SWT.NONE);
tltmHelp.setText("");
tltmHelp.setImage(imgQuestion);
tltmHelp.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
// create the help controller
SwtUtil.createHelpController(composite,
tltmHelp, compositeToolbar,
"Use the toolbar items 'Sensors' and 'Maps' to switch " +
"between collecting sensor offerings and maps for the Query Set.");
}
});
// // create drop down cool item to the cool bar
// CoolItem coolItem = new CoolItem(coolBar, SWT.DROP_DOWN);
// coolItem.setControl(toolBar);
//
// Point toolBarSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
// Point coolItemSize = coolItem.computeSize(toolBarSize.x, toolBarSize.y);
// coolItem.setMinimumSize(minWidth, coolItemSize.y);
// coolItem.setPreferredSize(coolItemSize);
// coolItem.setSize(coolItemSize);
// coolItem.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent event) {
// /*
// * NOTE (jhenriksson): Taken from Snippet140.java
// *
// * org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet140.java
// */
// if (event.detail == SWT.ARROW) {
// CoolItem item = (CoolItem) event.widget;
// Rectangle itemBounds = item.getBounds ();
// Point pt = coolBar.toDisplay(new Point(itemBounds.x, itemBounds.y));
// itemBounds.x = pt.x;
// itemBounds.y = pt.y;
// ToolBar bar = (ToolBar) item.getControl ();
// ToolItem[] tools = bar.getItems ();
//
// int i = 0;
// while (i < tools.length) {
// Rectangle toolBounds = tools[i].getBounds ();
// pt = bar.toDisplay(new Point(toolBounds.x, toolBounds.y));
// toolBounds.x = pt.x;
// toolBounds.y = pt.y;
//
// /* Figure out the visible portion of the tool by looking at the
// * intersection of the tool bounds with the cool item bounds. */
// Rectangle intersection = itemBounds.intersection (toolBounds);
//
// /* If the tool is not completely within the cool item bounds, then it
// * is partially hidden, and all remaining tools are completely hidden. */
// if (!intersection.equals (toolBounds)) break;
// i++;
// }
//
// /* Create a menu with items for each of the completely hidden buttons. */
// if (chevronMenu != null) chevronMenu.dispose();
// chevronMenu = new Menu (coolBar);
// for (int j = i; j < tools.length; j++) {
// MenuItem menuItem = new MenuItem (chevronMenu, SWT.PUSH);
// menuItem.setText (tools[j].getText());
// // jhenriksson: using the image as well, if it exists
// Image image = tools[j].getImage();
// if (image != null) {
// menuItem.setImage(image);
// }
// // jhenriksson: set status
// menuItem.setEnabled(tools[j].getEnabled());
// }
//
// /* Drop down the menu below the chevron, with the left edges aligned. */
// pt = coolBar.toDisplay(new Point(event.x, event.y));
// chevronMenu.setLocation (pt.x, pt.y);
// chevronMenu.setVisible (true);
// }
// }
// });
tabFolder = new CTabFolder(composite, SWT.BORDER);
tabFolder.setSimple(false);
tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
// create a new default query set
QuerySetTab querySet = createNewQuerySet();
// add to list of opened query sets
qm.addOpen(querySet.getUuid());
/*
* Add listeners
*
*/
tabFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
// listen to when tabs are closed and take appropriate action
public void close(CTabFolderEvent event) {
if (event.item instanceof QuerySetTab) {
QuerySetTab querySetTab = (QuerySetTab) event.item;
// close query set tab
closeQuerySetTab(querySetTab);
}
}
});
// listen to when we switch query sets
tabFolder.addSelectionListener(new SelectionAdapter() {
@SuppressWarnings("serial")
@Override
public void widgetSelected(SelectionEvent e) {
Widget widget = e.item;
if (widget instanceof QuerySetTab) {
final QuerySetTab querySetTab = (QuerySetTab) widget;
// clear the selection of services and maps for this
// query set
querySetTab.mapDiscoveryClearSelection();
// refresh viewers, if necessary
querySetTab.refreshViewers();
// notify that we should switch tab 'context' - send event
eventAdminService.sendEvent(new Event(EventTopic.QS_LAYERS_ACTIVATE.toString(),
new HashMap<String, Object>() {
{
put("object", querySetTab);
put("value", querySetTab.getMapLayers());
}
}));
// switch the selection provider
intermediator.setSelectionProviderDelegate(
querySetTab.getActiveSelectionProvider());
// update tool items' status
boolean sensors = querySetTab.isShowingSensorStack();
updateToolBarItems(sensors, !sensors);
}
}
});
// Handle double click events: rename query set
tabFolder.addListener(SWT.MouseDoubleClick, new Listener() {
@Override
public void handleEvent(org.eclipse.swt.widgets.Event event) {
if (event.widget instanceof CTabFolder) {
CTabItem tab = tabFolder.getSelection();
if (tab instanceof QuerySetTab) {
// rename tab
((QuerySetTab) tab).nameQuerySet();
}
}
}
});
// listener to show sensor data
tbItemSensors.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CTabItem tab = tabFolder.getSelection();
if (tab instanceof QuerySetTab) {
QuerySetTab queryTab = (QuerySetTab) tab;
queryTab.showSensorStack();
}
}
});
// listener to show map data
tbItemMaps.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CTabItem tab = tabFolder.getSelection();
if (tab instanceof QuerySetTab) {
QuerySetTab queryTab = (QuerySetTab) tab;
queryTab.showMapStack();
}
}
});
/*
* Register the selection provider intermediator as the
* selection provider
*/
getSite().setSelectionProvider(intermediator);
SelectionNotifier.getInstance().addPropertyChangeListener(this);
// get service
BundleContext ctx = Activator.getContext();
// create handler
EventHandler handler = new EventHandler() {
public void handleEvent(final Event event) {
Object obj = event.getProperty("object");
// load the given query set
if (event.getTopic().equals(EventTopic.QS_LOAD.toString())) {
if (obj instanceof QuerySet) {
final QuerySet querySet = (QuerySet) obj;
// load query set
if (parent.getDisplay().getThread() == Thread.currentThread()) {
loadQuerySet(querySet);
} else {
parent.getDisplay().syncExec(new Runnable() {
public void run() {
loadQuerySet(querySet);
}
});
}
}
}
// contribution change
else if (event.getTopic().equals(EventTopic.QS_OFFERINGS_CHANGED.toString())) {
if (obj instanceof SosOfferingLayer) {
SosOfferingLayer offeringLayer = (SosOfferingLayer) obj;
CTabItem item = tabFolder.getSelection();
if (item instanceof QuerySetTab) {
QuerySetTab querySetTab = (QuerySetTab) item;
// collect statistics
SosOfferingLayerStats stats = offeringLayer.collectStats();
Sector sector = offeringLayer.getSector();
// update geographic area
querySetTab.updateGeographicArea(sector,
stats.getCountInSector());
// update time
querySetTab.updateTime(stats.getCountTime());
// update properties
FacetData facetData = new FacetData(stats.getPropertyCount());
querySetTab.updateObservedProperties(facetData,
stats.getCountProperties());
// update formats
querySetTab.updateFormats(stats.getFormats(),
stats.getCountFormats());
// set offerings
querySetTab.updateSensorOfferings(stats.getSensorOfferingItems());
}
}
}
}
};
// register service for listening to events
Dictionary<String,String> properties = new Hashtable<String, String>();
properties.put(EventConstants.EVENT_TOPIC,
EventTopic.TOPIC_QUERYSET.toString());
ctx.registerService(EventHandler.class.getName(), handler, properties);
}
/**
* Loads and populates a query set tab from a query set model object
* read from disk
*
* @param querySet
*/
private void loadQuerySet(QuerySet querySet) {
// create the query set
QuerySetTab querySetTab = createNewQuerySet();
// populate the tab
populateQuerySetTab(querySetTab, querySet);
// add to list of opened query sets
qm.addOpen(querySet.getUuid());
// refresh viewers
querySetTab.refreshViewers();
}
/**
* Populate the given query set tab from the query set model
*
* @param querySetTab
* @param querySet
*/
private void populateQuerySetTab(QuerySetTab querySetTab, QuerySet querySet) {
// update UUID
querySetTab.setUuid(querySet.getUuid());
// not dirty yet
querySetTab.setDirty(false);
// has been saved before
querySetTab.setSaved(true);
// has been named before
querySetTab.setNamed(true);
// update title
querySetTab.setText(querySet.getTitle());
// SOS
// services
for (QuerySet.SosService sosService :
querySet.getSectionSos().getSosServices()) {
Service service = new Service(ServiceType.SOS);
service.setEndpoint(sosService.getEndpoint());
service.setName(sosService.getTitle());
// remember the active setting
service.setActive(sosService.isActive());
String color = sosService.getColor();
if (color != null) {
try {
service.setColor(Color.decode(color));
} catch (NumberFormatException e) {
log.error("Number format exception: " + e.getMessage());
}
}
querySetTab.addService(service);
}
// programmatically check the active services in the UI
querySetTab.checkActiveServices();
// ensure that checked services as displayed on the map
querySetTab.updateSelectedServices();
// bounding box
double[] bbox = querySet.getSectionSos().getBoundingBox().getAsArray();
if (bbox != null)
querySetTab.setSensorOfferingBoundingBox(bbox);
// observed properties
Collection<String> ops = new ArrayList<String>();
for (QuerySet.SosObservedProperty op :
querySet.getSectionSos().getObservedProperties()) {
// add the observed property URI
ops.add(op.getObservedProperty());
}
// set the active observed properties
querySetTab.setActiveObservedProperties(ops);
// WMS
for (QuerySet.WmsSavedMap map : querySet.getSectionWms().getMaps()) {
WmsSavedMap savedMap = new WmsSavedMap();
savedMap.setServiceEndpoint(map.getEndpoint());
savedMap.setWmsLayerTitle(map.getTitle());
savedMap.setName(map.getName());
savedMap.setNotes(map.getNotes());
// remember the active setting
savedMap.setActive(map.isActive());
querySetTab.addSavedMap(savedMap);
}
// programmatically check the active maps in the UI
querySetTab.checkActiveSavedMaps();
// ensure that checked maps are displayed on the map
querySetTab.updateSavedMaps();
}
/**
* Receives updates from map selection
*
*/
@Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(NotifyProperties.OFFERING)) {
MarkerSelection selection = (MarkerSelection)event.getNewValue();
CTabItem item = tabFolder.getSelection();
if (item instanceof QuerySetTab) {
QuerySetTab querySetTab = (QuerySetTab) item;
List<SensorOfferingMarker> markers =
selection.getSelection();
// NOTE: for now we only select one, the first one
if (markers.size() > 0) {
SensorOfferingMarker marker = markers.get(0);
SensorOfferingItem offeringItem =
new SensorOfferingItem(marker.getService(),
marker.getSensorOffering());
// invoke selection
querySetTab.selectSensorOffering(offeringItem);
}
}
}
}
/**
* Returns the current (active) Query Set (may be null)
*
* @return
*/
public QuerySetTab getCurrentQuerySet() {
CTabItem tab = tabFolder.getSelection();
if (tab != null && tab instanceof QuerySetTab) {
return (QuerySetTab) tab;
}
return null;
}
@Override
public void setFocus() {
}
/**
* Called when the perspective changes
*
* @see org.eclipse.ui.IPerspectiveListener#perspectiveActivated(org.eclipse.ui.IWorkbenchPage,
* org.eclipse.ui.IPerspectiveDescriptor)
*/
@SuppressWarnings("serial")
@Override
public void perspectiveActivated(IWorkbenchPage page,
IPerspectiveDescriptor perspective) {
CTabItem tabItem = tabFolder.getSelection();
if (!(tabItem != null && tabItem instanceof QuerySetTab))
return;
final QuerySetTab querySetTab = (QuerySetTab) tabItem;
// hide all contexts when we leave the discovery perspective
if (perspective.getId().equals(DiscoverPerspective.ID)) {
// notify that we should show layers from the active
// query set, if it exists
if (querySetTab != null) {
eventAdminService.sendEvent(new Event(EventTopic.QS_LAYERS_ACTIVATE.toString(),
new HashMap<String, Object>() {
{
put("object", querySetTab);
put("value", querySetTab.getMapLayers());
}
}));
}
} else {
// notify that we should show no layers (empty array list)
// NOTE: the event object (currentQuerySet) may be null
eventAdminService.sendEvent(new Event(EventTopic.QS_LAYERS_ACTIVATE.toString(),
new HashMap<String, Object>() {
{
put("object", querySetTab);
put("value", new ArrayList<IMapLayer>());
}
}));
}
// notify that we should switch tab 'context' - send event
}
/**
* Creates a new query set
*
*/
@SuppressWarnings("serial")
public QuerySetTab createNewQuerySet() {
// create a new tab
final QuerySetTab querySetTab =
new QuerySetTab(getSite(), intermediator, tabFolder, SWT.NONE);
// make the new tab the active one
tabFolder.setSelection(querySetTab);
// enable tool bar items
setToolBarEnabled(true);
// update the tool bar item status: sensors enabled by default
updateToolBarItems(true, false);
// notify that we should switch tab 'context'
eventAdminService.sendEvent(new Event(EventTopic.QS_LAYERS_ACTIVATE.toString(),
new HashMap<String, Object>() {
{
put("object", querySetTab);
put("value", querySetTab.getMapLayers());
}
}));
// get source provider service
ISourceProviderService sourceProviderService =
(ISourceProviderService) getSite().
getWorkbenchWindow().
getService(ISourceProviderService.class);
// get our service
QuerySetOpenState stateService =
(QuerySetOpenState) sourceProviderService
.getSourceProvider(QuerySetOpenState.STATE);
// activate change
stateService.setQuerySetOpen();
return querySetTab;
}
/**
* Closes a query set tab
*
* @param querySetTab
*/
@SuppressWarnings("serial")
public void closeQuerySetTab(final QuerySetTab querySetTab) {
String uuid = querySetTab.getUuid();
// should we save the changes before closing?
if (querySetTab.isDirty()) {
MessageDialog dialog =
UIUtil.getConfirmDialog(getSite().getShell(),
"Save query set",
"Do you want to save the changes?");
int result = dialog.open();
// return and do nothing if the user cancels the action
if (result == MessageDialog.OK) {
// provide a name
if (!querySetTab.isNamed()) {
querySetTab.nameQuerySet();
}
// persist the query set
QuerySet qs = QuerySetPersist.write(querySetTab);
// add as a stored query set
qm.addStored(uuid, qs);
}
}
// update toolbar items
if (tabFolder.getItemCount() <= 1) {
updateToolBarItems(false, false);
}
// notify that all map layers from the query set should
// be deleted - send event
eventAdminService.sendEvent(new Event(EventTopic.QS_LAYERS_DELETE.toString(),
new HashMap<String, Object>() {
{
put("object", querySetTab);
put("value", querySetTab.getMapLayers());
}
}));
// remove from list of opened query sets
qm.removeOpen(uuid);
}
/**
* Update the status of tool bar items
*
* @param sensors
* @param maps
*/
private void updateToolBarItems(boolean sensors, boolean maps) {
// update
boolean enabled = sensors || maps;
setToolBarEnabled(enabled);
// set selection
if (enabled) {
tbItemSensors.setSelection(sensors);
tbItemMaps.setSelection(maps);
} else {
tbItemSensors.setSelection(false);
tbItemMaps.setSelection(false);
}
}
/**
* Updates the enabled flag on the tool bar items
*
* @param status
*/
private void setToolBarEnabled(boolean status) {
tbItemSensors.setEnabled(status);
tbItemMaps.setEnabled(status);
}
/* (non-Javadoc)
*
* @see org.eclipse.ui.IPerspectiveListener#perspectiveChanged(org.eclipse.ui.IWorkbenchPage,
* org.eclipse.ui.IPerspectiveDescriptor, java.lang.String)
*/
@Override
public void perspectiveChanged(IWorkbenchPage page,
IPerspectiveDescriptor perspective, String changeId) {
}
}
| intelligentautomation/proteus | plugins/com.iai.proteus/src/com/iai/proteus/views/DiscoverView.java | Java | lgpl-3.0 | 23,890 |
"use strict";
var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = getLookup;
var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
/**
@name $SP().getLookup
@function
@category utils
@description Split the ID and Value
@param {String} str The string to split
@return {Object} .id returns the ID (or an array of IDs), and .value returns the value (or an array of values)
@example
$SP().getLookup("328;#Foo"); // --> {id:"328", value:"Foo"}
$SP().getLookup("328;#Foo;#191;#Other Value"); // --> {id:["328", "191"], value:["Foo", "Other Value"]}
$SP().getLookup("328"); // --> {id:"328", value:"328"}
*/
function getLookup(str) {
if (!str) return {
id: "",
value: ""
};
var a = str.split(";#");
if (a.length <= 2) return {
id: a[0],
value: typeof a[1] === "undefined" ? a[0] : a[1]
};else {
var _context;
// we have several lookups
return {
id: (0, _slice.default)(_context = str.replace(/([0-9]+;#)([^;]+)/g, "$1").replace(/;#;#/g, ",")).call(_context, 0, -2).split(","),
value: str.replace(/([0-9]+;#)([^;]+)/g, "$2").split(";#")
};
}
}
module.exports = exports.default; | Aymkdn/SharepointPlus | dist/utils/getLookup.js | JavaScript | lgpl-3.0 | 1,429 |
/*
* BusyDlg.java
* Created on 14. Mai 2007, 09:33
*
* This file is part of JAMS
* Copyright (C) 2006 FSU Jena
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
package jams.gui;
import java.awt.BorderLayout;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JLabel;
/**
*
* @author S. Kralisch
*/
public class ObserverWorkerDlg extends WorkerDlgDecorator implements Observer{
JLabel progressBarLabel = new JLabel();
public ObserverWorkerDlg(WorkerDlg parent) {
super(parent);
getWorkerDlg().progressBar.setLayout(new BorderLayout(5, 5));
getWorkerDlg().progressBar.add(progressBarLabel, BorderLayout.CENTER);
//progressBarLabel.setStringPainted(true);
getWorkerDlg().pack();
}
@Override
public void update(Observable observable, Object o){
//getWorkerDlg().progressBarLabel.setStringPainted(true);
progressBarLabel.setText(o.toString());
}
static private class XXX extends Observable{
public void change(){
setChanged();
}
}
public static void main(String[] args) {
ObserverWorkerDlg dlg = new ObserverWorkerDlg(new CancelableWorkerDlg(new WorkerDlg(null, "test", "test")).getWorkerDlg());
final XXX o = new XXX();
o.addObserver(dlg);
dlg.getWorkerDlg().setTask(new Runnable() {
@Override
public void run(){
try{
long i=0;
while(i>=0){
o.change();
o.notifyObservers(i++);
}
}catch(Throwable t){
t.printStackTrace();
}
}
});
dlg.getWorkerDlg().execute();
}
}
| kralisch/jams | JAMScommon/src/jams/gui/ObserverWorkerDlg.java | Java | lgpl-3.0 | 2,590 |
/*
* Copyright (C) 2015-2016 Didier Villevalois.
*
* This file is part of JLaTo.
*
* JLaTo 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.
*
* JLaTo 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 JLaTo. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlato.internal.shapes;
import org.jlato.internal.bu.BUTree;
import org.jlato.internal.bu.WRunRun;
import org.jlato.internal.bu.WTokenRun;
/**
* @author Didier Villevalois
*/
public class LSDecorated extends LexicalShape {
protected final LexicalShape shape;
public LSDecorated(LexicalShape shape) {
this.shape = shape;
}
@Override
public boolean isDefined(BUTree tree) {
return shape.isDefined(tree);
}
@Override
public void dress(DressingBuilder<?> builder, BUTree<?> discriminator) {
shape.dress(builder, discriminator);
}
@Override
public boolean acceptsTrailingWhitespace() {
return shape.acceptsTrailingWhitespace();
}
@Override
public boolean acceptsLeadingWhitespace() {
return shape.acceptsLeadingWhitespace();
}
@Override
public void dressTrailing(WTokenRun tokens, DressingBuilder<?> builder) {
shape.dressTrailing(tokens, builder);
}
@Override
public void dressLeading(WTokenRun tokens, DressingBuilder<?> builder) {
shape.dressLeading(tokens, builder);
}
@Override
public void render(BUTree tree, WRunRun run, Print print) {
shape.render(tree, run, print);
}
}
| ptitjes/jlato | src/main/java/org/jlato/internal/shapes/LSDecorated.java | Java | lgpl-3.0 | 1,876 |
/**
* \file mifareultralightcacscommands.hpp
* \author Maxime C. <maxime-dev@islog.com>
* \brief Mifare Ultralight C - SpringCard.
*/
#ifndef LOGICALACCESS_MIFAREULTRALIGHTCSPRINGCARDCOMMANDS_HPP
#define LOGICALACCESS_MIFAREULTRALIGHTCSPRINGCARDCOMMANDS_HPP
#include <logicalaccess/plugins/readers/pcsc/commands/mifareultralightcpcsccommands.hpp>
namespace logicalaccess
{
#define CMD_MIFAREULTRALIGHTCSPRINGCARD "MifareUltralightCSpringCard"
/**
* \brief The Mifare Ultralight C commands class for SpringCard reader.
*/
class LLA_READERS_PCSC_API MifareUltralightCSpringCardCommands
: public MifareUltralightCPCSCCommands
{
public:
/**
* \brief Constructor.
*/
MifareUltralightCSpringCardCommands();
explicit MifareUltralightCSpringCardCommands(std::string ct);
/**
* \brief Destructor.
*/
virtual ~MifareUltralightCSpringCardCommands();
protected:
void startGenericSession() override;
void stopGenericSession() override;
ISO7816Response sendGenericCommand(const ByteVector &data) override;
};
}
#endif /* LOGICALACCESS_MIFAREULTRALIGHTCSPRINGCARDCOMMANDS_HPP */ | islog/liblogicalaccess | plugins/logicalaccess/plugins/readers/pcsc/commands/mifareultralightcspringcardcommands.hpp | C++ | lgpl-3.0 | 1,139 |
/*
* JAMSDouble.java
* Created on 28. September 2005, 16:06
*
* This file is part of JAMS
* Copyright (C) 2005 FSU Jena
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
package jams.data;
import jams.JAMS;
import java.util.Locale;
/**
*
* @author S. Kralisch
*/
public class JAMSDouble implements Attribute.Double {
private double value;
/**
* Creates a new instance of JAMSDouble
*/
JAMSDouble() {
}
JAMSDouble(double value) {
this.value = (double)value;
}
/*
public JAMSDouble(double value, double minValue, double maxValue, String unitString) {
this.setValue(value);
this.setUnit(unitString);
this.setRange(minValue, maxValue);
}
*/
public String toString() {
// return Double.toString(value);
return String.format(Locale.ENGLISH, JAMS.getFloatFormat(), value);
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = (double)value;
}
public void setValue(String value) {
this.value = (double)Double.parseDouble(value);
}
public boolean equals(Object other) {
if ((other == null) || !(other instanceof JAMSDouble)) {
return false;
}
return value == ((JAMSDouble) other).getValue();
} // end equals()
}
| kralisch/jams | JAMSmain/src/jams/data/JAMSDouble.java | Java | lgpl-3.0 | 1,988 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# coding=utf-8
import sunburnt
from anta.util import config
# solr $ANTA_HOME/solr-conf
config_solr = config.config["solr"]
class SOLRInterface():
si = sunburnt.SolrInterface(config_solr['endpoint'])
def initialize(self):
"""Initialize schema"""
self.si.init_schema()
def delete_all(self):
"""Delete all documents"""
self.si.delete_all()
self.si.commit()
def add_documents(self, documents):
"""Add some documents"""
self.si.add(documents)
self.si.commit()
def add_document(self, document):
"""Add a document"""
self.si.add(document)
def commit(self):
self.si.commit()
def delete_document(self, document):
"""Delete a document"""
pass
| medialab/ANTA2 | anta/storage/solr_client.py | Python | lgpl-3.0 | 826 |
#include <iostream>
#include "DGtal/base/Common.h"
#include "DGtal/images/imagesSetsUtils/SetFromImage.h"
#include "DGtal/images/ImageSelector.h"
#include "DGtal/helpers/StdDefs.h"
#include "DGtal/io/Display3D.h"
#include "DGtal/io/readers/VolReader.h"
#include "DGtal/io/colormaps/GradientColorMap.h"
#include "DGtal/io/Color.h"
#include "DGtal/topology/KhalimskySpaceND.h"
#include "DGtal/topology/helpers/Surfaces.h"
#include "ImaGene/Arguments.h"
using namespace std;
using namespace DGtal;
using namespace Z3i;
static ImaGene::Arguments args;
int main( int argc, char** argv )
{
args.addOption("-image", "-image <filename> ", "aFile.vol ");
args.addOption("-output", "-output <filename> the output filename with .off extension", "output.off");
args.addOption("-exportSRC", "-exportSRC <filename> export the source set of voxels", "src.off");
args.addOption("-threshold", "-threshold <min> <max> (default: min = 128, max 255 ", "128", "255");
args.addOption( "-badj", "-badj <0/1>: 0 is interior bel adjacency, 1 is exterior (def. is 0).", "0" );
if ( ( argc <= 1 ) || ! args.readArguments( argc, argv ) )
{
cerr << args.usage( "extract3D: ",
"Extracts all 3D connected components from a .vol 3D image and generate a resulting 3D mesh on .OFF format. \nTypical use: \n extract3D -threshold 200 -image image.pgm > imageContour.fc ",
"" )
<< endl;
return 1;
}
string imageFileName = args.getOption("-image")->getValue(0);
string outputFileName = args.getOption("-output")->getValue(0);
string srcFileName = args.getOption("-exportSRC")->getValue(0);
int minThreshold = args.getOption("-threshold")->getIntValue(0);
int maxThreshold = args.getOption("-threshold")->getIntValue(1);
bool badj = (args.getOption("-badj")->getIntValue(0))!=1;
typedef ImageSelector < Domain, int>::Type Image;
typedef IntervalThresholder<Image::Value> Binarizer;
Image image = VolReader<Image>::importVol(imageFileName);
Binarizer b(minThreshold, maxThreshold);
PointFunctorPredicate<Image,Binarizer> predicate(image, b);
//A KhalimskySpace is constructed from the domain boundary points.
Point pUpper = image.domain().upperBound();
Point pLower = image.domain().lowerBound();
KSpace K;
K.init(pLower, pUpper, true);
SurfelAdjacency<3> sAdj( badj );
vector<vector<SCell> > vectConnectedSCell;
Surfaces<KSpace>::extractAllConnectedSCell(vectConnectedSCell,K, sAdj, predicate, false);
Display3D exportSurfel;
// Each connected compoments are simply displayed with a specific color.
GradientColorMap<long> gradient(0, (const long)vectConnectedSCell.size());
gradient.addColor(Color::Red);
gradient.addColor(Color::Yellow);
gradient.addColor(Color::Green);
gradient.addColor(Color::Cyan);
gradient.addColor(Color::Blue);
gradient.addColor(Color::Magenta);
gradient.addColor(Color::Red);
// Processing ViewerInt
for(int i=0; i< vectConnectedSCell.size();i++){
DGtal::Color col= gradient(i);
exportSurfel << CustomColors3D(Color(250, 0,0), Color(col.red(),
col.green(),
col.blue()));
for(int j=0; j< vectConnectedSCell.at(i).size();j++){
exportSurfel << vectConnectedSCell.at(i).at(j);
}
}
Z3i::DigitalSet imageSet(image.domain());
SetFromImage<Z3i::DigitalSet>::append<Image>(imageSet, image, minThreshold, maxThreshold);
exportSurfel << CustomColors3D(Color(250, 0,0),Color(250, 200,200, 200));
exportSurfel << imageSet;
exportSurfel >> outputFileName;
if(args.check("-exportSRC")){
Display3D exportSRC;
exportSRC << imageSet;
exportSRC >> srcFileName;
}
}
| kerautret/DGtal-forIPOL | demoIPOL/extract3D.cpp | C++ | lgpl-3.0 | 3,694 |
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>proj</title>
<script src="js/main.js" type="text/javascript"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php echo $this->load('menu') ?>
<div class="container theme-showcase" role="main">
<div class="page-header">
</div>
<?php echo $this->load('main') ?>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</body>
</html>
| totobill/CadosProject | data/genere/proj/layout/bootstrap.php | PHP | lgpl-3.0 | 1,344 |
package user_preferences;
/**
* Model a catalogue preference ( record of the table Preference of the catalogue db )
* @author avonva
*
*/
public class CataloguePreference extends Preference {
// default static keys for preferences
public final static String currentPicklistKey = "favouritePicklist";
public final static String maxRecentTerms = "maxRecentTerms";
public final static String minSearchChar = "minSearchChar";
public final static String copyImplicitFacets = "copyImplicitFacets";
public final static String enableBusinessRules = "enableBusinessRules";
// last graphical objects which were opened
public final static String LAST_TERM_PREF = "lastTermId";
public final static String LAST_HIER_PREF = "lastHierarchyId";
/**
* Constructor with key, value. The value variable is always converted to string
* in order to be saved.
* @param key
* @param value
*/
public CataloguePreference( String key, PreferenceType type,
Object value, boolean editable ) {
super( key, type, value, editable );
}
public CataloguePreference ( Preference p ) {
super ( p.getKey(), p.getType(), p.getValue(), p.isEditable() );
}
}
| openefsa/CatalogueBrowser | src/user_preferences/CataloguePreference.java | Java | lgpl-3.0 | 1,162 |
/*
* This file is part or JMathLib
*
* Check it out at http://www.jmathlib.de
*
* Author: stefan@held-mueller.de and others
* (c) 2008-2009
*/
package jmathlib.core.graphics;
/** A fairly conventional 3D matrix object that can transform sets of
3D points and perform a variety of manipulations on the transform */
public class Matrix3D {
double xx, xy, xz, xo;
double yx, yy, yz, yo;
double zx, zy, zz, zo;
static final double pi = 3.14159265;
double[][] matrix = new double[3][4];
double[][] unitMatrix = {{1.0, 0.0, 0.0, 0.0},{0.0, 1.0, 0.0, 0.0},{0.0, 0.0, 1.0, 0.0}};
/** Create a new unit matrix */
public Matrix3D()
{
xx = 1.0f;
yy = 1.0f;
zz = 1.0f;
matrix = unitMatrix;
}
/** Scale by f in all dimensions */
public void scale(double f)
{
//xx *= f; xy *= f; xz *= f; xo *= f;
//yx *= f; yy *= f; yz *= f; yo *= f;
//zx *= f; zy *= f; zz *= f; zo *= f;
scale(f, f, f);
}
/** Scale along each axis independently */
public void scale(double xf, double yf, double zf)
{
xx *= xf; xy *= xf; xz *= xf; xo *= xf;
yx *= yf; yy *= yf; yz *= yf; yo *= yf;
zx *= zf; zy *= zf; zz *= zf; zo *= zf;
for (int i=0; i<4; i++)
{
matrix[0][i] *= xf;
matrix[1][i] *= yf;
matrix[2][i] *= zf;
}
}
/** Translate the origin */
public void translate(double x, double y, double z)
{
xo += x;
yo += y;
zo += z;
}
/** rotate theta degrees about the y axis */
public void yrot(double theta)
{
theta *= (pi / 180);
double ct = Math.cos(theta);
double st = Math.sin(theta);
double Nxx = (double) (xx * ct + zx * st);
double Nxy = (double) (xy * ct + zy * st);
double Nxz = (double) (xz * ct + zz * st);
double Nxo = (double) (xo * ct + zo * st);
double Nzx = (double) (zx * ct - xx * st);
double Nzy = (double) (zy * ct - xy * st);
double Nzz = (double) (zz * ct - xz * st);
double Nzo = (double) (zo * ct - xo * st);
xo = Nxo;
xx = Nxx;
xy = Nxy;
xz = Nxz;
zo = Nzo;
zx = Nzx;
zy = Nzy;
zz = Nzz;
}
/** rotate theta degrees about the x axis */
public void xrot(double theta) {
theta *= (pi / 180);
double ct = Math.cos(theta);
double st = Math.sin(theta);
double Nyx = (double) (yx * ct + zx * st);
double Nyy = (double) (yy * ct + zy * st);
double Nyz = (double) (yz * ct + zz * st);
double Nyo = (double) (yo * ct + zo * st);
double Nzx = (double) (zx * ct - yx * st);
double Nzy = (double) (zy * ct - yy * st);
double Nzz = (double) (zz * ct - yz * st);
double Nzo = (double) (zo * ct - yo * st);
yo = Nyo;
yx = Nyx;
yy = Nyy;
yz = Nyz;
zo = Nzo;
zx = Nzx;
zy = Nzy;
zz = Nzz;
}
/** rotate theta degrees about the z axis */
public void zrot(double theta) {
theta *= (pi / 180);
double ct = Math.cos(theta);
double st = Math.sin(theta);
double Nyx = (double) (yx * ct + xx * st);
double Nyy = (double) (yy * ct + xy * st);
double Nyz = (double) (yz * ct + xz * st);
double Nyo = (double) (yo * ct + xo * st);
double Nxx = (double) (xx * ct - yx * st);
double Nxy = (double) (xy * ct - yy * st);
double Nxz = (double) (xz * ct - yz * st);
double Nxo = (double) (xo * ct - yo * st);
yo = Nyo;
yx = Nyx;
yy = Nyy;
yz = Nyz;
xo = Nxo;
xx = Nxx;
xy = Nxy;
xz = Nxz;
}
/** Multiply this matrix by a second: M = M*R */
public void mult(Matrix3D rhs) {
double lxx = xx * rhs.xx + yx * rhs.xy + zx * rhs.xz;
double lxy = xy * rhs.xx + yy * rhs.xy + zy * rhs.xz;
double lxz = xz * rhs.xx + yz * rhs.xy + zz * rhs.xz;
double lxo = xo * rhs.xx + yo * rhs.xy + zo * rhs.xz + rhs.xo;
double lyx = xx * rhs.yx + yx * rhs.yy + zx * rhs.yz;
double lyy = xy * rhs.yx + yy * rhs.yy + zy * rhs.yz;
double lyz = xz * rhs.yx + yz * rhs.yy + zz * rhs.yz;
double lyo = xo * rhs.yx + yo * rhs.yy + zo * rhs.yz + rhs.yo;
double lzx = xx * rhs.zx + yx * rhs.zy + zx * rhs.zz;
double lzy = xy * rhs.zx + yy * rhs.zy + zy * rhs.zz;
double lzz = xz * rhs.zx + yz * rhs.zy + zz * rhs.zz;
double lzo = xo * rhs.zx + yo * rhs.zy + zo * rhs.zz + rhs.zo;
xx = lxx;
xy = lxy;
xz = lxz;
xo = lxo;
yx = lyx;
yy = lyy;
yz = lyz;
yo = lyo;
zx = lzx;
zy = lzy;
zz = lzz;
zo = lzo;
}
/** Reinitialize to the unit matrix */
public void unit()
{
xx = 1; xy = 0; xz = 0; xo = 0;
yx = 0; yy = 1; yz = 0; yo = 0;
zx = 0; zy = 0; zz = 1; zo = 0;
}
/** Transform nvert points from v into tv. v contains the input
coordinates in floating point. Three successive entries in
the array constitute a point. tv ends up holding the transformed
points as integers; three successive entries per point */
public void transform(double x[], double y[], double z[],
int tx[], int ty[], int tz[])
{
for (int i=0; i<x.length; i++)
{
tx[i] = (int) (x[i] * xx + y[i] * xy + z[i] * xz + xo);
ty[i] = (int) (x[i] * yx + y[i] * yy + z[i] * yz + yo);
tz[i] = (int) (x[i] * zx + y[i] * zy + z[i] * zz + zo);
}
}
/** Transform nvert points from v into tv. v contains the input
coordinates in floating point. Three successive entries in
the array constitute a point. tv ends up holding the transformed
points as integers; three successive entries per point */
public void transform(double x[][], double y[][], double z[][],
int tx[][], int ty[][], int tz[][])
{
for (int i=0; i<x.length; i++)
{
for (int j=0; j<x[0].length; j++)
{
tx[i][j] = (int) (x[i][j] * xx + y[i][j] * xy + z[i][j] * xz + xo);
ty[i][j] = (int) (x[i][j] * yx + y[i][j] * yy + z[i][j] * yz + yo);
tz[i][j] = (int) (x[i][j] * zx + y[i][j] * zy + z[i][j] * zz + zo);
}
}
}
public java.awt.Point transform(double x, double y, double z)
{
return new java.awt.Point(
(int) (x * xx + y * xy + z * xz + xo),
(int) (x * yx + y * yy + z * yz + yo)
);
}
}
| nightscape/JMathLib | src/jmathlib/core/graphics/Matrix3D.java | Java | lgpl-3.0 | 6,366 |
import unittest
from Tribler.community.market.core.message import TraderId, MessageNumber, MessageId
from Tribler.community.market.core.order import OrderId, OrderNumber
from Tribler.community.market.core.price import Price
from Tribler.community.market.core.quantity import Quantity
from Tribler.community.market.core.side import Side
from Tribler.community.market.core.tick import Tick
from Tribler.community.market.core.timeout import Timeout
from Tribler.community.market.core.timestamp import Timestamp
class SideTestSuite(unittest.TestCase):
"""Side test cases."""
def setUp(self):
# Object creation
self.tick = Tick(MessageId(TraderId('0'), MessageNumber('message_number')),
OrderId(TraderId('0'), OrderNumber(1)), Price(400, 'BTC'), Quantity(30, 'MC'),
Timeout(float("inf")), Timestamp(float("inf")), True)
self.tick2 = Tick(MessageId(TraderId('1'), MessageNumber('message_number')),
OrderId(TraderId('1'), OrderNumber(2)), Price(800, 'BTC'), Quantity(30, 'MC'),
Timeout(float("inf")), Timestamp(float("inf")), True)
self.side = Side()
def test_max_price(self):
# Test max price (list)
self.assertEquals(None, self.side.get_max_price('BTC', 'MC'))
self.assertEquals(None, self.side.get_max_price_list('BTC', 'MC'))
self.side.insert_tick(self.tick)
self.side.insert_tick(self.tick2)
self.assertEquals('30.000000 MC\t@\t800.000000 BTC\n', str(self.side.get_max_price_list('BTC', 'MC')))
self.assertEquals(Price(800, 'BTC'), self.side.get_max_price('BTC', 'MC'))
def test_min_price(self):
# Test min price (list)
self.assertEquals(None, self.side.get_min_price_list('BTC', 'MC'))
self.assertEquals(None, self.side.get_min_price('BTC', 'MC'))
self.side.insert_tick(self.tick)
self.side.insert_tick(self.tick2)
self.assertEquals('30.000000 MC\t@\t400.000000 BTC\n', str(self.side.get_min_price_list('BTC', 'MC')))
self.assertEquals(Price(400, 'BTC'), self.side.get_min_price('BTC', 'MC'))
def test_insert_tick(self):
# Test insert tick
self.assertEquals(0, len(self.side))
self.assertFalse(self.side.tick_exists(OrderId(TraderId('0'), OrderNumber(1))))
self.side.insert_tick(self.tick)
self.side.insert_tick(self.tick2)
self.assertEquals(2, len(self.side))
self.assertTrue(self.side.tick_exists(OrderId(TraderId('0'), OrderNumber(1))))
def test_remove_tick(self):
# Test remove tick
self.side.insert_tick(self.tick)
self.side.insert_tick(self.tick2)
self.side.remove_tick(OrderId(TraderId('0'), OrderNumber(1)))
self.assertEquals(1, len(self.side))
self.side.remove_tick(OrderId(TraderId('1'), OrderNumber(2)))
self.assertEquals(0, len(self.side))
def test_get_price_level_list_wallets(self):
"""
Test the price level lists of wallets of a side
"""
self.assertFalse(self.side.get_price_level_list_wallets())
self.side.insert_tick(self.tick)
self.assertTrue(self.side.get_price_level_list_wallets())
def test_get_list_representation(self):
"""
Testing the list representation of a side
"""
self.assertFalse(self.side.get_list_representation())
self.side.insert_tick(self.tick)
list_rep = self.side.get_list_representation()
self.assertTrue(list_rep)
| vandenheuvel/tribler | Tribler/Test/Community/Market/test_side.py | Python | lgpl-3.0 | 3,565 |
module.exports = function(grunt) {
var version = grunt.option('release');
if (process.env.SELENIUM_BROWSER_CAPABILITIES != undefined) {
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
}
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify: {
openpgp: {
files: {
'dist/openpgp.js': [ './src/index.js' ]
},
options: {
browserifyOptions: {
standalone: 'openpgp',
external: [ 'crypto', 'node-localstorage' ]
}
}
},
openpgp_debug: {
files: {
'dist/openpgp_debug.js': [ './src/index.js' ]
},
options: {
browserifyOptions: {
debug: true,
standalone: 'openpgp',
external: [ 'crypto', 'node-localstorage' ]
}
}
},
worker: {
files: {
'dist/openpgp.worker.js': [ './src/worker/worker.js' ]
}
},
worker_min: {
files: {
'dist/openpgp.worker.min.js': [ './src/worker/worker.js' ]
}
},
unittests: {
files: {
'test/openpgp.js': [ './test/src/index.js' ],
'test/lib/unittests-bundle.js': [ './test/unittests.js' ]
},
options: {
browserifyOptions: {
external: [ 'openpgp', 'crypto', 'node-localstorage']
}
}
}
},
replace: {
openpgp: {
src: ['dist/openpgp.js'],
dest: ['dist/openpgp.js'],
replacements: [{
from: /OpenPGP.js VERSION/g,
to: 'OpenPGP.js v<%= pkg.version %>'
}]
},
openpgp_debug: {
src: ['dist/openpgp_debug.js'],
dest: ['dist/openpgp_debug.js'],
replacements: [{
from: /OpenPGP.js VERSION/g,
to: 'OpenPGP.js v<%= pkg.version %>'
}]
},
worker_min: {
src: ['dist/openpgp.worker.min.js'],
dest: ['dist/openpgp.worker.min.js'],
replacements: [{
from: "importScripts('openpgp.js')",
to: "importScripts('openpgp.min.js')"
}]
}
},
uglify: {
openpgp: {
files: {
'dist/openpgp.min.js' : [ 'dist/openpgp.js' ],
'dist/openpgp.worker.min.js' : [ 'dist/openpgp.worker.min.js' ]
}
},
options: {
banner: '/*! OpenPGPjs.org this is LGPL licensed code, see LICENSE/our website for more information.- v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */'
}
},
jsbeautifier: {
files: ['src/**/*.js'],
options: {
indent_size: 2,
preserve_newlines: true,
keep_array_indentation: false,
keep_function_indentation: false,
wrap_line_length: 120
}
},
jshint: {
all: ['src/**/*.js']
},
jsdoc: {
dist: {
src: ['README.md', 'src'],
options: {
destination: 'doc',
recurse: true,
template: 'jsdoc.template'
}
}
},
mocha_istanbul: {
coverage: {
src: 'test',
options: {
root: 'node_modules/openpgp',
timeout: 240000,
}
},
coveralls: {
src: ['test'],
options: {
root: 'node_modules/openpgp',
timeout: 240000,
coverage: true,
reportFormats: ['cobertura','lcovonly']
}
}
},
mochaTest: {
unittests: {
options: {
reporter: 'spec',
timeout: 120000
},
src: [ 'test/unittests.js' ]
}
},
copy: {
npm: {
expand: true,
flatten: true,
cwd: 'node_modules/',
src: ['mocha/mocha.css', 'mocha/mocha.js', 'chai/chai.js', 'whatwg-fetch/fetch.js'],
dest: 'test/lib/'
},
unittests: {
expand: true,
flatten: false,
cwd: './',
src: ['src/**'],
dest: 'test/'
},
zlib: {
expand: true,
cwd: 'node_modules/zlibjs/bin/',
src: ['rawdeflate.min.js','rawinflate.min.js','zlib.min.js'],
dest: 'src/compression/'
}
},
clean: ['dist/'],
connect: {
dev: {
options: {
port: 3000,
base: '.'
}
}
},
'saucelabs-mocha': {
all: {
options: {
username: 'openpgpjs',
key: '60ffb656-2346-4b77-81f3-bc435ff4c103',
urls: ['http://127.0.0.1:3000/test/unittests.html'],
build: process.env.TRAVIS_BUILD_ID,
testname: 'Sauce Unit Test for openpgpjs',
browsers: [browser_capabilities],
public: "public",
maxRetries: 3,
throttled: 2,
pollInterval: 4000,
statusCheckAttempts: 200
}
},
}
});
// Load the plugin(s)
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jsdoc');
grunt.loadNpmTasks('grunt-mocha-istanbul');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-saucelabs');
grunt.registerTask('set_version', function() {
if (!version) {
throw new Error('You must specify the version: "--release=1.0.0"');
}
patchFile({
fileName: 'package.json',
version: version
});
patchFile({
fileName: 'bower.json',
version: version
});
});
function patchFile(options) {
var fs = require('fs'),
path = './' + options.fileName,
file = require(path);
if (options.version) {
file.version = options.version;
}
fs.writeFileSync(path, JSON.stringify(file, null, 2));
}
grunt.registerTask('default', 'Build OpenPGP.js', function() {
grunt.task.run(['clean', 'copy:zlib', 'browserify', 'replace', 'uglify', 'npm_pack']);
//TODO jshint is not run because of too many discovered issues, once these are addressed it should autorun
grunt.log.ok('Before Submitting a Pull Request please also run `grunt jshint`.');
});
grunt.registerTask('documentation', ['jsdoc']);
// Alias the `npm_pack` task to run `npm pack`
grunt.registerTask('npm_pack', 'npm pack', function () {
var done = this.async();
var npm = require('child_process').exec('npm pack ../', { cwd: 'dist'}, function (err, stdout) {
var package = stdout;
if (err === null) {
var install = require('child_process').exec('npm install dist/' + package, function (err) {
done(err);
});
install.stdout.pipe(process.stdout);
install.stderr.pipe(process.stderr);
} else {
done(err);
}
});
npm.stdout.pipe(process.stdout);
npm.stderr.pipe(process.stderr);
});
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(err){
if (err) {
return done(err);
}
done();
});
});
// Test/Dev tasks
grunt.registerTask('test', ['copy:npm', 'copy:unittests', 'mochaTest']);
grunt.registerTask('coverage', ['default', 'copy:npm', 'copy:unittests', 'mocha_istanbul:coverage']);
grunt.registerTask('coveralls', ['default', 'copy:npm', 'copy:unittests', 'mocha_istanbul:coveralls']);
grunt.registerTask('saucelabs', ['default', 'copy:npm', 'copy:unittests', 'connect', 'saucelabs-mocha']);
};
| vSaKv/openpgpjs | Gruntfile.js | JavaScript | lgpl-3.0 | 7,704 |
/*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.crosstabs.base;
import java.io.IOException;
import java.io.ObjectInputStream;
import net.sf.jasperreports.crosstabs.JRCellContents;
import net.sf.jasperreports.crosstabs.JRCrosstabColumnGroup;
import net.sf.jasperreports.crosstabs.type.CrosstabColumnPositionEnum;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.engine.base.JRBaseObjectFactory;
import net.sf.jasperreports.engine.util.JRCloneUtils;
/**
* Base read-only implementation of crosstab column groups.
*
* @author Lucian Chirita (lucianc@users.sourceforge.net)
* @version $Id: JRBaseCrosstabColumnGroup.java 5960 2013-03-07 14:54:18Z lucianc $
*/
public class JRBaseCrosstabColumnGroup extends JRBaseCrosstabGroup implements JRCrosstabColumnGroup
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
protected int height;
protected CrosstabColumnPositionEnum positionValue = CrosstabColumnPositionEnum.LEFT;
protected JRCellContents crosstabHeader;
public JRBaseCrosstabColumnGroup(JRCrosstabColumnGroup group, JRBaseObjectFactory factory)
{
super(group, factory);
height = group.getHeight();
positionValue = group.getPositionValue();
crosstabHeader = factory.getCell(group.getCrosstabHeader());
}
public CrosstabColumnPositionEnum getPositionValue()
{
return positionValue;
}
public int getHeight()
{
return height;
}
@Override
public JRCellContents getCrosstabHeader()
{
return crosstabHeader;
}
@Override
public Object clone()
{
JRBaseCrosstabColumnGroup clone = (JRBaseCrosstabColumnGroup) super.clone();
clone.crosstabHeader = JRCloneUtils.nullSafeClone(crosstabHeader);
return clone;
}
/*
* These fields are only for serialization backward compatibility.
*/
private int PSEUDO_SERIAL_VERSION_UID = JRConstants.PSEUDO_SERIAL_VERSION_UID; //NOPMD
/**
* @deprecated
*/
private byte position;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (PSEUDO_SERIAL_VERSION_UID < JRConstants.PSEUDO_SERIAL_VERSION_UID_3_7_2)
{
positionValue = CrosstabColumnPositionEnum.getByValue(position);
}
}
}
| sikachu/jasperreports | src/net/sf/jasperreports/crosstabs/base/JRBaseCrosstabColumnGroup.java | Java | lgpl-3.0 | 3,189 |
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: '/'
}).listen(3000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:3000/');
});
| devsli/browser-webpack-brotli-error | devserver.js | JavaScript | unlicense | 348 |
/*===============================================================+
| 0-ZeT Library for Nashorn-JsX [ 1.0 ] |
| Asserts & Errors |
| / anton.baukin@gmail.com / |
+===============================================================*/
var ZeT = JsX.once('./checks.js')
ZeT.extend(ZeT,
{
/**
* Returns exception concatenating the optional
* arguments into string message. The stack is
* appended as string after the new line.
*/
ass : function(/* messages */)
{
var m = ZeT.cati(0, arguments)
var x = ZeT.stack()
//?: {has message}
if(!ZeT.ises(m)) x = m.concat('\n', x)
//!: return error to throw later
return new Error(x)
},
/**
* First argument of assertion tested with ZeT.test().
* The following optional arguments are the message
* components concatenated to string.
*
* The function returns the test argument.
*/
assert : function(test /* messages */)
{
if(ZeT.test(test)) return test
var m = ZeT.cati(1, arguments)
if(ZeT.ises(m)) m = 'Assertion failed!'
throw ZeT.ass(m)
},
/**
* Checks that given object is not null, or undefined.
*/
assertn : function(obj /* messages */)
{
if(!ZeT.isx(obj)) return obj
var m = ZeT.cati(1, arguments)
if(ZeT.ises(m)) m = 'The object is undefined or null!'
throw ZeT.ass(m)
},
/**
* Tests the the given object is a function
* and returns it back.
*/
assertf : function(f /* messages */)
{
if(ZeT.isf(f)) return f
var m = ZeTS.cati(1, arguments)
if(ZeT.ises(m)) m = 'A function is required!'
throw ZeT.ass(m)
},
/**
* Tests that the first argument is a string
* that is not whitespace-empty. Returns it.
*/
asserts : function(str /* messages */)
{
if(!ZeT.ises(str)) return str
var m = ZeT.cati(1, arguments)
if(ZeT.ises(m)) m = 'Not a whitespace-empty string is required!'
throw ZeT.ass(m)
},
/**
* Tests the the given object is a not-empty array
* and returns it back.
*/
asserta : function(array /* messages */)
{
if(ZeT.isa(array) && array.length)
return array
var m = ZeTS.cati(1, arguments)
if(ZeT.ises(m)) m = 'Not an empty array is required!'
throw ZeT.ass(m)
}
}) //<-- return this value | AntonBaukin/embeddy | springer/sources/net/java/osgi/embeddy/springer/jsx/zet/asserts.js | JavaScript | unlicense | 2,337 |
#include "arq_in_unit_tests.h"
#include "arq_runtime_mock_plugin.h"
#include <CppUTest/TestHarness.h>
#include <CppUTestExt/MockSupport.h>
TEST_GROUP(connect) {};
namespace {
TEST(connect, invalid_params)
{
CHECK_EQUAL(ARQ_ERR_INVALID_PARAM, arq_connect(nullptr));
}
TEST(connect, returns_err_not_disconnected_if_state_is_not_disconnected)
{
arq_t arq;
arq.conn.state = ARQ_CONN_STATE_ESTABLISHED;
CHECK_EQUAL(ARQ_ERR_NOT_DISCONNECTED, arq_connect(&arq));
}
TEST(connect, changes_state_to_rst_sent)
{
arq_t arq;
arq.conn.state = ARQ_CONN_STATE_CLOSED;
arq_connect(&arq);
CHECK_EQUAL(ARQ_CONN_STATE_RST_SENT, arq.conn.state);
}
TEST(connect, sets_cnt_to_zero)
{
arq_t arq;
arq.conn.state = ARQ_CONN_STATE_CLOSED;
arq.conn.u.rst_sent.cnt = 123;
arq_connect(&arq);
CHECK_EQUAL(0, arq.conn.u.rst_sent.cnt);
}
TEST(connect, sets_tmr_to_zero)
{
arq_t arq;
arq.conn.state = ARQ_CONN_STATE_CLOSED;
arq.conn.u.rst_sent.tmr = 123;
arq_connect(&arq);
CHECK_EQUAL(0, arq.conn.u.rst_sent.tmr);
}
TEST(connect, sets_recvd_rst_ack_to_false)
{
arq_t arq;
arq.conn.state = ARQ_CONN_STATE_CLOSED;
arq.conn.u.rst_sent.recvd_rst_ack = ARQ_TRUE;
arq_connect(&arq);
CHECK_EQUAL(ARQ_FALSE, arq.conn.u.rst_sent.recvd_rst_ack);
}
TEST(connect, sets_simultaneous_to_false)
{
arq_t arq;
arq.conn.state = ARQ_CONN_STATE_CLOSED;
arq.conn.u.rst_sent.simultaneous = ARQ_TRUE;
arq_connect(&arq);
CHECK_EQUAL(ARQ_FALSE, arq.conn.u.rst_sent.simultaneous);
}
TEST(connect, returns_success)
{
arq_t arq;
arq.conn.state = ARQ_CONN_STATE_CLOSED;
arq_err_t const e = arq_connect(&arq);
CHECK_EQUAL(ARQ_OK_POLL_REQUIRED, e);
}
}
| charlesnicholson/nanoarq | unit_tests/test_connect.cpp | C++ | unlicense | 1,729 |
/*******************************************************************************
Yuri V. Krugloff. 2013-2015. http://www.tver-soft.org
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*******************************************************************************/
#include "QtBinPatcher.hpp"
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <vector>
#include <algorithm>
#include <fstream>
#include "Logger.hpp"
#include "Functions.hpp"
#include "CmdLineOptions.hpp"
#include "CmdLineParser.hpp"
#include "CmdLineChecker.hpp"
#include "QMake.hpp"
#include "Backup.hpp"
//------------------------------------------------------------------------------
using namespace std;
using namespace Functions;
//------------------------------------------------------------------------------
#define QT_PATH_MAX_LEN 450
//------------------------------------------------------------------------------
// Case-insensitive comparision (only for case-independent file systems).
bool caseInsensitiveComp(const char c1, const char c2)
{
return tolower(c1) == tolower(c2);
}
//------------------------------------------------------------------------------
// String comparision. For OS Windows comparision is case-insensitive.
bool strneq(const string& s1, const string& s2)
{
#ifdef OS_WINDOWS
string _s1 = s1, _s2 = s2;
transform(_s1.begin(), _s1.end(), _s1.begin(), ::tolower);
transform(_s2.begin(), _s2.end(), _s2.begin(), ::tolower);
return _s1 != _s2;
#else
return s1 != s2;
#endif
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
string TQtBinPatcher::getStartDir() const
{
string Result = normalizeSeparators(m_ArgsMap.value(OPT_QT_DIR));
if (!Result.empty())
Result = absolutePath(Result);
return Result;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::getQtDir()
{
m_QtDir = m_QMake.qtPath();
if (m_QtDir.empty()) {
LOG_E("Can't determine path to Qt directory.\n");
return false;
}
LOG_V("Path to Qt directory: \"%s\".\n", m_QtDir.c_str());
return true;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::getNewQtDir()
{
assert(hasOnlyNormalSeparators(m_QtDir));
m_NewQtDir = normalizeSeparators(m_ArgsMap.value(OPT_NEW_DIR));
if (!m_NewQtDir.empty())
m_NewQtDir = absolutePath(m_NewQtDir);
else
m_NewQtDir = m_QtDir;
LOG_V("Path to new Qt directory: \"%s\".\n", m_NewQtDir.c_str());
if (m_NewQtDir.length() > QT_PATH_MAX_LEN) {
LOG_E("Path to new Qt directory too long (%i symbols).\n"
"Path must be not longer as %i symbols.",
m_NewQtDir.length(), QT_PATH_MAX_LEN);
return false;
}
return !m_NewQtDir.empty();
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::isPatchNeeded()
{
assert(hasOnlyNormalSeparators(m_NewQtDir));
string OldQtDir = normalizeSeparators(m_QMake.qtInstallPrefix());
if (!OldQtDir.empty() && !m_NewQtDir.empty())
return strneq(OldQtDir, m_NewQtDir);
return false;
}
//------------------------------------------------------------------------------
void TQtBinPatcher::addTxtPatchValues(const string& oldPath)
{
assert(hasOnlyNormalSeparators(oldPath));
assert(hasOnlyNormalSeparators(m_NewQtDir));
if (!oldPath.empty()) {
m_TxtPatchValues[oldPath] = m_NewQtDir;
#ifdef OS_WINDOWS
string Old = oldPath;
string New = m_NewQtDir;
replace(Old.begin(), Old.end(), '/', '\\');
replace(New.begin(), New.end(), '/', '\\');
m_TxtPatchValues[Old] = New;
string NewQtDirDS = m_NewQtDir;
replace(&NewQtDirDS, '/', "\\\\");
Old = oldPath;
replace(&Old, '/', "\\\\");
m_TxtPatchValues[Old] = NewQtDirDS;
#endif
}
}
//------------------------------------------------------------------------------
void TQtBinPatcher::createBinPatchValues()
{
struct TParam
{
const char* const Name;
const char* const Prefix;
};
static const TParam Params[] = {
{"QT_INSTALL_PREFIX", "qt_epfxpath="}, // "QT_EXT_PREFIX"
{"QT_INSTALL_PREFIX", "qt_prfxpath="},
{"QT_HOST_PREFIX", "qt_hpfxpath="}
#ifndef QTCROSS
,
{"QT_INSTALL_ARCHDATA", "qt_adatpath="},
{"QT_INSTALL_DATA", "qt_datapath="},
{"QT_INSTALL_DOCS", "qt_docspath="},
{"QT_INSTALL_HEADERS", "qt_hdrspath="},
{"QT_INSTALL_LIBS", "qt_libspath="},
{"QT_INSTALL_LIBEXECS", "qt_lbexpath="},
{"QT_INSTALL_BINS", "qt_binspath="},
{"QT_INSTALL_TESTS", "qt_tstspath="},
{"QT_INSTALL_PLUGINS", "qt_plugpath="},
{"QT_INSTALL_IMPORTS", "qt_impspath="},
{"QT_INSTALL_QML", "qt_qml2path="},
{"QT_INSTALL_TRANSLATIONS", "qt_trnspath="},
{"QT_INSTALL_EXAMPLES", "qt_xmplpath="},
{"QT_INSTALL_DEMOS", "qt_demopath="},
{"QT_HOST_DATA", "qt_hdatpath="},
{"QT_HOST_BINS", "qt_hbinpath="},
{"QT_HOST_LIBS", "qt_hlibpath="}
#endif
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string newQtDirNative = normalizeSeparators(m_NewQtDir);
for (size_t i = 0; i < sizeof(Params) / sizeof(Params[0]); ++i) {
const TParam& Param = Params[i];
if (!m_QMake.value(Param.Name).empty()) {
string NewValue = Param.Prefix;
NewValue.append(newQtDirNative);
const std::string suffix = m_QMake.suffix(Param.Name);
if (!suffix.empty())
NewValue += separator() + suffix;
m_BinPatchValues[Param.Prefix] = NewValue;
} else {
LOG_V("Variable \"%s\" not found in qmake output.\n", Param.Name);
}
}
}
//------------------------------------------------------------------------------
void TQtBinPatcher::createPatchValues()
{
m_TxtPatchValues.clear();
m_BinPatchValues.clear();
addTxtPatchValues(normalizeSeparators(m_QMake.qtInstallPrefix()));
createBinPatchValues();
const TStringList* pValues = m_ArgsMap.values(OPT_OLD_DIR);
if (pValues != NULL)
for (TStringList::const_iterator Iter = pValues->begin(); Iter != pValues->end(); ++Iter)
addTxtPatchValues(normalizeSeparators(*Iter));
LOG_V("\nPatch values for text files:\n%s",
stringMapToStr(m_TxtPatchValues, " \"", "\" -> \"", "\"\n").c_str());
LOG_V("\nPatch values for binary files:\n%s",
stringMapToStr(m_BinPatchValues, " \"", "\" -> \"", "\"\n").c_str());
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::createTxtFilesForPatchList()
{
struct TElement
{
const char* const Dir;
const char* const Name;
const bool Recursive;
};
// Files for patching in Qt4.
static const TElement Elements4[] = {
{"/lib/", "*.pri", true},
{"/demos/shared/", "libdemo_shared.prl", false},
{"/lib/pkgconfig/", "Qt*.pc", false},
{"/lib/pkgconfig/", "phonon*.pc", false},
{"/mkspecs/default/", "qmake.conf", false},
{"/", ".qmake.cache", false},
{"/lib/pkgconfig/", "qt*.pc", false},
{"/lib/", "*.la", false},
{"/mkspecs/", "qconfig.pri", false}
};
// Files for patching in Qt5.
static const TElement Elements5[] = {
{"/", "*.la", true},
{"/", "*.prl", true},
{"/lib/pkgconfig/", "Qt5*.pc", true},
{"/lib/pkgconfig/", "Enginio*.pc", true},
{"/", "*.pri", true},
{"/lib/cmake/Qt5LinguistTools/", "Qt5LinguistToolsConfig.cmake", false}
#ifndef QTCROSS
,
{"/mkspecs/default-host/", "qmake.conf", false},
{"/mkspecs/default/", "qmake.conf", false},
{"/", ".qmake.cache", false},
{"/lib/", "prl.txt", false}
#endif
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
m_TxtFilesForPatch.clear();
const TElement* Elements;
size_t Count;
switch (m_QMake.qtVersion()) {
case '4':
Elements = Elements4;
Count = sizeof(Elements4) / sizeof(Elements4[0]);
break;
case '5':
Elements = Elements5;
Count = sizeof(Elements5) / sizeof(Elements5[0]);
break;
default:
LOG_E("Unsupported Qt version (%c).", m_QMake.qtVersion());
return false;
}
for (size_t i = 0; i < Count; ++i) {
if (Elements[i].Recursive)
splice(&m_TxtFilesForPatch, findFilesRecursive(m_QtDir + Elements[i].Dir, Elements[i].Name));
else
splice(&m_TxtFilesForPatch, findFiles(m_QtDir + Elements[i].Dir, Elements[i].Name));
}
LOG_V("\nList of text files for patch:\n%s\n",
stringListToStr(m_TxtFilesForPatch, " ", "\n").c_str());
return true;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::createBinFilesForPatchList()
{
struct TElement
{
const char* const Dir;
const char* const Name;
const char *const xplatform;
};
// Files for patching in Qt4.
static const TElement Elements4[] = {
#if defined(OS_WINDOWS)
{"/bin/", "qmake.exe", NULL},
#else
{"/bin/", "qmake", NULL},
#endif
#ifndef QTCROSS
{"/bin/", "lrelease", NULL},
{"/bin/", "lrelease.exe", NULL},
{"/bin/", "QtCore*.dll", "win"},
{"/lib/", "QtCore*.dll", "win"},
{"/lib/", "libQtCore*.so", "linux"},
{"/lib/", "libQtCore*.dylib", "macx"},
{"/lib/QtCore.framework/", "QtCore", "macx"}
#endif
};
// Files for patching in Qt5.
static const TElement Elements5[] = {
#ifdef OS_WINDOWS
{"/bin/", "qmake.exe", NULL},
{"/bin/", "qdoc.exe", NULL},
#else
{"/bin/", "qmake", NULL},
{"/bin/", "qdoc", NULL},
#endif
#ifndef QTCROSS
{"/bin/", "lrelease", NULL},
{"/bin/", "lrelease.exe", NULL},
{"/bin/", "Qt5Core*.dll", "win"},
{"/lib/", "Qt5Core*.dll", "win"},
{"/lib/", "libQt5Core*.so", "linux"},
{"/lib/", "libQt5Core*.dylib", "macx"},
{"/lib/QtCore.framework/", "QtCore", "macx"}
#endif
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
m_BinFilesForPatch.clear();
const TElement* Elements;
size_t Count;
switch (m_QMake.qtVersion()) {
case '4':
Elements = Elements4;
Count = sizeof(Elements4) / sizeof(Elements4[0]);
break;
case '5':
Elements = Elements5;
Count = sizeof(Elements5) / sizeof(Elements5[0]);
break;
default:
LOG_E("Unsupported Qt version (%c).\n", m_QMake.qtVersion());
return false;
}
string xspec = m_QMake.xSpec();
if (xspec.empty()) {
LOG_E("Unable to get mkspec from Qt install.\n");
return false;
}
for (size_t i = 0; i < Count; ++i) {
bool flag = false;
if (Elements[i].xplatform == NULL)
flag = true;
else {
const char *const d = ",";
char *copystr = new char[strlen(Elements[i].xplatform) + 2];
strcpy(copystr, Elements[i].xplatform);
char *c = strtok(copystr, d);
while (c != NULL) {
if (xspec.find(c) != string::npos) {
flag = true;
break;
}
c = strtok(NULL, d);
}
delete[] copystr;
}
if (flag)
splice(&m_BinFilesForPatch, findFiles(m_QtDir + Elements[i].Dir, Elements[i].Name));
}
LOG_V("\nList of binary files for patch:\n%s\n",
stringListToStr(m_BinFilesForPatch, " ", "\n").c_str());
return true;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::patchTxtFile(const string& fileName)
{
LOG("Patching text file \"%s\".\n", fileName.c_str());
if (m_ArgsMap.contains(OPT_DRY_RUN))
return true;
bool Result = false;
if ((m_QMake.qtVersion() == '4') && (fileName.substr(fileName.length() - 26) == "mkspecs/default/qmake.conf")) // Workaround QTBUG-27593 && QTBUG-28792
return patchQtbug27593(fileName);
FILE* File = fopen(fileName.c_str(), "r+b");
if (File != NULL) {
vector<char> Buf;
long FileLength = getFileSize(File);
if (FileLength > 0) {
Buf.resize(FileLength);
if (fread(Buf.data(), FileLength, 1, File) == 1) {
for (TStringMap::const_iterator Iter = m_TxtPatchValues.begin(); Iter != m_TxtPatchValues.end(); ++Iter) {
string::size_type Delta = 0;
vector<char>::iterator Found;
while ((Found = search(Buf.begin() + Delta, Buf.end(),
Iter->first.begin(), Iter->first.end()
#ifdef OS_WINDOWS
, caseInsensitiveComp
#endif
))
!= Buf.end()) {
Delta = Found - Buf.begin() + static_cast<int>(Iter->second.length());
Found = Buf.erase(Found, Found + Iter->first.length());
Buf.insert(Found, Iter->second.begin(), Iter->second.end());
}
}
zeroFile(File);
if (fwrite(Buf.data(), Buf.size(), 1, File) == 1)
Result = true;
else
LOG_E("Error writing to file \"%s\".\n", fileName.c_str());
} else {
LOG_E("Error reading from file \"%s\".\n", fileName.c_str());
}
} else {
LOG_V(" File is empty. Skipping.\n");
Result = true;
}
fclose(File);
} else {
LOG_E("Error opening file \"%s\". Error %i.\n", fileName.c_str(), errno);
}
return Result;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::patchQtbug27593(const string &fileName)
{
try {
string xspec = m_QMake.xSpec();
ofstream ofs(fileName.c_str(), ios_base::out | ios_base::trunc);
ofs << (string("QMAKESPEC_ORIGINAL=") + m_NewQtDir + string("/mkspecs/") + xspec) << endl << endl;
ofs << (string("include(../") + xspec + string("/qmake.conf)")) << endl << endl;
} catch(...) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::patchBinFile(const string& fileName)
{
LOG("Patching binary file \"%s\".\n", fileName.c_str());
if (m_ArgsMap.contains(OPT_DRY_RUN))
return true;
bool Result = false;
FILE* File = fopen(fileName.c_str(), "r+b");
if (File != NULL) {
long BufSize = getFileSize(File);
char* Buf = new char[BufSize];
if (fread(Buf, BufSize, 1, File) == 1) {
for (TStringMap::const_iterator Iter = m_BinPatchValues.begin(); Iter != m_BinPatchValues.end(); ++Iter) {
char* First = Buf;
while ((First = search(First, Buf + BufSize,
Iter->first.begin(), Iter->first.end()
#ifdef OS_WINDOWS
, caseInsensitiveComp
#endif
))
!= Buf + BufSize
) {
strcpy(First, Iter->second.c_str());
First += Iter->second.length();
}
}
rewind(File);
if (fwrite(Buf, BufSize, 1, File) == 1)
Result = true;
else
LOG_E("Error writing to file \"%s\".\n", fileName.c_str());
} else {
LOG_E("Error reading from file \"%s\".\n", fileName.c_str());
}
delete[] Buf;
fclose(File);
} else {
LOG_E("Error opening file \"%s\". Error %i.\n", fileName.c_str(), errno);
}
return Result;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::patchTxtFiles()
{
for (TStringList::const_iterator Iter = m_TxtFilesForPatch.begin(); Iter != m_TxtFilesForPatch.end(); ++Iter)
if (!patchTxtFile(*Iter))
return false;
return true;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::patchBinFiles()
{
for (TStringList::const_iterator Iter = m_BinFilesForPatch.begin(); Iter != m_BinFilesForPatch.end(); ++Iter)
if (!patchBinFile(*Iter))
return false;
return true;
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::exec()
{
if (!getQtDir())
return false;
if (!getNewQtDir())
return false;
TBackup Backup;
if (!m_ArgsMap.contains(OPT_DRY_RUN)) {
Backup.setSkipBackup(m_ArgsMap.contains(OPT_NOBACKUP));
if (!Backup.backupFile(m_QtDir + "/bin/qt.conf", TBackup::bmRename))
return false;
}
if (!isPatchNeeded()) {
if (m_ArgsMap.contains(OPT_FORCE)) {
LOG("\nThe new and the old pathes to Qt directory are the same.\n"
"Perform forced patching.\n\n");
} else {
LOG("\nThe new and the old pathes to Qt directory are the same.\n"
"Patching not needed.\n");
return true;
}
}
createPatchValues();
if (!createTxtFilesForPatchList() || !createBinFilesForPatchList())
return false;
if (!m_ArgsMap.contains(OPT_DRY_RUN)) {
if (!Backup.backupFiles(m_TxtFilesForPatch) || !Backup.backupFiles(m_BinFilesForPatch))
return false;
}
if (!patchTxtFiles() || !patchBinFiles())
return false;
if (!m_ArgsMap.contains(OPT_DRY_RUN)) {
// Finalization.
if (m_ArgsMap.contains(OPT_BACKUP))
Backup.save();
else {
if (!Backup.remove())
return false;
}
}
return true;
}
//------------------------------------------------------------------------------
TQtBinPatcher::TQtBinPatcher(const TStringListMap& argsMap)
: m_ArgsMap(argsMap),
m_QMake(getStartDir()),
m_hasError(false)
{
if (m_QMake.hasError()) {
m_hasError = true;
LOG_E("%s\n", m_QMake.errorString().c_str());
} else {
m_hasError = !exec();
}
}
//------------------------------------------------------------------------------
bool TQtBinPatcher::exec(const TStringListMap& argsMap)
{
TQtBinPatcher QtBinPatcher(argsMap);
return !QtBinPatcher.m_hasError;
}
//------------------------------------------------------------------------------
| Fsu0413/QtBinPatcher | QtBinPatcher.cpp | C++ | unlicense | 20,363 |
exports.run = function (callback) {
console.log("Hello from worker");
var uri = require.sandbox.id + require.id("./worker-runner.js");
console.log("Worker runner uri: " + uri);
return require.sandbox(uri, function(sandbox) {
return sandbox.main(callback);
}, function (err) {
console.log("Error while loading bundle '" + uri + "':", err.stack);
return callback(err);
});
}
| pinf-it/pinf-it-bundler | test/assets/packages/multiple-declared-exports-bundles/util/worker.js | JavaScript | unlicense | 392 |
I.regist('z.Win',function(W,D){
var CFG={
skin:'Default',
mask:true,
mask_opacity:10,
mask_color:'#FFF',
mask_close:false,
width:400,
height:250,
shadow:'#333 0px 0px 8px',
round:6,
title:'窗口',
title_height:30,
title_background:'#EFEFF0',
title_color:'#000',
title_border_color:'#BBB',
title_border_height:1,
close_icon:'fa fa-times',
close_background:'#EFEFF0',
close_color:'#000',
close_hover_background:'#EFEFF0',
close_hover_color:'#000',
content:'',
content_background:'#FFF',
footer_height:0,
footer_background:'#FFF',
footer_border_color:'#EEE',
footer_border_height:0,
callback:function(){}
};
var _create=function(obj){
var cfg=obj.config;
if(cfg.mask){
obj.mask=I.ui.Mask.create({skin:cfg.skin,opacity:cfg.mask_opacity,color:cfg.mask_color});
}
var o=I.insert('div');
I.cls(o,obj.className);
o.innerHTML='<i class="i-header"></i><a href="javascript:void(0);" class="i-close"></a><i class="i-body"></i><i class="i-footer"></i>';
obj.layer=o;
I.util.Boost.round(o,cfg.round);
I.util.Boost.addStyle(o,'-webkit-box-shadow:'+cfg.shadow+';-moz-box-shadow:'+cfg.shadow+';-ms-box-shadow:'+cfg.shadow+';-o-box-shadow:'+cfg.shadow+';box-shadow:'+cfg.shadow+';');
obj.titleBar=I.$(o,'class','i-header')[0];
obj.titleBar.innerHTML=cfg.title;
I.util.Boost.addStyle(obj.titleBar,'background:'+cfg.title_background+';color:'+cfg.title_color+';border-bottom:'+cfg.title_border_height+'px inset '+cfg.title_border_color+';');
obj.closeButton=I.$(o,'class','i-close')[0];
if(cfg.close_icon){
I.cls(obj.closeButton,'i-close '+cfg.close_icon);
}
I.util.Boost.addStyle(obj.closeButton,'background:'+cfg.close_background+';color:'+cfg.close_color);
I.listen(obj.closeButton,'click',function(){
obj.close();
});
obj.contentPanel=I.$(o,'class','i-body')[0];
obj.contentPanel.innerHTML=cfg.content;
obj.contentPanel.style.background=cfg.content_background;
obj.footerBar=I.$(o,'class','i-footer')[0];
I.util.Boost.addStyle(obj.footerBar,'background:'+cfg.footer_background+';border-top:'+cfg.footer_border_height+'px solid '+cfg.footer_border_color+';');
if(cfg.mask){
if(cfg.mask_close){
I.listen(obj.mask.layer,'click',function(m,e){
obj.close();
return true;
});
}
}
obj.suit=function(){
var that=this;
var c=that.config;
var r=I.region();
var wd=c.width;
var ht=c.height+c.title_height+c.footer_height;
I.util.Boost.addStyle(that.layer,'width:'+wd+'px;height:'+ht+'px;');
I.util.Boost.addStyle(that.titleBar,'width:'+wd+'px;height:'+c.title_height+'px;line-height:'+c.title_height+'px;');
I.util.Boost.addStyle(that.closeButton,'width:'+(c.title_height-c.title_border_height)+'px;height:'+(c.title_height-c.title_border_height)+'px;line-height:'+c.title_height+'px;');
I.util.Boost.addStyle(that.contentPanel,'top:'+c.title_height+'px;width:'+wd+'px;height:'+c.height+'px;');
I.util.Boost.addStyle(that.footerBar,'width:'+wd+'px;height:'+c.footer_height+'px;');
};
obj.resizeTo=function(w,h){
var that=this;
var c=that.config;
c.width=w;
c.height=h;
that.suit();
};
obj.goCenter=function(){
var that=this;
var c=that.config;
var r=I.region();
var wd=c.width;
var ht=c.height+c.title_height+c.footer_height;
I.util.Boost.addStyle(that.layer,'left:'+(r.x+Math.floor((r.width-wd)/2))+'px;top:'+(r.y+Math.floor((r.height-ht)/2))+'px;');
};
obj.moveTo=function(x,y){
I.util.Boost.addStyle(this.layer,'left:'+x+'px;top:'+y+'px;');
};
obj.goCenter();
obj.suit();
I.util.Drager.drag(obj.titleBar,obj.layer);
};
var _prepare=function(config){
var obj={layer:null,mask:null,titleBar:null,closeButton:null,contentPanel:null,footerBar:null,className:null,config:cfg};
var cfg=I.ui.Component.initConfig(config,CFG);
obj.config=cfg;
obj.className='i-z-Win-'+cfg.skin;
I.util.Skin.init(cfg.skin);
_create(obj);
obj.close=function(){
this.config.callback.call(this);
try{this.mask.close();}catch(e){}
this.layer.parentNode.removeChild(this.layer);
};
return obj;
};
return{
create:function(cfg){return _prepare(cfg);}
};
}+''); | 6tail/nlf | WebContent/js/z/Win.js | JavaScript | unlicense | 4,167 |
package com.ushaqi.zhuishushenqi.adapter;
import android.widget.CheckBox;
import android.widget.TextView;
import butterknife.ButterKnife.Finder;
public class HomeShelfAdapter$TxtHolder$$ViewInjector
{
public static void inject(ButterKnife.Finder paramFinder, HomeShelfAdapter.TxtHolder paramTxtHolder, Object paramObject)
{
paramTxtHolder.title = ((TextView)paramFinder.findRequiredView(paramObject, 2131492936, "field 'title'"));
paramTxtHolder.desc = ((TextView)paramFinder.findRequiredView(paramObject, 2131493481, "field 'desc'"));
paramTxtHolder.top = paramFinder.findRequiredView(paramObject, 2131492978, "field 'top'");
paramTxtHolder.check = ((CheckBox)paramFinder.findRequiredView(paramObject, 2131492900, "field 'check'"));
}
public static void reset(HomeShelfAdapter.TxtHolder paramTxtHolder)
{
paramTxtHolder.title = null;
paramTxtHolder.desc = null;
paramTxtHolder.top = null;
paramTxtHolder.check = null;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.adapter.HomeShelfAdapter.TxtHolder..ViewInjector
* JD-Core Version: 0.6.0
*/ | clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/adapter/HomeShelfAdapter$TxtHolder$$ViewInjector.java | Java | unlicense | 1,184 |
using System.Collections.Generic;
using Tapeti.Config;
// ReSharper disable UnusedMember.Global
namespace Tapeti.Flow.SQL
{
/// <summary>
/// Extends ITapetiConfigBuilder to enable Flow SQL.
/// </summary>
public static class ConfigExtensions
{
/// <summary>
/// Enables the Flow SQL repository.
/// </summary>
/// <param name="config"></param>
/// <param name="connectionString"></param>
/// <param name="tableName"></param>
public static ITapetiConfigBuilder WithFlowSqlRepository(this ITapetiConfigBuilder config, string connectionString, string tableName = "Flow")
{
config.Use(new FlowSqlRepositoryExtension(connectionString, tableName));
return config;
}
}
internal class FlowSqlRepositoryExtension : ITapetiExtension
{
private readonly string connectionString;
private readonly string tableName;
public FlowSqlRepositoryExtension(string connectionString, string tableName)
{
this.connectionString = connectionString;
this.tableName = tableName;
}
public void RegisterDefaults(IDependencyContainer container)
{
container.RegisterDefaultSingleton<IFlowRepository>(() => new SqlConnectionFlowRepository(connectionString, tableName));
}
public IEnumerable<object> GetMiddleware(IDependencyResolver dependencyResolver)
{
return null;
}
}
}
| MvRens/Tapeti | Tapeti.Flow.SQL/ConfigExtensions.cs | C# | unlicense | 1,523 |
// TextColorDlg.cpp : implementation file
//
#include "stdafx.h"
#include "DlgDateExchange2.h"
#include "TextColorDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define WM_SET_COLOR WM_USER+100//×Ô¶¨ÒåÏûÏ¢
/////////////////////////////////////////////////////////////////////////////
// CTextColorDlg dialog
CTextColorDlg::CTextColorDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTextColorDlg::IDD, pParent)
{
ASSERT(pParent);//´°¿Ú¶ÔÏóÓÐЧ
m_pParent=pParent;//»ñÈ¡´°¿Ú¶ÔÏó
//{{AFX_DATA_INIT(CTextColorDlg)
m_red = 0;
m_green = 0;
m_blue = 0;
//}}AFX_DATA_INIT
}
void CTextColorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTextColorDlg)
DDX_Text(pDX, IDC_EDIT1, m_red);
DDV_MinMaxInt(pDX, m_red, 0, 255);
DDX_Text(pDX, IDC_EDIT2, m_green);
DDV_MinMaxInt(pDX, m_green, 0, 255);
DDX_Text(pDX, IDC_EDIT3, m_blue);
DDV_MinMaxInt(pDX, m_blue, 0, 255);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTextColorDlg, CDialog)
//{{AFX_MSG_MAP(CTextColorDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTextColorDlg message handlers
void CTextColorDlg::OnOK()
{
// TODO: Add extra validation here
UpdateData();//»ñÈ¡±à¼¿òÊý¾Ý
m_pParent->SendMessage(WM_SET_COLOR,(WPARAM)this);//·¢ËÍ×Ô¶¨ÒåÏûÏ¢
//CDialog::OnOK();
}
void CTextColorDlg::OnCancel()
{
// TODO: Add extra cleanup here
CDialog::OnCancel();
}
| hyller/CodeLibrary | Visual C++ Example/第6章 对话框程序设计/实例119——非模态对话框与应用程序之间的数据交换/DlgDateExchange2/TextColorDlg.cpp | C++ | unlicense | 1,555 |
//$Id: InstrumentTest.java 10976 2006-12-12 23:22:26Z steve.ebersole@jboss.com $
package org.hibernate.test.instrument.buildtime;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.hibernate.intercept.FieldInterceptionHelper;
import org.hibernate.testing.junit.UnitTestCase;
import org.hibernate.test.instrument.cases.Executable;
import org.hibernate.test.instrument.cases.TestCustomColumnReadAndWrite;
import org.hibernate.test.instrument.cases.TestDirtyCheckExecutable;
import org.hibernate.test.instrument.cases.TestFetchAllExecutable;
import org.hibernate.test.instrument.cases.TestInjectFieldInterceptorExecutable;
import org.hibernate.test.instrument.cases.TestIsPropertyInitializedExecutable;
import org.hibernate.test.instrument.cases.TestLazyExecutable;
import org.hibernate.test.instrument.cases.TestLazyManyToOneExecutable;
import org.hibernate.test.instrument.cases.TestLazyPropertyCustomTypeExecutable;
import org.hibernate.test.instrument.cases.TestManyToOneProxyExecutable;
import org.hibernate.test.instrument.cases.TestSharedPKOneToOneExecutable;
import org.hibernate.test.instrument.domain.Document;
/**
* @author Gavin King
*/
public class InstrumentTest extends UnitTestCase {
public InstrumentTest(String str) {
super(str);
}
public static Test suite() {
return new TestSuite( InstrumentTest.class );
}
public void testDirtyCheck() throws Exception {
execute( new TestDirtyCheckExecutable() );
}
public void testFetchAll() throws Exception {
execute( new TestFetchAllExecutable() );
}
public void testLazy() throws Exception {
execute( new TestLazyExecutable() );
}
public void testLazyManyToOne() throws Exception {
execute( new TestLazyManyToOneExecutable() );
}
public void testSetFieldInterceptor() throws Exception {
execute( new TestInjectFieldInterceptorExecutable() );
}
public void testPropertyInitialized() throws Exception {
execute( new TestIsPropertyInitializedExecutable() );
}
public void testManyToOneProxy() throws Exception {
execute( new TestManyToOneProxyExecutable() );
}
public void testLazyPropertyCustomTypeExecutable() throws Exception {
execute( new TestLazyPropertyCustomTypeExecutable() );
}
public void testSharedPKOneToOne() throws Exception {
execute( new TestSharedPKOneToOneExecutable() );
}
public void testCustomColumnReadAndWrite() throws Exception {
execute( new TestCustomColumnReadAndWrite() );
}
private void execute(Executable executable) throws Exception {
executable.prepare();
try {
executable.execute();
}
finally {
executable.complete();
}
}
protected void runTest() throws Throwable {
if ( isRunnable() ) {
super.runTest();
}
else {
reportSkip( "domain classes not instrumented", "build-time instrumentation" );
}
}
public static boolean isRunnable() {
return FieldInterceptionHelper.isInstrumented( new Document() );
}
}
| codeApeFromChina/resource | frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-testsuite/src/test/java/org/hibernate/test/instrument/buildtime/InstrumentTest.java | Java | unlicense | 2,922 |
#include <chrono>
#include <thread>
#include <iostream>
#include "tasks.h"
int main() {
f();
g();
return 0;
}
| jdgarciauc3m/talks | intro-conc/async/main1.cpp | C++ | unlicense | 117 |
<?php
/**
* This is the model class for table "zb_order".
*
* The followings are the available columns in table 'zb_order':
* @property string $order_num
* @property string $wx_open_id
* @property double $price
* @property double $discount_price
* @property string $pay_status
* @property integer $coupon_id
* @property string $child_name
* @property integer $child_age
* @property string $child_school
* @property string $child_tel
* @property string $classroom_name
* @property string $classroom_tel
* @property string $address
* @property string $close_status
* @property string $weixin_order_num
* @property string $pay_time
* @property string $backup
* @property string $create_time
* @property string $update_time
*
* The followings are the available model relations:
* @property OrderCourse[] $orderCourses
*/
class Order extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'zb_order';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('order_num', 'required'),
array('coupon_id, child_age', 'numerical', 'integerOnly'=>true),
array('price, discount_price', 'numerical'),
array('order_num, wx_open_id, weixin_order_num', 'length', 'max'=>100),
array('pay_status, close_status', 'length', 'max'=>1),
array('child_name', 'length', 'max'=>25),
array('child_school, address, backup', 'length', 'max'=>255),
array('child_tel, classroom_tel', 'length', 'max'=>20),
array('classroom_name', 'length', 'max'=>50),
array('pay_time, create_time, update_time', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('order_num, wx_open_id, price, discount_price, pay_status, coupon_id, child_name, child_age, child_school, child_tel, classroom_name, classroom_tel, address, close_status, weixin_order_num, pay_time, backup, create_time, update_time', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'orderCourses' => array(self::HAS_MANY, 'OrderCourse', 'order_num'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'order_num' => 'Order Num',
'wx_open_id' => 'Wx Open',
'price' => 'Price',
'discount_price' => 'Discount Price',
'pay_status' => 'Pay Status',
'coupon_id' => 'Coupon',
'child_name' => 'Child Name',
'child_age' => 'Child Age',
'child_school' => 'Child School',
'child_tel' => 'Child Tel',
'classroom_name' => 'Classroom Name',
'classroom_tel' => 'Classroom Tel',
'address' => 'Address',
'close_status' => 'Close Status',
'weixin_order_num' => 'Weixin Order Num',
'pay_time' => 'Pay Time',
'backup' => 'Backup',
'create_time' => 'Create Time',
'update_time' => 'Update Time',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('order_num',$this->order_num,true);
$criteria->compare('wx_open_id',$this->wx_open_id,true);
$criteria->compare('price',$this->price);
$criteria->compare('discount_price',$this->discount_price);
$criteria->compare('pay_status',$this->pay_status,true);
$criteria->compare('coupon_id',$this->coupon_id);
$criteria->compare('child_name',$this->child_name,true);
$criteria->compare('child_age',$this->child_age);
$criteria->compare('child_school',$this->child_school,true);
$criteria->compare('child_tel',$this->child_tel,true);
$criteria->compare('classroom_name',$this->classroom_name,true);
$criteria->compare('classroom_tel',$this->classroom_tel,true);
$criteria->compare('address',$this->address,true);
$criteria->compare('close_status',$this->close_status,true);
$criteria->compare('weixin_order_num',$this->weixin_order_num,true);
$criteria->compare('pay_time',$this->pay_time,true);
$criteria->compare('backup',$this->backup,true);
$criteria->compare('create_time',$this->create_time,true);
$criteria->compare('update_time',$this->update_time,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Order the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
| masonyeh/zb_api | protected/models/Order.php | PHP | unlicense | 5,435 |
from django.db import models
from django.contrib.gis.db import models as gmodels
from django_hstore import hstore
class License(models.Model):
"""A license under which a DataSource is published and useable."""
name = models.CharField(max_length=50)
url = models.URLField(help_text="A link to this license.")
version = models.CharField(
max_length=10, blank=True, null=True,
help_text="If this is some version of the license, identify it.")
body = models.TextField(
blank=True, null=True,
help_text="If there is no URL available, you can paste the license.")
def __unicode__(self):
return self.name
class DataSource(models.Model):
"""A data source from a third party."""
title = models.CharField(max_length=100)
attribution = models.TextField(
help_text="The attribution as the author requested it.")
year = models.PositiveIntegerField()
license = models.ForeignKey(License)
url = models.URLField(blank=True, null=True)
def __unicode__(self):
return self.title
class DataLayer(gmodels.Model):
"""Any external data that has a geometry that can be added to the map."""
name = gmodels.CharField(max_length=200)
description = gmodels.TextField(null=True, blank=True)
added = gmodels.DateTimeField(auto_now_add=True)
source = gmodels.ForeignKey(DataSource)
shape = gmodels.GeometryField()
info = hstore.DictionaryField(
null=True, blank=True,
help_text="Any supplementary data for this shape.")
| openwater/h2o-really | supplements/models.py | Python | unlicense | 1,549 |
/*
* debugFileInfoAccess.hpp
*
*
* @date 14-07-2020
* @author Teddy DIDE
* @version 1.00
* cppBase generated by gensources.
*/
#ifndef _DEBUGFILEINFO_ACCESS_HPP_
#define _DEBUGFILEINFO_ACCESS_HPP_
#include <boost/scoped_ptr.hpp>
#include <memory>
#include <boost/signals2.hpp>
#include <boost/any.hpp>
#include "cppBaseExport.hpp"
#include "debugFileInfo.hpp"
#define A(str) encode<EncodingT,ansi>(str)
#define C(str) encode<ansi,EncodingT>(str)
NAMESPACE_BEGIN(data_access)
using namespace entity;
/// Represents an access class for DebugFileInfo object.
/// This class is used to manage DebugFileInfo entity in database.
template <class EncodingT>
class CPPBASE_API _DebugFileInfoAccess {
private :
std::list< boost::shared_ptr< _DebugFileInfo<EncodingT> > > m_backup;
// Is a transaction in progress before queries ?
bool m_transactionOwner;
static _DebugFileInfoAccess<EncodingT>* m_instance;
public:
typedef boost::signals2::signal<void (operation_access_t, typename EncodingT::string_t const&, boost::any const&)> signal_t;
typedef boost::signals2::signal<void (operation_access_t)> signal_transaction_t;
typedef boost::signals2::connection connection_t;
private:
signal_t m_insertSignal;
signal_t m_updateSignal;
signal_t m_deleteSignal;
signal_transaction_t m_transactionSignal;
private:
/** Creates a new element DebugFileInfoAccess.
*/
_DebugFileInfoAccess();
/** Releases the DebugFileInfoAccess object.
*/
~_DebugFileInfoAccess();
Category* m_logger;
protected :
public :
/** Returns DebugFileInfoAccess object.
@return Instance of DebugFileInfoAccess.
*/
static _DebugFileInfoAccess<EncodingT>* getInstance();
/** Returns DebugFileInfo objects from database.
@param filter Condition allowing to filter data.
@return List of DebugFileInfo objects.
*/
std::vector< boost::shared_ptr< _DebugFileInfo<EncodingT> > > getManyDebugFileInfos(typename EncodingT::string_t const& filter) const;
/** Returns all DebugFileInfo objects from database.
@return List of DebugFileInfo objects.
*/
std::vector< boost::shared_ptr< _DebugFileInfo<EncodingT> > > getAllDebugFileInfos() const;
/** Returns DebugFileInfo object from database.
@param identifier
@return The DebugFileInfo object.
*/
boost::shared_ptr< _DebugFileInfo<EncodingT> > getOneDebugFileInfo(long long identifier) const;
/** Returns DebugFileInfo objects from database. Data are locked for update.
@param filter Condition allowing to filter data.
@param nowait Asynchonous call.
@return List of DebugFileInfo objects.
*/
std::vector< boost::shared_ptr< _DebugFileInfo<EncodingT> > > selectManyDebugFileInfos(typename EncodingT::string_t const& filter, bool nowait = false, bool addition = false);
/** Returns DebugFileInfo object from database. Data are locked for update.
@param identifier
@param nowait Asynchonous call.
@return The DebugFileInfo object.
*/
boost::shared_ptr< _DebugFileInfo<EncodingT> > selectOneDebugFileInfo(long long identifier, bool nowait = false, bool addition = false);
/** Returns whether the data <i>DebugFileInfo</i> are selected.
@param o The DebugFileInfo object.
@return True if the data <i>DebugFileInfo</i> are selected.
*/
bool isSelectedDebugFileInfo(boost::shared_ptr< _DebugFileInfo<EncodingT> > o) const;
/** Cancel the selection. The DebugFileInfo object cannot be updated or deleted from database.
*/
void cancelSelection();
/** Fills textFile data from database.
@param o The DebugFileInfo object.
*/
void fillTextFile(boost::shared_ptr< _DebugFileInfo<EncodingT> > o);
/** Fills debugFunctionInfo data from database.
@param o The DebugFileInfo object.
@param nowait Asynchronous call.
*/
void fillAllDebugFunctionInfos(boost::shared_ptr< _DebugFileInfo<EncodingT> > o, bool nowait = false);
/** Fills debugFunctionInfo data from database.
@param o The DebugFileInfo object.
@param identifier
@param nowait Asynchronous call.
*/
void fillOneDebugFunctionInfo(boost::shared_ptr< _DebugFileInfo<EncodingT> > o, long long identifier, bool nowait = false);
/** Fills debugFunctionInfo data from database.
@param o The DebugFileInfo object.
@param filter Condition allowing to filter data.
@param nowait Asynchonous call.
*/
void fillManyDebugFunctionInfos(boost::shared_ptr< _DebugFileInfo<EncodingT> > o, typename EncodingT::string_t const& filter, bool nowait = false);
/** Fills debugStubInfo data from database.
@param o The DebugFileInfo object.
@param nowait Asynchronous call.
*/
void fillAllDebugStubInfos(boost::shared_ptr< _DebugFileInfo<EncodingT> > o, bool nowait = false);
/** Fills debugStubInfo data from database.
@param o The DebugFileInfo object.
@param identifier
@param nowait Asynchronous call.
*/
void fillOneDebugStubInfo(boost::shared_ptr< _DebugFileInfo<EncodingT> > o, long long identifier, bool nowait = false);
/** Fills debugStubInfo data from database.
@param o The DebugFileInfo object.
@param filter Condition allowing to filter data.
@param nowait Asynchonous call.
*/
void fillManyDebugStubInfos(boost::shared_ptr< _DebugFileInfo<EncodingT> > o, typename EncodingT::string_t const& filter, bool nowait = false);
/** Returns whether DebugFileInfo data are altered from database.
@param o The DebugFileInfo object.
@return True if data DebugFileInfo have been altered.
*/
bool isModifiedDebugFileInfo(boost::shared_ptr< _DebugFileInfo<EncodingT> > o) const;
/** Updates DebugFileInfo data to database.
@param o The DebugFileInfo object.
*/
void updateDebugFileInfo(boost::shared_ptr< _DebugFileInfo<EncodingT> > o);
/** Inserts DebugFileInfo data to database.
@param o The DebugFileInfo object.
*/
void insertDebugFileInfo(boost::shared_ptr< _DebugFileInfo<EncodingT> > o);
/** Deletes DebugFileInfo data to database.
@param o The DebugFileInfo object.
*/
void deleteDebugFileInfo(boost::shared_ptr< _DebugFileInfo<EncodingT> > o);
/** Add signal for DebugFileInfo insertion.
@param subscriber The observer
@return The connection
*/
connection_t addInsertSignal(typename signal_t::slot_function_type subscriber);
/** Add signal for DebugFileInfo update.
@param subscriber The observer
@return The connection
*/
connection_t addUpdateSignal(typename signal_t::slot_function_type subscriber);
/** Add signal for DebugFileInfo deletion.
@param subscriber The observer
@return The connection
*/
connection_t addDeleteSignal(typename signal_t::slot_function_type subscriber);
/** Add signal for DebugFileInfo transaction result.
@param subscriber The observer
@return The connection
*/
connection_t addTransactionSignal(typename signal_transaction_t::slot_function_type subscriber);
/** Remove signal for DebugFileInfo insertion.
@param connection The connection
*/
void removeInsertSignal(connection_t connection);
/** Remove signal for DebugFileInfo update.
@param connection The connection
*/
void removeUpdateSignal(connection_t connection);
/** Remove signal for DebugFileInfo deletion.
@param connection The connection
*/
void removeDeleteSignal(connection_t connection);
/** Remove signal for DebugFileInfo transaction result.
@param connection The connection
*/
void removeTransactionSignal(connection_t connection);
};
typedef _DebugFileInfoAccess<ucs> UniDebugFileInfoAccess;
typedef _DebugFileInfoAccess<ansi> DebugFileInfoAccess;
NAMESPACE_END
#undef C
#undef A
#if !defined(HAS_CPPBASE_DLL) || defined(BUILD_CPPBASE_DLL)
#include "debugFileInfoAccess_impl.hpp"
#endif // !defined(HAS_CPPBASE_DLL) || defined(BUILD_CPPBASE_DLL)
#endif
| tedi21/SisypheReview | Sisyphe/cppbase/src/debugFileInfoAccess.hpp | C++ | unlicense | 7,588 |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AssessmentListComponent } from './assessment/assessment-list.component';
import { AssessmentDetailComponent } from './assessment/assessment-detail.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AssessmentCreateComponent } from './assessment/assessment-create.component';
import { ASSESSMENTDETAIL_ROUTES } from './assessment/assessment-detail.routes';
import { ResultEditorComponent } from './result/result-editor.component';
import { ResultDetailComponent } from './result/result-detail.component';
const routes: Routes = [
{ path: '', component: AssessmentListComponent},
// { path: '', redirectTo: '/assessments', pathMatch: 'full'},
{ path: 'dashboard', component: DashboardComponent },
{ path: 'assessment/:id', component: AssessmentDetailComponent },
{ path: 'assessment/:id', component: AssessmentDetailComponent},
{ path: 'assessments', component: AssessmentListComponent},
{ path: 'createassessment', component: AssessmentCreateComponent},
{ path: 'resulteditor/:id', component: ResultEditorComponent}
];
@NgModule({
imports: [ RouterModule.forRoot(routes)],
exports: [ RouterModule]
})
export class AppRoutingModule {}
| jonshern/securitycontrolassessment | website/src/app/app-routing.module.ts | TypeScript | unlicense | 1,326 |
<?php
class m130906_033817_add_user_table extends CDbMigration
{
public function up()
{
$this->createTable('user', array(
'id' => 'pk',
'name' => 'string NOT NULL',
'password' => 'string NOT NULL',
'email' => 'string NOT NULL',
'created_at' => 'DATETIME NOT NULL',
));
}
public function down()
{
$this->dropTable('user');
}
/*
// Use safeUp/safeDown to do migration with transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
} | davidgraig/HootBook | www/protected/migrations/m130906_033817_add_user_table.php | PHP | unlicense | 544 |
/**
* A dock
* @param {Object} The options
* @constructor
*/
hui.ui.IFrame = function(options) {
this.options = options;
this.element = hui.get(options.element);
this.name = options.name;
hui.ui.extend(this);
};
hui.ui.IFrame.prototype = {
/** Change the url of the iframe
* @param {String} url The url to change the iframe to
*/
setUrl : function(url) {
this.element.setAttribute('src',url);
//hui.frame.getDocument(this.element).location.href=url;
},
clear : function() {
this.setUrl('about:blank');
},
getDocument : function() {
return hui.frame.getDocument(this.element);
},
getWindow : function() {
return hui.frame.getWindow(this.element);
},
reload : function() {
this.getWindow().location.reload();
},
show : function() {
this.element.style.display='';
},
hide : function() {
this.element.style.display='none';
}
}; | Humanise/hui | js/IFrame.js | JavaScript | unlicense | 904 |
namespace LearningInterpreter.Basic.Code.Statements
{
using System;
using LearningInterpreter.Parsing;
using LearningInterpreter.RunTime;
public class Remove : IStatement
{
public Range Range { get; private set; }
public Remove(Range range)
{
if (range == Range.Undefined)
throw new ArgumentException(ErrorMessages.RemoveMissingRange, "range");
Range = range;
}
public EvaluateResult Execute(IRunTimeEnvironment rte)
{
int start;
int count;
Range.GetBounds(rte, out start, out count);
rte.RemoveRange(start, count);
var message = string.Format(Messages.RemoveResult, count);
return new EvaluateResult(message);
}
public override string ToString()
{
return "REMOVE " + Range.ToString();
}
}
}
| markshevchenko/learning-interpreter | LearningInterpreter.Basic/Code/Statements/Remove.cs | C# | unlicense | 930 |
import React from 'react'
import { Button } from 'styled-mdl'
const demo = () => <Button raised>Raised</Button>
const caption = 'Raised Button'
const code = '<Button raised>Raised</Button>'
export default { demo, caption, code }
| isogon/styled-mdl-website | demos/buttons/demos/raised-default.js | JavaScript | unlicense | 231 |
require "spec_helper"
describe Spira do
context "inheritance" do
before :all do
class ::InheritanceItem < Spira::Base
property :title, :predicate => DC.title, :type => String
has_many :subtitle, :predicate => DC.description, :type => String
type SIOC.Item
end
class ::InheritancePost < ::InheritanceItem
type SIOC.Post
property :creator, :predicate => DC.creator
property :subtitle, :predicate => DC.description, :type => String
end
class ::InheritedType < ::InheritanceItem
end
class ::InheritanceForumPost < ::InheritancePost
end
class ::InheritanceContainer < Spira::Base
type SIOC.Container
has_many :items, :type => 'InheritanceItem', :predicate => SIOC.container_of
end
class ::InheritanceForum < ::InheritanceContainer
type SIOC.Forum
#property :moderator, :predicate => SIOC.has_moderator
end
end
context "when redeclaring a property in a child" do
let(:item) {RDF::URI('http://example.org/item').as(InheritanceItem)}
let(:post) {RDF::URI('http://example.org/post').as(InheritancePost)}
before {Spira.repository = RDF::Repository.new}
it "should override the property on the child" do
expect(post.subtitle).to be_nil
expect(post).not_to respond_to(:subtitle_ids)
end
it "should not override the parent property" do
expect(item.subtitle).to be_empty
expect(item).to respond_to(:subtitle_ids)
end
end
context "when passing properties to children" do
let(:item) {RDF::URI('http://example.org/item').as(InheritanceItem)}
let(:post) {RDF::URI('http://example.org/post').as(InheritancePost)}
let(:type) {RDF::URI('http://example.org/type').as(InheritedType)}
let(:forum) {RDF::URI('http://example.org/forum').as(InheritanceForumPost)}
before {Spira.repository = RDF::Repository.new}
it "should respond to a property getter" do
expect(post).to respond_to :title
end
it "should respond to a property setter" do
expect(post).to respond_to :title=
end
it "should respond to a propety getter on a grandchild class" do
expect(forum).to respond_to :title
end
it "should respond to a propety setter on a grandchild class" do
expect(forum).to respond_to :title=
end
it "should maintain property metadata" do
expect(InheritancePost.properties).to have_key :title
expect(InheritancePost.properties[:title][:type]).to eql Spira::Types::String
end
it "should add properties of child classes" do
expect(post).to respond_to :creator
expect(post).to respond_to :creator=
expect(InheritancePost.properties).to have_key :creator
end
it "should allow setting a property" do
post.title = "test title"
expect(post.title).to eql "test title"
end
it "should inherit an RDFS type if one is not given" do
expect(InheritedType.type).to eql RDF::SIOC.Item
end
it "should overwrite the RDFS type if one is given" do
expect(InheritancePost.type).to eql RDF::SIOC.Post
end
it "should inherit an RDFS type from the most recent ancestor" do
expect(InheritanceForumPost.type).to eql RDF::SIOC.Post
end
it "should not define methods on parents" do
expect(item).not_to respond_to :creator
end
it "should not modify the properties of the base class" do
expect(Spira::Base.properties).to be_empty
end
context "when saving properties" do
before :each do
post.title = "test title"
post.save!
type.title = "type title"
type.save!
forum.title = "forum title"
forum.save!
end
it "should save an edited property" do
expect(InheritancePost.repository.query(:subject => post.uri, :predicate => RDF::DC.title).count).to eql 1
end
it "should save an edited property on a grandchild class" do
expect(InheritanceForumPost.repository.query(:subject => forum.uri, :predicate => RDF::DC.title).count).to eql 1
end
it "should save the new type" do
expect(InheritancePost.repository.query(:subject => post.uri, :predicate => RDF.type, :object => RDF::SIOC.Post).count).to eql 1
end
it "should not save the supertype for a subclass which has specified one" do
expect(InheritancePost.repository.query(:subject => post.uri, :predicate => RDF.type, :object => RDF::SIOC.Item).count).to eql 0
end
it "should save the supertype for a subclass which has not specified one" do
expect(InheritedType.repository.query(:subject => type.uri, :predicate => RDF.type, :object => RDF::SIOC.Item).count).to eql 1
end
end
end
end
describe "multitype classes" do
before do
class MultiTypeThing < Spira::Base
type SIOC.Item
type SIOC.Post
end
class InheritedMultiTypeThing < MultiTypeThing
end
class InheritedWithTypesMultiTypeThing < MultiTypeThing
type SIOC.Container
end
end
it "should have multiple types" do
types = Set.new [RDF::SIOC.Item, RDF::SIOC.Post]
expect(MultiTypeThing.types).to eql types
end
it "should inherit multiple types" do
expect(InheritedMultiTypeThing.types).to eql MultiTypeThing.types
end
it "should overwrite types" do
types = Set.new << RDF::SIOC.Container
expect(InheritedWithTypesMultiTypeThing.types).to eql types
end
context "when saved" do
before do
@thing = RDF::URI('http://example.org/thing').as(MultiTypeThing)
@thing.save!
end
it "should store multiple classes" do
expect(MultiTypeThing.repository.query(:subject => @thing.uri, :predicate => RDF.type, :object => RDF::SIOC.Item).count).to eql 1
expect(MultiTypeThing.repository.query(:subject => @thing.uri, :predicate => RDF.type, :object => RDF::SIOC.Post).count).to eql 1
end
end
end
context "base classes" do
before :all do
class ::BaseChild < Spira::Base ; end
end
it "should have access to Spira DSL methods" do
expect(BaseChild).to respond_to :property
expect(BaseChild).to respond_to :base_uri
expect(BaseChild).to respond_to :has_many
expect(BaseChild).to respond_to :default_vocabulary
end
end
end
| PerfectMemory/spira | spec/inheritance_spec.rb | Ruby | unlicense | 6,587 |
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Unity;
using Poseidon.BackOffice.Common;
using Poseidon.BackOffice.Module.Ums.Modules;
using Poseidon.BackOffice.Module.Ums.ViewModels;
using Poseidon.BackOffice.Module.Ums.Views;
namespace Poseidon.BackOffice.Module.Ums
{
public class UmsModule : IModule
{
readonly IUnityContainer _container;
public UmsModule(IUnityContainer container)
{
_container = container;
}
public void Initialize()
{
_container.RegisterType<UmsOfficeModule>(new ContainerControlledLifetimeManager());
_container.RegisterType<IOfficeModule, UserModule>(UserModule.Name);
_container.RegisterType<IOfficeModule, UserRoleModule>(UserRoleModule.Name);
_container.RegisterType<object, UserRolesView>(View.UserRolesView);
_container.RegisterType<object, UsersView>(View.UsersView);
_container.RegisterType<object, UmsModuleView>(View.ModuleView);
_container.RegisterType<UserRolesViewModel>();
_container.RegisterType<UsersViewModel>();
}
}
} | Slesa/Poseidon | old/src/2nd/BackOffice.Module.Ums/UmsModule.cs | C# | unlicense | 1,200 |
#!/usr/bin/env python
#This is free and unencumbered software released into the public domain.
#Anyone is free to copy, modify, publish, use, compile, sell, or
#distribute this software, either in source code form or as a compiled
#binary, for any purpose, commercial or non-commercial, and by any
#means.
#In jurisdictions that recognize copyright laws, the author or authors
#of this software dedicate any and all copyright interest in the
#software to the public domain. We make this dedication for the benefit
#of the public at large and to the detriment of our heirs and
#successors. We intend this dedication to be an overt act of
#relinquishment in perpetuity of all present and future rights to this
#software under copyright law.
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
#OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
#ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#OTHER DEALINGS IN THE SOFTWARE.
#For more information, please refer to <http://unlicense.org/>
#This is a python program that will open up a random url from a list
#It was a weird project for me to come up with
#Devloper: Matthew Deig
#Date: 2014-11-03
import webbrowser, random
from optparse import OptionParser
def argParser():
#this will return 2 objects
#the options and args
parser = OptionParser()
parser.add_option("-a", "--add", dest="newurl", help="Adds a new url to the list", metavar="NEWURL")
parser.add_option("-q", "--nobrowser", action="store_true", dest="nobrowser", help="Does not open a broswer just prints the url out")
return parser.parse_args()
def openBroswer(url):
webbrowser.open_new_tab(url)
def addUrl(url):
file = open("url.db", "a")
file.write(url+"\n")
file.close()
def readUrls():
file = open("url.db", "r")
urls = file.readlines()
file.close()
return urls
def pickUrl(urls):
#this is probley not very random but it is going to work
return random.choice(urls)
if __name__ == "__main__":
(options, args) = argParser()
if options.newurl is not None:
addUrl(options.newurl)
else:
if(options.nobrowser):
print(pickUrl(readUrls()))
else:
openBroswer(pickUrl(readUrls()))
| notptr/randURL | ranurl.py | Python | unlicense | 2,503 |
#ifndef SWZ_LINKED_LIST
#define SWZ_LINKED_LIST
namespace{
#include <iostream>
}
template<typename T>
class double_linked_list_node{
public:
explicit double_linked_list_node(T* value);
explicit double_linked_list_node(T value);
~double_linked_list_node() = default;
T* key;
double_linked_list_node *prev;
double_linked_list_node *next;
double_linked_list_node *&right = next;
double_linked_list_node *&left = prev;
};
template<typename T>
class double_linked_list{
public:
double_linked_list(void);
~double_linked_list(void);
const size_t& len(void);
void list_insert(double_linked_list_node<T>* x);
void list_insert(T* value);
void list_insert(T value);
void list_insert(double_linked_list<T> &list);
void list_insert_left(double_linked_list_node<T>* f,double_linked_list_node<T>* x);
void list_insert_left(double_linked_list_node<T>* f,T* value);
void list_insert_left(double_linked_list_node<T>* f,T value);
void list_insert_left(double_linked_list_node<T>* f,double_linked_list<T> &list);
void list_insert_right(double_linked_list_node<T> *f,double_linked_list_node<T>* x);
void list_insert_right(double_linked_list_node<T> *f,T* value);
void list_insert_right(double_linked_list_node<T> *f,T value);
void list_insert_right(double_linked_list_node<T> *f,double_linked_list<T> &list);
double_linked_list_node<T>* list_search(T *k);
double_linked_list_node<T>* list_search(T k);
double_linked_list_node<T>* list_search(double_linked_list_node<T> *k);
double_linked_list_node<T>* list_head(void);
bool list_delete(double_linked_list_node<T>* x);
bool list_delete(T* value);
bool list_delete(T value);
void list_clear(void); // It maybe cause memory leaking....
void list_destroy(void);
void list_print(void);
protected:
size_t length;
double_linked_list_node<T> *head;
};
template<typename T>
double_linked_list_node<T>::double_linked_list_node(T *value)
:key(value),prev(nullptr),next(nullptr){
}
template<typename T>
double_linked_list_node<T>::double_linked_list_node(T value)
:prev(nullptr),next(nullptr){
this->key = new T(value);
}
template<typename T>
double_linked_list<T>::double_linked_list(void){
this->head = nullptr;
this->length = 0;
}
template<typename T>
double_linked_list<T>::~double_linked_list(void){
this->list_destroy();
}
template<typename T>
inline double_linked_list_node<T>* double_linked_list<T>::list_head(void){
return this->head;
}
template<typename T>
inline void double_linked_list<T>::list_clear(void){
this->length = 0;
this->head = nullptr;
}
template<typename T>
void double_linked_list<T>::list_destroy(void){
if(this->length == 0)
return;
double_linked_list_node<T>* curr = nullptr;
double_linked_list_node<T>* x = this->head;
size_t len = this->length;
this->list_clear();
for(int i=0;i<len;++i){
curr = x;
x = curr->next;
delete curr;
}
x = nullptr;
curr = nullptr;
}
template<typename T>
inline const size_t& double_linked_list<T>::len(void){
return this->length;
}
template<typename T>
void double_linked_list<T>::list_insert_left(double_linked_list_node<T>* fiducial_node,
double_linked_list_node<T>* x){
if(this->head == nullptr){
this->head = x;
x->prev = x;
x->next = x;
this->length = 1;
return;
}
if(fiducial_node == nullptr){
auto y = this->head->left;
x->left = y;
x->right = this->head;
this->head->left = x;
y->right = x;
}else{
if(!this->list_search(fiducial_node))
return;
auto y = fiducial_node->left;
x->left = y;
x->right = fiducial_node;
fiducial_node->left = x;
y->right = x;
}
++this->length;
return;
}
template<typename T>
inline void double_linked_list<T>::list_insert_left(double_linked_list_node<T>* fiducial_node,
T *value){
auto x = new double_linked_list_node<T>(value);
return this->list_insert_left(fiducial_node,x);
}
template<typename T>
inline void double_linked_list<T>::list_insert_left(double_linked_list_node<T>* fiducial_node,
T value){
auto x = new double_linked_list_node<T>(value);
return this->list_insert_left(fiducial_node,x);
}
template<typename T>
void double_linked_list<T>::list_insert_left(double_linked_list_node<T>* f,
double_linked_list<T> &list){
if(list.len() == 0)
return;
auto x = list.list_head();
if(this->length == 0){
this->head = x;
this->length = list.len();
list.list_clear();
return;
}
auto t = f;
if(f == nullptr)
t = this->head;
else
if(!this->list_search(f))
return;
this->length += list.len();
list.list_clear();
auto y = t->left;
auto z = x->right;
y->right = z;
z->left = y;
x->right = t;
t->left = x;
}
template<typename T>
void double_linked_list<T>::list_insert_right(double_linked_list_node<T>* f,
double_linked_list<T> &list){
if(list.len() == 0)
return;
auto x = list.list_head();
if(this->length == 0){
this->head = x;
this->length = list.len();
list.clear();
return;
}
auto t = f;
if(f == nullptr)
t = this->head;
else
if(!this->list_search(f))
return;
this->length += list.len();
list.list_clear();
auto y = t->right;
auto z = x->right;
y->left = x;
z->left = t;
x->right = y;
t->right = z;
}
template<typename T>
void double_linked_list<T>::list_insert_right(double_linked_list_node<T>* fiducial_node,
double_linked_list_node<T>* x){
if(this->head == nullptr){
this->head = x;
x->prev = x;
x->next = x;
this->length = 1;
return;
}
if(fiducial_node == nullptr){
auto y = this->head->right;
x->right = y;
x->left = this->head;
this->head->right = x;
y->left = x;
}else{
if(!this->list_search(fiducial_node))
return;
auto y = fiducial_node->right;
x->right = y;
x->left = fiducial_node;
fiducial_node->right = x;
y->left = x;
}
++this->length;
return;
}
template<typename T>
inline void double_linked_list<T>::list_insert_right(double_linked_list_node<T>* fiducial_node,
T *value){
auto x = new double_linked_list_node<T>(value);
return this->list_insert_right(fiducial_node,x);
}
template<typename T>
inline void double_linked_list<T>::list_insert_right(double_linked_list_node<T>* fiducial_node,
T value){
auto x = new double_linked_list_node<T>(value);
return this->list_insert_right(fiducial_node,x);
}
template<typename T>
inline void double_linked_list<T>::list_insert(double_linked_list_node<T>* x){
this->list_insert_left(nullptr,x);
}
template<typename T>
inline void double_linked_list<T>::list_insert(T* value){
auto x = new double_linked_list_node<T>(value);
return this->list_insert(x);
}
template<typename T>
inline void double_linked_list<T>::list_insert(T value){
auto x = new double_linked_list_node<T>(value);
return this->list_insert(x);
}
template<typename T>
void double_linked_list<T>::list_insert(double_linked_list<T> &list){
if(list.len() == 0)
return;
auto x = list.list_head();
if(this->length == 0){
this->head = x;
}else{
auto n = this->head->next;
auto p = x->prev;
this->head->next = p;
p->prev = this->head;
n->prev = x;
x->next = n;
}
this->length += list.len();
list.list_clear();
}
template<typename T>
double_linked_list_node<T>* double_linked_list<T>::list_search(T* value){
if(value == nullptr)
return nullptr;
if(this->head->key == value)
return this->head;
for(auto x=this->head->next;x!=this->head;x=x->next)
if(x->key == value)
return x;
return nullptr;
}
template<typename T>
double_linked_list_node<T>* double_linked_list<T>::list_search(T value){
if(*(this->head->key) == value)
return this->head;
for(auto x=this->head->next;x!=this->head;x=x->next)
if(*(x->key) == value)
return x;
return nullptr;
}
template<typename T>
double_linked_list_node<T>* double_linked_list<T>::list_search(double_linked_list_node<T>*value){
if(value == nullptr)
return nullptr;
if(this->head == value)
return this->head;
for(auto x=this->head->next;x!=this->head;x=x->next)
if(x == value)
return x;
return nullptr;
}
template<typename T>
bool double_linked_list<T>::list_delete(double_linked_list_node<T> *x){
if(this->length == 0)
return false;
if(this->list_search(x)){
if(x == this->head)
this->head = x->next;
if(this->length == 1)
this->head = nullptr;
x->next->prev = x->prev;
x->prev->next = x->next;
delete x;
--this->length;
return true;
}
return false;
}
template<typename T>
inline bool double_linked_list<T>::list_delete(T *value){
return this->list_delete(this->list_search(value));
}
template<typename T>
inline bool double_linked_list<T>::list_delete(T value){
return this->list_delete(this->list_search(value));
}
template<typename T>
void double_linked_list<T>::list_print(void){
auto x=this->head;
std::cout << "----LIST_PRINT_START----" << std::endl;
std::cout << "List has " << this->length << " members" << std::endl;
for(int i=0;i<this->length;++i){
std::cout << "Number: "<< i << " : " << *(x->key) << std::endl;
x = x->next;
}
std::cout << "----LIST_PRINT_END------" << std::endl;
}
#endif
| Trickness/pl_learning | Algorithms/cpp/linked_list/double_linked_list.hpp | C++ | unlicense | 10,110 |
<?php
namespace Bamarni\Omnipay\Saferpay\Business\Message;
use Omnipay\Common\Exception\InvalidRequestException;
class CompleteAuthorizeRequest extends AbstractRequest
{
public function getData()
{
$this->validate('accountId', 'spPassword', 'amount');
$data = [
'ACCOUNTID' => $this->getAccountId(),
'spPassword' => $this->getSpPassword(),
'AMOUNT' => $this->getAmountInteger(),
'CURRENCY' => $this->getCurrency(),
'NAME' => $this->getCardHolderName(),
'IBAN' => $this->getIban(),
'MANDATEID' => $this->getMandateId(),
];
if ($card = $this->getCard()) {
$data['PAN'] = $card->getNumber();
$data['EXP'] = $card->getExpiryDate('my');
$data['CVC'] = $card->getCvv();
} elseif (!$data['IBAN']) {
$this->validate('bankCode', 'bankAccountNumber');
$data['TRACK2'] = ';59'.$this->getBankCode().'='.$this->getBankAccountNumber();
}
if (!$card && !$data['IBAN'] && !$data['TRACK2']) {
throw new InvalidRequestException(
'Either a "card", "IBAN" or a "bank code"/"bank account number" pair is required'
);
}
return $data;
}
public function getMandateId()
{
return $this->getParameter('mandateId');
}
public function setMandateId($value)
{
return $this->setParameter('mandateId', $value);
}
public function getCardHolderName()
{
return htmlspecialchars_decode($this->getParameter('cardHolderName'));
}
public function setCardHolderName($value)
{
return $this->setParameter('cardHolderName', htmlspecialchars($value));
}
public function getIBAN()
{
return $this->getParameter('IBAN');
}
public function setIBAN($value)
{
return $this->setParameter('IBAN', $value);
}
public function getBankCode()
{
return $this->getParameter('bankCode');
}
public function setBankCode($value)
{
return $this->setParameter('bankCode', $value);
}
public function getBankAccountNumber()
{
return $this->getParameter('bankAccountNumber');
}
public function setBankAccountNumber($value)
{
return $this->setParameter('bankAccountNumber', $value);
}
protected function getEndpoint()
{
return 'https://www.saferpay.com/hosting/execute.asp';
}
protected function createResponse($response)
{
return new CompleteAuthorizeResponse($this, $response);
}
}
| bamarni/omnipay-saferpay-business | src/Message/CompleteAuthorizeRequest.php | PHP | unlicense | 2,642 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->nullable();
$table->string('uuid');
$table->string('label', 250);
$table->string('path');
$table->string('password')->nullable()->default(null);
$table->string('plain_password', 400)->nullable()->default(null);
$table->boolean('is_private')->default(false);
$table->dateTime('expired_at')->nullable()->default(null);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('files');
}
}
| arvernester/file-sharing | database/migrations/2017_05_23_054056_create_files_table.php | PHP | unlicense | 1,035 |
<?php
namespace AppBundle\Services;
class TestService
{
public function sayHello()
{
return "hello from test service!";
}
} | Kolbasyatin/IFS | src/AppBundle/Services/TestService.php | PHP | unlicense | 147 |
package com.communitysurvivalgames.thesurvivalgames.command.standalone;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.communitysurvivalgames.thesurvivalgames.exception.ArenaNotFoundException;
import com.communitysurvivalgames.thesurvivalgames.managers.SGApi;
import com.communitysurvivalgames.thesurvivalgames.objects.SGArena;
public class SponsorCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (!(sender instanceof Player))
return false;
Player p = (Player) sender;
try {
SGArena a = SGApi.getArenaManager().getArena(p);
if (a.players.contains(p.getName())) {
p.sendMessage(ChatColor.RED + "You must be dead to sponsor players");
} else {
SGApi.getSponsorManager(a).sponsor(p);
}
} catch (ArenaNotFoundException e) {
p.sendMessage(ChatColor.RED + "You must be in a game to use that");
}
return false;
}
}
| SurvivalGamesDevTeam/TheSurvivalGames | src/main/java/com/communitysurvivalgames/thesurvivalgames/command/standalone/SponsorCommand.java | Java | unlicense | 1,102 |
#!/usr/bin/env python
"""Ensure that invalid files (non-episodes) are not renamed
"""
from functional_runner import run_tvnamer, verify_out_data
from helpers import attr
@attr("functional")
def test_simple_single_file():
"""Boring example
"""
out_data = run_tvnamer(
with_files = ['Some File.avi'],
with_flags = ["--batch"])
expected_files = ['Some File.avi']
verify_out_data(out_data, expected_files, expected_returncode = 2)
@attr("functional")
def test_no_series_name():
"""File without series name should be skipped (unless '--name=MySeries' arg is supplied)
"""
out_data = run_tvnamer(
with_files = ['s01e01 Some File.avi'],
with_flags = ["--batch"])
expected_files = ['s01e01 Some File.avi']
verify_out_data(out_data, expected_files, expected_returncode = 2)
@attr("functional")
def test_ambigious():
invalid_files = [
'show.123.avi', # Maybe s01e23 but too ambigious. #140
'Scrubs.0101.avi', # Ambigious. #140
]
for f in invalid_files:
out_data = run_tvnamer(
with_files = [f],
with_flags = ["--batch"])
expected_files = [f]
verify_out_data(out_data, expected_files, expected_returncode = 2)
| dbr/tvnamer | tests/test_invalid_files.py | Python | unlicense | 1,264 |
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#include <SDL/SDL.h>
#include <iostream>
#include <ctime>
using namespace std; // This is needed for the game to work.
#include"Table.h"
int ask();
int ask()
{
print("Do thy wish to play again ?");
string input = "";
while (true) {
cout << "Press y for yes and anything else for no: ";
getline(cin, input);
//stringstream myStream(input);
if (input == "y")//(myStream >> num && num<deck[x].getSize() && num>=0)
return 1;
return 0;
}
}
int main()
{
// xxxxx Initialisation de variables xxxxx//
Table table;
int play = 1; // Vaut 1 de base, on assume que le jou
bool end = false; // Vrai si la partie est finie
int player; // Contient le numéro du joueur jouant
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
while(play == 1) // tant que le joueur veut jouer
{
table.init(); // On initialise la table de jeu
end = false;
player = table.compD(3,4); // Le joueur sera celui qui a la plus petite valeur de deck
while(end!=true) // Tant que la partie n'est pas finie
{
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
table.drawCard(player);
table.printTable(player); // On affiche la table de jeu
//print(player);
table.putCardDown(player); // On demande au joueur la carte qu'il veut jouer
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
table.printTable(player);
//print(player);
//
if(table.compD(3,4) == player)
{
print("Player "+to_string(player)+" has lost.");
end=true;
}
else
{
if (player==1)
player = 2;
else
player = 1;
}
}
play = ask();
}
} | Raspberrymonster/Blade | blade.cpp | C++ | unlicense | 1,707 |
package com.lunaticedit.legendofwaffles.implementations.stageobject;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.lunaticedit.legendofwaffles.contracts.Processable;
import com.lunaticedit.legendofwaffles.contracts.Renderable;
import com.lunaticedit.legendofwaffles.contracts.StageObject;
import com.lunaticedit.legendofwaffles.factories.RepositoryFactory;
import com.lunaticedit.legendofwaffles.helpers.Constants;
import com.lunaticedit.legendofwaffles.helpers.Dimension;
import com.lunaticedit.legendofwaffles.helpers.Point;
import com.lunaticedit.legendofwaffles.physics.HitHandler;
import com.lunaticedit.legendofwaffles.physics.HitWatcher;
import com.lunaticedit.legendofwaffles.physics.Physics;
import org.w3c.dom.Element;
public class Door implements StageObject, Renderable, Processable, HitHandler {
private boolean _opened;
private int _posX;
private int _posY;
private Body _body;
private HitWatcher _hitWatcher;
private long _openTime;
private int _curFrame;
@Override
public void processXML(final Element element) {
_posX = (Integer.parseInt(element.getAttribute("x")));
_posY = (Integer.parseInt(element.getAttribute("y"))) - 8;
_opened = false;
_curFrame = 0;
initializePhysics();
(new RepositoryFactory()).generate().getObjects().add(this);
}
@Override
public void process() {
if (!_opened) { return; }
if (_opened && ((System.currentTimeMillis() - _openTime) >= 5000)) {
final long timeDiff = (System.currentTimeMillis() - _openTime);
if (timeDiff < 5100) { _curFrame = 4; return; }
if (timeDiff < 5200) { _curFrame = 3; return; }
if (timeDiff < 5300) { _curFrame = 2; return; }
if (timeDiff < 5400) { _curFrame = 1; return; }
_curFrame = 0;
_opened = false;
initializePhysics();
return;
}
if (_opened && ((System.currentTimeMillis() - _openTime) >= 500)) {
if (_curFrame == -1) { return; }
_curFrame = -1;
finalizePhysics();
return;
}
final long timeDiff = (System.currentTimeMillis() - _openTime);
if (timeDiff < 100) { _curFrame = 1; return; }
if (timeDiff < 200) { _curFrame = 2; return; }
if (timeDiff < 300) { _curFrame = 3; return; }
if (timeDiff < 400) { _curFrame = 4; return; }
_curFrame = 5;
}
@Override
public int getX() {
return _posX;
}
@Override
public int getY() {
return _posY;
}
@Override
public boolean getVisible() {
return (_curFrame != -1);
}
@Override
public Dimension getTileSize() {
return new Dimension(1,2);
}
@Override
public Point getTileOrigin() {
switch(_curFrame) {
case 1: return new Point(9, 19);
case 2: return new Point(10, 19);
case 3: return new Point(11, 19);
case 4: return new Point(12, 19);
case 5: return new Point(13, 19);
default: return new Point(8, 19);
}
}
@Override
public void hitOccurred(final Body body1, final Body body2) {
if (_opened) { return; }
if (!(new RepositoryFactory()).generate().getPlayer().involved(body1, body2)) { return; }
_opened = true;
_openTime = System.currentTimeMillis();
}
private void initializePhysics() {
final float meterSize = Physics.toMeters(Constants.TileSize);
final float halfTile = meterSize / 2.0f;
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(
(meterSize * (_posX / Constants.TileSize)) - halfTile,
(meterSize * (_posY / Constants.TileSize)) - meterSize);
_body = Physics.getInstance().createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox(halfTile, meterSize);
_body.createFixture(groundBox, 0.0f);
_hitWatcher = new HitWatcher(this, _body);
Physics.getInstance().registerHitWacher(_hitWatcher);
}
private void finalizePhysics() {
Physics.getInstance().removeHitWatcher(_hitWatcher);
_hitWatcher = null;
Physics.getInstance().removeBody(_body);
_body = null;
}
}
| essial/legend-of-waffles | Main/src/com/lunaticedit/legendofwaffles/implementations/stageobject/Door.java | Java | unlicense | 4,470 |
using System;
using System.Windows.Controls;
namespace _11_Screens.Framework.Controls
{
public class CustomTransitionControl : ContentControl
{
public event EventHandler ContentChanged = delegate { };
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
ContentChanged(this, EventArgs.Empty);
}
}
} | Slesa/Poseidon | sketches/wpf/caliburn/11_Screens/Framework/Controls/CustomTransitionControl.cs | C# | unlicense | 464 |
package de.protubero.ajs;
import org.junit.Test;
import static de.protubero.ajs.Helpers.namedPerson;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.*;
public class PersonStoreTest {
@Test
public void shouldBeAbleToStoreKnownPerson() {
PersonStore ps = new PersonStore();
Person p = ps.insert(namedPerson("Fred"));
assertThat(p.getId(), equalTo(1));
// access directly
assertTrue(ps.selectById(1).isPresent());
assertThat(ps.selectById(1).get().getName(), equalTo("Fred"));
// access again, via selectAll
assertNotNull(ps.selectAll().get(0));
assertEquals(ps.selectAll().size(), 1);
assertThat(ps.selectAll().get(0).getName(), equalTo("Fred"));
}
@Test
public void shouldBeAbleToDeleteKnownPerson() {
PersonStore ps = new PersonStore();
Person p = ps.insert(namedPerson("Fred"));
assertThat(p.getId(), equalTo(1));
ps.delete(1);
assertFalse(ps.selectById(1).isPresent());
}
}
| protubero/angular-jooby-starter | server/src/test/java/de/protubero/ajs/PersonStoreTest.java | Java | unlicense | 1,060 |
package collection
import (
"github.com/karousel/core/album"
gorp "gopkg.in/gorp.v1"
)
type Store struct {
Database *gorp.DbMap
}
func NewStore(database *gorp.DbMap) (Store, error) {
store := Store{
Database: database,
}
return store, nil
}
func (store Store) Add(collection *Collection) error {
err := store.Database.Insert(collection)
return err
}
func (store Store) GetById(id int64) (Collection, error) {
var collection Collection
err := store.Database.SelectOne(&collection, "select * from collections where id=$1", id)
return collection, err
}
func (store Store) GetAll() ([]Collection, error) {
var collections []Collection
_, err := store.Database.Select(&collections, "select * from collections order by id")
return collections, err
}
func (store Store) Delete(collection *Collection) (int64, error) {
count, err := store.Database.Delete(collection)
return count, err
}
func (store Store) Update(collection *Collection) (int64, error) {
count, err := store.Database.Update(collection)
return count, err
}
func (store Store) Size() (int64, error) {
size, err := store.Database.SelectInt("select count(*) from collections")
return size, err
}
func (store Store) GetAlbumsForCollection(collection *Collection) ([]album.Album, error) {
var albums []album.Album
_, err := store.Database.Select(&albums, "select * from albums where collection_id=$1", collection.Id)
return albums, err
}
| karousel/core | collection/store.go | GO | unlicense | 1,437 |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Schedule.Models.ViewModels
{
public class ConflictsViewModel : BaseViewModel
{
private object item;
private string description;
private ObservableCollection<ConflictsViewModel> children;
public ConflictsViewModel()
{
children = new ObservableCollection<ConflictsViewModel>();
}
public object Item
{
get { return item; }
set
{
item = value;
OnPropertyChanged();
}
}
public string Description
{
get { return description; }
set
{
description = value;
OnPropertyChanged();
}
}
public ObservableCollection<ConflictsViewModel> Children
{
get { return children; }
set
{
children = value;
OnPropertyChanged();
}
}
}
}
| surenkov/Schedule | Schedule/Models/ViewModels/ConflictsViewModel.cs | C# | unlicense | 1,084 |
<?php
require_once dirname(__FILE__) . '/latproc.php';
$property_list = get_iod_property_list(array('name','msg','id','type','blink', 'textcolor', 'textsize'), array('type','id'));
var_dump($property_list);
?>
| latproc/modbus-cmore-scripts | lib/iodProcess.php | PHP | unlicense | 219 |
package com.ushaqi.zhuishushenqi.widget;
import android.app.AlertDialog;
import android.content.Context;
import android.support.design.widget.am;
import android.util.AttributeSet;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.arcsoft.hpay100.a.a;
import com.ushaqi.zhuishushenqi.api.b;
import com.ushaqi.zhuishushenqi.model.Account;
import com.ushaqi.zhuishushenqi.model.Author;
import com.ushaqi.zhuishushenqi.model.PostComment;
import com.ushaqi.zhuishushenqi.model.PostComment.PostCommentReply;
import com.ushaqi.zhuishushenqi.ui.SmartImageView;
import com.ushaqi.zhuishushenqi.ui.post.AbsPostActivity;
import com.ushaqi.zhuishushenqi.ui.user.AuthLoginActivity;
import com.ushaqi.zhuishushenqi.util.e;
import com.ushaqi.zhuishushenqi.util.t;
import uk.me.lewisdeane.ldialogs.h;
public class CommentItemView extends HorizontalScrollView
implements View.OnClickListener
{
private int a;
private boolean b = true;
private boolean c = false;
private AbsPostActivity d;
private ViewGroup e;
private TextView f;
private b g = b.a();
private PostComment h;
private int i;
public CommentItemView(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
if (!isInEditMode())
{
if (!(paramContext instanceof AbsPostActivity))
throw new RuntimeException("Must be used in TopicDetailActivity");
this.d = ((AbsPostActivity)paramContext);
setHorizontalScrollBarEnabled(false);
this.a = this.d.getWindowManager().getDefaultDisplay().getWidth();
}
}
private static void a(View paramView, boolean paramBoolean)
{
if (paramBoolean);
for (int j = 8; ; j = 0)
{
paramView.setVisibility(j);
return;
}
}
private void a(TextView paramTextView, int paramInt)
{
StringBuilder localStringBuilder = new StringBuilder();
if (paramInt == 0);
for (Object localObject = ""; ; localObject = Integer.valueOf(paramInt))
{
paramTextView.setText(localObject + " 同感");
return;
}
}
private void a(boolean paramBoolean)
{
boolean bool = true;
int j = this.e.getWidth();
int m;
int k;
if (this.b)
{
m = -j;
k = 0;
if (!paramBoolean)
break label66;
smoothScrollTo(k - m, 0);
if (this.b)
break label61;
}
while (true)
{
this.b = bool;
return;
k = -j;
m = 0;
break;
label61: bool = false;
}
label66: scrollTo(k - m, 0);
if (!this.b);
while (true)
{
this.b = bool;
return;
bool = false;
}
}
private void c()
{
this.f.setCompoundDrawablesWithIntrinsicBounds(0, 2130837985, 0, 0);
int j = 1 + d().getLikeCount();
this.f.setTextColor(-2741204);
a(this.f, j);
}
private PostComment d()
{
return (PostComment)findViewById(2131493761).getTag();
}
public final void a()
{
if (!this.b)
a(true);
}
public final void a(PostComment paramPostComment, int paramInt)
{
this.h = paramPostComment;
this.i = paramInt;
SmartImageView localSmartImageView = (SmartImageView)findViewById(2131493761);
TextView localTextView1 = (TextView)findViewById(2131493764);
TextView localTextView2 = (TextView)findViewById(2131493765);
TextView localTextView3 = (TextView)findViewById(2131493769);
LinkifyTextView localLinkifyTextView = (LinkifyTextView)findViewById(2131493766);
TextView localTextView4 = (TextView)findViewById(2131493763);
TextView localTextView5 = (TextView)findViewById(2131493767);
View localView1 = findViewById(2131493759);
TextView localTextView6 = (TextView)findViewById(2131493772);
ImageView localImageView = (ImageView)findViewById(2131493762);
TextView localTextView7 = (TextView)findViewById(2131493432);
View localView2 = findViewById(2131493773);
label338: int j;
label367: String str2;
if (!am.m(getContext()))
{
localSmartImageView.setImageUrl(paramPostComment.getAuthor().getScaleAvatar(), 2130837614);
localSmartImageView.setTag(paramPostComment);
localTextView1.setText(paramPostComment.getAuthor().getNickname());
localTextView2.setText("lv." + paramPostComment.getAuthor().getLv());
localTextView3.setText(t.e(paramPostComment.getCreated()));
localLinkifyTextView.setLinkifyText(paramPostComment.getContent(), paramPostComment.getAuthor().isOfficial());
localTextView4.setText(paramPostComment.getFloor() + "楼");
PostComment.PostCommentReply localPostCommentReply = paramPostComment.getReplyTo();
if ((localPostCommentReply == null) || (localPostCommentReply.getAuthor() == null))
break label442;
Author localAuthor = localPostCommentReply.getAuthor();
a(localTextView5, false);
localTextView5.setText("回复 " + localAuthor.getNickname() + " (" + localPostCommentReply.getFloor() + "楼)");
localView1.getLayoutParams().width = this.a;
j = paramPostComment.getLikeCount();
if (!paramPostComment.isLikedInView())
break label451;
c();
if (!a.r(getContext(), "community_user_gender_icon_toggle"))
break label491;
str2 = paramPostComment.getAuthor().getGender();
a(localImageView, false);
if (!"male".equals(str2))
break label462;
localImageView.setImageLevel(2);
}
while (true)
{
if (paramPostComment.get_id() != null)
break label561;
a(localTextView7, true);
a(localView2, true);
return;
localSmartImageView.setImageResource(2130837614);
break;
label442: a(localTextView5, true);
break label338;
label451: a(localTextView6, j);
break label367;
label462: if ("female".equals(str2))
{
localImageView.setImageLevel(3);
continue;
}
localImageView.setImageLevel(4);
continue;
label491: String str1 = paramPostComment.getAuthor().getType();
if ("official".equals(str1))
{
a(localImageView, false);
localImageView.setImageLevel(0);
continue;
}
if ("doyen".equals(str1))
{
a(localImageView, false);
localImageView.setImageLevel(1);
continue;
}
a(localImageView, true);
}
label561: a(localTextView7, false);
a(localView2, false);
}
public final void b()
{
if (!this.b)
a(false);
}
public final void b(PostComment paramPostComment, int paramInt)
{
a(paramPostComment, -1);
TextView localTextView = (TextView)findViewById(2131493768);
localTextView.setVisibility(0);
localTextView.setText(paramPostComment.getLikeCount() + "次同感");
}
public void onClick(View paramView)
{
switch (paramView.getId())
{
default:
case 2131493760:
case 2131493759:
case 2131493766:
case 2131493771:
case 2131493772:
Account localAccount;
do
{
return;
this.d.startActivity(e.a(paramView.getContext(), d().getAuthor()));
return;
ListView localListView = this.d.m();
for (int j = 0; j < localListView.getChildCount(); j++)
{
View localView = localListView.getChildAt(j);
if ((!(localView instanceof CommentItemView)) || (localView == this))
continue;
((CommentItemView)localView).a();
}
a(true);
return;
PostComment localPostComment2 = d();
this.d.a(localPostComment2.toRepliedInfo(), this.d.m().getHeaderViewsCount() + this.i);
return;
localAccount = am.e();
if (localAccount != null)
continue;
e.a(this.d, "请登录后再操作");
this.d.startActivity(AuthLoginActivity.a(this.d));
localAccount = null;
}
while (localAccount == null);
n localn = new n(this, 0);
String[] arrayOfString2 = new String[2];
arrayOfString2[0] = d().get_id();
arrayOfString2[1] = localAccount.getToken();
localn.b(arrayOfString2);
return;
case 2131493432:
}
PostComment localPostComment1 = d();
if (localPostComment1.getReplyTo() == null);
for (String[] arrayOfString1 = { "举报" }; ; arrayOfString1 = new String[] { "查看回复的楼层", "举报" })
{
h localh = new h(this.d);
localh.d = "更多";
localh.a(arrayOfString1, new l(this, arrayOfString1, localPostComment1)).a().show();
return;
}
}
protected void onFinishInflate()
{
super.onFinishInflate();
findViewById(2131493760).setOnClickListener(this);
findViewById(2131493759).setOnClickListener(this);
this.e = ((ViewGroup)findViewById(2131493770));
findViewById(2131493766).setOnClickListener(this);
findViewById(2131493771).setOnClickListener(this);
this.f = ((TextView)findViewById(2131493772));
this.f.setOnClickListener(this);
findViewById(2131493432).setOnClickListener(this);
}
public boolean onInterceptTouchEvent(MotionEvent paramMotionEvent)
{
return false;
}
public boolean onTouchEvent(MotionEvent paramMotionEvent)
{
switch (paramMotionEvent.getAction())
{
default:
return super.onTouchEvent(paramMotionEvent);
case 0:
}
return false;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.widget.CommentItemView
* JD-Core Version: 0.6.0
*/ | clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/widget/CommentItemView.java | Java | unlicense | 9,782 |
#include <iostream>
#include "FactorialIterator.cpp"
int main() {
FactorialIterator seq;
for ( ; !seq.isLast(); seq++ ) {
std::cout << *seq << std::endl;
}
std::cout << seq.value() << std::endl;
seq.reset();
std::cout << "seq.reset(): " << seq.value() << std::endl;
std::cout << "seq[20]: " << seq[20] << std::endl;
std::cout << "seq.value(): " << seq.value() << std::endl;
std::cout << "seq[0]: " << seq[0] << std::endl;
std::cout << "seq.value(): " << seq.value() << std::endl;
seq.goTo(10);
std::cout << "seq.goTo(10): " << seq.value() << std::endl;
seq.prev();
std::cout << "seq.prev(): " << seq.value() << std::endl;
seq.reset();
std::cout << "seq.reset(): " << seq.value() << std::endl;
return 0;
}
| KozyrOK/Study | 4week/1task/Iterators/Factorial/main.cpp | C++ | unlicense | 835 |
using Microsoft.ApplicationInsights;
using System;
using System.Diagnostics;
namespace PostSharp.Samples.Profiling
{
public static class ProfilingServices
{
private static readonly Stopwatch stopwatch = Stopwatch.StartNew();
internal static long GetTimestamp() => stopwatch.ElapsedTicks + 1;
public static long StartTimestamp { get; private set; }
public static bool IsEnabled => Publisher != null;
internal static SampleCollector Collector { get; } = new SampleCollector();
internal static MetricPublisher Publisher { get; private set; }
public static void Initialize(TelemetryClient client, TimeSpan publishPeriod)
{
Publisher = new MetricPublisher(Collector, client);
StartTimestamp = GetTimestamp();
Publisher.Start(publishPeriod);
}
public static void Uninitialize()
{
Publisher?.Dispose();
Publisher = null;
}
}
}
| postsharp/PostSharp.Samples | Framework/PostSharp.Samples.Profiling/ProfilingServices.cs | C# | unlicense | 951 |
const bcrypt = require("bcryptjs");
const Promise = require("bluebird");
const hashPasswordHook = require('./utils/hashPasswordHook');
const Op = require("sequelize").Op;
module.exports = function(sequelize, DataTypes) {
const log = require("logfilename")(__filename);
const models = sequelize.models;
const User = sequelize.define(
"User",
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
username: {
type: DataTypes.STRING(64),
unique: true,
allowNull: false
},
email: {
type: DataTypes.STRING(64),
unique: true,
allowNull: false
},
firstName: {
type: DataTypes.STRING(64),
field: "first_name"
},
lastName: {
type: DataTypes.STRING(64),
field: "last_name"
},
picture: {
type: DataTypes.JSONB
},
password: DataTypes.VIRTUAL,
passwordHash: {
type: DataTypes.TEXT,
field: "password_hash"
}
},
{
tableName: "users",
hooks: {
beforeCreate: hashPasswordHook,
beforeUpdate: hashPasswordHook
}
}
);
User.seedDefault = async function() {
let usersJson = require("./fixtures/users.json");
//log.debug("seedDefault: ", JSON.stringify(usersJson, null, 4));
for (let userJson of usersJson) {
await User.createUserInGroups(userJson, userJson.groups);
}
};
User.findByKey = async function(key, value) {
return this.findOne({
include: [
{
model: models.Profile,
as: "profile",
attributes: ["biography"]
},
{
model: models.AuthProvider,
as: "auth_provider",
attributes: ["name", "authId"]
}
],
where: { [key]: value },
attributes: ["id", "email", "username", "picture", "createdAt", "updatedAt"]
});
};
User.findByEmail = async function(email) {
return this.findByKey("email", email);
};
User.findByUserId = async function(userid) {
return this.findByKey("id", userid);
};
User.findByUsername = async function(userName) {
return this.findByKey("username", userName);
};
User.findByUsernameOrEmail = async function(username) {
return this.findOne({
where: {
[Op.or]: [{ email: username }, { username: username }]
}
});
};
User.createUserInGroups = async function(userJson, groups) {
log.debug("createUserInGroups user:%s, group: ", userJson, groups);
return sequelize
.transaction(async function(t) {
let userCreated = await models.User.create(userJson, {
transaction: t
});
const userId = userCreated.get().id;
await models.UserGroup.addUserIdInGroups(groups, userId, t);
//Create the profile
let profile = await models.Profile.create(
{ ...userJson.profile, user_id: userId },
{ transaction: t }
);
log.debug("profile created ", profile.get());
//Create the eventual authentication provider
if (userJson.authProvider) {
await models.AuthProvider.create(
{ ...userJson.authProvider, user_id: userId },
{ transaction: t }
);
}
/*
sqlite doesn't support this
await models.UserPending.destroy({
where: {
email: userJson.email
}
},{transaction: t});
*/
return userCreated;
})
.then(async userCreated => {
await models.UserPending.destroy({
where: {
email: userJson.email
}
});
return userCreated;
})
.catch(function(err) {
log.error("createUserInGroups: rolling back", err);
throw err;
});
};
User.checkUserPermission = async function(userId, resource, action) {
log.debug("Checking %s permission for %s on %s", action, userId, resource);
let where = {
resource: resource
};
where[action.toUpperCase()] = true;
let res = await this.findOne({
include: [
{
model: models.Group,
include: [
{
model: models.Permission,
where: where
}
]
}
],
where: {
id: userId
}
});
let authorized = res.Groups.length > 0 ? true : false;
return authorized;
};
User.getPermissions = function(username) {
return this.findOne({
include: [
{
model: models.Group,
include: [
{
model: models.Permission
}
]
}
],
where: {
username: username
}
});
};
User.prototype.comparePassword = function(candidatePassword) {
let me = this;
return new Promise(function(resolve, reject) {
let hashPassword = me.get("passwordHash") || "";
bcrypt.compare(candidatePassword, hashPassword, function(err, isMatch) {
if (err) {
return reject(err);
}
resolve(isMatch);
});
});
};
User.prototype.toJSON = function() {
let values = this.get({ clone: true });
delete values.passwordHash;
return values;
};
return User;
};
| FredericHeem/starhackit | server/src/plugins/users/models/UserModel.js | JavaScript | unlicense | 5,359 |
/**
* Created by charques on 23/8/16.
*/
'use strict';
var express = require('express');
var router = express.Router();
var User = require(__base + 'app/models/user');
var hash = require(__base + 'app/helpers/crypto');
router.get('/', function(req, res) {
User.find({}, function(err, users) {
res.json(users);
});
});
router.get('/:id', function(req, res) {
User.findById(req.params.id, function (err, user) {
if (err) {
throw err;
}
res.json(user);
});
});
router.post('/', function(req, res) {
// TODO validate input
// create a sample user
var user = new User({
email: req.body.email,
password: hash(req.body.password, req.app.get('secret-key')),
admin: req.body.admin
});
//var error = user.validateSync();
// save the sample user
user.save(function(err) {
if (err) {
throw err;
}
console.log('User saved successfully');
res.json({ success: true });
});
});
module.exports = router;
| charques/macrolayer | macrolayer-srv-login/app/controllers/users.js | JavaScript | unlicense | 1,068 |
/**
* @author Joe Azar
* @version 1.3.1
*
* v1.0 - Standard Build, all basic features
* v1.1 - Added linear drawing, optimized point selection code and drawing methods, updated GUI and overall look.
* v1.2 - Two new sizes, Pixel and Super-Sampled. Optimized sampling drawing algorithm.
* v1.3 - Added caching [about an 11% increase in generations/second].
* v1.3.1 - Patched bug where cached values [yes, I know how that sounds] would cause erratic life behavior. Also added ability to show cachedVals. Sped up drawing algorithm.
* v1.3.2 - Fully integrated Breesenham's line algorithm with Pixel and Super-Sampled grids. Much faster and more reliable.
* v1.4 - Cleaned up the code significantly, implemented more encapsulation.
*
* NOTE: fractals can be observed with these settings: (Sierpinski's Triangle [U|3 - O|7 - B|3]) (Squares[U|1 - O|8 - B|1])
* For drawing: [U|2 - O|6 - B|7]
* TODO: Boundless grid
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
@SuppressWarnings("serial")
public class CGOL_UI extends JFrame
{
GridManager tr = new GridManager();
int gX = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
int gY = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
static JSlider cVal1, cVal2, cVal3, brush;
static JLabel gen1, pop1, cVal1L, cVal2L, cVal3L, timingL, brushL;
static JButton step, reset;
static JToggleButton start, showCached;
static JTextField timing;
static JComboBox<?> grid;
int preX, preY;
boolean first = true;
boolean zoom = false;
String[] txts1 = { "Big", "Medium", "Small", "Tiny", "Eensy-Weensy", "Pixel", "Super-Sampled" };
public CGOL_UI()
{
setResizable(true);
setTitle("Conway's GOL");
setSize(gX, gY);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// --------------------------------------------------------------------
timing = new JTextField();
timing.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
try
{
tr.setDelay(Integer.parseInt(timing.getText().trim()));
timingL.setText("Delay (ms) [" + tr.getDelay() + "]: ");
repaint();
}
catch (Exception e)
{
System.out.println("Bad Input!");
}
finally
{
timing.setText("");
}
}
});
cVal1 = new JSlider(SwingConstants.HORIZONTAL, 1, 8, 2);
cVal1.setMajorTickSpacing(1);
cVal1.setPaintTicks(true);
cVal1.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
tr.setVal1(cVal1.getValue());
repaint();
}
});
cVal2 = new JSlider(SwingConstants.HORIZONTAL, 1, 8, 3);
cVal2.setMajorTickSpacing(1);
cVal2.setPaintTicks(true);
cVal2.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
tr.setVal2(cVal2.getValue());
repaint();
}
});
cVal3 = new JSlider(SwingConstants.HORIZONTAL, 1, 8, 3);
cVal3.setMajorTickSpacing(1);
cVal3.setPaintTicks(true);
cVal3.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
tr.setVal3(cVal3.getValue());
repaint();
}
});
step = new JButton("Step");
step.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
// tr.toggleStep();
//
tr.findIndexSmoothedII(1450, 0, 1450, 2000);
repaint();
}
});
reset = new JButton("Reset Grid");
reset.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
tr.setStart(false);
start.setSelected(false);
start.setText("Start");
try
{
Thread.sleep(100);
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
tr.reset();
repaint();
}
});
showCached = new JToggleButton("Show Cached");
showCached.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ev)
{
if (!tr.isSuperSampled())
{
if (ev.getStateChange() == ItemEvent.SELECTED)
{
tr.setUsingCached(true);
showCached.setText("Hide Cached");
}
else if (ev.getStateChange() == ItemEvent.DESELECTED)
{
tr.setUsingCached(false);
showCached.setText("Show Cached");
repaint();
}
}
else
{
if (ev.getStateChange() == ItemEvent.SELECTED)
{
tr.setShowingHeatmap(true);
showCached.setText("Hide HeatMap");
}
else if (ev.getStateChange() == ItemEvent.DESELECTED)
{
tr.setShowingHeatmap(false);
showCached.setText("Show HeatMap");
repaint();
}
}
}
});
start = new JToggleButton("Start");
start.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ev)
{
if (ev.getStateChange() == ItemEvent.SELECTED)
{
tr.setStart(true);
start.setText("Stop");
}
else if (ev.getStateChange() == ItemEvent.DESELECTED)
{
tr.setStart(false);
start.setText("Start");
repaint();
}
}
});
brush = new JSlider(SwingConstants.HORIZONTAL, 1, 20, 2);
brush.setMajorTickSpacing(1);
brush.setPaintTicks(true);
brush.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
tr.setBrushSize(brush.getValue());
repaint();
}
});
grid = new JComboBox<Object>(txts1);
grid.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
tr.setStart(false);
start.setSelected(false);
start.setText("Start");
JComboBox<?> cb = (JComboBox<?>) evt.getSource();
// a quick but effective fix
try
{
Thread.sleep(150);
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
tr.resizeGrid(cb.getSelectedIndex());
if (tr.isSuperSampled())
showCached.setText("Show HeatMap");
else
{
if (showCached.isSelected())
{
showCached.setText("Hide Cached");
}
else
{
showCached.setText("Show Cached");
}
}
brush.setValue(tr.getBrushSize());
}
});
timingL = new JLabel("Delay (ms) [" + tr.getDelay() + "]: ");
brushL = new JLabel("Brush size: ");
cVal1L = new JLabel("Underpop Lim [Default 2]: ");
cVal2L = new JLabel(" Overpop Lim [Default 3]: ");
cVal3L = new JLabel(" \"Birth\" Lim [Default 3]: ");
gen1 = new JLabel("Generation: " + tr.getGen());
pop1 = new JLabel("Living Cells: " + tr.getPop());
// ------------------------------------------------------------------------
tr.addMouseListener(new MouseListener()
{
@Override
public void mouseEntered(MouseEvent arg0)
{
}
@Override
public void mouseExited(MouseEvent arg0)
{
}
@Override
public void mousePressed(MouseEvent arg0)
{
tr.findIndexSmoothed(arg0.getX(), arg0.getY());
preX = arg0.getX();
preY = arg0.getY();
repaint();
}
@Override
public void mouseReleased(MouseEvent arg0)
{
tr.updatePop();
}
@Override
public void mouseClicked(MouseEvent e)
{
}
});
tr.addMouseMotionListener(new MouseMotionListener()
{
@Override
public void mouseDragged(MouseEvent arg0)
{
if (first)
{
preX = arg0.getX();
preY = arg0.getY();
tr.findIndexSmoothed(preX, preY, arg0.getX(), arg0.getY());
first = false;
}
else if (tr.isSuperSampled())
{
tr.findIndexSmoothedII(preX << 1, preY << 1, arg0.getX() << 1, arg0.getY() << 1);
}
else if (tr.isUsingBres())
{
tr.findIndexSmoothedII(preX, preY, arg0.getX(), arg0.getY());
}
else
{
tr.findIndexSmoothed(preX, preY, arg0.getX(), arg0.getY());
}
preX = arg0.getX();
preY = arg0.getY();
repaint();
}
@Override
public void mouseMoved(MouseEvent arg0)
{
}
});
// -----------------------------------------------------------------------
reset.setBounds(gX - 190, 70, 150, 50);
timingL.setBounds(gX - 190, 250, 100, 20);
timing.setBounds(gX - 190, 280, 150, 40);
tr.setBounds(5, 5, 1154, 928);
start.setBounds(gX - 190, 130, 150, 50);
step.setBounds(gX - 190, 190, 150, 50);
brush.setBounds(gX - 190, 360, 155, 40);
brushL.setBounds(gX - 190, 330, 150, 20);
grid.setBounds(gX - 190, 420, 150, 30);
showCached.setBounds(gX - 190, 470, 150, 50);
cVal1L.setBounds(gX - 190, 530, 150, 20);
cVal1.setBounds(gX - 190, 560, 150, 40);
cVal2L.setBounds(gX - 190, 610, 150, 20);
cVal2.setBounds(gX - 190, 640, 150, 40);
cVal3L.setBounds(gX - 190, 690, 150, 20);
cVal3.setBounds(gX - 190, 720, 150, 40);
gen1.setBounds(gX - 190, 10, 150, 20);
pop1.setBounds(gX - 190, 35, 150, 20);
add(gen1);
add(pop1);
add(reset);
add(cVal1);
add(cVal1L);
add(cVal2);
add(cVal2L);
add(cVal3);
add(cVal3L);
add(showCached);
add(grid);
add(brushL);
add(brush);
add(start);
add(step);
add(timingL);
add(timing);
add(tr); // always last
setVisible(true);
tr.popGrid();
while (true)
{ // this little ditty took me a *while* to figure out
gen1.setText("Generation: " + tr.getGen());
pop1.setText("Living Cells: " + tr.getPop());
repaint();
}
}
}
| JoeAzar/CGOL-v1.4 | CGOL_UI.java | Java | unlicense | 9,701 |
describe('test', function() {
it('ok', function() {
if (2 + 2 !== 4) throw(new Error('Test failed'))
})
})
;; | sunflowerdeath/broccoli-karma-plugin | test/files/ok.js | JavaScript | unlicense | 113 |
package main
import (
"fmt"
"io"
"log"
"strconv"
"strings"
"time"
"github.com/chzyer/readline"
"go.bug.st/serial.v1"
)
var (
device serial.Port
console *readline.Instance
conOut io.Writer
serialRecv = make(chan []byte)
commandRecv = make(chan Command)
)
type Command struct {
line string
done chan struct{}
}
func main() {
log.SetFlags(0) // omit timestamps
config := readline.Config{
UniqueEditLine: true,
Prompt: "? ",
}
var err error
console, err = readline.NewEx(&config)
check(err)
conOut = console.Stdout()
port := selectPort()
console.SetPrompt(". ")
device, err = serial.Open(port, &serial.Mode{BaudRate: 115200})
check(err)
go serialInput()
go consoleInput()
for {
var done chan struct{}
reply := ""
select {
case data := <-serialRecv:
reply = string(data)
case cmd := <-commandRecv:
console.SetPrompt("- ")
console.Refresh()
device.Write([]byte(cmd.line + "\r"))
done = cmd.done
}
if !strings.HasSuffix(reply, "\n") {
reply += getReply()
}
if strings.HasSuffix(reply, " ok.\n") {
console.SetPrompt("> ")
}
console.Refresh()
fmt.Fprint(conOut, reply)
if done != nil {
close(done)
}
}
}
func check(e error) {
if e != nil {
log.Fatal(e)
}
}
func selectPort() string {
allPorts, err := serial.GetPortsList()
check(err)
var ports []string
for _, p := range allPorts {
if !strings.HasPrefix(p, "/dev/tty.") {
ports = append(ports, p)
fmt.Printf("%3d: %s\n", len(ports), p)
}
}
console.Refresh()
reply, err := console.Readline()
check(err)
sel, err := strconv.Atoi(reply)
check(err)
return ports[sel-1]
}
func serialInput() {
for {
data := make([]byte, 250)
n, err := device.Read(data)
if n > 0 {
serialRecv <- data[:n]
}
check(err)
}
}
func consoleInput() {
for {
line, err := console.Readline()
check(err)
done := make(chan struct{})
commandRecv <- Command{line, done}
<-done
}
}
func getReply() (reply string) {
for {
select {
case data := <-serialRecv:
reply += string(data)
if strings.HasSuffix(reply, " ok.\n") ||
strings.HasSuffix(reply, " not found.\n") ||
strings.HasSuffix(reply, " is compile-only.\n") ||
strings.HasSuffix(reply, " Stack underflow\n") {
console.SetPrompt("> ")
return
}
case <-time.After(500 * time.Millisecond):
reply += "[timeout]\n"
return
}
}
return
}
| jeelabs/folie | mini/main.go | GO | unlicense | 2,416 |
a = [1,2,3]
b = a + [4,5,6]
p a
| CaddyDz/Ruby | p2/ch9/collection_handling_with_arrays/s3/+.rb | Ruby | unlicense | 32 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace so18191213
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
} | ssarabando/so18191213 | Global.asax.cs | C# | unlicense | 791 |
//==============================================================================
#include <hgeresource.h>
#include <hgesprite.h>
#include <hgefont.h>
#include <sqlite3.h>
#include <Database.h>
#include <Query.h>
#include <game.hpp>
#include <engine.hpp>
#include <entity.hpp>
#include <viewport.hpp>
#include <score.hpp>
//------------------------------------------------------------------------------
Game::Game( Engine * engine )
:
Context( engine ),
m_ship( 0 ),
m_urchins(),
m_coins(),
m_tiles( 0 ),
m_num_tiles( 0 ),
m_backs( 0 ),
m_num_backs( 0 ),
m_fores( 0 ),
m_num_fores( 0 ),
m_sky( 0 ),
m_gui( 0 ),
m_urchin_count( 0 )
{
}
//------------------------------------------------------------------------------
Game::~Game()
{
}
//------------------------------------------------------------------------------
// public:
//------------------------------------------------------------------------------
void
Game::init()
{
HGE * hge( m_engine->getHGE() );
b2World * b2d( m_engine->getB2D() );
hgeResourceManager * rm( m_engine->getResourceManager() );
ViewPort * viewport( m_engine->getViewPort() );
viewport->offset().x = 0.0f;
viewport->offset().y = 0.0f;
viewport->bounds().x = 8.0f;
viewport->bounds().y = 6.0f;
m_ship = new Ship( m_engine, 0.01f );
m_ship->init();
m_sky = new hgeSprite( 0, 0, 0, 50, 50 );
m_sky->SetHotSpot( 25, 25 );
m_gui = new hgeSprite( 0, 0, 0, 1, 1 );
Database db( "world.db3" );
Query q( db );
q.get_result( "SELECT texture_id, x, y, angle, scale FROM tiles" );
m_num_tiles = 100;
hge->System_Log( "Found %d tiles", m_num_tiles );
m_tiles = new Scenery * [m_num_tiles];
for ( int i = 0; i < m_num_tiles; ++i )
{
hge->System_Log( "Tile %d", i );
m_tiles[i] = 0;
}
int index( 0 );
while ( q.fetch_row() )
{
int texture_id( q.getval() );
float x( static_cast<float>( q.getnum() ) );
float y( static_cast<float>( q.getnum() ) );
float angle( static_cast<float>( q.getnum() ) );
float scale( static_cast<float>( q.getnum() ) );
hge->System_Log( "%f %f %f %f", x, y, angle, scale );
m_tiles[index] = new Scenery( m_engine, scale );
m_tiles[index]->init( rm->GetTexture( "tiles" ), b2d, x, y, angle,
texture_id );
index += 1;
}
q.free_result();
m_num_backs = 1;
m_backs = new Nothing * [m_num_backs];
for ( int i = 0; i < m_num_backs; ++i )
{
m_backs[i] = 0;
}
m_backs[0] = new Nothing( 0.5f );
m_backs[0]->init( rm->GetTexture( "tiles" ), 0.0f, 0.0f, 8 );
m_num_fores = 1;
m_fores = new Nothing * [m_num_fores];
for ( int i = 0; i < m_num_fores; ++i )
{
m_fores[i] = 0;
}
m_fores[0] = new Nothing( 0.3f );
m_fores[0]->init( rm->GetTexture( "tiles" ), 0.0f, 5.0f, 9 );
}
//------------------------------------------------------------------------------
void
Game::fini()
{
for ( int i = 0; i < m_num_tiles; ++i )
{
delete m_tiles[i];
}
delete [] m_tiles;
m_tiles = 0;
for ( int i = 0; i < m_num_backs; ++i )
{
delete m_backs[i];
}
delete [] m_backs;
m_backs = 0;
for ( int i = 0; i < m_num_fores; ++i )
{
delete m_fores[i];
}
delete [] m_fores;
m_fores = 0;
delete m_ship;
m_ship = 0;
std::vector< Urchin * >::iterator i;
for ( i = m_urchins.begin(); i != m_urchins.end(); ++i )
{
delete * i;
}
m_urchins.clear();
m_urchin_count = 0;
std::vector< Coin * >::iterator j;
for ( j = m_coins.begin(); j != m_coins.end(); ++j )
{
delete * j;
}
m_coins.clear();
delete m_sky;
m_sky = 0;
delete m_gui;
m_gui = 0;
}
//------------------------------------------------------------------------------
bool
Game::update( float dt )
{
HGE * hge( m_engine->getHGE() );
b2World * b2d( m_engine->getB2D() );
ViewPort * viewport( m_engine->getViewPort() );
if ( m_ship->getScoreData().getLives() <= 0 ||
m_ship->getScoreData().getUrchins() == 99 )
{
int lives( m_ship->getScoreData().getLives() );
int urchins( m_ship->getScoreData().getUrchins() );
int coins( m_ship->getScoreData().getCoins() );
int time( m_ship->getScoreData().getTime() );
m_engine->switchContext( STATE_SCORE );
Score * score( static_cast<Score *>( m_engine->getContext() ) );
score->calculateScore( lives, urchins, coins, time );
return false;
}
if ( ! m_engine->isDebug() )
{
m_ship->camera( viewport );
}
m_ship->update( dt );
std::vector< Coin * >::iterator i;
for ( i = m_coins.begin(); i != m_coins.end(); )
{
( * i )->update( dt );
if ( ( * i )->isDestroyed() )
{
delete * i;
i = m_coins.erase( i );
}
else
{
++i;
}
}
std::vector< Urchin * >::iterator j;
for ( j = m_urchins.begin(); j != m_urchins.end(); )
{
( * j )->update( dt );
if ( ( * j )->isDestroyed() )
{
for ( int k = 0; k < static_cast<int>((*j)->getScale() * 1000.0f);
++k )
{
m_coins.push_back( new Coin( m_engine, 0.0007f ) );
m_coins.back()->init();
b2Body * coin( m_coins.back()->getBody() );
b2Body * urchin( ( * j )->getBody() );
coin->SetXForm( urchin->GetPosition(), 0.0f );
float spin( hge->Random_Float( 20.0f, 80.0f ) );
if ( hge->Random_Int( 0, 1 ) == 0 )
{
spin *= -1.0f;
}
coin->SetAngularVelocity( spin );
b2Vec2 velocity( hge->Random_Float( -0.5f, 0.5f ),
hge->Random_Float( -0.3f, -0.8f ) );
coin->SetLinearVelocity( velocity );
}
m_ship->killed();
delete * j;
j = m_urchins.erase( j );
}
else
{
++j;
}
}
if ( dt > 0.0f &&
m_urchin_count < 99 && hge->Random_Float( 0.0f, 1.0f ) < 0.03f )
{
m_urchin_count += 1;
m_urchins.push_back( new Urchin( m_engine,
hge->Random_Float(0.001f, 0.012f) ) );
m_urchins.back()->init();
b2Body * body( m_urchins.back()->getBody() );
float angle( hge->Random_Float( -M_PI, M_PI ) );
b2Vec2 position( hge->Random_Float( -5.0f, 5.0f ), -10.0f );
body->SetXForm( position, 0.0f );
}
return false;
}
//------------------------------------------------------------------------------
void
Game::render()
{
HGE * hge( m_engine->getHGE() );
ViewPort * viewport( m_engine->getViewPort() );
hge->Gfx_SetTransform( viewport->offset().x,
viewport->offset().y,
400.0f,
300.0f,
viewport->angle(),
viewport->hscale(),
viewport->vscale() );
m_sky->SetColor( 0xFF330011, 0 );
m_sky->SetColor( 0xFF000077, 1 );
m_sky->SetColor( 0xFF8833FF, 2 );
m_sky->SetColor( 0xFFAA8866, 3 );
m_sky->Render( 0, 0 );
hge->Gfx_SetTransform( viewport->offset().x,
viewport->offset().y,
400.0f,
300.0f,
viewport->angle(),
viewport->hscale() * 0.9f,
viewport->vscale() * 0.9f );
_renderBacks();
hge->Gfx_SetTransform( viewport->offset().x,
viewport->offset().y,
400.0f,
300.0f,
viewport->angle(),
viewport->hscale(),
viewport->vscale() );
_renderBodies();
m_engine->getParticleManager()->Render();
hge->Gfx_SetTransform( viewport->offset().x,
viewport->offset().y,
400.0f,
300.0f,
viewport->angle(),
viewport->hscale() * 1.1f,
viewport->vscale() * 1.1f );
_renderFores();
hge->Gfx_SetTransform();
_renderGui();
}
//------------------------------------------------------------------------------
// private
//------------------------------------------------------------------------------
void
Game::_renderBacks()
{
return;
ViewPort * viewport( m_engine->getViewPort() );
for ( int i = 0; i < m_num_backs; ++i )
{
if ( m_backs[i] != 0 )
{
m_backs[i]->render( * viewport );
}
}
}
//------------------------------------------------------------------------------
void
Game::_renderFores()
{
return;
ViewPort * viewport( m_engine->getViewPort() );
for ( int i = 0; i < m_num_fores; ++i )
{
if ( m_fores[i] != 0 )
{
m_fores[i]->render( * viewport );
}
}
}
//------------------------------------------------------------------------------
void
Game::_renderBodies()
{
ViewPort * viewport( m_engine->getViewPort() );
b2World * b2d( m_engine->getB2D() );
for ( b2Body * body( b2d->GetBodyList() ); body != NULL;
body = body->GetNext() )
{
if ( body->IsDynamic() )
{
Entity * entity( static_cast<Entity *>( body->GetUserData() ) );
if ( entity )
{
entity->render();
}
}
else
{
Scenery * tile( static_cast<Scenery *>( body->GetUserData() ) );
if ( tile )
{
tile->render();
}
}
}
}
//------------------------------------------------------------------------------
void
Game::_renderGui()
{
HGE * hge( m_engine->getHGE() );
hgeResourceManager * rm( m_engine->getResourceManager() );
float width =
static_cast< float >( hge->System_GetState( HGE_SCREENWIDTH ) );
float height =
static_cast< float >( hge->System_GetState( HGE_SCREENHEIGHT ) );
m_gui->SetColor( 0x88000000 );
m_gui->RenderStretch( 0.0f, 0.0f, 90.0f, 40.0f );
m_gui->RenderStretch( width - 60.0f, 0.0f, width, 40.0f );
m_gui->RenderStretch( 0.0f, height - 40.0f, 130.0f, height );
m_gui->RenderStretch( width - 155.0f, height - 40.0f, width, height );
hgeFont * font( rm->GetFont( "menu" ) );
font->printf( 80.0f, 10.0f, HGETEXT_RIGHT,
"x %d", m_ship->getScoreData().getLives() );
font->printf( width - 10.0f, 10.0f, HGETEXT_RIGHT,
"%03d", m_ship->getScoreData().getTime() );
font->printf( 120.0f, height - 30.0f, HGETEXT_RIGHT,
"x %04d", m_ship->getScoreData().getCoins() );
font->printf( width - 10.0f, height - 30.0f, HGETEXT_RIGHT,
"x %02d/99", m_ship->getScoreData().getUrchins() );
rm->GetSprite( "ship" )->Render( 20.0f, 20.0f );
rm->GetSprite( "coin")->SetColor( 0xFFFFFFFF );
rm->GetSprite( "coin" )->Render( 20.0f, height - 20.0f );
rm->GetSprite( "urchin_green" )->Render( width - 130.0f, height - 20.0f );
}
//==============================================================================
| jasonhutchens/thrust_harder | game.cpp | C++ | unlicense | 12,117 |
class AddImageToDevices < ActiveRecord::Migration
def change
add_column :devices, :images, :json
end
end
| marmorkuchen-net/darmstadt3000 | db/migrate/20150822160442_add_image_to_devices.rb | Ruby | unlicense | 113 |
/*
---- A DYNAMIC Huffman (FGK) Coding Implementation ----
Filename: FGKD.C (Decoder)
Written by: Gerald Tamayo
Date: 2005
This is the decompressor for
FGKC.C, an *Adaptive* Huffman (FGK) Algorithm implementation.
To compile: tcc -w fgkd.c gtbitio.c huf.c
bcc32 -w fgkd.c gtbitio.c huf.c
g++ -O2 fgkd.c gtbitio.c huf.c -s -o fgkd
*/
#include <stdio.h>
#include <stdlib.h>
#include "gtbitio.h"
#include "fgk.c"
typedef struct {
char algorithm[4];
unsigned long file_size;
} file_stamp;
void copyright( void );
int main( int argc, char *argv[] )
{
unsigned long in_file_len = 0, out_file_len = 0;
FILE *out;
file_stamp fstamp;
if ( argc != 3 ) {
fprintf(stderr, "\n Usage: fgkd infile outfile");
copyright();
return 0;
}
if ( (gIN = fopen( argv[1], "rb" )) == NULL ) {
fprintf(stderr, "\nError opening input file.");
copyright();
return 0;
}
if ( (out = fopen( argv[2], "wb" )) == NULL ) {
fprintf(stderr, "\nError opening output file.");
copyright();
return 0;
}
fprintf(stderr, "\n---- A DYNAMIC Huffman (FGK) Implementation ----\n");
fprintf(stderr, "\nName of input file : %s", argv[1] );
fprintf(stderr, "\nName of output file: %s", argv[2] );
/* get file length. */
fseek( gIN, 0, SEEK_END );
in_file_len = ftell( gIN );
/* ===== The Main Huffman Implementation ======= */
fprintf(stderr, "\n\nHuffman decompressing...");
/* This is a DYNAMIC algorithm, so no need to read stats. */
/* start the decoding process. */
rewind( gIN );
/* read first the file stamp/header. */
fread( &fstamp, sizeof(file_stamp), 1, gIN );
/* make sure all symbol node
addresses are NULL. */
init_hufflist();
/* get FIRST symbol. */
hc = fgetc( gIN );
out_file_len = fstamp.file_size - 1;
/*
create first 0-node which quickly becomes the root
of the Huffman tree.
*/
top = zero_node = create_node();
/* output first symbol as a raw byte. */
fputc( (unsigned char) hc, out );
/* Update the Huffman tree. */
update_treeFGK( hc ); /* pass the symbol. */
/* now get the bit stream. */
init_get_buffer();
while ( out_file_len-- ) {
hc = hdecompress( top );
if ( hc == ZERO_NODE_SYMBOL ) { /* unseen byte. */
/* get raw byte. */
hc = get_nbits( 8 );
}
/* update the Huffman tree. */
update_treeFGK( hc ); /* pass the symbol. */
/* output the decoded byte. */
putc( (unsigned char) hc, out );
}
fprintf(stderr, "done.");
/* get outfile's size. */
out_file_len = ftell( out );
fprintf(stderr, "\n\nLength of input file = %15lu bytes", in_file_len );
fprintf(stderr, "\nLength of output file = %15lu bytes\n", out_file_len );
halt_prog:
free_get_buffer();
if ( gIN ) fclose( gIN );
if ( out ) fclose( out );
return 0;
}
void copyright( void )
{
fprintf(stderr, "\n\n Written by: Gerald Tamayo, 2005\n");
}
| Bladefidz/algorithm | compression/FGK/FGKD.C | C++ | unlicense | 2,984 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WcfServer.Service
{
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
public class StringReverser : IStringReverser
{
public string ReverseString(string value)
{
var result = new String(value.ToArray().Reverse().ToArray());
Console.WriteLine(String.Format("Processing {0}: {1}", value, result));
return new String(value.ToArray().Reverse().ToArray());
}
}
}
| DonTomato/WcfNamedPipesExample | sources/WcfServer/Service/IStringReverser.cs | C# | unlicense | 574 |