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 |
|---|---|---|---|---|---|
import React from "react";
import Image from "@times-components/image";
import styleFactory from "./styles";
import propTypes from "./proptypes";
const MastHead = ({ publicationName, breakpoint }) => {
let uri = "https://www.thetimes.co.uk/d/img/leaders-masthead-d17db00289.png";
let aspectRatio = 1435 / 250;
let style = "mastheadStyleTimes";
const styles = styleFactory(breakpoint);
if (publicationName !== "TIMES") {
style = "mastheadStyleST";
aspectRatio = 243 / 45;
uri =
"https://www.thetimes.co.uk/d/img/logos/sundaytimes-with-crest-black-53d6e31fb8.png";
}
return <Image aspectRatio={aspectRatio} style={styles[style]} uri={uri} />;
};
MastHead.propTypes = propTypes;
export default MastHead;
| newsuk/times-components | packages/edition-slices/src/slices/leaders/masthead.js | JavaScript | bsd-3-clause | 738 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import djangocms_text_ckeditor.fields
def migrate_club_journal(apps, schema_editor):
import re
ClubJournalEntry = apps.get_model('domecek', 'ClubJournalEntry')
for entry in ClubJournalEntry.objects.all():
entry.agenda = '<p>{}</p>'.format('<br />'.join(entry.agenda.split('\n')))
entry.participants = [reg.participant for reg in entry.registrations.all()]
entry.period = entry.club.periods.get(start__lte=entry.start, end__gte=entry.end)
entry.save()
class Migration(migrations.Migration):
dependencies = [
('domecek', '0011_remove_clubregistration_periods'),
]
operations = [
migrations.AlterField(
model_name='clubjournalentry',
name='agenda',
field=djangocms_text_ckeditor.fields.HTMLField(verbose_name='agenda'),
preserve_default=True,
),
migrations.RenameField(
model_name='clubjournalentry',
old_name='participants',
new_name='registrations',
),
migrations.AddField(
model_name='clubjournalentry',
name='participants',
field=models.ManyToManyField(related_name='journal_entries', verbose_name='participants', to='domecek.Participant', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='clubjournalentry',
name='period',
field=models.ForeignKey(related_name='journal_entries', verbose_name='period', to='domecek.ClubPeriod', null=True),
preserve_default=True,
),
migrations.RunPython(migrate_club_journal),
migrations.AlterField(
model_name='clubjournalentry',
name='period',
field=models.ForeignKey(related_name='journal_entries', verbose_name='period', to='domecek.ClubPeriod'),
preserve_default=True,
),
migrations.RemoveField(
model_name='clubjournalentry',
name='club',
),
migrations.RemoveField(
model_name='clubjournalentry',
name='registrations',
),
]
| misli/django-domecek | domecek/migrations/0012_new_clubjournalentry.py | Python | bsd-3-clause | 2,269 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/wallet/instrument.h"
#include "chrome/browser/autofill/wallet/wallet_address.h"
#include "chrome/browser/autofill/wallet/wallet_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char kPrimaryAccountNumber[] = "4444444444444448";
const char kCardVerificationNumber[] = "123";
const char kLastFourDigits[] = "4448";
}
namespace autofill {
namespace wallet {
TEST(Instrument, LastFourDigits) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_EQ(ASCIIToUTF16(kLastFourDigits), instrument.last_four_digits());
EXPECT_TRUE(instrument.IsValid());
}
TEST(Instrument, NoPrimaryAccountNumberIsInvalid) {
Instrument instrument(string16(),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooShortPrimaryAccountNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16("44447"),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooLongPrimaryAccountNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16("44444444444444444448"),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, PrimaryAccountNumberNotPassingLuhnIsInvalid) {
Instrument instrument(ASCIIToUTF16("4444444444444444"),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, NoCardVerificationNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
string16(),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooShortCardVerificationNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16("12"),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooLongCardVerificationNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16("12345"),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, ZeroAsExpirationMonthIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
0,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooLargeExpirationMonthIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
13,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooSmallExpirationYearIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
12,
999,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooLargeExpirationYearIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
12,
10000,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, ToDictionary) {
base::DictionaryValue expected;
expected.SetString("type", "CREDIT_CARD");
expected.SetInteger("credit_card.exp_month", 12);
expected.SetInteger("credit_card.exp_year", 2015);
expected.SetString("credit_card.last_4_digits", kLastFourDigits);
expected.SetString("credit_card.fop_type", "VISA");
expected.SetString("credit_card.address.country_name_code",
"ship_country_name_code");
expected.SetString("credit_card.address.recipient_name",
"ship_recipient_name");
expected.SetString("credit_card.address.locality_name",
"ship_locality_name");
expected.SetString("credit_card.address.administrative_area_name",
"ship_admin_area_name");
expected.SetString("credit_card.address.postal_code_number",
"ship_postal_code_number");
base::ListValue* address_lines = new base::ListValue();
address_lines->AppendString("ship_address_line_1");
address_lines->AppendString("ship_address_line_2");
expected.Set("credit_card.address.address_line", address_lines);
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_TRUE(expected.Equals(instrument.ToDictionary().get()));
}
} // namespace wallet
} // namespace autofill
| zcbenz/cefode-chromium | chrome/browser/autofill/wallet/instrument_unittest.cc | C++ | bsd-3-clause | 6,679 |
/*
* Copyright (c) 2018, Ford Motor Company
* 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 Ford Motor Company 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "security_manager/security_manager_impl.h"
#include <functional>
#include "json/json.h"
#include "protocol_handler/protocol_packet.h"
#include "security_manager/crypto_manager_impl.h"
#include "utils/byte_order.h"
#include "utils/helpers.h"
#include "utils/jsoncpp_reader_wrapper.h"
#include "utils/logger.h"
namespace security_manager {
SDL_CREATE_LOG_VARIABLE("SecurityManager")
static const char* kErrId = "id";
static const char* kErrText = "text";
SecurityManagerImpl::SecurityManagerImpl(
std::unique_ptr<utils::SystemTimeHandler>&& system_time_handler)
: security_messages_("SecurityManager", this)
, session_observer_(NULL)
, crypto_manager_(NULL)
, protocol_handler_(NULL)
, system_time_handler_(std::move(system_time_handler))
, current_seq_number_(0)
, waiting_for_certificate_(false)
, waiting_for_time_(false) {
DCHECK(system_time_handler_);
system_time_handler_->SubscribeOnSystemTime(this);
}
SecurityManagerImpl::~SecurityManagerImpl() {
system_time_handler_->UnsubscribeFromSystemTime(this);
}
void SecurityManagerImpl::OnMessageReceived(
const ::protocol_handler::RawMessagePtr message) {
if (message->service_type() != protocol_handler::kControl) {
return;
}
SecurityMessage securityMessagePtr(std::make_shared<SecurityQuery>());
const bool result =
securityMessagePtr->SerializeQuery(message->data(), message->data_size());
if (!result) {
// result will be false only if data less then query header
const std::string error_text("Incorrect message received");
SDL_LOG_ERROR(error_text);
SendInternalError(
message->connection_key(), ERROR_INVALID_QUERY_SIZE, error_text);
return;
}
securityMessagePtr->set_connection_key(message->connection_key());
// Post message to message query for next processing in thread
security_messages_.PostMessage(securityMessagePtr);
}
void SecurityManagerImpl::OnMobileMessageSent(
const ::protocol_handler::RawMessagePtr) {}
void SecurityManagerImpl::set_session_observer(
protocol_handler::SessionObserver* observer) {
if (!observer) {
SDL_LOG_ERROR("Invalid (NULL) pointer to SessionObserver.");
return;
}
session_observer_ = observer;
}
void SecurityManagerImpl::set_protocol_handler(
protocol_handler::ProtocolHandler* handler) {
if (!handler) {
SDL_LOG_ERROR("Invalid (NULL) pointer to ProtocolHandler.");
return;
}
protocol_handler_ = handler;
}
void SecurityManagerImpl::set_crypto_manager(CryptoManager* crypto_manager) {
if (!crypto_manager) {
SDL_LOG_ERROR("Invalid (NULL) pointer to CryptoManager.");
return;
}
crypto_manager_ = crypto_manager;
}
void SecurityManagerImpl::Handle(const SecurityMessage message) {
DCHECK(message);
SDL_LOG_INFO("Received Security message from Mobile side");
if (!crypto_manager_) {
const std::string error_text("Invalid (NULL) CryptoManager.");
SDL_LOG_ERROR(error_text);
SendInternalError(
message->get_connection_key(), ERROR_NOT_SUPPORTED, error_text);
return;
}
switch (message->get_header().query_id) {
case SecurityQuery::SEND_HANDSHAKE_DATA:
if (!ProcessHandshakeData(message)) {
SDL_LOG_ERROR("Process HandshakeData failed");
}
break;
case SecurityQuery::SEND_INTERNAL_ERROR:
if (!ProcessInternalError(message)) {
SDL_LOG_ERROR("Processing income InternalError failed");
}
break;
default: {
// SecurityQuery::InvalidQuery
const std::string error_text("Unknown query identifier.");
SDL_LOG_ERROR(error_text);
SendInternalError(message->get_connection_key(),
ERROR_INVALID_QUERY_ID,
error_text,
message->get_header().seq_number);
} break;
}
}
security_manager::SSLContext* SecurityManagerImpl::CreateSSLContext(
const uint32_t& connection_key, ContextCreationStrategy cc_strategy) {
SDL_LOG_INFO("ProtectService processing");
DCHECK(session_observer_);
DCHECK(crypto_manager_);
if (kUseExisting == cc_strategy) {
security_manager::SSLContext* ssl_context =
session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl);
// If SSLContext for current connection/session exists - return it
if (ssl_context) {
return ssl_context;
}
}
security_manager::SSLContext* ssl_context =
crypto_manager_->CreateSSLContext();
if (!ssl_context) {
const std::string error_text("CryptoManager could not create SSL context.");
SDL_LOG_ERROR(error_text);
// Generate response query and post to security_messages_
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
return NULL;
}
const int result =
session_observer_->SetSSLContext(connection_key, ssl_context);
if (ERROR_SUCCESS != result) {
// delete SSLContext on any error
crypto_manager_->ReleaseSSLContext(ssl_context);
SendInternalError(connection_key, result, "");
return NULL;
}
DCHECK(session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl));
SDL_LOG_DEBUG("Set SSL context to connection_key " << connection_key);
return ssl_context;
}
void SecurityManagerImpl::PostponeHandshake(const uint32_t connection_key) {
SDL_LOG_TRACE("Handshake postponed");
sync_primitives::AutoLock lock(connections_lock_);
if (waiting_for_certificate_) {
awaiting_certificate_connections_.insert(connection_key);
}
if (waiting_for_time_) {
awaiting_time_connections_.insert(connection_key);
}
}
void SecurityManagerImpl::ResumeHandshake(uint32_t connection_key) {
SDL_LOG_TRACE("Handshake resumed");
security_manager::SSLContext* ssl_context =
CreateSSLContext(connection_key, kForceRecreation);
if (!ssl_context) {
SDL_LOG_WARN("Unable to resume handshake. No SSL context for key "
<< connection_key);
return;
}
SDL_LOG_DEBUG("Connection key : "
<< connection_key << " is waiting for certificate: "
<< std::boolalpha << waiting_for_certificate_
<< " and has certificate: " << ssl_context->HasCertificate());
ssl_context->ResetConnection();
if (!waiting_for_certificate_ && !ssl_context->HasCertificate()) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
ProceedHandshake(ssl_context, connection_key);
}
void SecurityManagerImpl::StartHandshake(uint32_t connection_key) {
DCHECK(session_observer_);
SDL_LOG_INFO("StartHandshake: connection_key " << connection_key);
security_manager::SSLContext* ssl_context = session_observer_->GetSSLContext(
connection_key, protocol_handler::kControl);
if (!ssl_context) {
const std::string error_text(
"StartHandshake failed, "
"connection is not protected");
SDL_LOG_ERROR(error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
if (!ssl_context->HasCertificate()) {
SDL_LOG_ERROR("Security certificate is absent");
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = true;
NotifyOnCertificateUpdateRequired();
}
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_time_ = true;
}
PostponeHandshake(connection_key);
system_time_handler_->QuerySystemTime();
}
bool SecurityManagerImpl::IsSystemTimeProviderReady() const {
return system_time_handler_->system_time_can_be_received();
}
void SecurityManagerImpl::ProceedHandshake(
security_manager::SSLContext* ssl_context, uint32_t connection_key) {
SDL_LOG_AUTO_TRACE();
if (!ssl_context) {
SDL_LOG_WARN("Unable to process handshake. No SSL context for key "
<< connection_key);
return;
}
if (ssl_context->IsInitCompleted()) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
return;
}
time_t cert_due_date;
if (!ssl_context->GetCertificateDueDate(cert_due_date)) {
SDL_LOG_ERROR("Failed to get certificate due date!");
PostponeHandshake(connection_key);
return;
}
if (crypto_manager_->IsCertificateUpdateRequired(
system_time_handler_->GetUTCTime(), cert_due_date)) {
SDL_LOG_DEBUG("Host certificate update required");
if (helpers::in_range(awaiting_certificate_connections_, connection_key)) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_CertExpired);
return;
}
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = true;
}
PostponeHandshake(connection_key);
NotifyOnCertificateUpdateRequired();
return;
}
SSLContext::HandshakeContext handshake_context =
session_observer_->GetHandshakeContext(connection_key);
handshake_context.system_time = system_time_handler_->GetUTCTime();
ssl_context->SetHandshakeContext(handshake_context);
size_t data_size = 0;
const uint8_t* data = NULL;
const security_manager::SSLContext::HandshakeResult result =
ssl_context->StartHandshake(&data, &data_size);
if (security_manager::SSLContext::Handshake_Result_Success != result) {
const std::string error_text("StartHandshake failed, handshake step fail");
SDL_LOG_ERROR(error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
// for client mode will be generated output data
if (data != NULL && data_size != 0) {
SendHandshakeBinData(connection_key, data, data_size);
}
}
bool SecurityManagerImpl::IsCertificateUpdateRequired(
const uint32_t connection_key) {
SDL_LOG_AUTO_TRACE();
security_manager::SSLContext* ssl_context =
CreateSSLContext(connection_key, kUseExisting);
DCHECK_OR_RETURN(ssl_context, true);
SDL_LOG_DEBUG("Set SSL context to connection_key " << connection_key);
time_t cert_due_date;
if (!ssl_context->GetCertificateDueDate(cert_due_date)) {
SDL_LOG_ERROR("Failed to get certificate due date!");
return true;
}
return crypto_manager_->IsCertificateUpdateRequired(
system_time_handler_->GetUTCTime(), cert_due_date);
}
void SecurityManagerImpl::AddListener(SecurityManagerListener* const listener) {
if (!listener) {
SDL_LOG_ERROR("Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.push_back(listener);
}
void SecurityManagerImpl::RemoveListener(
SecurityManagerListener* const listener) {
if (!listener) {
SDL_LOG_ERROR("Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.remove(listener);
}
bool SecurityManagerImpl::OnCertificateUpdated(const std::string& data) {
SDL_LOG_AUTO_TRACE();
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = false;
}
crypto_manager_->OnCertificateUpdated(data);
std::for_each(
awaiting_certificate_connections_.begin(),
awaiting_certificate_connections_.end(),
std::bind1st(std::mem_fun(&SecurityManagerImpl::ResumeHandshake), this));
awaiting_certificate_connections_.clear();
return true;
}
void SecurityManagerImpl::OnSystemTimeArrived(const time_t utc_time) {
SDL_LOG_AUTO_TRACE();
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_time_ = false;
}
std::for_each(
awaiting_time_connections_.begin(),
awaiting_time_connections_.end(),
std::bind1st(std::mem_fun(&SecurityManagerImpl::ResumeHandshake), this));
awaiting_time_connections_.clear();
}
void SecurityManagerImpl::OnSystemTimeFailed() {
SDL_LOG_AUTO_TRACE();
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_time_ = false;
}
NotifyListenersOnGetSystemTimeFailed();
awaiting_time_connections_.clear();
}
void SecurityManagerImpl::ProcessFailedPTU() {
SDL_LOG_AUTO_TRACE();
if (listeners_.empty()) {
SDL_LOG_DEBUG("listeners arrays IS EMPTY!");
return;
}
std::list<SecurityManagerListener*> listeners_to_remove;
for (auto listener : listeners_) {
if (listener->OnPTUFailed()) {
listeners_to_remove.push_back(listener);
}
}
for (auto& listener : listeners_to_remove) {
auto it = std::find(listeners_.begin(), listeners_.end(), listener);
DCHECK(it != listeners_.end());
SDL_LOG_DEBUG("Destroying listener: " << *it);
delete (*it);
listeners_.erase(it);
}
}
#if defined(EXTERNAL_PROPRIETARY_MODE) && defined(ENABLE_SECURITY)
void SecurityManagerImpl::ProcessFailedCertDecrypt() {
SDL_LOG_AUTO_TRACE();
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = false;
}
std::list<SecurityManagerListener*> listeners_to_remove;
for (auto listener : listeners_) {
if (listener->OnCertDecryptFailed()) {
listeners_to_remove.push_back(listener);
}
}
for (auto& listener : listeners_to_remove) {
auto it = std::find(listeners_.begin(), listeners_.end(), listener);
DCHECK(it != listeners_.end());
SDL_LOG_DEBUG("Destroying listener: " << *it);
delete (*it);
listeners_.erase(it);
}
awaiting_certificate_connections_.clear();
}
#endif
void SecurityManagerImpl::NotifyListenersOnHandshakeDone(
const uint32_t& connection_key, SSLContext::HandshakeResult error) {
SDL_LOG_AUTO_TRACE();
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
if ((*it)->OnHandshakeDone(connection_key, error)) {
SDL_LOG_DEBUG("Destroying listener: " << *it);
delete (*it);
it = listeners_.erase(it);
} else {
++it;
}
}
}
void SecurityManagerImpl::NotifyOnCertificateUpdateRequired() {
SDL_LOG_AUTO_TRACE();
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
(*it)->OnCertificateUpdateRequired();
++it;
}
}
void SecurityManagerImpl::ResetPendingSystemTimeRequests() {
system_time_handler_->ResetPendingSystemTimeRequests();
}
void SecurityManagerImpl::NotifyListenersOnGetSystemTimeFailed() {
SDL_LOG_AUTO_TRACE();
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
if ((*it)->OnGetSystemTimeFailed()) {
SDL_LOG_DEBUG("Destroying listener: " << *it);
delete (*it);
it = listeners_.erase(it);
} else {
++it;
}
}
}
bool SecurityManagerImpl::IsPolicyCertificateDataEmpty() {
SDL_LOG_AUTO_TRACE();
std::string certificate_data;
for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
if ((*it)->GetPolicyCertificateData(certificate_data)) {
SDL_LOG_DEBUG("Certificate data received from listener");
return certificate_data.empty();
}
}
return false;
}
bool SecurityManagerImpl::ProcessHandshakeData(
const SecurityMessage& inMessage) {
SDL_LOG_INFO("SendHandshakeData processing");
DCHECK(inMessage);
DCHECK(inMessage->get_header().query_id ==
SecurityQuery::SEND_HANDSHAKE_DATA);
const uint32_t seqNumber = inMessage->get_header().seq_number;
const uint32_t connection_key = inMessage->get_connection_key();
SDL_LOG_DEBUG("Received " << inMessage->get_data_size()
<< " bytes handshake data ");
if (!inMessage->get_data_size()) {
const std::string error_text("SendHandshakeData: null arguments size.");
SDL_LOG_ERROR(error_text);
SendInternalError(
connection_key, ERROR_INVALID_QUERY_SIZE, error_text, seqNumber);
return false;
}
DCHECK(session_observer_);
SSLContext* sslContext = session_observer_->GetSSLContext(
connection_key, protocol_handler::kControl);
if (!sslContext) {
const std::string error_text("SendHandshakeData: No ssl context.");
SDL_LOG_ERROR(error_text);
SendInternalError(
connection_key, ERROR_SERVICE_NOT_PROTECTED, error_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return false;
}
size_t out_data_size;
const uint8_t* out_data;
const SSLContext::HandshakeResult handshake_result =
sslContext->DoHandshakeStep(inMessage->get_data(),
inMessage->get_data_size(),
&out_data,
&out_data_size);
if (handshake_result == SSLContext::Handshake_Result_AbnormalFail) {
// Do not return handshake data on AbnormalFail or null returned values
const std::string error_text(sslContext->LastError());
SDL_LOG_ERROR("SendHandshakeData: Handshake failed: " << error_text);
SendInternalError(
connection_key, ERROR_SSL_INVALID_DATA, error_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
// no handshake data to send
return false;
}
if (sslContext->IsInitCompleted()) {
// On handshake success
SDL_LOG_DEBUG("SSL initialization finished success.");
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
} else if (handshake_result != SSLContext::Handshake_Result_Success) {
// On handshake fail
SDL_LOG_WARN("SSL initialization finished with fail.");
int32_t error_code = ERROR_HANDSHAKE_FAILED;
std::string error_text = "Handshake failed";
switch (handshake_result) {
case SSLContext::Handshake_Result_CertExpired:
error_code = ERROR_EXPIRED_CERT;
error_text = "Certificate is expired";
break;
case SSLContext::Handshake_Result_NotYetValid:
error_code = ERROR_INVALID_CERT;
error_text = "Certificate is not yet valid";
break;
case SSLContext::Handshake_Result_CertNotSigned:
error_code = ERROR_INVALID_CERT;
error_text = "Certificate is not signed";
break;
case SSLContext::Handshake_Result_AppIDMismatch:
error_code = ERROR_INVALID_CERT;
error_text = "App ID does not match certificate";
break;
default:
break;
}
SendInternalError(connection_key, error_code, error_text);
NotifyListenersOnHandshakeDone(connection_key, handshake_result);
}
if (out_data && out_data_size) {
// answer with the same seqNumber as income message
SendHandshakeBinData(connection_key, out_data, out_data_size, seqNumber);
}
return true;
}
bool SecurityManagerImpl::ProcessInternalError(
const SecurityMessage& inMessage) {
std::string str = inMessage->get_json_message();
const uint32_t connection_key = inMessage->get_connection_key();
SDL_LOG_INFO("Received InternalError with Json message" << str);
Json::Value root;
utils::JsonReader reader;
if (!reader.parse(str, &root)) {
SDL_LOG_DEBUG("Json parsing fails.");
return false;
}
uint8_t id = root[kErrId].asInt();
SDL_LOG_DEBUG("Received InternalError id " << std::to_string(id) << ", text: "
<< root[kErrText].asString());
if (ERROR_SSL_INVALID_DATA == id || ERROR_NOT_SUPPORTED == id) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
}
return true;
}
uint32_t SecurityManagerImpl::NextSequentialNumber() {
if (current_seq_number_ >= std::numeric_limits<uint32_t>::max()) {
current_seq_number_ = 0;
}
current_seq_number_++;
return current_seq_number_;
}
void SecurityManagerImpl::SendHandshakeBinData(
const uint32_t connection_key,
const uint8_t* const data,
const size_t data_size,
const uint32_t custom_seq_number) {
uint32_t seq_number =
(0 == custom_seq_number) ? NextSequentialNumber() : custom_seq_number;
const SecurityQuery::QueryHeader header(
SecurityQuery::REQUEST, SecurityQuery::SEND_HANDSHAKE_DATA, seq_number);
DCHECK(data_size < 1024 * 1024 * 1024);
const SecurityQuery query =
SecurityQuery(header, connection_key, data, data_size);
SendQuery(query, connection_key);
SDL_LOG_DEBUG("Sent " << data_size << " bytes handshake data ");
}
void SecurityManagerImpl::SendInternalError(const uint32_t connection_key,
const uint8_t& error_id,
const std::string& error_text,
const uint32_t seq_number) {
Json::Value value;
value[kErrId] = error_id;
value[kErrText] = error_text;
const std::string error_str = value.toStyledString();
SecurityQuery::QueryHeader header(
SecurityQuery::NOTIFICATION,
SecurityQuery::SEND_INTERNAL_ERROR,
// header save json size only (exclude last byte)
seq_number,
error_str.size());
// Raw data is json string and error id at last byte
std::vector<uint8_t> data_sending(error_str.size() + 1);
memcpy(&data_sending[0], error_str.c_str(), error_str.size());
data_sending[data_sending.size() - 1] = error_id;
const SecurityQuery query(
header, connection_key, &data_sending[0], data_sending.size());
SendQuery(query, connection_key);
SDL_LOG_DEBUG("Sent Internal error id " << static_cast<int>(error_id)
<< " : \"" << error_text << "\".");
}
void SecurityManagerImpl::SendQuery(const SecurityQuery& query,
const uint32_t connection_key) {
const std::vector<uint8_t> data_sending = query.DeserializeQuery();
uint32_t connection_handle = 0;
uint8_t sessionID = 0;
uint8_t protocol_version;
session_observer_->PairFromKey(
connection_key, &connection_handle, &sessionID);
if (session_observer_->ProtocolVersionUsed(
connection_handle, sessionID, protocol_version)) {
const ::protocol_handler::RawMessagePtr rawMessagePtr(
new protocol_handler::RawMessage(connection_key,
protocol_version,
&data_sending[0],
data_sending.size(),
false,
protocol_handler::kControl));
DCHECK(protocol_handler_);
// Add RawMessage to ProtocolHandler message query
protocol_handler_->SendMessageToMobileApp(rawMessagePtr, false, false);
}
}
const char* SecurityManagerImpl::ConfigSection() {
return "Security Manager";
}
} // namespace security_manager
| smartdevicelink/sdl_core | src/components/security_manager/src/security_manager_impl.cc | C++ | bsd-3-clause | 24,474 |
(function () {
'use strict';
angular.module('instance-info', ['motech-dashboard', 'instance-info.controllers', 'ngCookies', 'ui.bootstrap']).config(
['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/instance-info/info', {templateUrl: '../instance-info/resources/partials/info.html', controller: 'InfoController'});
}]);
}());
| motech/perf | instance-info/src/main/resources/webapp/js/app.js | JavaScript | bsd-3-clause | 399 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+relay
*/
'use strict';
require('configureForRelayOSS');
jest
.dontMock('GraphQLRange')
.dontMock('GraphQLSegment');
const Relay = require('Relay');
const RelayRecordStore = require('RelayRecordStore');
const RelayRecordWriter = require('RelayRecordWriter');
const RelayTestUtils = require('RelayTestUtils');
describe('writeRelayQueryPayload()', () => {
const {getNode, writePayload} = RelayTestUtils;
beforeEach(() => {
jest.resetModuleRegistry();
});
describe('default null', () => {
it('writes missing scalar field as null', () => {
const records = {};
const store = new RelayRecordStore({records});
const writer = new RelayRecordWriter(records, {}, false);
const query = getNode(Relay.QL`
query {
node(id:"123") {
id,
name
}
}
`);
const payload = {
node: {
__typename: 'User',
id: '123',
},
};
const results = writePayload(store, writer, query, payload);
expect(results).toEqual({
created: {
'123': true,
},
updated: {},
});
expect(store.getField('123', 'name')).toBe(null);
});
it('writes missing linked field as null', () => {
const records = {};
const store = new RelayRecordStore({records});
const writer = new RelayRecordWriter(records, {}, false);
const query = getNode(Relay.QL`
query {
viewer {
actor {
id
}
}
}
`);
const payload = {
viewer: {},
};
const results = writePayload(store, writer, query, payload);
expect(results).toEqual({
created: {
'client:1': true,
},
updated: {},
});
expect(store.getRecordState('client:1')).toBe('EXISTENT');
expect(store.getLinkedRecordID('client:1', 'actor')).toBe(null);
});
it('writes missing plural linked field as null', () => {
const records = {
'123': {
__dataID__: '123',
id: '123',
},
};
const store = new RelayRecordStore({records});
const writer = new RelayRecordWriter(records, {}, false);
const query = getNode(Relay.QL`
query {
node(id:"123") {
allPhones {
phoneNumber {
displayNumber
}
}
}
}
`);
const payload = {
node: {
__typename: 'User',
id: '123',
},
};
const results = writePayload(store, writer, query, payload);
expect(results).toEqual({
created: {},
updated: {
'123': true,
},
});
const phoneIDs = store.getLinkedRecordIDs('123', 'allPhones');
expect(phoneIDs).toEqual(null);
});
it('writes missing connection as null', () => {
const records = {};
const store = new RelayRecordStore({records});
const writer = new RelayRecordWriter(records, {}, false);
const query = getNode(Relay.QL`
query {
node(id:"123") {
friends(first:"3") {
edges {
cursor,
node {
id
},
},
pageInfo {
hasNextPage,
hasPreviousPage,
}
}
}
}
`);
const payload = {
node: {
id: '123',
__typename: 'User',
},
};
const results = writePayload(store, writer, query, payload);
expect(results).toEqual({
created: {
'123': true,
},
updated: {},
});
expect(store.getField('123', 'friends')).toBe(null);
});
});
});
| NevilleS/relay | src/traversal/__tests__/writeRelayQueryPayload_defaultNull-test.js | JavaScript | bsd-3-clause | 4,160 |
/*
* Copyright (c) 2010, Sun Microsystems, Inc.
* Copyright (c) 2010, The Storage Networking Industry Association.
*
* 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 Storage Networking Industry Association (SNIA) 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 org.snia.cdmiserver.exception;
/**
* <p>
* Exception that should be mapped to an HTTP Status 400 Response
* </p>
*/
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
public BadRequestException(Throwable cause) {
super(cause);
}
}
| dCache/CDMI | cdmi-core/src/main/java/org/snia/cdmiserver/exception/BadRequestException.java | Java | bsd-3-clause | 2,136 |
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\EventCategory;
/**
* EventCategorySearch represents the model behind the search form about `common\models\EventCategory`.
*/
class EventCategorySearch extends EventCategory
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'status'], 'integer'],
[['title_ru', 'created_at', 'updated_at'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = EventCategory::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'status' => $this->status,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'title_ru', $this->title_ru]);
return $dataProvider;
}
}
| djrosl/travel | backend/models/EventCategorySearch.php | PHP | bsd-3-clause | 1,683 |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from .models import Story
def index(request):
stories = Story.objects.order_by('score')
return render(request, 'reader/stories.html', {'stories': stories})
| n3bukadn3zar/reservo | reservo/reader/views.py | Python | bsd-3-clause | 263 |
<?php
namespace Livraria\Model;
class CategoriaService
{
/**
* @var Livraria\Model\CategoriaTable
*/
protected $categoriaTable;
/** ------------------------------------------------------------------------------------------------------------- */
/**
* @name __construct
* @return void
*
*/
public function __construct(CategoriaTable $table)
{
$this->categoriaTable = $table;
}
/** ------------------------------------------------------------------------------------------------------------- */
/**
* @name getTodosOsRegistros
* @return array
*
*/
public function retornarTodosOsRegistros()
{
return $this->categoriaTable->select();
}
/** ------------------------------------------------------------------------------------------------------------- */
} | eltonoliveira/curso.zend2 | module/Livraria/src/Livraria/Model/CategoriaService.php | PHP | bsd-3-clause | 784 |
export default (): boolean => process.env.NODE_ENV !== 'development';
| wakatime/chrome-wakatime | src/utils/isProd.ts | TypeScript | bsd-3-clause | 70 |
__version__ = '0.1dev'
import argparse
import string
import re
from rap.processing_unit import ProcessingUnit
from rap.program import Program, ProgramError
input_pair_regex = re.compile("^\s*([a-zA-Z0-9]+)\s*:\s*([0-9]+)\s*$")
def parse_input(string, sep=',', pair_regex=input_pair_regex):
registers = {}
for pair in string.split(','):
if not pair.strip():
continue
match = pair_regex.match(pair)
if not match:
raise ValueError('ass')
register, value = match.groups()
registers[register] = int(value)
return registers
class Formatter(string.Formatter):
"""Slightly modified string.Formatter.
The differences are:
- field names are considered strings (i.e. only kwargs are used)
- field names / attributes / items that are not found are silently
ignored and their corresponding replacement fields are preserved
- invalid replacement fields are are also silently preserved
"""
def get_field(self, field_name, args, kwargs):
first, rest = string._string.formatter_field_name_split(field_name)
obj = self.get_value(str(first), args, kwargs)
for is_attr, i in rest:
if is_attr:
obj = getattr(obj, i)
else:
obj = obj[str(i)]
return obj, first
def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
if recursion_depth < 0:
raise ValueError('Max string recursion exceeded')
result = []
for literal_text, field_name, format_spec, conversion in \
self.parse(format_string):
original_format_spec = format_spec
if literal_text:
result.append(literal_text)
if field_name is not None:
used_args_copy = used_args.copy()
try:
obj, arg_used = self.get_field(field_name, args, kwargs)
used_args_copy.add(arg_used)
obj = self.convert_field(obj, conversion)
format_spec = self._vformat(format_spec, args, kwargs,
used_args_copy, recursion_depth-1)
formatted = self.format_field(obj, format_spec)
result.append(formatted)
used_args.update(used_args_copy)
except (AttributeError, KeyError, ValueError):
result.append("{" + field_name)
if conversion:
result.append("!" + conversion)
if original_format_spec:
result.append(":" + original_format_spec)
result.append("}")
return ''.join(result)
def make_parser():
parser = argparse.ArgumentParser('rap',
description="Register Assembly Programming")
parser.add_argument('file', type=argparse.FileType('r'),
help="a file containing a RAP program")
parser.add_argument('-i', '--input', metavar='input', type=parse_input,
help="set the initial register values (e.g. \"a: 1, b: 2\")")
parser.add_argument('-o', '--output', metavar='format', nargs='?',
const=True, help="""
print the register values after the program ends; if format is
given, register names between braces will be replaced with
their values (e.g. "a: {a}")
""")
parser.add_argument('-t', '--trace', metavar='format', nargs='?',
const=True, help="""
print the register values before every executed instruction;
behaves like --output
""")
parser.add_argument('-s', '--start', metavar='step', type=int,
help="start from instruction step instead of the beginning")
parser.add_argument('-c', '--check', action='store_true',
help="only check the syntax (don't execute the program)")
return parser
def make_printer(what):
if what is None:
return None
if what is True:
return lambda pu: print(pu.registers)
formatter = Formatter()
def printer(pu):
names = dict(pu.registers)
print(formatter.vformat(what, (), names))
return printer
def main(args=None):
parser = make_parser()
args = parser.parse_args(args)
# TODO: validate args.output and args.trace
# TODO: decode character escapes for args.output and args.trace
try:
with args.file as f:
program = Program.load(f)
for error in program.check():
raise error
except ProgramError as e:
parser.error("{} (on line {})".format(e.message, e.line_no))
if args.check:
parser.exit(message=str(program))
if args.start is None:
start = program.start
elif args.start in program:
start = args.start
else:
parser.error("step {} not in program".format(args.start))
trace = make_printer(args.trace)
output = make_printer(args.output)
pu = ProcessingUnit()
pu.registers.update(args.input)
pu.run_program(program, start, trace)
if output:
output(pu)
| lemon24/rap | rap/__init__.py | Python | bsd-3-clause | 5,176 |
// menubar.js
// top menubar icon
const path = require('path');
const db = require('../lib/db');
const switcher = require('../lib/switcher');
const {Tray, Menu} = require('electron').remote;
const iconPath = path.join(__dirname, '../../resources/menubar-alt2.png');
let menubar = null; // prevent GC
module.exports = function() {
db.getCards().then(cards => {
let template = [];
cards.forEach(card => {
template.push({
label: `Switch to ${card.nickname}`,
click() {
switcher.switchTo(card.address, card.username);
}
});
});
template = template.concat([
{
type: 'separator'
},
{
label: 'Quit',
selector: 'terminate:'
}
]);
menubar = new Tray(iconPath);
menubar.setToolTip('Blue');
menubar.setContextMenu(Menu.buildFromTemplate(template));
})
.done();
};
| mysticflute/blue | src/menu/menubar.js | JavaScript | bsd-3-clause | 891 |
/*
-- MAGMA (version 2.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date August 2016
@generated from src/zgels_gpu.cpp, normal z -> s, Tue Aug 30 09:38:06 2016
*/
#include "magma_internal.h"
/***************************************************************************//**
Purpose
-------
SGELS solves the overdetermined, least squares problem
min || A*X - C ||
using the QR factorization A.
The underdetermined problem (m < n) is not currently handled.
Arguments
---------
@param[in]
trans magma_trans_t
- = MagmaNoTrans: the linear system involves A.
Only TRANS=MagmaNoTrans is currently handled.
@param[in]
m INTEGER
The number of rows of the matrix A. M >= 0.
@param[in]
n INTEGER
The number of columns of the matrix A. M >= N >= 0.
@param[in]
nrhs INTEGER
The number of columns of the matrix C. NRHS >= 0.
@param[in,out]
dA REAL array on the GPU, dimension (LDDA,N)
On entry, the M-by-N matrix A.
On exit, A is overwritten by details of its QR
factorization as returned by SGEQRF.
@param[in]
ldda INTEGER
The leading dimension of the array A, LDDA >= M.
@param[in,out]
dB REAL array on the GPU, dimension (LDDB,NRHS)
On entry, the M-by-NRHS matrix C.
On exit, the N-by-NRHS solution matrix X.
@param[in]
lddb INTEGER
The leading dimension of the array dB. LDDB >= M.
@param[out]
hwork (workspace) REAL array, dimension MAX(1,LWORK).
On exit, if INFO = 0, HWORK[0] returns the optimal LWORK.
@param[in]
lwork INTEGER
The dimension of the array HWORK,
LWORK >= (M - N + NB)*(NRHS + NB) + NRHS*NB,
where NB is the blocksize given by magma_get_sgeqrf_nb( M, N ).
\n
If LWORK = -1, then a workspace query is assumed; the routine
only calculates the optimal size of the HWORK array, returns
this value as the first entry of the HWORK array.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
@ingroup magma_gels
*******************************************************************************/
extern "C" magma_int_t
magma_sgels_gpu(
magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
magmaFloat_ptr dA, magma_int_t ldda,
magmaFloat_ptr dB, magma_int_t lddb,
float *hwork, magma_int_t lwork,
magma_int_t *info)
{
magmaFloat_ptr dT;
float *tau;
magma_int_t min_mn;
magma_int_t nb = magma_get_sgeqrf_nb( m, n );
magma_int_t lwkopt = (m - n + nb)*(nrhs + nb) + nrhs*nb;
bool lquery = (lwork == -1);
hwork[0] = magma_smake_lwork( lwkopt );
*info = 0;
/* For now, N is the only case working */
if ( trans != MagmaNoTrans )
*info = -1;
else if (m < 0)
*info = -2;
else if (n < 0 || m < n) /* LQ is not handle for now*/
*info = -3;
else if (nrhs < 0)
*info = -4;
else if (ldda < max(1,m))
*info = -6;
else if (lddb < max(1,m))
*info = -8;
else if (lwork < lwkopt && ! lquery)
*info = -10;
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
else if (lquery)
return *info;
min_mn = min(m,n);
if (min_mn == 0) {
hwork[0] = MAGMA_S_ONE;
return *info;
}
/*
* Allocate temporary buffers
*/
magma_int_t ldtwork = ( 2*min_mn + magma_roundup( n, 32 ) )*nb;
if (nb < nrhs)
ldtwork = ( 2*min_mn + magma_roundup( n, 32 ) )*nrhs;
if (MAGMA_SUCCESS != magma_smalloc( &dT, ldtwork )) {
*info = MAGMA_ERR_DEVICE_ALLOC;
return *info;
}
magma_smalloc_cpu( &tau, min_mn );
if ( tau == NULL ) {
magma_free( dT );
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
magma_sgeqrf_gpu( m, n, dA, ldda, tau, dT, info );
if ( *info == 0 ) {
magma_sgeqrs_gpu( m, n, nrhs,
dA, ldda, tau, dT,
dB, lddb, hwork, lwork, info );
}
magma_free( dT );
magma_free_cpu( tau );
return *info;
}
| maxhutch/magma | src/sgels_gpu.cpp | C++ | bsd-3-clause | 4,464 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pygesture/ui/templates/process_widget_template.ui'
#
# Created by: PyQt5 UI code generator 5.4.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ProcessWidget(object):
def setupUi(self, ProcessWidget):
ProcessWidget.setObjectName("ProcessWidget")
ProcessWidget.resize(823, 539)
self.gridLayout_2 = QtWidgets.QGridLayout(ProcessWidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.titleLabel = QtWidgets.QLabel(ProcessWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.titleLabel.sizePolicy().hasHeightForWidth())
self.titleLabel.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.titleLabel.setFont(font)
self.titleLabel.setText("")
self.titleLabel.setAlignment(QtCore.Qt.AlignCenter)
self.titleLabel.setObjectName("titleLabel")
self.verticalLayout.addWidget(self.titleLabel)
self.gridLayout_2.addLayout(self.verticalLayout, 0, 0, 1, 1)
self.groupBox = QtWidgets.QGroupBox(ProcessWidget)
self.groupBox.setMinimumSize(QtCore.QSize(250, 0))
self.groupBox.setObjectName("groupBox")
self.gridLayout = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout.setObjectName("gridLayout")
self.sessionBrowser = SessionBrowser(self.groupBox)
self.sessionBrowser.setObjectName("sessionBrowser")
self.gridLayout.addWidget(self.sessionBrowser, 0, 0, 1, 1)
self.processButton = QtWidgets.QPushButton(self.groupBox)
self.processButton.setEnabled(False)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.processButton.sizePolicy().hasHeightForWidth())
self.processButton.setSizePolicy(sizePolicy)
self.processButton.setObjectName("processButton")
self.gridLayout.addWidget(self.processButton, 1, 0, 1, 1)
self.progressBar = QtWidgets.QProgressBar(self.groupBox)
self.progressBar.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth())
self.progressBar.setSizePolicy(sizePolicy)
self.progressBar.setMaximum(1)
self.progressBar.setProperty("value", 1)
self.progressBar.setTextVisible(True)
self.progressBar.setOrientation(QtCore.Qt.Horizontal)
self.progressBar.setInvertedAppearance(False)
self.progressBar.setFormat("")
self.progressBar.setObjectName("progressBar")
self.gridLayout.addWidget(self.progressBar, 2, 0, 1, 1)
self.gridLayout_2.addWidget(self.groupBox, 0, 1, 1, 1)
self.retranslateUi(ProcessWidget)
QtCore.QMetaObject.connectSlotsByName(ProcessWidget)
def retranslateUi(self, ProcessWidget):
_translate = QtCore.QCoreApplication.translate
ProcessWidget.setWindowTitle(_translate("ProcessWidget", "Form"))
self.groupBox.setTitle(_translate("ProcessWidget", "Sessions"))
self.processButton.setText(_translate("ProcessWidget", "Process"))
from pygesture.ui.widgets import SessionBrowser
| ixjlyons/pygesture | pygesture/ui/templates/process_widget_template.py | Python | bsd-3-clause | 3,894 |
<?php
namespace Application\Factory;
use Exception;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class DefaultTableGatewayFactory implements AbstractFactoryInterface
{
/**
* Determine if we can create a service with name
*
* @param ServiceLocatorInterface $serviceLocator
* @param $name
* @param $requestedName
* @return bool
*/
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$nameSpace = explode( '\\', $requestedName);
return (isset($nameSpace[1]) && $nameSpace[1] == 'Model' )? true: false;
}
/**
* Create service with name
*
* @param ServiceLocatorInterface $serviceLocator
* @param $name
* @param $requestedName
* @return mixed
* @throws Exception
*/
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$nameSpace = explode( '\\', $requestedName);
$nameSpace [3] = $nameSpace[2];
$nameSpace[2] = 'Tables';
$requestedName = implode('\\', $nameSpace);
$adapter = $serviceLocator->get('Zend\Db\Adapter\Adapter');
$new = new $requestedName($adapter);
return $new;
}
} | Fryday80/SRzA | module/Application/src/Application/Factory/DefaultTableGatewayFactory.php | PHP | bsd-3-clause | 1,295 |
# -#- coding: utf-8 -#-
import feedparser
from django.db import models
from django.utils.translation import ugettext_lazy as _
from leonardo.module.web.models import ContentProxyWidgetMixin
from leonardo.module.web.models import Widget
from leonardo.module.web.widgets.mixins import JSONContentMixin
from leonardo.module.web.widgets.mixins import ListWidgetMixin
class FeedReaderWidget(Widget, JSONContentMixin, ContentProxyWidgetMixin,
ListWidgetMixin):
max_items = models.IntegerField(_('max. items'), default=5)
class Meta:
abstract = True
verbose_name = _("feed reader")
verbose_name_plural = _('feed readers')
def update_cache_data(self, save=True):
pass
def get_data(self):
feed = feedparser.parse(self.source_address)
entries = feed['entries'][:self.max_items]
return entries
| django-leonardo/django-leonardo | leonardo/module/web/widget/feedreader/models.py | Python | bsd-3-clause | 888 |
<?php
declare(strict_types=1);
/**
* @package Garp\Functional
* @author Harmen Janssen <harmen@grrr.nl>
* @license https://github.com/grrr-amsterdam/garp-functional/blob/master/LICENSE.md BSD-3-Clause
*/
namespace Garp\Functional;
/**
* Creates a negative version of an existing function.
*
* Example:
* $a = ['a', 'b', 'c'];
* in_array('a', $a); // true
*
* not('in_array')('a'); // false
* not('in_array')('d'); // true
*
* @param callable $fn Anything that call_user_func_array accepts
* @return callable
*/
function not(callable $fn): callable {
return function (...$args) use ($fn) {
return !$fn(...$args);
};
}
const not = '\Garp\Functional\not'; | grrr-amsterdam/garp-functional | functions/not.php | PHP | bsd-3-clause | 692 |
// Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
// Usage dictionary generator:
// % gen_usage_rewriter_dictionary_main
// --usage_data_file=usage_data.txt
// --cforms_file=cforms.def
// --output=output_header
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "base/file_stream.h"
#include "base/flags.h"
#include "base/init_mozc.h"
#include "base/logging.h"
#include "base/util.h"
DEFINE_string(usage_data_file, "", "usage data file");
DEFINE_string(cforms_file, "", "cforms file");
DEFINE_string(output, "", "output header file");
namespace mozc {
namespace {
struct ConjugationType {
string form;
string value_suffix;
string key_suffix;
};
struct UsageItem {
string key;
string value;
string conjugation;
int conjugation_id;
string meaning;
};
bool UsageItemKeynameCmp(const UsageItem& l, const UsageItem& r) {
return l.key < r.key;
}
// Load cforms_file
void LoadConjugation(const string &filename,
map<string, vector<ConjugationType> > *output,
map<string, ConjugationType> *baseform_map) {
InputFileStream ifs(filename.c_str());
CHECK(ifs.good());
string line;
vector<string> fields;
while (!getline(ifs, line).fail()) {
if (line.empty() || line[0] == '#') {
continue;
}
fields.clear();
Util::SplitStringUsing(line, "\t ", &fields);
CHECK_GE(fields.size(), 4) << "format error: " << line;
ConjugationType tmp;
tmp.form = fields[1];
tmp.value_suffix = ((fields[2] == "*") ? "" : fields[2]);
tmp.key_suffix = ((fields[3] == "*") ? "" : fields[3]);
(*output)[fields[0]].push_back(tmp); // insert
if (tmp.form == "\xE5\x9F\xBA\xE6\x9C\xAC\xE5\xBD\xA2") { // 基本形
(*baseform_map)[fields[0]] = tmp;
}
}
}
// Load usage_data_file
void LoadUsage(const string &filename,
vector<UsageItem> *usage_entries,
vector<string> *conjugation_list) {
InputFileStream ifs(filename.c_str());
if (!ifs.good()) {
LOG(WARNING) << "Can't open file:" << filename;
return;
}
string line;
vector<string> fields;
map<string, int> conjugation_id_map;
int conjugation_id = 0;
while (!getline(ifs, line).fail()) {
if (line.empty() || line[0] == '#') {
// starting with '#' is a comment line.
continue;
}
fields.clear();
Util::SplitStringAllowEmpty(line, "\t", &fields);
CHECK_GE(fields.size(), 4) << "format error: " << line;
UsageItem item;
item.key = ((fields[0] == "*") ? "" : fields[0]);
item.value = ((fields[1] == "*") ? "" : fields[1]);
item.conjugation = ((fields[2] == "*") ? "" : fields[2]);
string tmp = ((fields[3] == "*") ? "" : fields[3]);
Util::StringReplace(tmp, "\\n", "\n", true, &item.meaning);
map<string, int>::iterator it = conjugation_id_map.find(item.conjugation);
if (it == conjugation_id_map.end()) {
conjugation_id_map.insert(
pair<string, int>(item.conjugation, conjugation_id));
item.conjugation_id = conjugation_id;
conjugation_list->push_back(item.conjugation);
++conjugation_id;
} else {
item.conjugation_id = it->second;
}
usage_entries->push_back(item);
}
}
// remove "基本形"'s conjugation suffix
void RemoveBaseformConjugationSuffix(
const map<string, ConjugationType> &baseform_map,
vector<UsageItem> *usage_entries) {
for (vector<UsageItem>::iterator usage_itr = usage_entries->begin();
usage_itr != usage_entries->end(); ++usage_itr) {
const map<string, ConjugationType>::const_iterator baseform_itr =
baseform_map.find(usage_itr->conjugation);
if (baseform_itr == baseform_map.end()) {
continue;
}
const ConjugationType &type = baseform_itr->second;
if (usage_itr->key.length() <= type.key_suffix.length()) {
LOG(WARNING) << "key:[" << usage_itr->key << "] is not longer then "
<< "baseform.key_suffix of \"" << usage_itr->conjugation
<< "\" : [" << type.key_suffix << "]";
}
if (usage_itr->value.length() <= type.value_suffix.length()) {
LOG(WARNING) << "value:[" << usage_itr->value << "] is not longer then "
<< "baseform.value_suffix of \"" << usage_itr->conjugation
<< "\" : [" << type.value_suffix << "]";
}
usage_itr->key.erase(usage_itr->key.length() - type.key_suffix.length());
usage_itr->value.erase(
usage_itr->value.length() - type.value_suffix.length());
}
}
void Convert() {
// Load cforms_file
map<string, vector<ConjugationType> > inflection_map;
map<string, ConjugationType> baseform_map;
LoadConjugation(FLAGS_cforms_file, &inflection_map, &baseform_map);
// Load usage_data_file
vector<UsageItem> usage_entries;
vector<string> conjugation_list;
LoadUsage(FLAGS_usage_data_file, &usage_entries, &conjugation_list);
ostream *ofs = &std::cout;
if (!FLAGS_output.empty()) {
ofs = new OutputFileStream(FLAGS_output.c_str());
}
*ofs << "// This header file is generated by "
<< "gen_usage_rewriter_dictionary_main." << std::endl;
// Output kConjugationNum
*ofs << "static const int kConjugationNum = " << conjugation_list.size()
<< ";" << std::endl;
// Output kBaseConjugationSuffix
*ofs << "static const ConjugationSuffix kBaseConjugationSuffix[] = {"
<< std::endl;
for (size_t i = 0; i < conjugation_list.size(); ++i) {
string value_suffix, key_suffix;
Util::Escape(baseform_map[conjugation_list[i]].value_suffix, &value_suffix);
Util::Escape(baseform_map[conjugation_list[i]].key_suffix, &key_suffix);
*ofs << " {\"" << value_suffix << "\", \"" << key_suffix << "\"}, "
<< "// " << conjugation_list[i] << std::endl;
}
*ofs << "};" << std::endl;
// Output kConjugationSuffixData
vector<int> conjugation_index(conjugation_list.size() + 1);
*ofs << "static const ConjugationSuffix kConjugationSuffixData[] = {"
<< std::endl;
int out_count = 0;
for (size_t i = 0; i < conjugation_list.size(); ++i) {
vector<ConjugationType> conjugations = inflection_map[conjugation_list[i]];
conjugation_index[i] = out_count;
if (conjugations.size() == 0) {
*ofs << " // " << i << ": (" << out_count << "-" << out_count
<< "): no conjugations" << std::endl;
*ofs << " {\"\",\"\"}," << std::endl;
++out_count;
} else {
typedef pair<string, string> StrPair;
set<StrPair> key_and_value_suffix_set;
for (size_t j = 0; j < conjugations.size(); ++j) {
StrPair key_and_value_suffix(conjugations[j].value_suffix,
conjugations[j].key_suffix);
key_and_value_suffix_set.insert(key_and_value_suffix);
}
*ofs << " // " << i << ": (" << out_count << "-"
<< (out_count + key_and_value_suffix_set.size() - 1)
<< "): " << conjugation_list[i] << std::endl
<< " ";
set<StrPair>::iterator itr;
for (itr = key_and_value_suffix_set.begin();
itr != key_and_value_suffix_set.end(); ++itr) {
string value_suffix, key_suffix;
Util::Escape(itr->first, &value_suffix);
Util::Escape(itr->second, &key_suffix);
*ofs << " {\"" << value_suffix <<
"\", \"" << key_suffix << "\"},";
++out_count;
}
*ofs << std::endl;
}
}
*ofs << "};" << std::endl;
conjugation_index[conjugation_list.size()] = out_count;
// Output kConjugationSuffixDataIndex
*ofs << "static const int kConjugationSuffixDataIndex[] = {";
for (size_t i = 0; i < conjugation_index.size(); ++i) {
if (i != 0) {
*ofs << ", ";
}
*ofs << conjugation_index[i];
}
*ofs << "};" << std::endl;
RemoveBaseformConjugationSuffix(baseform_map, &usage_entries);
std::sort(usage_entries.begin(), usage_entries.end(), UsageItemKeynameCmp);
// Output kUsageDataSize
*ofs << "static const size_t kUsageDataSize = " << usage_entries.size() << ";"
<< std::endl;
// Output kUsageData_value
*ofs << "static const UsageDictItem kUsageData_value[] = {" << std::endl;
int32 usage_id = 0;
for (vector<UsageItem>::iterator i = usage_entries.begin();
i != usage_entries.end(); i++) {
string key, value, meaning;
Util::Escape(i->key, &key);
Util::Escape(i->value, &value);
Util::Escape(i->meaning, &meaning);
*ofs << " {" << usage_id << ", \"" << key << "\", "
<< "\"" << value << "\", "
<< "" << i->conjugation_id << ", "
<< "\"" << meaning << "\"}, // " << i->value << "(" << i->key << ")"
<< std::endl;
++usage_id;
}
*ofs << " { 0, NULL, NULL, 0, NULL }" << std::endl;
*ofs << "};" << std::endl;
if (ofs != &std::cout) {
delete ofs;
}
}
} // namespace
} // namespace mozc
int main(int argc, char **argv) {
mozc::InitMozc(argv[0], &argc, &argv, true);
mozc::Convert();
return 0;
}
| kbc-developers/Mozc | src/rewriter/gen_usage_rewriter_dictionary_main.cc | C++ | bsd-3-clause | 10,507 |
var class_app_store_1_1_models_1_1_category_instance =
[
[ "category", "de/d27/class_app_store_1_1_models_1_1_category_instance.html#ac1e8313d7f7d58349cf972f2be0ae365", null ]
]; | BuildmLearn/BuildmLearn-Store | WP/doc/DOxygen_HTML/de/d27/class_app_store_1_1_models_1_1_category_instance.js | JavaScript | bsd-3-clause | 182 |
// Copyright 2016 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "starboard/window.h"
void* SbWindowGetPlatformHandle(SbWindow window) {
return NULL;
}
| youtube/cobalt | starboard/shared/stub/window_get_platform_handle.cc | C++ | bsd-3-clause | 717 |
#include <stdio.h>
#include <cybozu/thread.hpp>
#include <cybozu/event.hpp>
#include <cybozu/test.hpp>
class Thread : public cybozu::ThreadBase {
cybozu::Event& ev_;
public:
bool done_;
Thread(cybozu::Event& ev)
: ev_(ev)
, done_(false)
{
}
void threadEntry()
{
puts("thread");
puts("sleep 100msec");
cybozu::Sleep(100);
puts("wakeup");
ev_.wakeup();
cybozu::Sleep(100);
ev_.wakeup();
}
};
CYBOZU_TEST_AUTO(event_test)
{
cybozu::Event ev;
Thread th(ev);
th.beginThread();
ev.wait();
puts("done");
ev.wait();
puts("done");
th.joinThread();
}
| herumi/cybozulib | test/base/event_test.cpp | C++ | bsd-3-clause | 581 |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2012. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy,
// Seaford, Vic 3198, Australia and are supplied subject to licence terms.
//
// Version 4.4.1.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
/// <summary>
/// View element adds padding to the provided drawing area.
/// </summary>
internal class ViewLayoutRibbonPadding : ViewComposite
{
#region Instance Fields
private Padding _preferredPadding;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewLayoutRibbonPadding class.
/// </summary>
/// <param name="preferredPadding">Padding to use when calculating space.</param>
public ViewLayoutRibbonPadding(Padding preferredPadding)
{
_preferredPadding = preferredPadding;
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewLayoutRibbonPadding:" + Id;
}
#endregion
#region Layout
/// <summary>
/// Discover the preferred size of the element.
/// </summary>
/// <param name="context">Layout context.</param>
public override Size GetPreferredSize(ViewLayoutContext context)
{
// Get the preferred size of the contained content
Size preferredSize = base.GetPreferredSize(context);
// Add on the padding we need around edges
return new Size(preferredSize.Width + _preferredPadding.Horizontal,
preferredSize.Height + _preferredPadding.Vertical);
}
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
// Validate incoming reference
if (context == null) throw new ArgumentNullException("context");
// We take on all the available display area
ClientRectangle = context.DisplayRectangle;
// Find the rectangle for the child elements by applying padding
context.DisplayRectangle = CommonHelper.ApplyPadding(Orientation.Horizontal, ClientRectangle, _preferredPadding);
// Let base perform actual layout process of child elements
base.Layout(context);
// Put back the original display value now we have finished
context.DisplayRectangle = ClientRectangle;
}
#endregion
}
}
| Cocotteseb/Krypton | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Layout/ViewLayoutRibbonPadding.cs | C# | bsd-3-clause | 3,234 |
// Copyright 2009 The Ninep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package clnt
var m2id = [...]uint8{
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 6,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 7,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 6,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 0,
}
func newPool(maxid uint32) *pool {
p := new(pool)
p.maxid = maxid
p.nchan = make(chan uint32)
return p
}
func (p *pool) getId() uint32 {
var n uint32 = 0
var ret uint32
p.Lock()
for n = 0; n < uint32(len(p.imap)); n++ {
if p.imap[n] != 0xFF {
break
}
}
if int(n) >= len(p.imap) {
m := uint32(len(p.imap) + 32)
if uint32(m*8) > p.maxid {
m = p.maxid/8 + 1
}
b := make([]byte, m)
copy(b, p.imap)
p.imap = b
}
if n >= uint32(len(p.imap)) {
p.need++
p.Unlock()
ret = <-p.nchan
} else {
ret = uint32(m2id[p.imap[n]])
p.imap[n] |= 1 << ret
ret += n * 8
p.Unlock()
}
return ret
}
func (p *pool) putId(id uint32) {
p.Lock()
if p.need > 0 {
p.nchan <- id
p.need--
p.Unlock()
return
}
p.imap[id/8] &= ^(1 << (id % 8))
p.Unlock()
}
| lionkov/ninep | clnt/pool.go | GO | bsd-3-clause | 1,798 |
<?php
use yii\db\Migration;
class m170212_160300_modify_subscription extends Migration
{
public function up() {
$this->addColumn('subscription', 'good_id', \yii\db\Schema::TYPE_INTEGER);
$this->addForeignKey(
'fk-subscription-good_id',
'subscription',
'good_id',
'good',
'id',
'CASCADE'
);
}
public function down() {
$this->dropForeignKey('fk-subscription-good_id', 'subscription');
$this->dropColumn('subscription', 'good_id');
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
| AlexanderBliznuk/disposable_razors | migrations/m170212_160300_modify_subscription.php | PHP | bsd-3-clause | 735 |
package abi38_0_0.expo.modules.taskManager;
import android.app.PendingIntent;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.util.Log;
import org.unimodules.interfaces.taskManager.TaskInterface;
import org.unimodules.interfaces.taskManager.TaskManagerUtilsInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import androidx.annotation.NonNull;
import androidx.collection.ArraySet;
public class TaskManagerUtils implements TaskManagerUtilsInterface {
// Key that every job created by the task manager must contain in its extras bundle.
private static final String EXTRAS_REQUIRED_KEY = "expo.modules.taskManager";
private static final String TAG = "TaskManagerUtils";
// Request code number used for pending intents created by this module.
private static final int PENDING_INTENT_REQUEST_CODE = 5055;
private static final int DEFAULT_OVERRIDE_DEADLINE = 60 * 1000; // 1 minute
private static final Set<TaskInterface> sTasksReschedulingJob = new ArraySet<>();
//region TaskManagerUtilsInterface
@Override
public PendingIntent createTaskIntent(Context context, TaskInterface task) {
return createTaskIntent(context, task, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public void cancelTaskIntent(Context context, String appId, String taskName) {
PendingIntent pendingIntent = createTaskIntent(context, appId, taskName, PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
pendingIntent.cancel();
}
}
@Override
public void scheduleJob(Context context, @NonNull TaskInterface task, List<PersistableBundle> data) {
if (task == null) {
Log.e(TAG, "Trying to schedule job for null task!");
} else {
updateOrScheduleJob(context, task, data);
}
}
@Override
public void cancelScheduledJob(Context context, int jobId) {
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.cancel(jobId);
} else {
Log.e(this.getClass().getName(), "Job scheduler not found!");
}
}
@Override
public List<PersistableBundle> extractDataFromJobParams(JobParameters params) {
PersistableBundle extras = params.getExtras();
List<PersistableBundle> data = new ArrayList<>();
int dataSize = extras.getInt("dataSize", 0);
for (int i = 0; i < dataSize; i++) {
data.add(extras.getPersistableBundle(String.valueOf(i)));
}
return data;
}
//endregion TaskManagerUtilsInterface
//region static helpers
static boolean notifyTaskJobCancelled(TaskInterface task) {
boolean isRescheduled = sTasksReschedulingJob.contains(task);
if (isRescheduled) {
sTasksReschedulingJob.remove(task);
}
return isRescheduled;
}
//endregion static helpers
//region private helpers
private void updateOrScheduleJob(Context context, TaskInterface task, List<PersistableBundle> data) {
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler == null) {
Log.e(this.getClass().getName(), "Job scheduler not found!");
return;
}
List<JobInfo> pendingJobs = jobScheduler.getAllPendingJobs();
Collections.sort(pendingJobs, new Comparator<JobInfo>() {
@Override
public int compare(JobInfo a, JobInfo b) {
return Integer.compare(a.getId(), b.getId());
}
});
// We will be looking for the lowest number that is not being used yet.
int newJobId = 0;
for (JobInfo jobInfo : pendingJobs) {
int jobId = jobInfo.getId();
if (isJobInfoRelatedToTask(jobInfo, task)) {
JobInfo mergedJobInfo = createJobInfoByAddingData(jobInfo, data);
// Add the task to the list of rescheduled tasks.
sTasksReschedulingJob.add(task);
try {
// Cancel jobs with the same ID to let them be rescheduled.
jobScheduler.cancel(jobId);
// Reschedule job for given task.
jobScheduler.schedule(mergedJobInfo);
} catch (IllegalStateException e) {
Log.e(this.getClass().getName(), "Unable to reschedule a job: " + e.getMessage());
}
return;
}
if (newJobId == jobId) {
newJobId++;
}
}
try {
// Given task doesn't have any pending jobs yet, create a new JobInfo and schedule it then.
JobInfo jobInfo = createJobInfo(context, task, newJobId, data);
jobScheduler.schedule(jobInfo);
} catch (IllegalStateException e) {
Log.e(this.getClass().getName(), "Unable to schedule a new job: " + e.getMessage());
}
}
private JobInfo createJobInfoByAddingData(JobInfo jobInfo, List<PersistableBundle> data) {
PersistableBundle mergedExtras = jobInfo.getExtras();
int dataSize = mergedExtras.getInt("dataSize", 0);
if (data != null) {
mergedExtras.putInt("dataSize", dataSize + data.size());
for (int i = 0; i < data.size(); i++) {
mergedExtras.putPersistableBundle(String.valueOf(dataSize + i), data.get(i));
}
}
return createJobInfo(jobInfo.getId(), jobInfo.getService(), mergedExtras);
}
private PendingIntent createTaskIntent(Context context, String appId, String taskName, int flags) {
if (context == null) {
return null;
}
Intent intent = new Intent(TaskBroadcastReceiver.INTENT_ACTION, null, context, TaskBroadcastReceiver.class);
Uri dataUri = new Uri.Builder()
.appendQueryParameter("appId", appId)
.appendQueryParameter("taskName", taskName)
.build();
intent.setData(dataUri);
return PendingIntent.getBroadcast(context, PENDING_INTENT_REQUEST_CODE, intent, flags);
}
private PendingIntent createTaskIntent(Context context, TaskInterface task, int flags) {
String appId = task.getAppId();
String taskName = task.getName();
return createTaskIntent(context, appId, taskName, flags);
}
private JobInfo createJobInfo(int jobId, ComponentName jobService, PersistableBundle extras) {
return new JobInfo.Builder(jobId, jobService)
.setExtras(extras)
.setMinimumLatency(0)
.setOverrideDeadline(DEFAULT_OVERRIDE_DEADLINE)
.build();
}
private JobInfo createJobInfo(Context context, TaskInterface task, int jobId, List<PersistableBundle> data) {
return createJobInfo(jobId, new ComponentName(context, TaskJobService.class), createExtrasForTask(task, data));
}
private PersistableBundle createExtrasForTask(TaskInterface task, List<PersistableBundle> data) {
PersistableBundle extras = new PersistableBundle();
extras.putInt(EXTRAS_REQUIRED_KEY, 1);
extras.putString("appId", task.getAppId());
extras.putString("taskName", task.getName());
if (data != null) {
extras.putInt("dataSize", data.size());
for (int i = 0; i < data.size(); i++) {
extras.putPersistableBundle(String.valueOf(i), data.get(i));
}
} else {
extras.putInt("dataSize", 0);
}
return extras;
}
private boolean isJobInfoRelatedToTask(JobInfo jobInfo, TaskInterface task) {
PersistableBundle extras = jobInfo.getExtras();
String appId = task.getAppId();
String taskName = task.getName();
if (extras.containsKey(EXTRAS_REQUIRED_KEY)) {
return appId.equals(extras.getString("appId", "")) && taskName.equals(extras.getString("taskName", ""));
}
return false;
}
//endregion private helpers
//region converting map to bundle
@SuppressWarnings("unchecked")
static Bundle mapToBundle(Map<String, Object> map) {
Bundle bundle = new Bundle();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object value = entry.getValue();
String key = entry.getKey();
if (value instanceof Double) {
bundle.putDouble(key, (Double) value);
} else if (value instanceof Integer) {
bundle.putInt(key, (Integer) value);
} else if (value instanceof String) {
bundle.putString(key, (String) value);
} else if (value instanceof Boolean) {
bundle.putBoolean(key, (Boolean) value);
} else if (value instanceof List) {
List<Object> list = (List<Object>) value;
Object first = list.get(0);
if (first == null || first instanceof Double) {
bundle.putDoubleArray(key, listToDoubleArray(list));
} else if (first instanceof Integer) {
bundle.putIntArray(key, listToIntArray(list));
} else if (first instanceof String) {
bundle.putStringArray(key, listToStringArray(list));
} else if (first instanceof Map) {
bundle.putParcelableArrayList(key, listToParcelableArrayList(list));
}
} else if (value instanceof Map) {
bundle.putBundle(key, mapToBundle((Map<String, Object>) value));
}
}
return bundle;
}
@SuppressWarnings("unchecked")
private static double[] listToDoubleArray(List<Object> list) {
double[] doubles = new double[list.size()];
for (int i = 0; i < list.size(); i++) {
doubles[i] = (Double) list.get(i);
}
return doubles;
}
@SuppressWarnings("unchecked")
private static int[] listToIntArray(List<Object> list) {
int[] integers = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
integers[i] = (Integer) list.get(i);
}
return integers;
}
@SuppressWarnings("unchecked")
private static String[] listToStringArray(List<Object> list) {
String[] strings = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
strings[i] = list.get(i).toString();
}
return strings;
}
@SuppressWarnings("unchecked")
private static ArrayList<Parcelable> listToParcelableArrayList(List<Object> list) {
ArrayList<Parcelable> arrayList = new ArrayList<>();
for (Object item : list) {
Map<String, Object> map = (Map<String, Object>) item;
arrayList.add(mapToBundle(map));
}
return arrayList;
}
//endregion converting map to bundle
}
| exponent/exponent | android/versioned-abis/expoview-abi38_0_0/src/main/java/abi38_0_0/expo/modules/taskManager/TaskManagerUtils.java | Java | bsd-3-clause | 10,404 |
var CoreView = require('backbone/core-view');
var ModalsServiceModel = require('../../../../../javascripts/cartodb3/components/modals/modals-service-model');
var Router = require('../../../../../javascripts/cartodb3/routes/router');
describe('components/modals/modals-service-model', function () {
beforeEach(function () {
this.modals = new ModalsServiceModel();
this.willCreateModalSpy = jasmine.createSpy('willCreateModal');
this.didCreateModalSpy = jasmine.createSpy('didCreateModal');
this.modals.on('willCreateModal', this.willCreateModalSpy);
this.modals.on('didCreateModal', this.didCreateModalSpy);
});
describe('.create', function () {
var contentView, contentView2;
beforeEach(function () {
spyOn(Router, 'navigate');
spyOn(document.body, 'appendChild');
contentView = new CoreView();
spyOn(contentView, 'render').and.callThrough();
this.modalView = this.modals.create(function () {
return contentView;
});
});
it('should return a modal view', function () {
expect(this.modalView).toBeDefined();
});
it('should trigger a willCreateModal event', function () {
expect(this.willCreateModalSpy).toHaveBeenCalled();
});
it('should trigger a didCreateModal event', function () {
expect(this.didCreateModalSpy).toHaveBeenCalled();
});
it('should render the content view', function () {
expect(contentView.render).toHaveBeenCalled();
});
it('should append the modal to the body', function () {
expect(document.body.appendChild).toHaveBeenCalledWith(this.modalView.el);
});
it('should add the special body class', function () {
expect(document.body.className).toContain('is-inDialog');
});
describe('subsequent calls', function () {
beforeEach(function () {
contentView2 = new CoreView();
spyOn(contentView2, 'render').and.callThrough();
this.modalView2 = this.modals.create(function () {
return contentView2;
});
});
it('should reuse modal view', function () {
expect(this.modalView2).toBe(this.modalView);
});
it('should append the new modal to the body', function () {
expect(document.body.appendChild).toHaveBeenCalledWith(this.modalView2.el);
});
it('should keep the special body class', function () {
expect(document.body.className).toContain('is-inDialog');
});
describe('when destroyed', function () {
beforeEach(function () {
jasmine.clock().install();
this.destroyOnceSpy = jasmine.createSpy('destroyedModal');
this.modals.onDestroyOnce(this.destroyOnceSpy);
spyOn(this.modalView2, 'clean').and.callThrough();
this.modalView2.destroy();
});
afterEach(function () {
jasmine.clock().uninstall();
});
it('should not clean the view right away but wait until after animation', function () {
expect(this.modalView2.clean).not.toHaveBeenCalled();
});
it('should have closing animation', function () {
expect(this.modalView2.el.className).toContain('is-closing');
expect(this.modalView2.el.className).not.toContain('is-opening');
});
it('should remove the special body class', function () {
expect(document.body.className).not.toContain('is-inDialog');
});
describe('when close animation is done', function () {
beforeEach(function () {
jasmine.clock().tick(250);
});
it('should have cleaned the view', function () {
expect(this.modalView2.clean).toHaveBeenCalled();
});
it('should have triggered listener', function () {
expect(this.destroyOnceSpy).toHaveBeenCalled();
});
});
});
});
});
});
| splashblot/dronedb | lib/assets/test/spec/cartodb3/components/modals/modals-service-model.spec.js | JavaScript | bsd-3-clause | 3,915 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The astropy.utils.iers package provides access to the tables provided by
the International Earth Rotation and Reference Systems Service, in
particular allowing interpolation of published UT1-UTC values for given
times. These are used in `astropy.time` to provide UT1 values. The polar
motions are also used for determining earth orientation for
celestial-to-terrestrial coordinate transformations
(in `astropy.coordinates`).
"""
from warnings import warn
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import numpy as np
from astropy import config as _config
from astropy import units as u
from astropy.table import Table, QTable
from astropy.utils.data import get_pkg_data_filename, clear_download_cache
from astropy import utils
from astropy.utils.exceptions import AstropyWarning
__all__ = ['Conf', 'conf',
'IERS', 'IERS_B', 'IERS_A', 'IERS_Auto',
'FROM_IERS_B', 'FROM_IERS_A', 'FROM_IERS_A_PREDICTION',
'TIME_BEFORE_IERS_RANGE', 'TIME_BEYOND_IERS_RANGE',
'IERS_A_FILE', 'IERS_A_URL', 'IERS_A_URL_MIRROR', 'IERS_A_README',
'IERS_B_FILE', 'IERS_B_URL', 'IERS_B_README',
'IERSRangeError', 'IERSStaleWarning']
# IERS-A default file name, URL, and ReadMe with content description
IERS_A_FILE = 'finals2000A.all'
IERS_A_URL = 'https://maia.usno.navy.mil/ser7/finals2000A.all'
IERS_A_URL_MIRROR = 'https://toshi.nofs.navy.mil/ser7/finals2000A.all'
IERS_A_README = get_pkg_data_filename('data/ReadMe.finals2000A')
# IERS-B default file name, URL, and ReadMe with content description
IERS_B_FILE = get_pkg_data_filename('data/eopc04_IAU2000.62-now')
IERS_B_URL = 'http://hpiers.obspm.fr/iers/eop/eopc04/eopc04_IAU2000.62-now'
IERS_B_README = get_pkg_data_filename('data/ReadMe.eopc04_IAU2000')
# Status/source values returned by IERS.ut1_utc
FROM_IERS_B = 0
FROM_IERS_A = 1
FROM_IERS_A_PREDICTION = 2
TIME_BEFORE_IERS_RANGE = -1
TIME_BEYOND_IERS_RANGE = -2
MJD_ZERO = 2400000.5
INTERPOLATE_ERROR = """\
interpolating from IERS_Auto using predictive values that are more
than {0} days old.
Normally you should not see this error because this class
automatically downloads the latest IERS-A table. Perhaps you are
offline? If you understand what you are doing then this error can be
suppressed by setting the auto_max_age configuration variable to
``None``:
from astropy.utils.iers import conf
conf.auto_max_age = None
"""
def download_file(*args, **kwargs):
"""
Overload astropy.utils.data.download_file within iers module to use a
custom (longer) wait time. This just passes through ``*args`` and
``**kwargs`` after temporarily setting the download_file remote timeout to
the local ``iers.conf.remote_timeout`` value.
"""
with utils.data.conf.set_temp('remote_timeout', conf.remote_timeout):
return utils.data.download_file(*args, **kwargs)
class IERSStaleWarning(AstropyWarning):
pass
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.utils.iers`.
"""
auto_download = _config.ConfigItem(
True,
'Enable auto-downloading of the latest IERS data. If set to False '
'then the local IERS-B file will be used by default. Default is True.')
auto_max_age = _config.ConfigItem(
30.0,
'Maximum age (days) of predictive data before auto-downloading. Default is 30.')
iers_auto_url = _config.ConfigItem(
IERS_A_URL,
'URL for auto-downloading IERS file data.')
iers_auto_url_mirror = _config.ConfigItem(
IERS_A_URL_MIRROR,
'Mirror URL for auto-downloading IERS file data.')
remote_timeout = _config.ConfigItem(
10.0,
'Remote timeout downloading IERS file data (seconds).')
conf = Conf()
class IERSRangeError(IndexError):
"""
Any error for when dates are outside of the valid range for IERS
"""
class IERS(QTable):
"""Generic IERS table class, defining interpolation functions.
Sub-classed from `astropy.table.QTable`. The table should hold columns
'MJD', 'UT1_UTC', 'dX_2000A'/'dY_2000A', and 'PM_x'/'PM_y'.
"""
iers_table = None
@classmethod
def open(cls, file=None, cache=False, **kwargs):
"""Open an IERS table, reading it from a file if not loaded before.
Parameters
----------
file : str or None
full local or network path to the ascii file holding IERS data,
for passing on to the ``read`` class methods (further optional
arguments that are available for some IERS subclasses can be added).
If None, use the default location from the ``read`` class method.
cache : bool
Whether to use cache. Defaults to False, since IERS files
are regularly updated.
Returns
-------
An IERS table class instance
Notes
-----
On the first call in a session, the table will be memoized (in the
``iers_table`` class attribute), and further calls to ``open`` will
return this stored table if ``file=None`` (the default).
If a table needs to be re-read from disk, pass on an explicit file
location or use the (sub-class) close method and re-open.
If the location is a network location it is first downloaded via
download_file.
For the IERS class itself, an IERS_B sub-class instance is opened.
"""
if file is not None or cls.iers_table is None:
if file is not None:
if urlparse(file).netloc:
kwargs.update(file=download_file(file, cache=cache))
else:
kwargs.update(file=file)
cls.iers_table = cls.read(**kwargs)
return cls.iers_table
@classmethod
def close(cls):
"""Remove the IERS table from the class.
This allows the table to be re-read from disk during one's session
(e.g., if one finds it is out of date and has updated the file).
"""
cls.iers_table = None
def mjd_utc(self, jd1, jd2=0.):
"""Turn a time to MJD, returning integer and fractional parts.
Parameters
----------
jd1 : float, array, or Time
first part of two-part JD, or Time object
jd2 : float or array, optional
second part of two-part JD.
Default is 0., ignored if jd1 is `~astropy.time.Time`.
Returns
-------
mjd : float or array
integer part of MJD
utc : float or array
fractional part of MJD
"""
try: # see if this is a Time object
jd1, jd2 = jd1.utc.jd1, jd1.utc.jd2
except Exception:
pass
mjd = np.floor(jd1 - MJD_ZERO + jd2)
utc = jd1 - (MJD_ZERO+mjd) + jd2
return mjd, utc
def ut1_utc(self, jd1, jd2=0., return_status=False):
"""Interpolate UT1-UTC corrections in IERS Table for given dates.
Parameters
----------
jd1 : float, float array, or Time object
first part of two-part JD, or Time object
jd2 : float or float array, optional
second part of two-part JD.
Default is 0., ignored if jd1 is `~astropy.time.Time`.
return_status : bool
Whether to return status values. If False (default),
raise ``IERSRangeError`` if any time is out of the range covered
by the IERS table.
Returns
-------
ut1_utc : float or float array
UT1-UTC, interpolated in IERS Table
status : int or int array
Status values (if ``return_status``=``True``)::
``iers.FROM_IERS_B``
``iers.FROM_IERS_A``
``iers.FROM_IERS_A_PREDICTION``
``iers.TIME_BEFORE_IERS_RANGE``
``iers.TIME_BEYOND_IERS_RANGE``
"""
return self._interpolate(jd1, jd2, ['UT1_UTC'],
self.ut1_utc_source if return_status else None)
def dcip_xy(self, jd1, jd2=0., return_status=False):
"""Interpolate CIP corrections in IERS Table for given dates.
Parameters
----------
jd1 : float, float array, or Time object
first part of two-part JD, or Time object
jd2 : float or float array, optional
second part of two-part JD (default 0., ignored if jd1 is Time)
return_status : bool
Whether to return status values. If False (default),
raise ``IERSRangeError`` if any time is out of the range covered
by the IERS table.
Returns
-------
D_x : Quantity with angle units
x component of CIP correction for the requested times
D_y : Quantity with angle units
y component of CIP correction for the requested times
status : int or int array
Status values (if ``return_status``=``True``)::
``iers.FROM_IERS_B``
``iers.FROM_IERS_A``
``iers.FROM_IERS_A_PREDICTION``
``iers.TIME_BEFORE_IERS_RANGE``
``iers.TIME_BEYOND_IERS_RANGE``
"""
return self._interpolate(jd1, jd2, ['dX_2000A', 'dY_2000A'],
self.dcip_source if return_status else None)
def pm_xy(self, jd1, jd2=0., return_status=False):
"""Interpolate polar motions from IERS Table for given dates.
Parameters
----------
jd1 : float, float array, or Time object
first part of two-part JD, or Time object
jd2 : float or float array, optional
second part of two-part JD.
Default is 0., ignored if jd1 is `~astropy.time.Time`.
return_status : bool
Whether to return status values. If False (default),
raise ``IERSRangeError`` if any time is out of the range covered
by the IERS table.
Returns
-------
PM_x : Quantity with angle units
x component of polar motion for the requested times
PM_y : Quantity with angle units
y component of polar motion for the requested times
status : int or int array
Status values (if ``return_status``=``True``)::
``iers.FROM_IERS_B``
``iers.FROM_IERS_A``
``iers.FROM_IERS_A_PREDICTION``
``iers.TIME_BEFORE_IERS_RANGE``
``iers.TIME_BEYOND_IERS_RANGE``
"""
return self._interpolate(jd1, jd2, ['PM_x', 'PM_y'],
self.pm_source if return_status else None)
def _check_interpolate_indices(self, indices_orig, indices_clipped, max_input_mjd):
"""
Check that the indices from interpolation match those after clipping
to the valid table range. This method gets overridden in the IERS_Auto
class because it has different requirements.
"""
if np.any(indices_orig != indices_clipped):
raise IERSRangeError('(some) times are outside of range covered '
'by IERS table.')
def _interpolate(self, jd1, jd2, columns, source=None):
mjd, utc = self.mjd_utc(jd1, jd2)
# enforce array
is_scalar = not hasattr(mjd, '__array__') or mjd.ndim == 0
if is_scalar:
mjd = np.array([mjd])
utc = np.array([utc])
self._refresh_table_as_needed(mjd)
# For typical format, will always find a match (since MJD are integer)
# hence, important to define which side we will be; this ensures
# self['MJD'][i-1]<=mjd<self['MJD'][i]
i = np.searchsorted(self['MJD'].value, mjd, side='right')
# Get index to MJD at or just below given mjd, clipping to ensure we
# stay in range of table (status will be set below for those outside)
i1 = np.clip(i, 1, len(self) - 1)
i0 = i1 - 1
mjd_0, mjd_1 = self['MJD'][i0].value, self['MJD'][i1].value
results = []
for column in columns:
val_0, val_1 = self[column][i0], self[column][i1]
d_val = val_1 - val_0
if column == 'UT1_UTC':
# Check & correct for possible leap second (correcting diff.,
# not 1st point, since jump can only happen right at 2nd point)
d_val -= d_val.round()
# Linearly interpolate (which is what TEMPO does for UT1-UTC, but
# may want to follow IERS gazette #13 for more precise
# interpolation and correction for tidal effects;
# http://maia.usno.navy.mil/iers-gaz13)
val = val_0 + (mjd - mjd_0 + utc) / (mjd_1 - mjd_0) * d_val
# Do not extrapolate outside range, instead just propagate last values.
val[i == 0] = self[column][0]
val[i == len(self)] = self[column][-1]
if is_scalar:
val = val[0]
results.append(val)
if source:
# Set status to source, using the routine passed in.
status = source(i1)
# Check for out of range
status[i == 0] = TIME_BEFORE_IERS_RANGE
status[i == len(self)] = TIME_BEYOND_IERS_RANGE
if is_scalar:
status = status[0]
results.append(status)
return results
else:
self._check_interpolate_indices(i1, i, np.max(mjd))
return results[0] if len(results) == 1 else results
def _refresh_table_as_needed(self, mjd):
"""
Potentially update the IERS table in place depending on the requested
time values in ``mdj`` and the time span of the table. The base behavior
is not to update the table. ``IERS_Auto`` overrides this method.
"""
pass
def ut1_utc_source(self, i):
"""Source for UT1-UTC. To be overridden by subclass."""
return np.zeros_like(i)
def dcip_source(self, i):
"""Source for CIP correction. To be overridden by subclass."""
return np.zeros_like(i)
def pm_source(self, i):
"""Source for polar motion. To be overridden by subclass."""
return np.zeros_like(i)
@property
def time_now(self):
"""
Property to provide the current time, but also allow for explicitly setting
the _time_now attribute for testing purposes.
"""
from astropy.time import Time
try:
return self._time_now
except Exception:
return Time.now()
class IERS_A(IERS):
"""IERS Table class targeted to IERS A, provided by USNO.
These include rapid turnaround and predicted times.
See http://maia.usno.navy.mil/
Notes
-----
The IERS A file is not part of astropy. It can be downloaded from
``iers.IERS_A_URL`` or ``iers.IERS_A_URL_MIRROR``. See ``iers.__doc__``
for instructions on use in ``Time``, etc.
"""
iers_table = None
@classmethod
def _combine_a_b_columns(cls, iers_a):
"""
Return a new table with appropriate combination of IERS_A and B columns.
"""
# IERS A has some rows at the end that hold nothing but dates & MJD
# presumably to be filled later. Exclude those a priori -- there
# should at least be a predicted UT1-UTC and PM!
table = iers_a[~iers_a['UT1_UTC_A'].mask &
~iers_a['PolPMFlag_A'].mask]
# This does nothing for IERS_A, but allows IERS_Auto to ensure the
# IERS B values in the table are consistent with the true ones.
table = cls._substitute_iers_b(table)
# Run np.where on the data from the table columns, since in numpy 1.9
# it otherwise returns an only partially initialized column.
table['UT1_UTC'] = np.where(table['UT1_UTC_B'].mask,
table['UT1_UTC_A'].data,
table['UT1_UTC_B'].data)
# Ensure the unit is correct, for later column conversion to Quantity.
table['UT1_UTC'].unit = table['UT1_UTC_A'].unit
table['UT1Flag'] = np.where(table['UT1_UTC_B'].mask,
table['UT1Flag_A'].data,
'B')
# Repeat for polar motions.
table['PM_x'] = np.where(table['PM_X_B'].mask,
table['PM_x_A'].data,
table['PM_X_B'].data)
table['PM_x'].unit = table['PM_x_A'].unit
table['PM_y'] = np.where(table['PM_Y_B'].mask,
table['PM_y_A'].data,
table['PM_Y_B'].data)
table['PM_y'].unit = table['PM_y_A'].unit
table['PolPMFlag'] = np.where(table['PM_X_B'].mask,
table['PolPMFlag_A'].data,
'B')
table['dX_2000A'] = np.where(table['dX_2000A_B'].mask,
table['dX_2000A_A'].data,
table['dX_2000A_B'].data)
table['dX_2000A'].unit = table['dX_2000A_A'].unit
table['dY_2000A'] = np.where(table['dY_2000A_B'].mask,
table['dY_2000A_A'].data,
table['dY_2000A_B'].data)
table['dY_2000A'].unit = table['dY_2000A_A'].unit
table['NutFlag'] = np.where(table['dX_2000A_B'].mask,
table['NutFlag_A'].data,
'B')
# Get the table index for the first row that has predictive values
# PolPMFlag_A IERS (I) or Prediction (P) flag for
# Bull. A polar motion values
# UT1Flag_A IERS (I) or Prediction (P) flag for
# Bull. A UT1-UTC values
is_predictive = (table['UT1Flag_A'] == 'P') | (table['PolPMFlag_A'] == 'P')
table.meta['predictive_index'] = np.min(np.flatnonzero(is_predictive))
table.meta['predictive_mjd'] = table['MJD'][table.meta['predictive_index']]
return table
@classmethod
def _substitute_iers_b(cls, table):
# See documentation in IERS_Auto.
return table
@classmethod
def read(cls, file=None, readme=None):
"""Read IERS-A table from a finals2000a.* file provided by USNO.
Parameters
----------
file : str
full path to ascii file holding IERS-A data.
Defaults to ``iers.IERS_A_FILE``.
readme : str
full path to ascii file holding CDS-style readme.
Defaults to package version, ``iers.IERS_A_README``.
Returns
-------
``IERS_A`` class instance
"""
if file is None:
file = IERS_A_FILE
if readme is None:
readme = IERS_A_README
# Read in as a regular Table, including possible masked columns.
# Columns will be filled and converted to Quantity in cls.__init__.
iers_a = Table.read(file, format='cds', readme=readme)
iers_a = Table(iers_a, masked=True, copy=False)
# Combine the A and B data for UT1-UTC and PM columns
table = cls._combine_a_b_columns(iers_a)
table.meta['data_path'] = file
table.meta['readme_path'] = readme
# Fill any masked values, and convert to a QTable.
return cls(table.filled())
def ut1_utc_source(self, i):
"""Set UT1-UTC source flag for entries in IERS table"""
ut1flag = self['UT1Flag'][i]
source = np.ones_like(i) * FROM_IERS_B
source[ut1flag == 'I'] = FROM_IERS_A
source[ut1flag == 'P'] = FROM_IERS_A_PREDICTION
return source
def dcip_source(self, i):
"""Set CIP correction source flag for entries in IERS table"""
nutflag = self['NutFlag'][i]
source = np.ones_like(i) * FROM_IERS_B
source[nutflag == 'I'] = FROM_IERS_A
source[nutflag == 'P'] = FROM_IERS_A_PREDICTION
return source
def pm_source(self, i):
"""Set polar motion source flag for entries in IERS table"""
pmflag = self['PolPMFlag'][i]
source = np.ones_like(i) * FROM_IERS_B
source[pmflag == 'I'] = FROM_IERS_A
source[pmflag == 'P'] = FROM_IERS_A_PREDICTION
return source
class IERS_B(IERS):
"""IERS Table class targeted to IERS B, provided by IERS itself.
These are final values; see http://www.iers.org/
Notes
-----
If the package IERS B file (```iers.IERS_B_FILE``) is out of date, a new
version can be downloaded from ``iers.IERS_B_URL``.
"""
iers_table = None
@classmethod
def read(cls, file=None, readme=None, data_start=14):
"""Read IERS-B table from a eopc04_iau2000.* file provided by IERS.
Parameters
----------
file : str
full path to ascii file holding IERS-B data.
Defaults to package version, ``iers.IERS_B_FILE``.
readme : str
full path to ascii file holding CDS-style readme.
Defaults to package version, ``iers.IERS_B_README``.
data_start : int
starting row. Default is 14, appropriate for standard IERS files.
Returns
-------
``IERS_B`` class instance
"""
if file is None:
file = IERS_B_FILE
if readme is None:
readme = IERS_B_README
# Read in as a regular Table, including possible masked columns.
# Columns will be filled and converted to Quantity in cls.__init__.
iers_b = Table.read(file, format='cds', readme=readme,
data_start=data_start)
return cls(iers_b.filled())
def ut1_utc_source(self, i):
"""Set UT1-UTC source flag for entries in IERS table"""
return np.ones_like(i) * FROM_IERS_B
def dcip_source(self, i):
"""Set CIP correction source flag for entries in IERS table"""
return np.ones_like(i) * FROM_IERS_B
def pm_source(self, i):
"""Set PM source flag for entries in IERS table"""
return np.ones_like(i) * FROM_IERS_B
class IERS_Auto(IERS_A):
"""
Provide most-recent IERS data and automatically handle downloading
of updated values as necessary.
"""
iers_table = None
@classmethod
def open(cls):
"""If the configuration setting ``astropy.utils.iers.conf.auto_download``
is set to True (default), then open a recent version of the IERS-A
table with predictions for UT1-UTC and polar motion out to
approximately one year from now. If the available version of this file
is older than ``astropy.utils.iers.conf.auto_max_age`` days old
(or non-existent) then it will be downloaded over the network and cached.
If the configuration setting ``astropy.utils.iers.conf.auto_download``
is set to False then ``astropy.utils.iers.IERS()`` is returned. This
is normally the IERS-B table that is supplied with astropy.
On the first call in a session, the table will be memoized (in the
``iers_table`` class attribute), and further calls to ``open`` will
return this stored table.
Returns
-------
`~astropy.table.QTable` instance with IERS (Earth rotation) data columns
"""
if not conf.auto_download:
cls.iers_table = IERS.open()
return cls.iers_table
all_urls = (conf.iers_auto_url, conf.iers_auto_url_mirror)
if cls.iers_table is not None:
# If the URL has changed, we need to redownload the file, so we
# should ignore the internally cached version.
if cls.iers_table.meta.get('data_url') in all_urls:
return cls.iers_table
dl_success = False
err_list = []
for url in all_urls:
try:
filename = download_file(url, cache=True)
except Exception as err:
err_list.append(str(err))
else:
dl_success = True
break
if not dl_success:
# Issue a warning here, perhaps user is offline. An exception
# will be raised downstream when actually trying to interpolate
# predictive values.
warn(AstropyWarning('failed to download {}, using local IERS-B: {}'
.format(' and '.join(all_urls),
';'.join(err_list)))) # noqa
cls.iers_table = IERS.open()
return cls.iers_table
cls.iers_table = cls.read(file=filename)
cls.iers_table.meta['data_url'] = str(url)
return cls.iers_table
def _check_interpolate_indices(self, indices_orig, indices_clipped, max_input_mjd):
"""Check that the indices from interpolation match those after clipping to the
valid table range. The IERS_Auto class is exempted as long as it has
sufficiently recent available data so the clipped interpolation is
always within the confidence bounds of current Earth rotation
knowledge.
"""
predictive_mjd = self.meta['predictive_mjd']
# See explanation in _refresh_table_as_needed for these conditions
auto_max_age = (conf.auto_max_age if conf.auto_max_age is not None
else np.finfo(float).max)
if (max_input_mjd > predictive_mjd and
self.time_now.mjd - predictive_mjd > auto_max_age):
raise ValueError(INTERPOLATE_ERROR.format(auto_max_age))
def _refresh_table_as_needed(self, mjd):
"""Potentially update the IERS table in place depending on the requested
time values in ``mjd`` and the time span of the table.
For IERS_Auto the behavior is that the table is refreshed from the IERS
server if both the following apply:
- Any of the requested IERS values are predictive. The IERS-A table
contains predictive data out for a year after the available
definitive values.
- The first predictive values are at least ``conf.auto_max_age days`` old.
In other words the IERS-A table was created by IERS long enough
ago that it can be considered stale for predictions.
"""
max_input_mjd = np.max(mjd)
now_mjd = self.time_now.mjd
# IERS-A table contains predictive data out for a year after
# the available definitive values.
fpi = self.meta['predictive_index']
predictive_mjd = self.meta['predictive_mjd']
# Update table in place if necessary
auto_max_age = (conf.auto_max_age if conf.auto_max_age is not None
else np.finfo(float).max)
# If auto_max_age is smaller than IERS update time then repeated downloads may
# occur without getting updated values (giving a IERSStaleWarning).
if auto_max_age < 10:
raise ValueError('IERS auto_max_age configuration value must be larger than 10 days')
if (max_input_mjd > predictive_mjd and
now_mjd - predictive_mjd > auto_max_age):
all_urls = (conf.iers_auto_url, conf.iers_auto_url_mirror)
dl_success = False
err_list = []
# Get the latest version
for url in all_urls:
try:
clear_download_cache(url)
filename = download_file(url, cache=True)
except Exception as err:
err_list.append(str(err))
else:
dl_success = True
break
if not dl_success:
# Issue a warning here, perhaps user is offline. An exception
# will be raised downstream when actually trying to interpolate
# predictive values.
warn(AstropyWarning('failed to download {}: {}.\nA coordinate or time-related '
'calculation might be compromised or fail because the dates are '
'not covered by the available IERS file. See the '
'"IERS data access" section of the astropy documentation '
'for additional information on working offline.'
.format(' and '.join(all_urls), ';'.join(err_list))))
return
new_table = self.__class__.read(file=filename)
new_table.meta['data_url'] = str(url)
# New table has new values?
if new_table['MJD'][-1] > self['MJD'][-1]:
# Replace *replace* current values from the first predictive index through
# the end of the current table. This replacement is much faster than just
# deleting all rows and then using add_row for the whole duration.
new_fpi = np.searchsorted(new_table['MJD'].value, predictive_mjd, side='right')
n_replace = len(self) - fpi
self[fpi:] = new_table[new_fpi:new_fpi + n_replace]
# Sanity check for continuity
if new_table['MJD'][new_fpi + n_replace] - self['MJD'][-1] != 1.0 * u.d:
raise ValueError('unexpected gap in MJD when refreshing IERS table')
# Now add new rows in place
for row in new_table[new_fpi + n_replace:]:
self.add_row(row)
self.meta.update(new_table.meta)
else:
warn(IERSStaleWarning(
'IERS_Auto predictive values are older than {} days but downloading '
'the latest table did not find newer values'.format(conf.auto_max_age)))
@classmethod
def _substitute_iers_b(cls, table):
"""Substitute IERS B values with those from a real IERS B table.
IERS-A has IERS-B values included, but for reasons unknown these
do not match the latest IERS-B values (see comments in #4436).
Here, we use the bundled astropy IERS-B table to overwrite the values
in the downloaded IERS-A table.
"""
iers_b = IERS_B.open()
# Substitute IERS-B values for existing B values in IERS-A table
mjd_b = table['MJD'][~table['UT1_UTC_B'].mask]
i0 = np.searchsorted(iers_b['MJD'].value, mjd_b[0], side='left')
i1 = np.searchsorted(iers_b['MJD'].value, mjd_b[-1], side='right')
iers_b = iers_b[i0:i1]
n_iers_b = len(iers_b)
# If there is overlap then replace IERS-A values from available IERS-B
if n_iers_b > 0:
# Sanity check that we are overwriting the correct values
if not np.allclose(table['MJD'][:n_iers_b], iers_b['MJD'].value):
raise ValueError('unexpected mismatch when copying '
'IERS-B values into IERS-A table.')
# Finally do the overwrite
table['UT1_UTC_B'][:n_iers_b] = iers_b['UT1_UTC'].value
table['PM_X_B'][:n_iers_b] = iers_b['PM_x'].value
table['PM_Y_B'][:n_iers_b] = iers_b['PM_y'].value
return table
# by default for IERS class, read IERS-B table
IERS.read = IERS_B.read
| bsipocz/astropy | astropy/utils/iers/iers.py | Python | bsd-3-clause | 31,536 |
/*
* Copyright (c) 2022 Snowplow Analytics Ltd
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*/
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import ts from 'rollup-plugin-ts';
import { banner } from '../../banner';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
import { terser } from 'rollup-plugin-terser';
import cleanup from 'rollup-plugin-cleanup';
import pkg from './package.json';
import { builtinModules } from 'module';
const umdPlugins = [nodeResolve({ browser: true }), commonjs(), ts()];
const umdName = 'snowplowYouTubeTracking';
export default [
// CommonJS (for Node) and ES module (for bundlers) build.
{
input: './src/index.ts',
plugins: [...umdPlugins, banner(true)],
treeshake: { moduleSideEffects: ['sha1'] },
output: [{ file: pkg.main, format: 'umd', sourcemap: true, name: umdName }],
},
{
input: './src/index.ts',
plugins: [...umdPlugins, compiler(), terser(), cleanup({ comments: 'none' }), banner(true)],
treeshake: { moduleSideEffects: ['sha1'] },
output: [{ file: pkg.main.replace('.js', '.min.js'), format: 'umd', sourcemap: true, name: umdName }],
},
{
input: './src/index.ts',
external: [...builtinModules, ...Object.keys(pkg.dependencies), ...Object.keys(pkg.devDependencies)],
plugins: [ts(), banner(true)],
output: [{ file: pkg.module, format: 'es', sourcemap: true }],
},
];
| snowplow/snowplow-javascript-tracker | plugins/browser-plugin-youtube-tracking/rollup.config.js | JavaScript | bsd-3-clause | 2,950 |
<?php
namespace E4W\Sms\Service;
use E4W\Sms\Adapter\Sms\SmsAdapterInterface;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerAwareTrait;
class SmsService implements EventManagerAwareInterface
{
use EventManagerAwareTrait;
/** @var SmsAdapterInterface */
protected $adapter;
/**
* Send message
*
* @param $to
* @param $text
* @param string $from
* @return mixed
*/
public function send($to, $text, $from = null)
{
$this->getEventManager()->trigger('send', $this, [
'to' => $to,
'text' => $text,
'from' => $from,
]);
return $this->adapter->send($to, $text, $from);
}
public function receive(array $data)
{
if (!method_exists($this->adapter, 'receive')) {
throw new \Exception('The adapter does not support two-ways sms');
}
$this->getEventManager()->trigger('receive', $this, [
'data' => $data,
]);
return $this->adapter->receive($data);
}
/**
* Set adapter
*
* @param SmsAdapterInterface $adapter
*/
public function setAdapter(SmsAdapterInterface $adapter)
{
$this->adapter = $adapter;
}
/**
* @return SmsAdapterInterface
*/
public function getAdapter()
{
return $this->adapter;
}
}
| Eye4web/E4WSms | src/E4W/Sms/Service/SmsService.php | PHP | bsd-3-clause | 1,405 |
from helper import CompatTestCase
from validator.compat import FX22_DEFINITION
class TestFX22Compat(CompatTestCase):
"""Test that compatibility tests for Gecko 22 are properly executed."""
VERSION = FX22_DEFINITION
def test_nsigh2(self):
self.run_regex_for_compat("nsIGlobalHistory2", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_nsilms(self):
self.run_regex_for_compat("nsILivemarkService", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_mpat(self):
self.run_regex_for_compat("markPageAsTyped", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_favicon(self):
self.run_regex_for_compat("setFaviconUrlForPage", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_nsitv(self):
self.run_regex_for_compat("getRowProperties", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_nsipb(self):
self.run_regex_for_compat("nsIPrivateBrowsingService", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_fullZoom(self):
self.run_regex_for_compat("fullZoom", is_js=True)
self.assert_silent()
self.assert_compat_error()
def test_userdata(self):
self.run_regex_for_compat("getUserData", is_js=True)
self.assert_silent()
self.assert_compat_warning()
def test_tooltip(self):
self.run_regex_for_compat("FillInHTMLTooltip", is_js=True)
self.assert_silent()
self.assert_compat_warning()
| mattbasta/amo-validator | tests/compat/test_gecko22.py | Python | bsd-3-clause | 1,747 |
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "nationality".
*
* @property integer $nationality_id
* @property string $nationality
*/
class Nationality extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'nationality';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nationality'], 'required'],
[['nationality'], 'string', 'max' => 200],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'nationality_id' => 'Nationality ID',
'nationality' => 'Nationality',
];
}
}
| robert-mill/cover | backend/models/Nationality.php | PHP | bsd-3-clause | 754 |
from pylons import tmpl_context as c
from pylons import app_globals as g
from pylons.i18n import _
from r2.config import feature
from r2.controllers import add_controller
from r2.controllers.reddit_base import RedditController
from r2.lib.errors import errors
from r2.lib.require import require, RequirementException
from r2.lib.validator import (
json_validate,
validate,
validatedForm,
VBoolean,
VExistingUname,
VGold,
VJSON,
VModhash,
VUser,
)
from reddit_gold.models import SnoovatarsByAccount
from reddit_gold.pages import (
GoldInfoPage,
Snoovatar,
SnoovatarProfilePage,
)
from reddit_gold.validators import VSnooColor
@add_controller
class GoldController(RedditController):
def GET_about(self):
return GoldInfoPage(
_("gold"),
show_sidebar=False,
page_classes=["gold-page-ga-tracking"]
).render()
def GET_partners(self):
self.redirect("/gold/about", code=301)
@validate(
vuser=VExistingUname("username"),
)
def GET_snoovatar(self, vuser):
if not vuser or vuser._deleted or not vuser.gold:
self.abort404()
snoovatar = SnoovatarsByAccount.load(vuser, "snoo")
user_is_owner = c.user_is_loggedin and c.user == vuser
if not user_is_owner:
if not snoovatar or not snoovatar["public"]:
self.abort404()
return SnoovatarProfilePage(
user=vuser,
content=Snoovatar(
editable=user_is_owner,
snoovatar=snoovatar,
username=vuser.name,
),
).render()
@add_controller
class GoldApiController(RedditController):
@validatedForm(
VUser(),
VGold(),
VModhash(),
public=VBoolean("public"),
snoo_color=VSnooColor("snoo_color"),
unvalidated_components=VJSON("components"),
)
def POST_snoovatar(self, form, jquery, public, snoo_color, unvalidated_components):
if form.has_errors("components",
errors.NO_TEXT,
errors.TOO_LONG,
errors.BAD_STRING,
):
return
if form.has_errors("snoo_color", errors.BAD_CSS_COLOR):
return
try:
tailors = g.plugins["gold"].tailors_data
validated = {}
for tailor in tailors:
tailor_name = tailor["name"]
component = unvalidated_components.get(tailor_name)
# if the tailor requires a selection, ensure there is one
if not tailor["allow_clear"]:
require(component)
# ensure this dressing exists
dressing = component.get("dressingName")
if dressing:
for d in tailor["dressings"]:
if dressing == d["name"]:
break
else:
raise RequirementException
validated[tailor_name] = component
except RequirementException:
c.errors.add(errors.INVALID_SNOOVATAR, field="components")
form.has_errors("components", errors.INVALID_SNOOVATAR)
return
SnoovatarsByAccount.save(
user=c.user,
name="snoo",
public=public,
snoo_color=snoo_color,
components=validated,
)
| madbook/reddit-plugin-gold | reddit_gold/controllers.py | Python | bsd-3-clause | 3,510 |
from django.http import HttpResponse
from error_capture_middleware import ErrorCaptureHandler
class PlainExceptionsMiddleware(ErrorCaptureHandler):
def handle(self, request, exception, tb):
return HttpResponse("\n".join(tb),
content_type="text/plain", status=500) | enderlabs/django-error-capture-middleware | src/error_capture_middleware/handlers/plain.py | Python | bsd-3-clause | 306 |
// Copyright (c) 2006, Sven Groot, see license.txt for details
#include "stdafx.h"
using namespace Gdiplus;
const float g_baseDpi = 96.0f;
float CDPIHelper::m_fScaleX = CDPIHelper::GetLogPixelsX() / g_baseDpi;
float CDPIHelper::m_fScaleY = CDPIHelper::GetLogPixelsY() / g_baseDpi;
float
CDPIHelper::ScaleX(float value)
{
return value * m_fScaleX;
}
float
CDPIHelper::ScaleY(float value)
{
return value * m_fScaleY;
}
float
CDPIHelper::GetLogPixelsX()
{
CDC dc(GetDC(NULL));
int value = dc.GetDeviceCaps(LOGPIXELSX);
return static_cast<float>(value);
}
float
CDPIHelper::GetLogPixelsY()
{
CDC dc(GetDC(NULL));
int value = dc.GetDeviceCaps(LOGPIXELSY);
return static_cast<float>(value);
}
bool
CDPIHelper::NeedScale()
{
return (!(m_fScaleX==1 && m_fScaleY==1));
}
bool
CDPIHelper::ScaleBitmap(CBitmap& bitmap)
{
if (!NeedScale()) return true;
CDC sourceDC(CreateCompatibleDC(NULL));
if (sourceDC.IsNull()) return false;
sourceDC.SelectBitmap(bitmap);
BITMAPINFO info;
ZeroMemory(&info, sizeof(info));
info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
if (GetDIBits(sourceDC, bitmap, 0, 0, NULL, &info, 0))
{
int scaledWidth = static_cast<int>(ScaleX(static_cast<float>(info.bmiHeader.biWidth)));
int scaledHeight = static_cast<int>(ScaleY(static_cast<float>(info.bmiHeader.biHeight)));
CBitmap result;
result.CreateCompatibleBitmap(sourceDC, scaledWidth, scaledHeight);
if (result.IsNull()) return false;
CDC destDC(CreateCompatibleDC(NULL));
if (destDC.IsNull()) return false;
destDC.SelectBitmap(result);
destDC.SetStretchBltMode(HALFTONE);
if (destDC.StretchBlt(0, 0, scaledWidth, scaledHeight, sourceDC, 0, 0, info.bmiHeader.biWidth, info.bmiHeader.biHeight, SRCCOPY))
{
// rescale done
bitmap = result.Detach();
}
}
return true;
} | darwin/upgradr | ieaddon/Upgradr/DPIHelper.cpp | C++ | bsd-3-clause | 1,874 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Gdata
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: MediaMimeStream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Gdata_MimeFile
*/
#require_once 'Zend/Gdata/MimeFile.php';
/**
* @see Zend_Gdata_MimeBodyString
*/
#require_once 'Zend/Gdata/MimeBodyString.php';
/**
* A streaming Media MIME class that allows for buffered read operations.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Gdata
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_MediaMimeStream
{
/**
* A valid MIME boundary.
*
* @var string
*/
protected $_boundaryString = null;
/**
* A handle to the file that is part of the message.
*
* @var resource
*/
protected $_fileHandle = null;
/**
* The current part being read from.
* @var integer
*/
protected $_currentPart = 0;
/**
* The size of the MIME message.
* @var integer
*/
protected $_totalSize = 0;
/**
* An array of all the parts to be sent. Array members are either a
* MimeFile or a MimeBodyString object.
* @var array
*/
protected $_parts = null;
/**
* Create a new MimeMediaStream object.
*
* @param string $xmlString The string corresponding to the XML section
* of the message, typically an atom entry or feed.
* @param string $filePath The path to the file that constitutes the binary
* part of the message.
* @param string $fileContentType The valid internet media type of the file.
* @throws Zend_Gdata_App_IOException If the file cannot be read or does
* not exist. Also if mbstring.func_overload has been set > 1.
*/
public function __construct($xmlString = null, $filePath = null,
$fileContentType = null)
{
if (!file_exists($filePath) || !is_readable($filePath)) {
#require_once 'Zend/Gdata/App/IOException.php';
throw new Zend_Gdata_App_IOException('File to be uploaded at ' .
$filePath . ' does not exist or is not readable.');
}
$this->_fileHandle = fopen($filePath, 'rb', TRUE);
$this->_boundaryString = '=_' . md5(microtime(1) . rand(1,20));
$entry = $this->wrapEntry($xmlString, $fileContentType);
$closingBoundary = new Zend_Gdata_MimeBodyString("\r\n--{$this->_boundaryString}--\r\n");
$file = new Zend_Gdata_MimeFile($this->_fileHandle);
$this->_parts = array($entry, $file, $closingBoundary);
$fileSize = filesize($filePath);
$this->_totalSize = $entry->getSize() + $fileSize
+ $closingBoundary->getSize();
}
/**
* Sandwiches the entry body into a MIME message
*
* @return void
*/
private function wrapEntry($entry, $fileMimeType)
{
$wrappedEntry = "--{$this->_boundaryString}\r\n";
$wrappedEntry .= "Content-Type: application/atom+xml\r\n\r\n";
$wrappedEntry .= $entry;
$wrappedEntry .= "\r\n--{$this->_boundaryString}\r\n";
$wrappedEntry .= "Content-Type: $fileMimeType\r\n\r\n";
return new Zend_Gdata_MimeBodyString($wrappedEntry);
}
/**
* Read a specific chunk of the the MIME multipart message.
*
* @param integer $bufferSize The size of the chunk that is to be read,
* must be lower than MAX_BUFFER_SIZE.
* @return string A corresponding piece of the message. This could be
* binary or regular text.
*/
public function read($bytesRequested)
{
if($this->_currentPart >= count($this->_parts)) {
return FALSE;
}
$activePart = $this->_parts[$this->_currentPart];
$buffer = $activePart->read($bytesRequested);
while(strlen($buffer) < $bytesRequested) {
$this->_currentPart += 1;
$nextBuffer = $this->read($bytesRequested - strlen($buffer));
if($nextBuffer === FALSE) {
break;
}
$buffer .= $nextBuffer;
}
return $buffer;
}
/**
* Return the total size of the mime message.
*
* @return integer Total size of the message to be sent.
*/
public function getTotalSize()
{
return $this->_totalSize;
}
/**
* Close the internal file that we are streaming to the socket.
*
* @return void
*/
public function closeFileHandle()
{
if ($this->_fileHandle !== null) {
fclose($this->_fileHandle);
}
}
/**
* Return a Content-type header that includes the current boundary string.
*
* @return string A valid HTTP Content-Type header.
*/
public function getContentType()
{
return 'multipart/related;boundary="' .
$this->_boundaryString . '"' . "\r\n";
}
}
| lmaxim/zend_gdata | library/Zend/Gdata/MediaMimeStream.php | PHP | bsd-3-clause | 5,671 |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import random
import unittest
from infra_libs.event_mon import router
from infra_libs.event_mon.log_request_lite_pb2 import LogRequestLite
DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
class RouterTests(unittest.TestCase):
def test_smoke(self):
# Use dry_run to avoid code that deals with http (including auth).
r = router._Router({}, endpoint=None)
self.assertTrue(r.close())
def test_smoke_with_credentials(self):
cache = {'service_account_creds':
os.path.join(DATA_DIR, 'valid_creds.json'),
'service_accounts_creds_root': 'whatever.the/other/is/absolute'}
r = router._Router(cache, endpoint='https://any.where')
self.assertTrue(r.close())
def test_push_smoke(self):
r = router._Router({}, endpoint=None)
req = LogRequestLite.LogEventLite()
req.event_time_ms = router.time_ms()
req.event_code = 1
req.event_flow_id = 2
r.push_event(req)
self.assertTrue(r.close())
def test_push_error_handling(self):
r = router._Router({}, endpoint=None)
r.push_event(None)
self.assertTrue(r.close())
class BackoffTest(unittest.TestCase):
def test_backoff_time_first_value(self):
t = router.backoff_time(attempt=0, retry_backoff=2.)
random.seed(0)
self.assertTrue(1.5 <= t <= 2.5)
def test_backoff_time_max_value(self):
t = router.backoff_time(attempt=10, retry_backoff=2., max_delay=5)
self.assertTrue(abs(t - 5.) < 0.0001)
| nicko96/Chrome-Infra | infra_libs/event_mon/test/router_test.py | Python | bsd-3-clause | 1,648 |
# -*- coding: utf-8 -*-
from django.db import models, migrations
import django.utils.timezone
import django.contrib.auth.models
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', serialize=False, auto_created=True)),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(null=True, verbose_name='last login', blank=True)),
('is_superuser', models.BooleanField(help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status', default=False)),
('username', models.CharField(max_length=30, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.', 'invalid')], verbose_name='username', error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True)),
('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)),
('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)),
('email', models.EmailField(max_length=254, verbose_name='email address', blank=True)),
('is_staff', models.BooleanField(help_text='Designates whether the user can log into this admin site.', verbose_name='staff status', default=False)),
('is_active', models.BooleanField(help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active', default=True)),
('date_joined', models.DateTimeField(verbose_name='date joined', default=django.utils.timezone.now)),
('groups', models.ManyToManyField(related_name='user_set', blank=True, verbose_name='groups', to='auth.Group', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='user')),
('user_permissions', models.ManyToManyField(related_name='user_set', blank=True, verbose_name='user permissions', to='auth.Permission', help_text='Specific permissions for this user.', related_query_name='user')),
('name', models.CharField(max_length=255, verbose_name='Name of User', blank=True)),
],
options={
'verbose_name': 'user',
'abstract': False,
'verbose_name_plural': 'users',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
| GeoMatDigital/django-geomat | geomat/users/migrations/0001_initial.py | Python | bsd-3-clause | 3,014 |
<?php
namespace App\Exceptions;
/**
* Interface for HTTP error exceptions.
*/
interface HttpExceptionInterface
{
/**
* Returns the status code.
*
* @return int An HTTP response status code
*/
public function getStatusCode();
/**
* Returns response headers.
*
* @return array Response headers
*/
public function getHeaders();
} | arcostasi/slimantic-skeleton | app/src/Exceptions/HttpExceptionInterface.php | PHP | bsd-3-clause | 391 |
/*
* Copyright 2015, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. 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 io.grpc;
import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ServiceLoader;
/**
* Provider of managed channels for transport agnostic consumption.
*
* <p>Implementations <em>should not</em> throw. If they do, it may interrupt class loading. If
* exceptions may reasonably occur for implementation-specific reasons, implementations should
* generally handle the exception gracefully and return {@code false} from {@link #isAvailable()}.
*/
@Internal
public abstract class ManagedChannelProvider {
private static final ManagedChannelProvider provider
= load(getCorrectClassLoader());
@VisibleForTesting
static ManagedChannelProvider load(ClassLoader classLoader) {
ServiceLoader<ManagedChannelProvider> providers
= ServiceLoader.load(ManagedChannelProvider.class, classLoader);
List<ManagedChannelProvider> list = new ArrayList<ManagedChannelProvider>();
for (ManagedChannelProvider current : providers) {
if (!current.isAvailable()) {
continue;
}
list.add(current);
}
if (list.isEmpty()) {
return null;
} else {
return Collections.max(list, new Comparator<ManagedChannelProvider>() {
@Override
public int compare(ManagedChannelProvider f1, ManagedChannelProvider f2) {
return f1.priority() - f2.priority();
}
});
}
}
/**
* Returns the ClassLoader-wide default channel.
*
* @throws ProviderNotFoundException if no provider is available
*/
public static ManagedChannelProvider provider() {
if (provider == null) {
throw new ProviderNotFoundException("No functional channel service provider found. "
+ "Try adding a dependency on the grpc-okhttp or grpc-netty artifact");
}
return provider;
}
private static ClassLoader getCorrectClassLoader() {
if (isAndroid()) {
// When android:sharedUserId or android:process is used, Android will setup a dummy
// ClassLoader for the thread context (http://stackoverflow.com/questions/13407006),
// instead of letting users to manually set context class loader, we choose the
// correct class loader here.
return ManagedChannelProvider.class.getClassLoader();
}
return Thread.currentThread().getContextClassLoader();
}
protected static boolean isAndroid() {
try {
Class.forName("android.app.Application", /*initialize=*/ false, null);
return true;
} catch (Exception e) {
// If Application isn't loaded, it might as well not be Android.
return false;
}
}
/**
* Whether this provider is available for use, taking the current environment into consideration.
* If {@code false}, no other methods are safe to be called.
*/
protected abstract boolean isAvailable();
/**
* A priority, from 0 to 10 that this provider should be used, taking the current environment into
* consideration. 5 should be considered the default, and then tweaked based on environment
* detection. A priority of 0 does not imply that the provider wouldn't work; just that it should
* be last in line.
*/
protected abstract int priority();
/**
* Creates a new builder with the given host and port.
*/
protected abstract ManagedChannelBuilder<?> builderForAddress(String name, int port);
/**
* Creates a new builder with the given target URI.
*/
protected abstract ManagedChannelBuilder<?> builderForTarget(String target);
public static final class ProviderNotFoundException extends RuntimeException {
public ProviderNotFoundException(String msg) {
super(msg);
}
}
}
| LuminateWireless/grpc-java | core/src/main/java/io/grpc/ManagedChannelProvider.java | Java | bsd-3-clause | 5,316 |
<?php
namespace backend\modules\personal;
/**
* personal module definition class
*/
class Module extends \yii\base\Module
{
/**
* @inheritdoc
*/
public $controllerNamespace = 'backend\modules\personal\controllers';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
// custom initialization code goes here
}
}
| spider049/yii2-meeting | backend/modules/personal/Module.php | PHP | bsd-3-clause | 387 |
package com.rezgame.backend.logic;
/*
* Copyright (c) <2013>, Amanj Sherwany and Nosheen Zaza
* All rights reserved.
* */
public class GameHistoryManager {
}
| amanjpro/9riskane | src/com/rezgame/backend/logic/GameHistoryManager.java | Java | bsd-3-clause | 162 |
/*
* Copyright (c) 2014, Victor Nazarov <asviraspossible@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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 com.github.sviperll.staticmustache;
import com.github.sviperll.staticmustache.context.ContextException;
import com.github.sviperll.staticmustache.context.TemplateCompilerContext;
import com.github.sviperll.staticmustache.token.MustacheTokenizer;
import java.io.IOException;
import javax.annotation.Nonnull;
/**
*
* @author Victor Nazarov <asviraspossible@gmail.com>
*/
class TemplateCompiler implements TokenProcessor<PositionedToken<MustacheToken>> {
public static Factory compilerFactory() {
return new Factory() {
@Override
public TemplateCompiler createTemplateCompiler(NamedReader reader, SwitchablePrintWriter writer,
TemplateCompilerContext context) {
return TemplateCompiler.createCompiler(reader, writer, context);
}
};
}
public static Factory headerCompilerFactory() {
return new Factory() {
@Override
public TemplateCompiler createTemplateCompiler(NamedReader reader, SwitchablePrintWriter writer,
TemplateCompilerContext context) {
return TemplateCompiler.createHeaderCompiler(reader, writer, context);
}
};
}
public static Factory footerCompilerFactory() {
return new Factory() {
@Override
public TemplateCompiler createTemplateCompiler(NamedReader reader, SwitchablePrintWriter writer,
TemplateCompilerContext context) {
return TemplateCompiler.createFooterCompiler(reader, writer, context);
}
};
}
public static TemplateCompiler createCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
return new SimpleTemplateCompiler(reader, writer, context);
}
public static TemplateCompiler createHeaderCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
return new HeaderTemplateCompiler(reader, writer, context);
}
public static TemplateCompiler createFooterCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
return new FooterTemplateCompiler(reader, writer, context);
}
private final NamedReader reader;
private final boolean expectsYield;
final SwitchablePrintWriter writer;
private TemplateCompilerContext context;
boolean foundYield = false;
private TemplateCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context, boolean expectsYield) {
this.reader = reader;
this.writer = writer;
this.context = context;
this.expectsYield = expectsYield;
}
void run() throws ProcessingException, IOException {
TokenProcessor<Character> processor = MustacheTokenizer.createInstance(reader.name(), this);
int readResult;
while ((readResult = reader.read()) >= 0) {
processor.processToken((char)readResult);
}
processor.processToken(TokenProcessor.EOF);
writer.println();
}
@Override
public void processToken(@Nonnull PositionedToken<MustacheToken> positionedToken) throws ProcessingException {
positionedToken.innerToken().accept(new CompilingTokenProcessor(positionedToken.position()));
}
private class CompilingTokenProcessor implements MustacheToken.Visitor<Void, ProcessingException> {
private final Position position;
public CompilingTokenProcessor(Position position) {
this.position = position;
}
@Override
public Void beginSection(String name) throws ProcessingException {
try {
context = context.getChild(name);
print(context.beginSectionRenderingCode());
} catch (ContextException ex) {
throw new ProcessingException(position, ex);
}
return null;
}
@Override
public Void beginInvertedSection(String name) throws ProcessingException {
try {
context = context.getInvertedChild(name);
print(context.beginSectionRenderingCode());
} catch (ContextException ex) {
throw new ProcessingException(position, ex);
}
return null;
}
@Override
public Void endSection(String name) throws ProcessingException {
if (!context.isEnclosed())
throw new ProcessingException(position, "Closing " + name + " block when no block is currently open");
else if (!context.currentEnclosedContextName().equals(name))
throw new ProcessingException(position, "Closing " + name + " block instead of " + context.currentEnclosedContextName());
else {
print(context.endSectionRenderingCode());
context = context.parentContext();
return null;
}
}
@Override
public Void variable(String name) throws ProcessingException {
try {
if (!expectsYield || !name.equals("yield")) {
TemplateCompilerContext variable = context.getChild(name);
writer.print(variable.renderingCode());
} else {
if (foundYield)
throw new ProcessingException(position, "Yield can be used only once");
else if (context.isEnclosed())
throw new ProcessingException(position, "Unclosed " + context.currentEnclosedContextName() + " block before yield");
else {
throw new ProcessingException(position, "Yield should be unescaped variable");
}
}
return null;
} catch (ContextException ex) {
throw new ProcessingException(position, ex);
}
}
@Override
public Void unescapedVariable(String name) throws ProcessingException {
try {
if (!expectsYield || !name.equals("yield")) {
TemplateCompilerContext variable = context.getChild(name);
writer.print(variable.unescapedRenderingCode());
} else {
if (foundYield)
throw new ProcessingException(position, "Yield can be used only once");
if (context.isEnclosed())
throw new ProcessingException(position, "Unclosed " + context.currentEnclosedContextName() + " block before yield");
else {
foundYield = true;
if (writer.suppressesOutput())
writer.enableOutput();
else
writer.disableOutput();
}
}
return null;
} catch (ContextException ex) {
throw new ProcessingException(position, ex);
}
}
@Override
public Void specialCharacter(char c) throws ProcessingException {
if (c == '\n') {
printCodeToWrite("\\n");
println();
} else if (c == '"') {
printCodeToWrite("\\\"");
} else
printCodeToWrite("" + c);
return null;
}
@Override
public Void text(String s) throws ProcessingException {
printCodeToWrite(s);
return null;
}
@Override
public Void endOfFile() throws ProcessingException {
if (!context.isEnclosed())
return null;
else {
throw new ProcessingException(position, "Unclosed " + context.currentEnclosedContextName() + " block at end of file");
}
}
private void printCodeToWrite(String s) {
print(context.unescapedWriterExpression() + ".append(\"" + s + "\"); ");
}
private void print(String s) {
writer.print(s);
}
private void println() {
writer.println();
}
}
static class SimpleTemplateCompiler extends TemplateCompiler {
private SimpleTemplateCompiler(NamedReader inputReader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
super(inputReader, writer, context, false);
}
@Override
void run() throws ProcessingException, IOException {
boolean suppressesOutput = writer.suppressesOutput();
writer.enableOutput();
super.run();
if (suppressesOutput)
writer.disableOutput();
else
writer.enableOutput();
}
}
static class HeaderTemplateCompiler extends TemplateCompiler {
private HeaderTemplateCompiler(NamedReader inputReader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
super(inputReader, writer, context, true);
}
@Override
void run() throws ProcessingException, IOException {
boolean suppressesOutput = writer.suppressesOutput();
foundYield = false;
writer.enableOutput();
super.run();
if (suppressesOutput)
writer.disableOutput();
else
writer.enableOutput();
}
}
static class FooterTemplateCompiler extends TemplateCompiler {
private FooterTemplateCompiler(NamedReader inputReader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
super(inputReader, writer, context, true);
}
@Override
void run() throws ProcessingException, IOException {
boolean suppressesOutput = writer.suppressesOutput();
foundYield = false;
writer.disableOutput();
super.run();
if (suppressesOutput)
writer.disableOutput();
else
writer.enableOutput();
}
}
interface Factory {
TemplateCompiler createTemplateCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context);
}
}
| sviperll/static-mustache | static-mustache/src/main/java/com/github/sviperll/staticmustache/TemplateCompiler.java | Java | bsd-3-clause | 12,095 |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#define SMW_INFO MITK_INFO("widget.stdmulti")
#include "QmitkStdMultiWidget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGridLayout>
#include <qsplitter.h>
#include <QList>
#include <QMouseEvent>
#include <QTimer>
#include <mitkProperties.h>
#include <mitkPlaneGeometryDataMapper2D.h>
#include <mitkPointSet.h>
#include <mitkLine.h>
#include <mitkInteractionConst.h>
#include <mitkDataStorage.h>
#include <mitkOverlayManager.h>
#include <mitkNodePredicateBase.h>
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkStatusBar.h>
#include <mitkImage.h>
#include <mitkVtkLayerController.h>
#include <mitkCameraController.h>
#include <vtkTextProperty.h>
#include <vtkCornerAnnotation.h>
#include <vtkMitkRectangleProp.h>
#include "mitkPixelTypeMultiplex.h"
#include "mitkImagePixelReadAccessor.h"
#include <iomanip>
QmitkStdMultiWidget::QmitkStdMultiWidget(QWidget* parent, Qt::WindowFlags f, mitk::RenderingManager* renderingManager, mitk::BaseRenderer::RenderingMode::Type renderingMode, const QString& name)
: QWidget(parent, f),
mitkWidget1(NULL),
mitkWidget2(NULL),
mitkWidget3(NULL),
mitkWidget4(NULL),
levelWindowWidget(NULL),
QmitkStdMultiWidgetLayout(NULL),
m_Layout(LAYOUT_DEFAULT),
m_PlaneMode(PLANE_MODE_SLICING),
m_RenderingManager(renderingManager),
m_GradientBackgroundFlag(true),
m_TimeNavigationController(NULL),
m_MainSplit(NULL),
m_LayoutSplit(NULL),
m_SubSplit1(NULL),
m_SubSplit2(NULL),
mitkWidget1Container(NULL),
mitkWidget2Container(NULL),
mitkWidget3Container(NULL),
mitkWidget4Container(NULL),
m_PendingCrosshairPositionEvent(false),
m_CrosshairNavigationEnabled(false)
{
/******************************************************
* Use the global RenderingManager if none was specified
* ****************************************************/
if (m_RenderingManager == NULL)
{
m_RenderingManager = mitk::RenderingManager::GetInstance();
}
m_TimeNavigationController = m_RenderingManager->GetTimeNavigationController();
/*******************************/
//Create Widget manually
/*******************************/
//create Layouts
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
QmitkStdMultiWidgetLayout->setContentsMargins(0,0,0,0);
//Set Layout to widget
this->setLayout(QmitkStdMultiWidgetLayout);
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//creae Widget Container
mitkWidget1Container = new QWidget(m_SubSplit1);
mitkWidget2Container = new QWidget(m_SubSplit1);
mitkWidget3Container = new QWidget(m_SubSplit2);
mitkWidget4Container = new QWidget(m_SubSplit2);
mitkWidget1Container->setContentsMargins(0,0,0,0);
mitkWidget2Container->setContentsMargins(0,0,0,0);
mitkWidget3Container->setContentsMargins(0,0,0,0);
mitkWidget4Container->setContentsMargins(0,0,0,0);
//create Widget Layout
QHBoxLayout *mitkWidgetLayout1 = new QHBoxLayout(mitkWidget1Container);
QHBoxLayout *mitkWidgetLayout2 = new QHBoxLayout(mitkWidget2Container);
QHBoxLayout *mitkWidgetLayout3 = new QHBoxLayout(mitkWidget3Container);
QHBoxLayout *mitkWidgetLayout4 = new QHBoxLayout(mitkWidget4Container);
m_CornerAnnotations[0] = vtkSmartPointer<vtkCornerAnnotation>::New();
m_CornerAnnotations[1] = vtkSmartPointer<vtkCornerAnnotation>::New();
m_CornerAnnotations[2] = vtkSmartPointer<vtkCornerAnnotation>::New();
m_CornerAnnotations[3] = vtkSmartPointer<vtkCornerAnnotation>::New();
m_RectangleProps[0] = vtkSmartPointer<vtkMitkRectangleProp>::New();
m_RectangleProps[1] = vtkSmartPointer<vtkMitkRectangleProp>::New();
m_RectangleProps[2] = vtkSmartPointer<vtkMitkRectangleProp>::New();
m_RectangleProps[3] = vtkSmartPointer<vtkMitkRectangleProp>::New();
mitkWidgetLayout1->setMargin(0);
mitkWidgetLayout2->setMargin(0);
mitkWidgetLayout3->setMargin(0);
mitkWidgetLayout4->setMargin(0);
//set Layout to Widget Container
mitkWidget1Container->setLayout(mitkWidgetLayout1);
mitkWidget2Container->setLayout(mitkWidgetLayout2);
mitkWidget3Container->setLayout(mitkWidgetLayout3);
mitkWidget4Container->setLayout(mitkWidgetLayout4);
//set SizePolicy
mitkWidget1Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
mitkWidget2Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
mitkWidget3Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
mitkWidget4Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
//insert Widget Container into the splitters
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit2->addWidget( mitkWidget3Container );
m_SubSplit2->addWidget( mitkWidget4Container );
//Create RenderWindows 1
mitkWidget1 = new QmitkRenderWindow(mitkWidget1Container, name + ".widget1", NULL, m_RenderingManager,renderingMode);
mitkWidget1->SetLayoutIndex( AXIAL );
mitkWidgetLayout1->addWidget(mitkWidget1);
//Create RenderWindows 2
mitkWidget2 = new QmitkRenderWindow(mitkWidget2Container, name + ".widget2", NULL, m_RenderingManager,renderingMode);
mitkWidget2->setEnabled( true );
mitkWidget2->SetLayoutIndex( SAGITTAL );
mitkWidgetLayout2->addWidget(mitkWidget2);
//Create RenderWindows 3
mitkWidget3 = new QmitkRenderWindow(mitkWidget3Container, name + ".widget3", NULL, m_RenderingManager,renderingMode);
mitkWidget3->SetLayoutIndex( CORONAL );
mitkWidgetLayout3->addWidget(mitkWidget3);
//Create RenderWindows 4
mitkWidget4 = new QmitkRenderWindow(mitkWidget4Container, name + ".widget4", NULL, m_RenderingManager,renderingMode);
mitkWidget4->SetLayoutIndex( THREE_D );
mitkWidgetLayout4->addWidget(mitkWidget4);
//create SignalSlot Connection
connect( mitkWidget1, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) );
connect( mitkWidget1, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) );
connect( mitkWidget1, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) );
connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget1, SLOT(OnWidgetPlaneModeChanged(int)) );
connect( mitkWidget2, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) );
connect( mitkWidget2, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) );
connect( mitkWidget2, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) );
connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget2, SLOT(OnWidgetPlaneModeChanged(int)) );
connect( mitkWidget3, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) );
connect( mitkWidget3, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) );
connect( mitkWidget3, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) );
connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget3, SLOT(OnWidgetPlaneModeChanged(int)) );
connect( mitkWidget4, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) );
connect( mitkWidget4, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) );
connect( mitkWidget4, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) );
connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget4, SLOT(OnWidgetPlaneModeChanged(int)) );
//Create Level Window Widget
levelWindowWidget = new QmitkLevelWindowWidget( m_MainSplit ); //this
levelWindowWidget->setObjectName(QString::fromUtf8("levelWindowWidget"));
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(levelWindowWidget->sizePolicy().hasHeightForWidth());
levelWindowWidget->setSizePolicy(sizePolicy);
levelWindowWidget->setMaximumWidth(50);
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//resize Image.
this->resize( QSize(364, 477).expandedTo(minimumSizeHint()) );
//Initialize the widgets.
this->InitializeWidget();
//Activate Widget Menu
this->ActivateMenuWidget( true );
}
void QmitkStdMultiWidget::InitializeWidget()
{
//Make all black and overwrite renderwindow 4
this->FillGradientBackgroundWithBlack();
//This is #191919 in hex
float tmp1[3] = { 0.098f, 0.098f, 0.098f};
//This is #7F7F7F in hex
float tmp2[3] = { 0.498f, 0.498f, 0.498f};
m_GradientBackgroundColors[3] = std::make_pair(mitk::Color(tmp1), mitk::Color(tmp2));
//Yellow is default color for widget4
m_DecorationColorWidget4[0] = 1.0f;
m_DecorationColorWidget4[1] = 1.0f;
m_DecorationColorWidget4[2] = 0.0f;
// transfer colors in WorldGeometry-Nodes of the associated Renderer
mitk::IntProperty::Pointer layer;
// of widget 1
m_PlaneNode1 = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode1->SetColor(GetDecorationColor(0));
layer = mitk::IntProperty::New(1000);
m_PlaneNode1->SetProperty("layer",layer);
// ... of widget 2
m_PlaneNode2 = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode2->SetColor(GetDecorationColor(1));
layer = mitk::IntProperty::New(1000);
m_PlaneNode2->SetProperty("layer",layer);
// ... of widget 3
m_PlaneNode3 = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode3->SetColor(GetDecorationColor(2));
layer = mitk::IntProperty::New(1000);
m_PlaneNode3->SetProperty("layer",layer);
//The parent node
m_ParentNodeForGeometryPlanes = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode();
layer = mitk::IntProperty::New(1000);
m_ParentNodeForGeometryPlanes->SetProperty("layer",layer);
mitk::OverlayManager::Pointer OverlayManager = mitk::OverlayManager::New();
mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->SetOverlayManager(OverlayManager);
mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->SetOverlayManager(OverlayManager);
mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->SetOverlayManager(OverlayManager);
mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetOverlayManager(OverlayManager);
mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetMapperID(mitk::BaseRenderer::Standard3D);
// Set plane mode (slicing/rotation behavior) to slicing (default)
m_PlaneMode = PLANE_MODE_SLICING;
// Set default view directions for SNCs
mitkWidget1->GetSliceNavigationController()->SetDefaultViewDirection(
mitk::SliceNavigationController::Axial );
mitkWidget2->GetSliceNavigationController()->SetDefaultViewDirection(
mitk::SliceNavigationController::Sagittal );
mitkWidget3->GetSliceNavigationController()->SetDefaultViewDirection(
mitk::SliceNavigationController::Frontal );
mitkWidget4->GetSliceNavigationController()->SetDefaultViewDirection(
mitk::SliceNavigationController::Original );
SetDecorationProperties("Axial", GetDecorationColor(0), 0);
SetDecorationProperties("Sagittal", GetDecorationColor(1), 1);
SetDecorationProperties("Coronal", GetDecorationColor(2), 2);
SetDecorationProperties("3D", GetDecorationColor(3), 3);
//connect to the "time navigation controller": send time via sliceNavigationControllers
m_TimeNavigationController->ConnectGeometryTimeEvent(
mitkWidget1->GetSliceNavigationController() , false);
m_TimeNavigationController->ConnectGeometryTimeEvent(
mitkWidget2->GetSliceNavigationController() , false);
m_TimeNavigationController->ConnectGeometryTimeEvent(
mitkWidget3->GetSliceNavigationController() , false);
m_TimeNavigationController->ConnectGeometryTimeEvent(
mitkWidget4->GetSliceNavigationController() , false);
mitkWidget1->GetSliceNavigationController()
->ConnectGeometrySendEvent(mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow()));
//reverse connection between sliceNavigationControllers and m_TimeNavigationController
mitkWidget1->GetSliceNavigationController()
->ConnectGeometryTimeEvent(m_TimeNavigationController, false);
mitkWidget2->GetSliceNavigationController()
->ConnectGeometryTimeEvent(m_TimeNavigationController, false);
mitkWidget3->GetSliceNavigationController()
->ConnectGeometryTimeEvent(m_TimeNavigationController, false);
//mitkWidget4->GetSliceNavigationController()
// ->ConnectGeometryTimeEvent(m_TimeNavigationController, false);
m_MouseModeSwitcher = mitk::MouseModeSwitcher::New();
// setup the department logo rendering
m_LogoRendering = mitk::LogoOverlay::New();
mitk::BaseRenderer::Pointer renderer4 = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow());
m_LogoRendering->SetOpacity(0.5);
mitk::Point2D offset;
offset.Fill(0.03);
m_LogoRendering->SetOffsetVector(offset);
m_LogoRendering->SetRelativeSize(0.15);
m_LogoRendering->SetCornerPosition(1);
m_LogoRendering->SetLogoImagePath("DefaultLogo");
renderer4->GetOverlayManager()->AddOverlay(m_LogoRendering.GetPointer(),renderer4);
}
void QmitkStdMultiWidget::FillGradientBackgroundWithBlack()
{
//We have 4 widgets and ...
for(unsigned int i = 0; i < 4; ++i)
{
float black[3] = {0.0f, 0.0f, 0.0f};
m_GradientBackgroundColors[i] = std::make_pair(mitk::Color(black), mitk::Color(black));
}
}
std::pair<mitk::Color, mitk::Color> QmitkStdMultiWidget::GetGradientColors(unsigned int widgetNumber)
{
if(widgetNumber > 3)
{
MITK_ERROR << "Decoration color for unknown widget!";
float black[3] = { 0.0f, 0.0f, 0.0f};
return std::make_pair(mitk::Color(black), mitk::Color(black));
}
return m_GradientBackgroundColors[widgetNumber];
}
mitk::Color QmitkStdMultiWidget::GetDecorationColor(unsigned int widgetNumber)
{
//The implementation looks a bit messy here, but it avoids
//synchronization of the color of the geometry nodes and an
//internal member here.
//Default colors were chosen for decent visibitliy.
//Feel free to change your preferences in the workbench.
float tmp[3] = {0.0f,0.0f,0.0f};
switch (widgetNumber) {
case 0:
{
if(m_PlaneNode1.IsNotNull())
{
if(m_PlaneNode1->GetColor(tmp))
{
return dynamic_cast<mitk::ColorProperty*>(
m_PlaneNode1->GetProperty("color"))->GetColor();
}
}
float red[3] = { 0.753f, 0.0f, 0.0f};//This is #C00000 in hex
return mitk::Color(red);
}
case 1:
{
if(m_PlaneNode2.IsNotNull())
{
if(m_PlaneNode2->GetColor(tmp))
{
return dynamic_cast<mitk::ColorProperty*>(
m_PlaneNode2->GetProperty("color"))->GetColor();
}
}
float green[3] = { 0.0f, 0.69f, 0.0f};//This is #00B000 in hex
return mitk::Color(green);
}
case 2:
{
if(m_PlaneNode3.IsNotNull())
{
if(m_PlaneNode3->GetColor(tmp))
{
return dynamic_cast<mitk::ColorProperty*>(
m_PlaneNode3->GetProperty("color"))->GetColor();
}
}
float blue[3] = { 0.0, 0.502f, 1.0f};//This is #0080FF in hex
return mitk::Color(blue);
}
case 3:
{
return m_DecorationColorWidget4;
}
default:
MITK_ERROR << "Decoration color for unknown widget!";
float black[3] = { 0.0f, 0.0f, 0.0f};
return mitk::Color(black);
}
}
std::string QmitkStdMultiWidget::GetCornerAnnotationText(unsigned int widgetNumber)
{
if(widgetNumber > 3)
{
MITK_ERROR << "Decoration color for unknown widget!";
return std::string("");
}
return std::string(m_CornerAnnotations[widgetNumber]->GetText(0));
}
QmitkStdMultiWidget::~QmitkStdMultiWidget()
{
DisablePositionTracking();
//DisableNavigationControllerEventListening();
m_TimeNavigationController->Disconnect(mitkWidget1->GetSliceNavigationController());
m_TimeNavigationController->Disconnect(mitkWidget2->GetSliceNavigationController());
m_TimeNavigationController->Disconnect(mitkWidget3->GetSliceNavigationController());
m_TimeNavigationController->Disconnect(mitkWidget4->GetSliceNavigationController());
}
void QmitkStdMultiWidget::RemovePlanesFromDataStorage()
{
if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_ParentNodeForGeometryPlanes.IsNotNull())
{
if(m_DataStorage.IsNotNull())
{
m_DataStorage->Remove(m_PlaneNode1);
m_DataStorage->Remove(m_PlaneNode2);
m_DataStorage->Remove(m_PlaneNode3);
m_DataStorage->Remove(m_ParentNodeForGeometryPlanes);
}
}
}
void QmitkStdMultiWidget::AddPlanesToDataStorage()
{
if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_ParentNodeForGeometryPlanes.IsNotNull())
{
if (m_DataStorage.IsNotNull())
{
m_DataStorage->Add(m_ParentNodeForGeometryPlanes);
m_DataStorage->Add(m_PlaneNode1, m_ParentNodeForGeometryPlanes);
m_DataStorage->Add(m_PlaneNode2, m_ParentNodeForGeometryPlanes);
m_DataStorage->Add(m_PlaneNode3, m_ParentNodeForGeometryPlanes);
}
}
}
void QmitkStdMultiWidget::changeLayoutTo2DImagesUp()
{
SMW_INFO << "changing layout to 2D images up... " << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//Set Layout to widget
this->setLayout(QmitkStdMultiWidgetLayout);
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget Container into splitter top
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit1->addWidget( mitkWidget3Container );
//set SplitterSize for splitter top
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
//insert Widget Container into splitter bottom
m_SubSplit2->addWidget( mitkWidget4Container );
//set SplitterSize for splitter m_LayoutSplit
splitterSize.clear();
splitterSize.push_back(400);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt
m_MainSplit->show();
//show Widget if hidden
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
//Change Layout Name
m_Layout = LAYOUT_2D_IMAGES_UP;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutTo2DImagesLeft()
{
SMW_INFO << "changing layout to 2D images left... " << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget into the splitters
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit1->addWidget( mitkWidget3Container );
//set splitterSize of SubSplit1
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
m_SubSplit2->addWidget( mitkWidget4Container );
//set splitterSize of Layout Split
splitterSize.clear();
splitterSize.push_back(400);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show Widget if hidden
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
//update Layout Name
m_Layout = LAYOUT_2D_IMAGES_LEFT;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::SetDecorationProperties( std::string text,
mitk::Color color, int widgetNumber)
{
if( widgetNumber > 3)
{
MITK_ERROR << "Unknown render window for annotation.";
return;
}
vtkRenderer* renderer = this->GetRenderWindow(widgetNumber)->GetRenderer()->GetVtkRenderer();
if(!renderer) return;
vtkSmartPointer<vtkCornerAnnotation> annotation = m_CornerAnnotations[widgetNumber];
annotation->SetText(0, text.c_str());
annotation->SetMaximumFontSize(12);
annotation->GetTextProperty()->SetColor( color[0],color[1],color[2] );
if(!renderer->HasViewProp(annotation))
{
renderer->AddViewProp(annotation);
}
vtkSmartPointer<vtkMitkRectangleProp> frame = m_RectangleProps[widgetNumber];
frame->SetColor(color[0],color[1],color[2]);
if(!renderer->HasViewProp(frame))
{
renderer->AddViewProp(frame);
}
}
void QmitkStdMultiWidget::SetCornerAnnotationVisibility(bool visibility)
{
for(int i = 0 ; i<4 ; ++i)
{
m_CornerAnnotations[i]->SetVisibility(visibility);
}
}
bool QmitkStdMultiWidget::IsCornerAnnotationVisible(void) const
{
return m_CornerAnnotations[0]->GetVisibility() > 0;
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow(unsigned int number)
{
switch (number) {
case 0:
return this->GetRenderWindow1();
case 1:
return this->GetRenderWindow2();
case 2:
return this->GetRenderWindow3();
case 3:
return this->GetRenderWindow4();
default:
MITK_ERROR << "Requested unknown render window";
break;
}
return NULL;
}
void QmitkStdMultiWidget::changeLayoutToDefault()
{
SMW_INFO << "changing layout to default... " << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget container into the splitters
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit2->addWidget( mitkWidget3Container );
m_SubSplit2->addWidget( mitkWidget4Container );
//set splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
m_SubSplit2->setSizes( splitterSize );
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show Widget if hidden
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_DEFAULT;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_DEFAULT );
mitkWidget2->LayoutDesignListChanged( LAYOUT_DEFAULT );
mitkWidget3->LayoutDesignListChanged( LAYOUT_DEFAULT );
mitkWidget4->LayoutDesignListChanged( LAYOUT_DEFAULT );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToBig3D()
{
SMW_INFO << "changing layout to big 3D ..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//add widget Splitter to main Splitter
m_MainSplit->addWidget( mitkWidget4Container );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
mitkWidget2->hide();
mitkWidget3->hide();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_BIG_3D;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_BIG_3D );
mitkWidget2->LayoutDesignListChanged( LAYOUT_BIG_3D );
mitkWidget3->LayoutDesignListChanged( LAYOUT_BIG_3D );
mitkWidget4->LayoutDesignListChanged( LAYOUT_BIG_3D );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToWidget1()
{
SMW_INFO << "changing layout to big Widget1 ..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//add widget Splitter to main Splitter
m_MainSplit->addWidget( mitkWidget1Container );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
mitkWidget2->hide();
mitkWidget3->hide();
mitkWidget4->hide();
m_Layout = LAYOUT_WIDGET1;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET1 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET1 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET1 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET1 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToWidget2()
{
SMW_INFO << "changing layout to big Widget2 ..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//add widget Splitter to main Splitter
m_MainSplit->addWidget( mitkWidget2Container );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
mitkWidget3->hide();
mitkWidget4->hide();
m_Layout = LAYOUT_WIDGET2;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET2 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET2 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET2 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET2 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToWidget3()
{
SMW_INFO << "changing layout to big Widget3 ..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//add widget Splitter to main Splitter
m_MainSplit->addWidget( mitkWidget3Container );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
mitkWidget2->hide();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
mitkWidget4->hide();
m_Layout = LAYOUT_WIDGET3;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET3 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET3 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET3 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET3 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToRowWidget3And4()
{
SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//add Widgets to splitter
m_LayoutSplit->addWidget( mitkWidget3Container );
m_LayoutSplit->addWidget( mitkWidget4Container );
//set Splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
mitkWidget2->hide();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_ROW_WIDGET_3_AND_4;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToColumnWidget3And4()
{
SMW_INFO << "changing layout to Widget3 and 4 in one Column..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//add Widgets to splitter
m_LayoutSplit->addWidget( mitkWidget3Container );
m_LayoutSplit->addWidget( mitkWidget4Container );
//set SplitterSize
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
mitkWidget2->hide();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_COLUMN_WIDGET_3_AND_4;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToRowWidgetSmall3andBig4()
{
SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl;
this->changeLayoutToRowWidget3And4();
m_Layout = LAYOUT_ROW_WIDGET_SMALL3_AND_BIG4;
}
void QmitkStdMultiWidget::changeLayoutToSmallUpperWidget2Big3and4()
{
SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget into the splitters
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit2->addWidget( mitkWidget3Container );
m_SubSplit2->addWidget( mitkWidget4Container );
//set Splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit2->setSizes( splitterSize );
splitterSize.clear();
splitterSize.push_back(500);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt
m_MainSplit->show();
//show Widget if hidden
mitkWidget1->hide();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutTo2x2Dand3DWidget()
{
SMW_INFO << "changing layout to 2 x 2D and 3D Widget" << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//add Widgets to splitter
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit2->addWidget( mitkWidget4Container );
//set Splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
mitkWidget3->hide();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_2X_2D_AND_3D_WIDGET;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToLeft2Dand3DRight2D()
{
SMW_INFO << "changing layout to 2D and 3D left, 2D right Widget" << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//add Widgets to splitter
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget4Container );
m_SubSplit2->addWidget( mitkWidget2Container );
//set Splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
mitkWidget3->hide();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutTo2DUpAnd3DDown()
{
SMW_INFO << "changing layout to 2D up and 3D down" << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//Set Layout to widget
this->setLayout(QmitkStdMultiWidgetLayout);
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget Container into splitter top
m_SubSplit1->addWidget( mitkWidget1Container );
//set SplitterSize for splitter top
QList<int> splitterSize;
//insert Widget Container into splitter bottom
m_SubSplit2->addWidget( mitkWidget4Container );
//set SplitterSize for splitter m_LayoutSplit
splitterSize.clear();
splitterSize.push_back(700);
splitterSize.push_back(700);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt
m_MainSplit->show();
//show/hide Widgets
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
mitkWidget2->hide();
mitkWidget3->hide();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_2D_UP_AND_3D_DOWN;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN );
//update all Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::SetDataStorage( mitk::DataStorage* ds )
{
mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->SetDataStorage(ds);
mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->SetDataStorage(ds);
mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->SetDataStorage(ds);
mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetDataStorage(ds);
m_DataStorage = ds;
}
void QmitkStdMultiWidget::Fit()
{
vtkSmartPointer<vtkRenderer> vtkrenderer;
vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetVtkRenderer();
if ( vtkrenderer!= NULL )
vtkrenderer->ResetCamera();
vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetVtkRenderer();
if ( vtkrenderer!= NULL )
vtkrenderer->ResetCamera();
vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetVtkRenderer();
if ( vtkrenderer!= NULL )
vtkrenderer->ResetCamera();
vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetVtkRenderer();
if ( vtkrenderer!= NULL )
vtkrenderer->ResetCamera();
mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetCameraController()->Fit();
mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetCameraController()->Fit();
mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetCameraController()->Fit();
mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetCameraController()->Fit();
int w = vtkObject::GetGlobalWarningDisplay();
vtkObject::GlobalWarningDisplayOff();
vtkObject::SetGlobalWarningDisplay(w);
}
void QmitkStdMultiWidget::InitPositionTracking()
{
// TODO POSITIONTRACKER
}
void QmitkStdMultiWidget::AddDisplayPlaneSubTree()
{
// add the displayed planes of the multiwidget to a node to which the subtree
// @a planesSubTree points ...
mitk::PlaneGeometryDataMapper2D::Pointer mapper;
// ... of widget 1
mitk::BaseRenderer* renderer1 = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow());
m_PlaneNode1 = renderer1->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode1->SetProperty("visible", mitk::BoolProperty::New(true));
m_PlaneNode1->SetProperty("name", mitk::StringProperty::New(std::string(renderer1->GetName()) + ".plane"));
m_PlaneNode1->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
m_PlaneNode1->SetProperty("helper object", mitk::BoolProperty::New(true));
mapper = mitk::PlaneGeometryDataMapper2D::New();
m_PlaneNode1->SetMapper(mitk::BaseRenderer::Standard2D, mapper);
// ... of widget 2
mitk::BaseRenderer* renderer2 = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow());
m_PlaneNode2 = renderer2->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode2->SetProperty("visible", mitk::BoolProperty::New(true));
m_PlaneNode2->SetProperty("name", mitk::StringProperty::New(std::string(renderer2->GetName()) + ".plane"));
m_PlaneNode2->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
m_PlaneNode2->SetProperty("helper object", mitk::BoolProperty::New(true));
mapper = mitk::PlaneGeometryDataMapper2D::New();
m_PlaneNode2->SetMapper(mitk::BaseRenderer::Standard2D, mapper);
// ... of widget 3
mitk::BaseRenderer* renderer3 = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow());
m_PlaneNode3 = renderer3->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode3->SetProperty("visible", mitk::BoolProperty::New(true));
m_PlaneNode3->SetProperty("name", mitk::StringProperty::New(std::string(renderer3->GetName()) + ".plane"));
m_PlaneNode3->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
m_PlaneNode3->SetProperty("helper object", mitk::BoolProperty::New(true));
mapper = mitk::PlaneGeometryDataMapper2D::New();
m_PlaneNode3->SetMapper(mitk::BaseRenderer::Standard2D, mapper);
m_ParentNodeForGeometryPlanes = mitk::DataNode::New();
m_ParentNodeForGeometryPlanes->SetProperty("name", mitk::StringProperty::New("Widgets"));
m_ParentNodeForGeometryPlanes->SetProperty("helper object", mitk::BoolProperty::New(true));
}
mitk::SliceNavigationController* QmitkStdMultiWidget::GetTimeNavigationController()
{
return m_TimeNavigationController;
}
void QmitkStdMultiWidget::EnableStandardLevelWindow()
{
levelWindowWidget->disconnect(this);
levelWindowWidget->SetDataStorage(mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetDataStorage());
levelWindowWidget->show();
}
void QmitkStdMultiWidget::DisableStandardLevelWindow()
{
levelWindowWidget->disconnect(this);
levelWindowWidget->hide();
}
// CAUTION: Legacy code for enabling Qt-signal-controlled view initialization.
// Use RenderingManager::InitializeViews() instead.
bool QmitkStdMultiWidget::InitializeStandardViews( const mitk::Geometry3D * geometry )
{
return m_RenderingManager->InitializeViews( geometry );
}
void QmitkStdMultiWidget::RequestUpdate()
{
m_RenderingManager->RequestUpdate(mitkWidget1->GetRenderWindow());
m_RenderingManager->RequestUpdate(mitkWidget2->GetRenderWindow());
m_RenderingManager->RequestUpdate(mitkWidget3->GetRenderWindow());
m_RenderingManager->RequestUpdate(mitkWidget4->GetRenderWindow());
}
void QmitkStdMultiWidget::ForceImmediateUpdate()
{
m_RenderingManager->ForceImmediateUpdate(mitkWidget1->GetRenderWindow());
m_RenderingManager->ForceImmediateUpdate(mitkWidget2->GetRenderWindow());
m_RenderingManager->ForceImmediateUpdate(mitkWidget3->GetRenderWindow());
m_RenderingManager->ForceImmediateUpdate(mitkWidget4->GetRenderWindow());
}
void QmitkStdMultiWidget::wheelEvent( QWheelEvent * e )
{
emit WheelMoved( e );
}
void QmitkStdMultiWidget::mousePressEvent(QMouseEvent * e)
{
}
void QmitkStdMultiWidget::moveEvent( QMoveEvent* e )
{
QWidget::moveEvent( e );
// it is necessary to readjust the position of the overlays as the StdMultiWidget has moved
// unfortunately it's not done by QmitkRenderWindow::moveEvent -> must be done here
emit Moved();
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow1() const
{
return mitkWidget1;
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow2() const
{
return mitkWidget2;
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow3() const
{
return mitkWidget3;
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow4() const
{
return mitkWidget4;
}
const mitk::Point3D QmitkStdMultiWidget::GetCrossPosition() const
{
const mitk::PlaneGeometry *plane1 =
mitkWidget1->GetSliceNavigationController()->GetCurrentPlaneGeometry();
const mitk::PlaneGeometry *plane2 =
mitkWidget2->GetSliceNavigationController()->GetCurrentPlaneGeometry();
const mitk::PlaneGeometry *plane3 =
mitkWidget3->GetSliceNavigationController()->GetCurrentPlaneGeometry();
mitk::Line3D line;
if ( (plane1 != NULL) && (plane2 != NULL)
&& (plane1->IntersectionLine( plane2, line )) )
{
mitk::Point3D point;
if ( (plane3 != NULL)
&& (plane3->IntersectionPoint( line, point )) )
{
return point;
}
}
// TODO BUG POSITIONTRACKER;
mitk::Point3D p;
return p;
//return m_LastLeftClickPositionSupplier->GetCurrentPoint();
}
void QmitkStdMultiWidget::EnablePositionTracking()
{
}
void QmitkStdMultiWidget::DisablePositionTracking()
{
}
void QmitkStdMultiWidget::EnsureDisplayContainsPoint(
mitk::BaseRenderer* renderer, const mitk::Point3D& p)
{
mitk::Point2D pointOnDisplay;
renderer->WorldToDisplay(p,pointOnDisplay);
if(pointOnDisplay[0] < renderer->GetVtkRenderer()->GetOrigin()[0]
|| pointOnDisplay[1] < renderer->GetVtkRenderer()->GetOrigin()[1]
|| pointOnDisplay[0] > renderer->GetVtkRenderer()->GetOrigin()[0]+renderer->GetViewportSize()[0]
|| pointOnDisplay[1] > renderer->GetVtkRenderer()->GetOrigin()[1]+renderer->GetViewportSize()[1])
{
mitk::Point2D pointOnPlane;
renderer->GetCurrentWorldPlaneGeometry()->Map(p,pointOnPlane);
renderer->GetCameraController()->MoveCameraToPoint(pointOnPlane);
}
}
void QmitkStdMultiWidget::MoveCrossToPosition(const mitk::Point3D& newPosition)
{
mitkWidget1->GetSliceNavigationController()->SelectSliceByPoint(newPosition);
mitkWidget2->GetSliceNavigationController()->SelectSliceByPoint(newPosition);
mitkWidget3->GetSliceNavigationController()->SelectSliceByPoint(newPosition);
m_RenderingManager->RequestUpdateAll();
}
void QmitkStdMultiWidget::HandleCrosshairPositionEvent()
{
if(!m_PendingCrosshairPositionEvent)
{
m_PendingCrosshairPositionEvent=true;
QTimer::singleShot(0,this,SLOT( HandleCrosshairPositionEventDelayed() ) );
}
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetTopLayerNode(mitk::DataStorage::SetOfObjects::ConstPointer nodes)
{
mitk::Point3D crosshairPos = this->GetCrossPosition();
mitk::DataNode::Pointer node;
int maxlayer = -32768;
if(nodes.IsNotNull())
{
mitk::BaseRenderer* baseRenderer = this->mitkWidget1->GetSliceNavigationController()->GetRenderer();
// find node with largest layer, that is the node shown on top in the render window
for (unsigned int x = 0; x < nodes->size(); x++)
{
if ( (nodes->at(x)->GetData()->GetGeometry() != NULL) &&
nodes->at(x)->GetData()->GetGeometry()->IsInside(crosshairPos) )
{
int layer = 0;
if(!(nodes->at(x)->GetIntProperty("layer", layer))) continue;
if(layer > maxlayer)
{
if( static_cast<mitk::DataNode::Pointer>(nodes->at(x))->IsVisible( baseRenderer ) )
{
node = nodes->at(x);
maxlayer = layer;
}
}
}
}
}
return node;
}
void QmitkStdMultiWidget::HandleCrosshairPositionEventDelayed()
{
m_PendingCrosshairPositionEvent = false;
// find image with highest layer
mitk::TNodePredicateDataType<mitk::Image>::Pointer isImageData = mitk::TNodePredicateDataType<mitk::Image>::New();
mitk::DataStorage::SetOfObjects::ConstPointer nodes = this->m_DataStorage->GetSubset(isImageData).GetPointer();
mitk::DataNode::Pointer node;
mitk::DataNode::Pointer topSourceNode;
mitk::Image::Pointer image;
bool isBinary = false;
node = this->GetTopLayerNode(nodes);
int component = 0;
if(node.IsNotNull())
{
node->GetBoolProperty("binary",isBinary);
if(isBinary)
{
mitk::DataStorage::SetOfObjects::ConstPointer sourcenodes = m_DataStorage->GetSources(node, NULL, true);
if(!sourcenodes->empty())
{
topSourceNode = this->GetTopLayerNode(sourcenodes);
}
if(topSourceNode.IsNotNull())
{
image = dynamic_cast<mitk::Image*>(topSourceNode->GetData());
topSourceNode->GetIntProperty("Image.Displayed Component", component);
}
else
{
image = dynamic_cast<mitk::Image*>(node->GetData());
node->GetIntProperty("Image.Displayed Component", component);
}
}
else
{
image = dynamic_cast<mitk::Image*>(node->GetData());
node->GetIntProperty("Image.Displayed Component", component);
}
}
mitk::Point3D crosshairPos = this->GetCrossPosition();
std::string statusText;
std::stringstream stream;
itk::Index<3> p;
mitk::BaseRenderer* baseRenderer = this->mitkWidget1->GetSliceNavigationController()->GetRenderer();
unsigned int timestep = baseRenderer->GetTimeStep();
if(image.IsNotNull() && (image->GetTimeSteps() > timestep ))
{
image->GetGeometry()->WorldToIndex(crosshairPos, p);
stream.precision(2);
stream<<"Position: <" << std::fixed <<crosshairPos[0] << ", " << std::fixed << crosshairPos[1] << ", " << std::fixed << crosshairPos[2] << "> mm";
stream<<"; Index: <"<<p[0] << ", " << p[1] << ", " << p[2] << "> ";
mitk::ScalarType pixelValue;
mitkPixelTypeMultiplex5(
mitk::FastSinglePixelAccess,
image->GetChannelDescriptor().GetPixelType(),
image,
image->GetVolumeData(baseRenderer->GetTimeStep()),
p,
pixelValue,
component);
if (fabs(pixelValue)>1000000 || fabs(pixelValue) < 0.01)
{
stream<<"; Time: " << baseRenderer->GetTime() << " ms; Pixelvalue: "<< std::scientific<< pixelValue <<" ";
}
else
{
stream<<"; Time: " << baseRenderer->GetTime() << " ms; Pixelvalue: "<< pixelValue <<" ";
}
}
else
{
stream << "No image information at this position!";
}
statusText = stream.str();
mitk::StatusBar::GetInstance()->DisplayGreyValueText(statusText.c_str());
}
int QmitkStdMultiWidget::GetLayout() const
{
return m_Layout;
}
bool QmitkStdMultiWidget::GetGradientBackgroundFlag() const
{
return m_GradientBackgroundFlag;
}
void QmitkStdMultiWidget::EnableGradientBackground()
{
// gradient background is by default only in widget 4, otherwise
// interferences between 2D rendering and VTK rendering may occur.
for(unsigned int i = 0; i < 4; ++i)
{
GetRenderWindow(i)->GetRenderer()->GetVtkRenderer()->GradientBackgroundOn();
}
m_GradientBackgroundFlag = true;
}
void QmitkStdMultiWidget::DisableGradientBackground()
{
for(unsigned int i = 0; i < 4; ++i)
{
GetRenderWindow(i)->GetRenderer()->GetVtkRenderer()->GradientBackgroundOff();
}
m_GradientBackgroundFlag = false;
}
void QmitkStdMultiWidget::EnableDepartmentLogo()
{
m_LogoRendering->SetVisibility(true);
RequestUpdate();
}
void QmitkStdMultiWidget::DisableDepartmentLogo()
{
m_LogoRendering->SetVisibility(false);
RequestUpdate();
}
bool QmitkStdMultiWidget::IsDepartmentLogoEnabled() const
{
return m_LogoRendering->IsVisible(mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow()));
}
void QmitkStdMultiWidget::SetWidgetPlaneVisibility(const char* widgetName, bool visible, mitk::BaseRenderer *renderer)
{
if (m_DataStorage.IsNotNull())
{
mitk::DataNode* n = m_DataStorage->GetNamedNode(widgetName);
if (n != NULL)
n->SetVisibility(visible, renderer);
}
}
void QmitkStdMultiWidget::SetWidgetPlanesVisibility(bool visible, mitk::BaseRenderer *renderer)
{
if (m_PlaneNode1.IsNotNull())
{
m_PlaneNode1->SetVisibility(visible, renderer);
}
if (m_PlaneNode2.IsNotNull())
{
m_PlaneNode2->SetVisibility(visible, renderer);
}
if (m_PlaneNode3.IsNotNull())
{
m_PlaneNode3->SetVisibility(visible, renderer);
}
m_RenderingManager->RequestUpdateAll();
}
void QmitkStdMultiWidget::SetWidgetPlanesLocked(bool locked)
{
//do your job and lock or unlock slices.
GetRenderWindow1()->GetSliceNavigationController()->SetSliceLocked(locked);
GetRenderWindow2()->GetSliceNavigationController()->SetSliceLocked(locked);
GetRenderWindow3()->GetSliceNavigationController()->SetSliceLocked(locked);
}
void QmitkStdMultiWidget::SetWidgetPlanesRotationLocked(bool locked)
{
//do your job and lock or unlock slices.
GetRenderWindow1()->GetSliceNavigationController()->SetSliceRotationLocked(locked);
GetRenderWindow2()->GetSliceNavigationController()->SetSliceRotationLocked(locked);
GetRenderWindow3()->GetSliceNavigationController()->SetSliceRotationLocked(locked);
}
void QmitkStdMultiWidget::SetWidgetPlanesRotationLinked( bool link )
{
emit WidgetPlanesRotationLinked( link );
}
void QmitkStdMultiWidget::SetWidgetPlaneMode( int userMode )
{
MITK_DEBUG << "Changing crosshair mode to " << userMode;
emit WidgetNotifyNewCrossHairMode( userMode );
// Convert user interface mode to actual mode
{
switch(userMode)
{
case 0:
m_MouseModeSwitcher->SetInteractionScheme(mitk::MouseModeSwitcher::InteractionScheme::MITK);
break;
case 1:
m_MouseModeSwitcher->SetInteractionScheme( mitk::MouseModeSwitcher::InteractionScheme::ROTATION);
break;
case 2:
m_MouseModeSwitcher->SetInteractionScheme( mitk::MouseModeSwitcher::InteractionScheme::ROTATIONLINKED);
break;
case 3:
m_MouseModeSwitcher->SetInteractionScheme( mitk::MouseModeSwitcher::InteractionScheme::SWIVEL);
break;
}
}
}
void QmitkStdMultiWidget::SetGradientBackgroundColorForRenderWindow( const mitk::Color & upper, const mitk::Color & lower, unsigned int widgetNumber )
{
if(widgetNumber > 3)
{
MITK_ERROR << "Gradientbackground for unknown widget!";
return;
}
m_GradientBackgroundColors[widgetNumber].first = upper;
m_GradientBackgroundColors[widgetNumber].second = lower;
vtkRenderer* renderer = GetRenderWindow(widgetNumber)->GetRenderer()->GetVtkRenderer();
renderer->SetBackground2(upper[0], upper[1], upper[2]);
renderer->SetBackground(lower[0], lower[1], lower[2]);
m_GradientBackgroundFlag = true;
}
void QmitkStdMultiWidget::SetGradientBackgroundColors( const mitk::Color & upper, const mitk::Color & lower )
{
for(unsigned int i = 0; i < 4; ++i)
{
vtkRenderer* renderer = GetRenderWindow(i)->GetRenderer()->GetVtkRenderer();
renderer->SetBackground2(upper[0], upper[1], upper[2]);
renderer->SetBackground(lower[0], lower[1], lower[2]);
}
m_GradientBackgroundFlag = true;
}
void QmitkStdMultiWidget::SetDepartmentLogoPath( const char * path )
{
m_LogoRendering->SetLogoImagePath(path);
mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow());
m_LogoRendering->Update(renderer);
RequestUpdate();
}
void QmitkStdMultiWidget::SetWidgetPlaneModeToSlicing( bool activate )
{
if ( activate )
{
this->SetWidgetPlaneMode( PLANE_MODE_SLICING );
}
}
void QmitkStdMultiWidget::SetWidgetPlaneModeToRotation( bool activate )
{
if ( activate )
{
this->SetWidgetPlaneMode( PLANE_MODE_ROTATION );
}
}
void QmitkStdMultiWidget::SetWidgetPlaneModeToSwivel( bool activate )
{
if ( activate )
{
this->SetWidgetPlaneMode( PLANE_MODE_SWIVEL );
}
}
void QmitkStdMultiWidget::OnLayoutDesignChanged( int layoutDesignIndex )
{
switch( layoutDesignIndex )
{
case LAYOUT_DEFAULT:
{
this->changeLayoutToDefault();
break;
}
case LAYOUT_2D_IMAGES_UP:
{
this->changeLayoutTo2DImagesUp();
break;
}
case LAYOUT_2D_IMAGES_LEFT:
{
this->changeLayoutTo2DImagesLeft();
break;
}
case LAYOUT_BIG_3D:
{
this->changeLayoutToBig3D();
break;
}
case LAYOUT_WIDGET1:
{
this->changeLayoutToWidget1();
break;
}
case LAYOUT_WIDGET2:
{
this->changeLayoutToWidget2();
break;
}
case LAYOUT_WIDGET3:
{
this->changeLayoutToWidget3();
break;
}
case LAYOUT_2X_2D_AND_3D_WIDGET:
{
this->changeLayoutTo2x2Dand3DWidget();
break;
}
case LAYOUT_ROW_WIDGET_3_AND_4:
{
this->changeLayoutToRowWidget3And4();
break;
}
case LAYOUT_COLUMN_WIDGET_3_AND_4:
{
this->changeLayoutToColumnWidget3And4();
break;
}
case LAYOUT_ROW_WIDGET_SMALL3_AND_BIG4:
{
this->changeLayoutToRowWidgetSmall3andBig4();
break;
}
case LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4:
{
this->changeLayoutToSmallUpperWidget2Big3and4();
break;
}
case LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET:
{
this->changeLayoutToLeft2Dand3DRight2D();
break;
}
};
}
void QmitkStdMultiWidget::UpdateAllWidgets()
{
mitkWidget1->resize( mitkWidget1Container->frameSize().width()-1, mitkWidget1Container->frameSize().height() );
mitkWidget1->resize( mitkWidget1Container->frameSize().width(), mitkWidget1Container->frameSize().height() );
mitkWidget2->resize( mitkWidget2Container->frameSize().width()-1, mitkWidget2Container->frameSize().height() );
mitkWidget2->resize( mitkWidget2Container->frameSize().width(), mitkWidget2Container->frameSize().height() );
mitkWidget3->resize( mitkWidget3Container->frameSize().width()-1, mitkWidget3Container->frameSize().height() );
mitkWidget3->resize( mitkWidget3Container->frameSize().width(), mitkWidget3Container->frameSize().height() );
mitkWidget4->resize( mitkWidget4Container->frameSize().width()-1, mitkWidget4Container->frameSize().height() );
mitkWidget4->resize( mitkWidget4Container->frameSize().width(), mitkWidget4Container->frameSize().height() );
}
void QmitkStdMultiWidget::HideAllWidgetToolbars()
{
mitkWidget1->HideRenderWindowMenu();
mitkWidget2->HideRenderWindowMenu();
mitkWidget3->HideRenderWindowMenu();
mitkWidget4->HideRenderWindowMenu();
}
void QmitkStdMultiWidget::ActivateMenuWidget( bool state )
{
mitkWidget1->ActivateMenuWidget( state, this );
mitkWidget2->ActivateMenuWidget( state, this );
mitkWidget3->ActivateMenuWidget( state, this );
mitkWidget4->ActivateMenuWidget( state, this );
}
bool QmitkStdMultiWidget::IsMenuWidgetEnabled() const
{
return mitkWidget1->GetActivateMenuWidgetFlag();
}
void QmitkStdMultiWidget::SetDecorationColor(unsigned int widgetNumber, mitk::Color color)
{
switch (widgetNumber) {
case 0:
if(m_PlaneNode1.IsNotNull())
{
m_PlaneNode1->SetColor(color);
}
break;
case 1:
if(m_PlaneNode2.IsNotNull())
{
m_PlaneNode2->SetColor(color);
}
break;
case 2:
if(m_PlaneNode3.IsNotNull())
{
m_PlaneNode3->SetColor(color);
}
break;
case 3:
m_DecorationColorWidget4 = color;
break;
default:
MITK_ERROR << "Decoration color for unknown widget!";
break;
}
}
void QmitkStdMultiWidget::ResetCrosshair()
{
if (m_DataStorage.IsNotNull())
{
m_RenderingManager->InitializeViewsByBoundingObjects(m_DataStorage);
//m_RenderingManager->InitializeViews( m_DataStorage->ComputeVisibleBoundingGeometry3D() );
// reset interactor to normal slicing
this->SetWidgetPlaneMode(PLANE_MODE_SLICING);
}
}
void QmitkStdMultiWidget::EnableColoredRectangles()
{
m_RectangleProps[0]->SetVisibility(1);
m_RectangleProps[1]->SetVisibility(1);
m_RectangleProps[2]->SetVisibility(1);
m_RectangleProps[3]->SetVisibility(1);
}
void QmitkStdMultiWidget::DisableColoredRectangles()
{
m_RectangleProps[0]->SetVisibility(0);
m_RectangleProps[1]->SetVisibility(0);
m_RectangleProps[2]->SetVisibility(0);
m_RectangleProps[3]->SetVisibility(0);
}
bool QmitkStdMultiWidget::IsColoredRectanglesEnabled() const
{
return m_RectangleProps[0]->GetVisibility()>0;
}
mitk::MouseModeSwitcher* QmitkStdMultiWidget::GetMouseModeSwitcher()
{
return m_MouseModeSwitcher;
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane1()
{
return this->m_PlaneNode1;
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane2()
{
return this->m_PlaneNode2;
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane3()
{
return this->m_PlaneNode3;
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane(int id)
{
switch(id)
{
case 1: return this->m_PlaneNode1;
break;
case 2: return this->m_PlaneNode2;
break;
case 3: return this->m_PlaneNode3;
break;
default: return NULL;
}
}
| NifTK/MITK | Modules/QtWidgets/src/QmitkStdMultiWidget.cpp | C++ | bsd-3-clause | 64,616 |
<?php
/**
* Created by PhpStorm.
* User: yunsong
* Date: 16-10-10
* Time: 下午3:12
*/
namespace yunsong\order\controllers\pay;
use izyue\alipay\AlipayConfig;
use izyue\alipay\AlipayNotify;
use izyue\alipay\AlipaySubmit;
use Yii;
use yii\web\Controller;
class AlipayController extends Controller
{
public function beforeAction($action)
{
if ('notify' == $action->id) {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
public function actionIndex($orderId)
{
/**************************请求参数**************************/
//服务器异步通知页面路径
$notify_url = Yii::$app->urlManager->createAbsoluteUrl(['/order/pay/alipay/notify']);
//需http://格式的完整路径,不允许加?id=123这类自定义参数
//付款账号
$email = 'awebc@foxmail.com';
// $email = $_POST['WIDemail'];
//必填
//付款账户名
$account_name = "北京纽斯洛网络科技有限公司";
//必填,个人支付宝账号是真实姓名公司支付宝账号是公司名称
//付款当天日期
$pay_date = date("Y-m-d");
//必填,格式:年[4位]月[2位]日[2位],如:20100801
//批次号
$batch_no = date("YmdHis");
//必填,格式:当天日期[8位]+序列号[3至16位],如:201008010000001
//付款总金额
$batch_fee = 0.02;
//必填,即参数detail_data的值中所有金额的总和
//付款笔数
$batch_num = 2;
//必填,即参数detail_data的值中,“|”字符出现的数量加1,最大支持1000笔(即“|”字符出现的数量999个)
//付款详细数据
$detail_data = "流水号1^收款方帐号1^真实姓名^0.01^测试付款1,这是备注|流水号2^收款方帐号2^真实姓名^0.01^测试付款2,这是备注";
//必填,格式:流水号1^收款方帐号1^真实姓名^付款金额1^备注说明1|流水号2^收款方帐号2^真实姓名^付款金额2^备注说明2....
/************************************************************/
$alipayConfig = (new AlipayConfig())->getAlipayConfig();
//构造要请求的参数数组,无需改动
$parameter = array(
"service" => "batch_trans_notify",
"partner" => trim($alipayConfig['partner']),
"notify_url" => $notify_url,
"email" => trim($alipayConfig['seller_email']),
"account_name" => $account_name,
"pay_date" => $pay_date,
"batch_no" => $batch_no,
"batch_fee" => $batch_fee,
"batch_num" => $batch_num,
"detail_data" => $detail_data,
"_input_charset" => trim(strtolower($alipayConfig['input_charset']))
);
//建立请求
$alipaySubmit = new AlipaySubmit($alipayConfig);
$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
return $html_text;
}
public function actionNotify()
{
$alipayConfig = (new AlipayConfig())->getAlipayConfig();
// Yii::getLogger()->log("alipay Notify Start", Logger::LEVEL_ERROR);
//
// Yii::getLogger()->log("↓↓↓↓↓↓↓↓↓↓alipayConfig↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓", Logger::LEVEL_ERROR);
// Yii::getLogger()->log(print_r($alipayConfig, true), Logger::LEVEL_ERROR);
$notify = new AlipayNotify($alipayConfig);
if ($notify->verifyNotify()) {
Yii::trace('verify Notify success');
//通知时间 2009-08-12 11:08:32
$notify_time = Yii::$app->request->post('notify_time');
//通知类型 batch_trans_notify
$notifyType = Yii::$app->request->post('notify_type');
//通知校验ID 70fec0c2730b27528665af4517c27b95
$notifyId = Yii::$app->request->post('notify_id');
//签名方式 MD5
$signType = Yii::$app->request->post('sign_type');
//签名 e7d51bf34a1317714d93fab13bbeab73
$sign = Yii::$app->request->post('sign');
//批次号
$batchNo = Yii::$app->request->post('batch_no');
//付款账号ID
$payUserId = Yii::$app->request->post('pay_user_id');
//付款账号姓名
$payUserName = Yii::$app->request->post('pay_user_name');
//付款账号
$payAccountNo = Yii::$app->request->post('pay_account_no');
//批量付款数据中转账成功的详细信息
$successDetails = Yii::$app->request->post('success_details');
//批量付款数据中转账失败的详细信息
$failDetails = Yii::$app->request->post('fail_details');
//请在这里加上商户的业务逻辑程序代
//判断是否在商户网站中已经做过了这次通知返回的处理
//如果没有做过处理,那么执行商户的业务程序
//如果有做过处理,那么不执行商户的业务程序
return "success";
} else {
Yii::trace('verify Notify failed');
return "fail";
}
}
} | awebc/web_yi | yunsong/order/controllers/pay/AlipayController.php | PHP | bsd-3-clause | 5,332 |
class CreatePostCategoryJoinTable < ActiveRecord::Migration
def change
create_table :categories_posts, :id => false do |t|
t.integer :post_id
t.integer :category_id
end
end
end
| erdbehrmund/blogyr | db/migrate/20130117003258_create_post_category_join_table.rb | Ruby | bsd-3-clause | 201 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/mojo/common/media_type_converters.h"
#include <stddef.h>
#include <stdint.h>
#include "base/numerics/safe_conversions.h"
#include "media/base/audio_buffer.h"
#include "media/base/audio_decoder_config.h"
#include "media/base/buffering_state.h"
#include "media/base/cdm_config.h"
#include "media/base/cdm_key_information.h"
#include "media/base/decoder_buffer.h"
#include "media/base/decrypt_config.h"
#include "media/base/decryptor.h"
#include "media/base/demuxer_stream.h"
#include "media/base/media_keys.h"
#include "media/base/video_decoder_config.h"
#include "media/base/video_frame.h"
#include "media/mojo/common/mojo_shared_buffer_video_frame.h"
#include "media/mojo/interfaces/demuxer_stream.mojom.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/public/cpp/system/buffer.h"
namespace mojo {
#define ASSERT_ENUM_EQ(media_enum, media_prefix, mojo_prefix, value) \
static_assert(media::media_prefix##value == \
static_cast<media::media_enum>( \
media::interfaces::media_enum::mojo_prefix##value), \
"Mismatched enum: " #media_prefix #value " != " #media_enum \
"::" #mojo_prefix #value)
#define ASSERT_ENUM_EQ_RAW(media_enum, media_enum_value, mojo_enum_value) \
static_assert( \
media::media_enum_value == \
static_cast<media::media_enum>(media::interfaces::mojo_enum_value), \
"Mismatched enum: " #media_enum_value " != " #mojo_enum_value)
// BufferingState.
ASSERT_ENUM_EQ(BufferingState, BUFFERING_, , HAVE_NOTHING);
ASSERT_ENUM_EQ(BufferingState, BUFFERING_, , HAVE_ENOUGH);
// AudioCodec.
ASSERT_ENUM_EQ_RAW(AudioCodec, kUnknownAudioCodec, AudioCodec::UNKNOWN);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , AAC);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , MP3);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , Vorbis);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , FLAC);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , AMR_NB);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM_MULAW);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , GSM_MS);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM_S16BE);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM_S24BE);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , Opus);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , EAC3);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM_ALAW);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , ALAC);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , AC3);
ASSERT_ENUM_EQ_RAW(AudioCodec, kAudioCodecMax, AudioCodec::MAX);
// ChannelLayout.
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _NONE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _UNSUPPORTED);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _MONO);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _STEREO);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _2_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _SURROUND);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _4_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _2_2);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _QUAD);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _5_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _5_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _5_0_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _5_1_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_1_WIDE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _STEREO_DOWNMIX);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _2POINT1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _3_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _4_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_0_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _HEXAGONAL);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_1_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_1_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_0_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_1_WIDE_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _OCTAGONAL);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _DISCRETE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _STEREO_AND_KEYBOARD_MIC);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _4_1_QUAD_SIDE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _MAX);
// SampleFormat.
ASSERT_ENUM_EQ_RAW(SampleFormat, kUnknownSampleFormat, SampleFormat::UNKNOWN);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , U8);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , S16);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , S32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , F32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , PlanarS16);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , PlanarF32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , Max);
// DemuxerStream Type. Note: Mojo DemuxerStream's don't have the TEXT type.
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
DemuxerStream::UNKNOWN,
DemuxerStream::Type::UNKNOWN);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
DemuxerStream::AUDIO,
DemuxerStream::Type::AUDIO);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
DemuxerStream::VIDEO,
DemuxerStream::Type::VIDEO);
static_assert(media::DemuxerStream::NUM_TYPES ==
static_cast<media::DemuxerStream::Type>(
static_cast<int>(
media::interfaces::DemuxerStream::Type::LAST_TYPE) +
2),
"Mismatched enum: media::DemuxerStream::NUM_TYPES != "
"media::interfaces::DemuxerStream::Type::LAST_TYPE + 2");
// DemuxerStream Status.
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
DemuxerStream::kOk,
DemuxerStream::Status::OK);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
DemuxerStream::kAborted,
DemuxerStream::Status::ABORTED);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
DemuxerStream::kConfigChanged,
DemuxerStream::Status::CONFIG_CHANGED);
// VideoFormat.
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_UNKNOWN,
VideoFormat::UNKNOWN);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_I420, VideoFormat::I420);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YV12, VideoFormat::YV12);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YV16, VideoFormat::YV16);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YV12A, VideoFormat::YV12A);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YV24, VideoFormat::YV24);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_NV12, VideoFormat::NV12);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_NV21, VideoFormat::NV21);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_UYVY, VideoFormat::UYVY);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YUY2, VideoFormat::YUY2);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_ARGB, VideoFormat::ARGB);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_XRGB, VideoFormat::XRGB);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_RGB24, VideoFormat::RGB24);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_RGB32, VideoFormat::RGB32);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_MJPEG, VideoFormat::MJPEG);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_MT21, VideoFormat::MT21);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV420P9,
VideoFormat::YUV420P9);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV422P9,
VideoFormat::YUV422P9);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV444P9,
VideoFormat::YUV444P9);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV420P10,
VideoFormat::YUV420P10);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV422P10,
VideoFormat::YUV422P10);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV444P10,
VideoFormat::YUV444P10);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_MAX, VideoFormat::FORMAT_MAX);
// ColorSpace.
ASSERT_ENUM_EQ_RAW(ColorSpace,
COLOR_SPACE_UNSPECIFIED,
ColorSpace::UNSPECIFIED);
ASSERT_ENUM_EQ_RAW(ColorSpace, COLOR_SPACE_JPEG, ColorSpace::JPEG);
ASSERT_ENUM_EQ_RAW(ColorSpace, COLOR_SPACE_HD_REC709, ColorSpace::HD_REC709);
ASSERT_ENUM_EQ_RAW(ColorSpace, COLOR_SPACE_SD_REC601, ColorSpace::SD_REC601);
ASSERT_ENUM_EQ_RAW(ColorSpace, COLOR_SPACE_MAX, ColorSpace::MAX);
// VideoCodec
ASSERT_ENUM_EQ_RAW(VideoCodec, kUnknownVideoCodec, VideoCodec::UNKNOWN);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , H264);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , HEVC);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , VC1);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , MPEG2);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , MPEG4);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , Theora);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , VP8);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , VP9);
ASSERT_ENUM_EQ_RAW(VideoCodec, kVideoCodecMax, VideoCodec::Max);
// VideoCodecProfile
ASSERT_ENUM_EQ(VideoCodecProfile, , , VIDEO_CODEC_PROFILE_UNKNOWN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VIDEO_CODEC_PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_BASELINE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_MAIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_EXTENDED);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_HIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_HIGH10PROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_HIGH422PROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_HIGH444PREDICTIVEPROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_SCALABLEBASELINE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_SCALABLEHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_STEREOHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_MULTIVIEWHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP8PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP8PROFILE_ANY);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP8PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP9PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP9PROFILE_ANY);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP9PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VIDEO_CODEC_PROFILE_MAX);
// Decryptor Status
ASSERT_ENUM_EQ_RAW(Decryptor::Status,
Decryptor::kSuccess,
Decryptor::Status::SUCCESS);
ASSERT_ENUM_EQ_RAW(Decryptor::Status,
Decryptor::kNoKey,
Decryptor::Status::NO_KEY);
ASSERT_ENUM_EQ_RAW(Decryptor::Status,
Decryptor::kNeedMoreData,
Decryptor::Status::NEED_MORE_DATA);
ASSERT_ENUM_EQ_RAW(Decryptor::Status,
Decryptor::kError,
Decryptor::Status::DECRYPTION_ERROR);
// CdmException
#define ASSERT_CDM_EXCEPTION(value) \
static_assert( \
media::MediaKeys::value == static_cast<media::MediaKeys::Exception>( \
media::interfaces::CdmException::value), \
"Mismatched CDM Exception")
ASSERT_CDM_EXCEPTION(NOT_SUPPORTED_ERROR);
ASSERT_CDM_EXCEPTION(INVALID_STATE_ERROR);
ASSERT_CDM_EXCEPTION(INVALID_ACCESS_ERROR);
ASSERT_CDM_EXCEPTION(QUOTA_EXCEEDED_ERROR);
ASSERT_CDM_EXCEPTION(UNKNOWN_ERROR);
ASSERT_CDM_EXCEPTION(CLIENT_ERROR);
ASSERT_CDM_EXCEPTION(OUTPUT_ERROR);
// CDM Session Type
#define ASSERT_CDM_SESSION_TYPE(value) \
static_assert( \
media::MediaKeys::value == \
static_cast<media::MediaKeys::SessionType>( \
media::interfaces::ContentDecryptionModule::SessionType::value), \
"Mismatched CDM Session Type")
ASSERT_CDM_SESSION_TYPE(TEMPORARY_SESSION);
ASSERT_CDM_SESSION_TYPE(PERSISTENT_LICENSE_SESSION);
ASSERT_CDM_SESSION_TYPE(PERSISTENT_RELEASE_MESSAGE_SESSION);
// CDM InitDataType
#define ASSERT_CDM_INIT_DATA_TYPE(value) \
static_assert(media::EmeInitDataType::value == \
static_cast<media::EmeInitDataType>( \
media::interfaces::ContentDecryptionModule:: \
InitDataType::value), \
"Mismatched CDM Init Data Type")
ASSERT_CDM_INIT_DATA_TYPE(UNKNOWN);
ASSERT_CDM_INIT_DATA_TYPE(WEBM);
ASSERT_CDM_INIT_DATA_TYPE(CENC);
ASSERT_CDM_INIT_DATA_TYPE(KEYIDS);
// CDM Key Status
#define ASSERT_CDM_KEY_STATUS(value) \
static_assert(media::CdmKeyInformation::value == \
static_cast<media::CdmKeyInformation::KeyStatus>( \
media::interfaces::CdmKeyStatus::value), \
"Mismatched CDM Key Status")
ASSERT_CDM_KEY_STATUS(USABLE);
ASSERT_CDM_KEY_STATUS(INTERNAL_ERROR);
ASSERT_CDM_KEY_STATUS(EXPIRED);
ASSERT_CDM_KEY_STATUS(OUTPUT_RESTRICTED);
ASSERT_CDM_KEY_STATUS(OUTPUT_DOWNSCALED);
ASSERT_CDM_KEY_STATUS(KEY_STATUS_PENDING);
// CDM Message Type
#define ASSERT_CDM_MESSAGE_TYPE(value) \
static_assert(media::MediaKeys::value == \
static_cast<media::MediaKeys::MessageType>( \
media::interfaces::CdmMessageType::value), \
"Mismatched CDM Message Type")
ASSERT_CDM_MESSAGE_TYPE(LICENSE_REQUEST);
ASSERT_CDM_MESSAGE_TYPE(LICENSE_RENEWAL);
ASSERT_CDM_MESSAGE_TYPE(LICENSE_RELEASE);
// static
media::interfaces::SubsampleEntryPtr TypeConverter<
media::interfaces::SubsampleEntryPtr,
media::SubsampleEntry>::Convert(const media::SubsampleEntry& input) {
media::interfaces::SubsampleEntryPtr mojo_subsample_entry(
media::interfaces::SubsampleEntry::New());
mojo_subsample_entry->clear_bytes = input.clear_bytes;
mojo_subsample_entry->cypher_bytes = input.cypher_bytes;
return mojo_subsample_entry;
}
// static
media::SubsampleEntry
TypeConverter<media::SubsampleEntry, media::interfaces::SubsampleEntryPtr>::
Convert(const media::interfaces::SubsampleEntryPtr& input) {
return media::SubsampleEntry(input->clear_bytes, input->cypher_bytes);
}
// static
media::interfaces::DecryptConfigPtr TypeConverter<
media::interfaces::DecryptConfigPtr,
media::DecryptConfig>::Convert(const media::DecryptConfig& input) {
media::interfaces::DecryptConfigPtr mojo_decrypt_config(
media::interfaces::DecryptConfig::New());
mojo_decrypt_config->key_id = input.key_id();
mojo_decrypt_config->iv = input.iv();
mojo_decrypt_config->subsamples =
Array<media::interfaces::SubsampleEntryPtr>::From(input.subsamples());
return mojo_decrypt_config;
}
// static
scoped_ptr<media::DecryptConfig>
TypeConverter<scoped_ptr<media::DecryptConfig>,
media::interfaces::DecryptConfigPtr>::
Convert(const media::interfaces::DecryptConfigPtr& input) {
return make_scoped_ptr(new media::DecryptConfig(
input->key_id, input->iv,
input->subsamples.To<std::vector<media::SubsampleEntry>>()));
}
// static
media::interfaces::DecoderBufferPtr
TypeConverter<media::interfaces::DecoderBufferPtr,
scoped_refptr<media::DecoderBuffer>>::
Convert(const scoped_refptr<media::DecoderBuffer>& input) {
DCHECK(input);
media::interfaces::DecoderBufferPtr mojo_buffer(
media::interfaces::DecoderBuffer::New());
if (input->end_of_stream())
return mojo_buffer;
mojo_buffer->timestamp_usec = input->timestamp().InMicroseconds();
mojo_buffer->duration_usec = input->duration().InMicroseconds();
mojo_buffer->is_key_frame = input->is_key_frame();
mojo_buffer->data_size = base::checked_cast<uint32_t>(input->data_size());
mojo_buffer->side_data_size =
base::checked_cast<uint32_t>(input->side_data_size());
mojo_buffer->front_discard_usec =
input->discard_padding().first.InMicroseconds();
mojo_buffer->back_discard_usec =
input->discard_padding().second.InMicroseconds();
mojo_buffer->splice_timestamp_usec =
input->splice_timestamp().InMicroseconds();
// Note: The side data is always small, so this copy is okay.
std::vector<uint8_t> side_data(input->side_data(),
input->side_data() + input->side_data_size());
mojo_buffer->side_data.Swap(&side_data);
if (input->decrypt_config()) {
mojo_buffer->decrypt_config =
media::interfaces::DecryptConfig::From(*input->decrypt_config());
}
// TODO(dalecurtis): We intentionally do not serialize the data section of
// the DecoderBuffer here; this must instead be done by clients via their
// own DataPipe. See http://crbug.com/432960
return mojo_buffer;
}
// static
scoped_refptr<media::DecoderBuffer>
TypeConverter<scoped_refptr<media::DecoderBuffer>,
media::interfaces::DecoderBufferPtr>::
Convert(const media::interfaces::DecoderBufferPtr& input) {
if (!input->data_size)
return media::DecoderBuffer::CreateEOSBuffer();
scoped_refptr<media::DecoderBuffer> buffer(
new media::DecoderBuffer(input->data_size));
if (input->side_data_size)
buffer->CopySideDataFrom(&input->side_data.front(), input->side_data_size);
buffer->set_timestamp(
base::TimeDelta::FromMicroseconds(input->timestamp_usec));
buffer->set_duration(base::TimeDelta::FromMicroseconds(input->duration_usec));
if (input->is_key_frame)
buffer->set_is_key_frame(true);
if (input->decrypt_config) {
buffer->set_decrypt_config(
input->decrypt_config.To<scoped_ptr<media::DecryptConfig>>());
}
media::DecoderBuffer::DiscardPadding discard_padding(
base::TimeDelta::FromMicroseconds(input->front_discard_usec),
base::TimeDelta::FromMicroseconds(input->back_discard_usec));
buffer->set_discard_padding(discard_padding);
buffer->set_splice_timestamp(
base::TimeDelta::FromMicroseconds(input->splice_timestamp_usec));
// TODO(dalecurtis): We intentionally do not deserialize the data section of
// the DecoderBuffer here; this must instead be done by clients via their
// own DataPipe. See http://crbug.com/432960
return buffer;
}
// static
media::interfaces::AudioDecoderConfigPtr TypeConverter<
media::interfaces::AudioDecoderConfigPtr,
media::AudioDecoderConfig>::Convert(const media::AudioDecoderConfig&
input) {
media::interfaces::AudioDecoderConfigPtr config(
media::interfaces::AudioDecoderConfig::New());
config->codec = static_cast<media::interfaces::AudioCodec>(input.codec());
config->sample_format =
static_cast<media::interfaces::SampleFormat>(input.sample_format());
config->channel_layout =
static_cast<media::interfaces::ChannelLayout>(input.channel_layout());
config->samples_per_second = input.samples_per_second();
if (!input.extra_data().empty()) {
config->extra_data = mojo::Array<uint8_t>::From(input.extra_data());
}
config->seek_preroll_usec = input.seek_preroll().InMicroseconds();
config->codec_delay = input.codec_delay();
config->is_encrypted = input.is_encrypted();
return config;
}
// static
media::AudioDecoderConfig
TypeConverter<media::AudioDecoderConfig,
media::interfaces::AudioDecoderConfigPtr>::
Convert(const media::interfaces::AudioDecoderConfigPtr& input) {
media::AudioDecoderConfig config;
config.Initialize(static_cast<media::AudioCodec>(input->codec),
static_cast<media::SampleFormat>(input->sample_format),
static_cast<media::ChannelLayout>(input->channel_layout),
input->samples_per_second, input->extra_data.storage(),
input->is_encrypted,
base::TimeDelta::FromMicroseconds(input->seek_preroll_usec),
input->codec_delay);
return config;
}
// static
media::interfaces::VideoDecoderConfigPtr TypeConverter<
media::interfaces::VideoDecoderConfigPtr,
media::VideoDecoderConfig>::Convert(const media::VideoDecoderConfig&
input) {
media::interfaces::VideoDecoderConfigPtr config(
media::interfaces::VideoDecoderConfig::New());
config->codec = static_cast<media::interfaces::VideoCodec>(input.codec());
config->profile =
static_cast<media::interfaces::VideoCodecProfile>(input.profile());
config->format = static_cast<media::interfaces::VideoFormat>(input.format());
config->color_space =
static_cast<media::interfaces::ColorSpace>(input.color_space());
config->coded_size = Size::From(input.coded_size());
config->visible_rect = Rect::From(input.visible_rect());
config->natural_size = Size::From(input.natural_size());
if (!input.extra_data().empty()) {
config->extra_data = mojo::Array<uint8_t>::From(input.extra_data());
}
config->is_encrypted = input.is_encrypted();
return config;
}
// static
media::VideoDecoderConfig
TypeConverter<media::VideoDecoderConfig,
media::interfaces::VideoDecoderConfigPtr>::
Convert(const media::interfaces::VideoDecoderConfigPtr& input) {
media::VideoDecoderConfig config;
config.Initialize(static_cast<media::VideoCodec>(input->codec),
static_cast<media::VideoCodecProfile>(input->profile),
static_cast<media::VideoPixelFormat>(input->format),
static_cast<media::ColorSpace>(input->color_space),
input->coded_size.To<gfx::Size>(),
input->visible_rect.To<gfx::Rect>(),
input->natural_size.To<gfx::Size>(),
input->extra_data.storage(), input->is_encrypted);
return config;
}
// static
media::interfaces::CdmKeyInformationPtr TypeConverter<
media::interfaces::CdmKeyInformationPtr,
media::CdmKeyInformation>::Convert(const media::CdmKeyInformation& input) {
media::interfaces::CdmKeyInformationPtr info(
media::interfaces::CdmKeyInformation::New());
std::vector<uint8_t> key_id_copy(input.key_id);
info->key_id.Swap(&key_id_copy);
info->status = static_cast<media::interfaces::CdmKeyStatus>(input.status);
info->system_code = input.system_code;
return info;
}
// static
scoped_ptr<media::CdmKeyInformation>
TypeConverter<scoped_ptr<media::CdmKeyInformation>,
media::interfaces::CdmKeyInformationPtr>::
Convert(const media::interfaces::CdmKeyInformationPtr& input) {
return make_scoped_ptr(new media::CdmKeyInformation(
input->key_id.storage(),
static_cast<media::CdmKeyInformation::KeyStatus>(input->status),
input->system_code));
}
// static
media::interfaces::CdmConfigPtr
TypeConverter<media::interfaces::CdmConfigPtr, media::CdmConfig>::Convert(
const media::CdmConfig& input) {
media::interfaces::CdmConfigPtr config(media::interfaces::CdmConfig::New());
config->allow_distinctive_identifier = input.allow_distinctive_identifier;
config->allow_persistent_state = input.allow_persistent_state;
config->use_hw_secure_codecs = input.use_hw_secure_codecs;
return config;
}
// static
media::CdmConfig
TypeConverter<media::CdmConfig, media::interfaces::CdmConfigPtr>::Convert(
const media::interfaces::CdmConfigPtr& input) {
media::CdmConfig config;
config.allow_distinctive_identifier = input->allow_distinctive_identifier;
config.allow_persistent_state = input->allow_persistent_state;
config.use_hw_secure_codecs = input->use_hw_secure_codecs;
return config;
}
// static
media::interfaces::AudioBufferPtr
TypeConverter<media::interfaces::AudioBufferPtr,
scoped_refptr<media::AudioBuffer>>::
Convert(const scoped_refptr<media::AudioBuffer>& input) {
media::interfaces::AudioBufferPtr buffer(
media::interfaces::AudioBuffer::New());
buffer->sample_format =
static_cast<media::interfaces::SampleFormat>(input->sample_format_);
buffer->channel_layout =
static_cast<media::interfaces::ChannelLayout>(input->channel_layout());
buffer->channel_count = input->channel_count();
buffer->sample_rate = input->sample_rate();
buffer->frame_count = input->frame_count();
buffer->end_of_stream = input->end_of_stream();
buffer->timestamp_usec = input->timestamp().InMicroseconds();
if (!input->end_of_stream()) {
std::vector<uint8_t> input_data(input->data_.get(),
input->data_.get() + input->data_size_);
buffer->data.Swap(&input_data);
}
return buffer;
}
// static
scoped_refptr<media::AudioBuffer>
TypeConverter<scoped_refptr<media::AudioBuffer>,
media::interfaces::AudioBufferPtr>::
Convert(const media::interfaces::AudioBufferPtr& input) {
if (input->end_of_stream)
return media::AudioBuffer::CreateEOSBuffer();
// Setup channel pointers. AudioBuffer::CopyFrom() will only use the first
// one in the case of interleaved data.
std::vector<const uint8_t*> channel_ptrs(input->channel_count, nullptr);
std::vector<uint8_t> storage = input->data.storage();
const size_t size_per_channel = storage.size() / input->channel_count;
DCHECK_EQ(0u, storage.size() % input->channel_count);
for (int i = 0; i < input->channel_count; ++i)
channel_ptrs[i] = storage.data() + i * size_per_channel;
return media::AudioBuffer::CopyFrom(
static_cast<media::SampleFormat>(input->sample_format),
static_cast<media::ChannelLayout>(input->channel_layout),
input->channel_count, input->sample_rate, input->frame_count,
&channel_ptrs[0],
base::TimeDelta::FromMicroseconds(input->timestamp_usec));
}
// static
media::interfaces::VideoFramePtr
TypeConverter<media::interfaces::VideoFramePtr,
scoped_refptr<media::VideoFrame>>::
Convert(const scoped_refptr<media::VideoFrame>& input) {
media::interfaces::VideoFramePtr frame(media::interfaces::VideoFrame::New());
frame->end_of_stream =
input->metadata()->IsTrue(media::VideoFrameMetadata::END_OF_STREAM);
if (frame->end_of_stream)
return frame;
// Handle non EOS frame. It must be a MojoSharedBufferVideoFrame.
// TODO(jrummell): Support other types of VideoFrame.
CHECK_EQ(media::VideoFrame::STORAGE_MOJO_SHARED_BUFFER,
input->storage_type());
media::MojoSharedBufferVideoFrame* input_frame =
static_cast<media::MojoSharedBufferVideoFrame*>(input.get());
mojo::ScopedSharedBufferHandle duplicated_handle;
const MojoResult result =
DuplicateBuffer(input_frame->Handle(), nullptr, &duplicated_handle);
CHECK_EQ(MOJO_RESULT_OK, result);
CHECK(duplicated_handle.is_valid());
frame->format = static_cast<media::interfaces::VideoFormat>(input->format());
frame->coded_size = Size::From(input->coded_size());
frame->visible_rect = Rect::From(input->visible_rect());
frame->natural_size = Size::From(input->natural_size());
frame->timestamp_usec = input->timestamp().InMicroseconds();
frame->frame_data = std::move(duplicated_handle);
frame->frame_data_size = input_frame->MappedSize();
frame->y_stride = input_frame->stride(media::VideoFrame::kYPlane);
frame->u_stride = input_frame->stride(media::VideoFrame::kUPlane);
frame->v_stride = input_frame->stride(media::VideoFrame::kVPlane);
frame->y_offset = input_frame->PlaneOffset(media::VideoFrame::kYPlane);
frame->u_offset = input_frame->PlaneOffset(media::VideoFrame::kUPlane);
frame->v_offset = input_frame->PlaneOffset(media::VideoFrame::kVPlane);
return frame;
}
// static
scoped_refptr<media::VideoFrame>
TypeConverter<scoped_refptr<media::VideoFrame>,
media::interfaces::VideoFramePtr>::
Convert(const media::interfaces::VideoFramePtr& input) {
if (input->end_of_stream)
return media::VideoFrame::CreateEOSFrame();
return media::MojoSharedBufferVideoFrame::Create(
static_cast<media::VideoPixelFormat>(input->format),
input->coded_size.To<gfx::Size>(), input->visible_rect.To<gfx::Rect>(),
input->natural_size.To<gfx::Size>(), std::move(input->frame_data),
input->frame_data_size, input->y_offset, input->u_offset, input->v_offset,
input->y_stride, input->u_stride, input->v_stride,
base::TimeDelta::FromMicroseconds(input->timestamp_usec));
}
} // namespace mojo
| highweb-project/highweb-webcl-html5spec | media/mojo/common/media_type_converters.cc | C++ | bsd-3-clause | 29,089 |
from enum import Enum
from django.conf import settings
from django.utils.translation import npgettext_lazy, pgettext_lazy
from django_prices.templatetags import prices_i18n
from prices import Money
class OrderStatus:
DRAFT = 'draft'
UNFULFILLED = 'unfulfilled'
PARTIALLY_FULFILLED = 'partially fulfilled'
FULFILLED = 'fulfilled'
CANCELED = 'canceled'
CHOICES = [
(DRAFT, pgettext_lazy(
'Status for a fully editable, not confirmed order created by '
'staff users',
'Draft')),
(UNFULFILLED, pgettext_lazy(
'Status for an order with no items marked as fulfilled',
'Unfulfilled')),
(PARTIALLY_FULFILLED, pgettext_lazy(
'Status for an order with some items marked as fulfilled',
'Partially fulfilled')),
(FULFILLED, pgettext_lazy(
'Status for an order with all items marked as fulfilled',
'Fulfilled')),
(CANCELED, pgettext_lazy(
'Status for a permanently canceled order',
'Canceled'))]
class FulfillmentStatus:
FULFILLED = 'fulfilled'
CANCELED = 'canceled'
CHOICES = [
(FULFILLED, pgettext_lazy(
'Status for a group of products in an order marked as fulfilled',
'Fulfilled')),
(CANCELED, pgettext_lazy(
'Status for a fulfilled group of products in an order marked '
'as canceled',
'Canceled'))]
class OrderEvents(Enum):
PLACED = 'placed'
PLACED_FROM_DRAFT = 'draft_placed'
OVERSOLD_ITEMS = 'oversold_items'
ORDER_MARKED_AS_PAID = 'marked_as_paid'
CANCELED = 'canceled'
ORDER_FULLY_PAID = 'order_paid'
UPDATED = 'updated'
EMAIL_SENT = 'email_sent'
PAYMENT_CAPTURED = 'captured'
PAYMENT_REFUNDED = 'refunded'
PAYMENT_VOIDED = 'voided'
FULFILLMENT_CANCELED = 'fulfillment_canceled'
FULFILLMENT_RESTOCKED_ITEMS = 'restocked_items'
FULFILLMENT_FULFILLED_ITEMS = 'fulfilled_items'
TRACKING_UPDATED = 'tracking_updated'
NOTE_ADDED = 'note_added'
# Used mostly for importing legacy data from before Enum-based events
OTHER = 'other'
class OrderEventsEmails(Enum):
PAYMENT = 'payment_confirmation'
SHIPPING = 'shipping_confirmation'
ORDER = 'order_confirmation'
FULFILLMENT = 'fulfillment_confirmation'
EMAIL_CHOICES = {
OrderEventsEmails.PAYMENT.value: pgettext_lazy(
'Email type', 'Payment confirmation'),
OrderEventsEmails.SHIPPING.value: pgettext_lazy(
'Email type', 'Shipping confirmation'),
OrderEventsEmails.FULFILLMENT.value: pgettext_lazy(
'Email type', 'Fulfillment confirmation'),
OrderEventsEmails.ORDER.value: pgettext_lazy(
'Email type', 'Order confirmation')}
def get_money_from_params(amount):
"""Money serialization changed at one point, as for now it's serialized
as a dict. But we keep those settings for the legacy data.
Can be safely removed after migrating to Dashboard 2.0
"""
if isinstance(amount, Money):
return amount
if isinstance(amount, dict):
return Money(amount=amount['amount'], currency=amount['currency'])
return Money(amount, settings.DEFAULT_CURRENCY)
def display_order_event(order_event):
"""This function is used to keep the backwards compatibility
with the old dashboard and new type of order events
(storing enums instead of messages)
"""
event_type = order_event.type
params = order_event.parameters
if event_type == OrderEvents.PLACED_FROM_DRAFT.value:
return pgettext_lazy(
'Dashboard message related to an order',
'Order created from draft order by %(user_name)s' % {
'user_name': order_event.user})
if event_type == OrderEvents.PAYMENT_VOIDED.value:
return pgettext_lazy(
'Dashboard message related to an order',
'Payment was voided by %(user_name)s' % {
'user_name': order_event.user})
if event_type == OrderEvents.PAYMENT_REFUNDED.value:
amount = get_money_from_params(params['amount'])
return pgettext_lazy(
'Dashboard message related to an order',
'Successfully refunded: %(amount)s' % {
'amount': prices_i18n.amount(amount)})
if event_type == OrderEvents.PAYMENT_CAPTURED.value:
amount = get_money_from_params(params['amount'])
return pgettext_lazy(
'Dashboard message related to an order',
'Successfully captured: %(amount)s' % {
'amount': prices_i18n.amount(amount)})
if event_type == OrderEvents.ORDER_MARKED_AS_PAID.value:
return pgettext_lazy(
'Dashboard message related to an order',
'Order manually marked as paid by %(user_name)s' % {
'user_name': order_event.user})
if event_type == OrderEvents.CANCELED.value:
return pgettext_lazy(
'Dashboard message related to an order',
'Order was canceled by %(user_name)s' % {
'user_name': order_event.user})
if event_type == OrderEvents.FULFILLMENT_RESTOCKED_ITEMS.value:
return npgettext_lazy(
'Dashboard message related to an order',
'We restocked %(quantity)d item',
'We restocked %(quantity)d items',
number='quantity') % {'quantity': params['quantity']}
if event_type == OrderEvents.NOTE_ADDED.value:
return pgettext_lazy(
'Dashboard message related to an order',
'%(user_name)s added note: %(note)s' % {
'note': params['message'],
'user_name': order_event.user})
if event_type == OrderEvents.FULFILLMENT_CANCELED.value:
return pgettext_lazy(
'Dashboard message',
'Fulfillment #%(fulfillment)s canceled by %(user_name)s') % {
'fulfillment': params['composed_id'],
'user_name': order_event.user}
if event_type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS.value:
return npgettext_lazy(
'Dashboard message related to an order',
'Fulfilled %(quantity_fulfilled)d item',
'Fulfilled %(quantity_fulfilled)d items',
number='quantity_fulfilled') % {
'quantity_fulfilled': params['quantity']}
if event_type == OrderEvents.PLACED.value:
return pgettext_lazy(
'Dashboard message related to an order',
'Order was placed')
if event_type == OrderEvents.ORDER_FULLY_PAID.value:
return pgettext_lazy(
'Dashboard message related to an order',
'Order was fully paid')
if event_type == OrderEvents.EMAIL_SENT.value:
return pgettext_lazy(
'Dashboard message related to an order',
'%(email_type)s email was sent to the customer '
'(%(email)s)') % {
'email_type': EMAIL_CHOICES[params['email_type']],
'email': params['email']}
if event_type == OrderEvents.UPDATED.value:
return pgettext_lazy(
'Dashboard message related to an order',
'Order details were updated by %(user_name)s' % {
'user_name': order_event.user})
if event_type == OrderEvents.TRACKING_UPDATED.value:
return pgettext_lazy(
'Dashboard message related to an order',
'Fulfillment #%(fulfillment)s tracking was updated to'
' %(tracking_number)s by %(user_name)s') % {
'fulfillment': params['composed_id'],
'tracking_number': params['tracking_number'],
'user_name': order_event.user}
if event_type == OrderEvents.OVERSOLD_ITEMS.value:
return npgettext_lazy(
'Dashboard message related to an order',
'%(quantity)d line item oversold on this order.',
'%(quantity)d line items oversold on this order.',
number='quantity') % {
'quantity': len(params['oversold_items'])}
if event_type == OrderEvents.OTHER.value:
return order_event.parameters['message']
raise ValueError('Not supported event type: %s' % (event_type))
| UITools/saleor | saleor/order/__init__.py | Python | bsd-3-clause | 8,246 |
// Copyright (c) 2015, Robert Escriva
// 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 Replicant 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.
#define __STDC_LIMIT_MACROS
// Google SparseHash
#include <google/dense_hash_map>
// po6
#include <po6/errno.h>
#include <po6/threads/mutex.h>
#include <po6/threads/thread.h>
#include <po6/time.h>
// e
#include <e/atomic.h>
// Ygor
#include <ygor.h>
// Replicant
#include <replicant.h>
#include "tools/common.h"
#define MICROS 1000ULL
#define MILLIS (1000ULL * MICROS)
#define SECONDS (1000ULL * MILLIS)
struct benchmark
{
benchmark();
~benchmark() throw ();
void producer();
void consumer();
const char* output;
const char* object;
const char* function;
long target;
long length;
ygor_data_logger* dl;
uint32_t done;
po6::threads::mutex mtx;
replicant_client* client;
google::dense_hash_map<int64_t, uint64_t> times;
replicant_returncode rr;
private:
benchmark(const benchmark&);
benchmark& operator = (const benchmark&);
};
benchmark :: benchmark()
: output("benchmark.dat.bz2")
, object("echo")
, function("echo")
, target(100)
, length(60)
, dl(NULL)
, done(0)
, mtx()
, client(NULL)
, times()
, rr()
{
times.set_empty_key(INT64_MAX);
times.set_deleted_key(INT64_MAX - 1);
}
benchmark :: ~benchmark() throw ()
{
}
void
benchmark :: producer()
{
const uint64_t start = po6::wallclock_time();
const uint64_t end = start + length * SECONDS;
uint64_t now = start;
uint64_t issued = 0;
while (now < end)
{
double elapsed = double(now - start) / SECONDS;
uint64_t expected = elapsed * target;
for (uint64_t i = issued; i < expected; ++i)
{
po6::threads::mutex::hold hold(&mtx);
now = po6::wallclock_time();
int64_t id = replicant_client_call(client, object, function, "", 0, 0, &rr, NULL, 0);
if (id < 0)
{
std::cerr << "call failed: "
<< replicant_client_error_message(client) << " @ "
<< replicant_client_error_location(client) << std::endl;
abort();
}
times.insert(std::make_pair(id, now));
}
issued = expected;
timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 1 * MILLIS;
nanosleep(&ts, NULL);
now = po6::wallclock_time();
}
e::atomic::store_32_release(&done, 1);
}
void
benchmark :: consumer()
{
while (true)
{
replicant_client_block(client, 250);
po6::threads::mutex::hold hold(&mtx);
replicant_returncode lr;
int64_t id = replicant_client_loop(client, 0, &lr);
if (id < 0 && lr == REPLICANT_NONE_PENDING && e::atomic::load_32_acquire(&done) != 0)
{
break;
}
else if (id < 0 && (lr == REPLICANT_TIMEOUT || lr == REPLICANT_NONE_PENDING))
{
continue;
}
else if (id < 0)
{
std::cerr << "loop failed: "
<< replicant_client_error_message(client) << " @ "
<< replicant_client_error_location(client) << std::endl;
abort();
}
if (rr != REPLICANT_SUCCESS)
{
std::cerr << "call failed: "
<< replicant_client_error_message(client) << " @ "
<< replicant_client_error_location(client) << std::endl;
abort();
}
const uint64_t end = po6::wallclock_time();
google::dense_hash_map<int64_t, uint64_t>::iterator it = times.find(id);
if (it == times.end())
{
std::cerr << "bad map handling code" << std::endl;
abort();
}
const uint64_t start = it->second;
times.erase(it);
ygor_data_record dr;
dr.series = 1;
dr.when = start;
dr.data = end - start;
if (ygor_data_logger_record(dl, &dr) < 0)
{
std::cerr << "could not record data point: " << po6::strerror(errno) << std::endl;
abort();
}
}
}
int
main(int argc, const char* argv[])
{
benchmark b;
connect_opts conn;
e::argparser ap;
ap.autohelp();
ap.arg().name('o', "output")
.description("where to save the recorded benchmark stats (default: benchmark.dat.bz2)")
.as_string(&b.output);
ap.arg().long_name("object")
.description("object to call (default: echo)")
.as_string(&b.object);
ap.arg().long_name("function")
.description("function to call (default: echo)")
.as_string(&b.function);
ap.arg().name('t', "throughput")
.description("target throughput (default: 100 ops/s)")
.as_long(&b.target);
ap.arg().name('r', "runtime")
.description("total test runtime length in seconds (default: 60)")
.as_long(&b.length);
ap.add("Connect to a cluster:", conn.parser());
if (!ap.parse(argc, argv))
{
return EXIT_FAILURE;
}
if (ap.args_sz() != 0)
{
std::cerr << "command requires no positional arguments\n" << std::endl;
ap.usage();
return EXIT_FAILURE;
}
if (!conn.validate())
{
std::cerr << "invalid host:port specification\n" << std::endl;
ap.usage();
return EXIT_FAILURE;
}
ygor_data_logger* dl = ygor_data_logger_create(b.output, 1000000, 1000);
if (!dl)
{
std::cerr << "could not open output: " << po6::strerror(errno) << std::endl;
return EXIT_FAILURE;
}
b.client = replicant_client_create(conn.host(), conn.port());
b.dl = dl;
po6::threads::thread prod(po6::threads::make_thread_wrapper(&benchmark::producer, &b));
po6::threads::thread cons(po6::threads::make_thread_wrapper(&benchmark::consumer, &b));
prod.start();
cons.start();
prod.join();
cons.join();
if (ygor_data_logger_flush_and_destroy(dl) < 0)
{
std::cerr << "could not close output: " << po6::strerror(errno) << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| rescrv/Replicant | replicant-benchmark.cc | C++ | bsd-3-clause | 7,712 |
from pprint import pprint as pp
from scout.load.transcript import load_transcripts
def test_load_transcripts(adapter, gene_bulk, transcripts_handle):
# GIVEN a empty database
assert sum(1 for i in adapter.all_genes()) == 0
assert sum(1 for i in adapter.transcripts()) == 0
# WHEN inserting a number of genes and some transcripts
adapter.load_hgnc_bulk(gene_bulk)
load_transcripts(adapter, transcripts_lines=transcripts_handle, build="37")
# THEN assert all genes have been added to the database
assert sum(1 for i in adapter.all_genes()) == len(gene_bulk)
# THEN assert that the transcripts where loaded loaded
assert sum(1 for i in adapter.transcripts()) > 0
| Clinical-Genomics/scout | tests/load/test_load_transcripts.py | Python | bsd-3-clause | 707 |
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from casepro.test import BaseCasesTest
class OrgExtCRUDLTest(BaseCasesTest):
def test_home(self):
url = reverse('orgs_ext.org_home')
self.login(self.admin)
response = self.url_get('unicef', url)
self.assertEqual(response.status_code, 200)
| praekelt/helpdesk | casepro/orgs_ext/tests.py | Python | bsd-3-clause | 382 |
/**
* Shake Table web interface.
*
* @author Michael Diponio <michael.diponio@uts.edu.au>
* @author Jesse Charlton <jesse.charlton@uts.edu.au>
* @date 1/6/2013
*/
/* ============================================================================
* == Shake Table. ==
* ============================================================================ */
function ShakeTable(is3DOF)
{
new WebUIApp(is3DOF ? Config3DOF() : Config2DOF()).setup().run();
}
/**
* 2 degree of freedom (2DOF) Shake Table interface.
*/
function Config2DOF()
{
return {
anchor: "#shake-table-anchor",
controller: "ShakeTableController",
dataAction: "dataAndGraph",
dataDuration: 30,
dataPeriod: 10,
pollPeriod: 1000,
windowToggle: true,
theme: Globals.THEMES.flat,
cookie: "shaketable2dof",
widgets: [
new MimicWidget(false),
new Container("graphs-container", {
title: "Graphs",
reizable: true,
left: -191,
top: 540,
widgets: [
new Graph("graph-displacement", {
title: "Displacements",
resizable: true,
fields: {
'disp-graph-1': 'Base',
'disp-graph-2': 'Level 1',
'disp-graph-3': 'Level 2'
},
minValue: -60,
maxValue: 60,
duration: 10,
durationCtl: true,
yLabel: "Displacement (mm)",
fieldCtl: true,
autoCtl: true,
traceLabels: true,
width: 832,
height: 325,
}),
new Container("graphs-lissajous-container", {
title: "Lissajous",
widgets: [
new ScatterPlot("graph-lissajous-l0l1", {
title: "L0 vs L1",
xLabel: "L0 (mm)",
yLabel: "L1 (mm)",
autoScale: true,
vertScales: 5,
horizScales: 5,
sampleSize: 125,
fields: {
'disp-graph-1': 'disp-graph-2'
},
labels: {
'disp-graph-1': "L0 vs L1",
},
traceLabels: false,
}),
new ScatterPlot("graph-lissajous-l0l2", {
title: "L0 vs L2",
xLabel: "L0 (mm)",
yLabel: "L2 (mm)",
autoScale: true,
vertScales: 5,
horizScales: 5,
sampleSize: 125,
fields: {
'disp-graph-1': 'disp-graph-3'
},
labels: {
'disp-graph-1': "L0 vs L2",
},
traceLabels: false
}),
new ScatterPlot("graph-lissajous-l1l2", {
title: "L1 vs L2",
xLabel: "L1 (mm)",
yLabel: "L2 (mm)",
autoScale: true,
vertScales: 5,
horizScales: 5,
sampleSize: 125,
fields: {
'disp-graph-2': 'disp-graph-3'
},
labels: {
'disp-graph-2': "L1 vs L2",
},
traceLabels: false
}),
],
layout: new TabLayout({
position: TabLayout.POSITION.left,
border: 0,
})
}),
new Container("fft-container", {
title: "FFT",
widgets: [
new FFTGraph("graph-fft", {
title: "FFT",
resizable: true,
fields: {
'disp-graph-1': 'Base',
'disp-graph-2': 'Level 1',
'disp-graph-3': 'Level 2'
},
xLabel: "Frequency (Hz)",
yLabel: "Amplitude (mm)",
horizScales: 10,
maxValue: 30,
period: 10,
duration: 10,
fieldCtl: true,
autoScale: true,
}),
new Button("button-fft-export", {
label: "Export FFT",
link: "/primitive/file/pc/ShakeTableController/pa/exportFFT/fn/fft.txt",
target: "_blank",
width: 80,
height: 20,
resizable: false
})
],
layout: new AbsoluteLayout({
coords: {
"graph-fft": { x: 0, y: 0 },
"button-fft-export": { x: 20, y: -1 }
}
})
}),
],
layout: new TabLayout({
position: TabLayout.POSITION.top,
border: 10,
})
}),
new CameraStream("camera-stream", {
resizable: true,
left: -2,
top: 5,
videoWidth: 320,
videoHeight: 240,
swfParam: 'camera-swf',
mjpegParam: 'camera-mjpeg',
title: "Camera"
}),
new Container("controls-container", {
title: "Controls",
resizable: false,
left: -2,
top: 335,
widgets: [
new Slider("slider-motor-speed", {
field: "motor-speed",
action: "setMotor",
max: 8,
precision: 2,
label: "Motor Frequency",
units: "Hz",
vertical: false,
}),
new Slider("slider-coil-1", {
length: 75,
action: "setCoil",
field: "coils-1-power",
label: "Coil 1",
vertical: true,
scales: 2,
units: "%"
}),
new Slider("slider-coil-2", {
length: 75,
action: "setCoil",
field: "coils-2-power",
label: "Coil 2",
vertical: true,
scales: 2,
units: "%"
}),
new Container("container-control-buttons", {
width: 200,
widgets: [
new Switch("switch-motor-on", {
field: "motor-on",
action: "setMotor",
label: "Motor",
width: 96,
}),
new Switch("switch-coils-on", {
field: "coils-on",
action: "setCoils",
label: "Coils",
width: 92,
}),
new Switch("switch-coupling", {
field: "motor-coil-couple",
action: "setCouple",
label: "Couple",
width: 107,
}),
new Image("couple-to-motor" , {
image: "/uts/shaketable/images/arrow-couple-left.png",
}),
new Image("couple-to-coils" , {
image: "/uts/shaketable/images/arrow-couple-right.png",
}),
],
layout: new AbsoluteLayout({
border: 10,
coords: {
"switch-motor-on": { x: -5, y: 20 },
"switch-coils-on": { x: 100, y: 20 },
"switch-coupling": { x: 40, y: 80 },
"couple-to-motor": { x: 0, y: 55 },
"couple-to-coils": { x: 154, y: 55 },
}
})
}),
],
layout: new GridLayout({
padding: 5,
columns: [
[ "container-control-buttons" ],
[ "slider-motor-speed" ],
[ "slider-coil-1" ],
[ "slider-coil-2" ]
]
})
}),
new DataLogging("data-logger", {
left: -193,
top: 142,
width: 183,
height: 388,
})
]
};
}
/*
* 3 degree of freedom (3DOF) Shake Table interface.
*/
function Config3DOF()
{
return {
anchor: "#shake-table-anchor",
controller: "ShakeTableController",
dataAction: "dataAndGraph",
dataDuration: 10,
dataPeriod: 100,
pollPeriod: 1000,
windowToggle: true,
theme: Globals.THEMES.flat,
cookie: "shaketable",
widgets: [
new Graph("graph-displacement", {
title: "Graphs",
resizable: true,
width: 418,
height: 328,
left: 351,
top: 423,
fields: {
'disp-graph-1': 'Level 1',
'disp-graph-2': 'Level 2',
'disp-graph-3': 'Level 3'
},
minValue: -60,
maxValue: 60,
duration: 10,
yLabel: "Displacement (mm)",
fieldCtl: false,
autoCtl: false,
durationCtl: false,
traceLabels: false,
}),
new MimicWidget(true),
new CameraStream("camera-stream", {
resizable: true,
left: 2,
top: 45,
videoWidth: 320,
videoHeight: 240,
swfParam: 'camera-swf',
mjpegParam: 'camera-mjpeg',
title: "Camera"
}),
new Container("controls-container", {
title: "Controls",
resizable: false,
left: 2,
top: 375,
widgets: [
new Switch("switch-motor-on", {
field: "motor-on",
action: "setMotor",
label: "Motor",
}),
new Switch("switch-coils-on", {
field: "coils-on",
action: "setCoils",
label: "Dampening",
}),
new Slider("slider-motor-speed", {
field: "motor-speed",
action: "setMotor",
max: 8,
precision: 2,
label: "Motor Frequency",
units: "Hz",
vertical: false,
})
],
layout: new FlowLayout({
padding: 5,
size: 320,
vertical: false,
center: true,
})
})
]
};
}
/* ============================================================================
* == Mimic Widget. ==
* ============================================================================ */
/**
* Mimic Widget. This widget creates and controls the Shake Table Mimic.
*
* @param {boolean} is3DOF whether to display 2DOF or 3DOF configuration
*/
function MimicWidget(is3DOF)
{
Widget.call(this, "shaker-mimic", {
title: "Model",
windowed: true,
resizable: true,
preserveAspectRatio: true,
minWidth: 320,
minHeight: 410,
closeable: true,
shadeable: true,
expandable: true,
draggable: true,
left: 338,
top: 5,
width: 334
});
/** Model dimensions in mm. */
this.model = {
levelWidth: 200, // Width of the model
armWidth: 70, // Width of the stroke arm connecting the motor to the model
motorRadius: 10, // Radius of the motor
wallHeight: 120, // Height of the walls
levelHeight: 30, // Height of the levels
trackHeight: 20, // Height of the track
trackWidth: 300, // Width of track
carHeight: 10, // Height of carriage
carWidth: 120, // Width of carriage
maxDisp: 60, // Maximum displacement of the diagram
baseDisp: 0.7 // Displacement of the base when the motor is on
};
/** Whether this mimic represents a 2DOF or a 3DOF widget. */
this.is3DOF = is3DOF;
/** Number of levels in the model. */
this.numberLevels = this.is3DOF ? 4 : 3;
/** Millimeters per pixel. */
this.mmPerPx = 1.475;
/** The width of the diagram in pixels. */
this.width = undefined;
/** The height of the diagram in pixels. */
this.height = undefined;
/** The period in milliseconds. */
this.period = 10;
/** Canvas context. */
this.ctx = null;
/** Amplitude of displacement in mm. */
this.amp = [ 0, 0, 0, 0 ];
/** Angular frequency r/s. */
this.w = 0;
/** Offsets of levels. */
this.o = [ 0, 0, 0, 0 ];
/** Frame count. */
this.fr = 0;
/** Motor frequency. */
this.motor = 0;
/** Coil power percentages. */
this.coils = [ undefined, undefined, undefined ];
/** Center line. */
this.cx = undefined;
/** Animation interval. */
this.animateInterval = undefined;
}
MimicWidget.prototype = new Widget;
MimicWidget.ANIMATE_PERIOD = 50;
MimicWidget.prototype.init = function($container) {
var canvas, thiz = this;
this.mmPerPx = 1.475;
if (this.window.width)
{
this.mmPerPx = 320 / this.window.width * 1.475;
}
/* The width of the canvas diagram is the width of the building model plus
* the maximum possible displacement. */
this.width = this.px(this.model.levelWidth + this.model.maxDisp * 2) + this.px(100);
this.height = this.px(this.model.levelHeight * (this.is3DOF ? 4 : 3) +
this.model.wallHeight * (this.is3DOF ? 3: 2) + this.model.trackHeight + this.model.carHeight);
this.cx = this.width / 2;
/* Box. */
this.$widget = this._generate($container, "<div class='mimic'></div>");
this.$widget.css("height", "auto");
/* Canvas to draw display. */
canvas = Util.getCanvas(this.id + "-canvas", this.width, this.height);
this.$widget.find(".mimic").append(canvas);
this.ctx = canvas.getContext("2d");
this.ctx.translate(0.5, 0.5);
/* Draw initial frame of zero position. */
this.drawFrame([0, 0, 0, 0]);
this.boxWidth = this.$widget.width();
/* Start animation. */
this.animateInterval = setInterval(function() { thiz.animationFrame(); }, MimicWidget.ANIMATE_PERIOD);
};
MimicWidget.prototype.consume = function(data) {
var i, l, peaks = [], level, range, topLevel = this.numberLevels - 1;
/* We need to find a list of peaks for each of the levels. */
for (l = 1; l <= this.numberLevels; l++)
{
if (!$.isArray(data["disp-graph-" + l])) continue;
/* To find peaks we are searching for the values where the preceding value is
* not larger than the subsequent value. */
level = [ ];
for (i = data["disp-graph-" + l].length - 2; i > 1; i--)
{
if (data["disp-graph-" + l][i] > data["disp-graph-" + l][i + 1] &&
data["disp-graph-" + l][i] >= data["disp-graph-" + l][i - 1])
{
level.push(i);
/* We only require a maximum of 5 peaks. */
if (level.length == 5) break;
}
}
/* If we don't have the requiste number of peaks, don't update data. */
while (level.length < 5) return;
peaks.push(level);
/* Amplitude is a peak value. The amplitude we are using will the median
* of the last 3 peaks. */
this.amp[l] = this.medianFilter([ data["disp-graph-" + l][level[0]],
data["disp-graph-" + l][level[1]],
data["disp-graph-" + l][level[2]] ]);
/* Without a distinct signal, the model has an unrepresentative wiggle,
* so we small amplitudes will be thresholded to 0. */
if (this.amp[l] < 2) this.amp[l] = 0;
}
/* Amplitude for the base is fixed at 0.7 mm but only applies if the motor
* is active. */
this.amp[0] = data['motor-on'] ? this.model.baseDisp : 0;
/* Angular frequency is derived by the periodicity of peaks. */
range = this.medianFilter([ peaks[topLevel][0] - peaks[topLevel][1],
peaks[topLevel][1] - peaks[topLevel][2],
peaks[topLevel][2] - peaks[topLevel][3],
peaks[topLevel][3] - peaks[topLevel][4] ]);
this.w = isFinite(i = 2 * Math.PI * 1 / (this.period / 1000 * range)) != Number.Infinity ? i : 0;
/* Phase if determined based on the difference in peaks between the top
* level and lower levels. */
for (l = 2; l < this.numberLevels - 1; l++)
{
this.o[l] = 2 * Math.PI * this.medianFilter([ peaks[l - 1][0] - peaks[topLevel][0],
peaks[l - 1][1] - peaks[topLevel][1],
peaks[l - 1][2] - peaks[topLevel][2],
peaks[l - 1][3] - peaks[topLevel][3] ]) / range;
}
/** Coil states. */
if (this.is3DOF)
{
/* The 3DOF is either on or off. */
for (i = 0; i < this.coils.length; i++) this.coils[i] = data['coils-on'] ? 100 : 0;
}
else
{
this.coils[0] = data['coils-1-on'] ? data['coils-1-power'] : 0;
this.coils[1] = data['coils-2-on'] ? data['coils-2-power'] : 0;
}
/* Motor details. */
this.motor = data['motor-on'] ? data['motor-speed'] : 0;
};
/**
* Runs a median filter on the algorithm.
*/
MimicWidget.prototype.medianFilter = function(data) {
data = data.sort(function(a, b) { return a - b; });
return data[Math.round(data.length / 2)];
};
MimicWidget.prototype.animationFrame = function() {
var disp = [], i;
this.fr++;
for (i = 1; i <= this.numberLevels; i++)
{
disp[i - 1] = this.amp[i] * Math.sin(this.w * MimicWidget.ANIMATE_PERIOD / 1000 * this.fr + this.o[i]);
}
this.drawFrame(disp, this.motor > 0 ? (this.w * MimicWidget.ANIMATE_PERIOD / 1000 * this.fr) : 0);
};
/**
* Animates the mimic.
*
* @param disp displacements of each level in mm
* @param motor motor rotation
*/
MimicWidget.prototype.drawFrame = function(disp, motor) {
/* Store the current transformation matrix. */
this.ctx.save();
/* Use the identity matrix while clearing the canvas to fix I.E not clearing. */
this.ctx.setTransform(1, 0, 0, 1, 0, 0);
this.ctx.clearRect(0, 0, this.width, this.height);
/* Restore the transform. */
this.ctx.restore();
this.drawTrackCarriageMotor(disp[0], motor);
var l, xVert = [], yVert = [];
/* Levels. */
for (l = 0; l < this.numberLevels; l++)
{
xVert.push(this.cx - this.px(this.model.levelWidth / 2 + disp[l]));
yVert.push(this.height - this.px(this.model.trackHeight + this.model.carHeight) -
this.px(this.model.levelHeight * (l + 1)) - this.px(this.model.wallHeight * l));
/* Coil. */
if (l > 0) this.drawCoil(yVert[l] + this.px(this.model.levelHeight / 2), this.coils[l - 1]);
/* Mass. */
this.drawLevel(xVert[l], yVert[l], l);
}
/* Arm vertices. */
for (l = 0; l < xVert.length - 1; l++)
{
this.drawVertex(xVert[l], yVert[l], xVert[l + 1], yVert[l + 1] + this.px(this.model.levelHeight));
this.drawVertex(xVert[l] + this.px(this.model.levelWidth), yVert[l],
xVert[l + 1] + this.px(this.model.levelWidth), yVert[l + 1] + this.px(this.model.levelHeight));
}
this.drawGrid();
};
/** The widget of the coil box in mm. */
MimicWidget.COIL_BOX_WIDTH = 26;
/**
* Draws a coil.
*
* @param y the vertical position of coil
* @param pw coil power
*/
MimicWidget.prototype.drawCoil = function(y, pw) {
var gx = this.width - this.px(20), gy;
this.ctx.strokeStyle = "#888888";
this.ctx.lineWidth = 1;
this.ctx.beginPath();
this.ctx.moveTo(this.cx, y);
this.ctx.lineTo(gx, y);
this.ctx.moveTo(gx, y - this.px(this.model.levelHeight) / 2);
this.ctx.lineTo(gx, y + this.px(this.model.levelHeight / 2));
for (gy = y - this.px(this.model.levelHeight) / 2;
gy <= y + this.px(this.model.levelHeight) / 2; gy += this.px(this.model.levelHeight) / 4)
{
this.ctx.moveTo(gx, gy);
this.ctx.lineTo(this.width, gy + this.px(5));
}
this.ctx.stroke();
this.ctx.fillStyle = pw === undefined ? "#CCCCCC" : pw > 0 ? "#50C878" : "#ED2939";
this.ctx.fillRect(this.width - this.px(55), y - this.px(MimicWidget.COIL_BOX_WIDTH / 2),
this.px(MimicWidget.COIL_BOX_WIDTH), this.px(MimicWidget.COIL_BOX_WIDTH));
this.ctx.strokeRect(this.width - this.px(55), y - this.px(MimicWidget.COIL_BOX_WIDTH / 2),
this.px(MimicWidget.COIL_BOX_WIDTH), this.px(MimicWidget.COIL_BOX_WIDTH));
this.ctx.fillStyle = "#000000";
this.ctx.font = this.px(13) + "px sans-serif";
this.ctx.textAlign = "center";
this.ctx.textBaseline = "middle";
this.ctx.fillText("C", this.width - this.px(30) - this.px(MimicWidget.COIL_BOX_WIDTH / 2), y);
};
MimicWidget.prototype.drawVertex = function(x0, y0, x1, y1) {
this.ctx.strokeStyle = "#333333";
this.ctx.lineWidth = 2;
this.ctx.beginPath();
this.ctx.moveTo(x0, y0);
this.ctx.lineTo(x1, y1);
this.ctx.stroke();
};
/**
* Draws a level box from the top left position.
*
* @param x x coordinate
* @param y y coordinate
* @param l level number
*/
MimicWidget.prototype.drawLevel = function(x, y, l) {
this.ctx.fillStyle = "#548DD4";
this.ctx.fillRect(x, y, this.px(this.model.levelWidth), this.px(this.model.levelHeight));
this.ctx.strokeStyle = "#333333";
this.ctx.lineWidth = 1.5;
this.ctx.strokeRect(x, y, this.px(this.model.levelWidth), this.px(this.model.levelHeight));
if (l > 0)
{
this.ctx.fillStyle = "#000000";
this.ctx.font = this.px(13) + "px sans-serif";
this.ctx.textAlign = "center";
this.ctx.textBaseline = "middle";
this.ctx.fillText("M" + l, x + this.px(this.model.levelWidth) / 2, y + this.px(this.model.levelHeight / 2));
}
};
/**
* Draws the track, carriage and motor.
*
* @param d0 displacement of base level
* @param motor motor rotation
*/
MimicWidget.prototype.drawTrackCarriageMotor = function(d0, motor) {
var tx = this.cx - this.px(this.model.trackWidth / 2),
ty = this.height - this.px(this.model.trackHeight),
mx, my, mr;
/* Track. */
this.ctx.fillStyle = "#AAAAAA";
this.ctx.fillRect(tx, ty, this.px(this.model.trackWidth), this.px(this.model.trackHeight));
this.ctx.strokeStyle = "#333333";
this.ctx.lineWidth = 1;
this.ctx.strokeRect(tx, ty, this.px(this.model.trackWidth), this.px(this.model.trackHeight));
this.ctx.beginPath();
this.ctx.moveTo(tx, ty + this.px(this.model.trackHeight) / 2 - 1);
this.ctx.lineTo(tx + this.px(this.model.trackWidth), ty + this.px(this.model.trackHeight) / 2 - 1);
this.ctx.lineWidth = 2;
this.ctx.stroke();
/* Carriage. */
this.ctx.fillStyle = "#666666";
this.ctx.fillRect(this.cx - this.px(this.model.levelWidth / 4 + 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20));
this.ctx.fillRect(this.cx + this.px(this.model.levelWidth / 4 - 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20));
this.ctx.strokeStyle = "#222222";
this.ctx.strokeRect(this.cx - this.px(this.model.levelWidth / 4 + 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20));
this.ctx.strokeRect(this.cx + this.px(this.model.levelWidth / 4 - 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20));
mx = this.px(40);
my = this.height - this.px(44);
mr = this.px(20);
/* Arm. */
this.ctx.beginPath();
this.ctx.moveTo(mx - this.px(8 + d0), my - this.px(15));
this.ctx.lineTo(mx + this.px(8 - d0), my - this.px(15));
this.ctx.lineTo(mx + this.px(8 - d0), my - this.px(5));
this.ctx.lineTo(this.cx, my - this.px(5));
this.ctx.lineTo(this.cx, my + this.px(5));
this.ctx.lineTo(mx + this.px(8 - d0), my + this.px(5));
this.ctx.lineTo(mx + this.px(8 - d0), my + this.px(15));
this.ctx.lineTo(mx - this.px(8 + d0), my + this.px(15));
this.ctx.closePath();
this.ctx.fillStyle = "#AAAAAA";
this.ctx.fill();
this.ctx.clearRect(mx - this.px(2.5 + d0), my - this.px(9), this.px(5), this.px(18));
this.ctx.strokeStyle = "#333333";
this.ctx.stroke();
this.ctx.strokeRect(mx - this.px(2.5 + d0), my - this.px(9), this.px(5), this.px(18));
/* Motor. */
this.ctx.save();
this.ctx.globalCompositeOperation = "destination-over";
/* Couple between the motor and the arm. */
this.ctx.beginPath();
this.ctx.arc(mx, my - this.px(d0), this.px(4), 0, 2 * Math.PI);
this.ctx.fillStyle = "#222222";
this.ctx.fill();
this.ctx.beginPath();
this.ctx.arc(mx, my, mr, -Math.PI / 18 + motor, Math.PI / 18 + motor, false);
this.ctx.arc(mx, my, mr, Math.PI - Math.PI / 18 + motor, Math.PI + Math.PI / 18 + motor, false);
this.ctx.closePath();
this.ctx.strokeStyle = "#333333";
this.ctx.stroke();
this.ctx.fillStyle = "#999999";
this.ctx.fill();
this.ctx.beginPath();
this.ctx.arc(mx, my, mr, 0, 2 * Math.PI);
this.ctx.fillStyle = "#666666";
this.ctx.fill();
this.ctx.strokeStyle = "#333333";
this.ctx.stroke();
this.ctx.restore();
};
MimicWidget.GRID_WIDTH = 50;
/**
* Draws a grid.
*/
MimicWidget.prototype.drawGrid = function() {
var d, dt = this.px(MimicWidget.GRID_WIDTH);
this.ctx.save();
this.ctx.globalCompositeOperation = "destination-over";
/* Grid lines. */
this.ctx.beginPath();
for (d = this.cx - dt; d > 0; d -= dt) this.stippleLine(d, 0, d, this.height);
for (d = this.cx + dt; d < this.width - dt; d+= dt) this.stippleLine(d, 0, d, this.height);
for (d = dt; d < this.height; d += dt) this.stippleLine(0, d, this.width, d);
this.ctx.strokeStyle = "#AAAAAA";
this.ctx.lineWidth = 1;
this.ctx.stroke();
/* Units. */
this.ctx.beginPath();
this.ctx.moveTo(this.px(22), 0);
this.ctx.lineTo(this.px(22), dt);
this.ctx.moveTo(this.px(10), this.px(10));
this.ctx.lineTo(dt + this.px(10), this.px(10));
this.ctx.strokeStyle = "#555555";
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.moveTo(this.px(22), 0);
this.ctx.lineTo(this.px(22 + 2.5), this.px(5));
this.ctx.lineTo(this.px(22 - 2.5), this.px(5));
this.ctx.closePath();
this.ctx.fillStyle = "#555555";
this.ctx.fill();
this.ctx.beginPath();
this.ctx.moveTo(this.px(22), dt);
this.ctx.lineTo(this.px(22 + 2.5), dt - this.px(5));
this.ctx.lineTo(this.px(22 - 2.5), dt - this.px(5));
this.ctx.closePath();
this.ctx.fill();
this.ctx.beginPath();
this.ctx.moveTo(this.px(10), this.px(10));
this.ctx.lineTo(this.px(15), this.px(7.5));
this.ctx.lineTo(this.px(15), this.px(12.5));
this.ctx.closePath();
this.ctx.fill();
this.ctx.beginPath();
this.ctx.moveTo(this.px(10) + dt, this.px(10));
this.ctx.lineTo(this.px(5) + dt, this.px(7.5));
this.ctx.lineTo(this.px(5) + dt, this.px(12.5));
this.ctx.closePath();
this.ctx.fill();
this.ctx.font = this.px(10) + "px sans-serif";
this.ctx.fillText(MimicWidget.GRID_WIDTH + "mm", this.px(40), this.px(20));
/* Center line. */
this.ctx.beginPath();
this.ctx.moveTo(this.cx, 0);
this.ctx.lineTo(this.cx, this.height);
this.ctx.moveTo(0, this.height / 2);
this.ctx.strokeStyle = "#555555";
this.ctx.lineWidth = 1.5;
this.ctx.stroke();
this.ctx.restore();
};
MimicWidget.STIPPLE_WIDTH = 10;
/**
* Draws a stippled line.
*
* @param x0 begin x coordinate
* @param y0 begin y coordinate
* @param x1 end x coordinate
* @param y1 end y coordinate
*/
MimicWidget.prototype.stippleLine = function(x0, y0, x1, y1) {
var p;
if (x0 == x1) // Horizontal line
{
p = y0 - MimicWidget.STIPPLE_WIDTH;
while (p < y1)
{
this.ctx.moveTo(x0, p += MimicWidget.STIPPLE_WIDTH);
this.ctx.lineTo(x0, p += MimicWidget.STIPPLE_WIDTH);
}
}
else if (y0 == y1) // Vertical line
{
p = x0 - MimicWidget.STIPPLE_WIDTH;
while (p < x1)
{
this.ctx.moveTo(p += MimicWidget.STIPPLE_WIDTH, y0);
this.ctx.lineTo(p += MimicWidget.STIPPLE_WIDTH, y0);
}
}
else // Diagonal
{
throw "Diagonal lines not implemented.";
}
};
/**
* Converts a pixel dimension to a millimetre dimension.
*
* @param px pixel dimension
* @return millimetre dimension
*/
MimicWidget.prototype.mm = function(px) {
return px * this.mmPerPx;
};
/**
* Converts a millimetre dimension to a pixel dimension.
*
* @param mm millimetre dimension
* @return pixel dimension
*/
MimicWidget.prototype.px = function(mm) {
return mm / this.mmPerPx;
};
MimicWidget.prototype.resized = function(width, height) {
if (this.animateInterval)
{
clearInterval(this.animateInterval);
this.animateInterval = undefined;
}
height -= 63;
this.$widget.find("canvas").attr({
width: width,
height: height
});
this.ctx.fillStyle = "#FAFAFA";
this.ctx.fillRect(0, 0, width, height);
};
MimicWidget.prototype.resizeStopped = function(width, height) {
this.mmPerPx *= this.boxWidth / width;
this.width = this.px(this.model.levelWidth + this.model.maxDisp * 2) + this.px(100);
this.cx = this.width / 2;
this.height = this.px(this.model.levelHeight * (this.is3DOF ? 4 : 3) +
this.model.wallHeight * (this.is3DOF ? 3: 2) + this.model.trackHeight + this.model.carHeight);
this.boxWidth = width;
this.$widget.find("canvas").attr({
width: this.width,
height: this.height
});
this.$widget.css("height", "auto");
if (!this.animateInterval)
{
var thiz = this;
this.animateInterval = setInterval(function() { thiz.animationFrame(); }, MimicWidget.ANIMATE_PERIOD);
}
};
MimicWidget.prototype.destroy = function() {
clearInterval(this.animateInterval);
this.animateInterval = undefined;
Widget.prototype.destroy.call(this);
};
/**
* Displays an FFT of one or more signals.
*
* @constructor
* @param {string} id graph identifier
* @param {object} config configuration object
* @config {object} [fields] map of graphed data fields with field => label
* @config {object} [colors] map of graph trace colors with field => color (optional)
* @config {boolean} [autoScale] whether to autoscale the graph dependant (default off)
* @config {integer} [minValue] minimum value that is graphed, implies not autoscaling (default 0)
* @config {integer} [maxValue] maximum value that is graphed, implies not autoscaling (default 100)
* @config {integer} [duration] number of seconds this graph displays (default 60)
* @config {integer} [period] period betweeen samples in milliseconds (default 100)
* @config {string} [xLabel] X axis label (default (Time (s))
* @config {String} [yLabel] Y axis label (optional)
* @config {boolean} [traceLabels] whether to show trace labels (default true)
* @config {boolean} [fieldCtl] whether data field displays can be toggled (default false)
* @config {boolean} [autoCtl] whether autoscaling enable control is shown (default false)
* @config {boolean} [durationCtl] whether duration control slider is displayed
* @config {integer} [vertScales] number of vertical scales (default 5)
* @config {integer} [horizScales] number of horizontal scales (default 8)
*/
function FFTGraph(id, config)
{
Graph.call(this, id, config);
}
FFTGraph.prototype = new Graph;
FFTGraph.prototype.consume = function(data) {
/* Not stopping updates when controls are showing , causes ugly blinking. */
if (this.showingControls) return;
var i = 0;
if (this.startTime == undefined)
{
this.startTime = data.start;
this._updateIndependentScale();
}
this.latestTime = data.time;
for (i in this.dataFields)
{
if (data[i] === undefined) continue;
this.dataFields[i].values = this.fftTransform(
this._pruneSample(data[i], this.config.duration * 1000 / this.config.period));
this.dataFields[i].seconds = this.dataFields[i].values.length * this.config.period / 1000;
this.displayedDuration = data.duration;
}
if (this.config.autoScale)
{
/* Determine graph scaling for this frame and label it. */
this._adjustScaling();
this._updateDependantScale();
}
this._drawFrame();
};
FFTGraph.prototype._updateIndependentScale = function() {
var i, $d = this.$widget.find(".graph-bottom-scale-0"), t;
for (i = 0; i <= this.config.horizScales; i++)
{
t = 1000 * i / this.config.period / this.config.horizScales / 20;
$d.html(Util.zeroPad(t, 1));
$d = $d.next();
}
};
/**
* Pads the length of the array with 0 until its length is a multiple of 2.
*
* @param {Array} arr array to pad
* @return {Array} padded arary (same as input)
*/
FFTGraph.prototype.fftTransform = function(sample) {
var i, n = sample.length, vals = new Array(n);
/* The FFT is computed on complex numbers. */
for (i = 0; i < n; i++)
{
vals[i] = new Complex(sample[i], 0);
}
/* The Cooley-Turkey algorithm operates on samples whose length is a
* multiple of 2. */
while (((n = vals.length) & (n - 1)) != 0)
{
vals.push(new Complex(0, 0));
}
/** Apply the FFT transform. */
vals = fft(vals);
/* We only care about the first 10 Hz. */
vals.splice(n / 20 - 1, n - n / 20);
/* The plot is of the absolute values of the sample, then scaled . */
for (i = 0; i < vals.length; i++)
{
vals[i] = vals[i].abs() * 2 / n;
}
return vals;
};
| jeking3/web-interface | public/uts/shaketable/shaketable.js | JavaScript | bsd-3-clause | 37,584 |
/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file FlightTaskFailsafe.hpp
*
*/
#pragma once
#include "FlightTask.hpp"
class FlightTaskFailsafe : public FlightTask
{
public:
FlightTaskFailsafe() = default;
virtual ~FlightTaskFailsafe() = default;
bool update() override;
bool activate() override;
private:
DEFINE_PARAMETERS_CUSTOM_PARENT(FlightTask,
(ParamFloat<px4::params::MPC_LAND_SPEED>) MPC_LAND_SPEED,
(ParamFloat<px4::params::MPC_THR_HOVER>) MPC_THR_HOVER /**< throttle value at which vehicle is at hover equilibrium */
)
};
| Aerotenna/Firmware | src/lib/FlightTasks/tasks/Failsafe/FlightTaskFailsafe.hpp | C++ | bsd-3-clause | 2,259 |
package transfer.test;
import transfer.TypeReference;
import java.util.Map;
/**
* Created by Jake on 2015/3/7.
*/
public class TestType {
public static void main(String[] args) {
System.out.println(new TypeReference<Entity>(){}.getType() == new TypeReference<Entity>(){}.getType());
System.out.println(new TypeReference<Map<String,Entity>>(){}.getType() == new TypeReference<Map<String,Entity>>(){}.getType());
System.out.println(new TypeReference<Map<String,Entity>>(){}.getType().hashCode());
System.out.println(new TypeReference<Map<String,Entity>>(){}.getType().hashCode());
System.out.println(System.identityHashCode(new TypeReference<Map<String,Entity>>(){}.getType()));
System.out.println(System.identityHashCode(new TypeReference<Map<String,Entity>>(){}.getType()));
}
}
| Jakegogo/concurrent | concur/src-transfer/transfer/test/TestType.java | Java | bsd-3-clause | 867 |
/*
* Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider,
* Jérémie Comarmond, Didier Colin.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Core/Logger.h>
#include <Renderer/Common/Texture.h>
#include <Renderer/Common/Tools.h>
#include <Renderer/SM2/FreeFormRenderer.h>
#include <algorithm>
namespace Renderer
{
//-----------------------------------------------------------------------------
FreeFormRenderer::FreeFormRenderer(const Ptr<Gfx::IDevice> & pDevice, const Ptr<ShaderLib> & pShaderLib, const Ptr<GPUResourceLib> & pResLib,
const Ptr<TextureMap> & pDefaultTex,
const RendererSettings & settings) :
_pDevice(pDevice),
_pShaderLib(pShaderLib),
_pResLib(pResLib),
_pDefaultTex(pDefaultTex),
_settings(settings)
{
_pResLib->registerResource(this);
}
//-----------------------------------------------------------------------------
FreeFormRenderer::~FreeFormRenderer()
{
_pResLib->unregisterResource(this);
}
//-----------------------------------------------------------------------------
bool FreeFormRenderer::initialise()
{
bool result = true;
int32 iMode = 0;
int32 iFlag = 0;
try
{
for(iMode=0; iMode < EFreeFormMode_COUNT; iMode++)
for(iFlag=0; iFlag < FLAG_COUNT; iFlag++)
initialise(_params[iMode][iFlag], EFreeFormMode(iMode), iFlag);
}
catch(Core::Exception & exception)
{
ERR << L"Error initializing FreeFormRenderer : '" << exception.getMessage() << L"' ("
<< Renderer::toString(EFreeFormMode(iMode))
<< L" 0x" << Core::toStringHex(iFlag) << L")\n";
result = false;
}
return result;
}
//-----------------------------------------------------------------------------
void FreeFormRenderer::onDeviceLost()
{
}
//-----------------------------------------------------------------------------
void FreeFormRenderer::onDeviceReset()
{
}
//-----------------------------------------------------------------------------
void FreeFormRenderer::initialise(ShaderParams & params, EFreeFormMode mode, int32 flags)
{
// Shaders
Core::List<Gfx::ShaderMacro> macros;
if(mode == FREE_FORM_REFRAC)
macros.push_back(Gfx::ShaderMacro(L"REFRACTION_FLAG", L"1"));
if(flags & NORMAL_MAP_DXT5_FLAG)
macros.push_back(Gfx::ShaderMacro(L"NORMAL_MAP_DXT5_FLAG", L"1"));
if(flags & GLOW_FLAG)
macros.push_back(Gfx::ShaderMacro(L"GLOW_FLAG", L"1"));
if(flags & LIGHT_FLAG)
macros.push_back(Gfx::ShaderMacro(L"LIGHT_FLAG", L"1"));
if(flags & WORLD_SPACE_FLAG)
macros.push_back(Gfx::ShaderMacro(L"WORLD_SPACE_FLAG", L"1"));
params.pVShader = _pShaderLib->getVShader(L"FreeForm.vsh", Gfx::VS_V1_1, L"vs_main", macros);
params.pPShader = _pShaderLib->getPShader(L"FreeForm.psh", Gfx::PS_V2_0, L"ps_main", macros);
params.pVConst = params.pVShader->getConstantTable();
params.pPConst = params.pPShader->getConstantTable();
params.idWorldViewProj = params.pVConst->getConstantIndexIfExists(L"WorldViewProj");
params.idWorldView = params.pVConst->getConstantIndexIfExists(L"WorldView");
params.idEyePos = params.pVConst->getConstantIndexIfExists(L"EyePos");
params.idFogRange = params.pVConst->getConstantIndexIfExists(L"FogRange");
params.idMainLightDir = params.pVConst->getConstantIndexIfExists(L"MainLightDir");
params.idSamplerColor = params.pPConst->getConstantIndexIfExists(L"SamplerColor");
params.idSamplerNormal = params.pPConst->getConstantIndexIfExists(L"SamplerNormal");
params.idSamplerRefraction = params.pPConst->getConstantIndexIfExists(L"SamplerRefraction");
params.idRefrScale = params.pPConst->getConstantIndexIfExists(L"RefrScale");
// Format
Gfx::VertexFormatDesc formatDesc;
formatDesc.addAttribut(0, Gfx::VAT_FLOAT3, Gfx::VAU_POSITION);
formatDesc.addAttribut(0, Gfx::VAT_COLOR, Gfx::VAU_COLOR);
formatDesc.addAttribut(0, Gfx::VAT_FLOAT3, Gfx::VAU_TEXTURE_COORD, 0); // texcoord
formatDesc.addAttribut(0, Gfx::VAT_COLOR, Gfx::VAU_TEXTURE_COORD, 1); // glow
params.pFormat = _pDevice->createVertexFormat(formatDesc, params.pVShader);
// State
Gfx::RSRasterizerDesc raster(Gfx::CM_NOCM, true, Gfx::FM_SOLID);
Gfx::RSRasterizerDesc rasterLIGHT(Gfx::CM_BACK, true, Gfx::FM_SOLID);
Gfx::RSDepthStencilDesc depthLIGHT(true, true, Gfx::COMPARISON_LESS_EQUAL);
Gfx::RSDepthStencilDesc depth(true, false, Gfx::COMPARISON_LESS_EQUAL);
Gfx::RSBlendDesc blendADD(Gfx::BM_SRC_ALPHA, Gfx::BO_ADD, Gfx::BM_ONE);
Gfx::RSBlendDesc blendLERP(Gfx::BM_SRC_ALPHA, Gfx::BO_ADD, Gfx::BM_INVERT_SRC_ALPHA);
Gfx::RSBlendDesc blendREFRAC;
Gfx::RSBlendDesc blendLIGHT;
Gfx::RSSamplerDesc samplerColor(Gfx::TEXTURE_ADDRESS_WRAP);
Gfx::RSSamplerDesc samplerNormal(Gfx::TEXTURE_ADDRESS_CLAMP);
setSampler(samplerColor, _settings.filterLevel);
setSampler(samplerNormal, _settings.filterLevel);
blendADD.sRGBWriteEnabled = true;
blendLERP.sRGBWriteEnabled = true;
blendREFRAC.sRGBWriteEnabled = true;
blendLIGHT.sRGBWriteEnabled = true;
samplerColor.isSRGB = true;
switch(mode)
{
case FREE_FORM_ADD:
LM_ASSERT(params.idSamplerColor != Gfx::UNDEFINED_SHADER_CONST);
params.state = _pDevice->createState(raster, depth, blendADD);
params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerColor)] = _pDevice->createState(samplerColor);
break;
case FREE_FORM_LERP:
LM_ASSERT(params.idSamplerColor != Gfx::UNDEFINED_SHADER_CONST);
params.state = _pDevice->createState(raster, depth, blendLERP);
params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerColor)] = _pDevice->createState(samplerColor);
break;
case FREE_FORM_REFRAC:
LM_ASSERT(params.idSamplerNormal != Gfx::UNDEFINED_SHADER_CONST);
LM_ASSERT(params.idSamplerRefraction != Gfx::UNDEFINED_SHADER_CONST);
params.state = _pDevice->createState(raster, depth, blendREFRAC);
params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerNormal)] = _pDevice->createState(samplerNormal);
params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerRefraction)] = _pDevice->createState(samplerColor);
break;
case FREE_FORM_LIGHT_MESH:
LM_ASSERT(params.idSamplerColor != Gfx::UNDEFINED_SHADER_CONST);
params.state = _pDevice->createState(rasterLIGHT, depthLIGHT, blendLIGHT);
params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerColor)] = _pDevice->createState(samplerColor);
break;
}
}
//-----------------------------------------------------------------------------
void FreeFormRenderer::bind(const ShaderParams & params, const FreeForm & freeForm)
{
_pDevice->setState(params.state);
_pDevice->setVertexFormat(params.pFormat);
_pDevice->setVertexShader(params.pVShader);
_pDevice->setPixelShader(params.pPShader);
Core::Matrix4f world;
freeForm.getWorldMatrix(world);
Core::Matrix4f worldView(_view * world);
Core::Matrix4f worldViewProj(_viewProj * world);
Core::Vector3f fogRange(_fogSettings.getStart(), _fogSettings.getInvRange(), _fogSettings.getColor().a);
if(freeForm.isWorldSpaceCoords())
fogRange.x = _fogSettings.getEnd() + _eye.z;
params.pVConst->setConstantSafe(params.idFogRange, fogRange);
params.pVConst->setConstantSafe(params.idEyePos, _eye);
params.pVConst->setConstantSafe(params.idWorldViewProj, worldViewProj);
params.pVConst->setConstantSafe(params.idWorldView, worldView);
params.pVConst->setConstantSafe(params.idMainLightDir, -_lightSettings.getDirection());
if(params.idSamplerColor != Gfx::UNDEFINED_SHADER_CONST)
{
if(freeForm.getTexture() != null)
params.pPConst->setSampler2D(params.idSamplerColor, LM_DEBUG_PTR_CAST<TextureMap>(freeForm.getTexture())->getResource());
else
params.pPConst->setSampler2D(params.idSamplerColor, _pDefaultTex->getResource());
}
if(params.idSamplerNormal != Gfx::UNDEFINED_SHADER_CONST)
{
params.pPConst->setSampler2D(params.idSamplerNormal, LM_DEBUG_PTR_CAST<TextureMap>(freeForm.getTexture())->getResource());
}
if(params.idSamplerRefraction != Gfx::UNDEFINED_SHADER_CONST)
{
params.pPConst->setSampler2D(params.idSamplerRefraction, _pRenderTarget->getShaderTextureView(RT_REFRACTION_BUFFER));
}
}
//-----------------------------------------------------------------------------
void FreeFormRenderer::startContext(const RenderContext & context, ERenderPass pass)
{
_pass = pass;
_eye = context.getEye();
_view = context.getView();
_proj = context.getProj();
_viewProj = context.getViewProj();
_fogSettings = context.getFog();
_lightSettings = context.getLight();
_pRenderTarget = context.getRenderTarget();
_commands.clear();
const Core::List<FreeForm *> & fforms = context.getFreeForms();
if(pass == PASS_GLOW || pass == PASS_LIGHTING || pass == PASS_REFLECTION)
{
Command command;
command.pass = pass;
command.pExecuter = this;
command.flags = 0;
for(int32 ii=0; ii < fforms.size(); ii++)
{
const FreeForm & fform = *fforms[ii];
if(pass != PASS_GLOW || fform.getGlowFlag())
{
command.mode = (fform.getMode() == FREE_FORM_LIGHT_MESH) ? CMD_SOLID : CMD_TRANS;
command.camDist = Core::dot(fform.getBoundingBox().getCenter() - context.getEye(), context.getEyeDir());
command.pExecData = (void*)&fform;
_commands.push_back(command);
}
}
}
}
//-----------------------------------------------------------------------------
int32 FreeFormRenderer::getFlags(const FreeForm & freeForm) const
{
int32 flags = 0;
if(freeForm.getMode() == FREE_FORM_LIGHT_MESH)
flags |= LIGHT_FLAG;
if(freeForm.getTexture() != null && freeForm.getTexture()->getSourceTexture()->getFormat() == Assets::TEX_FORMAT_DXTC5)
flags |= NORMAL_MAP_DXT5_FLAG;
if(freeForm.isWorldSpaceCoords())
flags |= WORLD_SPACE_FLAG;
return flags;
}
//-----------------------------------------------------------------------------
void FreeFormRenderer::endContext()
{
}
//-----------------------------------------------------------------------------
void FreeFormRenderer::enqueueCommands(Core::List<Command> & commands)
{
commands.insert(commands.end(), _commands.begin(), _commands.end());
}
//-----------------------------------------------------------------------------
void FreeFormRenderer::exec(Command * pStart, Command * pEnd)
{
while(pStart != pEnd)
{
const FreeForm & freeForm = *(FreeForm*)pStart->pExecData;
switch(_pass)
{
case PASS_LIGHTING:
case PASS_REFLECTION:
{
bind(_params[int32(freeForm.getMode())][getFlags(freeForm)], freeForm);
break;
}
case PASS_GLOW:
{
bind(_params[int32(FREE_FORM_ADD)][getFlags(freeForm) + GLOW_FLAG], freeForm);
break;
}
}
freeForm.sendData();
pStart++;
}
}
//-----------------------------------------------------------------------------
}
| benkaraban/anima-games-engine | Sources/Modules/Renderer/SM2/FreeFormRenderer.cpp | C++ | bsd-3-clause | 13,312 |
from smtplib import SMTPException
from django.conf import settings
from django.core.mail import send_mail
from django.views.decorators.http import require_GET
from django.shortcuts import redirect
from django.template.loader import render_to_string
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.utils import timezone
@login_required
def send_account_verification(request):
"""
* if already verified => returns message: info: verification already completed
* if unverified =>
* if no verification code: set it and save UserDetails
* send the verification email and returns message: info: email sent, please check
"""
userdetails = request.user.userdetails
if userdetails.verification_completed:
messages.info(request, "Your email address is already verified.")
else:
userdetails.reset_verification()
code = userdetails.verification_code
subject = 'Mind My Health Email Verification'
domain = request.get_host()
try:
send_mail(
subject,
render_to_string(
'myhpom/accounts/verification_email.txt',
context={
'code': code,
'domain': domain
},
request=request,
),
settings.DEFAULT_FROM_EMAIL,
[request.user.email],
fail_silently=False,
)
messages.info(request, "Please check your email to verify your address.")
except SMTPException:
messages.error(
request, "The verification email could not be sent. Please try again later."
)
userdetails.save()
return redirect('myhpom:dashboard')
@require_GET
@login_required
def verify_account(request, code):
"""This URL is usually accessed from an email. Login will redirect here if needed.
* if already verified => returns message: success: verification already completed
* if not verified: Check the given code against the user's verification code
* if match:
* set verification_completed as now and save UserDetails
* message: success: email verified
* if not match:
* message: invalid: the verification code is invalid.
"""
userdetails = request.user.userdetails
if userdetails.verification_completed:
messages.info(request, "Your email address is already verified.")
else:
if code == userdetails.verification_code:
userdetails.verification_completed = timezone.now()
userdetails.save()
messages.success(request, "Your email address is now verified.")
else:
messages.error(request, "The verification code is invalid.")
return redirect('myhpom:dashboard')
| ResearchSoftwareInstitute/MyHPOM | myhpom/views/verification.py | Python | bsd-3-clause | 2,927 |
#include <leveldb/db.h>
#include <string>
#include <iostream>
using namespace std;
using namespace leveldb;
int main( int argc, char* argv[])
{
DB* db;
Options options;
options.create_if_missing = true;
if( argc < 2 )
return 0;
char delim;
if( argc == 3 )
delim = argv[2][0];
else
delim = '\t';
leveldb::Status status = leveldb::DB::Open(options, argv[1], &db);
string line;
int n=0;
while( getline(cin, line))
{
size_t i=line.find(delim);
if( i == string::npos )
continue;
db->Put(leveldb::WriteOptions(), line.substr(0, i), line.substr(i+1));
++n;
if( ( n & 0xFFFF ) == 0 )
cout << n << endl;
}
return 0;
}
| nonego/ldb | qq/testwrite.cpp | C++ | bsd-3-clause | 761 |
# -*- coding: utf-8 -*-
#
# django cms documentation build configuration file, created by
# sphinx-quickstart on Tue Sep 15 10:47:03 2009.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out serve
# to show the default.
import os
import sys
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it absolute,
# like shown here.
sys.path.append(os.path.abspath('.'))
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
#extensions = ['sphinx.ext.autodoc']
extensions = ['djangocms', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.autodoc']
intersphinx_mapping = {
'python': ('http://docs.python.org/3/', None),
'django': ('https://docs.djangoproject.com/en/1.10/', 'https://docs.djangoproject.com/en/1.10/_objects/'),
'classytags': ('http://readthedocs.org/docs/django-classy-tags/en/latest/', None),
'sekizai': ('http://readthedocs.org/docs/django-sekizai/en/latest/', None),
'treebeard': ('http://django-treebeard.readthedocs.io/en/latest/', None),
}
# Add any paths that contain templates here, relative to this directory.
# templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'django cms'
copyright = u'2009-2017, Divio AG and contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
path = os.path.split(os.path.dirname(__file__))[0]
path = os.path.split(path)[0]
sys.path.insert(0, path)
import cms
version = cms.__version__
# The full version, including alpha/beta/rc tags.
release = cms.__version__
# The language for content autogenerated by Sphinx. Refer to documentation for
# a list of supported languages.
language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['build', 'env']
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be
# searched for source files.
exclude_trees = ['build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description unit
# titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
todo_include_todos = True
# -- Options for HTML output ---------------------------------------------------
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
try:
import divio_docs_theme
html_theme = 'divio_docs_theme'
html_theme_path = [divio_docs_theme.get_html_theme_path()]
except:
html_theme = 'default'
show_cloud_banner = True
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'djangocmsdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
latex_paper_size = 'a4'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'djangocms.tex', u'django cms Documentation',
u'Divio AG and contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top
# of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# -- Options for LaTeX output --------------------------------------------------
# Spelling check needs an additional module that is not installed by default.
# Add it only if spelling check is requested so docs can be generated without it.
# temporarily disabled because of an issue on RTD. see docs/requirements.txt
# if 'spelling' in sys.argv:
# extensions.append("sphinxcontrib.spelling")
# Spelling language.
spelling_lang = 'en_GB'
# Location of word list.
spelling_word_list_filename = 'spelling_wordlist'
spelling_ignore_pypi_package_names = True
| czpython/django-cms | docs/conf.py | Python | bsd-3-clause | 8,185 |
require 'rubygems'
require 'google_chart'
# http://badpopcorn.com/blog/2008/09/08/rails-google-charts-gchartrb/
class WorkloadsController < ApplicationController
layout 'pdc'
def index
person_id = params[:person_id]
project_ids = params[:project_ids]
iterations_ids = params[:iterations_ids]
tags_ids = params[:person_tags_ids]
session['workload_person_id'] = person_id if person_id
session['workload_person_id'] = current_user.id if not session['workload_person_id']
session['workload_person_id'] = params[:wl_person] if params[:wl_person]
if project_ids
if project_ids.class==Array
session['workload_person_project_ids'] = project_ids # array of strings
else
session['workload_person_project_ids'] = [project_ids] # array with one string
end
else
session['workload_person_project_ids'] = []
end
session['workload_persons_iterations'] = []
if iterations_ids
iterations_ids.each do |i|
iteration = Iteration.find(i)
iteration_name = iteration.name
project_code = iteration.project_code
project_id = iteration.project.id
session['workload_persons_iterations'] << {:name=>iteration_name, :project_code=>project_code, :project_id=>project_id}
end
end
session['workload_person_tags'] = []
if tags_ids
if tags_ids.class==Array
session['workload_person_tags'] = tags_ids # array of strings
else
session['workload_person_tags'] = [tags_ids] # array with one string
end
end
@people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0", :order=>"name").map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]}
@projects = Project.find(:all).map {|p| ["#{p.name} (#{p.wl_lines.size} persons)", p.id]}
change_workload(session['workload_person_id'])
end
def change_workload(person_id=nil)
person_id = params[:person_id] if !person_id
session['workload_person_id'] = person_id
@workload = Workload.new(person_id,session['workload_person_project_ids'], session['workload_persons_iterations'],session['workload_person_tags'], {:hide_lines_with_no_workload => session['workload_hide_lines_with_no_workload'].to_s=='true', :include_forecast=>true})
@person = @workload.person
get_last_sdp_update
get_suggested_requests(@workload)
get_sdp_tasks(@workload)
get_chart
get_sdp_gain(@workload.person)
get_backup_warnings(@workload.person)
get_holiday_warning(@workload.person)
get_unlinked_sdp_tasks(@workload)
end
def get_last_sdp_update
@last_sdp_phase = SDPPhase.find(:first, :order=>'updated_at desc')
if @last_sdp_phase != nil
@last_sdp_update = @last_sdp_phase.updated_at
else
@last_sdp_update = nil
end
end
def get_chart
chart = GoogleChart::LineChart.new('1000x300', "#{@workload.person.name} workload", false)
serie = @workload.percents.map{ |p| p[:value] }
return if serie.size == 0
realmax = serie.max
high_limit = 150.0
max = realmax > high_limit ? high_limit : realmax
high_limit = high_limit > max ? max : high_limit
chart.data "non capped", serie, '0000ff'
chart.axis :y, :range => [0,max], :font_size => 10, :alignment => :center
chart.axis :x, :labels => @workload.months, :font_size => 10, :alignment => :center
chart.shape_marker :circle, :color=>'3333ff', :data_set_index=>0, :data_point_index=>-1, :pixel_size=>7
serie.each_with_index do |p,index|
if p > high_limit
chart.shape_marker :circle, :color=>'ff3333', :data_set_index=>0, :data_point_index=>index, :pixel_size=>8
end
end
chart.range_marker :horizontal, :color=>'DDDDDD', :start_point=>97.0/max, :end_point=>103.0/max
chart.show_legend = false
@chart_url = chart.to_url({:chd=>"t:#{serie.join(',')}", :chds=>"0,#{high_limit}"})
end
def get_suggested_requests(wl)
if !wl or !wl.person or wl.person.rmt_user == ""
@suggested_requests = []
return
end
request_ids = wl.wl_lines.select {|l| l.request_id != nil}.map { |l| filled_number(l.request_id,7)}
cond = ""
cond = " and request_id not in (#{request_ids.join(',')})" if request_ids.size > 0
@suggested_requests = Request.find(:all, :conditions => "assigned_to='#{wl.person.rmt_user}' and status!='closed' and status!='performed' and status!='cancelled' and status!='removed' and resolution!='ended' #{cond}", :order=>"project_name, summary")
@suggested_requests = @suggested_requests.select { |r| r.sdp_tasks_remaining_sum > 0 }
end
def get_backup_warnings(person_id)
currentWeek = wlweek(Date.today)
nextWeek = wlweek(Date.today+7.days)
backups = WlBackup.find(:all, :conditions=>["backup_person_id = ? and (week = ? or week = ?)", person_id, currentWeek, nextWeek])
@backup_holidays = []
backups.each do |b|
# Load for holyday and concerned user (for the 14 next days)
person_holiday_load = WlLoad.find(:all,
:joins => 'JOIN wl_lines ON wl_lines.id = wl_loads.wl_line_id',
:conditions=>["wl_lines.person_id = ? and wl_lines.wl_type = ? and (wl_loads.week = ? or wl_loads.week = ?)", b.person.id.to_s, WL_LINE_HOLIDAYS, currentWeek, nextWeek])
if person_holiday_load.count > 0
load_total = 0
# Calcul the number of day of holiday. If it's over the threshold, display the warning
person_holiday_load.map { |wload| load_total += wload.wlload }
if (load_total > APP_CONFIG['workload_holiday_threshold_before_backup'])
@backup_holidays << b.person.name if !@backup_holidays.include?(b.person.name)
end
end
end
end
def do_get_sdp_tasks()
person_id = session['workload_person_id']
p = Person.find(person_id)
@sdp_tasks = SDPTask.find(:all, :conditions=>["collab=?", p.trigram], :order=>"title").map{|t| ["[#{t.project_name}] #{ActionController::Base.helpers.sanitize(t.title)} (#{t.remaining})", t.sdp_id]}
render(:partial=>'sdp_task_options')
end
def get_sdp_tasks(wl,options = {})
# if wl.nil?
if wl.person.trigram == ""
@sdp_tasks = []
return
end
task_ids = wl.wl_lines.map{|l| l.sdp_tasks.map{|l| l.sdp_id}}.select{|l| (l != [])}#wl.wl_lines.select {|l| l.sdp_task_id != nil}.map { |l| l.sdp_task_id}
cond = ""
cond = " and sdp_id not in (#{task_ids.join(',')})" if task_ids.size > 0
@sdp_tasks = SDPTask.find(:all, :conditions=>["collab=? and request_id is null #{cond} and remaining > 0", wl.person.trigram], :order=>"title").map{|t| ["[#{t.project_name}] #{ActionController::Base.helpers.sanitize(t.title)} (#{t.assigned})", t.sdp_id]}
# end
end
def get_unlinked_sdp_tasks(wl)
# Directly linked wl<=> sdp
task_ids = wl.wl_lines.map{|l| l.sdp_tasks.map{|l| l.sdp_id}}.select{|l| (l != [])}
cond = " and sdp_id not in (#{task_ids.join(',')})" if task_ids.size > 0
@sdp_tasks_unlinked = SDPTask.find(:all, :conditions => ["collab = ? AND request_id IS NULL #{cond} and remaining > 0", wl.person.trigram])
# By requests
wl_lines_id = wl.wl_lines.map{ |l| l.request_id}
@sdp_tasks_unlinked_req = SDPTask.find(:all, :conditions => ["collab = ? AND request_id IS NOT NULL AND request_id NOT IN (?) and remaining > 0", wl.person.trigram, wl_lines_id])
# Requests not linked and with no remaining
person = Person.find(session['workload_person_id'].to_i)
@requests_to_close = Array.new
reqs = Request.find(:all,
:conditions=>["status='assigned' and resolution!='ended' and resolution!='aborted' and assigned_to = ?", person.rmt_user])
reqs.each { |r|
total_remaining = 0
sdpTaskTemp = SDPTask.find(:all, :conditions=>"request_id='#{r.request_id}'")
sdpTaskTemp.each do |tmp_sdp|
total_remaining += tmp_sdp.remaining
end
if sdpTaskTemp.size > 0 and total_remaining == 0
@requests_to_close << r
end
}
# render :layout => false
end
# Return an array of hash
# Hash : {"holidayObject" => HolidayModel, "needBackup" => BOOL, "hasBackup" => BOOL, "backup_people" => [STRING], "backup_comments" => [STIRNG]}
def get_holiday_warning_detailed(person, dateMax)
holiday_array = Array.new
index = 0
# Get holidays
person_holiday_load = WlLoad.find(:all,
:joins => 'JOIN wl_lines ON wl_lines.id = wl_loads.wl_line_id',
:conditions=>["wl_lines.person_id = ? and wl_lines.wl_type = ? and week >= ? and week < ?", person.id.to_s, WL_LINE_HOLIDAYS, wlweek(Date.today), wlweek(dateMax)],
:order=>"week")
# Each holiday
person_holiday_load.each do |holiday|
backups = WlBackup.find(:all, :conditions=>["person_id = ? and week = ?",person.id.to_s, holiday.week])
# Create hash object
holiday_hash = {"holidayObject" => holiday, "needBackup" => false, "hasBackup" => false, "backup_people" => [], "backup_comments" => []}
# Need backup by week load ?
if holiday.wlload >= APP_CONFIG['workload_holiday_threshold_before_backup'].to_i
holiday_hash["needBackup"] = true
end
# Have backups ?
if backups != nil and backups.size > 0
holiday_hash["hasBackup"] = true
backups.each do |b|
holiday_hash["backup_people"] << b.backup.name
if b.comment != nil and b.comment.length > 0
holiday_hash["backup_comments"] << b.comment
else
holiday_hash["backup_comments"] << ""
end
end
end
# Add hash
holiday_array << holiday_hash
# Check previous and update needBackup if necessary
if (index > 0)
previous_holiday_hash = holiday_array[index-1]
if (wlweek_reverse(previous_holiday_hash["holidayObject"].week) + 1.week) == wlweek_reverse(holiday_hash["holidayObject"].week)
if ((previous_holiday_hash["holidayObject"].wlload.to_i + holiday_hash["holidayObject"].wlload.to_i) >= 4)
if (previous_holiday_hash["holidayObject"].wlload.to_i >= APP_CONFIG['workload_holiday_threshold_before_backup'].to_i) or (holiday_hash["holidayObject"].wlload.to_i >= APP_CONFIG['workload_holiday_threshold_before_backup'].to_i)
previous_holiday_hash["needBackup"] = true
holiday_hash["needBackup"] = true
end
end
end
end
index += 1
end
return holiday_array
end
def get_holiday_warning(person)
@holiday_without_backup = false # Backup button in red if holiday without backup
@holiday_backup_warning = Hash.new # WLload in red if holiday without backup while it should
holiday_array = get_holiday_warning_detailed(person, Date.today+8.weeks)
# Analyze the array of hash - Set
holiday_array.each do |hash|
if hash["needBackup"] == true and hash["hasBackup"] == false
@holiday_without_backup = true
@holiday_backup_warning[hash["holidayObject"].week] = true
else
@holiday_backup_warning[hash["holidayObject"].week] = false
end
end
end
def get_sdp_gain(person)
@balance = person.sdp_balance
@sdp_logs = SdpLog.find(:all, :conditions=>["person_id=?", person.id], :order=>"`date` desc", :limit=>3).reverse
end
def consolidation
@companies = Company.all.map {|p| ["#{p.name}", p.id]}
@projects = Project.all.map {|p| ["#{p.name}", p.id]}
end
def get_people
@company_ids = params['company']
@company_ids = @company_ids['company_ids'] if @company_ids # FIXME: pass only a simple field....
@project_ids = params['project']
@project_ids = @project_ids['project_ids'] if @project_ids # FIXME: pass only a simple field....
if @project_ids and @project_ids != ''
@project_ids = [@project_ids]
else
@project_ids = []
end
cond = ""
cond += " and company_id in (#{@company_ids})" if @company_ids and @company_ids!=''
@people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0 and is_transverse=0" + cond, :order=>"name")
end
def refresh_conso
@start_time = Time.now
# find "to be validated" requests not in the workload
already_in_the_workload = WlLine.all.select{|l| l.request and (l.request.status=='to be validated' or (l.request.status=='assigned' and l.request.resolution!='ended' and l.request.resolution!='aborted'))}.map{|l| l.request}
@not_in_workload = (Request.find(:all,:conditions=>"status='to be validated' or (status='assigned' and resolution!='ended' and resolution!='aborted')") - already_in_the_workload).sort_by{|r| (r.project ? r.project.full_name : "")}
# find the corresponding production days (minus 20% of gain)
@not_in_workload_days = @not_in_workload.inject(0) { |sum, r| sum += r.workload2} * 0.80
get_people
@transverse_people = Person.find(:all, :conditions=>"has_left=0 and is_transverse=1", :order=>"name").map{|p| p.name.split(" ")[0]}.join(", ")
@workloads = []
@total_days = 0
@total_planned_days = 0
@to_be_validated_in_wl_remaining_total = 0
for p in @people
next if not p.has_workload_for_projects?(@project_ids)
w = Workload.new(p.id,[],'','', {:add_holidays=>true})
next if w.wl_lines.select{|l| l.wl_type != WL_LINE_HOLIDAYS}.size == 0 # do not display people with no lines at all
@workloads << w
@total_days += w.line_sums.inject(0) { |sum, (k,v)|
sum += v[:remaining] == '' ? 0 : v[:remaining]
}
@total_planned_days += w.planned_total
@to_be_validated_in_wl_remaining_total += w.to_be_validated_in_wl_remaining_total
#break
end
@workloads = @workloads.sort_by {|w| [-w.person.is_virtual, w.next_month_percents, w.three_next_months_percents, w.person.name]}
@totals = []
@cap_totals = []
@chart_totals = []
@chart_cap_totals = []
@avail_totals = []
size = @workloads.size
if size == 0
render :layout => false
return
end
chart_size = @workloads.select{|w| w.person.is_virtual==0}.size
# to plan
@totals << (@workloads.inject(0) { |sum,w| sum += w.remain_to_plan_days })
@cap_totals << ''
@avail_totals << ''
# next 5 weeks
@totals << (@workloads.inject(0) { |sum,w| sum += w.next_month_percents} / size).round
@cap_totals << (@workloads.inject(0) { |sum,w| sum += cap(w.next_month_percents)} / size).round
@avail_totals << ''
# next 3 months
@totals << (@workloads.inject(0) { |sum,w| sum += w.three_next_months_percents} / size).round
@cap_totals << (@workloads.inject(0) { |sum,w| sum += cap(w.three_next_months_percents)} / size).round
@avail_totals << ''
# availability 2 mths
@totals << ''
@cap_totals << ''
@avail_totals << (@workloads.inject(0) { |sum,w| sum += w.sum_availability })
# per weeks
@workloads.first.weeks.each_with_index do |tmp,i|
@totals << (@workloads.inject(0) { |sum,w| sum += w.percents[i][:value]} / size).round
@chart_totals << (@workloads.inject(0) { |sum,w| w.person.is_virtual==1 ? 0.0 : sum += w.percents[i][:value]} / chart_size).round
@cap_totals << (@workloads.inject(0) { |sum,w| sum += cap(w.percents[i][:value])} / size).round
@chart_cap_totals << (@workloads.inject(0) { |sum,w| w.person.is_virtual==1 ? 0.0 : sum += cap(w.percents[i][:value])} / chart_size).round
@avail_totals << (@workloads.inject(0) { |sum,w| sum += w.availability[i][:value]})
end
# workload chart
chart = GoogleChart::LineChart.new('1000x300', "Workload (without virtual people)", false)
realmax = [@chart_totals.max, @chart_cap_totals.max].max
high_limit = 150.0
max = realmax > high_limit ? high_limit : realmax
high_limit = high_limit > max ? max : high_limit
cap_serie = @chart_cap_totals.map { |p| p <= max ? p : max}
noncap_serie = @chart_totals.map { |p| p <= max ? p : max}
chart.data "capped", cap_serie, 'ff0000'
chart.data "non capped", noncap_serie, '0000ff'
#chart.add_labels @chart_cap_totals
chart.axis :y, :range => [0,max], :font_size => 10, :alignment => :center
chart.axis :x, :labels => @workloads.first.months, :font_size => 10, :alignment => :center
chart.shape_marker :circle, :color=>'ff3333', :data_set_index=>0, :data_point_index=>-1, :pixel_size=>8
chart.shape_marker :circle, :color=>'3333ff', :data_set_index=>1, :data_point_index=>-1, :pixel_size=>8
@chart_cap_totals.each_with_index do |p,index|
if p > high_limit
chart.shape_marker :circle, :color=>'333333', :data_set_index=>0, :data_point_index=>index, :pixel_size=>8
end
end
@chart_totals.each_with_index do |p,index|
if p > high_limit
chart.shape_marker :circle, :color=>'ff3333', :data_set_index=>1, :data_point_index=>index, :pixel_size=>8
end
end
chart.range_marker :horizontal, :color=>'EEEEEE', :start_point=>95.0/max, :end_point=>105.0/max
chart.show_legend = true
#chart.enable_interactivity = true
#chart.params[:chm] = "h,FF0000,0,-1,1"
@chart_url = chart.to_url #({:chm=>"r,DDDDDD,0,#{100.0/max-0.01},#{100.0/max}"}) #({:enableInteractivity=>true})
if APP_CONFIG['use_virtual_people']
# staffing chart
serie = []
@workloads.first.weeks.each_with_index do |tmp,i|
serie << @workloads.inject(0) { |sum,w| sum += w.staffing[i]}
end
chart = GoogleChart::LineChart.new('1000x300', "Staffing", false)
max = serie.max
chart.data "nb person", serie, 'ff0000'
chart.axis :y, :range => [0,max], :font_size => 10, :alignment => :center
chart.axis :x, :labels => @workloads.first.months, :font_size => 10, :alignment => :center
chart.shape_marker :circle, :color=>'ff3333', :data_set_index=>0, :data_point_index=>-1, :pixel_size=>8
chart.show_legend = true
@staffing_chart_url = chart.to_url #({:chm=>"r,DDDDDD,0,#{100.0/max-0.01},#{100.0/max}"}) #({:enableInteractivity=>true})
end
render :layout => false
end
def cap(nb)
nb > 100 ? 100 : nb
end
def refresh_holidays
@people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0", :order=>"name")
@workloads = []
@resfresh_holidays_backup_warnings = {} #resfresh_holidays_backup_warnings[person.id] = Hash from get_holiday_warning
for p in @people
# Person Workload
@workloads << Workload.new(p.id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'], {:only_holidays=>true})
# Person Holiday Warning
@resfresh_holidays_backup_warnings[p.id] = get_holiday_warning_detailed(p, Date.today+27.weeks)
end
@workloads = @workloads.sort_by {|w| [w.person.name]}
render :layout => false
end
# Find all lines without tasks
def refresh_missing_tasks
@lines = WlLine.find(:all, :conditions=>"wl_lines.id not in (select wl_line_id from wl_line_tasks) and wl_lines.wl_type=200", :order=>"project_id, person_id")
render :layout => false
end
# find all SDP tasks not associated to workload lines
def refresh_missing_wl_lines
task_ids = WlLineTask.find(:all, :select=>"sdp_task_id").map{ |t| t.sdp_task_id}.uniq
@tasks = SDPTask.find(:all, :conditions=>"remaining > 0 and sdp_id not in (#{task_ids.join(',')})", :order=>"project_code, remaining desc")
render :layout => false
end
# find all sdp tasks affected to wrong workload
def refresh_errors_in_affectations
@associations = WlLineTask.find(:all).select{|a| !a.sdp_task or a.sdp_task.collab != a.wl_line.person.trigram}.sort_by { |a| [a.wl_line.project_name, a.wl_line.name]}
render :layout => false
end
def refresh_requests_to_validate
@requests = Request.find(:all, :conditions=>"status='to be validated'", :order=>"summary")
@week1 = wlweek(Date.today)
@week2 = wlweek(Date.today+7.days)
@requests = @requests.select {|r| wl = r.wl_line; wl and (wl.get_load_by_week(@week1) > 0 or wl.get_load_by_week(@week2) > 0)}
render :layout => false
end
def refresh_tbp
get_people
@workloads = []
for p in @people
w = Workload.new(p.id, @project_ids, '', '', {:include_forecast=>true, :add_holidays=>false, :weeks_to_display=>12})
next if w.wl_lines.select{|l| l.wl_type != WL_LINE_HOLIDAYS}.size == 0 # do not display people with no lines at all
@workloads << w
end
render :layout => false
end
def add_by_request
request_id = params[:request_id]
if !request_id or request_id.empty?
@error = "Please provide a request number"
return
end
request_id.strip!
person_id = session['workload_person_id'].to_i
# person_id = params[:wl_person].to_i
session['workload_person_id'] = person_id.to_s
filled = filled_number(request_id,7)
request = Request.find_by_request_id(filled)
if not request
@error = "Can not find request with number #{request_id}"
return
end
project = request.project
name = request.workload_name
found = WlLine.find_by_person_id_and_request_id(person_id, request_id)
if not found
@line = WlLine.create(:name=>name, :request_id=>request_id, :person_id=>person_id, :wl_type=>WL_LINE_REQUEST)
get_workload_data(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
else
@error = "This line already exists: #{request_id}"
end
end
def add_by_name
name = params[:name].strip
if name.empty?
@error = "Please provide a name."
return
end
person_id = session['workload_person_id'].to_i
# person_id = params[:wl_person].to_i
session['workload_person_id'] = person_id.to_s
found = WlLine.find_by_person_id_and_name(person_id, name)
if not found
@line = WlLine.create(:name=>name, :request_id=>nil, :person_id=>person_id, :wl_type=>WL_LINE_OTHER)
get_workload_data(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
else
@error = "This line already exists: #{name}"
end
end
def add_by_sdp_task
sdp_task_id = params[:sdp_task_id].to_i
person_id = params[:wl_person].to_i
session['workload_person_id'] = person_id.to_s
sdp_task = SDPTask.find_by_sdp_id(sdp_task_id)
if not sdp_task
@error = "Can not find SDP Task with id #{sdp_task_id}"
return
end
found = WlLineTask.find(:first, :conditions=>["sdp_task_id=?",sdp_task_id])
if not found
@line = WlLine.create(:name=>sdp_task.title, :person_id=>person_id, :wl_type=>WL_LINE_OTHER)
WlLineTask.create(:wl_line_id=>@line.id, :sdp_task_id=>sdp_task_id)
if(APP_CONFIG['auto_link_task_to_project']) and sdp_task.project
@line.project_id = sdp_task.project.id
@line.save
end
else
@error = "Task '#{found.sdp_task.title}' is already linked to workload line '#{found.wl_line.name}'"
end
get_workload_data(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
end
def add_by_project
project_id = params[:project_id].to_i
person_id = session['workload_person_id'].to_i
# person_id = params[:wl_person].to_i
session['workload_person_id'] = person_id.to_s
project = Project.find(project_id)
if not project
@error = "Can not find project with id #{project_id}"
return
end
found = WlLine.find_by_project_id_and_person_id(project_id, person_id)
# allow to add several lines by projet
#if not found
@line = WlLine.create(:name=>project.name, :project_id=>project_id, :person_id=>person_id, :wl_type=>WL_LINE_OTHER)
#else
# @error = "This line already exists: #{found.name}"
#end
get_workload_data(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
end
def display_edit_line
line_id = params[:l].to_i
@wl_line = WlLine.find(line_id)
@workload = Workload.new(session['workload_person_id'],session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
if APP_CONFIG['workloads_add_by_project']
@projects = Project.all.map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]}
end
if @workload.person.trigram == ""
@sdp_tasks = []
else
get_sdp_tasks(@workload)
end
end
def edit_line
@wl_line = WlLine.find(params[:id])
@wl_line.update_attributes(params[:wl_line])
@workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
end
def destroy_line
@wl_line_id = params[:id]
wl_line = WlLine.find(@wl_line_id)
person_id = wl_line.person_id
wl_line.destroy
WlLineTask.find(:all, :conditions=>["wl_line_id=?",@wl_line_id]).each do |l|
l.destroy
end
line_tags = LineTag.find(:all, :conditions=>["line_id=#{@wl_line_id}"])
tags = []
line_tags.each do |l|
tag = Tag.find(l.tag_id)
tags << tag if !tags.include?(tag)
end
line_tags.each do |l|
l.destroy
end
tags.each do |t|
t.destroy if LineTag.find(:all, :conditions=>["tag_id=#{t.id}"]).size == 0
end
@workload = Workload.new(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
get_sdp_tasks(@workload)
end
def link_to_request
request_id = params[:request_id].strip
line_id = params[:id]
if request_id.empty?
@error = "Please provide a request number."
return
end
person_id = session['workload_person_id'].to_i
# person_id = params[:wl_person].to_i
session['workload_person_id'] = person_id.to_s
filled = filled_number(request_id,7)
request = Request.find_by_request_id(filled)
if not request
@error = "Can not find request with number #{request_id}"
return
end
project = request.project
name = request.workload_name
found = WlLine.find_by_person_id_and_request_id(person_id, request_id)
if not found
@wl_line = WlLine.find(line_id)
@wl_line.name = name
@wl_line.request_id = request_id
@wl_line.wl_type = WL_LINE_REQUEST
@wl_line.save
@workload = Workload.new(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
else
@error = "This line already exists: #{request_id}"
end
end
def unlink_request
line_id = params[:id]
@wl_line = WlLine.find(line_id)
@wl_line.request_id = nil
@wl_line.wl_type = WL_LINE_OTHER
@wl_line.save
@workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
end
def update_settings_name
update_status = params[:on]
if update_status=='true'
current_user.settings.wl_line_change_name = 1
else
current_user.settings.wl_line_change_name = 0
end
current_user.save
render(:nothing=>true)
end
def link_to_sdp
sdp_task_id = params[:sdp_task_id].to_i
line_id = params[:id]
task = SDPTask.find_by_sdp_id(sdp_task_id)
@wl_line = WlLine.find(line_id)
@wl_line.add_sdp_task_by_id(sdp_task_id) if not @wl_line.sdp_tasks.include?(task)
update_line_name(@wl_line) if ( current_user.settings.wl_line_change_name == 1 )
@wl_line.wl_type = WL_LINE_OTHER
@wl_line.save
@workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
get_sdp_tasks(@workload)
end
def unlink_sdp_task
sdp_task_id = params[:sdp_task_id].to_i
line_id = params[:id]
@wl_line = WlLine.find(line_id)
person = Person.find(session['workload_person_id'].to_i)
@wl_line.delete_sdp(sdp_task_id)
update_line_name(@wl_line) if ( current_user.settings.wl_line_change_name == 1 )
@wl_line.save
@workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
get_sdp_tasks(@workload)
end
def link_to_project
project_id = params[:project_id].to_i
line_id = params[:id]
@wl_line = WlLine.find(line_id)
@wl_line.project_id = project_id
@wl_line.wl_type = WL_LINE_OTHER
@wl_line.save
@workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
end
def unlink_project
line_id = params[:id]
@wl_line = WlLine.find(line_id)
@wl_line.project_id = nil
@wl_line.wl_type = WL_LINE_OTHER
@wl_line.save
@workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
end
def edit_load
view_by = (params['view_by']=='1' ? :project : :person)
@line_id = params[:l].to_i
@wlweek = params[:w].to_i
value = round_to_hour(params[:v].to_f)
value = 0 if value < 0
line = WlLine.find(@line_id)
id = view_by==:person ? line.person_id : line.project_id
if value == 0.0
if (line.wl_type == WL_LINE_HOLIDAYS)
backup = WlBackup.find(:all, :conditions=>["person_id = ? and week = ?", line.person.id.to_s, @wlweek])
# Send email
backup.each do |b|
Mailer::deliver_backup_delete(b)
end
backup.each(&:destroy)
end
WlLoad.delete_all(["wl_line_id=? and week=?",@line_id, @wlweek])
@value = ""
else
wl_load = WlLoad.find_by_wl_line_id_and_week(@line_id, @wlweek)
wl_load = WlLoad.create(:wl_line_id=>@line_id, :week=>@wlweek) if not wl_load
wl_load.wlload = value
wl_load.save
@value = value
end
@lsum, @plsum, @csum, @cpercent, @case_percent, @total, @planned_total, @avail, @diff_planned_remaining_line, @diff_planned_remaining = get_sums(line, @wlweek, id, view_by)
end
# type is :person or :projet and indicates what is the id (person or projet)
def get_sums(line, week, id, type=:person)
@type = type
today_week = wlweek(Date.today)
plsum = line.wl_loads.map{|l| (l.week < today_week ? 0 : l.wlload)}.inject(:+) || 0
lsum = line.wl_loads.map{|l| l.wlload}.inject(:+)
if(type==:project)
wl_lines = WlLine.find(:all, :conditions=>["project_id in (#{session['workload_project_ids'].join(',')})"])
person_wl_lines = WlLine.find(:all, :conditions=>["person_id=?", line.person.id])
case_sum = person_wl_lines.map{|l| l.get_load_by_week(week)}.inject(:+)
case_sum = 0 if !case_sum
nb_days_per_weeks = 5 * wl_lines.map{|l| l.person_id}.uniq.size
else
wl_lines = WlLine.find(:all, :conditions=>["person_id=?", id])
nb_days_per_weeks = 5
end
csum = wl_lines.map{|l| l.get_load_by_week(week)}.inject(:+)
csum = 0 if !csum
case_sum = csum if type==:person
open = nb_days_per_weeks
wl_lines.map{|l| l.person}.uniq.each do |p|
company = Company.find_by_id(p.company_id)
open = open - WlHoliday.get_from_week_and_company(week,company)
end
company = Company.find_by_id(line.person.company_id)
person_open = 5 - WlHoliday.get_from_week_and_company(week,company)
# cpercent is the percent of occupation for a week. It depends of the view (person or project)
cpercent = open > 0 ? (csum / open*100).round : 0
# case_percent is the percent of occupation for a week for a person. It does not depend of the view (person or project)
case_percent = open > 0 ? (case_sum / person_open*100).round : 0
if APP_CONFIG['workload_show_overload_availability']
avail = open-csum
else
avail = [0,(open-csum)].max
end
planned_total = 0
total = 0
total_remaining = 0
for l in wl_lines
next if l.wl_type > 200
l.wl_loads.each { |load|
total += load.wlload
planned_total += (load.week < today_week ? 0 : load.wlload)
}
total_remaining += l.sdp_tasks_remaining
end
diff_planned_remaining_line = plsum - line.sdp_tasks_remaining
diff_planned_remaining = planned_total - total_remaining
[lsum, plsum, csum, cpercent, case_percent, total, planned_total, avail, diff_planned_remaining_line, diff_planned_remaining]
end
def transfert
@people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0", :order=>"name").map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]}
# WL Lines without project
@lines = WlLine.find(:all, :conditions=>["person_id=? and project_id IS NULL", session['workload_person_id']],
:include=>["request","wl_line_task","person"], :order=>"wl_type, name")
# WL lines by project
temp_lines_qr_qwr = WlLine.find(:all, :conditions=>["person_id=? and project_id IS NOT NULL", session['workload_person_id']],
:include=>["request","wl_line_task","person"], :order=>"wl_type, name")
@lines_qr_qwr = Hash.new
temp_lines_qr_qwr.each do |wl|
@lines_qr_qwr[wl.project_id] = [wl]
end
@owner_id = session['workload_person_id']
# all lines
@all_lines = WlLine.find(:all, :conditions=>["person_id=?", session['workload_person_id']], :include=>["project"], :order=>"wl_type, name")
end
def do_transfert
# Params
lines = params['lines'] # array of ids (as strings)
lines_qr_qwr = params['lines_qr_qwr'] # array of ids of wl lines qr qwr (as strings)
p_id = params['person_id']
owner_id = params['owner_id']
# Lines to transfert
if lines
lines.each { |l_id|
l = WlLine.find(l_id.to_i)
l.person_id = p_id.to_i
l.save
}
end
# Lines of qr_qwr to transfert
if lines_qr_qwr
lines_qr_qwr.each { |l_id|
# Find all lines (two line by project qr_qwr)
l = WlLine.find(l_id.to_i)
WlLine.find(:all,:conditions=>["person_id = ? and project_id = ?",owner_id.to_s, l.project_id.to_s]).each { |line_by_project|
line_by_project.person_id = p_id.to_i
line_by_project.project.qr_qwr_id = p_id.to_i
line_by_project.save
line_by_project.project.save
}
}
end
redirect_to(:action=>"transfert")
end
def duplicate
@months = []
@weeks = []
@wl_weeks = []
@months = params[:months]
@weeks = params[:weeks]
@wl_weeks = params[:wl_weeks]
@people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0", :order=>"name").map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]}
# WL lines without project_id
@lines = WlLine.find(:all, :conditions=>["person_id=? and project_id IS NULL", session['workload_person_id']],
:include=>["request","wl_line_task","person"], :order=>"wl_type, name")
# WL lines by project
@lines_qr_qwr = WlLine.find(:all, :conditions=>["person_id=? and project_id IS NOT NULL", session['workload_person_id']],
:include=>["request","wl_line_task","person"], :order=>"project_id,wl_type,name")
end
def do_duplication
lines_loads = params['lines_loads'] # array of lineId_loadId
p_id = params['person_id']
lines_loads.each { |l_l|
# Wl_line and Wl_load selected
l_l_splited = l_l.split("_")
line_id = l_l_splited[0]
load_id = l_l_splited[1]
line = WlLine.find(line_id.to_i)
load = WlLoad.find(load_id.to_i)
# Check if the line to duplicate isn't already duplicated from another line
# If Line to duplicate is already duplicate, so we take the first line as parent_id
parent_id = line.id
if line.parent_line
parent = WlLine.find(line.parent_line)
parent_id = parent.id
end
# Check if the person selected has not already a duplicate
duplicate = 0 # Id of the Wl_line duplicated and managed by the person selected (0 if null)
if line.duplicates != nil
line.duplicates.each { |l|
if l.person_id.to_s == p_id
duplicate = l.id
end
}
end
# If the person selected has not already a duplicate, we create it
if duplicate == 0
new_line = line.clone
new_line.parent_line = parent_id
new_line.person_id = p_id
new_line.save
duplicate = new_line.id
end
# Change wl_line of load selected
load.wl_line_id = duplicate
load.save
# Project
request = Request.first(:conditions=>["request_id = ?",line.request_id]) if line.request_id
if request != nil
project_id = request.project_id
project_person = ProjectPerson.first(:conditions => ["project_id = ? and person_id = ?", project_id, p_id]) if project_id
if project_person == nil
project_person = ProjectPerson.new
project_person.project_id = project_id
project_person.person_id = p_id
project_person.save
end
end
}
redirect_to(:action=>"index")
end
def hide_lines_with_no_workload
on = (params[:on].to_s != 'false')
session['workload_hide_lines_with_no_workload'] = on
get_workload_data(session['workload_person_id'],session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'])
end
def hide_wmenu
session['wmenu_hidden'] = params[:on]
render(:nothing=>true)
end
def backup
@people = Person.find(:all, :conditions=>["has_left=0 and is_supervisor=0 and id != ?", session['workload_person_id']], :order=>"name").map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]}
@backups = WlBackup.find(:all, :conditions=>["person_id=?", session['workload_person_id']]);
@self_backups = WlBackup.find(:all, :conditions=>["backup_person_id=?", session['workload_person_id']]);
backup_weeks = Array.new
@backups.each do |b|
backup_weeks << b.week
end
# Get holidays week
conditions = "wl_lines.person_id = #{session['workload_person_id'].to_s} and wl_lines.wl_type = #{WL_LINE_HOLIDAYS} and wlload > 0 and week >= #{wlweek(Date.today)}"
person_holiday_load = WlLoad.find(:all,
:joins => 'JOIN wl_lines ON wl_lines.id = wl_loads.wl_line_id',
:conditions=>conditions,
:order=>"week")
@holiday_dates = person_holiday_load.map { |h|
year = h.week.to_s[0..-3]
week = h.week.to_s[4..6]
["#{week}-#{year}","#{h.week}"]
}
end
def create_backup
b_id = params['backup_person_id']
p_id = params['person_id']
week = params['week']
backups = WlBackup.first(:conditions=>["backup_person_id = ? and person_id = ? and week = ?", b_id, p_id, week]);
if (backups == nil)
backup = WlBackup.new
backup.backup_person_id = b_id
backup.person_id = p_id
backup.week = week
backup.save
render :text=>backup.week.to_s+"_"+backup.backup.name
else
render(:nothing=>true)
end
end
def delete_backup
backup_id = params['backup_id']
backup = WlBackup.first(:conditions=>["id = ?", backup_id]);
backup.destroy
render(:nothing=>true)
end
def update_backup_comment
backup_id = params['backup_id']
backup_comment = params['backup_comment']
backup = WlBackup.first(:conditions=>["id = ?", backup_id]);
if backup != nil
backup.comment = backup_comment
backup.save
end
render :text=>backup.comment, :layout => false
end
private
def get_workload_data(person_id, projects_ids, person_iterations, tags_ids)
@workload = Workload.new(person_id,projects_ids,person_iterations, tags_ids, {:hide_lines_with_no_workload => session['workload_hide_lines_with_no_workload'].to_s=='true'})
@person = @workload.person
get_last_sdp_update
get_suggested_requests(@workload)
get_chart
get_sdp_gain(@workload.person)
get_sdp_tasks(@workload)
get_backup_warnings(@workload.person)
get_unlinked_sdp_tasks(@workload)
get_holiday_warning(@workload.person)
end
def update_line_name(line)
line.name = line.sdp_tasks.map{|p| p.title}.sort.join(', ')
line.name = "No line name" if line.name == ""
end
end
| micktaiwan/scpm | app/controllers/workloads_controller.rb | Ruby | bsd-3-clause | 41,083 |
import { select } from '@storybook/addon-knobs';
import readme from '@ovh-ux/ui-kit.button/README.md';
const state = {
label: 'State',
options: {
Normal: '',
Disabled: 'disabled',
},
default: '',
};
export default {
title: 'Design System/Components/Buttons/Native/Primary',
parameters: {
notes: readme,
options: {
showPanel: true,
},
},
};
export const Default = () => `
<button class="oui-button oui-button_primary" ${select(state.label, state.options, state.default)}>
Call to action
</button>
<button class="oui-button oui-button_primary oui-button_icon-left" ${select(
state.label,
state.options,
state.default,
)}>
<span class="oui-icon oui-icon-folder" aria-hidden="true"></span>
Call to action
</button>
<button class="oui-button oui-button_primary oui-button_icon-right" ${select(
state.label,
state.options,
state.default,
)}>
Call to action
<span class="oui-icon oui-icon-folder" aria-hidden="true"></span>
</button>`;
export const Large = () => `
<button class="oui-button oui-button_l oui-button_primary" ${select(
state.label,
state.options,
state.default,
)}>
Call to action
</button>
<button class="oui-button oui-button_l oui-button_primary oui-button_icon-left" ${select(
state.label,
state.options,
state.default,
)}>
<span class="oui-icon oui-icon-folder" aria-hidden="true"></span>
Call to action
</button>
<button class="oui-button oui-button_l oui-button_primary oui-button_icon-right" ${select(
state.label,
state.options,
state.default,
)}>
Call to action
<span class="oui-icon oui-icon-folder" aria-hidden="true"></span>
</button>`;
export const Small = () => `
<button class="oui-button oui-button_s oui-button_primary" ${select(
state.label,
state.options,
state.default,
)}>
OK
</button>
<button class="oui-button oui-button_s oui-button_primary" ${select(
state.label,
state.options,
state.default,
)}>
<span class="oui-icon oui-icon-folder"></span>
</button>`;
export const Block = () => `
<button class="oui-button oui-button_block oui-button_primary" ${select(
state.label,
state.options,
state.default,
)}>
Call to action
</button>
<button class="oui-button oui-button_block oui-button_primary oui-button_icon-left" ${select(
state.label,
state.options,
state.default,
)}>
<span class="oui-icon oui-icon-folder"></span>
Call to action
</button>
<button class="oui-button oui-button_block oui-button_primary oui-button_icon-right" ${select(
state.label,
state.options,
state.default,
)}>
Call to action
<span class="oui-icon oui-icon-folder"></span>
</button>`;
export const Group = () => `
<div class="oui-button-group">
<button class="oui-button oui-button_primary">Lorem</button>
<button class="oui-button oui-button_primary">Ipsum</button>
<button class="oui-button oui-button_primary">Dolor</button>
<button class="oui-button oui-button_primary">Sit</button>
<button class="oui-button oui-button_primary">Amet</button>
</div>`;
| ovh-ux/ovh-ui-kit | packages/apps/workshop/stories/design-system/components/button-native-primary.stories.js | JavaScript | bsd-3-clause | 3,190 |
# -*-coding:Utf-8 -*
# Copyright (c) 2010 DAVY Guillaume
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder 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.
"""Fichier contenant la classe Sorts, détaillée plus bas."""
from abstraits.obase import BaseObj
from .sort import Sort
class Sorts(BaseObj):
"""Classe-conteneur des sorts.
Cette classe contient tous les sortilèges et autres maléfices de
l'univers, éditables et utilisables, et offre quelques méthodes de
manipulation.
Voir : ./sort.py
"""
enregistrer = True
def __init__(self):
"""Constructeur du conteneur"""
BaseObj.__init__(self)
self.__sorts = {}
def __getnewargs__(self):
return ()
def __contains__(self, cle):
"""Renvoie True si le sort existe, False sinon"""
return cle in self.__sorts
def __len__(self):
return len(self.__sorts)
def __getitem__(self, cle):
"""Renvoie un sort à partir de sa clé"""
return self.__sorts[cle]
def __setitem__(self, cle, sort):
"""Ajoute un sort à la liste"""
self.__sorts[cle] = sort
def __delitem__(self, cle):
"""Détruit le sort spécifié"""
del self.__sorts[cle]
def values(self):
return self.__sorts.values()
def ajouter_ou_modifier(self, cle):
"""Ajoute un sort ou le renvoie si existant"""
if cle in self.__sorts:
return self.__sorts[cle]
else:
sort = Sort(cle, self)
self.__sorts[cle] = sort
return sort
def get(self, cle, valeur=None):
"""Retourne le sort ou valeur si non présent."""
return self.__sorts.get(cle, valeur)
| stormi/tsunami | src/secondaires/magie/sorts.py | Python | bsd-3-clause | 3,125 |
/// <reference path="../../server.d.ts" />
'use strict';
module.exports = {
ip: process.env.IP || undefined,
server: {
url: 'http://www.<%= appname %>.com'
}<% if (filters.backend === 'mongo') { %>,
mongo: {
uri: 'mongodb://localhost/<%= slugName %>'
}<% } %>,
facebook: {
clientID: '975041909195011',
clientSecret: '6bcf8b64f80546cfd799a4f467cd1a20',
callbackURL: '/auth/facebook/callback'
}
};
| NovaeWorkshop/Nova | app/templates/server/config/environment/production.js | JavaScript | bsd-3-clause | 465 |
#include <iostream>
#include <vector>
using namespace std;
typedef unsigned long long int ull;
int main() {
static const ull MAX = 28123;
ull sum = 0;
vector<ull> abu;
vector<bool> is_abu(MAX+1);
for(ull i = 1; i <= MAX; i++) {
ull sum_d = 0;
for(ull j = 1; j < i; j++) {
if(0 == i%j) sum_d += j;
}
if(sum_d > i) {
abu.push_back(i);
is_abu[i] = true;
}
}
for(ull i = 1; i < MAX; i++) {
bool add = true;
for(vector<ull>::const_iterator it = abu.begin(); it != abu.end(); it++) {
if(*it <= i && is_abu[i-*it]) {
add = false;
break;
}
}
if(add) sum += i;
}
cout << sum << endl;
return 0;
}
| nikolasco/project_euler | 023.cpp | C++ | bsd-3-clause | 793 |
<?php
/* @var $this yii\web\View */
/* @var $lastPosts */
/* @var $featured */
/* @var $drafts */
use yii\helpers\Url;
use yii\helpers\Html;
$this->title = 'Головна';
?>
<div class="site-index">
<h1 class="by-center">Адмін панель</h1>
<hr />
<div class="body-content">
<div class="row">
<div class="col-lg-3 col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row row-panel">
<div class="col-xs-3">
<i class="glyphicon glyphicon-list-alt dashboard-glyp"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge"><?= $postsCount ?></div>
<div>Всього вакансій</div>
</div>
</div>
</div>
<a href="<?= Url::toRoute('post/index') ?>">
<div class="panel-footer">
<span class="pull-left">Переглянути</span>
<span class="pull-right"><i class="glyphicon glyphicon-circle-arrow-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-green">
<div class="panel-green panel-heading">
<div class="row row-panel">
<div class="col-xs-3">
<i class="glyphicon glyphicon-bookmark dashboard-glyp"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge"><?= $categoryCount ?></div>
<div>Всього напрямків</div>
</div>
</div>
</div>
<a href="<?= Url::toRoute('category/index') ?>">
<div class="panel-footer">
<span class="pull-left">Переглянути</span>
<span class="pull-right"><i class="glyphicon glyphicon-circle-arrow-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-yellow">
<div class="panel-yellow panel-heading">
<div class="row row-panel">
<div class="col-xs-3">
<i class="glyphicon glyphicon-circle-arrow-up dashboard-glyp"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge"><?= $mostPopularCategory->qty ?></div>
<div> Топ напрямок: <b><?= $mostPopularCategory->title ?></b></div>
</div>
</div>
</div>
<a href="<?= Url::toRoute(['./../posts/category', 'id' => $mostPopularCategory->id]) ?>">
<div class="panel-footer">
<span class="pull-left">Переглянути</span>
<span class="pull-right"><i class="glyphicon glyphicon-circle-arrow-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-red">
<div class="panel-red panel-heading">
<div class="row row-panel">
<div class="col-xs-3">
<i class="glyphicon glyphicon-tags dashboard-glyp"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge"><?= $mostPopularTag->qty ?></div>
<div> Навички: <b><?= $mostPopularTag->title ?></b></div>
</div>
</div>
</div>
<a href="<?= Url::toRoute(['./../posts/tag', 'ids' => $mostPopularTag->id]) ?>">
<div class="panel-footer">
<span class="pull-left">Переглянути</span>
<span class="pull-right"><i class="glyphicon glyphicon-circle-arrow-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
</div>
<hr />
<div class="row">
<div class="col-lg-4">
<div class="panel panel-default">
<div class="panel-heading">
<?= Html::a('<h4><i class="glyphicon glyphicon-list-alt"></i> Останні вакансії</h4>', ['/post/index'])?>
</div>
<ul class="list-group">
<?php foreach($lastPosts as $post): ?>
<li class="list-group-item">
<?= Html::a($post->title , ['./../posts/view', 'id' => $post->id], ['target'=>'_blank'])?>
</li>
<?php endforeach ?>
</ul>
</div>
</div>
<div class="col-lg-4">
<div class="panel panel-default">
<div class="panel-heading">
<?= Html::a('<h4><i class="glyphicon glyphicon-thumbs-up"></i> Термінові вакансії</h4>', ['/post/index'])?>
</div>
<ul class="list-group">
<?php foreach($featured as $post): ?>
<li class="list-group-item">
<?= Html::a($post->title , ['./../posts/view', 'id' => $post->id], ['target'=>'_blank'])?>
</li>
<?php endforeach ?>
</ul>
</div>
</div>
<div class="col-lg-4">
<div class="panel panel-default">
<div class="panel-heading">
<?= Html::a('<h4><i class="glyphicon glyphicon-file"></i> Чернетки</h4>', ['/post/index'])?>
</div>
<ul class="list-group">
<?php foreach($drafts as $post): ?>
<li class="list-group-item">
<?= Html::a($post->title , ['./../posts/view', 'id' => $post->id], ['target'=>'_blank'])?>
</li>
<?php endforeach ?>
</ul>
</div>
</div>
</div>
</div>
</div>
| VitaliyProdan/hr | backend/views/site/index.php | PHP | bsd-3-clause | 7,390 |
/*
* Copyright (c) 2011-2021, PCJ Library, Marek Nowicki
* All rights reserved.
*
* Licensed under New BSD License (3-clause license).
*
* See the file "LICENSE" for the full license governing this code.
*/
package org.pcj.internal.message.scatter;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.pcj.PcjFuture;
import org.pcj.PcjRuntimeException;
import org.pcj.internal.InternalCommonGroup;
import org.pcj.internal.InternalPCJ;
import org.pcj.internal.InternalStorages;
import org.pcj.internal.Networker;
import org.pcj.internal.NodeData;
import org.pcj.internal.PcjThread;
import org.pcj.internal.message.Message;
/**
* @author Marek Nowicki (faramir@mat.umk.pl)
*/
public class ScatterStates {
private final AtomicInteger counter;
private final ConcurrentMap<List<Integer>, State> stateMap;
public ScatterStates() {
counter = new AtomicInteger(0);
stateMap = new ConcurrentHashMap<>();
}
public State create(int threadId, InternalCommonGroup commonGroup) {
int requestNum = counter.incrementAndGet();
NodeData nodeData = InternalPCJ.getNodeData();
ScatterFuture future = new ScatterFuture();
State state = new State(requestNum, threadId,
commonGroup.getCommunicationTree().getChildrenNodes(nodeData.getCurrentNodePhysicalId()).size(),
future);
stateMap.put(Arrays.asList(requestNum, threadId), state);
return state;
}
public State getOrCreate(int requestNum, int requesterThreadId, InternalCommonGroup commonGroup) {
NodeData nodeData = InternalPCJ.getNodeData();
int requesterPhysicalId = nodeData.getPhysicalId(commonGroup.getGlobalThreadId(requesterThreadId));
return stateMap.computeIfAbsent(Arrays.asList(requestNum, requesterThreadId),
key -> new State(requestNum, requesterThreadId,
commonGroup.getCommunicationTree().getChildrenNodes(requesterPhysicalId).size()));
}
public State remove(int requestNum, int threadId) {
return stateMap.remove(Arrays.asList(requestNum, threadId));
}
public class State {
private final int requestNum;
private final int requesterThreadId;
private final AtomicInteger notificationCount;
private final ScatterFuture future;
private final Queue<Exception> exceptions;
private State(int requestNum, int requesterThreadId, int childrenCount, ScatterFuture future) {
this.requestNum = requestNum;
this.requesterThreadId = requesterThreadId;
this.future = future;
// notification from children and from itself
notificationCount = new AtomicInteger(childrenCount + 1);
exceptions = new ConcurrentLinkedQueue<>();
}
private State(int requestNum, int requesterThreadId, int childrenCount) {
this(requestNum, requesterThreadId, childrenCount, null);
}
public int getRequestNum() {
return requestNum;
}
public PcjFuture<Void> getFuture() {
return future;
}
void downProcessNode(InternalCommonGroup group, String sharedEnumClassName, String name, int[] indices, Map<Integer, Object> newValueMap) {
NodeData nodeData = InternalPCJ.getNodeData();
Set<Integer> threadsId = group.getLocalThreadsId();
for (int threadId : threadsId) {
if (!newValueMap.containsKey(threadId)) {
continue;
}
int globalThreadId = group.getGlobalThreadId(threadId);
PcjThread pcjThread = nodeData.getPcjThread(globalThreadId);
InternalStorages storage = pcjThread.getThreadData().getStorages();
try {
Object newValue = newValueMap.remove(threadId);
storage.put(newValue, sharedEnumClassName, name, indices);
} catch (Exception ex) {
exceptions.add(ex);
}
}
Networker networker = InternalPCJ.getNetworker();
int requesterPhysicalId = nodeData.getPhysicalId(group.getGlobalThreadId(requesterThreadId));
Set<Integer> childrenNodes = group.getCommunicationTree().getChildrenNodes(requesterPhysicalId);
Map<Integer, Integer> groupIdToGlobalIdMap = group.getThreadsMap();
for (int childrenNode : childrenNodes) {
List<Integer> subTree = group.getCommunicationTree().getSubtree(requesterPhysicalId, childrenNode);
Map<Integer, Object> subTreeNewValueMap = groupIdToGlobalIdMap.entrySet()
.stream()
.filter(entry -> subTree.contains(nodeData.getPhysicalId(entry.getValue())))
.map(Map.Entry::getKey)
.filter(newValueMap::containsKey)
.collect(HashMap::new, (map, key) -> map.put(key, newValueMap.get(key)), HashMap::putAll);
ScatterRequestMessage message = new ScatterRequestMessage(
group.getGroupId(), requestNum, requesterThreadId,
sharedEnumClassName, name, indices, subTreeNewValueMap);
SocketChannel socket = nodeData.getSocketChannelByPhysicalId(childrenNode);
networker.send(socket, message);
}
nodeProcessed(group);
}
void upProcessNode(InternalCommonGroup group, Queue<Exception> messageExceptions) {
if ((messageExceptions != null) && (!messageExceptions.isEmpty())) {
exceptions.addAll(messageExceptions);
}
nodeProcessed(group);
}
private void nodeProcessed(InternalCommonGroup group) {
int leftPhysical = notificationCount.decrementAndGet();
NodeData nodeData = InternalPCJ.getNodeData();
if (leftPhysical == 0) {
int requesterPhysicalId = nodeData.getPhysicalId(group.getGlobalThreadId(requesterThreadId));
if (requesterPhysicalId != nodeData.getCurrentNodePhysicalId()) { // requester will receive response
ScatterStates.this.remove(requestNum, requesterThreadId);
}
int parentId = group.getCommunicationTree().getParentNode(requesterPhysicalId);
if (parentId >= 0) {
Message message = new ScatterResponseMessage(group.getGroupId(), requestNum, requesterThreadId, exceptions);
SocketChannel socket = nodeData.getSocketChannelByPhysicalId(parentId);
InternalPCJ.getNetworker().send(socket, message);
} else {
ScatterStates.State state = ScatterStates.this.remove(requestNum, requesterThreadId);
state.signal(exceptions);
}
}
}
public void signal(Queue<Exception> messageExceptions) {
if ((messageExceptions != null) && (!messageExceptions.isEmpty())) {
PcjRuntimeException ex = new PcjRuntimeException("Scatter value array failed", messageExceptions.poll());
messageExceptions.forEach(ex::addSuppressed);
future.signalException(ex);
} else {
future.signalDone();
}
}
protected void addException(Exception ex) {
exceptions.add(ex);
}
}
}
| hpdcj/PCJ | src/main/java/org/pcj/internal/message/scatter/ScatterStates.java | Java | bsd-3-clause | 8,076 |
<?php
/*
* Copyright 2016 Google LLC
* 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 Google Inc. 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.
*/
namespace Google\ApiCore;
use Generator;
use Google\Protobuf\Internal\Message;
use IteratorAggregate;
/**
* A Page object wraps an API list method response and provides methods
* to retrieve additional pages using the page token.
*/
class Page implements IteratorAggregate
{
const FINAL_PAGE_TOKEN = "";
private $call;
private $callable;
private $options;
private $pageStreamingDescriptor;
private $pageToken;
private $response;
/**
* Page constructor.
*
* @param Call $call
* @param array $options
* @param callable $callable
* @param PageStreamingDescriptor $pageStreamingDescriptor
* @param Message $response
*/
public function __construct(
Call $call,
array $options,
callable $callable,
PageStreamingDescriptor $pageStreamingDescriptor,
Message $response
) {
$this->call = $call;
$this->options = $options;
$this->callable = $callable;
$this->pageStreamingDescriptor = $pageStreamingDescriptor;
$this->response = $response;
$requestPageTokenGetMethod = $this->pageStreamingDescriptor->getRequestPageTokenGetMethod();
$this->pageToken = $this->call->getMessage()->$requestPageTokenGetMethod();
}
/**
* Returns true if there are more pages that can be retrieved from the
* API.
*
* @return bool
*/
public function hasNextPage()
{
return strcmp($this->getNextPageToken(), Page::FINAL_PAGE_TOKEN) != 0;
}
/**
* Returns the next page token from the response.
*
* @return string
*/
public function getNextPageToken()
{
$responsePageTokenGetMethod = $this->pageStreamingDescriptor->getResponsePageTokenGetMethod();
return $this->getResponseObject()->$responsePageTokenGetMethod();
}
/**
* Retrieves the next Page object using the next page token.
*
* @param int|null $pageSize
* @throws ValidationException if there are no pages remaining, or if pageSize is supplied but
* is not supported by the API
* @throws ApiException if the call to fetch the next page fails.
* @return Page
*/
public function getNextPage($pageSize = null)
{
if (!$this->hasNextPage()) {
throw new ValidationException(
'Could not complete getNextPage operation: ' .
'there are no more pages to retrieve.'
);
}
$newRequest = clone $this->getRequestObject();
$requestPageTokenSetMethod = $this->pageStreamingDescriptor->getRequestPageTokenSetMethod();
$newRequest->$requestPageTokenSetMethod($this->getNextPageToken());
if (isset($pageSize)) {
if (!$this->pageStreamingDescriptor->requestHasPageSizeField()) {
throw new ValidationException(
'pageSize argument was defined, but the method does not ' .
'support a page size parameter in the optional array argument'
);
}
$requestPageSizeSetMethod = $this->pageStreamingDescriptor->getRequestPageSizeSetMethod();
$newRequest->$requestPageSizeSetMethod($pageSize);
}
$this->call = $this->call->withMessage($newRequest);
$callable = $this->callable;
$response = $callable(
$this->call,
$this->options
)->wait();
return new Page(
$this->call,
$this->options,
$this->callable,
$this->pageStreamingDescriptor,
$response
);
}
/**
* Return the number of elements in the response.
*
* @return int
*/
public function getPageElementCount()
{
$resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod();
return count($this->getResponseObject()->$resourcesGetMethod());
}
/**
* Return an iterator over the elements in the response.
*
* @return Generator
*/
public function getIterator()
{
$resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod();
foreach ($this->getResponseObject()->$resourcesGetMethod() as $element) {
yield $element;
}
}
/**
* Return an iterator over Page objects, beginning with this object.
* Additional Page objects are retrieved lazily via API calls until
* all elements have been retrieved.
*
* @return Generator|Page[]
* @throws ValidationException
* @throws ApiException
*/
public function iteratePages()
{
$currentPage = $this;
yield $this;
while ($currentPage->hasNextPage()) {
$currentPage = $currentPage->getNextPage();
yield $currentPage;
}
}
/**
* Gets the request object used to generate the Page.
*
* @return mixed|Message
*/
public function getRequestObject()
{
return $this->call->getMessage();
}
/**
* Gets the API response object.
*
* @return mixed|Message
*/
public function getResponseObject()
{
return $this->response;
}
/**
* Returns a collection of elements with a fixed size set by
* the collectionSize parameter. The collection will only contain
* fewer than collectionSize elements if there are no more
* pages to be retrieved from the server.
*
* NOTE: it is an error to call this method if an optional parameter
* to set the page size is not supported or has not been set in the
* API call that was used to create this page. It is also an error
* if the collectionSize parameter is less than the page size that
* has been set.
*
* @param $collectionSize int
* @throws ValidationException if a FixedSizeCollection of the specified size cannot be constructed
* @return FixedSizeCollection
*/
public function expandToFixedSizeCollection($collectionSize)
{
if (!$this->pageStreamingDescriptor->requestHasPageSizeField()) {
throw new ValidationException(
"FixedSizeCollection is not supported for this method, because " .
"the method does not support an optional argument to set the " .
"page size."
);
}
$request = $this->getRequestObject();
$pageSizeGetMethod = $this->pageStreamingDescriptor->getRequestPageSizeGetMethod();
$pageSize = $request->$pageSizeGetMethod();
if (is_null($pageSize)) {
throw new ValidationException(
"Error while expanding Page to FixedSizeCollection: No page size " .
"parameter found. The page size parameter must be set in the API " .
"optional arguments array, and must be less than the collectionSize " .
"parameter, in order to create a FixedSizeCollection object."
);
}
if ($pageSize > $collectionSize) {
throw new ValidationException(
"Error while expanding Page to FixedSizeCollection: collectionSize " .
"parameter is less than the page size optional argument specified in " .
"the API call. collectionSize: $collectionSize, page size: $pageSize"
);
}
return new FixedSizeCollection($this, $collectionSize);
}
}
| michaelbausor/gax-php | src/Page.php | PHP | bsd-3-clause | 9,056 |
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "quux/server/chlo_extractor.h"
#include "net/quic/crypto/crypto_framer.h"
#include "net/quic/crypto/crypto_handshake_message.h"
#include "net/quic/crypto/crypto_protocol.h"
#include "net/quic/crypto/quic_decrypter.h"
#include "net/quic/crypto/quic_encrypter.h"
#include "net/quic/quic_framer.h"
using base::StringPiece;
namespace net {
namespace {
class ChloFramerVisitor : public QuicFramerVisitorInterface,
public CryptoFramerVisitorInterface {
public:
ChloFramerVisitor(QuicFramer* framer, ChloExtractor::Delegate* delegate);
~ChloFramerVisitor() override {}
// QuicFramerVisitorInterface implementation
void OnError(QuicFramer* framer) override {}
bool OnProtocolVersionMismatch(QuicVersion version) override;
void OnPacket() override {}
void OnPublicResetPacket(const QuicPublicResetPacket& packet) override {}
void OnVersionNegotiationPacket(
const QuicVersionNegotiationPacket& packet) override {}
bool OnUnauthenticatedPublicHeader(
const QuicPacketPublicHeader& header) override;
bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override;
void OnDecryptedPacket(EncryptionLevel level) override {}
bool OnPacketHeader(const QuicPacketHeader& header) override;
bool OnStreamFrame(const QuicStreamFrame& frame) override;
bool OnAckFrame(const QuicAckFrame& frame) override;
bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override;
bool OnPingFrame(const QuicPingFrame& frame) override;
bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override;
bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override;
bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override;
bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
bool OnBlockedFrame(const QuicBlockedFrame& frame) override;
bool OnPathCloseFrame(const QuicPathCloseFrame& frame) override;
bool OnPaddingFrame(const QuicPaddingFrame& frame) override;
void OnPacketComplete() override {}
// CryptoFramerVisitorInterface implementation.
void OnError(CryptoFramer* framer) override;
void OnHandshakeMessage(const CryptoHandshakeMessage& message) override;
bool found_chlo() { return found_chlo_; }
private:
QuicFramer* framer_;
ChloExtractor::Delegate* delegate_;
bool found_chlo_;
QuicConnectionId connection_id_;
};
ChloFramerVisitor::ChloFramerVisitor(QuicFramer* framer,
ChloExtractor::Delegate* delegate)
: framer_(framer),
delegate_(delegate),
found_chlo_(false),
connection_id_(0) {}
bool ChloFramerVisitor::OnProtocolVersionMismatch(QuicVersion version) {
if (!framer_->IsSupportedVersion(version)) {
return false;
}
framer_->set_version(version);
return true;
}
bool ChloFramerVisitor::OnUnauthenticatedPublicHeader(
const QuicPacketPublicHeader& header) {
connection_id_ = header.connection_id;
return true;
}
bool ChloFramerVisitor::OnUnauthenticatedHeader(
const QuicPacketHeader& header) {
return true;
}
bool ChloFramerVisitor::OnPacketHeader(const QuicPacketHeader& header) {
return true;
}
bool ChloFramerVisitor::OnStreamFrame(const QuicStreamFrame& frame) {
StringPiece data(frame.data_buffer, frame.data_length);
if (frame.stream_id == kCryptoStreamId && frame.offset == 0 &&
data.starts_with("CHLO")) {
CryptoFramer crypto_framer;
crypto_framer.set_visitor(this);
if (!crypto_framer.ProcessInput(data)) {
return false;
}
}
return true;
}
bool ChloFramerVisitor::OnAckFrame(const QuicAckFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnPingFrame(const QuicPingFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnConnectionCloseFrame(
const QuicConnectionCloseFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnWindowUpdateFrame(
const QuicWindowUpdateFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnBlockedFrame(const QuicBlockedFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnPathCloseFrame(const QuicPathCloseFrame& frame) {
return true;
}
bool ChloFramerVisitor::OnPaddingFrame(const QuicPaddingFrame& frame) {
return true;
}
void ChloFramerVisitor::OnError(CryptoFramer* framer) {}
void ChloFramerVisitor::OnHandshakeMessage(
const CryptoHandshakeMessage& message) {
delegate_->OnChlo(framer_->version(), connection_id_, message);
found_chlo_ = true;
}
} // namespace
// static
bool ChloExtractor::Extract(const QuicEncryptedPacket& packet,
const QuicVersionVector& versions,
Delegate* delegate) {
QuicFramer framer(versions, QuicTime::Zero(), Perspective::IS_SERVER);
ChloFramerVisitor visitor(&framer, delegate);
framer.set_visitor(&visitor);
if (!framer.ProcessPacket(packet)) {
return false;
}
return visitor.found_chlo();
}
} // namespace net
| aliclark/libquic | src/quux/server/chlo_extractor.cc | C++ | bsd-3-clause | 5,344 |
// Copyright 2015 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pool
import (
"sort"
"testing"
"github.com/tsuru/config"
"github.com/tsuru/tsuru/auth"
"github.com/tsuru/tsuru/db"
"github.com/tsuru/tsuru/db/dbtest"
tsuruErrors "github.com/tsuru/tsuru/errors"
"github.com/tsuru/tsuru/router"
"github.com/tsuru/tsuru/service"
_ "github.com/tsuru/tsuru/storage/mongodb"
"gopkg.in/check.v1"
"gopkg.in/mgo.v2/bson"
)
func Test(t *testing.T) {
check.TestingT(t)
}
type S struct {
storage *db.Storage
}
var _ = check.Suite(&S{})
func (s *S) SetUpSuite(c *check.C) {
config.Set("log:disable-syslog", true)
config.Set("database:driver", "mongodb")
config.Set("database:url", "127.0.0.1:27017")
config.Set("database:name", "pool_tests_s")
var err error
s.storage, err = db.Conn()
c.Assert(err, check.IsNil)
}
func (s *S) TearDownSuite(c *check.C) {
s.storage.Apps().Database.DropDatabase()
s.storage.Close()
}
func (s *S) SetUpTest(c *check.C) {
err := dbtest.ClearAllCollections(s.storage.Apps().Database)
c.Assert(err, check.IsNil)
err = auth.CreateTeam("ateam", &auth.User{})
c.Assert(err, check.IsNil)
err = auth.CreateTeam("test", &auth.User{})
c.Assert(err, check.IsNil)
err = auth.CreateTeam("pteam", &auth.User{})
c.Assert(err, check.IsNil)
}
func (s *S) TestAddPool(c *check.C) {
msg := "Invalid pool name, pool name should have at most 63 " +
"characters, containing only lower case letters, numbers or dashes, " +
"starting with a letter."
vErr := &tsuruErrors.ValidationError{Message: msg}
tt := []struct {
name string
expectedErr error
}{
{"pool1", nil},
{"myPool", vErr},
{"my pool", vErr},
{"123mypool", vErr},
{"", ErrPoolNameIsRequired},
{"p", nil},
}
for _, t := range tt {
err := AddPool(AddPoolOptions{Name: t.name})
c.Assert(err, check.DeepEquals, t.expectedErr, check.Commentf("%s", t.name))
if t.expectedErr == nil {
pool, err := GetPoolByName(t.name)
c.Assert(err, check.IsNil, check.Commentf("%s", t.name))
c.Assert(pool, check.DeepEquals, &Pool{Name: t.name}, check.Commentf("%s", t.name))
}
}
}
func (s *S) TestAddNonPublicPool(c *check.C) {
coll := s.storage.Pools()
opts := AddPoolOptions{
Name: "pool1",
Public: false,
Default: false,
}
err := AddPool(opts)
c.Assert(err, check.IsNil)
var p Pool
err = coll.Find(bson.M{"_id": "pool1"}).One(&p)
c.Assert(err, check.IsNil)
constraints, err := getConstraintsForPool("pool1", "team")
c.Assert(err, check.IsNil)
c.Assert(constraints["team"].AllowsAll(), check.Equals, false)
}
func (s *S) TestAddPublicPool(c *check.C) {
coll := s.storage.Pools()
opts := AddPoolOptions{
Name: "pool1",
Public: true,
Default: false,
}
err := AddPool(opts)
c.Assert(err, check.IsNil)
var p Pool
err = coll.Find(bson.M{"_id": "pool1"}).One(&p)
c.Assert(err, check.IsNil)
constraints, err := getConstraintsForPool("pool1", "team")
c.Assert(err, check.IsNil)
c.Assert(constraints["team"].AllowsAll(), check.Equals, true)
}
func (s *S) TestAddPoolWithoutNameShouldBreak(c *check.C) {
opts := AddPoolOptions{
Name: "",
Public: false,
Default: false,
}
err := AddPool(opts)
c.Assert(err, check.NotNil)
c.Assert(err.Error(), check.Equals, "Pool name is required.")
}
func (s *S) TestAddDefaultPool(c *check.C) {
opts := AddPoolOptions{
Name: "pool1",
Public: false,
Default: true,
}
err := AddPool(opts)
c.Assert(err, check.IsNil)
}
func (s *S) TestAddTeamToPoolNotFound(c *check.C) {
err := AddTeamsToPool("notfound", []string{"ateam"})
c.Assert(err, check.Equals, ErrPoolNotFound)
}
func (s *S) TestDefaultPoolCantHaveTeam(c *check.C) {
err := AddPool(AddPoolOptions{Name: "nonteams", Public: false, Default: true})
c.Assert(err, check.IsNil)
err = AddTeamsToPool("nonteams", []string{"ateam"})
c.Assert(err, check.NotNil)
c.Assert(err, check.Equals, ErrPublicDefaultPoolCantHaveTeams)
}
func (s *S) TestDefaultPoolShouldBeUnique(c *check.C) {
err := AddPool(AddPoolOptions{Name: "nonteams", Public: false, Default: true})
c.Assert(err, check.IsNil)
err = AddPool(AddPoolOptions{Name: "pool1", Public: false, Default: true})
c.Assert(err, check.NotNil)
}
func (s *S) TestAddPoolNameShouldBeUnique(c *check.C) {
err := AddPool(AddPoolOptions{Name: "mypool"})
c.Assert(err, check.IsNil)
err = AddPool(AddPoolOptions{Name: "mypool"})
c.Assert(err, check.DeepEquals, ErrPoolAlreadyExists)
}
func (s *S) TestForceAddDefaultPool(c *check.C) {
coll := s.storage.Pools()
opts := AddPoolOptions{
Name: "pool1",
Public: false,
Default: true,
}
err := AddPool(opts)
c.Assert(err, check.IsNil)
opts = AddPoolOptions{
Name: "pool2",
Public: false,
Default: true,
Force: true,
}
err = AddPool(opts)
c.Assert(err, check.IsNil)
var p Pool
err = coll.Find(bson.M{"_id": "pool1"}).One(&p)
c.Assert(err, check.IsNil)
c.Assert(p.Default, check.Equals, false)
err = coll.Find(bson.M{"_id": "pool2"}).One(&p)
c.Assert(err, check.IsNil)
c.Assert(p.Default, check.Equals, true)
}
func (s *S) TestRemovePoolNotFound(c *check.C) {
err := RemovePool("notfound")
c.Assert(err, check.Equals, ErrPoolNotFound)
}
func (s *S) TestRemovePool(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1"}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
err = RemovePool("pool1")
c.Assert(err, check.IsNil)
p, err := coll.FindId("pool1").Count()
c.Assert(err, check.IsNil)
c.Assert(p, check.Equals, 0)
}
func (s *S) TestAddTeamToPool(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1"}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
err = AddTeamsToPool("pool1", []string{"ateam", "test"})
c.Assert(err, check.IsNil)
var p Pool
err = coll.FindId(pool.Name).One(&p)
c.Assert(err, check.IsNil)
teams, err := p.GetTeams()
c.Assert(err, check.IsNil)
sort.Strings(teams)
c.Assert(teams, check.DeepEquals, []string{"ateam", "test"})
}
func (s *S) TestAddTeamToPoolWithTeams(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1"}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
err = AddTeamsToPool(pool.Name, []string{"test", "ateam"})
c.Assert(err, check.IsNil)
err = AddTeamsToPool(pool.Name, []string{"pteam"})
c.Assert(err, check.IsNil)
teams, err := pool.GetTeams()
c.Assert(err, check.IsNil)
sort.Strings(teams)
c.Assert(teams, check.DeepEquals, []string{"ateam", "pteam", "test"})
}
func (s *S) TestAddTeamToPollShouldNotAcceptDuplicatedTeam(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1"}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
err = AddTeamsToPool(pool.Name, []string{"test", "ateam"})
c.Assert(err, check.IsNil)
err = AddTeamsToPool(pool.Name, []string{"ateam"})
c.Assert(err, check.NotNil)
teams, err := pool.GetTeams()
c.Assert(err, check.IsNil)
sort.Strings(teams)
c.Assert(teams, check.DeepEquals, []string{"ateam", "test"})
}
func (s *S) TestAddTeamsToAPublicPool(c *check.C) {
err := AddPool(AddPoolOptions{Name: "nonteams", Public: true})
c.Assert(err, check.IsNil)
err = AddTeamsToPool("nonteams", []string{"ateam"})
c.Assert(err, check.NotNil)
c.Assert(err, check.Equals, ErrPublicDefaultPoolCantHaveTeams)
}
func (s *S) TestAddTeamsToPoolWithBlacklistShouldFail(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1"}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool1", Field: "team", Values: []string{"myteam"}, Blacklist: true})
c.Assert(err, check.IsNil)
err = AddTeamsToPool("pool1", []string{"otherteam"})
c.Assert(err, check.NotNil)
constraint, err := getExactConstraintForPool("pool1", "team")
c.Assert(err, check.IsNil)
c.Assert(constraint.Blacklist, check.Equals, true)
c.Assert(constraint.Values, check.DeepEquals, []string{"myteam"})
}
func (s *S) TestRemoveTeamsFromPoolNotFound(c *check.C) {
err := RemoveTeamsFromPool("notfound", []string{"test"})
c.Assert(err, check.Equals, ErrPoolNotFound)
}
func (s *S) TestRemoveTeamsFromPool(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1"}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
err = AddTeamsToPool(pool.Name, []string{"test", "ateam"})
c.Assert(err, check.IsNil)
teams, err := pool.GetTeams()
c.Assert(err, check.IsNil)
sort.Strings(teams)
c.Assert(teams, check.DeepEquals, []string{"ateam", "test"})
err = RemoveTeamsFromPool(pool.Name, []string{"test"})
c.Assert(err, check.IsNil)
teams, err = pool.GetTeams()
c.Assert(err, check.IsNil)
c.Assert(teams, check.DeepEquals, []string{"ateam"})
}
func (s *S) TestRemoveTeamsFromPoolWithBlacklistShouldFail(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1"}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool1", Field: "team", Values: []string{"myteam"}, Blacklist: true})
c.Assert(err, check.IsNil)
err = RemoveTeamsFromPool("pool1", []string{"myteam"})
c.Assert(err, check.NotNil)
constraint, err := getExactConstraintForPool("pool1", "team")
c.Assert(err, check.IsNil)
c.Assert(constraint.Blacklist, check.Equals, true)
c.Assert(constraint.Values, check.DeepEquals, []string{"myteam"})
}
func boolPtr(v bool) *bool {
return &v
}
func (s *S) TestPoolUpdateNotFound(c *check.C) {
err := PoolUpdate("notfound", UpdatePoolOptions{Public: boolPtr(true)})
c.Assert(err, check.Equals, ErrPoolNotFound)
}
func (s *S) TestPoolUpdate(c *check.C) {
opts := AddPoolOptions{
Name: "pool1",
Public: false,
}
err := AddPool(opts)
c.Assert(err, check.IsNil)
err = PoolUpdate("pool1", UpdatePoolOptions{Public: boolPtr(true)})
c.Assert(err, check.IsNil)
constraint, err := getExactConstraintForPool("pool1", "team")
c.Assert(err, check.IsNil)
c.Assert(constraint.AllowsAll(), check.Equals, true)
}
func (s *S) TestPoolUpdateToDefault(c *check.C) {
opts := AddPoolOptions{
Name: "pool1",
Public: false,
Default: false,
}
err := AddPool(opts)
c.Assert(err, check.IsNil)
err = PoolUpdate("pool1", UpdatePoolOptions{Public: boolPtr(true), Default: boolPtr(true)})
c.Assert(err, check.IsNil)
p, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
c.Assert(p.Default, check.Equals, true)
}
func (s *S) TestPoolUpdateForceToDefault(c *check.C) {
err := AddPool(AddPoolOptions{Name: "pool1", Public: false, Default: true})
c.Assert(err, check.IsNil)
err = AddPool(AddPoolOptions{Name: "pool2", Public: false, Default: false})
c.Assert(err, check.IsNil)
err = PoolUpdate("pool2", UpdatePoolOptions{Public: boolPtr(true), Default: boolPtr(true), Force: true})
c.Assert(err, check.IsNil)
p, err := GetPoolByName("pool2")
c.Assert(err, check.IsNil)
c.Assert(p.Default, check.Equals, true)
}
func (s *S) TestPoolUpdateDefaultAttrFailIfDefaultPoolAlreadyExists(c *check.C) {
err := AddPool(AddPoolOptions{Name: "pool1", Public: false, Default: true})
c.Assert(err, check.IsNil)
err = AddPool(AddPoolOptions{Name: "pool2", Public: false, Default: false})
c.Assert(err, check.IsNil)
err = PoolUpdate("pool2", UpdatePoolOptions{Public: boolPtr(true), Default: boolPtr(true)})
c.Assert(err, check.NotNil)
c.Assert(err, check.Equals, ErrDefaultPoolAlreadyExists)
}
func (s *S) TestPoolUpdateDontHaveSideEffects(c *check.C) {
err := AddPool(AddPoolOptions{Name: "pool1", Public: false, Default: true})
c.Assert(err, check.IsNil)
err = PoolUpdate("pool1", UpdatePoolOptions{Public: boolPtr(true)})
c.Assert(err, check.IsNil)
p, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
c.Assert(p.Default, check.Equals, true)
constraint, err := getExactConstraintForPool("pool1", "team")
c.Assert(err, check.IsNil)
c.Assert(constraint.AllowsAll(), check.Equals, true)
}
func (s *S) TestListPool(c *check.C) {
err := AddPool(AddPoolOptions{Name: "pool1"})
c.Assert(err, check.IsNil)
err = AddPool(AddPoolOptions{Name: "pool2", Default: true})
c.Assert(err, check.IsNil)
err = AddPool(AddPoolOptions{Name: "pool3"})
c.Assert(err, check.IsNil)
pools, err := ListPools("pool1", "pool3")
c.Assert(err, check.IsNil)
c.Assert(len(pools), check.Equals, 2)
c.Assert(pools[0].Name, check.Equals, "pool1")
c.Assert(pools[1].Name, check.Equals, "pool3")
}
func (s *S) TestListPossiblePoolsAll(c *check.C) {
err := AddPool(AddPoolOptions{Name: "pool1", Default: true})
c.Assert(err, check.IsNil)
pools, err := ListPossiblePools(nil)
c.Assert(err, check.IsNil)
c.Assert(pools, check.HasLen, 1)
}
func (s *S) TestListPoolByQuery(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1", Default: true}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
pool2 := Pool{Name: "pool2", Default: true}
err = coll.Insert(pool2)
c.Assert(err, check.IsNil)
pools, err := listPools(bson.M{"_id": "pool2"})
c.Assert(err, check.IsNil)
c.Assert(pools, check.HasLen, 1)
c.Assert(pools[0].Name, check.Equals, "pool2")
}
func (s *S) TestListPoolEmpty(c *check.C) {
pools, err := ListPossiblePools(nil)
c.Assert(err, check.IsNil)
c.Assert(pools, check.HasLen, 0)
}
func (s *S) TestGetPoolByName(c *check.C) {
coll := s.storage.Pools()
pool := Pool{Name: "pool1", Default: true}
err := coll.Insert(pool)
c.Assert(err, check.IsNil)
p, err := GetPoolByName(pool.Name)
c.Assert(err, check.IsNil)
c.Assert(p.Name, check.Equals, pool.Name)
p, err = GetPoolByName("not found")
c.Assert(p, check.IsNil)
c.Assert(err, check.NotNil)
}
func (s *S) TestGetRouters(c *check.C) {
config.Set("routers:router1:type", "hipache")
config.Set("routers:router2:type", "hipache")
defer config.Unset("routers")
err := AddPool(AddPoolOptions{Name: "pool1"})
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router2"}, Blacklist: true})
c.Assert(err, check.IsNil)
pool, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
routers, err := pool.GetRouters()
c.Assert(err, check.IsNil)
c.Assert(routers, check.DeepEquals, []string{"router1"})
pool.Name = "other"
routers, err = pool.GetRouters()
c.Assert(err, check.IsNil)
c.Assert(routers, check.DeepEquals, []string{"router1", "router2"})
}
func (s *S) TestGetServices(c *check.C) {
serv := service.Service{Name: "demacia", Password: "pentakill", Endpoint: map[string]string{"production": "http://localhost:1234"}, OwnerTeams: []string{"ateam"}}
err := serv.Create()
c.Assert(err, check.IsNil)
err = AddPool(AddPoolOptions{Name: "pool1"})
c.Assert(err, check.IsNil)
pool, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
services, err := pool.GetServices()
c.Assert(err, check.IsNil)
c.Assert(services, check.DeepEquals, []string{"demacia"})
}
func (s *S) TestGetDefaultRouterFromConstraint(c *check.C) {
config.Set("routers:router1:type", "hipache")
config.Set("routers:router2:type", "hipache")
defer config.Unset("routers")
err := AddPool(AddPoolOptions{Name: "pool1"})
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router2"}, Blacklist: false})
c.Assert(err, check.IsNil)
pool, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
r, err := pool.GetDefaultRouter()
c.Assert(err, check.IsNil)
c.Assert(r, check.Equals, "router2")
}
func (s *S) TestGetDefaultRouterNoDefault(c *check.C) {
config.Set("routers:router1:type", "hipache")
config.Set("routers:router2:type", "hipache")
defer config.Unset("routers")
err := AddPool(AddPoolOptions{Name: "pool1"})
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"*"}, Blacklist: false})
c.Assert(err, check.IsNil)
pool, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
r, err := pool.GetDefaultRouter()
c.Assert(err, check.Equals, router.ErrDefaultRouterNotFound)
c.Assert(r, check.Equals, "")
}
func (s *S) TestGetDefaultFallbackFromConfig(c *check.C) {
config.Set("routers:router1:type", "hipache")
config.Set("routers:router2:type", "hipache")
config.Set("routers:router2:default", true)
defer config.Unset("routers")
err := AddPool(AddPoolOptions{Name: "pool1"})
c.Assert(err, check.IsNil)
pool, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
r, err := pool.GetDefaultRouter()
c.Assert(err, check.Equals, nil)
c.Assert(r, check.Equals, "router2")
}
func (s *S) TestGetDefaultAllowAllSingleAllowedValue(c *check.C) {
config.Set("routers:router2:type", "hipache")
defer config.Unset("routers")
err := AddPool(AddPoolOptions{Name: "pool1"})
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router*"}, Blacklist: false})
c.Assert(err, check.IsNil)
pool, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
r, err := pool.GetDefaultRouter()
c.Assert(err, check.IsNil)
c.Assert(r, check.Equals, "router2")
}
func (s *S) TestGetDefaultBlacklistSingleAllowedValue(c *check.C) {
config.Set("routers:router1:type", "hipache")
config.Set("routers:router2:type", "hipache")
defer config.Unset("routers")
err := AddPool(AddPoolOptions{Name: "pool1"})
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router2"}, Blacklist: true})
c.Assert(err, check.IsNil)
pool, err := GetPoolByName("pool1")
c.Assert(err, check.IsNil)
r, err := pool.GetDefaultRouter()
c.Assert(err, check.IsNil)
c.Assert(r, check.Equals, "router1")
}
func (s *S) TestPoolAllowedValues(c *check.C) {
config.Set("routers:router:type", "hipache")
config.Set("routers:router1:type", "hipache")
config.Set("routers:router2:type", "hipache")
defer config.Unset("routers")
err := auth.CreateTeam("pubteam", &auth.User{})
c.Assert(err, check.IsNil)
err = auth.CreateTeam("team1", &auth.User{})
c.Assert(err, check.IsNil)
coll := s.storage.Pools()
pool := Pool{Name: "pool1"}
err = coll.Insert(pool)
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "team", Values: []string{"pubteam"}})
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router"}, Blacklist: true})
c.Assert(err, check.IsNil)
err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool1", Field: "team", Values: []string{"team1"}})
c.Assert(err, check.IsNil)
constraints, err := pool.allowedValues()
c.Assert(err, check.IsNil)
c.Assert(constraints, check.DeepEquals, map[string][]string{
"team": {"team1"},
"router": {"router1", "router2"},
"service": nil,
})
pool.Name = "other"
constraints, err = pool.allowedValues()
c.Assert(err, check.IsNil)
c.Assert(constraints, check.HasLen, 3)
sort.Strings(constraints["team"])
c.Assert(constraints["team"], check.DeepEquals, []string{
"ateam", "pteam", "pubteam", "team1", "test",
})
sort.Strings(constraints["router"])
c.Assert(constraints["router"], check.DeepEquals, []string{
"router", "router1", "router2",
})
}
func (s *S) TestRenamePoolTeam(c *check.C) {
coll := s.storage.PoolsConstraints()
constraints := []PoolConstraint{
{PoolExpr: "e1", Field: "router", Values: []string{"t1", "t2"}},
{PoolExpr: "e2", Field: "team", Values: []string{"t1", "t2"}},
{PoolExpr: "e3", Field: "team", Values: []string{"t2", "t3"}},
}
for _, constraint := range constraints {
err := SetPoolConstraint(&constraint)
c.Assert(err, check.IsNil)
}
err := RenamePoolTeam("t2", "t9000")
c.Assert(err, check.IsNil)
var cs []PoolConstraint
err = coll.Find(nil).Sort("poolexpr").All(&cs)
c.Assert(err, check.IsNil)
c.Assert(cs, check.DeepEquals, []PoolConstraint{
{PoolExpr: "e1", Field: "router", Values: []string{"t1", "t2"}},
{PoolExpr: "e2", Field: "team", Values: []string{"t1", "t9000"}},
{PoolExpr: "e3", Field: "team", Values: []string{"t3", "t9000"}},
})
}
| cezarsa/tsuru | provision/pool/pool_test.go | GO | bsd-3-clause | 19,932 |
from tests.modules.ffi.base import BaseFFITest
from rpython.rtyper.lltypesystem import rffi
# Most of the stuff is still very vague.
# This is because lots of the constants had to be set to something in order to
# run some specs but the specs weren't about them.
class TestTypeDefs(BaseFFITest):
def test_it_is_kind_of_a_Hash(self, space):
assert self.ask(space, 'FFI::TypeDefs.kind_of? Hash')
class TestTypes(BaseFFITest):
def test_it_is_kind_of_a_Hash(self, space):
assert self.ask(space, 'FFI::Types.kind_of? Hash')
class TestPlatform(BaseFFITest):
def test_it_is_a_Module(self, space):
assert self.ask(space, "FFI::Platform.is_a? Module")
def test_it_offers_some_SIZE_constants(self, space):
w_res = space.execute('FFI::Platform::INT8_SIZE')
assert space.int_w(w_res) == rffi.sizeof(rffi.CHAR)
w_res = space.execute('FFI::Platform::INT16_SIZE')
assert space.int_w(w_res) == rffi.sizeof(rffi.SHORT)
w_res = space.execute('FFI::Platform::INT32_SIZE')
assert space.int_w(w_res) == rffi.sizeof(rffi.INT)
w_res = space.execute('FFI::Platform::INT64_SIZE')
assert space.int_w(w_res) == rffi.sizeof(rffi.LONGLONG)
w_res = space.execute('FFI::Platform::LONG_SIZE')
assert space.int_w(w_res) == rffi.sizeof(rffi.LONG)
w_res = space.execute('FFI::Platform::FLOAT_SIZE')
assert space.int_w(w_res) == rffi.sizeof(rffi.FLOAT)
w_res = space.execute('FFI::Platform::DOUBLE_SIZE')
assert space.int_w(w_res) == rffi.sizeof(rffi.DOUBLE)
w_res = space.execute('FFI::Platform::ADDRESS_SIZE')
assert space.int_w(w_res) == rffi.sizeof(rffi.VOIDP)
class TestStructLayout(BaseFFITest):
def test_it_is_a_class(self, space):
assert self.ask(space, "FFI::StructLayout.is_a? Class")
def test_its_Field_constant_is_nil(self, space):
assert self.ask(space, "FFI::StructLayout::Field.nil?")
class TestStructByReference(BaseFFITest):
def test_it_is_a_class(self, space):
assert self.ask(space, "FFI::StructByReference.is_a? Class")
class TestNullPointerError(BaseFFITest):
def test_it_inherits_from_Exception(self, space):
assert self.ask(space,
"FFI::NullPointerError.ancestors.include? Exception")
| babelsberg/babelsberg-r | tests/modules/ffi/test_ffi.py | Python | bsd-3-clause | 2,305 |
<?php
/**
* Copyright (c) 2011-present Mediasift Ltd
* 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 names of the copyright holders nor the names of his
* 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.
*
* @category Libraries
* @package Storyplayer/Modules/Types
* @author Thomas Shipley <thomas.shipley@datasift.com>
* @copyright 2011-present Mediasift Ltd www.datasift.com
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://datasift.github.io/storyplayer
*/
namespace Storyplayer\SPv3\Modules\Types;
use Storyplayer\SPv3\Modules\Types;
/**
* A collection of functions for manipulating arrays
*
* Great for testing APIs
*
* @category Libraries
* @package Storyplayer/Modules/Types
* @author Thomas Shipley <thomas.shipley@datasift.com>
* @copyright 2011-present Mediasift Ltd www.datasift.com
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://datasift.github.io/storyplayer
*/
class FromArray extends Prose
{
/**
* Sets a value in an array for a . delimited path
* if the path does not exist it will be added to the array
* @param $array - array to add the value to
* @param $path - the . delimited path to the key of the value to add -
* if path not found key at that path will be created
* @param $val - the value to add
*/
public function setValueInArray(&$array, $path, $val)
{
$pathAsArray = Types::fromString()->splitDotSeparatedPath($path);
for ($i=&$array; $key=array_shift($pathAsArray); $i=&$i[$key]) {
if (!isset($i[$key])) {
$i[$key] = [];
}
}
$i = $val;
}
}
| datasift/storyplayer | src/php/Storyplayer/SPv3/Modules/Types/FromArray.php | PHP | bsd-3-clause | 3,138 |
package com.codewaves.codehighlight.languages;
import com.codewaves.codehighlight.core.Keyword;
import com.codewaves.codehighlight.core.Language;
import com.codewaves.codehighlight.core.Mode;
/**
* Created by Sergej Kravcenko on 5/17/2017.
* Copyright (c) 2017 Sergej Kravcenko
*/
public class BashLanguage implements LanguageBuilder {
private static String[] ALIASES = { "sh", "zsh" };
private static String KEYWORDS = "if then else elif fi for while in do done case esac function";
private static String KEYWORDS_LITERAL = "true false";
private static String KEYWORDS_BUILTIN = "break cd continue eval exec exit export getopts hash pwd readonly return shift test times " +
"trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf " +
"read readarray source type typeset ulimit unalias set shopt " +
"autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles " +
"compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate " +
"fc fg float functions getcap getln history integer jobs kill limit log noglob popd print " +
"pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit " +
"unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof " +
"zpty zregexparse zsocket zstyle ztcp";
private static String KEYWORDS_REL = "-ne -eq -lt -gt -f -d -e -s -l -a";
@Override
public Language build() {
final Mode VAR = new Mode()
.className("variable")
.variants(new Mode[] {
new Mode().begin("\\$[\\w\\d#@][\\w\\d_]*"),
new Mode().begin("\\$\\{(.*?)\\}")
});
final Mode QUOTE_STRING = new Mode()
.className("string")
.begin("\"")
.end("\"")
.contains(new Mode[] {
Mode.BACKSLASH_ESCAPE,
VAR,
new Mode().className("variable")
.begin("\\$\\(")
.end("\\)")
.contains(new Mode[] { Mode.BACKSLASH_ESCAPE })
});
final Mode APOS_STRING = new Mode()
.className("string")
.begin("'")
.end("'");
return (Language) new Language()
.aliases(ALIASES)
.lexemes("\\b-?[a-z\\._]+\\b")
.keywords(new Keyword[] {
new Keyword("keyword", KEYWORDS),
new Keyword("literal", KEYWORDS_LITERAL),
new Keyword("built_in", KEYWORDS_BUILTIN),
new Keyword("_", KEYWORDS_REL)
})
.contains(new Mode[] {
new Mode().className("meta").begin("^#![^\\n]+sh\\s*$").relevance(10),
new Mode()
.className("function")
.begin("\\w[\\w\\d_]*\\s*\\(\\s*\\)\\s*\\{")
.returnBegin()
.contains(new Mode[] { Mode.inherit(Mode.TITLE_MODE, new Mode().begin("\\w[\\w\\d_]*")) })
.relevance(0),
Mode.HASH_COMMENT_MODE,
QUOTE_STRING,
APOS_STRING,
VAR
});
}
}
| Codewaves/Highlight.java | src/main/java/com/codewaves/codehighlight/languages/BashLanguage.java | Java | bsd-3-clause | 3,376 |
<?php
/**
* User: sometimes
* Date: 2016/10/1
* Time: 23:47
*/
namespace backend\models;
use yii\base\Model;
use yii\helpers\FileHelper;
class ImageUpload extends Model
{
//private $imageFile;
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png,jpg'],
];
}
/**
* 用于上传图片
* @param string $filePath 指定图片存放在何处,such as: path/to/image/,Note that:最后需要加上一个 /符号,表示存放目录
* @return bool 上传成功返回 true,上传失败返回false
*/
public function upload($filePath)
{
if(!file_exists($filePath)){
FileHelper::createDirectory($filePath);
}
$fileName = date('YmdHis') . '_'
. rand(111, 999) . '_' . md5($this->imageFile->baseName) . '.' . $this->imageFile->extension;
if ($this->validate()) {
$this->imageFile->saveAs($filePath.$fileName);
return $filePath.$fileName;
} else {
return false;
}
}
} | 419989658/conciseCMS | backend/models/ImageUpload.php | PHP | bsd-3-clause | 1,127 |
<?php
namespace Grocery\Service;
interface productImageServiceInterface {
/**
* Should return a set of all blog posts that we can iterate over. Single entries of the array are supposed to be
* implementing \Blog\Model\PostInterface
*
* @return array|PostInterface[]
*/
public function deleteProductImages($productImages, $product);
/**
* Should return a set of all blog posts that we can iterate over. Single entries of the array are supposed to be
* implementing \Blog\Model\PostInterface
*
* @return array|PostInterface[]
*/
public function deleteImageFile($productImageType);
}
| verzeilberg/boodschappen | module/Grocery/src/Grocery/Service/productImageServiceInterface.php | PHP | bsd-3-clause | 673 |
#include "DesktopViewPlugin.h"
#include <QFileInfo>
#include <QDir>
#include <QClipboard>
#include <QMimeData>
#include <QImageReader>
#include <LuminaXDG.h>
#include "LSession.h"
DesktopViewPlugin::DesktopViewPlugin(QWidget* parent, QString ID) : LDPlugin(parent, ID){
this->setLayout( new QVBoxLayout());
this->layout()->setContentsMargins(0,0,0,0);
list = new QListWidget(this);
list->setViewMode(QListView::IconMode);
list->setFlow(QListWidget::TopToBottom); //Qt bug workaround - need the opposite flow in the widget constructor
list->setWrapping(true);
list->setSpacing(4);
list->setSelectionBehavior(QAbstractItemView::SelectItems);
list->setSelectionMode(QAbstractItemView::ExtendedSelection);
list->setContextMenuPolicy(Qt::CustomContextMenu);
list->setMovement(QListView::Snap); //make sure items are "stuck" in the grid
menu = new QMenu(this);
menu->addAction( LXDG::findIcon("run-build-file",""), tr("Open"), this, SLOT(runItems()) );
menu->addSeparator();
menu->addAction( LXDG::findIcon("edit-cut",""), tr("Cut"), this, SLOT(cutItems()) );
menu->addAction( LXDG::findIcon("edit-copy",""), tr("Copy"), this, SLOT(copyItems()) );
menu->addSeparator();
menu->addAction( LXDG::findIcon("zoom-in",""), tr("Increase Icons"), this, SLOT(increaseIconSize()) );
menu->addAction( LXDG::findIcon("zoom-out",""), tr("Decrease Icons"), this, SLOT(decreaseIconSize()) );
menu->addSeparator();
menu->addAction( LXDG::findIcon("edit-delete",""), tr("Delete"), this, SLOT(deleteItems()) );
menu->addSeparator();
if(LUtils::isValidBinary("lumina-fileinfo")){
menu->addAction( LXDG::findIcon("system-search",""), tr("Properties"), this, SLOT(displayProperties()) );
}
this->layout()->addWidget(list);
connect(QApplication::instance(), SIGNAL(DesktopFilesChanged()), this, SLOT(updateContents()) );
connect(list, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(runItems()) );
connect(list, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showMenu(const QPoint&)) );
QTimer::singleShot(1000,this, SLOT(updateContents()) ); //wait a second before loading contents
}
DesktopViewPlugin::~DesktopViewPlugin(){
}
void DesktopViewPlugin::runItems(){
QList<QListWidgetItem*> sel = list->selectedItems();
for(int i=0; i<sel.length(); i++){
LSession::LaunchApplication("lumina-open \""+sel[i]->whatsThis()+"\"");
}
}
void DesktopViewPlugin::copyItems(){
QList<QListWidgetItem*> sel = list->selectedItems();
if(sel.isEmpty()){ return; } //nothing selected
QStringList items;
//Format the data string
for(int i=0; i<sel.length(); i++){
items << "copy::::"+sel[i]->whatsThis();
}
//Now save that data to the global clipboard
QMimeData *dat = new QMimeData;
dat->clear();
dat->setData("x-special/lumina-copied-files", items.join("\n").toLocal8Bit());
QApplication::clipboard()->clear();
QApplication::clipboard()->setMimeData(dat);
}
void DesktopViewPlugin::cutItems(){
QList<QListWidgetItem*> sel = list->selectedItems();
if(sel.isEmpty()){ return; } //nothing selected
QStringList items;
//Format the data string
for(int i=0; i<sel.length(); i++){
items << "cut::::"+sel[i]->whatsThis();
}
//Now save that data to the global clipboard
QMimeData *dat = new QMimeData;
dat->clear();
dat->setData("x-special/lumina-copied-files", items.join("\n").toLocal8Bit());
QApplication::clipboard()->clear();
QApplication::clipboard()->setMimeData(dat);
}
void DesktopViewPlugin::deleteItems(){
QList<QListWidgetItem*> sel = list->selectedItems();
for(int i=0; i<sel.length(); i++){
if(QFileInfo(sel[i]->whatsThis()).isDir()){
QProcess::startDetached("rm -r \""+sel[i]->whatsThis()+"\"");
}else{
QFile::remove(sel[i]->whatsThis());
}
}
}
void DesktopViewPlugin::showMenu(const QPoint &pos){
//Make sure there is an item underneath the mouse first
if(list->itemAt(pos)!=0){
menu->popup(this->mapToGlobal(pos));
}else{
//Pass the context menu request on to the desktop (emit it from the plugin)
this->showPluginMenu();
//emit OpenDesktopMenu();
}
}
void DesktopViewPlugin::increaseIconSize(){
int icosize = this->readSetting("IconSize",64).toInt();
icosize+=16; //go in orders of 16 pixels
//list->setIconSize(QSize(icosize,icosize));
this->saveSetting("IconSize",icosize);
QTimer::singleShot(10, this, SLOT(updateContents()));
}
void DesktopViewPlugin::decreaseIconSize(){
int icosize = this->readSetting("IconSize",64).toInt();
if(icosize < 20){ return; } //too small to decrease more
icosize-=16; //go in orders of 16 pixels
//list->setIconSize(QSize(icosize,icosize));
this->saveSetting("IconSize",icosize);
QTimer::singleShot(10,this, SLOT(updateContents()));
}
void DesktopViewPlugin::updateContents(){
list->clear();
int icosize = this->readSetting("IconSize",64).toInt();
QSize gridSZ = QSize(qRound(1.8*icosize),icosize+4+(2*this->fontMetrics().height()) );
//qDebug() << "Icon Size:" << icosize <<"Grid Size:" << gridSZ.width() << gridSZ.height();
list->setGridSize(gridSZ);
list->setIconSize(QSize(icosize,icosize));
QDir dir(QDir::homePath()+"/Desktop");
QFileInfoList files = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name | QDir::Type | QDir::DirsFirst);
for(int i=0; i<files.length(); i++){
QListWidgetItem *it = new QListWidgetItem;
it->setSizeHint(gridSZ); //ensure uniform item sizes
//it->setForeground(QBrush(Qt::black, Qt::Dense2Pattern)); //Try to use a font color which will always be visible
it->setTextAlignment(Qt::AlignCenter);
it->setWhatsThis(files[i].absoluteFilePath());
QString txt;
if(files[i].isDir()){
it->setIcon( LXDG::findIcon("folder","") );
txt = files[i].fileName();
}else if(files[i].suffix() == "desktop" ){
bool ok = false;
XDGDesktop desk = LXDG::loadDesktopFile(files[i].absoluteFilePath(), ok);
if(ok){
it->setIcon( LXDG::findIcon(desk.icon,"unknown") );
if(desk.name.isEmpty()){
txt = files[i].fileName();
}else{
txt = desk.name;
}
}else{
//Revert back to a standard file handling
it->setIcon( LXDG::findMimeIcon(files[i].fileName()) );
txt = files[i].fileName();
}
}else if(LUtils::imageExtensions().contains(files[i].suffix().toLower()) ){
it->setIcon( QIcon( QPixmap(files[i].absoluteFilePath()).scaled(icosize,icosize,Qt::IgnoreAspectRatio, Qt::SmoothTransformation) ) );
txt = files[i].fileName();
}else{
it->setIcon( LXDG::findMimeIcon( files[i].fileName() ) );
txt = files[i].fileName();
}
//Add the sym-link overlay to the icon as necessary
if(files[i].isSymLink()){
QImage img = it->icon().pixmap(QSize(icosize,icosize)).toImage();
int oSize = icosize/2; //overlay size
QPixmap overlay = LXDG::findIcon("emblem-symbolic-link").pixmap(oSize,oSize).scaled(oSize,oSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
QPainter painter(&img);
painter.drawPixmap(icosize-oSize,icosize-oSize,overlay); //put it in the bottom-right corner
it->setIcon( QIcon(QPixmap::fromImage(img)) );
}
//Now adjust the visible text as necessary based on font/grid sizing
it->setToolTip(txt);
if(this->fontMetrics().width(txt) > (gridSZ.width()-4) ){
//int dash = this->fontMetrics().width("-");
//Text too long, try to show it on two lines
txt = txt.section(" ",0,2).replace(" ","\n"); //First take care of any natural breaks
if(txt.contains("\n")){
//need to check each line
QStringList txtL = txt.split("\n");
for(int i=0; i<txtL.length(); i++){ txtL[i] = this->fontMetrics().elidedText(txtL[i], Qt::ElideRight, gridSZ.width()-4); }
txt = txtL.join("\n");
if(txtL.length()>2){ txt = txt.section("\n",0,1); } //only keep the first two lines
}else{
txt = this->fontMetrics().elidedText(txt,Qt::ElideRight, 2*(gridSZ.width()-4));
//Now split the line in half for the two lines
txt.insert( (txt.count()/2), "\n");
}
}else{
txt.append("\n "); //ensure two lines (2nd one invisible) - keeps formatting sane
}
it->setText(txt);
list->addItem(it);
if( (i%10) == 0){ QApplication::processEvents(); }//keep the UI snappy, every 10 items
}
list->setFlow(QListWidget::TopToBottom); //To ensure this is consistent - issues with putting it in the constructor
list->update(); //Re-paint the widget after all items are added
}
void DesktopViewPlugin::displayProperties(){
QList<QListWidgetItem*> sel = list->selectedItems();
for(int i=0; i<sel.length(); i++){
LSession::LaunchApplication("lumina-fileinfo \""+sel[i]->whatsThis());
}
}
| krytarowski/lumina | src-qt5/core/lumina-desktop/desktop-plugins/desktopview/DesktopViewPlugin.cpp | C++ | bsd-3-clause | 8,788 |
<?php
namespace app\modules\admcapacitaciones;
class admcapacitacionesModule extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\admcapacitaciones\controllers';
public function init()
{
parent::init();
// custom initialization code goes here
}
}
| programacionav/Proyecto2015 | modules/admcapacitaciones/admcapacitacionesModule.php | PHP | bsd-3-clause | 300 |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model app\modules\aux_planejamento\models\cadastros\Materialconsumo */
$this->title = $model->matcon_cod;
$this->params['breadcrumbs'][] = ['label' => 'Materialconsumos', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="materialconsumo-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->matcon_cod], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->matcon_cod], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'matcon_cod',
'matcon_descricao',
'matcon_tipo',
'matcon_valor',
'matcon_status',
],
]) ?>
</div>
| FernandoMauricio/portal-senac | modules/aux_planejamento/views/cadastros/materialconsumo/view.php | PHP | bsd-3-clause | 1,077 |
<?php
require_once(dirname(__FILE__)."/../include/common.inc.php");
function GetChannel()
{
global $dsql;
$str = "分类:<select name=\"typeid\"><option value=''>--请选择--</option>";
$sql = "select * from #@__nav where pid='0' and isopen='1' and webid='0' and typeid != '10'";
$row = $dsql->getAll($sql);
foreach($row AS $res)
{
$str .= "<option value='" . $res['typeid'] . "'>" . $res['shortname'] . "</option>";
}
$str .= "</select>";
return $str;
}
$select=GetChannel();
?>
<div id="QS">
<form action="<?php echo $GLOBALS['cfg_cmsurl']; ?>/public/question.php" method="post" onSubmit="return SubmitQ();">
<div id="Submit">
<p><span>温馨提示:</span>请把你要问的问题按以下信息进行描述,我们将以最快的速度回复您</p>
<ul class="Submit_bt">
<li style=" height:30px; line-height:30px">
<b class="fl">问题标题:</b>
<input class="text fl" type="text" name="title" id="qtitle" />
<span class="color_f60 hf fl"><?php echo $select; ?></span>
<span class="color_f60 hf fl">*需要及时回复<input name="musttime" type="checkbox" value="1" /></span>
</li>
<li><textarea name="content" cols="" rows="" id="qcontent"></textarea></li>
<li style=" height:30px; line-height:30px" class="fl">
<span class="fl">联系人:</span>
<input class="text1 fl" type="text" name="leavename" id="qusername" />
<span class="fl">匿名:<input class="nimi" name="noname" type="checkbox" id="noname" value="0" /></span>
<span class="yzm fl">验证码:<img src= "<?php echo $GLOBALS['cfg_cmsurl']; ?>/include/vdimgck.php" style="cursor:pointer" onclick="this.src=this.src+'?'" title="点击我更换图片" alt="点击我更换图片" /></span>
<input class="text2 fl" type="text" name="validate" id="validate" /><span class="color_46 fl">请输入图片上的预算结果</span>
</li>
</ul>
<ul class="contact">
<li class="lx"><b>您的联系方式:</b>(方便客服人员及时联系为您解答疑问)</li>
<li class="fl fs"><span>电话:</span><input class="text" type="text" name="telephone" id="telephone" /></li>
<li class="fl fs"><span>邮箱:</span><input class="text" type="text" name="email" id="email" /></li>
<li class="fl fs"><span>Q Q:</span><input class="text" type="text" name="qq" id="qq" /></li>
<li class="fl fs"><span>MSN:</span><input class="text" type="text" name="msn" id="msn" /></li>
<li class="fl fs"><input class="button_2" type="submit" name="anniu" value="提交问题" /></li>
</ul>
</div>
</form>
</div>
| lz1988/stourwebcms | questions/ask.php | PHP | bsd-3-clause | 2,695 |
from django_sqlalchemy.test import *
from apps.blog.models import Category
class TestContains(object):
def setup(self):
Category.__table__.insert().execute({'name': 'Python'},
{'name': 'PHP'}, {'name': 'Ruby'}, {'name': 'Smalltalk'},
{'name': 'CSharp'}, {'name': 'Modula'}, {'name': 'Algol'},
{'name': 'Forth'}, {'name': 'Pascal'})
@fails_on('sqlite')
def test_should_contain_string_in_name(self):
assert 4 == Category.objects.filter(name__contains='a').count()
assert 1 == Category.objects.filter(name__contains='A').count()
@fails_on_everything_except('sqlite')
def test_should_contain_string_in_name_on_sqlite(self):
assert 5 == Category.objects.filter(name__contains='a').count()
assert 5 == Category.objects.filter(name__contains='A').count()
def test_should_contain_string_in_name_regardless_of_case(self):
assert 5 == Category.objects.filter(name__icontains='a').count()
assert 5 == Category.objects.filter(name__icontains='A').count()
def test_should_contain_string_at_beginning(self):
category = Category.objects.filter(name__contains='Sma')
assert 1 == category.count()
assert_equal(u'Smalltalk', category[0].name)
def test_should_contain_string_at_end(self):
category = Category.objects.filter(name__contains='arp')
assert 1 == category.count()
assert_equal(u'CSharp', category[0].name)
| brosner/django-sqlalchemy | tests/query/test_contains.py | Python | bsd-3-clause | 1,486 |
<?php
if (!isset($border)) {
$border = false;
}
if (!isset($button)) {
$button = false;
}
?>
<div class="container best-projects">
<div class="row">
<a href="/advert/create" class="create-best-project">
Реклама по<br/> доступной цене
</a>
</div>
<div id="carousel-prev" class="carousel-btn"></div>
<div id="carousel-next" class="carousel-btn"></div>
<div id="owl-best-projects" class="row owl-carousel owl-theme<?= $border ? " border" : "" ?>">
<?php
foreach (\common\models\Post::find()->where(["active" => true, "status_id" => \common\models\AdvertStatus::STATUS_ACTIVE])->orderBy("date DESC")->limit(20)->all() as $post) {
?>
<div class="item" data-id="<?= $post->id ?>">
<a href="<?= $post->url ?>" target="_blank"><div class="post-img"><?= $post->photoFile ? '<img src="'. $post->photoFile->getUrl(178, 103, true) .'" />' : '' ?></div>
<h4><?= \yii\bootstrap\Html::encode($post->name) ?></h4>
<p><?= \yii\bootstrap\Html::encode($post->description) ?></p></a>
</div>
<?php } ?>
</div>
<?php /*if ($button) : */?><!--
<div class="row" style="text-align: center;">
<a href="/competition/create" class="btn btn-success btn-lg">Создать конкурс бесплатно</a>
</div>
--><?php /*endif; */?>
</div> | syrexby/repostni | frontend/views/layouts/_advert.php | PHP | bsd-3-clause | 1,439 |
export const SET_SEARCHED_POKEMONS = "SET_SEARCHED_POKEMONS";
export const SET_SEARCHED_QUERY = "SET_SEARCHED_QUERY";
export const SET_SEARCHED_TYPE = "SET_SEARCHED_TYPE";
export const RESET_SEARCHED_PARAMS = "RESET_SEARCHED_PARAMS";
export const RESET_SEARCHED_POKEMONS = "RESET_SEARCHED_POKEMONS";
export const REMOVE_SEARCHED_PARAMS_TYPE = "REMOVE_SEARCHED_PARAMS_TYPE";
| esgiprojetninja/ninjaPokedex | public/js/lib/pokedex/actions/pokeSearchTypes.js | JavaScript | bsd-3-clause | 374 |
<?php
namespace Gaia\ShortCircuit;
/**
* A utility class designed to convert names into file paths for actions and views.
*/
class Resolver implements Iface\Resolver
{
protected $appdir = '';
const param_match = '#\\\\\(([a-z0-9_\-]+)\\\\\)#iu';
protected $urls = array();
public function __construct( $dir = '', array $urls = null ){
$this->appdir = $dir;
if( $urls ) $this->setUrls( $urls );
}
/**
* convert a URI string into an action.
*/
public function match( $uri, & $args ){
$args = array();
if( $this->urls ){
$buildRegex = function ( $pattern ){
$params = array();
$regex = preg_replace_callback(Resolver::param_match, function($match) use ( &$params ) {
$params[] = $match[1];
// only exclude line breaks from my match. this will let utf-8 sequences through.
// older patterns below.
// turns out I don't need to be super strict on my pattern matching.
// php sapi does most of the work for me in giving me the url.
return '([^\n]+)';
//return '([[:graph:][:space:]]+)';
//return '([a-z0-9\.+\,\;\'\\\&%\$\#\=~_\-%\s\"\{\}/\:\(\)\[\]]+)';
}, preg_quote($pattern, '#'));
return array('#^' . $regex . '$#i', $params );
};
foreach( $this->urls as $pattern => $action ){
list( $regex, $params ) = $buildRegex( $pattern );
if( ! preg_match( $regex, $uri, $matches ) ) continue;
$a = array_slice($matches, 1);
foreach( $a as $i=>$v ){
$args[ $params[$i] ] = $v;
}
return $action;
}
}
$uri = strtolower(trim( $uri, '/'));
if( ! $uri ) $uri = 'index';
$res = $this->get( $uri, 'action', TRUE);
if( $res ) return $uri;
return '';
}
public function link( $name, array $params = array() ){
$s = new \Gaia\Serialize\QueryString;
$args = array();
if( $this->urls ){
$createLink = function( $pattern, array & $params ) use( $s ) {
$url = preg_replace_callback(Resolver::param_match, function($match) use ( & $params, $s ) {
if( ! array_key_exists( $match[1], $params ) ) return '';
$ret = $s->serialize($params[ $match[1] ]);
unset( $params[ $match[1] ] );
return $ret;
}, preg_quote($pattern, '#'));
return $url;
};
$match = FALSE;
foreach( $this->urls as $pattern => $a ){
if( $a == $name ){
$match = TRUE;
break;
}
}
if( $match ) {
$url = $createLink( $pattern, $params );
$qs = $s->serialize($params);
if( $qs ) $qs = '?' . $qs;
return $url . $qs;
}
}
$p = array();
foreach( $params as $k => $v ){
if( is_int( $k ) ){
$args[ $k ] = $s->serialize($v);
} else {
$p[ $k ] = $v;
}
}
$params = $s->serialize($p);
if( $params ) $params = '?' . $params;
return '/' . $name . '/' . implode('/', $args ) . $params;
}
/**
* convert a name into a file path.
*/
public function get($name, $type, $skip_lower = FALSE ) {
if( ! $skip_lower ) $name = strtolower($name);
if( strlen( $name ) < 1 ) $name = 'index';
$path = $this->appdir . $name . '.' . $type . '.php';
if( ! file_exists( $path ) ) return '';
return $path;
}
public function appdir(){
return $this->appdir;
}
public function setAppDir( $dir ){
return $this->appdir = $dir;
}
public function addURL( $pattern, $action ){
$this->urls[ '/' . trim($pattern, '/') ] = $action;
}
public function setURLS( array $urls ){
$this->urls = array();
foreach( $urls as $pattern => $action ) {
$this->addURL( $pattern, $action );
}
}
public function urls(){
return $this->urls;
}
}
// EOF | Gaia-Interactive/gaia_core_php | lib/gaia/shortcircuit/resolver.php | PHP | bsd-3-clause | 4,536 |
'''
script @ mandrewcito
'''
import cv2
import numpy as np
import sys
def callback(x):
x = cv2.getTrackbarPos('Kernel X','image')
y = cv2.getTrackbarPos('Kernel Y','image')
sigma = cv2.getTrackbarPos('sigma/100','image')
img =cv2.GaussianBlur(imgOrig,(x,y),sigma/100.0)
cv2.imshow('image',img)
# Get the total number of args passed to the demo.py
total = len(sys.argv)
# Get the arguments list
cmdargs = str(sys.argv)
cv2.namedWindow('image',cv2.CV_WINDOW_AUTOSIZE)
# create trackbars for color change
cv2.createTrackbar('Kernel X','image',1,100,callback)
cv2.createTrackbar('Kernel Y','image',1,100,callback)
cv2.createTrackbar('sigma/100','image',0,1000,callback)
imgOrig = cv2.imread(sys.argv[1])
img=imgOrig
cv2.startWindowThread()
cv2.imshow('image',img)
cv2.waitKey(0) & 0xFF
cv2.destroyAllWindows()
| mandrewcito/EOpenCV | scriptExamples/gaussianFilter.py | Python | bsd-3-clause | 826 |
<?php
/*
$Rev: 373 $ | $LastChangedBy: nate $
$LastChangedDate: 2008-01-04 12:54:39 -0700 (Fri, 04 Jan 2008) $
+-------------------------------------------------------------------------+
| Copyright (c) 2004 - 2007, Kreotek LLC |
| 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 Kreotek LLC nor the names of its contributore 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. |
| |
+-------------------------------------------------------------------------+
*/
require("../../../include/session.php");
class totalReport{
var $selectcolumns;
var $selecttable;
var $whereclause="";
var $group="";
var $showinvoices=false;
var $showlineitems=false;
var $padamount=20;
function totalReport($db,$variables = NULL){
$this->db = $db;
// first we define the available groups
$this->addGroup("Invoice ID","invoices.id"); //0
$this->addGroup("Product","concat(products.partnumber,' - ',products.partname)"); //1
$this->addGroup("Product Category","concat(productcategories.id,' - ',productcategories.name)",NULL,"INNER JOIN productcategories ON products.categoryid=productcategories.id"); //2
$this->addGroup("Invoice Date - Year","YEAR(invoices.invoicedate)"); //3
$this->addGroup("Invoice Date - Quarter","QUARTER(invoices.invoicedate)"); //4
$this->addGroup("Invoice Date - Month","MONTH(invoices.invoicedate)"); //5
$this->addGroup("Invoice Date","invoices.invoicedate","date"); //6
$this->addGroup("Order Date - Year","YEAR(invoices.orderdate)"); //7
$this->addGroup("Order Date - Quarter","QUARTER(invoices.orderdate)");//8
$this->addGroup("Order Date - Month","MONTH(invoices.orderdate)");//9
$this->addGroup("Order Date","invoices.orderdate","date");//10
$this->addGroup("Client","if(clients.lastname!='',concat(clients.lastname,', ',clients.firstname,if(clients.company!='',concat(' (',clients.company,')'),'')),clients.company)");//11
$this->addGroup("Client Sales Person","concat(salesPerson.firstname,' ',salesPerson.lastname)",NULL, "LEFT JOIN users AS salesPerson ON clients.salesmanagerid = salesPerson.id");//12
$this->addGroup("Client Lead Source","clients.leadsource");//13
$this->addGroup("Invoice Lead Source","invoices.leadsource");//14
$this->addGroup("Payment Method","paymentmethods.name");//15
$this->addGroup("Shipping Method","shippingmethods.name");//16
$this->addGroup("Invoice Shipping Country","invoices.country");//17
$this->addGroup("Invoice Shipping State / Province","invoices.state");//18
$this->addGroup("Invoice Shipping Postal Code","invoices.postalcode");//19
$this->addGroup("Invoice Shipping City","invoices.city");//20
$this->addGroup("Web Order","invoices.weborder","boolean");//21
//next we do the columns
$this->addColumn("Record Count","count(lineitems.id)");//0
$this->addColumn("Extended Price","sum(lineitems.unitprice*lineitems.quantity)","currency");//1
$this->addColumn("Average Extended Price","avg(lineitems.unitprice*lineitems.quantity)","currency");//2
$this->addColumn("Unit Price","sum(lineitems.unitprice)","currency");//3
$this->addColumn("Average Unit Price","avg(lineitems.unitprice)","currency");//4
$this->addColumn("Quantity","sum(lineitems.quantity)","real");//5
$this->addColumn("Average Quantity","avg(lineitems.quantity)","real");//6
$this->addColumn("Unit Cost","sum(lineitems.unitcost)","currency");//7
$this->addColumn("Average Unit Cost","avg(lineitems.unitcost)","currency");//8
$this->addColumn("Extended Cost","sum(lineitems.unitcost*lineitems.quantity)","currency");//9
$this->addColumn("Average Extended Cost","avg(lineitems.unitcost*lineitems.quantity)","currency");//10
$this->addColumn("Unit Weight","sum(lineitems.unitweight)","real");//11
$this->addColumn("Average Unit Weight","avg(lineitems.unitweight)","real");//12
$this->addColumn("Extended Unit Weight","sum(lineitems.unitweight*lineitems.quantity)","real");//13
$this->addColumn("Extended Average Unit Weight","avg(lineitems.unitweight*lineitems.quantity)","real");//14
if($variables){
$tempArray = explode("::", $variables["columns"]);
foreach($tempArray as $id)
$this->selectcolumns[] = $this->columns[$id];
$this->selectcolumns = array_reverse($this->selectcolumns);
//change
$this->selecttable="(((((lineitems left join products on lineitems.productid=products.id)
inner join invoices on lineitems.invoiceid=invoices.id)
inner join clients on invoices.clientid=clients.id)
LEFT JOIN shippingmethods ON shippingmethods.name=invoices.shippingmethodid)
LEFT JOIN paymentmethods ON paymentmethods.name=invoices.paymentmethodid)
";
if($variables["groupings"] !== ""){
$this->group = explode("::",$variables["groupings"]);
$this->group = array_reverse($this->group);
} else
$this->group = array();
foreach($this->group as $grp){
if($this->groupings[$grp]["table"])
$this->selecttable="(".$this->selecttable." ".$this->groupings[$grp]["table"].")";
}
$this->whereclause=$_SESSION["printing"]["whereclause"];
if($this->whereclause=="") $this->whereclause="WHERE invoices.id!=-1";
switch($variables["showwhat"]){
case "invoices":
$this->showinvoices = true;
$this->showlineitems = false;
break;
case "lineitems":
$this->showinvoices = true;
$this->showlineitems = true;
break;
default:
$this->showinvoices = false;
$this->showlineitems = false;
}// endswitch
if($this->whereclause!="") $this->whereclause=" WHERE (".substr($this->whereclause,6).") ";
}// endif
}//end method
function addGroup($name, $field, $format = NULL, $tableAddition = NULL){
$temp = array();
$temp["name"] = $name;
$temp["field"] = $field;
$temp["format"] = $format;
$temp["table"] = $tableAddition;
$this->groupings[] = $temp;
}//end method
function addColumn($name, $field, $format = NULL){
$temp = array();
$temp["name"] = $name;
$temp["field"] = $field;
$temp["format"] = $format;
$this->columns[] = $temp;
}//end method
function showReportTable(){
?><table border="0" cellspacing="0" cellpadding="0">
<tr>
<th> </th>
<?php
foreach($this->selectcolumns as $thecolumn){
?><th align="right"><?php echo $thecolumn["name"]?></th><?php
}//end foreach
?>
</tr>
<?php $this->showGroup($this->group,"",10);?>
<?php $this->showGrandTotals();?>
</table>
<?php
}
function showGrandTotals(){
$querystatement="SELECT ";
foreach($this->selectcolumns as $thecolumn)
$querystatement.=$thecolumn["field"]." AS `".$thecolumn["name"]."`,";
$querystatement.=" count(lineitems.id) as thecount ";
$querystatement.=" FROM ".$this->selecttable.$this->whereclause;
$queryresult=$this->db->query($querystatement);
$therecord=$this->db->fetchArray($queryresult);
?>
<tr>
<td class="grandtotals" align="right">Totals: (<?php echo $therecord["thecount"]?>)</td>
<?php
foreach($this->selectcolumns as $thecolumn){
?><td align="right" class="grandtotals"><?php echo formatVariable($therecord[$thecolumn["name"]],$thecolumn["format"])?></td><?php
}//end foreach
?>
</tr>
<?php
}
function showGroup($group,$where,$indent){
if(!$group){
if($this->showlineitems)
$this->showLineItems($where,$indent+$this->padamount);
} else {
$groupby = array_pop($group);
$querystatement="SELECT ";
foreach($this->selectcolumns as $thecolumn)
$querystatement.=$thecolumn["field"]." AS `".$thecolumn["name"]."`,";
$querystatement .= $this->groupings[$groupby]["field"]." AS thegroup, count(lineitems.id) as thecount ";
$querystatement .= " FROM ".$this->selecttable.$this->whereclause.$where." GROUP BY ".$this->groupings[$groupby]["field"];
$queryresult=$this->db->query($querystatement);
while($therecord=$this->db->fetchArray($queryresult)){
$showbottom=true;
if($group or $this->showinvoices) {
$showbottom=false;
?>
<tr><td colspan="<?php echo (count($this->selectcolumns)+1)?>" class="group" style="padding-left:<?php echo ($indent+2)?>px;"><?php echo $this->groupings[$groupby]["name"].": <strong>".formatVariable($therecord["thegroup"],$this->groupings[$groupby]["format"])."</strong>"?> </td></tr>
<?php
}//endif
if($group) {
$whereadd = $where." AND (".$this->groupings[$groupby]["field"]."= \"".$therecord["thegroup"]."\"";
if(!$therecord["thegroup"])
$whereadd .= " OR ISNULL(".$this->groupings[$groupby]["field"].")";
$whereadd .= ")";
$this->showGroup($group,$whereadd,$indent+$this->padamount);
} elseif($this->showlineitems) {
if($therecord["thegroup"])
$this->showLineItems($where." AND (".$this->groupings[$groupby]["field"]."= \"".$therecord["thegroup"]."\")",$indent+$this->padamount);
else
$this->showLineItems($where." AND (".$this->groupings[$groupby]["field"]."= \"".$therecord["thegroup"]."\" or isnull(".$this->groupings[$groupby]["field"].") )",$indent+$this->padamount);
}//endif
?>
<tr>
<td width="100%" style=" <?php
echo "padding-left:".($indent+2)."px";
?>" class="groupFooter">
<?php echo $this->groupings[$groupby]["name"].": <strong>".formatVariable($therecord["thegroup"],$this->groupings[$groupby]["format"])."</strong> ";?>
</td>
<?php
foreach($this->selectcolumns as $thecolumn){
?><td align="right" class="groupFooter"><?php echo formatVariable($therecord[$thecolumn["name"]],$thecolumn["format"])?></td><?php
}//end foreach
?>
</tr>
<?php
}//end while
}//endif
}//end function
function showLineItems($where,$indent){
$querystatement="SELECT lineitems.invoiceid,
if(clients.lastname!=\"\",concat(clients.lastname,\", \",clients.firstname,if(clients.company!=\"\",concat(\" (\",clients.company,\")\"),\"\")),clients.company) as thename,
invoices.invoicedate, invoices.orderdate,
lineitems.id,products.partnumber,products.partname,quantity,lineitems.unitprice,quantity*lineitems.unitprice as extended
FROM ".$this->selecttable.$this->whereclause.$where." GROUP BY lineitems.id ";
$queryresult=$this->db->query($querystatement);
if($this->db->numRows($queryresult)){
?>
<tr><td class="invoices" style="padding-left:<?php echo ($indent+2)?>px;">
<table border="0" cellspacing="0" cellpadding="0" id="lineitems">
<tr>
<th align="left">id</th>
<th align="left">date</th>
<th width="20%" align="left" >client</th>
<th width="60%" align="left">product</th>
<th width="9%" align="right" nowrap="nowrap">price</th>
<th width="8%" align="right" nowrap="nowrap">qty.</th>
<th width="7%" align="right" nowrap="nowrap">ext.</th>
</tr>
<?php
while($therecord=$this->db->fetchArray($queryresult)){
?>
<tr>
<td nowrap="nowrap"><?php echo $therecord["invoiceid"]?></td>
<td nowrap="nowrap"><?php if($therecord["invoicedate"]) echo formatFromSQLDate($therecord["invoicedate"]); else echo "<strong>".formatFromSQLDate($therecord["orderdate"])."</strong>";?></td>
<td><?php echo $therecord["thename"]?></td>
<td width="60%" nowrap="nowrap"><?php echo $therecord["partnumber"]?> <?php echo $therecord["partname"]?></td>
<td width="9%" align="right" nowrap="nowrap"><?php echo numberToCurrency($therecord["unitprice"])?></td>
<td width="8%" align="center" nowrap="nowrap"><?php echo formatVariable($therecord["quantity"],"real")?></td>
<td width="7%" align="right" nowrap="nowrap"><?php echo numberToCurrency($therecord["extended"])?></td>
</tr>
<?php
}// endwhile
?></table></td>
<?php
for($i=1;$i < count($this->selectcolumns); $i++)
echo "<td> </td>"
?>
</tr><?php
}// endif
}//end method
function showReport(){
if($_POST["reporttitle"])
$pageTitle = $_POST["reporttitle"];
else
$pageTitle = "Line Item Totals";
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo APP_PATH ?>common/stylesheet/<?php echo STYLESHEET ?>/pages/totalreports.css" rel="stylesheet" type="text/css" />
<title><?php echo $pageTitle?></title>
</head>
<body>
<div id="toprint">
<h1><span><?php echo $pageTitle?></span></h1>
<h2>Source: <?php echo $_SESSION["printing"]["dataprint"]?></h2>
<h2>Date: <?php echo dateToString(mktime())." ".timeToString(mktime())?></h2>
<?php $this->showReportTable();?>
</div>
</body>
</html><?php
}// end method
function showOptions($what){
?><option value="0">----- Choose One -----</option>
<?php
$i=0;
foreach($this->$what as $value){
?><option value="<?php echo $i+1; ?>"><?php echo $value["name"];?></option>
<?php
$i++;
}// endforeach
}//end mothd
function showSelectScreen(){
global $phpbms;
$pageTitle="Line Items Total";
$phpbms->showMenu = false;
$phpbms->cssIncludes[] = "pages/totalreports.css";
$phpbms->jsIncludes[] = "modules/bms/javascript/totalreports.js";
include("header.php");
?>
<div class="bodyline">
<h1>Line Items Total Options</h1>
<form id="GroupForm" action="<?php echo $_SERVER["PHP_SELF"]?>" method="post" name="GroupForm">
<fieldset>
<legend>report</legend>
<p>
<label for="reporttitle">report title</label><br />
<input type="text" name="reporttitle" id="reporttitle" size="45"/>
</p>
</fieldset>
<fieldset>
<legend>groupings</legend>
<input id="groupings" type="hidden" name="groupings"/>
<div id="theGroups">
<div id="Group1">
<select id="Group1Field">
<?php $this->showOptions("groupings")?>
</select>
<button type="button" id="Group1Minus" class="graphicButtons buttonMinusDisabled"><span>-</span></button>
<button type="button" id="Group1Plus" class="graphicButtons buttonPlus"><span>+</span></button>
</div>
</div>
</fieldset>
<fieldset>
<legend>columns</legend>
<input id="columns" type="hidden" name="columns"/>
<div id="theColumns">
<div id="Column1">
<select id="Column1Field">
<?php $this->showOptions("columns")?>
</select>
<button type="button" id="Column1Minus" class="graphicButtons buttonMinusDisabled"><span>-</span></button>
<button type="button" id="Column1Plus" class="graphicButtons buttonPlus"><span>+</span></button>
</div>
</div>
</fieldset>
<fieldset>
<legend>Options</legend>
<p>
<label for="showwhat">information shown</label><br />
<select name="showwhat" id="showwhat">
<option selected="selected" value="totals">Totals Only</option>
<option value="invoices">Invoices</option>
<option value="lineitems">Invoices & Line Items</option>
</select>
</p>
</fieldset>
<p align="right">
<button id="print" type="button" class="Buttons">Print</button>
<button id="cancel" type="button" class="Buttons">Cancel</button>
</p>
</form>
</div>
<?php
include("footer.php");
}//end method
}//end class
// Processing ===================================================================================================================
if(!isset($dontProcess)){
if(isset($_POST["columns"])){
$myreport= new totalReport($db,$_POST);
$myreport->showReport();
} else {
$myreport = new totalReport($db);
$myreport->showSelectScreen();
}
}?> | eandbsoftware/phpbms | modules/bms/report/lineitems_totals.php | PHP | bsd-3-clause | 18,530 |
describe("go.components.actions", function() {
var actions = go.components.actions;
var Model = go.components.models.Model;
var testHelpers = go.testHelpers,
assertRequest = testHelpers.rpc.assertRequest,
response = testHelpers.rpc.response,
noElExists = testHelpers.noElExists,
oneElExists = testHelpers.oneElExists;
describe("PopoverNotifierView", function() {
var ActionView = actions.ActionView,
PopoverNotifierView = actions.PopoverNotifierView;
var action,
notifier;
beforeEach(function() {
action = new ActionView({name: 'Crimp'});
action.$el.appendTo($('body'));
notifier = new PopoverNotifierView({
delay: 0,
busyWait: 0,
action: action,
bootstrap: {
container: 'body',
animation: false
}
});
sinon.stub(
JST,
'components_notifiers_popover_busy',
function() { return 'busy'; });
});
afterEach(function() {
JST.components_notifiers_popover_busy.restore();
action.remove();
notifier.remove();
});
describe("when the action is invoked", function() {
it("should show a notification", function() {
assert(noElExists('.popover'));
assert.equal(notifier.$el.text(), '');
action.trigger('invoke');
assert(oneElExists('.popover'));
assert.equal(notifier.$el.text(), 'busy');
});
it("set the appropriate class name on the popover element", function() {
var $popover = notifier.popover.tip();
assert(!$popover.hasClass('notifier'));
assert(!$popover.hasClass('success'));
assert(!$popover.hasClass('error'));
assert(!$popover.hasClass('info'));
action.trigger('invoke');
assert(!$popover.hasClass('success'));
assert(!$popover.hasClass('error'));
assert($popover.hasClass('notifier'));
assert($popover.hasClass('info'));
});
});
describe("when the action is successful", function() {
beforeEach(function() {
action.trigger('invoke');
});
it("should show a notification", function() {
action.trigger('success');
assert.include(notifier.$el.text(), 'Crimp successful.');
});
it("set the appropriate class name on the popover element", function() {
var $popover = notifier.popover.tip();
assert(!$popover.hasClass('success'));
assert(!$popover.hasClass('error'));
assert($popover.hasClass('notifier'));
assert($popover.hasClass('info'));
action.trigger('success');
assert(!$popover.hasClass('error'));
assert(!$popover.hasClass('info'));
assert($popover.hasClass('notifier'));
assert($popover.hasClass('success'));
});
});
describe("when the action is unsuccessful", function() {
beforeEach(function() {
action.trigger('invoke');
});
it("should show a notification", function() {
action.trigger('error');
assert.include(notifier.$el.text(), 'Crimp failed.');
});
it("set the appropriate class name on the popover element", function() {
var $popover = notifier.popover.tip();
assert(!$popover.hasClass('success'));
assert(!$popover.hasClass('error'));
assert($popover.hasClass('notifier'));
assert($popover.hasClass('info'));
action.trigger('error');
assert(!$popover.hasClass('success'));
assert(!$popover.hasClass('info'));
assert($popover.hasClass('notifier'));
assert($popover.hasClass('error'));
});
});
describe("when '.close' is clicked", function() {
beforeEach(function() {
action.trigger('success');
});
it("should close the popover", function() {
assert(oneElExists('.popover'));
notifier.$('.close').click();
assert(noElExists('.popover'));
});
});
});
describe("ActionView", function() {
var ActionView = actions.ActionView;
var ToyActionView = ActionView.extend({
invoke: function() { this.trigger('invoke'); }
});
var action;
beforeEach(function() {
action = new ToyActionView();
});
describe("when it is clicked", function() {
it("should invoke its own action", function(done) {
action.on('invoke', function() { done(); });
action.$el.click();
});
});
});
describe("SaveActionView", function() {
var SaveActionView = actions.SaveActionView;
var ToyModel = Model.extend({
url: '/test',
methods: {
create: {method: 's', params: ['a', 'b']}
}
});
var action;
beforeEach(function() {
action = new SaveActionView({
model: new ToyModel({a: 'foo', b: 'bar'})
});
});
describe(".invoke", function() {
var server;
beforeEach(function() {
server = sinon.fakeServer.create();
});
afterEach(function() {
server.restore();
});
it("should emit an 'invoke' event", function(done) {
action.on('invoke', function() { done(); });
action.invoke();
});
it("should send its model's data to the server", function(done) {
server.respondWith(function(req) {
assertRequest(req, '/test', 's', ['foo', 'bar']);
done();
});
action.invoke();
server.respond();
});
describe("when the request is successful", function() {
it("should emit a 'success' event", function(done) {
action.on('success', function() { done(); });
server.respondWith(response());
action.invoke();
server.respond();
});
});
describe("when the request is not successful", function() {
it("should emit a 'failure' event", function(done) {
action.on('error', function() { done(); });
server.respondWith([400, {}, '']);
action.invoke();
server.respond();
});
});
});
});
describe("ResetActionView", function() {
var ResetActionView = actions.ResetActionView;
var action;
beforeEach(function() {
action = new ResetActionView({
model: new Model({a: 'foo', b: 'bar'})
});
});
describe(".invoke", function() {
it("should emit an 'invoke' event", function(done) {
action.on('invoke', function() { done(); });
action.invoke();
});
it("should reset its model to its initial state", function(done) {
action.model.set('a', 'larp');
assert.deepEqual(action.model.toJSON(), {a: 'larp', b: 'bar'});
action.invoke();
action.once('success', function() {
assert.deepEqual(action.model.toJSON(), {a: 'foo', b: 'bar'});
done();
});
});
});
});
});
| praekelt/vumi-go | go/base/static/js/test/components/actions.test.js | JavaScript | bsd-3-clause | 6,932 |
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2014, PostgreSQL Global Development Group
*
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc2;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.*;
import java.nio.charset.Charset;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.TimeZone;
import java.util.Calendar;
import org.postgresql.Driver;
import org.postgresql.largeobject.*;
import org.postgresql.core.*;
import org.postgresql.core.types.*;
import org.postgresql.util.ByteConverter;
import org.postgresql.util.HStoreConverter;
import org.postgresql.util.PGBinaryObject;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.PGobject;
import org.postgresql.util.GT;
/**
* This class defines methods of the jdbc2 specification.
* The real Statement class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Statement
*/
public abstract class AbstractJdbc2Statement implements BaseStatement
{
// only for testing purposes. even single shot statements will use binary transfers
private boolean forceBinaryTransfers = Boolean.getBoolean("org.postgresql.forceBinary");
protected ArrayList batchStatements = null;
protected ArrayList batchParameters = null;
protected final int resultsettype; // the resultset type to return (ResultSet.TYPE_xxx)
protected final int concurrency; // is it updateable or not? (ResultSet.CONCUR_xxx)
protected int fetchdirection = ResultSet.FETCH_FORWARD; // fetch direction hint (currently ignored)
private volatile TimerTask cancelTimerTask = null;
/**
* Does the caller of execute/executeUpdate want generated keys for this
* execution? This is set by Statement methods that have generated keys
* arguments and cleared after execution is complete.
*/
protected boolean wantsGeneratedKeysOnce = false;
/**
* Was this PreparedStatement created to return generated keys for every
* execution? This is set at creation time and never cleared by
* execution.
*/
public boolean wantsGeneratedKeysAlways = false;
// The connection who created us
protected BaseConnection connection;
/** The warnings chain. */
protected SQLWarning warnings = null;
/** The last warning of the warning chain. */
protected SQLWarning lastWarning = null;
/** Maximum number of rows to return, 0 = unlimited */
protected int maxrows = 0;
/** Number of rows to get in a batch. */
protected int fetchSize = 0;
/** Timeout (in seconds) for a query */
protected int timeout = 0;
protected boolean replaceProcessingEnabled = true;
/** The current results. */
protected ResultWrapper result = null;
/** The first unclosed result. */
protected ResultWrapper firstUnclosedResult = null;
/** Results returned by a statement that wants generated keys. */
protected ResultWrapper generatedKeys = null;
/** used to differentiate between new function call
* logic and old function call logic
* will be set to true if the server is < 8.1 or
* if we are using v2 protocol
* There is an exception to this where we are using v3, and the
* call does not have an out parameter before the call
*/
protected boolean adjustIndex = false;
/*
* Used to set adjustIndex above
*/
protected boolean outParmBeforeFunc=false;
// Static variables for parsing SQL when replaceProcessing is true.
private static final short IN_SQLCODE = 0;
private static final short IN_STRING = 1;
private static final short IN_IDENTIFIER = 6;
private static final short BACKSLASH = 2;
private static final short ESC_TIMEDATE = 3;
private static final short ESC_FUNCTION = 4;
private static final short ESC_OUTERJOIN = 5;
private static final short ESC_ESCAPECHAR = 7;
protected final Query preparedQuery; // Query fragments for prepared statement.
protected final ParameterList preparedParameters; // Parameter values for prepared statement.
protected Query lastSimpleQuery;
protected int m_prepareThreshold; // Reuse threshold to enable use of PREPARE
protected int m_useCount = 0; // Number of times this statement has been used
//Used by the callablestatement style methods
private boolean isFunction;
// functionReturnType contains the user supplied value to check
// testReturn contains a modified version to make it easier to
// check the getXXX methods..
private int []functionReturnType;
private int []testReturn;
// returnTypeSet is true when a proper call to registerOutParameter has been made
private boolean returnTypeSet;
protected Object []callResult;
protected int maxfieldSize = 0;
public ResultSet createDriverResultSet(Field[] fields, List tuples)
throws SQLException
{
return createResultSet(null, fields, tuples, null);
}
public AbstractJdbc2Statement (AbstractJdbc2Connection c, int rsType, int rsConcurrency) throws SQLException
{
this.connection = c;
this.preparedQuery = null;
this.preparedParameters = null;
this.lastSimpleQuery = null;
forceBinaryTransfers |= c.getForceBinary();
resultsettype = rsType;
concurrency = rsConcurrency;
}
public AbstractJdbc2Statement(AbstractJdbc2Connection connection, String sql, boolean isCallable, int rsType, int rsConcurrency) throws SQLException
{
this.connection = connection;
this.lastSimpleQuery = null;
String parsed_sql = replaceProcessing(sql);
if (isCallable)
parsed_sql = modifyJdbcCall(parsed_sql);
this.preparedQuery = connection.getQueryExecutor().createParameterizedQuery(parsed_sql);
this.preparedParameters = preparedQuery.createParameterList();
int inParamCount = preparedParameters.getInParameterCount() + 1;
this.testReturn = new int[inParamCount];
this.functionReturnType = new int[inParamCount];
forceBinaryTransfers |= connection.getForceBinary();
resultsettype = rsType;
concurrency = rsConcurrency;
}
public abstract ResultSet createResultSet(Query originalQuery, Field[] fields, List tuples, ResultCursor cursor)
throws SQLException;
public BaseConnection getPGConnection() {
return connection;
}
public String getFetchingCursorName() {
return null;
}
public int getFetchSize() {
return fetchSize;
}
protected boolean wantsScrollableResultSet() {
return resultsettype != ResultSet.TYPE_FORWARD_ONLY;
}
protected boolean wantsHoldableResultSet() {
return false;
}
//
// ResultHandler implementations for updates, queries, and either-or.
//
public class StatementResultHandler implements ResultHandler {
private SQLException error;
private ResultWrapper results;
ResultWrapper getResults() {
return results;
}
private void append(ResultWrapper newResult) {
if (results == null)
results = newResult;
else
results.append(newResult);
}
public void handleResultRows(Query fromQuery, Field[] fields, List tuples, ResultCursor cursor) {
try
{
ResultSet rs = AbstractJdbc2Statement.this.createResultSet(fromQuery, fields, tuples, cursor);
append(new ResultWrapper(rs));
}
catch (SQLException e)
{
handleError(e);
}
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
append(new ResultWrapper(updateCount, insertOID));
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Statement.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (error == null)
error = newError;
else
error.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (error != null)
throw error;
}
}
/*
* Execute a SQL statement that retruns a single ResultSet
*
* @param sql typically a static SQL SELECT statement
* @return a ResulSet that contains the data produced by the query
* @exception SQLException if a database access error occurs
*/
public java.sql.ResultSet executeQuery(String p_sql) throws SQLException
{
if (preparedQuery != null)
throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
if (forceBinaryTransfers) {
clearWarnings();
// Close any existing resultsets associated with this statement.
while (firstUnclosedResult != null)
{
if (firstUnclosedResult.getResultSet() != null)
firstUnclosedResult.getResultSet().close();
firstUnclosedResult = firstUnclosedResult.getNext();
}
PreparedStatement ps = connection.prepareStatement(p_sql, resultsettype, concurrency, getResultSetHoldability());
ps.setMaxFieldSize(getMaxFieldSize());
ps.setFetchSize(getFetchSize());
ps.setFetchDirection(getFetchDirection());
AbstractJdbc2ResultSet rs = (AbstractJdbc2ResultSet) ps.executeQuery();
rs.registerRealStatement(this);
result = firstUnclosedResult = new ResultWrapper(rs);
return rs;
}
if (!executeWithFlags(p_sql, 0))
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
if (result.getNext() != null)
throw new PSQLException(GT.tr("Multiple ResultSets were returned by the query."),
PSQLState.TOO_MANY_RESULTS);
return (ResultSet)result.getResultSet();
}
/*
* A Prepared SQL query is executed and its ResultSet is returned
*
* @return a ResultSet that contains the data produced by the
* * query - never null
* @exception SQLException if a database access error occurs
*/
public java.sql.ResultSet executeQuery() throws SQLException
{
if (!executeWithFlags(0))
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
if (result.getNext() != null)
throw new PSQLException(GT.tr("Multiple ResultSets were returned by the query."), PSQLState.TOO_MANY_RESULTS);
return (ResultSet) result.getResultSet();
}
/*
* Execute a SQL INSERT, UPDATE or DELETE statement. In addition
* SQL statements that return nothing such as SQL DDL statements
* can be executed
*
* @param sql a SQL statement
* @return either a row count, or 0 for SQL commands
* @exception SQLException if a database access error occurs
*/
public int executeUpdate(String p_sql) throws SQLException
{
if (preparedQuery != null)
throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
if( isFunction )
{
executeWithFlags(p_sql, 0);
return 0;
}
executeWithFlags(p_sql, QueryExecutor.QUERY_NO_RESULTS);
ResultWrapper iter = result;
while (iter != null) {
if (iter.getResultSet() != null) {
throw new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS);
}
iter = iter.getNext();
}
return getUpdateCount();
}
/*
* Execute a SQL INSERT, UPDATE or DELETE statement. In addition,
* SQL statements that return nothing such as SQL DDL statements can
* be executed.
*
* @return either the row count for INSERT, UPDATE or DELETE; or
* * 0 for SQL statements that return nothing.
* @exception SQLException if a database access error occurs
*/
public int executeUpdate() throws SQLException
{
if( isFunction )
{
executeWithFlags(0);
return 0;
}
executeWithFlags(QueryExecutor.QUERY_NO_RESULTS);
ResultWrapper iter = result;
while (iter != null) {
if (iter.getResultSet() != null) {
throw new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS);
}
iter = iter.getNext();
}
return getUpdateCount();
}
/*
* Execute a SQL statement that may return multiple results. We
* don't have to worry about this since we do not support multiple
* ResultSets. You can use getResultSet or getUpdateCount to
* retrieve the result.
*
* @param sql any SQL statement
* @return true if the next result is a ResulSet, false if it is
* an update count or there are no more results
* @exception SQLException if a database access error occurs
*/
public boolean execute(String p_sql) throws SQLException
{
if (preparedQuery != null)
throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
return executeWithFlags(p_sql, 0);
}
public boolean executeWithFlags(String p_sql, int flags) throws SQLException
{
checkClosed();
p_sql = replaceProcessing(p_sql);
Query simpleQuery = connection.getQueryExecutor().createSimpleQuery(p_sql);
execute(simpleQuery, null, QueryExecutor.QUERY_ONESHOT | flags);
this.lastSimpleQuery = simpleQuery;
return (result != null && result.getResultSet() != null);
}
public boolean execute() throws SQLException
{
return executeWithFlags(0);
}
public boolean executeWithFlags(int flags) throws SQLException
{
checkClosed();
execute(preparedQuery, preparedParameters, flags);
// If we are executing and there are out parameters
// callable statement function set the return data
if (isFunction && returnTypeSet )
{
if (result == null || result.getResultSet() == null)
throw new PSQLException(GT.tr("A CallableStatement was executed with nothing returned."), PSQLState.NO_DATA);
ResultSet rs = result.getResultSet();
if (!rs.next())
throw new PSQLException(GT.tr("A CallableStatement was executed with nothing returned."), PSQLState.NO_DATA);
// figure out how many columns
int cols = rs.getMetaData().getColumnCount();
int outParameterCount = preparedParameters.getOutParameterCount() ;
if ( cols != outParameterCount )
throw new PSQLException(GT.tr("A CallableStatement was executed with an invalid number of parameters"),PSQLState.SYNTAX_ERROR);
// reset last result fetched (for wasNull)
lastIndex = 0;
// allocate enough space for all possible parameters without regard to in/out
callResult = new Object[preparedParameters.getParameterCount()+1];
// move them into the result set
for ( int i=0,j=0; i < cols; i++,j++)
{
// find the next out parameter, the assumption is that the functionReturnType
// array will be initialized with 0 and only out parameters will have values
// other than 0. 0 is the value for java.sql.Types.NULL, which should not
// conflict
while( j< functionReturnType.length && functionReturnType[j]==0) j++;
callResult[j] = rs.getObject(i+1);
int columnType = rs.getMetaData().getColumnType(i+1);
if (columnType != functionReturnType[j])
{
// this is here for the sole purpose of passing the cts
if ( columnType == Types.DOUBLE && functionReturnType[j] == Types.REAL )
{
// return it as a float
if ( callResult[j] != null)
callResult[j] = new Float(((Double)callResult[j]).floatValue());
}
else
{
throw new PSQLException (GT.tr("A CallableStatement function was executed and the out parameter {0} was of type {1} however type {2} was registered.",
new Object[]{new Integer(i+1),
"java.sql.Types=" + columnType, "java.sql.Types=" + functionReturnType[j] }),
PSQLState.DATA_TYPE_MISMATCH);
}
}
}
rs.close();
result = null;
return false;
}
return (result != null && result.getResultSet() != null);
}
protected void closeForNextExecution() throws SQLException {
// Every statement execution clears any previous warnings.
clearWarnings();
// Close any existing resultsets associated with this statement.
while (firstUnclosedResult != null)
{
ResultSet rs = firstUnclosedResult.getResultSet();
if (rs != null)
{
rs.close();
}
firstUnclosedResult = firstUnclosedResult.getNext();
}
result = null;
if (lastSimpleQuery != null) {
lastSimpleQuery.close();
lastSimpleQuery = null;
}
if (generatedKeys != null) {
if (generatedKeys.getResultSet() != null) {
generatedKeys.getResultSet().close();
}
generatedKeys = null;
}
}
protected void execute(Query queryToExecute, ParameterList queryParameters, int flags) throws SQLException {
closeForNextExecution();
// Enable cursor-based resultset if possible.
if (fetchSize > 0 && !wantsScrollableResultSet() && !connection.getAutoCommit() && !wantsHoldableResultSet())
flags |= QueryExecutor.QUERY_FORWARD_CURSOR;
if (wantsGeneratedKeysOnce || wantsGeneratedKeysAlways)
{
flags |= QueryExecutor.QUERY_BOTH_ROWS_AND_STATUS;
// If the no results flag is set (from executeUpdate)
// clear it so we get the generated keys results.
//
if ((flags & QueryExecutor.QUERY_NO_RESULTS) != 0)
flags &= ~(QueryExecutor.QUERY_NO_RESULTS);
}
// Only use named statements after we hit the threshold. Note that only
// named statements can be transferred in binary format.
if (preparedQuery != null)
{
++m_useCount; // We used this statement once more.
if ((m_prepareThreshold == 0 || m_useCount < m_prepareThreshold) && !forceBinaryTransfers)
flags |= QueryExecutor.QUERY_ONESHOT;
}
if (connection.getAutoCommit())
flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN;
// updateable result sets do not yet support binary updates
if (concurrency != ResultSet.CONCUR_READ_ONLY)
flags |= QueryExecutor.QUERY_NO_BINARY_TRANSFER;
if (queryToExecute.isEmpty())
{
flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN;
}
if (!queryToExecute.isStatementDescribed() && forceBinaryTransfers) {
int flags2 = flags | QueryExecutor.QUERY_DESCRIBE_ONLY;
StatementResultHandler handler2 = new StatementResultHandler();
connection.getQueryExecutor().execute(queryToExecute, queryParameters, handler2, 0, 0, flags2);
ResultWrapper result2 = handler2.getResults();
if (result2 != null) {
result2.getResultSet().close();
}
}
StatementResultHandler handler = new StatementResultHandler();
result = null;
try
{
startTimer();
connection.getQueryExecutor().execute(queryToExecute,
queryParameters,
handler,
maxrows,
fetchSize,
flags);
}
finally
{
killTimerTask();
}
result = firstUnclosedResult = handler.getResults();
if (wantsGeneratedKeysOnce || wantsGeneratedKeysAlways)
{
generatedKeys = result;
result = result.getNext();
if (wantsGeneratedKeysOnce)
wantsGeneratedKeysOnce = false;
}
}
/*
* setCursorName defines the SQL cursor name that will be used by
* subsequent execute methods. This name can then be used in SQL
* positioned update/delete statements to identify the current row
* in the ResultSet generated by this statement. If a database
* doesn't support positioned update/delete, this method is a
* no-op.
*
* <p><B>Note:</B> By definition, positioned update/delete execution
* must be done by a different Statement than the one which
* generated the ResultSet being used for positioning. Also, cursor
* names must be unique within a Connection.
*
* @param name the new cursor name
* @exception SQLException if a database access error occurs
*/
public void setCursorName(String name) throws SQLException
{
checkClosed();
// No-op.
}
protected boolean isClosed = false;
private int lastIndex = 0;
/*
* getUpdateCount returns the current result as an update count,
* if the result is a ResultSet or there are no more results, -1
* is returned. It should only be called once per result.
*
* @return the current result as an update count.
* @exception SQLException if a database access error occurs
*/
public int getUpdateCount() throws SQLException
{
checkClosed();
if (result == null || result.getResultSet() != null)
return -1;
return result.getUpdateCount();
}
/*
* getMoreResults moves to a Statement's next result. If it returns
* true, this result is a ResulSet.
*
* @return true if the next ResultSet is valid
* @exception SQLException if a database access error occurs
*/
public boolean getMoreResults() throws SQLException
{
if (result == null)
return false;
result = result.getNext();
// Close preceding resultsets.
while (firstUnclosedResult != result)
{
if (firstUnclosedResult.getResultSet() != null)
firstUnclosedResult.getResultSet().close();
firstUnclosedResult = firstUnclosedResult.getNext();
}
return (result != null && result.getResultSet() != null);
}
/*
* The maxRows limit is set to limit the number of rows that
* any ResultSet can contain. If the limit is exceeded, the
* excess rows are silently dropped.
*
* @return the current maximum row limit; zero means unlimited
* @exception SQLException if a database access error occurs
*/
public int getMaxRows() throws SQLException
{
checkClosed();
return maxrows;
}
/*
* Set the maximum number of rows
*
* @param max the new max rows limit; zero means unlimited
* @exception SQLException if a database access error occurs
* @see getMaxRows
*/
public void setMaxRows(int max) throws SQLException
{
checkClosed();
if (max < 0)
throw new PSQLException(GT.tr("Maximum number of rows must be a value grater than or equal to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
maxrows = max;
}
/*
* If escape scanning is on (the default), the driver will do escape
* substitution before sending the SQL to the database.
*
* @param enable true to enable; false to disable
* @exception SQLException if a database access error occurs
*/
public void setEscapeProcessing(boolean enable) throws SQLException
{
checkClosed();
replaceProcessingEnabled = enable;
}
/*
* The queryTimeout limit is the number of seconds the driver
* will wait for a Statement to execute. If the limit is
* exceeded, a SQLException is thrown.
*
* @return the current query timeout limit in seconds; 0 = unlimited
* @exception SQLException if a database access error occurs
*/
public int getQueryTimeout() throws SQLException
{
checkClosed();
return timeout;
}
/*
* Sets the queryTimeout limit
*
* @param seconds - the new query timeout limit in seconds
* @exception SQLException if a database access error occurs
*/
public void setQueryTimeout(int seconds) throws SQLException
{
checkClosed();
if (seconds < 0)
throw new PSQLException(GT.tr("Query timeout must be a value greater than or equals to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
timeout = seconds;
}
/**
* This adds a warning to the warning chain. We track the
* tail of the warning chain as well to avoid O(N) behavior
* for adding a new warning to an existing chain. Some
* server functions which RAISE NOTICE (or equivalent) produce
* a ton of warnings.
* @param warn warning to add
*/
public void addWarning(SQLWarning warn)
{
if (warnings == null) {
warnings = warn;
lastWarning = warn;
} else {
lastWarning.setNextWarning(warn);
lastWarning = warn;
}
}
/*
* The first warning reported by calls on this Statement is
* returned. A Statement's execute methods clear its SQLWarning
* chain. Subsequent Statement warnings will be chained to this
* SQLWarning.
*
* <p>The Warning chain is automatically cleared each time a statement
* is (re)executed.
*
* <p><B>Note:</B> If you are processing a ResultSet then any warnings
* associated with ResultSet reads will be chained on the ResultSet
* object.
*
* @return the first SQLWarning on null
* @exception SQLException if a database access error occurs
*/
public SQLWarning getWarnings() throws SQLException
{
checkClosed();
return warnings;
}
/*
* The maxFieldSize limit (in bytes) is the maximum amount of
* data returned for any column value; it only applies to
* BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR
* columns. If the limit is exceeded, the excess data is silently
* discarded.
*
* @return the current max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs
*/
public int getMaxFieldSize() throws SQLException
{
return maxfieldSize;
}
/*
* Sets the maxFieldSize
*
* @param max the new max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs
*/
public void setMaxFieldSize(int max) throws SQLException
{
checkClosed();
if (max < 0)
throw new PSQLException(GT.tr("The maximum field size must be a value greater than or equal to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
maxfieldSize = max;
}
/*
* After this call, getWarnings returns null until a new warning
* is reported for this Statement.
*
* @exception SQLException if a database access error occurs
*/
public void clearWarnings() throws SQLException
{
warnings = null;
lastWarning = null;
}
/*
* getResultSet returns the current result as a ResultSet. It
* should only be called once per result.
*
* @return the current result set; null if there are no more
* @exception SQLException if a database access error occurs (why?)
*/
public java.sql.ResultSet getResultSet() throws SQLException
{
checkClosed();
if (result == null)
return null;
return (ResultSet) result.getResultSet();
}
/*
* In many cases, it is desirable to immediately release a
* Statement's database and JDBC resources instead of waiting
* for this to happen when it is automatically closed. The
* close method provides this immediate release.
*
* <p><B>Note:</B> A Statement is automatically closed when it is
* garbage collected. When a Statement is closed, its current
* ResultSet, if one exists, is also closed.
*
* @exception SQLException if a database access error occurs (why?)
*/
public void close() throws SQLException
{
// closing an already closed Statement is a no-op.
if (isClosed)
return ;
killTimerTask();
closeForNextExecution();
if (preparedQuery != null)
preparedQuery.close();
isClosed = true;
}
/**
* This finalizer ensures that statements that have allocated server-side
* resources free them when they become unreferenced.
*/
protected void finalize() throws Throwable {
try
{
close();
}
catch (SQLException e)
{
}
finally
{
super.finalize();
}
}
/*
* Filter the SQL string of Java SQL Escape clauses.
*
* Currently implemented Escape clauses are those mentioned in 11.3
* in the specification. Basically we look through the sql string for
* {d xxx}, {t xxx}, {ts xxx}, {oj xxx} or {fn xxx} in non-string sql
* code. When we find them, we just strip the escape part leaving only
* the xxx part.
* So, something like "select * from x where d={d '2001-10-09'}" would
* return "select * from x where d= '2001-10-09'".
*/
protected String replaceProcessing(String p_sql) throws SQLException
{
if (replaceProcessingEnabled)
{
// Since escape codes can only appear in SQL CODE, we keep track
// of if we enter a string or not.
int len = p_sql.length();
StringBuilder newsql = new StringBuilder(len);
int i=0;
while (i<len){
i=parseSql(p_sql,i,newsql,false,connection.getStandardConformingStrings());
// We need to loop here in case we encounter invalid
// SQL, consider: SELECT a FROM t WHERE (1 > 0)) ORDER BY a
// We can't ending replacing after the extra closing paren
// because that changes a syntax error to a valid query
// that isn't what the user specified.
if (i < len) {
newsql.append(p_sql.charAt(i));
i++;
}
}
return newsql.toString();
}
else
{
return p_sql;
}
}
/**
* parse the given sql from index i, appending it to the gven buffer
* until we hit an unmatched right parentheses or end of string. When
* the stopOnComma flag is set we also stop processing when a comma is
* found in sql text that isn't inside nested parenthesis.
*
* @param p_sql the original query text
* @param i starting position for replacing
* @param newsql where to write the replaced output
* @param stopOnComma should we stop after hitting the first comma in sql text?
* @param stdStrings whether standard_conforming_strings is on
* @return the position we stopped processing at
*/
protected static int parseSql(String p_sql,int i,StringBuilder newsql, boolean stopOnComma,
boolean stdStrings)throws SQLException{
short state = IN_SQLCODE;
int len = p_sql.length();
int nestedParenthesis=0;
boolean endOfNested=false;
// because of the ++i loop
i--;
while (!endOfNested && ++i < len)
{
char c = p_sql.charAt(i);
switch (state)
{
case IN_SQLCODE:
if (c == '\'') // start of a string?
state = IN_STRING;
else if (c == '"') // start of a identifer?
state = IN_IDENTIFIER;
else if (c=='(') { // begin nested sql
nestedParenthesis++;
} else if (c==')') { // end of nested sql
nestedParenthesis--;
if (nestedParenthesis<0){
endOfNested=true;
break;
}
} else if (stopOnComma && c==',' && nestedParenthesis==0) {
endOfNested=true;
break;
} else if (c == '{') { // start of an escape code?
if (i + 1 < len)
{
char next = p_sql.charAt(i + 1);
char nextnext = (i + 2 < len) ? p_sql.charAt(i + 2) : '\0';
if (next == 'd' || next == 'D')
{
state = ESC_TIMEDATE;
i++;
newsql.append("DATE ");
break;
}
else if (next == 't' || next == 'T')
{
state = ESC_TIMEDATE;
if (nextnext == 's' || nextnext == 'S'){
// timestamp constant
i+=2;
newsql.append("TIMESTAMP ");
}else{
// time constant
i++;
newsql.append("TIME ");
}
break;
}
else if ( next == 'f' || next == 'F' )
{
state = ESC_FUNCTION;
i += (nextnext == 'n' || nextnext == 'N') ? 2 : 1;
break;
}
else if ( next == 'o' || next == 'O' )
{
state = ESC_OUTERJOIN;
i += (nextnext == 'j' || nextnext == 'J') ? 2 : 1;
break;
}
else if ( next == 'e' || next == 'E' )
{ // we assume that escape is the only escape sequence beginning with e
state = ESC_ESCAPECHAR;
break;
}
}
}
newsql.append(c);
break;
case IN_STRING:
if (c == '\'') // end of string?
state = IN_SQLCODE;
else if (c == '\\' && !stdStrings) // a backslash?
state = BACKSLASH;
newsql.append(c);
break;
case IN_IDENTIFIER:
if (c == '"') // end of identifier
state = IN_SQLCODE;
newsql.append(c);
break;
case BACKSLASH:
state = IN_STRING;
newsql.append(c);
break;
case ESC_FUNCTION:
// extract function name
String functionName;
int posArgs = p_sql.indexOf('(',i);
if (posArgs!=-1){
functionName=p_sql.substring(i,posArgs).trim();
// extract arguments
i= posArgs+1;// we start the scan after the first (
StringBuilder args=new StringBuilder();
i = parseSql(p_sql,i,args,false,stdStrings);
// translate the function and parse arguments
newsql.append(escapeFunction(functionName,args.toString(),stdStrings));
}
// go to the end of the function copying anything found
i++;
while (i<len && p_sql.charAt(i)!='}')
newsql.append(p_sql.charAt(i++));
state = IN_SQLCODE; // end of escaped function (or query)
break;
case ESC_TIMEDATE:
case ESC_OUTERJOIN:
case ESC_ESCAPECHAR:
if (c == '}')
state = IN_SQLCODE; // end of escape code.
else
newsql.append(c);
break;
} // end switch
}
return i;
}
/**
* generate sql for escaped functions
* @param functionName the escaped function name
* @param args the arguments for this functin
* @param stdStrings whether standard_conforming_strings is on
* @return the right postgreSql sql
*/
protected static String escapeFunction(String functionName, String args, boolean stdStrings) throws SQLException{
// parse function arguments
int len = args.length();
int i=0;
ArrayList parsedArgs = new ArrayList();
while (i<len){
StringBuilder arg = new StringBuilder();
int lastPos=i;
i=parseSql(args,i,arg,true,stdStrings);
if (lastPos!=i){
parsedArgs.add(arg);
}
i++;
}
// we can now tranlate escape functions
try{
Method escapeMethod = EscapedFunctions.getFunction(functionName);
return (String) escapeMethod.invoke(null,new Object[] {parsedArgs});
}catch(InvocationTargetException e){
if (e.getTargetException() instanceof SQLException)
throw (SQLException) e.getTargetException();
else
throw new PSQLException(e.getTargetException().getMessage(),
PSQLState.SYSTEM_ERROR);
}catch (Exception e){
// by default the function name is kept unchanged
StringBuilder buf = new StringBuilder();
buf.append(functionName).append('(');
for (int iArg = 0;iArg<parsedArgs.size();iArg++){
buf.append(parsedArgs.get(iArg));
if (iArg!=(parsedArgs.size()-1))
buf.append(',');
}
buf.append(')');
return buf.toString();
}
}
/*
*
* The following methods are postgres extensions and are defined
* in the interface BaseStatement
*
*/
/*
* Returns the Last inserted/updated oid. Deprecated in 7.2 because
* range of OID values is greater than a java signed int.
* @deprecated Replaced by getLastOID in 7.2
*/
public int getInsertedOID() throws SQLException
{
checkClosed();
if (result == null)
return 0;
return (int) result.getInsertOID();
}
/*
* Returns the Last inserted/updated oid.
* @return OID of last insert
* @since 7.2
*/
public long getLastOID() throws SQLException
{
checkClosed();
if (result == null)
return 0;
return result.getInsertOID();
}
/*
* Set a parameter to SQL NULL
*
* <p><B>Note:</B> You must specify the parameter's SQL type.
*
* @param parameterIndex the first parameter is 1, etc...
* @param sqlType the SQL type code defined in java.sql.Types
* @exception SQLException if a database access error occurs
*/
public void setNull(int parameterIndex, int sqlType) throws SQLException
{
checkClosed();
int oid;
switch (sqlType)
{
case Types.INTEGER:
oid = Oid.INT4;
break;
case Types.TINYINT:
case Types.SMALLINT:
oid = Oid.INT2;
break;
case Types.BIGINT:
oid = Oid.INT8;
break;
case Types.REAL:
oid = Oid.FLOAT4;
break;
case Types.DOUBLE:
case Types.FLOAT:
oid = Oid.FLOAT8;
break;
case Types.DECIMAL:
case Types.NUMERIC:
oid = Oid.NUMERIC;
break;
case Types.CHAR:
oid = Oid.BPCHAR;
break;
case Types.VARCHAR:
case Types.LONGVARCHAR:
oid = connection.getStringVarcharFlag() ? Oid.VARCHAR : Oid.UNSPECIFIED;
break;
case Types.DATE:
oid = Oid.DATE;
break;
case Types.TIME:
case Types.TIMESTAMP:
oid = Oid.UNSPECIFIED;
break;
case Types.BIT:
oid = Oid.BOOL;
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
if (connection.haveMinimumCompatibleVersion("7.2"))
{
oid = Oid.BYTEA;
}
else
{
oid = Oid.OID;
}
break;
case Types.BLOB:
case Types.CLOB:
oid = Oid.OID;
break;
case Types.ARRAY:
case Types.DISTINCT:
case Types.STRUCT:
case Types.NULL:
case Types.OTHER:
oid = Oid.UNSPECIFIED;
break;
default:
// Bad Types value.
throw new PSQLException(GT.tr("Unknown Types value."), PSQLState.INVALID_PARAMETER_TYPE);
}
if ( adjustIndex )
parameterIndex--;
preparedParameters.setNull( parameterIndex, oid);
}
/*
* Set a parameter to a Java boolean value. The driver converts this
* to a SQL BIT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBoolean(int parameterIndex, boolean x) throws SQLException
{
checkClosed();
bindString(parameterIndex, x ? "1" : "0", Oid.BOOL);
}
/*
* Set a parameter to a Java byte value. The driver converts this to
* a SQL TINYINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setByte(int parameterIndex, byte x) throws SQLException
{
setShort(parameterIndex, x);
}
/*
* Set a parameter to a Java short value. The driver converts this
* to a SQL SMALLINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setShort(int parameterIndex, short x) throws SQLException
{
checkClosed();
if (connection.binaryTransferSend(Oid.INT2)) {
byte[] val = new byte[2];
ByteConverter.int2(val, 0, x);
bindBytes(parameterIndex, val, Oid.INT2);
return;
}
bindLiteral(parameterIndex, Integer.toString(x), Oid.INT2);
}
/*
* Set a parameter to a Java int value. The driver converts this to
* a SQL INTEGER value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setInt(int parameterIndex, int x) throws SQLException
{
checkClosed();
if (connection.binaryTransferSend(Oid.INT4)) {
byte[] val = new byte[4];
ByteConverter.int4(val, 0, x);
bindBytes(parameterIndex, val, Oid.INT4);
return;
}
bindLiteral(parameterIndex, Integer.toString(x), Oid.INT4);
}
/*
* Set a parameter to a Java long value. The driver converts this to
* a SQL BIGINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setLong(int parameterIndex, long x) throws SQLException
{
checkClosed();
if (connection.binaryTransferSend(Oid.INT8)) {
byte[] val = new byte[8];
ByteConverter.int8(val, 0, x);
bindBytes(parameterIndex, val, Oid.INT8);
return;
}
bindLiteral(parameterIndex, Long.toString(x), Oid.INT8);
}
/*
* Set a parameter to a Java float value. The driver converts this
* to a SQL FLOAT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setFloat(int parameterIndex, float x) throws SQLException
{
checkClosed();
if (connection.binaryTransferSend(Oid.FLOAT4)) {
byte[] val = new byte[4];
ByteConverter.float4(val, 0, x);
bindBytes(parameterIndex, val, Oid.FLOAT4);
return;
}
bindLiteral(parameterIndex, Float.toString(x), Oid.FLOAT8);
}
/*
* Set a parameter to a Java double value. The driver converts this
* to a SQL DOUBLE value when it sends it to the database
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setDouble(int parameterIndex, double x) throws SQLException
{
checkClosed();
if (connection.binaryTransferSend(Oid.FLOAT8)) {
byte[] val = new byte[8];
ByteConverter.float8(val, 0, x);
bindBytes(parameterIndex, val, Oid.FLOAT8);
return;
}
bindLiteral(parameterIndex, Double.toString(x), Oid.FLOAT8);
}
/*
* Set a parameter to a java.lang.BigDecimal value. The driver
* converts this to a SQL NUMERIC value when it sends it to the
* database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException
{
checkClosed();
if (x == null)
setNull(parameterIndex, Types.DECIMAL);
else
bindLiteral(parameterIndex, x.toString(), Oid.NUMERIC);
}
/*
* Set a parameter to a Java String value. The driver converts this
* to a SQL VARCHAR or LONGVARCHAR value (depending on the arguments
* size relative to the driver's limits on VARCHARs) when it sends it
* to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setString(int parameterIndex, String x) throws SQLException
{
checkClosed();
setString(parameterIndex, x, getStringType());
}
private int getStringType() {
return (connection.getStringVarcharFlag() ? Oid.VARCHAR : Oid.UNSPECIFIED);
}
protected void setString(int parameterIndex, String x, int oid) throws SQLException
{
// if the passed string is null, then set this column to null
checkClosed();
if (x == null)
{
if ( adjustIndex )
parameterIndex--;
preparedParameters.setNull( parameterIndex, oid);
}
else
bindString(parameterIndex, x, oid);
}
/*
* Set a parameter to a Java array of bytes. The driver converts this
* to a SQL VARBINARY or LONGVARBINARY (depending on the argument's
* size relative to the driver's limits on VARBINARYs) when it sends
* it to the database.
*
* <p>Implementation note:
* <br>With org.postgresql, this creates a large object, and stores the
* objects oid in this column.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBytes(int parameterIndex, byte[] x) throws SQLException
{
checkClosed();
if (null == x)
{
setNull(parameterIndex, Types.VARBINARY);
return ;
}
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports the bytea datatype for byte arrays
byte[] copy = new byte[x.length];
System.arraycopy(x, 0, copy, 0, x.length);
preparedParameters.setBytea( parameterIndex, copy, 0, x.length);
}
else
{
//Version 7.1 and earlier support done as LargeObjects
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
lob.write(x);
lob.close();
setLong(parameterIndex, oid);
}
}
/*
* Set a parameter to a java.sql.Date value. The driver converts this
* to a SQL DATE value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setDate(int parameterIndex, java.sql.Date x) throws SQLException
{
setDate(parameterIndex, x, null);
}
/*
* Set a parameter to a java.sql.Time value. The driver converts
* this to a SQL TIME value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...));
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setTime(int parameterIndex, Time x) throws SQLException
{
setTime(parameterIndex, x, null);
}
/*
* Set a parameter to a java.sql.Timestamp value. The driver converts
* this to a SQL TIMESTAMP value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException
{
setTimestamp(parameterIndex, x, null);
}
private void setCharacterStreamPost71(int parameterIndex, InputStream x, int length, String encoding) throws SQLException
{
if (x == null)
{
setNull(parameterIndex, Types.VARCHAR);
return ;
}
if (length < 0)
throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)),
PSQLState.INVALID_PARAMETER_VALUE);
//Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
//As the spec/javadoc for this method indicate this is to be used for
//large String values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all text datatypes are capable of
//handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server
try
{
InputStreamReader l_inStream = new InputStreamReader(x, encoding);
char[] l_chars = new char[length];
int l_charsRead = 0;
while (true)
{
int n = l_inStream.read(l_chars, l_charsRead, length - l_charsRead);
if (n == -1)
break;
l_charsRead += n;
if (l_charsRead == length)
break;
}
setString(parameterIndex, new String(l_chars, 0, l_charsRead), Oid.VARCHAR);
}
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException(GT.tr("The JVM claims not to support the {0} encoding.", encoding), PSQLState.UNEXPECTED_ERROR, l_uee);
}
catch (IOException l_ioe)
{
throw new PSQLException(GT.tr("Provided InputStream failed."), PSQLState.UNEXPECTED_ERROR, l_ioe);
}
}
/*
* When a very large ASCII value is input to a LONGVARCHAR parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file. The JDBC driver will do any necessary conversion from
* ASCII to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @param length the number of bytes in the stream
* @exception SQLException if a database access error occurs
*/
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException
{
checkClosed();
if (connection.haveMinimumCompatibleVersion("7.2"))
{
setCharacterStreamPost71(parameterIndex, x, length, "ASCII");
}
else
{
//Version 7.1 supported only LargeObjects by treating everything
//as binary data
setBinaryStream(parameterIndex, x, length);
}
}
/*
* When a very large Unicode value is input to a LONGVARCHAR parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file. The JDBC driver will do any necessary conversion from
* UNICODE to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException
{
checkClosed();
if (connection.haveMinimumCompatibleVersion("7.2"))
{
setCharacterStreamPost71(parameterIndex, x, length, "UTF-8");
}
else
{
//Version 7.1 supported only LargeObjects by treating everything
//as binary data
setBinaryStream(parameterIndex, x, length);
}
}
/*
* When a very large binary value is input to a LONGVARBINARY parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file.
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException
{
checkClosed();
if (x == null)
{
setNull(parameterIndex, Types.VARBINARY);
return ;
}
if (length < 0)
throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)),
PSQLState.INVALID_PARAMETER_VALUE);
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports BinaryStream for for the PG bytea type
//As the spec/javadoc for this method indicate this is to be used for
//large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
//long binary datatype, but with toast the bytea datatype is capable of
//handling very large values.
preparedParameters.setBytea(parameterIndex, x, length);
}
else
{
//Version 7.1 only supported streams for LargeObjects
//but the jdbc spec indicates that streams should be
//available for LONGVARBINARY instead
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c = x.read();
int p = 0;
while (c > -1 && p < length)
{
los.write(c);
c = x.read();
p++;
}
los.close();
}
catch (IOException se)
{
throw new PSQLException(GT.tr("Provided InputStream failed."), PSQLState.UNEXPECTED_ERROR, se);
}
// lob is closed by the stream so don't call lob.close()
setLong(parameterIndex, oid);
}
}
/*
* In general, parameter values remain in force for repeated used of a
* Statement. Setting a parameter value automatically clears its
* previous value. However, in coms cases, it is useful to immediately
* release the resources used by the current parameter values; this
* can be done by calling clearParameters
*
* @exception SQLException if a database access error occurs
*/
public void clearParameters() throws SQLException
{
preparedParameters.clear();
}
private PGType createInternalType( Object x, int targetType ) throws PSQLException
{
if ( x instanceof Byte ) return PGByte.castToServerType((Byte)x, targetType );
if ( x instanceof Short ) return PGShort.castToServerType((Short)x, targetType );
if ( x instanceof Integer ) return PGInteger.castToServerType((Integer)x, targetType );
if ( x instanceof Long ) return PGLong.castToServerType((Long)x, targetType );
if ( x instanceof Double ) return PGDouble.castToServerType((Double)x, targetType );
if ( x instanceof Float ) return PGFloat.castToServerType((Float)x, targetType );
if ( x instanceof BigDecimal) return PGBigDecimal.castToServerType((BigDecimal)x, targetType );
// since all of the above are instances of Number make sure this is after them
if ( x instanceof Number ) return PGNumber.castToServerType((Number)x, targetType );
if ( x instanceof Boolean) return PGBoolean.castToServerType((Boolean)x, targetType );
return new PGUnknown(x);
}
// Helper method for setting parameters to PGobject subclasses.
private void setPGobject(int parameterIndex, PGobject x) throws SQLException {
String typename = x.getType();
int oid = connection.getTypeInfo().getPGType(typename);
if (oid == Oid.UNSPECIFIED)
throw new PSQLException(GT.tr("Unknown type {0}.", typename), PSQLState.INVALID_PARAMETER_TYPE);
if ((x instanceof PGBinaryObject) && connection.binaryTransferSend(oid)) {
PGBinaryObject binObj = (PGBinaryObject) x;
byte[] data = new byte[binObj.lengthInBytes()];
binObj.toBytes(data, 0);
bindBytes(parameterIndex, data, oid);
} else {
setString(parameterIndex, x.getValue(), oid);
}
}
private void setMap(int parameterIndex, Map x) throws SQLException {
int oid = connection.getTypeInfo().getPGType("hstore");
if (oid == Oid.UNSPECIFIED)
throw new PSQLException(GT.tr("No hstore extension installed."), PSQLState.INVALID_PARAMETER_TYPE);
if (connection.binaryTransferSend(oid)) {
byte[] data = HStoreConverter.toBytes(x, connection.getEncoding());
bindBytes(parameterIndex, data, oid);
} else {
setString(parameterIndex, HStoreConverter.toString(x), oid);
}
}
/*
* Set the value of a parameter using an object; use the java.lang
* equivalent objects for integral values.
*
* <P>The given Java object will be converted to the targetSqlType before
* being sent to the database.
*
* <P>note that this method may be used to pass database-specific
* abstract data types. This is done by using a Driver-specific
* Java type and using a targetSqlType of java.sql.Types.OTHER
*
* @param parameterIndex the first parameter is 1...
* @param x the object containing the input parameter value
* @param targetSqlType The SQL type to be send to the database
* @param scale For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC
* * types this is the number of digits after the decimal. For
* * all other types this value will be ignored.
* @exception SQLException if a database access error occurs
*/
public void setObject(int parameterIndex, Object in, int targetSqlType, int scale) throws SQLException
{
checkClosed();
if (in == null)
{
setNull(parameterIndex, targetSqlType);
return ;
}
Object pgType = createInternalType( in, targetSqlType );
switch (targetSqlType)
{
case Types.INTEGER:
bindLiteral(parameterIndex, pgType.toString(), Oid.INT4);
break;
case Types.TINYINT:
case Types.SMALLINT:
bindLiteral(parameterIndex, pgType.toString(), Oid.INT2);
break;
case Types.BIGINT:
bindLiteral(parameterIndex, pgType.toString(), Oid.INT8);
break;
case Types.REAL:
//TODO: is this really necessary ?
//bindLiteral(parameterIndex, new Float(pgType.toString()).toString(), Oid.FLOAT4);
bindLiteral(parameterIndex, pgType.toString(), Oid.FLOAT4);
break;
case Types.DOUBLE:
case Types.FLOAT:
bindLiteral(parameterIndex, pgType.toString(), Oid.FLOAT8);
break;
case Types.DECIMAL:
case Types.NUMERIC:
bindLiteral(parameterIndex, pgType.toString(), Oid.NUMERIC);
break;
case Types.CHAR:
setString(parameterIndex, pgType.toString(), Oid.BPCHAR);
break;
case Types.VARCHAR:
case Types.LONGVARCHAR:
setString(parameterIndex, pgType.toString(), getStringType());
break;
case Types.DATE:
if (in instanceof java.sql.Date)
setDate(parameterIndex, (java.sql.Date)in);
else
{
java.sql.Date tmpd;
if (in instanceof java.util.Date) {
tmpd = new java.sql.Date(((java.util.Date)in).getTime());
} else {
tmpd = connection.getTimestampUtils().toDate(null, in.toString());
}
setDate(parameterIndex, tmpd);
}
break;
case Types.TIME:
if (in instanceof java.sql.Time)
setTime(parameterIndex, (java.sql.Time)in);
else
{
java.sql.Time tmpt;
if (in instanceof java.util.Date) {
tmpt = new java.sql.Time(((java.util.Date)in).getTime());
} else {
tmpt = connection.getTimestampUtils().toTime(null, in.toString());
}
setTime(parameterIndex, tmpt);
}
break;
case Types.TIMESTAMP:
if (in instanceof java.sql.Timestamp)
setTimestamp(parameterIndex , (java.sql.Timestamp)in);
else
{
java.sql.Timestamp tmpts;
if (in instanceof java.util.Date) {
tmpts = new java.sql.Timestamp(((java.util.Date)in).getTime());
} else {
tmpts = connection.getTimestampUtils().toTimestamp(null, in.toString());
}
setTimestamp(parameterIndex, tmpts);
}
break;
case Types.BIT:
bindLiteral(parameterIndex, pgType.toString(), Oid.BOOL);
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
setObject(parameterIndex, in);
break;
case Types.BLOB:
if (in instanceof Blob)
{
setBlob(parameterIndex, (Blob)in);
}
else if (in instanceof InputStream)
{
long oid = createBlob(parameterIndex, (InputStream) in, -1);
setLong(parameterIndex, oid);
}
else
{
throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.BLOB"}), PSQLState.INVALID_PARAMETER_TYPE);
}
break;
case Types.CLOB:
if (in instanceof Clob)
setClob(parameterIndex, (Clob)in);
else
throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.CLOB"}), PSQLState.INVALID_PARAMETER_TYPE);
break;
case Types.ARRAY:
if (in instanceof Array)
setArray(parameterIndex, (Array)in);
else
throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.ARRAY"}), PSQLState.INVALID_PARAMETER_TYPE);
break;
case Types.DISTINCT:
bindString(parameterIndex, in.toString(), Oid.UNSPECIFIED);
break;
case Types.OTHER:
if (in instanceof PGobject)
setPGobject(parameterIndex, (PGobject)in);
else
bindString(parameterIndex, in.toString(), Oid.UNSPECIFIED);
break;
default:
throw new PSQLException(GT.tr("Unsupported Types value: {0}", new Integer(targetSqlType)), PSQLState.INVALID_PARAMETER_TYPE);
}
}
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException
{
setObject(parameterIndex, x, targetSqlType, 0);
}
/*
* This stores an Object into a parameter.
*/
public void setObject(int parameterIndex, Object x) throws SQLException
{
checkClosed();
if (x == null)
setNull(parameterIndex, Types.OTHER);
else if (x instanceof String)
setString(parameterIndex, (String)x);
else if (x instanceof BigDecimal)
setBigDecimal(parameterIndex, (BigDecimal)x);
else if (x instanceof Short)
setShort(parameterIndex, ((Short)x).shortValue());
else if (x instanceof Integer)
setInt(parameterIndex, ((Integer)x).intValue());
else if (x instanceof Long)
setLong(parameterIndex, ((Long)x).longValue());
else if (x instanceof Float)
setFloat(parameterIndex, ((Float)x).floatValue());
else if (x instanceof Double)
setDouble(parameterIndex, ((Double)x).doubleValue());
else if (x instanceof byte[])
setBytes(parameterIndex, (byte[])x);
else if (x instanceof java.sql.Date)
setDate(parameterIndex, (java.sql.Date)x);
else if (x instanceof Time)
setTime(parameterIndex, (Time)x);
else if (x instanceof Timestamp)
setTimestamp(parameterIndex, (Timestamp)x);
else if (x instanceof Boolean)
setBoolean(parameterIndex, ((Boolean)x).booleanValue());
else if (x instanceof Byte)
setByte(parameterIndex, ((Byte)x).byteValue());
else if (x instanceof Blob)
setBlob(parameterIndex, (Blob)x);
else if (x instanceof Clob)
setClob(parameterIndex, (Clob)x);
else if (x instanceof Array)
setArray(parameterIndex, (Array)x);
else if (x instanceof PGobject)
setPGobject(parameterIndex, (PGobject)x);
else if (x instanceof Character)
setString(parameterIndex, ((Character)x).toString());
else if (x instanceof Map)
setMap(parameterIndex, (Map)x);
else
{
// Can't infer a type.
throw new PSQLException(GT.tr("Can''t infer the SQL type to use for an instance of {0}. Use setObject() with an explicit Types value to specify the type to use.", x.getClass().getName()), PSQLState.INVALID_PARAMETER_TYPE);
}
}
/*
* Before executing a stored procedure call you must explicitly
* call registerOutParameter to register the java.sql.Type of each
* out parameter.
*
* <p>Note: When reading the value of an out parameter, you must use
* the getXXX method whose Java type XXX corresponds to the
* parameter's registered SQL type.
*
* ONLY 1 RETURN PARAMETER if {?= call ..} syntax is used
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @param sqlType SQL type code defined by java.sql.Types; for
* parameters of type Numeric or Decimal use the version of
* registerOutParameter that accepts a scale value
* @exception SQLException if a database-access error occurs.
*/
public void registerOutParameter(int parameterIndex, int sqlType, boolean setPreparedParameters) throws SQLException
{
checkClosed();
switch( sqlType )
{
case Types.TINYINT:
// we don't have a TINYINT type use SMALLINT
sqlType = Types.SMALLINT;
break;
case Types.LONGVARCHAR:
sqlType = Types.VARCHAR;
break;
case Types.DECIMAL:
sqlType = Types.NUMERIC;
break;
case Types.FLOAT:
// float is the same as double
sqlType = Types.DOUBLE;
break;
case Types.VARBINARY:
case Types.LONGVARBINARY:
sqlType = Types.BINARY;
break;
default:
break;
}
if (!isFunction)
throw new PSQLException (GT.tr("This statement does not declare an OUT parameter. Use '{' ?= call ... '}' to declare one."), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
checkIndex(parameterIndex, false);
if( setPreparedParameters )
preparedParameters.registerOutParameter( parameterIndex, sqlType );
// functionReturnType contains the user supplied value to check
// testReturn contains a modified version to make it easier to
// check the getXXX methods..
functionReturnType[parameterIndex-1] = sqlType;
testReturn[parameterIndex-1] = sqlType;
if (functionReturnType[parameterIndex-1] == Types.CHAR ||
functionReturnType[parameterIndex-1] == Types.LONGVARCHAR)
testReturn[parameterIndex-1] = Types.VARCHAR;
else if (functionReturnType[parameterIndex-1] == Types.FLOAT)
testReturn[parameterIndex-1] = Types.REAL; // changes to streamline later error checking
returnTypeSet = true;
}
/*
* You must also specify the scale for numeric/decimal types:
*
* <p>Note: When reading the value of an out parameter, you must use
* the getXXX method whose Java type XXX corresponds to the
* parameter's registered SQL type.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @param sqlType use either java.sql.Type.NUMERIC or java.sql.Type.DECIMAL
* @param scale a value greater than or equal to zero representing the
* desired number of digits to the right of the decimal point
* @exception SQLException if a database-access error occurs.
*/
public void registerOutParameter(int parameterIndex, int sqlType,
int scale, boolean setPreparedParameters) throws SQLException
{
registerOutParameter (parameterIndex, sqlType, setPreparedParameters); // ignore for now..
}
/*
* An OUT parameter may have the value of SQL NULL; wasNull
* reports whether the last value read has this special value.
*
* <p>Note: You must first call getXXX on a parameter to read its
* value and then call wasNull() to see if the value was SQL NULL.
* @return true if the last parameter read was SQL NULL
* @exception SQLException if a database-access error occurs.
*/
public boolean wasNull() throws SQLException
{
if (lastIndex == 0)
throw new PSQLException(GT.tr("wasNull cannot be call before fetching a result."), PSQLState.OBJECT_NOT_IN_STATE);
// check to see if the last access threw an exception
return (callResult[lastIndex-1] == null);
}
/*
* Get the value of a CHAR, VARCHAR, or LONGVARCHAR parameter as a
* Java String.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public String getString(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.VARCHAR, "String");
return (String)callResult[parameterIndex-1];
}
/*
* Get the value of a BIT parameter as a Java boolean.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is false
* @exception SQLException if a database-access error occurs.
*/
public boolean getBoolean(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.BIT, "Boolean");
if (callResult[parameterIndex-1] == null)
return false;
return ((Boolean)callResult[parameterIndex-1]).booleanValue ();
}
/*
* Get the value of a TINYINT parameter as a Java byte.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public byte getByte(int parameterIndex) throws SQLException
{
checkClosed();
// fake tiny int with smallint
checkIndex (parameterIndex, Types.SMALLINT, "Byte");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Integer)callResult[parameterIndex-1]).byteValue();
}
/*
* Get the value of a SMALLINT parameter as a Java short.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public short getShort(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.SMALLINT, "Short");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Integer)callResult[parameterIndex-1]).shortValue ();
}
/*
* Get the value of an INTEGER parameter as a Java int.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public int getInt(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.INTEGER, "Int");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Integer)callResult[parameterIndex-1]).intValue ();
}
/*
* Get the value of a BIGINT parameter as a Java long.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public long getLong(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.BIGINT, "Long");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Long)callResult[parameterIndex-1]).longValue ();
}
/*
* Get the value of a FLOAT parameter as a Java float.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public float getFloat(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.REAL, "Float");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Float)callResult[parameterIndex-1]).floatValue ();
}
/*
* Get the value of a DOUBLE parameter as a Java double.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public double getDouble(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.DOUBLE, "Double");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Double)callResult[parameterIndex-1]).doubleValue ();
}
/*
* Get the value of a NUMERIC parameter as a java.math.BigDecimal
* object.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @param scale a value greater than or equal to zero representing the
* desired number of digits to the right of the decimal point
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
* @deprecated in Java2.0
*/
public BigDecimal getBigDecimal(int parameterIndex, int scale)
throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal");
return ((BigDecimal)callResult[parameterIndex-1]);
}
/*
* Get the value of a SQL BINARY or VARBINARY parameter as a Java
* byte[]
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public byte[] getBytes(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.VARBINARY, Types.BINARY, "Bytes");
return ((byte [])callResult[parameterIndex-1]);
}
/*
* Get the value of a SQL DATE parameter as a java.sql.Date object
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public java.sql.Date getDate(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.DATE, "Date");
return (java.sql.Date)callResult[parameterIndex-1];
}
/*
* Get the value of a SQL TIME parameter as a java.sql.Time object.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public java.sql.Time getTime(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.TIME, "Time");
return (java.sql.Time)callResult[parameterIndex-1];
}
/*
* Get the value of a SQL TIMESTAMP parameter as a java.sql.Timestamp object.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public java.sql.Timestamp getTimestamp(int parameterIndex)
throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.TIMESTAMP, "Timestamp");
return (java.sql.Timestamp)callResult[parameterIndex-1];
}
// getObject returns a Java object for the parameter.
// See the JDBC spec's "Dynamic Programming" chapter for details.
/*
* Get the value of a parameter as a Java object.
*
* <p>This method returns a Java object whose type coresponds to the
* SQL type that was registered for this parameter using
* registerOutParameter.
*
* <P>Note that this method may be used to read datatabase-specific,
* abstract data types. This is done by specifying a targetSqlType
* of java.sql.types.OTHER, which allows the driver to return a
* database-specific Java type.
*
* <p>See the JDBC spec's "Dynamic Programming" chapter for details.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return A java.lang.Object holding the OUT parameter value.
* @exception SQLException if a database-access error occurs.
*/
public Object getObject(int parameterIndex)
throws SQLException
{
checkClosed();
checkIndex (parameterIndex);
return callResult[parameterIndex-1];
}
/*
* Returns the SQL statement with the current template values
* substituted.
*/
public String toString()
{
if (preparedQuery == null)
return super.toString();
return preparedQuery.toString(preparedParameters);
}
/*
* Note if s is a String it should be escaped by the caller to avoid SQL
* injection attacks. It is not done here for efficency reasons as
* most calls to this method do not require escaping as the source
* of the string is known safe (i.e. Integer.toString())
*/
protected void bindLiteral(int paramIndex, String s, int oid) throws SQLException
{
if(adjustIndex)
paramIndex--;
preparedParameters.setLiteralParameter(paramIndex, s, oid);
}
protected void bindBytes(int paramIndex, byte[] b, int oid) throws SQLException
{
if(adjustIndex)
paramIndex--;
preparedParameters.setBinaryParameter(paramIndex, b, oid);
}
/*
* This version is for values that should turn into strings
* e.g. setString directly calls bindString with no escaping;
* the per-protocol ParameterList does escaping as needed.
*/
private void bindString(int paramIndex, String s, int oid) throws SQLException
{
if (adjustIndex)
paramIndex--;
preparedParameters.setStringParameter( paramIndex, s, oid);
}
/**
* this method will turn a string of the form
* { [? =] call <some_function> [(?, [?,..])] }
* into the PostgreSQL format which is
* select <some_function> (?, [?, ...]) as result
* or select * from <some_function> (?, [?, ...]) as result (7.3)
*/
private String modifyJdbcCall(String p_sql) throws SQLException
{
checkClosed();
// Mini-parser for JDBC function-call syntax (only)
// TODO: Merge with escape processing (and parameter parsing?)
// so we only parse each query once.
isFunction = false;
boolean stdStrings = connection.getStandardConformingStrings();
int len = p_sql.length();
int state = 1;
boolean inQuotes = false, inEscape = false;
outParmBeforeFunc = false;
int startIndex = -1, endIndex = -1;
boolean syntaxError = false;
int i = 0;
while (i < len && !syntaxError)
{
char ch = p_sql.charAt(i);
switch (state)
{
case 1: // Looking for { at start of query
if (ch == '{')
{
++i;
++state;
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
// Not function-call syntax. Skip the rest of the string.
i = len;
}
break;
case 2: // After {, looking for ? or =, skipping whitespace
if (ch == '?')
{
outParmBeforeFunc = isFunction = true; // { ? = call ... } -- function with one out parameter
++i;
++state;
}
else if (ch == 'c' || ch == 'C')
{ // { call ... } -- proc with no out parameters
state += 3; // Don't increase 'i'
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
// "{ foo ...", doesn't make sense, complain.
syntaxError = true;
}
break;
case 3: // Looking for = after ?, skipping whitespace
if (ch == '=')
{
++i;
++state;
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
syntaxError = true;
}
break;
case 4: // Looking for 'call' after '? =' skipping whitespace
if (ch == 'c' || ch == 'C')
{
++state; // Don't increase 'i'.
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
syntaxError = true;
}
break;
case 5: // Should be at 'call ' either at start of string or after ?=
if ((ch == 'c' || ch == 'C') && i + 4 <= len && p_sql.substring(i, i + 4).equalsIgnoreCase("call"))
{
isFunction=true;
i += 4;
++state;
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
syntaxError = true;
}
break;
case 6: // Looking for whitespace char after 'call'
if (Character.isWhitespace(ch))
{
// Ok, we found the start of the real call.
++i;
++state;
startIndex = i;
}
else
{
syntaxError = true;
}
break;
case 7: // In "body" of the query (after "{ [? =] call ")
if (ch == '\'')
{
inQuotes = !inQuotes;
++i;
}
else if (inQuotes && ch == '\\' && !stdStrings)
{
// Backslash in string constant, skip next character.
i += 2;
}
else if (!inQuotes && ch == '{')
{
inEscape = !inEscape;
++i;
}
else if (!inQuotes && ch == '}')
{
if (!inEscape)
{
// Should be end of string.
endIndex = i;
++i;
++state;
}
else
{
inEscape = false;
}
}
else if (!inQuotes && ch == ';')
{
syntaxError = true;
}
else
{
// Everything else is ok.
++i;
}
break;
case 8: // At trailing end of query, eating whitespace
if (Character.isWhitespace(ch))
{
++i;
}
else
{
syntaxError = true;
}
break;
default:
throw new IllegalStateException("somehow got into bad state " + state);
}
}
// We can only legally end in a couple of states here.
if (i == len && !syntaxError)
{
if (state == 1)
return p_sql; // Not an escaped syntax.
if (state != 8)
syntaxError = true; // Ran out of query while still parsing
}
if (syntaxError)
throw new PSQLException (GT.tr("Malformed function or procedure escape syntax at offset {0}.", new Integer(i)),
PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
if (connection.haveMinimumServerVersion("8.1") && ((AbstractJdbc2Connection)connection).getProtocolVersion() == 3)
{
String s = p_sql.substring(startIndex, endIndex );
StringBuilder sb = new StringBuilder(s);
if ( outParmBeforeFunc )
{
// move the single out parameter into the function call
// so that it can be treated like all other parameters
boolean needComma=false;
// have to use String.indexOf for java 2
int opening = s.indexOf('(')+1;
int closing = s.indexOf(')');
for ( int j=opening; j< closing;j++ )
{
if ( !Character.isWhitespace(sb.charAt(j)) )
{
needComma = true;
break;
}
}
if ( needComma )
{
sb.insert(opening, "?,");
}
else
{
sb.insert(opening, "?");
}
}
return "select * from " + sb.toString() + " as result";
}
else
{
return "select " + p_sql.substring(startIndex, endIndex) + " as result";
}
}
/** helperfunction for the getXXX calls to check isFunction and index == 1
* Compare BOTH type fields against the return type.
*/
protected void checkIndex (int parameterIndex, int type1, int type2, String getName)
throws SQLException
{
checkIndex (parameterIndex);
if (type1 != this.testReturn[parameterIndex-1] && type2 != this.testReturn[parameterIndex-1])
throw new PSQLException(GT.tr("Parameter of type {0} was registered, but call to get{1} (sqltype={2}) was made.",
new Object[]{"java.sql.Types=" + testReturn[parameterIndex-1],
getName,
"java.sql.Types=" + type1}),
PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH);
}
/** helperfunction for the getXXX calls to check isFunction and index == 1
*/
protected void checkIndex (int parameterIndex, int type, String getName)
throws SQLException
{
checkIndex (parameterIndex);
if (type != this.testReturn[parameterIndex-1])
throw new PSQLException(GT.tr("Parameter of type {0} was registered, but call to get{1} (sqltype={2}) was made.",
new Object[]{"java.sql.Types=" + testReturn[parameterIndex-1],
getName,
"java.sql.Types=" + type}),
PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH);
}
private void checkIndex (int parameterIndex) throws SQLException
{
checkIndex(parameterIndex, true);
}
/** helperfunction for the getXXX calls to check isFunction and index == 1
* @param parameterIndex index of getXXX (index)
* check to make sure is a function and index == 1
*/
private void checkIndex (int parameterIndex, boolean fetchingData) throws SQLException
{
if (!isFunction)
throw new PSQLException(GT.tr("A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made."), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
if (fetchingData) {
if (!returnTypeSet)
throw new PSQLException(GT.tr("No function outputs were registered."), PSQLState.OBJECT_NOT_IN_STATE);
if (callResult == null)
throw new PSQLException(GT.tr("Results cannot be retrieved from a CallableStatement before it is executed."), PSQLState.NO_DATA);
lastIndex = parameterIndex;
}
}
public void setPrepareThreshold(int newThreshold) throws SQLException {
checkClosed();
if (newThreshold < 0) {
forceBinaryTransfers = true;
newThreshold = 1;
}
else
forceBinaryTransfers = false;
this.m_prepareThreshold = newThreshold;
}
public int getPrepareThreshold() {
return m_prepareThreshold;
}
public void setUseServerPrepare(boolean flag) throws SQLException {
setPrepareThreshold(flag ? 1 : 0);
}
public boolean isUseServerPrepare() {
return (preparedQuery != null && m_prepareThreshold != 0 && m_useCount + 1 >= m_prepareThreshold);
}
protected void checkClosed() throws SQLException
{
if (isClosed)
throw new PSQLException(GT.tr("This statement has been closed."),
PSQLState.OBJECT_NOT_IN_STATE);
}
// ** JDBC 2 Extensions **
public void addBatch(String p_sql) throws SQLException
{
checkClosed();
if (preparedQuery != null)
throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
if (batchStatements == null)
{
batchStatements = new ArrayList();
batchParameters = new ArrayList();
}
p_sql = replaceProcessing(p_sql);
batchStatements.add(connection.getQueryExecutor().createSimpleQuery(p_sql));
batchParameters.add(null);
}
public void clearBatch() throws SQLException
{
if (batchStatements != null)
{
batchStatements.clear();
batchParameters.clear();
}
}
//
// ResultHandler for batch queries.
//
private class BatchResultHandler implements ResultHandler {
private BatchUpdateException batchException = null;
private int resultIndex = 0;
private final Query[] queries;
private final ParameterList[] parameterLists;
private final int[] updateCounts;
private final boolean expectGeneratedKeys;
private ResultSet generatedKeys;
BatchResultHandler(Query[] queries, ParameterList[] parameterLists, int[] updateCounts, boolean expectGeneratedKeys) {
this.queries = queries;
this.parameterLists = parameterLists;
this.updateCounts = updateCounts;
this.expectGeneratedKeys = expectGeneratedKeys;
}
public void handleResultRows(Query fromQuery, Field[] fields, List tuples, ResultCursor cursor) {
if (!expectGeneratedKeys) {
handleError(new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS));
} else {
if (generatedKeys == null) {
try
{
generatedKeys = AbstractJdbc2Statement.this.createResultSet(fromQuery, fields, tuples, cursor);
}
catch (SQLException e)
{
handleError(e);
}
} else {
((AbstractJdbc2ResultSet)generatedKeys).addRows(tuples);
}
}
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
if (resultIndex >= updateCounts.length)
{
handleError(new PSQLException(GT.tr("Too many update results were returned."),
PSQLState.TOO_MANY_RESULTS));
return ;
}
updateCounts[resultIndex++] = updateCount;
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Statement.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (batchException == null)
{
int[] successCounts;
if (resultIndex >= updateCounts.length)
successCounts = updateCounts;
else
{
successCounts = new int[resultIndex];
System.arraycopy(updateCounts, 0, successCounts, 0, resultIndex);
}
String queryString = "<unknown>";
if (resultIndex < queries.length)
queryString = queries[resultIndex].toString(parameterLists[resultIndex]);
batchException = new BatchUpdateException(GT.tr("Batch entry {0} {1} was aborted. Call getNextException to see the cause.",
new Object[]{ new Integer(resultIndex),
queryString}),
newError.getSQLState(),
successCounts);
}
batchException.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (batchException != null)
throw batchException;
}
public ResultSet getGeneratedKeys() {
return generatedKeys;
}
}
private class CallableBatchResultHandler implements ResultHandler {
private BatchUpdateException batchException = null;
private int resultIndex = 0;
private final Query[] queries;
private final ParameterList[] parameterLists;
private final int[] updateCounts;
CallableBatchResultHandler(Query[] queries, ParameterList[] parameterLists, int[] updateCounts) {
this.queries = queries;
this.parameterLists = parameterLists;
this.updateCounts = updateCounts;
}
public void handleResultRows(Query fromQuery, Field[] fields, List tuples, ResultCursor cursor)
{
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
if (resultIndex >= updateCounts.length)
{
handleError(new PSQLException(GT.tr("Too many update results were returned."),
PSQLState.TOO_MANY_RESULTS));
return ;
}
updateCounts[resultIndex++] = updateCount;
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Statement.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (batchException == null)
{
int[] successCounts;
if (resultIndex >= updateCounts.length)
successCounts = updateCounts;
else
{
successCounts = new int[resultIndex];
System.arraycopy(updateCounts, 0, successCounts, 0, resultIndex);
}
String queryString = "<unknown>";
if (resultIndex < queries.length)
queryString = queries[resultIndex].toString(parameterLists[resultIndex]);
batchException = new BatchUpdateException(GT.tr("Batch entry {0} {1} was aborted. Call getNextException to see the cause.",
new Object[]{ new Integer(resultIndex),
queryString}),
newError.getSQLState(),
successCounts);
}
batchException.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (batchException != null)
throw batchException;
}
}
public int[] executeBatch() throws SQLException
{
checkClosed();
closeForNextExecution();
if (batchStatements == null || batchStatements.isEmpty())
return new int[0];
int size = batchStatements.size();
int[] updateCounts = new int[size];
// Construct query/parameter arrays.
Query[] queries = (Query[])batchStatements.toArray(new Query[batchStatements.size()]);
ParameterList[] parameterLists = (ParameterList[])batchParameters.toArray(new ParameterList[batchParameters.size()]);
batchStatements.clear();
batchParameters.clear();
int flags = 0;
// Force a Describe before any execution? We need to do this if we're going
// to send anything dependent on the Desribe results, e.g. binary parameters.
boolean preDescribe = false;
if (wantsGeneratedKeysAlways) {
/*
* This batch will return generated keys, tell the executor to
* expect result rows. We also force a Describe later so we know
* the size of the results to expect.
*
* If the parameter type(s) change between batch entries and the
* default binary-mode changes we might get mixed binary and text
* in a single result set column, which we cannot handle. To prevent
* this, disable binary transfer mode in batches that return generated
* keys. See GitHub issue #267
*/
flags = QueryExecutor.QUERY_BOTH_ROWS_AND_STATUS
| QueryExecutor.QUERY_NO_BINARY_TRANSFER;
} else {
// If a batch hasn't specified that it wants generated keys, using the appropriate
// Connection.createStatement(...) interfaces, disallow any result set.
flags = QueryExecutor.QUERY_NO_RESULTS;
}
// Only use named statements after we hit the threshold
if (preparedQuery != null)
{
m_useCount += queries.length;
}
if (m_prepareThreshold == 0 || m_useCount < m_prepareThreshold) {
flags |= QueryExecutor.QUERY_ONESHOT;
} else {
// If a batch requests generated keys and isn't already described,
// force a Describe of the query before proceeding. That way we can
// determine the appropriate size of each batch by estimating the
// maximum data returned. Without that, we don't know how many queries
// we'll be able to queue up before we risk a deadlock.
// (see v3.QueryExecutorImpl's MAX_BUFFERED_RECV_BYTES)
preDescribe = wantsGeneratedKeysAlways && !queries[0].isStatementDescribed();
/*
* It's also necessary to force a Describe on the first execution of the
* new statement, even though we already described it, to work around
* bug #267.
*/
flags |= QueryExecutor.QUERY_FORCE_DESCRIBE_PORTAL;
}
if (connection.getAutoCommit())
flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN;
if (preDescribe || forceBinaryTransfers) {
// Do a client-server round trip, parsing and describing the query so we
// can determine its result types for use in binary parameters, batch sizing,
// etc.
int flags2 = flags | QueryExecutor.QUERY_DESCRIBE_ONLY;
StatementResultHandler handler2 = new StatementResultHandler();
connection.getQueryExecutor().execute(queries[0], parameterLists[0], handler2, 0, 0, flags2);
ResultWrapper result2 = handler2.getResults();
if (result2 != null) {
result2.getResultSet().close();
}
}
result = null;
ResultHandler handler;
if (isFunction) {
handler = new CallableBatchResultHandler(queries, parameterLists, updateCounts );
} else {
handler = new BatchResultHandler(queries, parameterLists, updateCounts, wantsGeneratedKeysAlways);
}
try {
startTimer();
connection.getQueryExecutor().execute(queries,
parameterLists,
handler,
maxrows,
fetchSize,
flags);
} finally {
killTimerTask();
}
if (wantsGeneratedKeysAlways) {
generatedKeys = new ResultWrapper(((BatchResultHandler)handler).getGeneratedKeys());
}
return updateCounts;
}
/*
* Cancel can be used by one thread to cancel a statement that
* is being executed by another thread.
* <p>
*
* @exception SQLException only because thats the spec.
*/
public void cancel() throws SQLException
{
connection.cancelQuery();
}
public Connection getConnection() throws SQLException
{
return (Connection) connection;
}
public int getFetchDirection()
{
return fetchdirection;
}
public int getResultSetConcurrency()
{
return concurrency;
}
public int getResultSetType()
{
return resultsettype;
}
public void setFetchDirection(int direction) throws SQLException
{
switch (direction)
{
case ResultSet.FETCH_FORWARD:
case ResultSet.FETCH_REVERSE:
case ResultSet.FETCH_UNKNOWN:
fetchdirection = direction;
break;
default:
throw new PSQLException(GT.tr("Invalid fetch direction constant: {0}.", new Integer(direction)),
PSQLState.INVALID_PARAMETER_VALUE);
}
}
public void setFetchSize(int rows) throws SQLException
{
checkClosed();
if (rows < 0)
throw new PSQLException(GT.tr("Fetch size must be a value greater to or equal to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
fetchSize = rows;
}
public void addBatch() throws SQLException
{
checkClosed();
if (batchStatements == null)
{
batchStatements = new ArrayList();
batchParameters = new ArrayList();
}
// we need to create copies of our parameters, otherwise the values can be changed
batchStatements.add(preparedQuery);
batchParameters.add(preparedParameters.copy());
}
public ResultSetMetaData getMetaData() throws SQLException
{
checkClosed();
ResultSet rs = getResultSet();
if (rs == null || ((AbstractJdbc2ResultSet)rs).isResultSetClosed() ) {
// OK, we haven't executed it yet, or it was closed
// we've got to go to the backend
// for more info. We send the full query, but just don't
// execute it.
int flags = QueryExecutor.QUERY_ONESHOT | QueryExecutor.QUERY_DESCRIBE_ONLY | QueryExecutor.QUERY_SUPPRESS_BEGIN;
StatementResultHandler handler = new StatementResultHandler();
connection.getQueryExecutor().execute(preparedQuery, preparedParameters, handler, 0, 0, flags);
ResultWrapper wrapper = handler.getResults();
if (wrapper != null) {
rs = wrapper.getResultSet();
}
}
if (rs != null)
return rs.getMetaData();
return null;
}
public void setArray(int i, java.sql.Array x) throws SQLException
{
checkClosed();
if (null == x)
{
setNull(i, Types.ARRAY);
return;
}
// This only works for Array implementations that return a valid array
// literal from Array.toString(), such as the implementation we return
// from ResultSet.getArray(). Eventually we need a proper implementation
// here that works for any Array implementation.
// Use a typename that is "_" plus the base type; this matches how the
// backend looks for array types.
String typename = "_" + x.getBaseTypeName();
int oid = connection.getTypeInfo().getPGType(typename);
if (oid == Oid.UNSPECIFIED)
throw new PSQLException(GT.tr("Unknown type {0}.", typename), PSQLState.INVALID_PARAMETER_TYPE);
if (x instanceof AbstractJdbc2Array) {
AbstractJdbc2Array arr = (AbstractJdbc2Array) x;
if (arr.isBinary()) {
bindBytes(i, arr.toBytes(), oid);
return;
}
}
setString(i, x.toString(), oid);
}
protected long createBlob(int i, InputStream inputStream, long length) throws SQLException
{
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
OutputStream outputStream = lob.getOutputStream();
byte[] buf = new byte[4096];
try
{
long remaining;
if (length > 0)
{
remaining = length;
}
else
{
remaining = Long.MAX_VALUE;
}
int numRead = inputStream.read(buf, 0, (length > 0 && remaining < buf.length ? (int)remaining : buf.length));
while (numRead != -1 && remaining > 0)
{
remaining -= numRead;
outputStream.write(buf, 0, numRead);
numRead = inputStream.read(buf, 0, (length > 0 && remaining < buf.length ? (int)remaining : buf.length));
}
}
catch (IOException se)
{
throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se);
}
finally
{
try
{
outputStream.close();
}
catch ( Exception e )
{
}
}
return oid;
}
public void setBlob(int i, Blob x) throws SQLException
{
checkClosed();
if (x == null)
{
setNull(i, Types.BLOB);
return;
}
InputStream inStream = x.getBinaryStream();
try
{
long oid = createBlob(i, inStream, x.length());
setLong(i, oid);
}
finally
{
try
{
inStream.close();
}
catch ( Exception e )
{
}
}
}
public void setCharacterStream(int i, java.io.Reader x, int length) throws SQLException
{
checkClosed();
if (x == null) {
if (connection.haveMinimumServerVersion("7.2")) {
setNull(i, Types.VARCHAR);
} else {
setNull(i, Types.CLOB);
}
return;
}
if (length < 0)
throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)),
PSQLState.INVALID_PARAMETER_VALUE);
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports CharacterStream for for the PG text types
//As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all the text datatypes are capable of
//handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server
char[] l_chars = new char[length];
int l_charsRead = 0;
try
{
while (true)
{
int n = x.read(l_chars, l_charsRead, length - l_charsRead);
if (n == -1)
break;
l_charsRead += n;
if (l_charsRead == length)
break;
}
}
catch (IOException l_ioe)
{
throw new PSQLException(GT.tr("Provided Reader failed."), PSQLState.UNEXPECTED_ERROR, l_ioe);
}
setString(i, new String(l_chars, 0, l_charsRead));
}
else
{
//Version 7.1 only supported streams for LargeObjects
//but the jdbc spec indicates that streams should be
//available for LONGVARCHAR instead
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c = x.read();
int p = 0;
while (c > -1 && p < length)
{
los.write(c);
c = x.read();
p++;
}
los.close();
}
catch (IOException se)
{
throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se);
}
// lob is closed by the stream so don't call lob.close()
setLong(i, oid);
}
}
public void setClob(int i, Clob x) throws SQLException
{
checkClosed();
if (x == null)
{
setNull(i, Types.CLOB);
return;
}
Reader l_inStream = x.getCharacterStream();
int l_length = (int) x.length();
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
Charset connectionCharset = Charset.forName(connection.getEncoding().name());
OutputStream los = lob.getOutputStream();
Writer lw = new OutputStreamWriter(los, connectionCharset);
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c = l_inStream.read();
int p = 0;
while (c > -1 && p < l_length)
{
lw.write(c);
c = l_inStream.read();
p++;
}
lw.close();
}
catch (IOException se)
{
throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se);
}
// lob is closed by the stream so don't call lob.close()
setLong(i, oid);
}
public void setNull(int i, int t, String s) throws SQLException
{
checkClosed();
setNull(i, t);
}
public void setRef(int i, Ref x) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "setRef(int,Ref)");
}
public void setDate(int i, java.sql.Date d, java.util.Calendar cal) throws SQLException
{
checkClosed();
if (d == null)
{
setNull(i, Types.DATE);
return;
}
if (connection.binaryTransferSend(Oid.DATE)) {
byte[] val = new byte[4];
TimeZone tz = cal != null ? cal.getTimeZone() : null;
connection.getTimestampUtils().toBinDate(tz, val, d);
preparedParameters.setBinaryParameter(i, val, Oid.DATE);
return;
}
if (cal != null)
cal = (Calendar)cal.clone();
// We must use UNSPECIFIED here, or inserting a Date-with-timezone into a
// timestamptz field does an unexpected rotation by the server's TimeZone:
//
// We want to interpret 2005/01/01 with calendar +0100 as
// "local midnight in +0100", but if we go via date it interprets it
// as local midnight in the server's timezone:
// template1=# select '2005-01-01+0100'::timestamptz;
// timestamptz
// ------------------------
// 2005-01-01 02:00:00+03
// (1 row)
// template1=# select '2005-01-01+0100'::date::timestamptz;
// timestamptz
// ------------------------
// 2005-01-01 00:00:00+03
// (1 row)
bindString(i, connection.getTimestampUtils().toString(cal, d), Oid.UNSPECIFIED);
}
public void setTime(int i, Time t, java.util.Calendar cal) throws SQLException
{
checkClosed();
if (t == null)
{
setNull(i, Types.TIME);
return;
}
if (cal != null)
cal = (Calendar)cal.clone();
bindString(i, connection.getTimestampUtils().toString(cal, t), Oid.UNSPECIFIED);
}
public void setTimestamp(int i, Timestamp t, java.util.Calendar cal) throws SQLException
{
checkClosed();
if (t == null) {
setNull(i, Types.TIMESTAMP);
return;
}
if (cal != null)
cal = (Calendar)cal.clone();
// Use UNSPECIFIED as a compromise to get both TIMESTAMP and TIMESTAMPTZ working.
// This is because you get this in a +1300 timezone:
//
// template1=# select '2005-01-01 15:00:00 +1000'::timestamptz;
// timestamptz
// ------------------------
// 2005-01-01 18:00:00+13
// (1 row)
// template1=# select '2005-01-01 15:00:00 +1000'::timestamp;
// timestamp
// ---------------------
// 2005-01-01 15:00:00
// (1 row)
// template1=# select '2005-01-01 15:00:00 +1000'::timestamptz::timestamp;
// timestamp
// ---------------------
// 2005-01-01 18:00:00
// (1 row)
// So we want to avoid doing a timestamptz -> timestamp conversion, as that
// will first convert the timestamptz to an equivalent time in the server's
// timezone (+1300, above), then turn it into a timestamp with the "wrong"
// time compared to the string we originally provided. But going straight
// to timestamp is OK as the input parser for timestamp just throws away
// the timezone part entirely. Since we don't know ahead of time what type
// we're actually dealing with, UNSPECIFIED seems the lesser evil, even if it
// does give more scope for type-mismatch errors being silently hidden.
bindString(i, connection.getTimestampUtils().toString(cal, t), Oid.UNSPECIFIED); // Let the server infer the right type.
}
// ** JDBC 2 Extensions for CallableStatement**
public java.sql.Array getArray(int i) throws SQLException
{
checkClosed();
checkIndex(i, Types.ARRAY, "Array");
return (Array)callResult[i-1];
}
public java.math.BigDecimal getBigDecimal(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal");
return ((BigDecimal)callResult[parameterIndex-1]);
}
public Blob getBlob(int i) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "getBlob(int)");
}
public Clob getClob(int i) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "getClob(int)");
}
public Object getObjectImpl(int i, java.util.Map map) throws SQLException
{
if (map == null || map.isEmpty()) {
return getObject(i);
}
throw Driver.notImplemented(this.getClass(), "getObjectImpl(int,Map)");
}
public Ref getRef(int i) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "getRef(int)");
}
public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
{
checkClosed();
checkIndex(i, Types.DATE, "Date");
if (callResult[i-1] == null)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
String value = callResult[i-1].toString();
return connection.getTimestampUtils().toDate(cal, value);
}
public Time getTime(int i, java.util.Calendar cal) throws SQLException
{
checkClosed();
checkIndex(i, Types.TIME, "Time");
if (callResult[i-1] == null)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
String value = callResult[i-1].toString();
return connection.getTimestampUtils().toTime(cal, value);
}
public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
{
checkClosed();
checkIndex(i, Types.TIMESTAMP, "Timestamp");
if (callResult[i-1] == null)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
String value = callResult[i-1].toString();
return connection.getTimestampUtils().toTimestamp(cal, value);
}
// no custom types allowed yet..
public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "registerOutParameter(int,int,String)");
}
protected synchronized void startTimer()
{
if (timeout == 0)
return;
/*
* there shouldn't be any previous timer active, but better safe than
* sorry.
*/
killTimerTask();
cancelTimerTask = new TimerTask() {
public void run()
{
try {
AbstractJdbc2Statement.this.cancel();
} catch (SQLException e) {
}
}
};
connection.addTimerTask(cancelTimerTask, timeout * 1000);
}
private synchronized void killTimerTask()
{
if (cancelTimerTask != null) {
cancelTimerTask.cancel();
cancelTimerTask = null;
connection.purgeTimerTasks();
}
}
protected boolean getForceBinaryTransfer()
{
return forceBinaryTransfers;
}
}
| ekoontz/pgjdbc | org/postgresql/jdbc2/AbstractJdbc2Statement.java | Java | bsd-3-clause | 126,655 |
package netcode
import (
"log"
"net"
"time"
)
const CLIENT_MAX_RECEIVE_PACKETS = 64
const PACKET_SEND_RATE = 10.0
const NUM_DISCONNECT_PACKETS = 10 // number of disconnect packets the client/server should send when disconnecting
type Context struct {
WritePacketKey []byte
ReadPacketKey []byte
}
type ClientState int8
const (
StateTokenExpired ClientState = -6
StateInvalidConnectToken = -5
StateConnectionTimedOut = -4
StateConnectionResponseTimedOut = -3
StateConnectionRequestTimedOut = -2
StateConnectionDenied = -1
StateDisconnected = 0
StateSendingConnectionRequest = 1
StateSendingConnectionResponse = 2
StateConnected = 3
)
var clientStateMap = map[ClientState]string{
StateTokenExpired: "connect token expired",
StateInvalidConnectToken: "invalid connect token",
StateConnectionTimedOut: "connection timed out",
StateConnectionResponseTimedOut: "connection response timed out",
StateConnectionRequestTimedOut: "connection request timed out",
StateConnectionDenied: "connection denied",
StateDisconnected: "disconnected",
StateSendingConnectionRequest: "sending connection request",
StateSendingConnectionResponse: "sending connection response",
StateConnected: "connected",
}
type Client struct {
id uint64
connectToken *ConnectToken
time float64
startTime float64
lastPacketSendTime float64
lastPacketRecvTime float64
shouldDisconnect bool
state ClientState
shouldDisconnectState ClientState
sequence uint64
challengeSequence uint64
clientIndex uint32
maxClients uint32
serverIndex int
address *net.UDPAddr
serverAddress *net.UDPAddr
challengeData []byte
context *Context
replayProtection *ReplayProtection
conn *NetcodeConn
packetQueue *PacketQueue
allowedPackets []byte
packetCh chan *NetcodeData
}
func NewClient(connectToken *ConnectToken) *Client {
c := &Client{connectToken: connectToken}
c.lastPacketRecvTime = -1
c.lastPacketSendTime = -1
c.packetCh = make(chan *NetcodeData, PACKET_QUEUE_SIZE)
c.setState(StateDisconnected)
c.shouldDisconnect = false
c.challengeData = make([]byte, CHALLENGE_TOKEN_BYTES)
c.context = &Context{}
c.packetQueue = NewPacketQueue(PACKET_QUEUE_SIZE)
c.replayProtection = NewReplayProtection()
c.allowedPackets = make([]byte, ConnectionNumPackets)
c.allowedPackets[ConnectionDenied] = 1
c.allowedPackets[ConnectionChallenge] = 1
c.allowedPackets[ConnectionKeepAlive] = 1
c.allowedPackets[ConnectionPayload] = 1
c.allowedPackets[ConnectionDisconnect] = 1
return c
}
func (c *Client) GetState() ClientState {
return c.state
}
func (c *Client) SetId(id uint64) {
c.id = id
}
func (c *Client) setState(newState ClientState) {
c.state = newState
}
func (c *Client) Connect() error {
var err error
c.startTime = 0
if c.serverIndex > len(c.connectToken.ServerAddrs) {
return ErrExceededServerNumber
}
c.serverAddress = &c.connectToken.ServerAddrs[c.serverIndex]
c.conn = NewNetcodeConn()
c.conn.SetRecvHandler(c.handleNetcodeData)
if err = c.conn.Dial(c.serverAddress); err != nil {
return err
}
c.context.ReadPacketKey = c.connectToken.ServerKey
c.context.WritePacketKey = c.connectToken.ClientKey
c.setState(StateSendingConnectionRequest)
return nil
}
func (c *Client) connectNextServer() bool {
if c.serverIndex+1 >= len(c.connectToken.ServerAddrs) {
return false
}
c.serverIndex++
c.serverAddress = &c.connectToken.ServerAddrs[c.serverIndex]
c.Reset()
log.Printf("client[%d] connecting to next server %s (%d/%d)\n", c.id, c.serverAddress.String(), c.serverIndex, len(c.connectToken.ServerAddrs))
if err := c.Connect(); err != nil {
log.Printf("error connecting to next server: %s\n", err)
return false
}
c.setState(StateSendingConnectionRequest)
return true
}
func (c *Client) Close() error {
return c.conn.Close()
}
func (c *Client) Reset() {
c.lastPacketSendTime = c.time - 1
c.lastPacketRecvTime = c.time
c.shouldDisconnect = false
c.shouldDisconnectState = StateDisconnected
c.challengeData = make([]byte, CHALLENGE_TOKEN_BYTES)
c.challengeSequence = 0
c.replayProtection.Reset()
}
func (c *Client) resetConnectionData(newState ClientState) {
c.sequence = 0
c.clientIndex = 0
c.maxClients = 0
c.startTime = 0
c.serverIndex = 0
c.serverAddress = nil
c.connectToken = nil
c.context = nil
c.setState(newState)
c.Reset()
c.packetQueue.Clear()
c.conn.Close()
}
func (c *Client) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *Client) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
func (c *Client) Update(t float64) {
c.time = t
c.recv()
if err := c.send(); err != nil {
log.Printf("error sending packet: %s\n", err)
}
state := c.GetState()
if state > StateDisconnected && state < StateConnected {
expire := c.connectToken.ExpireTimestamp - c.connectToken.CreateTimestamp
if c.startTime+float64(expire) <= c.time {
log.Printf("client[%d] connect failed. connect token expired\n", c.id)
c.Disconnect(StateTokenExpired, false)
return
}
}
if c.shouldDisconnect {
log.Printf("client[%d] should disconnect -> %s\n", c.id, clientStateMap[c.shouldDisconnectState])
if c.connectNextServer() {
return
}
c.Disconnect(c.shouldDisconnectState, false)
return
}
switch c.GetState() {
case StateSendingConnectionRequest:
timeout := c.lastPacketRecvTime + float64(c.connectToken.TimeoutSeconds*1000)
if timeout < c.time {
log.Printf("client[%d] connection request timed out.\n", c.id)
if c.connectNextServer() {
return
}
c.Disconnect(StateConnectionRequestTimedOut, false)
}
case StateSendingConnectionResponse:
timeout := c.lastPacketRecvTime + float64(c.connectToken.TimeoutSeconds*1000)
if timeout < c.time {
log.Printf("client[%d] connect failed. connection response timed out\n", c.id)
if c.connectNextServer() {
return
}
c.Disconnect(StateConnectionResponseTimedOut, false)
}
case StateConnected:
timeout := c.lastPacketRecvTime + float64(c.connectToken.TimeoutSeconds*1000)
if timeout < c.time {
log.Printf("client[%d] connection timed out\n", c.id)
c.Disconnect(StateConnectionTimedOut, false)
}
}
}
func (c *Client) recv() {
// empty recv'd data from channel
for {
select {
case recv := <-c.packetCh:
c.OnPacketData(recv.data, recv.from)
default:
return
}
}
}
func (c *Client) Disconnect(reason ClientState, sendDisconnect bool) error {
log.Printf("client[%d] disconnected: %s\n", c.id, clientStateMap[reason])
if c.GetState() <= StateDisconnected {
log.Printf("state <= StateDisconnected")
return nil
}
if sendDisconnect && c.GetState() > StateDisconnected {
for i := 0; i < NUM_DISCONNECT_PACKETS; i += 1 {
packet := &DisconnectPacket{}
c.sendPacket(packet)
}
}
c.resetConnectionData(reason)
return nil
}
func (c *Client) SendData(payloadData []byte) error {
if c.GetState() != StateConnected {
return ErrClientNotConnected
}
p := NewPayloadPacket(payloadData)
return c.sendPacket(p)
}
func (c *Client) send() error {
// check our send rate prior to bother sending
if c.lastPacketSendTime+float64(1.0/PACKET_SEND_RATE) >= c.time {
return nil
}
switch c.GetState() {
case StateSendingConnectionRequest:
p := &RequestPacket{}
p.VersionInfo = c.connectToken.VersionInfo
p.ProtocolId = c.connectToken.ProtocolId
p.ConnectTokenExpireTimestamp = c.connectToken.ExpireTimestamp
p.ConnectTokenSequence = c.connectToken.Sequence
p.ConnectTokenData = c.connectToken.PrivateData.Buffer()
log.Printf("client[%d] sent connection request packet to server\n", c.id)
return c.sendPacket(p)
case StateSendingConnectionResponse:
p := &ResponsePacket{}
p.ChallengeTokenSequence = c.challengeSequence
p.ChallengeTokenData = c.challengeData
log.Printf("client[%d] sent connection response packet to server\n", c.id)
return c.sendPacket(p)
case StateConnected:
p := &KeepAlivePacket{}
p.ClientIndex = 0
p.MaxClients = 0
log.Printf("client[%d] sent connection keep-alive packet to server\n", c.id)
return c.sendPacket(p)
}
return nil
}
func (c *Client) sendPacket(packet Packet) error {
buffer := make([]byte, MAX_PACKET_BYTES)
packet_bytes, err := packet.Write(buffer, c.connectToken.ProtocolId, c.sequence, c.context.WritePacketKey)
if err != nil {
return err
}
_, err = c.conn.Write(buffer[:packet_bytes])
if err != nil {
log.Printf("error writing packet %s to server: %s\n", packetTypeMap[packet.GetType()], err)
}
c.lastPacketSendTime = c.time
c.sequence++
return err
}
func (c *Client) RecvData() ([]byte, uint64) {
packet := c.packetQueue.Pop()
p, ok := packet.(*PayloadPacket)
if !ok {
return nil, 0
}
return p.PayloadData, p.sequence
}
// write the netcodeData to our unbuffered packet channel. The NetcodeConn verifies
// that the recv'd data is > 0 < maxBytes and is of a valid packet type before
// this is even called.
func (c *Client) handleNetcodeData(packetData *NetcodeData) {
c.packetCh <- packetData
}
func (c *Client) OnPacketData(packetData []byte, from *net.UDPAddr) {
var err error
var size int
var sequence uint64
if !addressEqual(c.serverAddress, from) {
log.Printf("client[%d] unknown/old server address sent us data %s != %s\n", c.id, c.serverAddress.String(), from.String())
return
}
size = len(packetData)
timestamp := uint64(time.Now().Unix())
packet := NewPacket(packetData)
if err = packet.Read(packetData, size, c.connectToken.ProtocolId, timestamp, c.context.ReadPacketKey, nil, c.allowedPackets, c.replayProtection); err != nil {
log.Printf("error reading packet: %s\n", err)
}
c.processPacket(packet, sequence)
}
func (c *Client) processPacket(packet Packet, sequence uint64) {
state := c.GetState()
switch packet.GetType() {
case ConnectionDenied:
if state == StateSendingConnectionRequest || state == StateSendingConnectionResponse {
c.shouldDisconnect = true
c.shouldDisconnectState = StateConnectionDenied
}
case ConnectionChallenge:
if state != StateSendingConnectionRequest {
return
}
p, ok := packet.(*ChallengePacket)
if !ok {
return
}
c.challengeData = p.ChallengeTokenData
c.challengeSequence = p.ChallengeTokenSequence
c.setState(StateSendingConnectionResponse)
case ConnectionKeepAlive:
p, ok := packet.(*KeepAlivePacket)
if !ok {
return
}
if state == StateSendingConnectionResponse {
c.clientIndex = p.ClientIndex
c.maxClients = p.MaxClients
c.setState(StateConnected)
}
case ConnectionPayload:
if state != StateConnected {
return
}
c.packetQueue.Push(packet)
case ConnectionDisconnect:
if state != StateConnected {
return
}
c.shouldDisconnect = true
c.shouldDisconnectState = StateDisconnected
default:
return
}
// always update last packet recv time for valid packets.
c.lastPacketRecvTime = c.time
}
| wirepair/netcode | client.go | GO | bsd-3-clause | 11,175 |
"""
SymPy core decorators.
The purpose of this module is to expose decorators without any other
dependencies, so that they can be easily imported anywhere in sympy/core.
"""
from functools import wraps
from sympify import SympifyError, sympify
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
@wraps(func)
def new_func(*args, **kwargs):
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(
"Call to deprecated function.",
feature=func.__name__ + "()"
).warn()
return func(*args, **kwargs)
return new_func
def _sympifyit(arg, retval=None):
"""decorator to smartly _sympify function arguments
@_sympifyit('other', NotImplemented)
def add(self, other):
...
In add, other can be thought of as already being a SymPy object.
If it is not, the code is likely to catch an exception, then other will
be explicitly _sympified, and the whole code restarted.
if _sympify(arg) fails, NotImplemented will be returned
see: __sympifyit
"""
def deco(func):
return __sympifyit(func, arg, retval)
return deco
def __sympifyit(func, arg, retval=None):
"""decorator to _sympify `arg` argument for function `func`
don't use directly -- use _sympifyit instead
"""
# we support f(a,b) only
assert func.func_code.co_argcount
# only b is _sympified
assert func.func_code.co_varnames[1] == arg
if retval is None:
@wraps(func)
def __sympifyit_wrapper(a, b):
return func(a, sympify(b, strict=True))
else:
@wraps(func)
def __sympifyit_wrapper(a, b):
try:
return func(a, sympify(b, strict=True))
except SympifyError:
return retval
return __sympifyit_wrapper
def call_highest_priority(method_name):
"""A decorator for binary special methods to handle _op_priority.
Binary special methods in Expr and its subclasses use a special attribute
'_op_priority' to determine whose special method will be called to
handle the operation. In general, the object having the highest value of
'_op_priority' will handle the operation. Expr and subclasses that define
custom binary special methods (__mul__, etc.) should decorate those
methods with this decorator to add the priority logic.
The ``method_name`` argument is the name of the method of the other class
that will be called. Use this decorator in the following manner::
# Call other.__rmul__ if other._op_priority > self._op_priority
@call_highest_priority('__rmul__')
def __mul__(self, other):
...
# Call other.__mul__ if other._op_priority > self._op_priority
@call_highest_priority('__mul__')
def __rmul__(self, other):
...
"""
def priority_decorator(func):
def binary_op_wrapper(self, other):
if hasattr(other, '_op_priority'):
if other._op_priority > self._op_priority:
try:
f = getattr(other, method_name)
except AttributeError:
pass
else:
return f(self)
return func(self, other)
return binary_op_wrapper
return priority_decorator
| ichuang/sympy | sympy/core/decorators.py | Python | bsd-3-clause | 3,543 |
from .models import CreateModel, DeleteModel, AlterModelTable, AlterUniqueTogether, AlterIndexTogether
from .fields import AddField, RemoveField, AlterField, RenameField
| denisenkom/django | django/db/migrations/operations/__init__.py | Python | bsd-3-clause | 170 |
<?php
namespace app\controllers;
use yii\web\Controller;
class AppController extends Controller {
protected function setMeta( $title = null, $keywords = null, $description = null ) { //Устанавливаем мета-теги
$this->view->title = $title;
$this->view->registerMetaTag(['name' => 'keywords', 'content' => "$keywords"]);
$this->view->registerMetaTag(['name' => 'description', 'content' => "$description"]);
}
} | RuslanKozin/yii2-int.mag | controllers/AppController.php | PHP | bsd-3-clause | 472 |
<?php
//
// Scry - Simple PHP Photo Album
// Copyright 2004 James Byers <jbyers@users.sf.net>
// http://scry.org
//
// Scry is distributed under a BSD License. See LICENSE for details.
//
// $Id: functions.php,v 1.18 2004/11/29 00:42:56 jbyers Exp $
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !! !!
// !! NOTE - this file does not need to be edited; see setup.php !!
// !! !!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
//////////////////////////////////////////////////////////////////////////////
// Security
//
// Two functions contain filesystem calls (search for "FS" in this
// file):
//
// directory_data()
// cache_test()
//
// function path_security_check(string $victim, string $test)
//
// the resolved path of $victim must be below $test on the filesystem
// check only if victim exists; otherwise realpath cannot resolve path
//
function path_security_check($victim, $test) {
if (!realpath($victim) ||
//eregi("^" . rtrim($test, '/') . ".*", rtrim(realpath($victim), '/'))) {
preg_match("/^" . rtrim('/', $test) . ".*/", rtrim('/', realpath($victim)))) {
return true;
}
die("path security check failed: $victim - $test");
} // function path_security_check
// function parse_resolution(string $res)
//
// converts a string dimension (800x600, 800X600, 800 x 600, 800 X 600)
// to a two-element array
//
function parse_resolution($res) {
//return(explode('x', ereg_replace('[^0-9x]', '', strtolower($res))));
return(explode('x', preg_replace('/[^0-9x]/', '', strtolower($res))));
} // function parse_resolution
// function cache_test(string $url, int $x, int $y) {
//
// creates the file's cache path and tests for existance in the cache
// returns:
// array(
// is_cached,
// name,
// path,
// cache_url
// )
//
function cache_test($url, $x, $y) {
global $CFG_cache_enable, $CFG_path_cache, $CFG_url_cache;
// cache paths and URL references to images must be URL and filesystem safe
// pure urlencoding would require double-urlencoding image URLs -- confusing
// instead replace %2f (/) with ! and % with $ (!, $ are URL safe) for readability and consistency between two versions
//
//ereg("(.*)(\.[A-Za-z0-9]+)$", $url, $matches);
preg_match("/(.*)(\.[A-Za-z0-9]+)$/", $url, $matches);
$result = array();
$result['is_cached'] = false;
$result['name'] = str_replace('%', '$', str_replace('%2F', '!', urlencode($matches[1]))) . '_' . $x . 'x' . $y . $matches[2];
$result['path'] = $CFG_path_cache . '/' . $result['name'];
$result['cache_url'] = $CFG_url_cache . '/' . $result['name'];
path_security_check($result['path'], $CFG_path_cache);
if ($CFG_cache_enable && is_file($result['path']) && is_readable($result['path'])) { // FS READ
$result['is_cached'] = true;
}
return $result;
} // function cache_test
// function directory_data(string $path, string $url_path)
//
// walks the specified directory and returns an array containing image file
// and directory details:
//
// array(
// files => array(
// name,
// index,
// path,
// thumb_url,
// image_url,
// view_url,
// raw_url
// ),
// directories => array(
// name,
// index,
// list_url
// )
// )
//
// note: only files with extensions matching $CFG_image_valid are included
// '.' and '..' are not referenced in the directory array
//
function directory_data($path, $url_path) {
global $CFG_image_valid, $CFG_url_album, $CFG_thumb_width, $CFG_thumb_height, $CFG_image_width, $CFG_image_height, $CFG_path_images, $CFG_cache_outside_docroot, $CFG_movies_enabled, $CFG_movie_valid;
//compensate for switching away from eregi
$CFG_image_valid_i = array();
foreach($CFG_image_valid as $e) {
$CFG_image_valid_i[] = $e;
$CFG_image_valid_i[] = strtoupper($e);
}
if ($CFG_movies_enabled) {
$CFG_movie_valid_i = array();
foreach($CFG_movie_valid as $e) {
$CFG_image_valid_i[] = $e;
$CFG_image_valid_i[] = strtoupper($e);
$CFG_movie_valid_i[] = $e;
$CFG_movie_valid_i[] = strtoupper($e);
}
}
// put CFG_image_valid array into eregi form
//
$valid_extensions = '(.' . implode('|.', $CFG_image_valid_i) . ')$';
if ($CFG_movies_enabled) {
$valid_movie_extensions = '(.' . implode('|.', $CFG_movie_valid_i) . ')$';
}
path_security_check($path, $CFG_path_images);
// load raw directory first, sort, and reprocess
//
$files_raw = array();
$dirs_raw = array();
if ($h_dir = opendir($path)) { // FS READ
while (false !== ($filename = readdir($h_dir))) { // FS READ
if ($filename != '.' && $filename != '..') {
// set complete url
//
if ($url_path == '') {
$url = $filename;
} else {
$url = "$url_path/$filename";
}
path_security_check("$path/$filename", $CFG_path_images);
if (is_readable("$path/$filename") && // FS READ
is_file("$path/$filename") && // FS READ
//eregi($valid_extensions, $filename)) {
preg_match("/{$valid_extensions}/", $filename)) {
$files_raw[] = array('name' => $filename,
'url' => $url);
} else if (is_readable("$path/$filename") &&
is_dir("$path/$filename") &&
substr($filename, 0, 1) != '_') { // FS READ
$dirs_raw[] = array('name' => $filename,
'url' => $url);
} // if ... else is_file or is_dir
} // if
} // while
closedir($h_dir); // FS READ
} // if opendir
// sort directory arrays by filename
//
function cmp($a, $b) {
global $CFG_sort_reversed;
if (!$CFG_sort_reversed) {
return strcasecmp($a['name'], $b['name']);
} else {
return strcasecmp($b['name'], $a['name']);
}
} // function cmp
@usort($dirs_raw, 'cmp');
@usort($files_raw, 'cmp');
// reprocess arrays
//
$files = array();
$dirs = array();
$file_count = 0;
$dir_count = 0;
while (list($k, $v) = each($files_raw)) {
// set thumbnail cached vs. not
//
$thumb = cache_test($v['url'], $CFG_thumb_width, $CFG_thumb_height); // FS FUNCTION
$image = cache_test($v['url'], $CFG_view_width, $CFG_view_height); // FS FUNCTION
if ($CFG_cache_outside_docroot || !$thumb['is_cached']) {
$thumb_url = build_url('image', $CFG_thumb_width . 'x' . $CFG_thumb_height, $v['url']);
} else {
$thumb_url = $thumb['cache_url'];
}
if ($CFG_cache_outside_docroot || !$image['is_cached']) {
$image_url = build_url('image', $CFG_image_width . 'x' . $CFG_image_height, $v['url']);
} else {
$image_url = $image['cache_url'];
}
path_security_check("$path/$v[name]", $CFG_path_images);
if ($CFG_movies_enabled) {
if (preg_match("/{$valid_movie_extensions}/", "$v[name]")) {
$ismovie = true;
} else {
$ismovie = false;
}
}
$files[] = array('name' => $v['name'],
'index' => $file_count,
'path' => "$path/$v[name]",
'thumb_url' => $thumb_url,
'image_url' => $image_url,
'view_url' => build_url('view', $file_count, $v['url']),
'raw_url' => build_url('image', '0', $v['url']), // 0 index for raw image
'is_movie' => $ismovie);
$file_count++;
}
while (list($k, $v) = each($dirs_raw)) {
$dirs[] = array('name' => $v['name'],
'index' => $dir_count,
'list_url' => build_url('list', '0', $v['url']));
$dir_count++;
}
return(array('files' => $files, 'directories' => $dirs));
} // function directory_data
// function path_list(string $path)
//
// return list of path parts and URLs in an array:
//
// array(
// url,
// name
// )
//
function path_list($path) {
global $CFG_url_album, $CFG_album_name;
$image_subdir_parts = array();
if ($path != '') {
$image_subdir_parts = explode('/', $path);
}
$path_list[] = array('url' => $CFG_url_album,
'name' => $CFG_album_name);
for ($i = 0; $i < count($image_subdir_parts); $i++) {
list($k, $v) = each($image_subdir_parts);
$path_list[] = array('url' => build_url('list', '0', implode('/', array_slice($image_subdir_parts, 0, $i + 1))),
'name' => $image_subdir_parts[$i]);
} // for
return $path_list;
} // function path_data
// function debug(string $type[, string $message])
//
// sets an entry in global DEBUG_MESSAGES
//
function debug($type, $message = '') {
global $DEBUG_MESSAGES;
if ($message == '') {
$message = $type;
$type = 'debug';
} // if
if (is_array($message) || is_object($message)) {
ob_start();
var_dump($message);
$message = ob_get_contents();
ob_end_clean();
} // if
$DEBUG_MESSAGES[] = "[$type]: $message";
} // function debug
// return a URL string based on view, index, path components and CFG vars
//
function build_url($view, $index, $path) {
global $CFG_variable_mode, $CFG_url_album;
if ($CFG_variable_mode == 'path') {
return("$CFG_url_album/$view/$index/" . str_replace('%2F', '/', urlencode($path)));
} else {
return("$CFG_url_album?v=$view&i=$index&p=" . str_replace('%2F', '/', urlencode($path)));
}
} // function build_url
// function resize($x, $y)
// calculates resized image based on image x1,y1 and bounding box x2,y2
// three modes: constant X, constant Y, full bounding box
// returns array(x, y)
//
function calculate_resize($x1, $y1, $x2, $y2) {
global $CFG_resize_mode;
switch ($CFG_resize_mode) {
case 'X':
(int)$resize_x = $x2;
if ( $x1 != "" ) {
(int)$resize_y = round(($y1 * $x2)/$x1);
}
break;
case 'Y':
if ( $y1 != "" ) {
(int)$resize_x = round(($x1 * $y2)/$y1);
}
(int)$resize_y = $y2;
break;
default:
if ( $y1 != "" ) {
(int)$resize_x = ($x1 <= $y1) ? round(($x1 * $y2)/$y1) : $x2;
}
if ( $x1 != "" ) {
(int)$resize_y = ($x1 > $y1) ? round(($y1 * $x2)/$x1) : $y2;
}
break;
}
return array($resize_x, $resize_y);
} // calculate_resize
?>
| candhill/scry | functions.php | PHP | bsd-3-clause | 10,408 |
<?php
/**
* Part of the Sentinel package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file.
*
* @package Sentinel
* @version 2.0.4
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011-2015, Cartalyst LLC
* @link http://cartalyst.com
*/
namespace Cartalyst\Sentinel\Roles;
use Cartalyst\Support\Traits\RepositoryTrait;
class IlluminateRoleRepository implements RoleRepositoryInterface
{
use RepositoryTrait;
/**
* The Eloquent role model name.
*
* @var string
*/
protected $model = 'Cartalyst\Sentinel\Roles\EloquentRole';
/**
* Create a new Illuminate role repository.
*
* @param string $model
* @return void
*/
public function __construct($model = null)
{
if (isset($model)) {
$this->model = $model;
}
}
/**
* {@inheritDoc}
*/
public function findById($id)
{
return $this
->createModel()
->newQuery()
->find($id);
}
/**
* {@inheritDoc}
*/
public function findBySlug($slug)
{
return $this
->createModel()
->newQuery()
->where('slug', $slug)
->first();
}
/**
* {@inheritDoc}
*/
public function findByName($name)
{
return $this
->createModel()
->newQuery()
->where('name', $name)
->first();
}
}
| junsanity06/Sentinel | src/Roles/IlluminateRoleRepository.php | PHP | bsd-3-clause | 1,637 |
function showMessage(object, message){
if(message == null) message="";
object.text(message);
}
function getEmptyResultHtml(){
flushEmptyResultHtml();
var html = '<div class="emptyMsg text-center" class="text-center">列表为空</div>';
return html;
}
function flushEmptyResultHtml(){
$(".emptyMsg").remove();
}
//一波分页搜索函数
function nextPage(){
var allPages = parseInt($("#allPages").text());
if(adminUserSelect["curPage"]+1 <= allPages){
adminUserSelect["curPage"]++;
changeTable();
$("#curPage").text(adminUserSelect["curPage"]);
}
}
function prevPage(){
if(adminUserSelect["curPage"]-1 >= 1){
adminUserSelect["curPage"]--;
changeTable();
$("#curPage").text(adminUserSelect["curPage"]);
}
}
function changeState(){
var state = parseInt($("#state-select").val());
adminUserSelect["state"] = state;
adminUserSelect["curPage"] = 1;
adminUserSelect["pageCount"] = 10;
changeTable();
$("#curPage").text("1");
}
function searchTextChange(){
var text = $("#searchText").val();
adminUserSelect["searchText"] = text;
adminUserSelect["curPage"] = 1;
adminUserSelect["pageCount"] = 10;
changeTable();
$("#curPage").text("1");
}
function displayLoading(switcher){
if(switcher==true){
$("#loading").show();
}else{
$("#loading").hide();
}
}
//操作checkbox函数
function checkAllBoxes(){
var grouper = $("#check-all")[0].checked;
$("tbody :checkbox").each(function(){
$(this)[0].checked = grouper;
});
}
//清空checkbox
function flushAllBoxes(checked){
$('tbody :checkbox').each(function(){
$(this)[0].checked = checked;
});
}
function getSelectedIdArray(){
var ids = new Array(0);
$("tbody :checkbox").each(function(){
if($(this)[0].checked == true)
ids.push(($(this)[0].id).split("-")[1]);
});
return ids;
}
function getSellerLogoLink(){
} | liujiasheng/kuaidishu | public/js/adminCommon.js | JavaScript | bsd-3-clause | 1,995 |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace TurboControl
{
/// <summary>
/// Summary description for Win32.
/// </summary>
public class Win32
{
[DllImport("gdi32.dll", EntryPoint="BitBlt")]
public static extern int BitBlt (IntPtr hDestC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
[DllImport("gdi32.dll", EntryPoint="CreateCompatibleDC")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll", EntryPoint="DeleteDC")]
public static extern int DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll", EntryPoint="SelectObject")]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
[DllImport("gdi32.dll", EntryPoint="DeleteObject")]
public static extern int DeleteObject(IntPtr hdc);
[DllImport("gdi32.dll", EntryPoint="SetBkColor")]
public static extern int SetBkColor (IntPtr hdc, int crColor);
public const int SRCCOPY = 0xCC0020;
public const int SRCAND = 0x8800C6;
public const int SRCERASE = 0x440328;
public const int SRCINVERT = 0x660046;
public const int SRCPAINT = 0xEE0086;
public const int IMAGE_BITMAP = 0x0;
public const int LR_LOADFROMFILE = 16;
public const int WM_WINDOWPOSCHANGING = 0x46;
public static void TurboBitmapCopy(Graphics g, Bitmap bmp, int targetX, int targetY)
{
IntPtr ptrTargetContext = g.GetHdc();
IntPtr ptrSourceContext = Win32.CreateCompatibleDC(ptrTargetContext);
// Select the bitmap into the source context, keeping the original object
IntPtr ptrOriginalObject;
IntPtr ptrNewObject;
ptrOriginalObject = Win32.SelectObject(ptrSourceContext, bmp.GetHbitmap());
// Copy the bitmap from the source to the target
Win32.BitBlt(ptrTargetContext, targetX, targetY, bmp.Width, bmp.Height, ptrSourceContext, 0, 0, Win32.SRCCOPY);
// 'Select our bitmap out of the dc and delete it
ptrNewObject = Win32.SelectObject(ptrSourceContext, ptrOriginalObject);
Win32.DeleteObject(ptrNewObject);
Win32.DeleteDC(ptrSourceContext);
g.ReleaseHdc(ptrTargetContext);
}
}
public struct WM_PosChanging
{
public int hWnd, hWndInsertAfter, X, Y, cX, cY, Flags;
}
}
| nocoolnicksleft/TurboControl | TurboControl/Win32.cs | C# | bsd-3-clause | 2,229 |
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package service
import (
keybase1 "github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/go-framed-msgpack-rpc/rpc"
"golang.org/x/net/context"
)
type RemoteGPGUI struct {
sessionID int
uicli keybase1.GpgUiClient
}
func NewRemoteGPGUI(sessionID int, c *rpc.Client) *RemoteGPGUI {
return &RemoteGPGUI{
sessionID: sessionID,
uicli: keybase1.GpgUiClient{Cli: c},
}
}
func (r *RemoteGPGUI) SelectKey(ctx context.Context, arg keybase1.SelectKeyArg) (string, error) {
arg.SessionID = r.sessionID
return r.uicli.SelectKey(ctx, arg)
}
func (r *RemoteGPGUI) SelectKeyAndPushOption(ctx context.Context, arg keybase1.SelectKeyAndPushOptionArg) (keybase1.SelectKeyRes, error) {
arg.SessionID = r.sessionID
return r.uicli.SelectKeyAndPushOption(ctx, arg)
}
func (r *RemoteGPGUI) WantToAddGPGKey(ctx context.Context, _ int) (bool, error) {
return r.uicli.WantToAddGPGKey(ctx, r.sessionID)
}
func (r *RemoteGPGUI) ConfirmDuplicateKeyChosen(ctx context.Context, _ int) (bool, error) {
return r.uicli.ConfirmDuplicateKeyChosen(ctx, r.sessionID)
}
func (r *RemoteGPGUI) ConfirmImportSecretToExistingKey(ctx context.Context, _ int) (bool, error) {
return r.uicli.ConfirmImportSecretToExistingKey(ctx, r.sessionID)
}
func (r *RemoteGPGUI) Sign(ctx context.Context, arg keybase1.SignArg) (string, error) {
return r.uicli.Sign(ctx, arg)
}
func (r *RemoteGPGUI) GetTTY(ctx context.Context) (string, error) {
return r.uicli.GetTTY(ctx)
}
| keybase/client | go/service/gpg.go | GO | bsd-3-clause | 1,584 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.browserservices.digitalgoods;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.chromium.chrome.browser.browserservices.digitalgoods.AcknowledgeConverter.PARAM_ACKNOWLEDGE_MAKE_AVAILABLE_AGAIN;
import static org.chromium.chrome.browser.browserservices.digitalgoods.AcknowledgeConverter.PARAM_ACKNOWLEDGE_PURCHASE_TOKEN;
import static org.chromium.chrome.browser.browserservices.digitalgoods.AcknowledgeConverter.RESPONSE_ACKNOWLEDGE;
import static org.chromium.chrome.browser.browserservices.digitalgoods.AcknowledgeConverter.RESPONSE_ACKNOWLEDGE_RESPONSE_CODE;
import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.PLAY_BILLING_ITEM_ALREADY_OWNED;
import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.PLAY_BILLING_ITEM_NOT_OWNED;
import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.PLAY_BILLING_ITEM_UNAVAILABLE;
import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.PLAY_BILLING_OK;
import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.convertResponseCode;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.browser.trusted.TrustedWebActivityCallback;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.payments.mojom.BillingResponseCode;
import org.chromium.payments.mojom.DigitalGoods.AcknowledgeResponse;
import org.chromium.payments.mojom.DigitalGoods.GetDetailsResponse;
import org.chromium.payments.mojom.DigitalGoods.ListPurchasesResponse;
import org.chromium.payments.mojom.ItemDetails;
import org.chromium.payments.mojom.PurchaseDetails;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tests for {@link DigitalGoodsConverterTest}.
*/
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class DigitalGoodsConverterTest {
// TODO(peconn): Add tests for error cases as well.
@Test
public void convertGetDetailsParams() {
String[] itemIds = { "id1", "id2" };
Bundle b = GetDetailsConverter.convertParams(itemIds);
String[] out = b.getStringArray(GetDetailsConverter.PARAM_GET_DETAILS_ITEM_IDS);
assertArrayEquals(itemIds, out);
}
@Test
public void convertItemDetails() {
String id = "id";
String title = "Item";
String desc = "An item.";
String currency = "GBP";
String value = "10";
Bundle bundle =
GetDetailsConverter.createItemDetailsBundle(id, title, desc, currency, value);
ItemDetails item = GetDetailsConverter.convertItemDetails(bundle);
assertItemDetails(item, id, title, desc, currency, value);
assertSubsItemDetails(item, null, null, null, null, null);
}
@Test
public void convertItemDetails_subscriptions() {
String subsPeriod = "2 weeks";
String freeTrialPeriod = "1 week";
String introPriceCurrency = "GBP";
String introPriceValue = "3.0";
String introPricePeriod = "1 month";
Bundle bundle = GetDetailsConverter.createItemDetailsBundle("id", "Title", "desc", "GBP",
"10.0", subsPeriod, freeTrialPeriod, introPriceCurrency, introPriceValue,
introPricePeriod);
ItemDetails item = GetDetailsConverter.convertItemDetails(bundle);
assertSubsItemDetails(item, subsPeriod, freeTrialPeriod, introPriceCurrency,
introPriceValue, introPricePeriod);
}
/**
* A class to allow passing values out of callbacks.
*/
private static class TestState<T> {
public int responseCode;
public T[] results;
}
@Test
public void convertGetDetailsCallback() {
TestState<ItemDetails> state = new TestState<>();
GetDetailsResponse callback = (responseCode, itemDetails) -> {
state.responseCode = responseCode;
state.results = itemDetails;
};
TrustedWebActivityCallback convertedCallback =
GetDetailsConverter.convertCallback(callback);
int responseCode = 0;
Bundle args = GetDetailsConverter.createResponseBundle(responseCode,
GetDetailsConverter.createItemDetailsBundle("1", "t1", "d1", "c1", "v1"),
GetDetailsConverter.createItemDetailsBundle(
"2", "t2", "d2", "c2", "v2", "sp2", "ftp2", "ipc2", "ipv2", "ipp2"));
convertedCallback.onExtraCallback(GetDetailsConverter.RESPONSE_COMMAND, args);
assertEquals(DigitalGoodsConverter.convertResponseCode(responseCode, Bundle.EMPTY),
state.responseCode);
assertItemDetails(state.results[0], "1", "t1", "d1", "c1", "v1");
assertSubsItemDetails(state.results[0], null, null, null, null, null);
assertItemDetails(state.results[1], "2", "t2", "d2", "c2", "v2");
assertSubsItemDetails(state.results[1], "sp2", "ftp2", "ipc2", "ipv2", "ipp2");
}
private static void assertItemDetails(ItemDetails item, String id, String title, String desc,
String currency, String value) {
assertEquals(id, item.itemId);
assertEquals(title, item.title);
assertEquals(desc, item.description);
assertEquals(currency, item.price.currency);
assertEquals(value, item.price.value);
}
private static void assertSubsItemDetails(ItemDetails item, @Nullable String subsPeriod,
@Nullable String freeTrialPeriod, @Nullable String introPriceCurrency,
@Nullable String introPriceValue, @Nullable String intoPricePeriod) {
assertEquals(subsPeriod, item.subscriptionPeriod);
assertEquals(freeTrialPeriod, item.freeTrialPeriod);
if (introPriceCurrency == null || introPriceValue == null) {
assertNull(item.introductoryPrice);
} else {
assertEquals(introPriceCurrency, item.introductoryPrice.currency);
assertEquals(introPriceValue, item.introductoryPrice.value);
}
assertEquals(intoPricePeriod, item.introductoryPricePeriod);
}
@Test
public void convertAcknowledgeParams() {
String token = "abcdef";
boolean makeAvailableAgain = true;
Bundle b = AcknowledgeConverter.convertParams(token, makeAvailableAgain);
String outToken = b.getString(PARAM_ACKNOWLEDGE_PURCHASE_TOKEN);
boolean outMakeAvailableAgain = b.getBoolean(PARAM_ACKNOWLEDGE_MAKE_AVAILABLE_AGAIN);
assertEquals(token, outToken);
assertEquals(makeAvailableAgain, outMakeAvailableAgain);
}
@Test
public void convertAcknowledgeCallback() {
// Since there's only one value we want to get out of the callback, we can use Atomic*
// instead of creating a new class.
AtomicInteger state = new AtomicInteger();
AcknowledgeResponse callback = (responseCode) -> state.set(responseCode);
TrustedWebActivityCallback convertedCallback =
AcknowledgeConverter.convertCallback(callback);
Bundle args = new Bundle();
int responseCode = 0;
args.putInt(RESPONSE_ACKNOWLEDGE_RESPONSE_CODE, responseCode);
convertedCallback.onExtraCallback(RESPONSE_ACKNOWLEDGE, args);
assertEquals(responseCode, state.get());
}
@Test
public void convertListPurchases() {
String id = "id";
String token = "token";
boolean acknowledged = true;
int state = 2;
long time = 1234L;
boolean autoRenew = true;
Bundle bundle = ListPurchasesConverter.createPurchaseDetailsBundle(
id, token, acknowledged, state, time, autoRenew);
PurchaseDetails details = ListPurchasesConverter.convertPurchaseDetails(bundle);
assertPurchaseDetails(details, id, token, acknowledged, state, time, autoRenew);
}
private static void assertPurchaseDetails(PurchaseDetails details, String itemId,
String purchaseToken, boolean acknowledged, int purchaseState, long purchaseTime,
boolean willAutoRenew) {
assertEquals(details.itemId, itemId);
assertEquals(details.purchaseToken, purchaseToken);
assertEquals(details.acknowledged, acknowledged);
assertEquals(details.purchaseState, purchaseState);
assertEquals(details.purchaseTime.microseconds, purchaseTime);
assertEquals(details.willAutoRenew, willAutoRenew);
}
@Test
public void convertListPurchases_wrongTypes() {
Bundle validBundle = ListPurchasesConverter.createPurchaseDetailsBundle(
"id", "token", true, 1, 2L, true);
assertNotNull(ListPurchasesConverter.convertPurchaseDetails(validBundle));
{
Bundle bundle = validBundle.deepCopy();
bundle.putInt(ListPurchasesConverter.KEY_ITEM_ID, 5);
assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle));
}
{
Bundle bundle = validBundle.deepCopy();
bundle.putInt(ListPurchasesConverter.KEY_PURCHASE_TOKEN, 5);
assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle));
}
{
Bundle bundle = validBundle.deepCopy();
bundle.putInt(ListPurchasesConverter.KEY_ACKNOWLEDGED, 5);
assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle));
}
{
Bundle bundle = validBundle.deepCopy();
bundle.putBoolean(ListPurchasesConverter.KEY_PURCHASE_STATE, true);
assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle));
}
{
Bundle bundle = validBundle.deepCopy();
bundle.putInt(ListPurchasesConverter.KEY_PURCHASE_TIME_MICROSECONDS_PAST_UNIX_EPOCH, 5);
assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle));
}
{
Bundle bundle = validBundle.deepCopy();
bundle.putInt(ListPurchasesConverter.KEY_WILL_AUTO_RENEW, 5);
assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle));
}
}
@Test
public void convertListPurchasesCallback() {
TestState<PurchaseDetails> state = new TestState<>();
ListPurchasesResponse callback = (responseCode, purchaseDetails) -> {
state.responseCode = responseCode;
state.results = purchaseDetails;
};
TrustedWebActivityCallback convertedCallback =
ListPurchasesConverter.convertCallback(callback);
int responseCode = 0;
Bundle args = ListPurchasesConverter.createResponseBundle(responseCode,
ListPurchasesConverter.createPurchaseDetailsBundle("1", "t1", true, 1, 1L, true),
ListPurchasesConverter.createPurchaseDetailsBundle("2", "t2", false, 2, 2L, false));
convertedCallback.onExtraCallback(ListPurchasesConverter.RESPONSE_COMMAND, args);
assertEquals(DigitalGoodsConverter.convertResponseCode(responseCode, Bundle.EMPTY),
state.responseCode);
assertPurchaseDetails(state.results[0], "1", "t1", true, 1, 1L, true);
assertPurchaseDetails(state.results[1], "2", "t2", false, 2, 2L, false);
}
@Test
public void convertResponseCodes_v0() {
Bundle args = Bundle.EMPTY;
assertEquals(BillingResponseCode.OK,
DigitalGoodsConverter.convertResponseCode(PLAY_BILLING_OK, args));
assertEquals(BillingResponseCode.ITEM_ALREADY_OWNED,
DigitalGoodsConverter.convertResponseCode(PLAY_BILLING_ITEM_ALREADY_OWNED, args));
assertEquals(BillingResponseCode.ITEM_NOT_OWNED,
DigitalGoodsConverter.convertResponseCode(PLAY_BILLING_ITEM_NOT_OWNED, args));
assertEquals(BillingResponseCode.ITEM_UNAVAILABLE,
DigitalGoodsConverter.convertResponseCode(PLAY_BILLING_ITEM_UNAVAILABLE, args));
// Check that other numbers get set to ERROR.
assertEquals(BillingResponseCode.ERROR, DigitalGoodsConverter.convertResponseCode(2, args));
assertEquals(
BillingResponseCode.ERROR, DigitalGoodsConverter.convertResponseCode(-1, args));
assertEquals(
BillingResponseCode.ERROR, DigitalGoodsConverter.convertResponseCode(10, args));
}
@Test
public void convertResponseCodes_v1() {
Bundle args = new Bundle();
args.putInt(DigitalGoodsConverter.KEY_VERSION, 1);
assertEquals(BillingResponseCode.OK, convertResponseCode(BillingResponseCode.OK, args));
assertEquals(BillingResponseCode.ITEM_ALREADY_OWNED,
convertResponseCode(BillingResponseCode.ITEM_ALREADY_OWNED, args));
assertEquals(BillingResponseCode.ITEM_NOT_OWNED,
convertResponseCode(BillingResponseCode.ITEM_NOT_OWNED, args));
assertEquals(BillingResponseCode.ITEM_UNAVAILABLE,
convertResponseCode(BillingResponseCode.ITEM_UNAVAILABLE, args));
assertEquals(BillingResponseCode.ERROR, convertResponseCode(123, args));
assertEquals(BillingResponseCode.ERROR, convertResponseCode(-12, args));
}
} | nwjs/chromium.src | chrome/android/junit/src/org/chromium/chrome/browser/browserservices/digitalgoods/DigitalGoodsConverterTest.java | Java | bsd-3-clause | 13,661 |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkOverlay.h"
mitk::Overlay::Overlay() : m_LayoutedBy(NULL)
{
m_PropertyList = mitk::PropertyList::New();
}
mitk::Overlay::~Overlay()
{
}
void mitk::Overlay::SetProperty(const std::string& propertyKey,
const BaseProperty::Pointer& propertyValue,
const mitk::BaseRenderer* renderer)
{
GetPropertyList(renderer)->SetProperty(propertyKey, propertyValue);
this->Modified();
}
void mitk::Overlay::ReplaceProperty(const std::string& propertyKey,
const BaseProperty::Pointer& propertyValue,
const mitk::BaseRenderer* renderer)
{
GetPropertyList(renderer)->ReplaceProperty(propertyKey, propertyValue);
}
void mitk::Overlay::AddProperty(const std::string& propertyKey,
const BaseProperty::Pointer& propertyValue,
const mitk::BaseRenderer* renderer,
bool overwrite)
{
if ((overwrite) || (GetProperty(propertyKey, renderer) == NULL))
{
SetProperty(propertyKey, propertyValue, renderer);
}
}
void mitk::Overlay::ConcatenatePropertyList(PropertyList *pList, bool replace)
{
m_PropertyList->ConcatenatePropertyList(pList, replace);
}
mitk::BaseProperty* mitk::Overlay::GetProperty(const std::string& propertyKey, const mitk::BaseRenderer* renderer) const
{
//renderer specified?
if (renderer)
{
std::map<const mitk::BaseRenderer*, mitk::PropertyList::Pointer>::const_iterator it;
//check for the renderer specific property
it = m_MapOfPropertyLists.find(renderer);
if (it != m_MapOfPropertyLists.cend()) //found
{
mitk::BaseProperty::Pointer property = it->second->GetProperty(propertyKey);
if (property.IsNotNull())//found an enabled property in the render specific list
return property;
else //found a renderer specific list, but not the desired property
return m_PropertyList->GetProperty(propertyKey); //return renderer unspecific property
}
else //didn't find the property list of the given renderer
{
//return the renderer unspecific property if there is one
return m_PropertyList->GetProperty(propertyKey);
}
}
else //no specific renderer given; use the renderer independent one
{
mitk::BaseProperty::Pointer property = m_PropertyList->GetProperty(propertyKey);
if (property.IsNotNull())
return property;
}
//only to satisfy compiler!
return NULL;
}
bool mitk::Overlay::GetBoolProperty(const std::string& propertyKey, bool& boolValue, mitk::BaseRenderer* renderer) const
{
mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty*>(GetProperty(propertyKey, renderer));
if (boolprop.IsNull())
return false;
boolValue = boolprop->GetValue();
return true;
}
bool mitk::Overlay::GetIntProperty(const std::string& propertyKey, int &intValue, mitk::BaseRenderer* renderer) const
{
mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty*>(GetProperty(propertyKey, renderer));
if (intprop.IsNull())
return false;
intValue = intprop->GetValue();
return true;
}
bool mitk::Overlay::GetFloatProperty(const std::string& propertyKey, float &floatValue, mitk::BaseRenderer* renderer) const
{
mitk::FloatProperty::Pointer floatprop = dynamic_cast<mitk::FloatProperty*>(GetProperty(propertyKey, renderer));
if (floatprop.IsNull())
return false;
floatValue = floatprop->GetValue();
return true;
}
bool mitk::Overlay::GetStringProperty(const std::string& propertyKey, std::string& string, mitk::BaseRenderer* renderer) const
{
mitk::StringProperty::Pointer stringProp = dynamic_cast<mitk::StringProperty*>(GetProperty(propertyKey, renderer));
if (stringProp.IsNull())
{
return false;
}
else
{
//memcpy((void*)string, stringProp->GetValue(), strlen(stringProp->GetValue()) + 1 ); // looks dangerous
string = stringProp->GetValue();
return true;
}
}
void mitk::Overlay::SetIntProperty(const std::string& propertyKey, int intValue, mitk::BaseRenderer* renderer)
{
GetPropertyList(renderer)->SetProperty(propertyKey, mitk::IntProperty::New(intValue));
Modified();
}
void mitk::Overlay::SetBoolProperty(const std::string& propertyKey, bool boolValue, mitk::BaseRenderer* renderer/*=NULL*/)
{
GetPropertyList(renderer)->SetProperty(propertyKey, mitk::BoolProperty::New(boolValue));
Modified();
}
void mitk::Overlay::SetFloatProperty(const std::string& propertyKey, float floatValue, mitk::BaseRenderer* renderer/*=NULL*/)
{
GetPropertyList(renderer)->SetProperty(propertyKey, mitk::FloatProperty::New(floatValue));
Modified();
}
void mitk::Overlay::SetStringProperty(const std::string& propertyKey, const std::string& stringValue, mitk::BaseRenderer* renderer/*=NULL*/)
{
GetPropertyList(renderer)->SetProperty(propertyKey, mitk::StringProperty::New(stringValue));
Modified();
}
std::string mitk::Overlay::GetName() const
{
mitk::StringProperty* sp = dynamic_cast<mitk::StringProperty*>(this->GetProperty("name"));
if (sp == NULL)
return "";
return sp->GetValue();
}
void mitk::Overlay::SetName(const std::string& name)
{
this->SetStringProperty("name", name);
}
bool mitk::Overlay::GetName(std::string& nodeName, mitk::BaseRenderer* renderer, const std::string& propertyKey) const
{
return GetStringProperty(propertyKey, nodeName, renderer);
}
void mitk::Overlay::SetText(std::string text)
{
SetStringProperty("Overlay.Text", text.c_str());
}
std::string mitk::Overlay::GetText() const
{
std::string text;
GetPropertyList()->GetStringProperty("Overlay.Text", text);
return text;
}
void mitk::Overlay::SetFontSize(int fontSize)
{
SetIntProperty("Overlay.FontSize", fontSize);
}
int mitk::Overlay::GetFontSize() const
{
int fontSize = 1;
GetPropertyList()->GetIntProperty("Overlay.FontSize", fontSize);
return fontSize;
}
bool mitk::Overlay::GetVisibility(bool& visible, mitk::BaseRenderer* renderer, const std::string& propertyKey) const
{
return GetBoolProperty(propertyKey, visible, renderer);
}
bool mitk::Overlay::IsVisible(mitk::BaseRenderer* renderer, const std::string& propertyKey, bool defaultIsOn) const
{
return IsOn(propertyKey, renderer, defaultIsOn);
}
bool mitk::Overlay::GetColor(float rgb[], mitk::BaseRenderer* renderer, const std::string& propertyKey) const
{
mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(GetProperty(propertyKey, renderer));
if (colorprop.IsNull())
return false;
memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3 * sizeof(float));
return true;
}
void mitk::Overlay::SetColor(const mitk::Color &color, mitk::BaseRenderer* renderer, const std::string& propertyKey)
{
mitk::ColorProperty::Pointer prop;
prop = mitk::ColorProperty::New(color);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
void mitk::Overlay::SetColor(float red, float green, float blue, mitk::BaseRenderer* renderer, const std::string& propertyKey)
{
float color[3];
color[0] = red;
color[1] = green;
color[2] = blue;
SetColor(color, renderer, propertyKey);
}
void mitk::Overlay::SetColor(const float rgb[], mitk::BaseRenderer* renderer, const std::string& propertyKey)
{
mitk::ColorProperty::Pointer prop;
prop = mitk::ColorProperty::New(rgb);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
bool mitk::Overlay::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const std::string& propertyKey) const
{
mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty*>(GetProperty(propertyKey, renderer));
if (opacityprop.IsNull())
return false;
opacity = opacityprop->GetValue();
return true;
}
void mitk::Overlay::SetOpacity(float opacity, mitk::BaseRenderer* renderer, const std::string& propertyKey)
{
mitk::FloatProperty::Pointer prop;
prop = mitk::FloatProperty::New(opacity);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
void mitk::Overlay::SetVisibility(bool visible, mitk::BaseRenderer *renderer, const std::string& propertyKey)
{
mitk::BoolProperty::Pointer prop;
prop = mitk::BoolProperty::New(visible);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
mitk::PropertyList* mitk::Overlay::GetPropertyList(const mitk::BaseRenderer* renderer) const
{
if (renderer == NULL)
return m_PropertyList;
mitk::PropertyList::Pointer & propertyList = m_MapOfPropertyLists[renderer];
if (propertyList.IsNull())
propertyList = mitk::PropertyList::New();
assert(m_MapOfPropertyLists[renderer].IsNotNull());
return propertyList;
}
bool mitk::Overlay::BaseLocalStorage::IsGenerateDataRequired(mitk::BaseRenderer *renderer, mitk::Overlay *overlay)
{
if (m_LastGenerateDataTime < overlay->GetMTime())
return true;
if (renderer && m_LastGenerateDataTime < renderer->GetTimeStepUpdateTime())
return true;
return false;
}
mitk::Overlay::Bounds mitk::Overlay::GetBoundsOnDisplay(mitk::BaseRenderer*) const
{
mitk::Overlay::Bounds bounds;
bounds.Position[0] = bounds.Position[1] = bounds.Size[0] = bounds.Size[1] = 0;
return bounds;
}
void mitk::Overlay::SetBoundsOnDisplay(mitk::BaseRenderer*, const mitk::Overlay::Bounds&)
{
}
void mitk::Overlay::SetForceInForeground(bool forceForeground)
{
m_ForceInForeground = forceForeground;
}
bool mitk::Overlay::IsForceInForeground() const
{
return m_ForceInForeground;
} | NifTK/MITK | Modules/Core/src/Rendering/mitkOverlay.cpp | C++ | bsd-3-clause | 9,744 |
// Copyright 2016 The Gosl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ode
import (
"github.com/cpmech/gosl/chk"
"github.com/cpmech/gosl/la"
)
// rkmethod defines the required functions of Runge-Kutta method
type rkmethod interface {
Free() // free memory
Info() (fixedOnly, implicit bool, nstages int) // information
Init(ndim int, conf *Config, work *rkwork, stat *Stat, fcn Func, jac JacF, M *la.Triplet) // initialize
Accept(y0 la.Vector, x0 float64) (dxnew float64) // accept update (must compute rerr)
Reject() (dxnew float64) // process step rejection (must compute rerr)
DenseOut(yout la.Vector, h, x float64, y la.Vector, xout float64) // dense output (after Accept)
Step(x0 float64, y0 la.Vector) // step update
}
// rkmMaker defines a function that makes rkmethods
type rkmMaker func() rkmethod
// rkmDB implements a database of rkmethod makers
var rkmDB = make(map[string]rkmMaker)
// newRKmethod finds a rkmethod in database or panic
func newRKmethod(kind string) rkmethod {
if maker, ok := rkmDB[kind]; ok {
return maker()
}
chk.Panic("cannot find rkmethod named %q in database\n", kind)
return nil
}
| cpmech/gosl | ode/methods.go | GO | bsd-3-clause | 1,549 |
// Copyright (c) 2016-2017, blockoperation. All rights reserved.
// boxnope is distributed under the terms of the BSD license.
// See LICENSE for details.
#ifndef BOXNOPE_UTILS_HPP
#define BOXNOPE_UTILS_HPP
#define QS(s) QString(s)
#define QSL(s) QStringLiteral(s)
#define QL1S(s) QLatin1String(s)
#endif
| blockoperation/boxnope | src/utils.hpp | C++ | bsd-3-clause | 308 |
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var PropTypes;
var checkPropTypes;
var React;
var ReactDOM;
var Component;
var MyComponent;
function resetWarningCache() {
jest.resetModules();
checkPropTypes = require('prop-types/checkPropTypes');
PropTypes = require('ReactPropTypes');
}
function getPropTypeWarningMessage(propTypes, object, componentName) {
if (!console.error.calls) {
spyOn(console, 'error');
} else {
console.error.calls.reset();
}
resetWarningCache();
checkPropTypes(propTypes, object, 'prop', 'testComponent');
const callCount = console.error.calls.count();
if (callCount > 1) {
throw new Error('Too many warnings.');
}
const message = console.error.calls.argsFor(0)[0] || null;
console.error.calls.reset();
return message;
}
function typeCheckFail(declaration, value, expectedMessage) {
const propTypes = {
testProp: declaration,
};
const props = {
testProp: value,
};
const message = getPropTypeWarningMessage(propTypes, props, 'testComponent');
expect(message).toContain(expectedMessage);
}
function typeCheckFailRequiredValues(declaration) {
var specifiedButIsNullMsg =
'The prop `testProp` is marked as required in ' +
'`testComponent`, but its value is `null`.';
var unspecifiedMsg =
'The prop `testProp` is marked as required in ' +
'`testComponent`, but its value is \`undefined\`.';
var propTypes = {testProp: declaration};
// Required prop is null
var message1 = getPropTypeWarningMessage(
propTypes,
{testProp: null},
'testComponent',
);
expect(message1).toContain(specifiedButIsNullMsg);
// Required prop is undefined
var message2 = getPropTypeWarningMessage(
propTypes,
{testProp: undefined},
'testComponent',
);
expect(message2).toContain(unspecifiedMsg);
// Required prop is not a member of props object
var message3 = getPropTypeWarningMessage(propTypes, {}, 'testComponent');
expect(message3).toContain(unspecifiedMsg);
}
function typeCheckPass(declaration, value) {
const propTypes = {
testProp: declaration,
};
const props = {
testProp: value,
};
const message = getPropTypeWarningMessage(propTypes, props, 'testComponent');
expect(message).toBe(null);
}
function expectThrowInDevelopment(declaration, value) {
var props = {testProp: value};
var propName = 'testProp' + Math.random().toString();
var componentName = 'testComponent' + Math.random().toString();
var message;
try {
declaration(props, propName, componentName, 'prop');
} catch (e) {
message = e.message;
}
expect(message).toContain(
'Calling PropTypes validators directly is not supported',
);
console.error.calls.reset();
}
describe('ReactPropTypes', () => {
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
resetWarningCache();
});
describe('checkPropTypes', () => {
it('does not return a value from a validator', () => {
spyOn(console, 'error');
const propTypes = {
foo(props, propName, componentName) {
return new Error('some error');
},
};
const props = {foo: 'foo'};
const returnValue = checkPropTypes(
propTypes,
props,
'prop',
'testComponent',
null,
);
expect(console.error.calls.argsFor(0)[0]).toContain('some error');
expect(returnValue).toBe(undefined);
});
it('does not throw if validator throws', () => {
spyOn(console, 'error');
const propTypes = {
foo(props, propName, componentName) {
throw new Error('some error');
},
};
const props = {foo: 'foo'};
const returnValue = checkPropTypes(
propTypes,
props,
'prop',
'testComponent',
null,
);
expect(console.error.calls.argsFor(0)[0]).toContain('some error');
expect(returnValue).toBe(undefined);
});
});
describe('Primitive Types', () => {
it('should warn for invalid strings', () => {
typeCheckFail(
PropTypes.string,
[],
'Invalid prop `testProp` of type `array` supplied to ' +
'`testComponent`, expected `string`.',
);
typeCheckFail(
PropTypes.string,
false,
'Invalid prop `testProp` of type `boolean` supplied to ' +
'`testComponent`, expected `string`.',
);
typeCheckFail(
PropTypes.string,
0,
'Invalid prop `testProp` of type `number` supplied to ' +
'`testComponent`, expected `string`.',
);
typeCheckFail(
PropTypes.string,
{},
'Invalid prop `testProp` of type `object` supplied to ' +
'`testComponent`, expected `string`.',
);
typeCheckFail(
PropTypes.string,
Symbol(),
'Invalid prop `testProp` of type `symbol` supplied to ' +
'`testComponent`, expected `string`.',
);
});
it('should fail date and regexp correctly', () => {
typeCheckFail(
PropTypes.string,
new Date(),
'Invalid prop `testProp` of type `date` supplied to ' +
'`testComponent`, expected `string`.',
);
typeCheckFail(
PropTypes.string,
/please/,
'Invalid prop `testProp` of type `regexp` supplied to ' +
'`testComponent`, expected `string`.',
);
});
it('should not warn for valid values', () => {
typeCheckPass(PropTypes.array, []);
typeCheckPass(PropTypes.bool, false);
typeCheckPass(PropTypes.func, function() {});
typeCheckPass(PropTypes.number, 0);
typeCheckPass(PropTypes.string, '');
typeCheckPass(PropTypes.object, {});
typeCheckPass(PropTypes.object, new Date());
typeCheckPass(PropTypes.object, /please/);
typeCheckPass(PropTypes.symbol, Symbol());
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(PropTypes.string, null);
typeCheckPass(PropTypes.string, undefined);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(PropTypes.string.isRequired);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.array, /please/);
expectThrowInDevelopment(PropTypes.array, []);
expectThrowInDevelopment(PropTypes.array.isRequired, /please/);
expectThrowInDevelopment(PropTypes.array.isRequired, []);
expectThrowInDevelopment(PropTypes.array.isRequired, null);
expectThrowInDevelopment(PropTypes.array.isRequired, undefined);
expectThrowInDevelopment(PropTypes.bool, []);
expectThrowInDevelopment(PropTypes.bool, true);
expectThrowInDevelopment(PropTypes.bool.isRequired, []);
expectThrowInDevelopment(PropTypes.bool.isRequired, true);
expectThrowInDevelopment(PropTypes.bool.isRequired, null);
expectThrowInDevelopment(PropTypes.bool.isRequired, undefined);
expectThrowInDevelopment(PropTypes.func, false);
expectThrowInDevelopment(PropTypes.func, function() {});
expectThrowInDevelopment(PropTypes.func.isRequired, false);
expectThrowInDevelopment(PropTypes.func.isRequired, function() {});
expectThrowInDevelopment(PropTypes.func.isRequired, null);
expectThrowInDevelopment(PropTypes.func.isRequired, undefined);
expectThrowInDevelopment(PropTypes.number, function() {});
expectThrowInDevelopment(PropTypes.number, 42);
expectThrowInDevelopment(PropTypes.number.isRequired, function() {});
expectThrowInDevelopment(PropTypes.number.isRequired, 42);
expectThrowInDevelopment(PropTypes.number.isRequired, null);
expectThrowInDevelopment(PropTypes.number.isRequired, undefined);
expectThrowInDevelopment(PropTypes.string, 0);
expectThrowInDevelopment(PropTypes.string, 'foo');
expectThrowInDevelopment(PropTypes.string.isRequired, 0);
expectThrowInDevelopment(PropTypes.string.isRequired, 'foo');
expectThrowInDevelopment(PropTypes.string.isRequired, null);
expectThrowInDevelopment(PropTypes.string.isRequired, undefined);
expectThrowInDevelopment(PropTypes.symbol, 0);
expectThrowInDevelopment(PropTypes.symbol, Symbol('Foo'));
expectThrowInDevelopment(PropTypes.symbol.isRequired, 0);
expectThrowInDevelopment(PropTypes.symbol.isRequired, Symbol('Foo'));
expectThrowInDevelopment(PropTypes.symbol.isRequired, null);
expectThrowInDevelopment(PropTypes.symbol.isRequired, undefined);
expectThrowInDevelopment(PropTypes.object, '');
expectThrowInDevelopment(PropTypes.object, {foo: 'bar'});
expectThrowInDevelopment(PropTypes.object.isRequired, '');
expectThrowInDevelopment(PropTypes.object.isRequired, {foo: 'bar'});
expectThrowInDevelopment(PropTypes.object.isRequired, null);
expectThrowInDevelopment(PropTypes.object.isRequired, undefined);
});
});
describe('Any type', () => {
it('should should accept any value', () => {
typeCheckPass(PropTypes.any, 0);
typeCheckPass(PropTypes.any, 'str');
typeCheckPass(PropTypes.any, []);
typeCheckPass(PropTypes.any, Symbol());
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(PropTypes.any, null);
typeCheckPass(PropTypes.any, undefined);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(PropTypes.any.isRequired);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.any, null);
expectThrowInDevelopment(PropTypes.any.isRequired, null);
expectThrowInDevelopment(PropTypes.any.isRequired, undefined);
});
});
describe('ArrayOf Type', () => {
it('should fail for invalid argument', () => {
typeCheckFail(
PropTypes.arrayOf({foo: PropTypes.string}),
{foo: 'bar'},
'Property `testProp` of component `testComponent` has invalid PropType notation inside arrayOf.',
);
});
it('should support the arrayOf propTypes', () => {
typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]);
typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']);
typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']);
typeCheckPass(PropTypes.arrayOf(PropTypes.symbol), [Symbol(), Symbol()]);
});
it('should support arrayOf with complex types', () => {
typeCheckPass(
PropTypes.arrayOf(PropTypes.shape({a: PropTypes.number.isRequired})),
[{a: 1}, {a: 2}],
);
function Thing() {}
typeCheckPass(PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [
new Thing(),
new Thing(),
]);
});
it('should warn with invalid items in the array', () => {
typeCheckFail(
PropTypes.arrayOf(PropTypes.number),
[1, 2, 'b'],
'Invalid prop `testProp[2]` of type `string` supplied to ' +
'`testComponent`, expected `number`.',
);
});
it('should warn with invalid complex types', () => {
function Thing() {}
var name = Thing.name || '<<anonymous>>';
typeCheckFail(
PropTypes.arrayOf(PropTypes.instanceOf(Thing)),
[new Thing(), 'xyz'],
'Invalid prop `testProp[1]` of type `String` supplied to ' +
'`testComponent`, expected instance of `' +
name +
'`.',
);
});
it('should warn when passed something other than an array', () => {
typeCheckFail(
PropTypes.arrayOf(PropTypes.number),
{'0': 'maybe-array', length: 1},
'Invalid prop `testProp` of type `object` supplied to ' +
'`testComponent`, expected an array.',
);
typeCheckFail(
PropTypes.arrayOf(PropTypes.number),
123,
'Invalid prop `testProp` of type `number` supplied to ' +
'`testComponent`, expected an array.',
);
typeCheckFail(
PropTypes.arrayOf(PropTypes.number),
'string',
'Invalid prop `testProp` of type `string` supplied to ' +
'`testComponent`, expected an array.',
);
});
it('should not warn when passing an empty array', () => {
typeCheckPass(PropTypes.arrayOf(PropTypes.number), []);
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(PropTypes.arrayOf(PropTypes.number), null);
typeCheckPass(PropTypes.arrayOf(PropTypes.number), undefined);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(
PropTypes.arrayOf(PropTypes.number).isRequired,
);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.arrayOf({foo: PropTypes.string}), {
foo: 'bar',
});
expectThrowInDevelopment(PropTypes.arrayOf(PropTypes.number), [
1,
2,
'b',
]);
expectThrowInDevelopment(PropTypes.arrayOf(PropTypes.number), {
'0': 'maybe-array',
length: 1,
});
expectThrowInDevelopment(
PropTypes.arrayOf(PropTypes.number).isRequired,
null,
);
expectThrowInDevelopment(
PropTypes.arrayOf(PropTypes.number).isRequired,
undefined,
);
});
});
describe('Component Type', () => {
beforeEach(() => {
Component = class extends React.Component {
static propTypes = {
label: PropTypes.element.isRequired,
};
render() {
return <div>{this.props.label}</div>;
}
};
});
it('should support components', () => {
typeCheckPass(PropTypes.element, <div />);
});
it('should not support multiple components or scalar values', () => {
typeCheckFail(
PropTypes.element,
[<div />, <div />],
'Invalid prop `testProp` of type `array` supplied to `testComponent`, ' +
'expected a single ReactElement.',
);
typeCheckFail(
PropTypes.element,
123,
'Invalid prop `testProp` of type `number` supplied to `testComponent`, ' +
'expected a single ReactElement.',
);
typeCheckFail(
PropTypes.element,
'foo',
'Invalid prop `testProp` of type `string` supplied to `testComponent`, ' +
'expected a single ReactElement.',
);
typeCheckFail(
PropTypes.element,
false,
'Invalid prop `testProp` of type `boolean` supplied to `testComponent`, ' +
'expected a single ReactElement.',
);
});
it('should be able to define a single child as label', () => {
spyOn(console, 'error');
var container = document.createElement('div');
ReactDOM.render(<Component label={<div />} />, container);
expectDev(console.error.calls.count()).toBe(0);
});
it('should warn when passing no label and isRequired is set', () => {
spyOn(console, 'error');
var container = document.createElement('div');
ReactDOM.render(<Component />, container);
expectDev(console.error.calls.count()).toBe(1);
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(PropTypes.element, null);
typeCheckPass(PropTypes.element, undefined);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(PropTypes.element.isRequired);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.element, [<div />, <div />]);
expectThrowInDevelopment(PropTypes.element, <div />);
expectThrowInDevelopment(PropTypes.element, 123);
expectThrowInDevelopment(PropTypes.element, 'foo');
expectThrowInDevelopment(PropTypes.element, false);
expectThrowInDevelopment(PropTypes.element.isRequired, null);
expectThrowInDevelopment(PropTypes.element.isRequired, undefined);
});
});
describe('Instance Types', () => {
it('should warn for invalid instances', () => {
function Person() {}
function Cat() {}
var personName = Person.name || '<<anonymous>>';
var dateName = Date.name || '<<anonymous>>';
var regExpName = RegExp.name || '<<anonymous>>';
typeCheckFail(
PropTypes.instanceOf(Person),
false,
'Invalid prop `testProp` of type `Boolean` supplied to ' +
'`testComponent`, expected instance of `' +
personName +
'`.',
);
typeCheckFail(
PropTypes.instanceOf(Person),
{},
'Invalid prop `testProp` of type `Object` supplied to ' +
'`testComponent`, expected instance of `' +
personName +
'`.',
);
typeCheckFail(
PropTypes.instanceOf(Person),
'',
'Invalid prop `testProp` of type `String` supplied to ' +
'`testComponent`, expected instance of `' +
personName +
'`.',
);
typeCheckFail(
PropTypes.instanceOf(Date),
{},
'Invalid prop `testProp` of type `Object` supplied to ' +
'`testComponent`, expected instance of `' +
dateName +
'`.',
);
typeCheckFail(
PropTypes.instanceOf(RegExp),
{},
'Invalid prop `testProp` of type `Object` supplied to ' +
'`testComponent`, expected instance of `' +
regExpName +
'`.',
);
typeCheckFail(
PropTypes.instanceOf(Person),
new Cat(),
'Invalid prop `testProp` of type `Cat` supplied to ' +
'`testComponent`, expected instance of `' +
personName +
'`.',
);
typeCheckFail(
PropTypes.instanceOf(Person),
Object.create(null),
'Invalid prop `testProp` of type `<<anonymous>>` supplied to ' +
'`testComponent`, expected instance of `' +
personName +
'`.',
);
});
it('should not warn for valid values', () => {
function Person() {}
function Engineer() {}
Engineer.prototype = new Person();
typeCheckPass(PropTypes.instanceOf(Person), new Person());
typeCheckPass(PropTypes.instanceOf(Person), new Engineer());
typeCheckPass(PropTypes.instanceOf(Date), new Date());
typeCheckPass(PropTypes.instanceOf(RegExp), /please/);
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(PropTypes.instanceOf(String), null);
typeCheckPass(PropTypes.instanceOf(String), undefined);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(PropTypes.instanceOf(String).isRequired);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.instanceOf(Date), {});
expectThrowInDevelopment(PropTypes.instanceOf(Date), new Date());
expectThrowInDevelopment(PropTypes.instanceOf(Date).isRequired, {});
expectThrowInDevelopment(
PropTypes.instanceOf(Date).isRequired,
new Date(),
);
});
});
describe('React Component Types', () => {
beforeEach(() => {
MyComponent = class extends React.Component {
render() {
return <div />;
}
};
});
it('should warn for invalid values', () => {
var failMessage =
'Invalid prop `testProp` supplied to ' +
'`testComponent`, expected a ReactNode.';
typeCheckFail(PropTypes.node, true, failMessage);
typeCheckFail(PropTypes.node, function() {}, failMessage);
typeCheckFail(PropTypes.node, {key: function() {}}, failMessage);
typeCheckFail(PropTypes.node, {key: <div />}, failMessage);
});
it('should not warn for valid values', () => {
typeCheckPass(PropTypes.node, <div />);
typeCheckPass(PropTypes.node, false);
typeCheckPass(PropTypes.node, <MyComponent />);
typeCheckPass(PropTypes.node, 'Some string');
typeCheckPass(PropTypes.node, []);
typeCheckPass(PropTypes.node, [
123,
'Some string',
<div />,
['Another string', [456], <span />, <MyComponent />],
<MyComponent />,
null,
undefined,
]);
});
it('should not warn for iterables', () => {
var iterable = {
'@@iterator': function() {
var i = 0;
return {
next: function() {
var done = ++i > 2;
return {value: done ? undefined : <MyComponent />, done: done};
},
};
},
};
typeCheckPass(PropTypes.node, iterable);
});
it('should not warn for entry iterables', () => {
var iterable = {
'@@iterator': function() {
var i = 0;
return {
next: function() {
var done = ++i > 2;
return {
value: done ? undefined : ['#' + i, <MyComponent />],
done: done,
};
},
};
},
};
iterable.entries = iterable['@@iterator'];
typeCheckPass(PropTypes.node, iterable);
});
it('should not warn for null/undefined if not required', () => {
typeCheckPass(PropTypes.node, null);
typeCheckPass(PropTypes.node, undefined);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(PropTypes.node.isRequired);
});
it('should accept empty array for required props', () => {
typeCheckPass(PropTypes.node.isRequired, []);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.node, 'node');
expectThrowInDevelopment(PropTypes.node, {});
expectThrowInDevelopment(PropTypes.node.isRequired, 'node');
expectThrowInDevelopment(PropTypes.node.isRequired, undefined);
expectThrowInDevelopment(PropTypes.node.isRequired, undefined);
});
});
describe('ObjectOf Type', () => {
it('should fail for invalid argument', () => {
typeCheckFail(
PropTypes.objectOf({foo: PropTypes.string}),
{foo: 'bar'},
'Property `testProp` of component `testComponent` has invalid PropType notation inside objectOf.',
);
});
it('should support the objectOf propTypes', () => {
typeCheckPass(PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 3});
typeCheckPass(PropTypes.objectOf(PropTypes.string), {
a: 'a',
b: 'b',
c: 'c',
});
typeCheckPass(PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])), {
a: 'a',
b: 'b',
});
typeCheckPass(PropTypes.objectOf(PropTypes.symbol), {
a: Symbol(),
b: Symbol(),
c: Symbol(),
});
});
it('should support objectOf with complex types', () => {
typeCheckPass(
PropTypes.objectOf(PropTypes.shape({a: PropTypes.number.isRequired})),
{a: {a: 1}, b: {a: 2}},
);
function Thing() {}
typeCheckPass(PropTypes.objectOf(PropTypes.instanceOf(Thing)), {
a: new Thing(),
b: new Thing(),
});
});
it('should warn with invalid items in the object', () => {
typeCheckFail(
PropTypes.objectOf(PropTypes.number),
{a: 1, b: 2, c: 'b'},
'Invalid prop `testProp.c` of type `string` supplied to `testComponent`, ' +
'expected `number`.',
);
});
it('should warn with invalid complex types', () => {
function Thing() {}
var name = Thing.name || '<<anonymous>>';
typeCheckFail(
PropTypes.objectOf(PropTypes.instanceOf(Thing)),
{a: new Thing(), b: 'xyz'},
'Invalid prop `testProp.b` of type `String` supplied to ' +
'`testComponent`, expected instance of `' +
name +
'`.',
);
});
it('should warn when passed something other than an object', () => {
typeCheckFail(
PropTypes.objectOf(PropTypes.number),
[1, 2],
'Invalid prop `testProp` of type `array` supplied to ' +
'`testComponent`, expected an object.',
);
typeCheckFail(
PropTypes.objectOf(PropTypes.number),
123,
'Invalid prop `testProp` of type `number` supplied to ' +
'`testComponent`, expected an object.',
);
typeCheckFail(
PropTypes.objectOf(PropTypes.number),
'string',
'Invalid prop `testProp` of type `string` supplied to ' +
'`testComponent`, expected an object.',
);
typeCheckFail(
PropTypes.objectOf(PropTypes.symbol),
Symbol(),
'Invalid prop `testProp` of type `symbol` supplied to ' +
'`testComponent`, expected an object.',
);
});
it('should not warn when passing an empty object', () => {
typeCheckPass(PropTypes.objectOf(PropTypes.number), {});
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(PropTypes.objectOf(PropTypes.number), null);
typeCheckPass(PropTypes.objectOf(PropTypes.number), undefined);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(
PropTypes.objectOf(PropTypes.number).isRequired,
);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.objectOf({foo: PropTypes.string}), {
foo: 'bar',
});
expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), {
a: 1,
b: 2,
c: 'b',
});
expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), [1, 2]);
expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), null);
expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), undefined);
});
});
describe('OneOf Types', () => {
it('should warn but not error for invalid argument', () => {
spyOn(console, 'error');
PropTypes.oneOf('red', 'blue');
expectDev(console.error).toHaveBeenCalled();
expectDev(console.error.calls.argsFor(0)[0]).toContain(
'Invalid argument supplied to oneOf, expected an instance of array.',
);
typeCheckPass(PropTypes.oneOf('red', 'blue'), 'red');
});
it('should warn for invalid values', () => {
typeCheckFail(
PropTypes.oneOf(['red', 'blue']),
true,
'Invalid prop `testProp` of value `true` supplied to ' +
'`testComponent`, expected one of ["red","blue"].',
);
typeCheckFail(
PropTypes.oneOf(['red', 'blue']),
[],
'Invalid prop `testProp` of value `` supplied to `testComponent`, ' +
'expected one of ["red","blue"].',
);
typeCheckFail(
PropTypes.oneOf(['red', 'blue']),
'',
'Invalid prop `testProp` of value `` supplied to `testComponent`, ' +
'expected one of ["red","blue"].',
);
typeCheckFail(
PropTypes.oneOf([0, 'false']),
false,
'Invalid prop `testProp` of value `false` supplied to ' +
'`testComponent`, expected one of [0,"false"].',
);
});
it('should not warn for valid values', () => {
typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'red');
typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'blue');
typeCheckPass(PropTypes.oneOf(['red', 'blue', NaN]), NaN);
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(PropTypes.oneOf(['red', 'blue']), null);
typeCheckPass(PropTypes.oneOf(['red', 'blue']), undefined);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(PropTypes.oneOf(['red', 'blue']).isRequired);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), true);
expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), null);
expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), undefined);
});
});
describe('Union Types', () => {
it('should warn but not error for invalid argument', () => {
spyOn(console, 'error');
PropTypes.oneOfType(PropTypes.string, PropTypes.number);
expectDev(console.error).toHaveBeenCalled();
expectDev(console.error.calls.argsFor(0)[0]).toContain(
'Invalid argument supplied to oneOfType, expected an instance of array.',
);
typeCheckPass(PropTypes.oneOf(PropTypes.string, PropTypes.number), []);
});
it('should warn if none of the types are valid', () => {
typeCheckFail(
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
[],
'Invalid prop `testProp` supplied to `testComponent`.',
);
var checker = PropTypes.oneOfType([
PropTypes.shape({a: PropTypes.number.isRequired}),
PropTypes.shape({b: PropTypes.number.isRequired}),
]);
typeCheckFail(
checker,
{c: 1},
'Invalid prop `testProp` supplied to `testComponent`.',
);
});
it('should not warn if one of the types are valid', () => {
var checker = PropTypes.oneOfType([PropTypes.string, PropTypes.number]);
typeCheckPass(checker, null);
typeCheckPass(checker, 'foo');
typeCheckPass(checker, 123);
checker = PropTypes.oneOfType([
PropTypes.shape({a: PropTypes.number.isRequired}),
PropTypes.shape({b: PropTypes.number.isRequired}),
]);
typeCheckPass(checker, {a: 1});
typeCheckPass(checker, {b: 1});
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
null,
);
typeCheckPass(
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
undefined,
);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(
PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
[],
);
expectThrowInDevelopment(
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
null,
);
expectThrowInDevelopment(
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
undefined,
);
});
});
describe('Shape Types', () => {
it('should warn for non objects', () => {
typeCheckFail(
PropTypes.shape({}),
'some string',
'Invalid prop `testProp` of type `string` supplied to ' +
'`testComponent`, expected `object`.',
);
typeCheckFail(
PropTypes.shape({}),
['array'],
'Invalid prop `testProp` of type `array` supplied to ' +
'`testComponent`, expected `object`.',
);
});
it('should not warn for empty values', () => {
typeCheckPass(PropTypes.shape({}), undefined);
typeCheckPass(PropTypes.shape({}), null);
typeCheckPass(PropTypes.shape({}), {});
});
it('should not warn for an empty object', () => {
typeCheckPass(PropTypes.shape({}).isRequired, {});
});
it('should not warn for non specified types', () => {
typeCheckPass(PropTypes.shape({}), {key: 1});
});
it('should not warn for valid types', () => {
typeCheckPass(PropTypes.shape({key: PropTypes.number}), {key: 1});
});
it('should warn for required valid types', () => {
typeCheckFail(
PropTypes.shape({key: PropTypes.number.isRequired}),
{},
'The prop `testProp.key` is marked as required in `testComponent`, ' +
'but its value is `undefined`.',
);
});
it('should warn for the first required type', () => {
typeCheckFail(
PropTypes.shape({
key: PropTypes.number.isRequired,
secondKey: PropTypes.number.isRequired,
}),
{},
'The prop `testProp.key` is marked as required in `testComponent`, ' +
'but its value is `undefined`.',
);
});
it('should warn for invalid key types', () => {
typeCheckFail(
PropTypes.shape({key: PropTypes.number}),
{key: 'abc'},
'Invalid prop `testProp.key` of type `string` supplied to `testComponent`, ' +
'expected `number`.',
);
});
it('should be implicitly optional and not warn without values', () => {
typeCheckPass(
PropTypes.shape(PropTypes.shape({key: PropTypes.number})),
null,
);
typeCheckPass(
PropTypes.shape(PropTypes.shape({key: PropTypes.number})),
undefined,
);
});
it('should warn for missing required values', () => {
typeCheckFailRequiredValues(
PropTypes.shape({key: PropTypes.number}).isRequired,
);
});
it('should throw if called manually in development', () => {
spyOn(console, 'error');
expectThrowInDevelopment(PropTypes.shape({}), 'some string');
expectThrowInDevelopment(PropTypes.shape({foo: PropTypes.number}), {
foo: 42,
});
expectThrowInDevelopment(
PropTypes.shape({key: PropTypes.number}).isRequired,
null,
);
expectThrowInDevelopment(
PropTypes.shape({key: PropTypes.number}).isRequired,
undefined,
);
expectThrowInDevelopment(PropTypes.element, <div />);
});
});
describe('Symbol Type', () => {
it('should warn for non-symbol', () => {
typeCheckFail(
PropTypes.symbol,
'hello',
'Invalid prop `testProp` of type `string` supplied to ' +
'`testComponent`, expected `symbol`.',
);
typeCheckFail(
PropTypes.symbol,
function() {},
'Invalid prop `testProp` of type `function` supplied to ' +
'`testComponent`, expected `symbol`.',
);
typeCheckFail(
PropTypes.symbol,
{
'@@toStringTag': 'Katana',
},
'Invalid prop `testProp` of type `object` supplied to ' +
'`testComponent`, expected `symbol`.',
);
});
it('should not warn for a polyfilled Symbol', () => {
var CoreSymbol = require('core-js/library/es6/symbol');
typeCheckPass(PropTypes.symbol, CoreSymbol('core-js'));
});
});
describe('Custom validator', () => {
beforeEach(() => {
jest.resetModules();
});
it('should have been called with the right params', () => {
var spy = jasmine.createSpy();
Component = class extends React.Component {
static propTypes = {num: spy};
render() {
return <div />;
}
};
var container = document.createElement('div');
ReactDOM.render(<Component num={5} />, container);
expect(spy.calls.count()).toBe(1);
expect(spy.calls.argsFor(0)[1]).toBe('num');
});
it('should have been called even if the prop is not present', () => {
var spy = jasmine.createSpy();
Component = class extends React.Component {
static propTypes = {num: spy};
render() {
return <div />;
}
};
var container = document.createElement('div');
ReactDOM.render(<Component bla={5} />, container);
expect(spy.calls.count()).toBe(1);
expect(spy.calls.argsFor(0)[1]).toBe('num');
});
it("should have received the validator's return value", () => {
spyOn(console, 'error');
var spy = jasmine
.createSpy()
.and.callFake(function(props, propName, componentName) {
if (props[propName] !== 5) {
return new Error('num must be 5!');
}
});
Component = class extends React.Component {
static propTypes = {num: spy};
render() {
return <div />;
}
};
var container = document.createElement('div');
ReactDOM.render(<Component num={6} />, container);
expectDev(console.error.calls.count()).toBe(1);
expect(
console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'),
).toBe(
'Warning: Failed prop type: num must be 5!\n' +
' in Component (at **)',
);
});
it('should not warn if the validator returned null', () => {
spyOn(console, 'error');
var spy = jasmine
.createSpy()
.and.callFake(function(props, propName, componentName) {
return null;
});
Component = class extends React.Component {
static propTypes = {num: spy};
render() {
return <div />;
}
};
var container = document.createElement('div');
ReactDOM.render(<Component num={5} />, container);
expectDev(console.error.calls.count()).toBe(0);
});
});
});
| flipactual/react | src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js | JavaScript | bsd-3-clause | 37,790 |
package com.smartdevicelink.protocol;
import com.smartdevicelink.protocol.enums.FrameType;
import com.smartdevicelink.protocol.enums.SessionType;
import com.smartdevicelink.util.BitConverter;
public class ProtocolFrameHeader {
private byte version = 1;
private boolean compressed = false;
private FrameType frameType = FrameType.Control;
private SessionType sessionType = SessionType.RPC;
private byte frameData = 0;
private byte sessionID;
private int dataSize;
private int messageID;
public static final byte FrameDataSingleFrame = 0x00;
public static final byte FrameDataFirstFrame = 0x00;
public static final byte FrameDataFinalConsecutiveFrame = 0x00;
public ProtocolFrameHeader() {}
public static ProtocolFrameHeader parseWiProHeader(byte[] header) {
ProtocolFrameHeader msg = new ProtocolFrameHeader();
byte version = (byte) (header[0] >>> 4);
msg.setVersion(version);
boolean compressed = 1 == ((header[0] & 0x08) >>> 3);
msg.setCompressed(compressed);
byte frameType = (byte) (header[0] & 0x07);
msg.setFrameType(FrameType.valueOf(frameType));
byte serviceType = header[1];
msg.setSessionType(SessionType.valueOf(serviceType));
byte frameData = header[2];
msg.setFrameData(frameData);
byte sessionID = header[3];
msg.setSessionID(sessionID);
int dataSize = BitConverter.intFromByteArray(header, 4);
msg.setDataSize(dataSize);
if (version > 1) {
int messageID = BitConverter.intFromByteArray(header, 8);
msg.setMessageID(messageID);
} else msg.setMessageID(0);
return msg;
}
protected byte[] assembleHeaderBytes() {
int header = 0;
header |= (version & 0x0F);
header <<= 1;
header |= (compressed ? 1 : 0);
header <<= 3;
header |= (frameType.value() & 0x07);
header <<= 8;
header |= (sessionType.value() & 0xFF);
header <<= 8;
header |= (frameData & 0xFF);
header <<= 8;
header |= (sessionID & 0xFF);
if (version == 1) {
byte[] ret = new byte[8];
System.arraycopy(BitConverter.intToByteArray(header), 0, ret, 0, 4);
System.arraycopy(BitConverter.intToByteArray(dataSize), 0, ret, 4, 4);
return ret;
} else if (version > 1) {
byte[] ret = new byte[12];
System.arraycopy(BitConverter.intToByteArray(header), 0, ret, 0, 4);
System.arraycopy(BitConverter.intToByteArray(dataSize), 0, ret, 4, 4);
System.arraycopy(BitConverter.intToByteArray(messageID), 0, ret, 8, 4);
return ret;
} else return null;
}
public String toString() {
String ret = "";
ret += "version " + version + ", " + (compressed ? "compressed" : "uncompressed") + "\n";
ret += "frameType " + frameType + ", serviceType " + sessionType;
ret += "\nframeData " + frameData;
ret += ", sessionID " + sessionID;
ret += ", dataSize " + dataSize;
ret += ", messageID " + messageID;
return ret;
}
public byte getVersion() {
return version;
}
public void setVersion(byte version) {
this.version = version;
}
public boolean isCompressed() {
return compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
public byte getFrameData() {
return frameData;
}
public void setFrameData(byte frameData) {
this.frameData = frameData;
}
public byte getSessionID() {
return sessionID;
}
public void setSessionID(byte sessionID) {
this.sessionID = sessionID;
}
public int getDataSize() {
return dataSize;
}
public void setDataSize(int dataSize) {
this.dataSize = dataSize;
}
public int getMessageID() {
return messageID;
}
public void setMessageID(int messageID) {
this.messageID = messageID;
}
public FrameType getFrameType() {
return frameType;
}
public void setFrameType(FrameType frameType) {
this.frameType = frameType;
}
public SessionType getSessionType() {
return sessionType;
}
public void setSessionType(SessionType sessionType) {
this.sessionType = sessionType;
}
}
| mrapitis/sdl_android | sdl_android_lib/src/com/smartdevicelink/protocol/ProtocolFrameHeader.java | Java | bsd-3-clause | 4,083 |